quorum: Inline quorum_aio_cb()
[qemu.git] / qemu-char.c
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 #include "qemu/osdep.h"
25 #include "qemu-common.h"
26 #include "qemu/cutils.h"
27 #include "monitor/monitor.h"
28 #include "sysemu/sysemu.h"
29 #include "sysemu/block-backend.h"
30 #include "qemu/error-report.h"
31 #include "qemu/timer.h"
32 #include "sysemu/char.h"
33 #include "hw/usb.h"
34 #include "qmp-commands.h"
35 #include "qapi/clone-visitor.h"
36 #include "qapi-visit.h"
37 #include "qemu/base64.h"
38 #include "io/channel-socket.h"
39 #include "io/channel-file.h"
40 #include "io/channel-tls.h"
41 #include "sysemu/replay.h"
42 #include "qemu/help_option.h"
43
44 #include <zlib.h>
45
46 #ifndef _WIN32
47 #include <sys/times.h>
48 #include <sys/wait.h>
49 #include <termios.h>
50 #include <sys/ioctl.h>
51 #include <sys/resource.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
54 #include <net/if.h>
55 #include <arpa/inet.h>
56 #include <netdb.h>
57 #include <sys/select.h>
58 #ifdef CONFIG_BSD
59 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
60 #include <dev/ppbus/ppi.h>
61 #include <dev/ppbus/ppbconf.h>
62 #elif defined(__DragonFly__)
63 #include <dev/misc/ppi/ppi.h>
64 #include <bus/ppbus/ppbconf.h>
65 #endif
66 #else
67 #ifdef __linux__
68 #include <linux/ppdev.h>
69 #include <linux/parport.h>
70 #endif
71 #ifdef __sun__
72 #include <sys/ethernet.h>
73 #include <sys/sockio.h>
74 #include <netinet/arp.h>
75 #include <netinet/in.h>
76 #include <netinet/in_systm.h>
77 #include <netinet/ip.h>
78 #include <netinet/ip_icmp.h> // must come after ip.h
79 #include <netinet/udp.h>
80 #include <netinet/tcp.h>
81 #endif
82 #endif
83 #endif
84
85 #include "qemu/sockets.h"
86 #include "ui/qemu-spice.h"
87
88 #define READ_BUF_LEN 4096
89 #define READ_RETRIES 10
90 #define TCP_MAX_FDS 16
91
92 typedef struct MuxDriver MuxDriver;
93
94 /***********************************************************/
95 /* Socket address helpers */
96
97 static char *SocketAddress_to_str(const char *prefix, SocketAddress *addr,
98 bool is_listen, bool is_telnet)
99 {
100 switch (addr->type) {
101 case SOCKET_ADDRESS_KIND_INET:
102 return g_strdup_printf("%s%s:%s:%s%s", prefix,
103 is_telnet ? "telnet" : "tcp",
104 addr->u.inet.data->host,
105 addr->u.inet.data->port,
106 is_listen ? ",server" : "");
107 break;
108 case SOCKET_ADDRESS_KIND_UNIX:
109 return g_strdup_printf("%sunix:%s%s", prefix,
110 addr->u.q_unix.data->path,
111 is_listen ? ",server" : "");
112 break;
113 case SOCKET_ADDRESS_KIND_FD:
114 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd.data->str,
115 is_listen ? ",server" : "");
116 break;
117 default:
118 abort();
119 }
120 }
121
122 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
123 struct sockaddr_storage *ps, socklen_t ps_len,
124 bool is_listen, bool is_telnet)
125 {
126 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
127 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
128 const char *left = "", *right = "";
129
130 switch (ss->ss_family) {
131 #ifndef _WIN32
132 case AF_UNIX:
133 return g_strdup_printf("unix:%s%s",
134 ((struct sockaddr_un *)(ss))->sun_path,
135 is_listen ? ",server" : "");
136 #endif
137 case AF_INET6:
138 left = "[";
139 right = "]";
140 /* fall through */
141 case AF_INET:
142 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
143 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
144 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
145 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
146 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
147 is_telnet ? "telnet" : "tcp",
148 left, shost, right, sserv,
149 is_listen ? ",server" : "",
150 left, phost, right, pserv);
151
152 default:
153 return g_strdup_printf("unknown");
154 }
155 }
156
157 /***********************************************************/
158 /* character device */
159
160 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
161 QTAILQ_HEAD_INITIALIZER(chardevs);
162
163 static void qemu_chr_free_common(CharDriverState *chr);
164
165 CharDriverState *qemu_chr_alloc(ChardevCommon *backend, Error **errp)
166 {
167 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
168 qemu_mutex_init(&chr->chr_write_lock);
169
170 if (backend->has_logfile) {
171 int flags = O_WRONLY | O_CREAT;
172 if (backend->has_logappend &&
173 backend->logappend) {
174 flags |= O_APPEND;
175 } else {
176 flags |= O_TRUNC;
177 }
178 chr->logfd = qemu_open(backend->logfile, flags, 0666);
179 if (chr->logfd < 0) {
180 error_setg_errno(errp, errno,
181 "Unable to open logfile %s",
182 backend->logfile);
183 g_free(chr);
184 return NULL;
185 }
186 } else {
187 chr->logfd = -1;
188 }
189
190 return chr;
191 }
192
193 void qemu_chr_be_event(CharDriverState *s, int event)
194 {
195 CharBackend *be = s->be;
196
197 /* Keep track if the char device is open */
198 switch (event) {
199 case CHR_EVENT_OPENED:
200 s->be_open = 1;
201 break;
202 case CHR_EVENT_CLOSED:
203 s->be_open = 0;
204 break;
205 }
206
207 if (!be || !be->chr_event) {
208 return;
209 }
210
211 be->chr_event(be->opaque, event);
212 }
213
214 void qemu_chr_be_generic_open(CharDriverState *s)
215 {
216 qemu_chr_be_event(s, CHR_EVENT_OPENED);
217 }
218
219
220 /* Not reporting errors from writing to logfile, as logs are
221 * defined to be "best effort" only */
222 static void qemu_chr_fe_write_log(CharDriverState *s,
223 const uint8_t *buf, size_t len)
224 {
225 size_t done = 0;
226 ssize_t ret;
227
228 if (s->logfd < 0) {
229 return;
230 }
231
232 while (done < len) {
233 retry:
234 ret = write(s->logfd, buf + done, len - done);
235 if (ret == -1 && errno == EAGAIN) {
236 g_usleep(100);
237 goto retry;
238 }
239
240 if (ret <= 0) {
241 return;
242 }
243 done += ret;
244 }
245 }
246
247 static int qemu_chr_fe_write_buffer(CharDriverState *s, const uint8_t *buf, int len, int *offset)
248 {
249 int res = 0;
250 *offset = 0;
251
252 qemu_mutex_lock(&s->chr_write_lock);
253 while (*offset < len) {
254 retry:
255 res = s->chr_write(s, buf + *offset, len - *offset);
256 if (res < 0 && errno == EAGAIN) {
257 g_usleep(100);
258 goto retry;
259 }
260
261 if (res <= 0) {
262 break;
263 }
264
265 *offset += res;
266 }
267 if (*offset > 0) {
268 qemu_chr_fe_write_log(s, buf, *offset);
269 }
270 qemu_mutex_unlock(&s->chr_write_lock);
271
272 return res;
273 }
274
275 int qemu_chr_fe_write(CharBackend *be, const uint8_t *buf, int len)
276 {
277 CharDriverState *s = be->chr;
278 int ret;
279
280 if (!s) {
281 return 0;
282 }
283
284 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
285 int offset;
286 replay_char_write_event_load(&ret, &offset);
287 assert(offset <= len);
288 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
289 return ret;
290 }
291
292 qemu_mutex_lock(&s->chr_write_lock);
293 ret = s->chr_write(s, buf, len);
294
295 if (ret > 0) {
296 qemu_chr_fe_write_log(s, buf, ret);
297 }
298
299 qemu_mutex_unlock(&s->chr_write_lock);
300
301 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
302 replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
303 }
304
305 return ret;
306 }
307
308 static int qemu_chr_write_all(CharDriverState *s, const uint8_t *buf, int len)
309 {
310 int offset;
311 int res;
312
313 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
314 replay_char_write_event_load(&res, &offset);
315 assert(offset <= len);
316 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
317 return res;
318 }
319
320 res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
321
322 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
323 replay_char_write_event_save(res, offset);
324 }
325
326 if (res < 0) {
327 return res;
328 }
329 return offset;
330 }
331
332 int qemu_chr_fe_write_all(CharBackend *be, const uint8_t *buf, int len)
333 {
334 CharDriverState *s = be->chr;
335
336 if (!s) {
337 return 0;
338 }
339
340 return qemu_chr_write_all(s, buf, len);
341 }
342
343 int qemu_chr_fe_read_all(CharBackend *be, uint8_t *buf, int len)
344 {
345 CharDriverState *s = be->chr;
346 int offset = 0, counter = 10;
347 int res;
348
349 if (!s || !s->chr_sync_read) {
350 return 0;
351 }
352
353 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
354 return replay_char_read_all_load(buf);
355 }
356
357 while (offset < len) {
358 retry:
359 res = s->chr_sync_read(s, buf + offset, len - offset);
360 if (res == -1 && errno == EAGAIN) {
361 g_usleep(100);
362 goto retry;
363 }
364
365 if (res == 0) {
366 break;
367 }
368
369 if (res < 0) {
370 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
371 replay_char_read_all_save_error(res);
372 }
373 return res;
374 }
375
376 offset += res;
377
378 if (!counter--) {
379 break;
380 }
381 }
382
383 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
384 replay_char_read_all_save_buf(buf, offset);
385 }
386 return offset;
387 }
388
389 int qemu_chr_fe_ioctl(CharBackend *be, int cmd, void *arg)
390 {
391 CharDriverState *s = be->chr;
392 int res;
393
394 if (!s || !s->chr_ioctl || s->replay) {
395 res = -ENOTSUP;
396 } else {
397 res = s->chr_ioctl(s, cmd, arg);
398 }
399
400 return res;
401 }
402
403 int qemu_chr_be_can_write(CharDriverState *s)
404 {
405 CharBackend *be = s->be;
406
407 if (!be || !be->chr_can_read) {
408 return 0;
409 }
410
411 return be->chr_can_read(be->opaque);
412 }
413
414 void qemu_chr_be_write_impl(CharDriverState *s, uint8_t *buf, int len)
415 {
416 CharBackend *be = s->be;
417
418 if (be && be->chr_read) {
419 be->chr_read(be->opaque, buf, len);
420 }
421 }
422
423 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
424 {
425 if (s->replay) {
426 if (replay_mode == REPLAY_MODE_PLAY) {
427 return;
428 }
429 replay_chr_be_write(s, buf, len);
430 } else {
431 qemu_chr_be_write_impl(s, buf, len);
432 }
433 }
434
435 int qemu_chr_fe_get_msgfd(CharBackend *be)
436 {
437 CharDriverState *s = be->chr;
438 int fd;
439 int res = (qemu_chr_fe_get_msgfds(be, &fd, 1) == 1) ? fd : -1;
440 if (s && s->replay) {
441 fprintf(stderr,
442 "Replay: get msgfd is not supported for serial devices yet\n");
443 exit(1);
444 }
445 return res;
446 }
447
448 int qemu_chr_fe_get_msgfds(CharBackend *be, int *fds, int len)
449 {
450 CharDriverState *s = be->chr;
451
452 if (!s) {
453 return -1;
454 }
455
456 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
457 }
458
459 int qemu_chr_fe_set_msgfds(CharBackend *be, int *fds, int num)
460 {
461 CharDriverState *s = be->chr;
462
463 if (!s) {
464 return -1;
465 }
466
467 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
468 }
469
470 int qemu_chr_add_client(CharDriverState *s, int fd)
471 {
472 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
473 }
474
475 void qemu_chr_fe_accept_input(CharBackend *be)
476 {
477 CharDriverState *s = be->chr;
478
479 if (!s) {
480 return;
481 }
482
483 if (s->chr_accept_input)
484 s->chr_accept_input(s);
485 qemu_notify_event();
486 }
487
488 void qemu_chr_fe_printf(CharBackend *be, const char *fmt, ...)
489 {
490 char buf[READ_BUF_LEN];
491 va_list ap;
492 va_start(ap, fmt);
493 vsnprintf(buf, sizeof(buf), fmt, ap);
494 /* XXX this blocks entire thread. Rewrite to use
495 * qemu_chr_fe_write and background I/O callbacks */
496 qemu_chr_fe_write_all(be, (uint8_t *)buf, strlen(buf));
497 va_end(ap);
498 }
499
500 static void remove_fd_in_watch(CharDriverState *chr);
501 static void mux_chr_set_handlers(CharDriverState *chr, GMainContext *context);
502 static void mux_set_focus(MuxDriver *d, int focus);
503
504 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
505 {
506 return len;
507 }
508
509 static CharDriverState *qemu_chr_open_null(const char *id,
510 ChardevBackend *backend,
511 ChardevReturn *ret,
512 bool *be_opened,
513 Error **errp)
514 {
515 CharDriverState *chr;
516 ChardevCommon *common = backend->u.null.data;
517
518 chr = qemu_chr_alloc(common, errp);
519 if (!chr) {
520 return NULL;
521 }
522 chr->chr_write = null_chr_write;
523 *be_opened = false;
524 return chr;
525 }
526
527 /* MUX driver for serial I/O splitting */
528 #define MAX_MUX 4
529 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
530 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
531 struct MuxDriver {
532 CharBackend *backends[MAX_MUX];
533 CharBackend chr;
534 int focus;
535 int mux_cnt;
536 int term_got_escape;
537 int max_size;
538 /* Intermediate input buffer allows to catch escape sequences even if the
539 currently active device is not accepting any input - but only until it
540 is full as well. */
541 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
542 int prod[MAX_MUX];
543 int cons[MAX_MUX];
544 int timestamps;
545
546 /* Protected by the CharDriverState chr_write_lock. */
547 int linestart;
548 int64_t timestamps_start;
549 };
550
551 /* Called with chr_write_lock held. */
552 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
553 {
554 MuxDriver *d = chr->opaque;
555 int ret;
556 if (!d->timestamps) {
557 ret = qemu_chr_fe_write(&d->chr, buf, len);
558 } else {
559 int i;
560
561 ret = 0;
562 for (i = 0; i < len; i++) {
563 if (d->linestart) {
564 char buf1[64];
565 int64_t ti;
566 int secs;
567
568 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
569 if (d->timestamps_start == -1)
570 d->timestamps_start = ti;
571 ti -= d->timestamps_start;
572 secs = ti / 1000;
573 snprintf(buf1, sizeof(buf1),
574 "[%02d:%02d:%02d.%03d] ",
575 secs / 3600,
576 (secs / 60) % 60,
577 secs % 60,
578 (int)(ti % 1000));
579 /* XXX this blocks entire thread. Rewrite to use
580 * qemu_chr_fe_write and background I/O callbacks */
581 qemu_chr_fe_write_all(&d->chr,
582 (uint8_t *)buf1, strlen(buf1));
583 d->linestart = 0;
584 }
585 ret += qemu_chr_fe_write(&d->chr, buf + i, 1);
586 if (buf[i] == '\n') {
587 d->linestart = 1;
588 }
589 }
590 }
591 return ret;
592 }
593
594 static const char * const mux_help[] = {
595 "% h print this help\n\r",
596 "% x exit emulator\n\r",
597 "% s save disk data back to file (if -snapshot)\n\r",
598 "% t toggle console timestamps\n\r",
599 "% b send break (magic sysrq)\n\r",
600 "% c switch between console and monitor\n\r",
601 "% % sends %\n\r",
602 NULL
603 };
604
605 int term_escape_char = 0x01; /* ctrl-a is used for escape */
606 static void mux_print_help(CharDriverState *chr)
607 {
608 int i, j;
609 char ebuf[15] = "Escape-Char";
610 char cbuf[50] = "\n\r";
611
612 if (term_escape_char > 0 && term_escape_char < 26) {
613 snprintf(cbuf, sizeof(cbuf), "\n\r");
614 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
615 } else {
616 snprintf(cbuf, sizeof(cbuf),
617 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
618 term_escape_char);
619 }
620 /* XXX this blocks entire thread. Rewrite to use
621 * qemu_chr_fe_write and background I/O callbacks */
622 qemu_chr_write_all(chr, (uint8_t *)cbuf, strlen(cbuf));
623 for (i = 0; mux_help[i] != NULL; i++) {
624 for (j=0; mux_help[i][j] != '\0'; j++) {
625 if (mux_help[i][j] == '%')
626 qemu_chr_write_all(chr, (uint8_t *)ebuf, strlen(ebuf));
627 else
628 qemu_chr_write_all(chr, (uint8_t *)&mux_help[i][j], 1);
629 }
630 }
631 }
632
633 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
634 {
635 CharBackend *be = d->backends[mux_nr];
636
637 if (be && be->chr_event) {
638 be->chr_event(be->opaque, event);
639 }
640 }
641
642 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
643 {
644 if (d->term_got_escape) {
645 d->term_got_escape = 0;
646 if (ch == term_escape_char)
647 goto send_char;
648 switch(ch) {
649 case '?':
650 case 'h':
651 mux_print_help(chr);
652 break;
653 case 'x':
654 {
655 const char *term = "QEMU: Terminated\n\r";
656 qemu_chr_write_all(chr, (uint8_t *)term, strlen(term));
657 exit(0);
658 break;
659 }
660 case 's':
661 blk_commit_all();
662 break;
663 case 'b':
664 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
665 break;
666 case 'c':
667 assert(d->mux_cnt > 0); /* handler registered with first fe */
668 /* Switch to the next registered device */
669 mux_set_focus(d, (d->focus + 1) % d->mux_cnt);
670 break;
671 case 't':
672 d->timestamps = !d->timestamps;
673 d->timestamps_start = -1;
674 d->linestart = 0;
675 break;
676 }
677 } else if (ch == term_escape_char) {
678 d->term_got_escape = 1;
679 } else {
680 send_char:
681 return 1;
682 }
683 return 0;
684 }
685
686 static void mux_chr_accept_input(CharDriverState *chr)
687 {
688 MuxDriver *d = chr->opaque;
689 int m = d->focus;
690 CharBackend *be = d->backends[m];
691
692 while (be && d->prod[m] != d->cons[m] &&
693 be->chr_can_read && be->chr_can_read(be->opaque)) {
694 be->chr_read(be->opaque,
695 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
696 }
697 }
698
699 static int mux_chr_can_read(void *opaque)
700 {
701 CharDriverState *chr = opaque;
702 MuxDriver *d = chr->opaque;
703 int m = d->focus;
704 CharBackend *be = d->backends[m];
705
706 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE) {
707 return 1;
708 }
709
710 if (be && be->chr_can_read) {
711 return be->chr_can_read(be->opaque);
712 }
713
714 return 0;
715 }
716
717 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
718 {
719 CharDriverState *chr = opaque;
720 MuxDriver *d = chr->opaque;
721 int m = d->focus;
722 CharBackend *be = d->backends[m];
723 int i;
724
725 mux_chr_accept_input(opaque);
726
727 for (i = 0; i < size; i++)
728 if (mux_proc_byte(chr, d, buf[i])) {
729 if (d->prod[m] == d->cons[m] &&
730 be && be->chr_can_read &&
731 be->chr_can_read(be->opaque))
732 be->chr_read(be->opaque, &buf[i], 1);
733 else
734 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
735 }
736 }
737
738 static bool muxes_realized;
739
740 static void mux_chr_event(void *opaque, int event)
741 {
742 CharDriverState *chr = opaque;
743 MuxDriver *d = chr->opaque;
744 int i;
745
746 if (!muxes_realized) {
747 return;
748 }
749
750 /* Send the event to all registered listeners */
751 for (i = 0; i < d->mux_cnt; i++)
752 mux_chr_send_event(d, i, event);
753 }
754
755 /**
756 * Called after processing of default and command-line-specified
757 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
758 * to a mux chardev. This is done here to ensure that
759 * output/prompts/banners are only displayed for the FE that has
760 * focus when initial command-line processing/machine init is
761 * completed.
762 *
763 * After this point, any new FE attached to any new or existing
764 * mux will receive CHR_EVENT_OPENED notifications for the BE
765 * immediately.
766 */
767 static void muxes_realize_done(Notifier *notifier, void *unused)
768 {
769 CharDriverState *chr;
770
771 QTAILQ_FOREACH(chr, &chardevs, next) {
772 if (chr->is_mux) {
773 MuxDriver *d = chr->opaque;
774 int i;
775
776 /* send OPENED to all already-attached FEs */
777 for (i = 0; i < d->mux_cnt; i++) {
778 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
779 }
780 /* mark mux as OPENED so any new FEs will immediately receive
781 * OPENED event
782 */
783 qemu_chr_be_generic_open(chr);
784 }
785 }
786 muxes_realized = true;
787 }
788
789 static Notifier muxes_realize_notify = {
790 .notify = muxes_realize_done,
791 };
792
793 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
794 {
795 MuxDriver *d = s->opaque;
796 CharDriverState *chr = qemu_chr_fe_get_driver(&d->chr);
797
798 return chr->chr_add_watch(chr, cond);
799 }
800
801 static void mux_chr_free(struct CharDriverState *chr)
802 {
803 MuxDriver *d = chr->opaque;
804 int i;
805
806 for (i = 0; i < d->mux_cnt; i++) {
807 CharBackend *be = d->backends[i];
808 if (be) {
809 be->chr = NULL;
810 }
811 }
812 qemu_chr_fe_deinit(&d->chr);
813 g_free(d);
814 }
815
816 static void mux_chr_set_handlers(CharDriverState *chr, GMainContext *context)
817 {
818 MuxDriver *d = chr->opaque;
819
820 /* Fix up the real driver with mux routines */
821 qemu_chr_fe_set_handlers(&d->chr,
822 mux_chr_can_read,
823 mux_chr_read,
824 mux_chr_event,
825 chr,
826 context, true);
827 }
828
829 static void mux_set_focus(MuxDriver *d, int focus)
830 {
831 assert(focus >= 0);
832 assert(focus < d->mux_cnt);
833
834 if (d->focus != -1) {
835 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
836 }
837
838 d->focus = focus;
839 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
840 }
841
842 static CharDriverState *qemu_chr_open_mux(const char *id,
843 ChardevBackend *backend,
844 ChardevReturn *ret,
845 bool *be_opened,
846 Error **errp)
847 {
848 ChardevMux *mux = backend->u.mux.data;
849 CharDriverState *chr, *drv;
850 MuxDriver *d;
851 ChardevCommon *common = qapi_ChardevMux_base(mux);
852
853 drv = qemu_chr_find(mux->chardev);
854 if (drv == NULL) {
855 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
856 return NULL;
857 }
858
859 chr = qemu_chr_alloc(common, errp);
860 if (!chr) {
861 return NULL;
862 }
863 d = g_new0(MuxDriver, 1);
864
865 chr->opaque = d;
866 d->focus = -1;
867 chr->chr_free = mux_chr_free;
868 chr->chr_write = mux_chr_write;
869 chr->chr_accept_input = mux_chr_accept_input;
870 /* Frontend guest-open / -close notification is not support with muxes */
871 chr->chr_set_fe_open = NULL;
872 if (drv->chr_add_watch) {
873 chr->chr_add_watch = mux_chr_add_watch;
874 }
875 /* only default to opened state if we've realized the initial
876 * set of muxes
877 */
878 *be_opened = muxes_realized;
879 chr->is_mux = 1;
880 if (!qemu_chr_fe_init(&d->chr, drv, errp)) {
881 qemu_chr_free(chr);
882 return NULL;
883 }
884
885 return chr;
886 }
887
888 CharDriverState *qemu_chr_fe_get_driver(CharBackend *be)
889 {
890 return be->chr;
891 }
892
893 bool qemu_chr_fe_init(CharBackend *b, CharDriverState *s, Error **errp)
894 {
895 int tag = 0;
896
897 if (s->is_mux) {
898 MuxDriver *d = s->opaque;
899
900 if (d->mux_cnt >= MAX_MUX) {
901 goto unavailable;
902 }
903
904 d->backends[d->mux_cnt] = b;
905 tag = d->mux_cnt++;
906 } else if (s->be) {
907 goto unavailable;
908 } else {
909 s->be = b;
910 }
911
912 b->fe_open = false;
913 b->tag = tag;
914 b->chr = s;
915 return true;
916
917 unavailable:
918 error_setg(errp, QERR_DEVICE_IN_USE, s->label);
919 return false;
920 }
921
922 static bool qemu_chr_is_busy(CharDriverState *s)
923 {
924 if (s->is_mux) {
925 MuxDriver *d = s->opaque;
926 return d->mux_cnt >= 0;
927 } else {
928 return s->be != NULL;
929 }
930 }
931
932 void qemu_chr_fe_deinit(CharBackend *b)
933 {
934 assert(b);
935
936 if (b->chr) {
937 qemu_chr_fe_set_handlers(b, NULL, NULL, NULL, NULL, NULL, true);
938 b->chr->be = NULL;
939 if (b->chr->is_mux) {
940 MuxDriver *d = b->chr->opaque;
941 d->backends[b->tag] = NULL;
942 }
943 b->chr = NULL;
944 }
945 }
946
947 void qemu_chr_fe_set_handlers(CharBackend *b,
948 IOCanReadHandler *fd_can_read,
949 IOReadHandler *fd_read,
950 IOEventHandler *fd_event,
951 void *opaque,
952 GMainContext *context,
953 bool set_open)
954 {
955 CharDriverState *s;
956 int fe_open;
957
958 s = b->chr;
959 if (!s) {
960 return;
961 }
962
963 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
964 fe_open = 0;
965 remove_fd_in_watch(s);
966 } else {
967 fe_open = 1;
968 }
969 b->chr_can_read = fd_can_read;
970 b->chr_read = fd_read;
971 b->chr_event = fd_event;
972 b->opaque = opaque;
973 if (s->chr_update_read_handler) {
974 s->chr_update_read_handler(s, context);
975 }
976
977 if (set_open) {
978 qemu_chr_fe_set_open(b, fe_open);
979 }
980
981 if (fe_open) {
982 qemu_chr_fe_take_focus(b);
983 /* We're connecting to an already opened device, so let's make sure we
984 also get the open event */
985 if (s->be_open) {
986 qemu_chr_be_generic_open(s);
987 }
988 }
989
990 if (s->is_mux) {
991 mux_chr_set_handlers(s, context);
992 }
993 }
994
995 void qemu_chr_fe_take_focus(CharBackend *b)
996 {
997 if (!b->chr) {
998 return;
999 }
1000
1001 if (b->chr->is_mux) {
1002 mux_set_focus(b->chr->opaque, b->tag);
1003 }
1004 }
1005
1006 typedef struct IOWatchPoll
1007 {
1008 GSource parent;
1009
1010 QIOChannel *ioc;
1011 GSource *src;
1012
1013 IOCanReadHandler *fd_can_read;
1014 GSourceFunc fd_read;
1015 void *opaque;
1016 GMainContext *context;
1017 } IOWatchPoll;
1018
1019 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
1020 {
1021 return container_of(source, IOWatchPoll, parent);
1022 }
1023
1024 static gboolean io_watch_poll_prepare(GSource *source,
1025 gint *timeout_)
1026 {
1027 IOWatchPoll *iwp = io_watch_poll_from_source(source);
1028 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
1029 bool was_active = iwp->src != NULL;
1030 if (was_active == now_active) {
1031 return FALSE;
1032 }
1033
1034 if (now_active) {
1035 iwp->src = qio_channel_create_watch(
1036 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
1037 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
1038 g_source_attach(iwp->src, iwp->context);
1039 } else {
1040 g_source_destroy(iwp->src);
1041 g_source_unref(iwp->src);
1042 iwp->src = NULL;
1043 }
1044 return FALSE;
1045 }
1046
1047 static gboolean io_watch_poll_check(GSource *source)
1048 {
1049 return FALSE;
1050 }
1051
1052 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
1053 gpointer user_data)
1054 {
1055 abort();
1056 }
1057
1058 static void io_watch_poll_finalize(GSource *source)
1059 {
1060 /* Due to a glib bug, removing the last reference to a source
1061 * inside a finalize callback causes recursive locking (and a
1062 * deadlock). This is not a problem inside other callbacks,
1063 * including dispatch callbacks, so we call io_remove_watch_poll
1064 * to remove this source. At this point, iwp->src must
1065 * be NULL, or we would leak it.
1066 *
1067 * This would be solved much more elegantly by child sources,
1068 * but we support older glib versions that do not have them.
1069 */
1070 IOWatchPoll *iwp = io_watch_poll_from_source(source);
1071 assert(iwp->src == NULL);
1072 }
1073
1074 static GSourceFuncs io_watch_poll_funcs = {
1075 .prepare = io_watch_poll_prepare,
1076 .check = io_watch_poll_check,
1077 .dispatch = io_watch_poll_dispatch,
1078 .finalize = io_watch_poll_finalize,
1079 };
1080
1081 /* Can only be used for read */
1082 static guint io_add_watch_poll(CharDriverState *chr,
1083 QIOChannel *ioc,
1084 IOCanReadHandler *fd_can_read,
1085 QIOChannelFunc fd_read,
1086 gpointer user_data,
1087 GMainContext *context)
1088 {
1089 IOWatchPoll *iwp;
1090 int tag;
1091 char *name;
1092
1093 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs,
1094 sizeof(IOWatchPoll));
1095 iwp->fd_can_read = fd_can_read;
1096 iwp->opaque = user_data;
1097 iwp->ioc = ioc;
1098 iwp->fd_read = (GSourceFunc) fd_read;
1099 iwp->src = NULL;
1100 iwp->context = context;
1101
1102 name = g_strdup_printf("chardev-iowatch-%s", chr->label);
1103 g_source_set_name((GSource *)iwp, name);
1104 g_free(name);
1105
1106 tag = g_source_attach(&iwp->parent, context);
1107 g_source_unref(&iwp->parent);
1108 return tag;
1109 }
1110
1111 static void io_remove_watch_poll(guint tag)
1112 {
1113 GSource *source;
1114 IOWatchPoll *iwp;
1115
1116 g_return_if_fail (tag > 0);
1117
1118 source = g_main_context_find_source_by_id(NULL, tag);
1119 g_return_if_fail (source != NULL);
1120
1121 iwp = io_watch_poll_from_source(source);
1122 if (iwp->src) {
1123 g_source_destroy(iwp->src);
1124 g_source_unref(iwp->src);
1125 iwp->src = NULL;
1126 }
1127 g_source_destroy(&iwp->parent);
1128 }
1129
1130 static void remove_fd_in_watch(CharDriverState *chr)
1131 {
1132 if (chr->fd_in_tag) {
1133 io_remove_watch_poll(chr->fd_in_tag);
1134 chr->fd_in_tag = 0;
1135 }
1136 }
1137
1138
1139 static int io_channel_send_full(QIOChannel *ioc,
1140 const void *buf, size_t len,
1141 int *fds, size_t nfds)
1142 {
1143 size_t offset = 0;
1144
1145 while (offset < len) {
1146 ssize_t ret = 0;
1147 struct iovec iov = { .iov_base = (char *)buf + offset,
1148 .iov_len = len - offset };
1149
1150 ret = qio_channel_writev_full(
1151 ioc, &iov, 1,
1152 fds, nfds, NULL);
1153 if (ret == QIO_CHANNEL_ERR_BLOCK) {
1154 if (offset) {
1155 return offset;
1156 }
1157
1158 errno = EAGAIN;
1159 return -1;
1160 } else if (ret < 0) {
1161 errno = EINVAL;
1162 return -1;
1163 }
1164
1165 offset += ret;
1166 }
1167
1168 return offset;
1169 }
1170
1171
1172 #ifndef _WIN32
1173 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
1174 {
1175 return io_channel_send_full(ioc, buf, len, NULL, 0);
1176 }
1177
1178
1179 typedef struct FDCharDriver {
1180 CharDriverState *chr;
1181 QIOChannel *ioc_in, *ioc_out;
1182 int max_size;
1183 } FDCharDriver;
1184
1185 /* Called with chr_write_lock held. */
1186 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1187 {
1188 FDCharDriver *s = chr->opaque;
1189
1190 return io_channel_send(s->ioc_out, buf, len);
1191 }
1192
1193 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1194 {
1195 CharDriverState *chr = opaque;
1196 FDCharDriver *s = chr->opaque;
1197 int len;
1198 uint8_t buf[READ_BUF_LEN];
1199 ssize_t ret;
1200
1201 len = sizeof(buf);
1202 if (len > s->max_size) {
1203 len = s->max_size;
1204 }
1205 if (len == 0) {
1206 return TRUE;
1207 }
1208
1209 ret = qio_channel_read(
1210 chan, (gchar *)buf, len, NULL);
1211 if (ret == 0) {
1212 remove_fd_in_watch(chr);
1213 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1214 return FALSE;
1215 }
1216 if (ret > 0) {
1217 qemu_chr_be_write(chr, buf, ret);
1218 }
1219
1220 return TRUE;
1221 }
1222
1223 static int fd_chr_read_poll(void *opaque)
1224 {
1225 CharDriverState *chr = opaque;
1226 FDCharDriver *s = chr->opaque;
1227
1228 s->max_size = qemu_chr_be_can_write(chr);
1229 return s->max_size;
1230 }
1231
1232 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1233 {
1234 FDCharDriver *s = chr->opaque;
1235 return qio_channel_create_watch(s->ioc_out, cond);
1236 }
1237
1238 static void fd_chr_update_read_handler(CharDriverState *chr,
1239 GMainContext *context)
1240 {
1241 FDCharDriver *s = chr->opaque;
1242
1243 remove_fd_in_watch(chr);
1244 if (s->ioc_in) {
1245 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc_in,
1246 fd_chr_read_poll,
1247 fd_chr_read, chr,
1248 context);
1249 }
1250 }
1251
1252 static void fd_chr_free(struct CharDriverState *chr)
1253 {
1254 FDCharDriver *s = chr->opaque;
1255
1256 remove_fd_in_watch(chr);
1257 if (s->ioc_in) {
1258 object_unref(OBJECT(s->ioc_in));
1259 }
1260 if (s->ioc_out) {
1261 object_unref(OBJECT(s->ioc_out));
1262 }
1263
1264 g_free(s);
1265 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1266 }
1267
1268 /* open a character device to a unix fd */
1269 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1270 ChardevCommon *backend, Error **errp)
1271 {
1272 CharDriverState *chr;
1273 FDCharDriver *s;
1274 char *name;
1275
1276 chr = qemu_chr_alloc(backend, errp);
1277 if (!chr) {
1278 return NULL;
1279 }
1280 s = g_new0(FDCharDriver, 1);
1281 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1282 name = g_strdup_printf("chardev-file-in-%s", chr->label);
1283 qio_channel_set_name(QIO_CHANNEL(s->ioc_in), name);
1284 g_free(name);
1285 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1286 name = g_strdup_printf("chardev-file-out-%s", chr->label);
1287 qio_channel_set_name(QIO_CHANNEL(s->ioc_out), name);
1288 g_free(name);
1289 qemu_set_nonblock(fd_out);
1290 s->chr = chr;
1291 chr->opaque = s;
1292 chr->chr_add_watch = fd_chr_add_watch;
1293 chr->chr_write = fd_chr_write;
1294 chr->chr_update_read_handler = fd_chr_update_read_handler;
1295 chr->chr_free = fd_chr_free;
1296
1297 return chr;
1298 }
1299
1300 static CharDriverState *qemu_chr_open_pipe(const char *id,
1301 ChardevBackend *backend,
1302 ChardevReturn *ret,
1303 bool *be_opened,
1304 Error **errp)
1305 {
1306 ChardevHostdev *opts = backend->u.pipe.data;
1307 int fd_in, fd_out;
1308 char *filename_in;
1309 char *filename_out;
1310 const char *filename = opts->device;
1311 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1312
1313
1314 filename_in = g_strdup_printf("%s.in", filename);
1315 filename_out = g_strdup_printf("%s.out", filename);
1316 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1317 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1318 g_free(filename_in);
1319 g_free(filename_out);
1320 if (fd_in < 0 || fd_out < 0) {
1321 if (fd_in >= 0)
1322 close(fd_in);
1323 if (fd_out >= 0)
1324 close(fd_out);
1325 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1326 if (fd_in < 0) {
1327 error_setg_file_open(errp, errno, filename);
1328 return NULL;
1329 }
1330 }
1331 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1332 }
1333
1334 /* init terminal so that we can grab keys */
1335 static struct termios oldtty;
1336 static int old_fd0_flags;
1337 static bool stdio_in_use;
1338 static bool stdio_allow_signal;
1339 static bool stdio_echo_state;
1340
1341 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1342
1343 static void term_exit(void)
1344 {
1345 tcsetattr (0, TCSANOW, &oldtty);
1346 fcntl(0, F_SETFL, old_fd0_flags);
1347 }
1348
1349 static void term_stdio_handler(int sig)
1350 {
1351 /* restore echo after resume from suspend. */
1352 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1353 }
1354
1355 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1356 {
1357 struct termios tty;
1358
1359 stdio_echo_state = echo;
1360 tty = oldtty;
1361 if (!echo) {
1362 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1363 |INLCR|IGNCR|ICRNL|IXON);
1364 tty.c_oflag |= OPOST;
1365 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1366 tty.c_cflag &= ~(CSIZE|PARENB);
1367 tty.c_cflag |= CS8;
1368 tty.c_cc[VMIN] = 1;
1369 tty.c_cc[VTIME] = 0;
1370 }
1371 if (!stdio_allow_signal)
1372 tty.c_lflag &= ~ISIG;
1373
1374 tcsetattr (0, TCSANOW, &tty);
1375 }
1376
1377 static void qemu_chr_free_stdio(struct CharDriverState *chr)
1378 {
1379 term_exit();
1380 fd_chr_free(chr);
1381 }
1382
1383 static CharDriverState *qemu_chr_open_stdio(const char *id,
1384 ChardevBackend *backend,
1385 ChardevReturn *ret,
1386 bool *be_opened,
1387 Error **errp)
1388 {
1389 ChardevStdio *opts = backend->u.stdio.data;
1390 CharDriverState *chr;
1391 struct sigaction act;
1392 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1393
1394 if (is_daemonized()) {
1395 error_setg(errp, "cannot use stdio with -daemonize");
1396 return NULL;
1397 }
1398
1399 if (stdio_in_use) {
1400 error_setg(errp, "cannot use stdio by multiple character devices");
1401 return NULL;
1402 }
1403
1404 stdio_in_use = true;
1405 old_fd0_flags = fcntl(0, F_GETFL);
1406 tcgetattr(0, &oldtty);
1407 qemu_set_nonblock(0);
1408 atexit(term_exit);
1409
1410 memset(&act, 0, sizeof(act));
1411 act.sa_handler = term_stdio_handler;
1412 sigaction(SIGCONT, &act, NULL);
1413
1414 chr = qemu_chr_open_fd(0, 1, common, errp);
1415 if (!chr) {
1416 return NULL;
1417 }
1418 chr->chr_free = qemu_chr_free_stdio;
1419 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1420 if (opts->has_signal) {
1421 stdio_allow_signal = opts->signal;
1422 }
1423 qemu_chr_set_echo_stdio(chr, false);
1424
1425 return chr;
1426 }
1427
1428 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1429 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1430 || defined(__GLIBC__)
1431
1432 #define HAVE_CHARDEV_SERIAL 1
1433 #define HAVE_CHARDEV_PTY 1
1434
1435 typedef struct {
1436 QIOChannel *ioc;
1437 int read_bytes;
1438
1439 /* Protected by the CharDriverState chr_write_lock. */
1440 int connected;
1441 guint timer_tag;
1442 guint open_tag;
1443 } PtyCharDriver;
1444
1445 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1446 static void pty_chr_state(CharDriverState *chr, int connected);
1447
1448 static gboolean pty_chr_timer(gpointer opaque)
1449 {
1450 struct CharDriverState *chr = opaque;
1451 PtyCharDriver *s = chr->opaque;
1452
1453 qemu_mutex_lock(&chr->chr_write_lock);
1454 s->timer_tag = 0;
1455 s->open_tag = 0;
1456 if (!s->connected) {
1457 /* Next poll ... */
1458 pty_chr_update_read_handler_locked(chr);
1459 }
1460 qemu_mutex_unlock(&chr->chr_write_lock);
1461 return FALSE;
1462 }
1463
1464 /* Called with chr_write_lock held. */
1465 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1466 {
1467 PtyCharDriver *s = chr->opaque;
1468 char *name;
1469
1470 if (s->timer_tag) {
1471 g_source_remove(s->timer_tag);
1472 s->timer_tag = 0;
1473 }
1474
1475 if (ms == 1000) {
1476 name = g_strdup_printf("pty-timer-secs-%s", chr->label);
1477 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1478 } else {
1479 name = g_strdup_printf("pty-timer-ms-%s", chr->label);
1480 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1481 }
1482 g_source_set_name_by_id(s->timer_tag, name);
1483 g_free(name);
1484 }
1485
1486 /* Called with chr_write_lock held. */
1487 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1488 {
1489 PtyCharDriver *s = chr->opaque;
1490 GPollFD pfd;
1491 int rc;
1492 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1493
1494 pfd.fd = fioc->fd;
1495 pfd.events = G_IO_OUT;
1496 pfd.revents = 0;
1497 do {
1498 rc = g_poll(&pfd, 1, 0);
1499 } while (rc == -1 && errno == EINTR);
1500 assert(rc >= 0);
1501
1502 if (pfd.revents & G_IO_HUP) {
1503 pty_chr_state(chr, 0);
1504 } else {
1505 pty_chr_state(chr, 1);
1506 }
1507 }
1508
1509 static void pty_chr_update_read_handler(CharDriverState *chr,
1510 GMainContext *context)
1511 {
1512 qemu_mutex_lock(&chr->chr_write_lock);
1513 pty_chr_update_read_handler_locked(chr);
1514 qemu_mutex_unlock(&chr->chr_write_lock);
1515 }
1516
1517 /* Called with chr_write_lock held. */
1518 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1519 {
1520 PtyCharDriver *s = chr->opaque;
1521
1522 if (!s->connected) {
1523 /* guest sends data, check for (re-)connect */
1524 pty_chr_update_read_handler_locked(chr);
1525 if (!s->connected) {
1526 return 0;
1527 }
1528 }
1529 return io_channel_send(s->ioc, buf, len);
1530 }
1531
1532 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1533 {
1534 PtyCharDriver *s = chr->opaque;
1535 if (!s->connected) {
1536 return NULL;
1537 }
1538 return qio_channel_create_watch(s->ioc, cond);
1539 }
1540
1541 static int pty_chr_read_poll(void *opaque)
1542 {
1543 CharDriverState *chr = opaque;
1544 PtyCharDriver *s = chr->opaque;
1545
1546 s->read_bytes = qemu_chr_be_can_write(chr);
1547 return s->read_bytes;
1548 }
1549
1550 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1551 {
1552 CharDriverState *chr = opaque;
1553 PtyCharDriver *s = chr->opaque;
1554 gsize len;
1555 uint8_t buf[READ_BUF_LEN];
1556 ssize_t ret;
1557
1558 len = sizeof(buf);
1559 if (len > s->read_bytes)
1560 len = s->read_bytes;
1561 if (len == 0) {
1562 return TRUE;
1563 }
1564 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1565 if (ret <= 0) {
1566 pty_chr_state(chr, 0);
1567 return FALSE;
1568 } else {
1569 pty_chr_state(chr, 1);
1570 qemu_chr_be_write(chr, buf, ret);
1571 }
1572 return TRUE;
1573 }
1574
1575 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1576 {
1577 CharDriverState *chr = opaque;
1578 PtyCharDriver *s = chr->opaque;
1579
1580 s->open_tag = 0;
1581 qemu_chr_be_generic_open(chr);
1582 return FALSE;
1583 }
1584
1585 /* Called with chr_write_lock held. */
1586 static void pty_chr_state(CharDriverState *chr, int connected)
1587 {
1588 PtyCharDriver *s = chr->opaque;
1589
1590 if (!connected) {
1591 if (s->open_tag) {
1592 g_source_remove(s->open_tag);
1593 s->open_tag = 0;
1594 }
1595 remove_fd_in_watch(chr);
1596 s->connected = 0;
1597 /* (re-)connect poll interval for idle guests: once per second.
1598 * We check more frequently in case the guests sends data to
1599 * the virtual device linked to our pty. */
1600 pty_chr_rearm_timer(chr, 1000);
1601 } else {
1602 if (s->timer_tag) {
1603 g_source_remove(s->timer_tag);
1604 s->timer_tag = 0;
1605 }
1606 if (!s->connected) {
1607 g_assert(s->open_tag == 0);
1608 s->connected = 1;
1609 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1610 }
1611 if (!chr->fd_in_tag) {
1612 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
1613 pty_chr_read_poll,
1614 pty_chr_read,
1615 chr, NULL);
1616 }
1617 }
1618 }
1619
1620 static void pty_chr_free(struct CharDriverState *chr)
1621 {
1622 PtyCharDriver *s = chr->opaque;
1623
1624 qemu_mutex_lock(&chr->chr_write_lock);
1625 pty_chr_state(chr, 0);
1626 object_unref(OBJECT(s->ioc));
1627 if (s->timer_tag) {
1628 g_source_remove(s->timer_tag);
1629 s->timer_tag = 0;
1630 }
1631 qemu_mutex_unlock(&chr->chr_write_lock);
1632 g_free(s);
1633 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1634 }
1635
1636 static CharDriverState *qemu_chr_open_pty(const char *id,
1637 ChardevBackend *backend,
1638 ChardevReturn *ret,
1639 bool *be_opened,
1640 Error **errp)
1641 {
1642 CharDriverState *chr;
1643 PtyCharDriver *s;
1644 int master_fd, slave_fd;
1645 char pty_name[PATH_MAX];
1646 ChardevCommon *common = backend->u.pty.data;
1647 char *name;
1648
1649 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1650 if (master_fd < 0) {
1651 error_setg_errno(errp, errno, "Failed to create PTY");
1652 return NULL;
1653 }
1654
1655 close(slave_fd);
1656 qemu_set_nonblock(master_fd);
1657
1658 chr = qemu_chr_alloc(common, errp);
1659 if (!chr) {
1660 close(master_fd);
1661 return NULL;
1662 }
1663
1664 chr->filename = g_strdup_printf("pty:%s", pty_name);
1665 ret->pty = g_strdup(pty_name);
1666 ret->has_pty = true;
1667
1668 fprintf(stderr, "char device redirected to %s (label %s)\n",
1669 pty_name, id);
1670
1671 s = g_new0(PtyCharDriver, 1);
1672 chr->opaque = s;
1673 chr->chr_write = pty_chr_write;
1674 chr->chr_update_read_handler = pty_chr_update_read_handler;
1675 chr->chr_free = pty_chr_free;
1676 chr->chr_add_watch = pty_chr_add_watch;
1677 *be_opened = false;
1678
1679 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1680 name = g_strdup_printf("chardev-pty-%s", chr->label);
1681 qio_channel_set_name(QIO_CHANNEL(s->ioc), name);
1682 g_free(name);
1683 s->timer_tag = 0;
1684
1685 return chr;
1686 }
1687
1688 static void tty_serial_init(int fd, int speed,
1689 int parity, int data_bits, int stop_bits)
1690 {
1691 struct termios tty;
1692 speed_t spd;
1693
1694 #if 0
1695 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1696 speed, parity, data_bits, stop_bits);
1697 #endif
1698 tcgetattr (fd, &tty);
1699
1700 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1701 speed = speed * 10 / 11;
1702 do {
1703 check_speed(50);
1704 check_speed(75);
1705 check_speed(110);
1706 check_speed(134);
1707 check_speed(150);
1708 check_speed(200);
1709 check_speed(300);
1710 check_speed(600);
1711 check_speed(1200);
1712 check_speed(1800);
1713 check_speed(2400);
1714 check_speed(4800);
1715 check_speed(9600);
1716 check_speed(19200);
1717 check_speed(38400);
1718 /* Non-Posix values follow. They may be unsupported on some systems. */
1719 check_speed(57600);
1720 check_speed(115200);
1721 #ifdef B230400
1722 check_speed(230400);
1723 #endif
1724 #ifdef B460800
1725 check_speed(460800);
1726 #endif
1727 #ifdef B500000
1728 check_speed(500000);
1729 #endif
1730 #ifdef B576000
1731 check_speed(576000);
1732 #endif
1733 #ifdef B921600
1734 check_speed(921600);
1735 #endif
1736 #ifdef B1000000
1737 check_speed(1000000);
1738 #endif
1739 #ifdef B1152000
1740 check_speed(1152000);
1741 #endif
1742 #ifdef B1500000
1743 check_speed(1500000);
1744 #endif
1745 #ifdef B2000000
1746 check_speed(2000000);
1747 #endif
1748 #ifdef B2500000
1749 check_speed(2500000);
1750 #endif
1751 #ifdef B3000000
1752 check_speed(3000000);
1753 #endif
1754 #ifdef B3500000
1755 check_speed(3500000);
1756 #endif
1757 #ifdef B4000000
1758 check_speed(4000000);
1759 #endif
1760 spd = B115200;
1761 } while (0);
1762
1763 cfsetispeed(&tty, spd);
1764 cfsetospeed(&tty, spd);
1765
1766 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1767 |INLCR|IGNCR|ICRNL|IXON);
1768 tty.c_oflag |= OPOST;
1769 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1770 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1771 switch(data_bits) {
1772 default:
1773 case 8:
1774 tty.c_cflag |= CS8;
1775 break;
1776 case 7:
1777 tty.c_cflag |= CS7;
1778 break;
1779 case 6:
1780 tty.c_cflag |= CS6;
1781 break;
1782 case 5:
1783 tty.c_cflag |= CS5;
1784 break;
1785 }
1786 switch(parity) {
1787 default:
1788 case 'N':
1789 break;
1790 case 'E':
1791 tty.c_cflag |= PARENB;
1792 break;
1793 case 'O':
1794 tty.c_cflag |= PARENB | PARODD;
1795 break;
1796 }
1797 if (stop_bits == 2)
1798 tty.c_cflag |= CSTOPB;
1799
1800 tcsetattr (fd, TCSANOW, &tty);
1801 }
1802
1803 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1804 {
1805 FDCharDriver *s = chr->opaque;
1806 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1807
1808 switch(cmd) {
1809 case CHR_IOCTL_SERIAL_SET_PARAMS:
1810 {
1811 QEMUSerialSetParams *ssp = arg;
1812 tty_serial_init(fioc->fd,
1813 ssp->speed, ssp->parity,
1814 ssp->data_bits, ssp->stop_bits);
1815 }
1816 break;
1817 case CHR_IOCTL_SERIAL_SET_BREAK:
1818 {
1819 int enable = *(int *)arg;
1820 if (enable) {
1821 tcsendbreak(fioc->fd, 1);
1822 }
1823 }
1824 break;
1825 case CHR_IOCTL_SERIAL_GET_TIOCM:
1826 {
1827 int sarg = 0;
1828 int *targ = (int *)arg;
1829 ioctl(fioc->fd, TIOCMGET, &sarg);
1830 *targ = 0;
1831 if (sarg & TIOCM_CTS)
1832 *targ |= CHR_TIOCM_CTS;
1833 if (sarg & TIOCM_CAR)
1834 *targ |= CHR_TIOCM_CAR;
1835 if (sarg & TIOCM_DSR)
1836 *targ |= CHR_TIOCM_DSR;
1837 if (sarg & TIOCM_RI)
1838 *targ |= CHR_TIOCM_RI;
1839 if (sarg & TIOCM_DTR)
1840 *targ |= CHR_TIOCM_DTR;
1841 if (sarg & TIOCM_RTS)
1842 *targ |= CHR_TIOCM_RTS;
1843 }
1844 break;
1845 case CHR_IOCTL_SERIAL_SET_TIOCM:
1846 {
1847 int sarg = *(int *)arg;
1848 int targ = 0;
1849 ioctl(fioc->fd, TIOCMGET, &targ);
1850 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1851 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1852 if (sarg & CHR_TIOCM_CTS)
1853 targ |= TIOCM_CTS;
1854 if (sarg & CHR_TIOCM_CAR)
1855 targ |= TIOCM_CAR;
1856 if (sarg & CHR_TIOCM_DSR)
1857 targ |= TIOCM_DSR;
1858 if (sarg & CHR_TIOCM_RI)
1859 targ |= TIOCM_RI;
1860 if (sarg & CHR_TIOCM_DTR)
1861 targ |= TIOCM_DTR;
1862 if (sarg & CHR_TIOCM_RTS)
1863 targ |= TIOCM_RTS;
1864 ioctl(fioc->fd, TIOCMSET, &targ);
1865 }
1866 break;
1867 default:
1868 return -ENOTSUP;
1869 }
1870 return 0;
1871 }
1872
1873 static void qemu_chr_free_tty(CharDriverState *chr)
1874 {
1875 fd_chr_free(chr);
1876 }
1877
1878 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1879 ChardevCommon *backend,
1880 bool *be_opened,
1881 Error **errp)
1882 {
1883 CharDriverState *chr;
1884
1885 tty_serial_init(fd, 115200, 'N', 8, 1);
1886 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1887 if (!chr) {
1888 return NULL;
1889 }
1890 chr->chr_ioctl = tty_serial_ioctl;
1891 chr->chr_free = qemu_chr_free_tty;
1892 return chr;
1893 }
1894 #endif /* __linux__ || __sun__ */
1895
1896 #if defined(__linux__)
1897
1898 #define HAVE_CHARDEV_PARPORT 1
1899
1900 typedef struct {
1901 int fd;
1902 int mode;
1903 } ParallelCharDriver;
1904
1905 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1906 {
1907 if (s->mode != mode) {
1908 int m = mode;
1909 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1910 return 0;
1911 s->mode = mode;
1912 }
1913 return 1;
1914 }
1915
1916 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1917 {
1918 ParallelCharDriver *drv = chr->opaque;
1919 int fd = drv->fd;
1920 uint8_t b;
1921
1922 switch(cmd) {
1923 case CHR_IOCTL_PP_READ_DATA:
1924 if (ioctl(fd, PPRDATA, &b) < 0)
1925 return -ENOTSUP;
1926 *(uint8_t *)arg = b;
1927 break;
1928 case CHR_IOCTL_PP_WRITE_DATA:
1929 b = *(uint8_t *)arg;
1930 if (ioctl(fd, PPWDATA, &b) < 0)
1931 return -ENOTSUP;
1932 break;
1933 case CHR_IOCTL_PP_READ_CONTROL:
1934 if (ioctl(fd, PPRCONTROL, &b) < 0)
1935 return -ENOTSUP;
1936 /* Linux gives only the lowest bits, and no way to know data
1937 direction! For better compatibility set the fixed upper
1938 bits. */
1939 *(uint8_t *)arg = b | 0xc0;
1940 break;
1941 case CHR_IOCTL_PP_WRITE_CONTROL:
1942 b = *(uint8_t *)arg;
1943 if (ioctl(fd, PPWCONTROL, &b) < 0)
1944 return -ENOTSUP;
1945 break;
1946 case CHR_IOCTL_PP_READ_STATUS:
1947 if (ioctl(fd, PPRSTATUS, &b) < 0)
1948 return -ENOTSUP;
1949 *(uint8_t *)arg = b;
1950 break;
1951 case CHR_IOCTL_PP_DATA_DIR:
1952 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1953 return -ENOTSUP;
1954 break;
1955 case CHR_IOCTL_PP_EPP_READ_ADDR:
1956 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1957 struct ParallelIOArg *parg = arg;
1958 int n = read(fd, parg->buffer, parg->count);
1959 if (n != parg->count) {
1960 return -EIO;
1961 }
1962 }
1963 break;
1964 case CHR_IOCTL_PP_EPP_READ:
1965 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1966 struct ParallelIOArg *parg = arg;
1967 int n = read(fd, parg->buffer, parg->count);
1968 if (n != parg->count) {
1969 return -EIO;
1970 }
1971 }
1972 break;
1973 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1974 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1975 struct ParallelIOArg *parg = arg;
1976 int n = write(fd, parg->buffer, parg->count);
1977 if (n != parg->count) {
1978 return -EIO;
1979 }
1980 }
1981 break;
1982 case CHR_IOCTL_PP_EPP_WRITE:
1983 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1984 struct ParallelIOArg *parg = arg;
1985 int n = write(fd, parg->buffer, parg->count);
1986 if (n != parg->count) {
1987 return -EIO;
1988 }
1989 }
1990 break;
1991 default:
1992 return -ENOTSUP;
1993 }
1994 return 0;
1995 }
1996
1997 static void pp_free(CharDriverState *chr)
1998 {
1999 ParallelCharDriver *drv = chr->opaque;
2000 int fd = drv->fd;
2001
2002 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2003 ioctl(fd, PPRELEASE);
2004 close(fd);
2005 g_free(drv);
2006 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2007 }
2008
2009 static CharDriverState *qemu_chr_open_pp_fd(int fd,
2010 ChardevCommon *backend,
2011 bool *be_opened,
2012 Error **errp)
2013 {
2014 CharDriverState *chr;
2015 ParallelCharDriver *drv;
2016
2017 if (ioctl(fd, PPCLAIM) < 0) {
2018 error_setg_errno(errp, errno, "not a parallel port");
2019 close(fd);
2020 return NULL;
2021 }
2022
2023 chr = qemu_chr_alloc(backend, errp);
2024 if (!chr) {
2025 return NULL;
2026 }
2027
2028 drv = g_new0(ParallelCharDriver, 1);
2029 chr->opaque = drv;
2030 chr->chr_write = null_chr_write;
2031 chr->chr_ioctl = pp_ioctl;
2032 chr->chr_free = pp_free;
2033
2034 drv->fd = fd;
2035 drv->mode = IEEE1284_MODE_COMPAT;
2036
2037 return chr;
2038 }
2039 #endif /* __linux__ */
2040
2041 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
2042
2043 #define HAVE_CHARDEV_PARPORT 1
2044
2045 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2046 {
2047 int fd = (int)(intptr_t)chr->opaque;
2048 uint8_t b;
2049
2050 switch(cmd) {
2051 case CHR_IOCTL_PP_READ_DATA:
2052 if (ioctl(fd, PPIGDATA, &b) < 0)
2053 return -ENOTSUP;
2054 *(uint8_t *)arg = b;
2055 break;
2056 case CHR_IOCTL_PP_WRITE_DATA:
2057 b = *(uint8_t *)arg;
2058 if (ioctl(fd, PPISDATA, &b) < 0)
2059 return -ENOTSUP;
2060 break;
2061 case CHR_IOCTL_PP_READ_CONTROL:
2062 if (ioctl(fd, PPIGCTRL, &b) < 0)
2063 return -ENOTSUP;
2064 *(uint8_t *)arg = b;
2065 break;
2066 case CHR_IOCTL_PP_WRITE_CONTROL:
2067 b = *(uint8_t *)arg;
2068 if (ioctl(fd, PPISCTRL, &b) < 0)
2069 return -ENOTSUP;
2070 break;
2071 case CHR_IOCTL_PP_READ_STATUS:
2072 if (ioctl(fd, PPIGSTATUS, &b) < 0)
2073 return -ENOTSUP;
2074 *(uint8_t *)arg = b;
2075 break;
2076 default:
2077 return -ENOTSUP;
2078 }
2079 return 0;
2080 }
2081
2082 static CharDriverState *qemu_chr_open_pp_fd(int fd,
2083 ChardevCommon *backend,
2084 bool *be_opened,
2085 Error **errp)
2086 {
2087 CharDriverState *chr;
2088
2089 chr = qemu_chr_alloc(backend, errp);
2090 if (!chr) {
2091 return NULL;
2092 }
2093 chr->opaque = (void *)(intptr_t)fd;
2094 chr->chr_write = null_chr_write;
2095 chr->chr_ioctl = pp_ioctl;
2096 *be_opened = false;
2097 return chr;
2098 }
2099 #endif
2100
2101 #else /* _WIN32 */
2102
2103 #define HAVE_CHARDEV_SERIAL 1
2104
2105 typedef struct {
2106 int max_size;
2107 HANDLE hcom, hrecv, hsend;
2108 OVERLAPPED orecv;
2109 BOOL fpipe;
2110 DWORD len;
2111
2112 /* Protected by the CharDriverState chr_write_lock. */
2113 OVERLAPPED osend;
2114 } WinCharState;
2115
2116 typedef struct {
2117 HANDLE hStdIn;
2118 HANDLE hInputReadyEvent;
2119 HANDLE hInputDoneEvent;
2120 HANDLE hInputThread;
2121 uint8_t win_stdio_buf;
2122 } WinStdioCharState;
2123
2124 #define NSENDBUF 2048
2125 #define NRECVBUF 2048
2126 #define MAXCONNECT 1
2127 #define NTIMEOUT 5000
2128
2129 static int win_chr_poll(void *opaque);
2130 static int win_chr_pipe_poll(void *opaque);
2131
2132 static void win_chr_free(CharDriverState *chr)
2133 {
2134 WinCharState *s = chr->opaque;
2135
2136 if (s->hsend) {
2137 CloseHandle(s->hsend);
2138 s->hsend = NULL;
2139 }
2140 if (s->hrecv) {
2141 CloseHandle(s->hrecv);
2142 s->hrecv = NULL;
2143 }
2144 if (s->hcom) {
2145 CloseHandle(s->hcom);
2146 s->hcom = NULL;
2147 }
2148 if (s->fpipe)
2149 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2150 else
2151 qemu_del_polling_cb(win_chr_poll, chr);
2152
2153 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2154 }
2155
2156 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
2157 {
2158 WinCharState *s = chr->opaque;
2159 COMMCONFIG comcfg;
2160 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2161 COMSTAT comstat;
2162 DWORD size;
2163 DWORD err;
2164
2165 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2166 if (!s->hsend) {
2167 error_setg(errp, "Failed CreateEvent");
2168 goto fail;
2169 }
2170 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2171 if (!s->hrecv) {
2172 error_setg(errp, "Failed CreateEvent");
2173 goto fail;
2174 }
2175
2176 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2177 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2178 if (s->hcom == INVALID_HANDLE_VALUE) {
2179 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
2180 s->hcom = NULL;
2181 goto fail;
2182 }
2183
2184 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2185 error_setg(errp, "Failed SetupComm");
2186 goto fail;
2187 }
2188
2189 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2190 size = sizeof(COMMCONFIG);
2191 GetDefaultCommConfig(filename, &comcfg, &size);
2192 comcfg.dcb.DCBlength = sizeof(DCB);
2193 CommConfigDialog(filename, NULL, &comcfg);
2194
2195 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2196 error_setg(errp, "Failed SetCommState");
2197 goto fail;
2198 }
2199
2200 if (!SetCommMask(s->hcom, EV_ERR)) {
2201 error_setg(errp, "Failed SetCommMask");
2202 goto fail;
2203 }
2204
2205 cto.ReadIntervalTimeout = MAXDWORD;
2206 if (!SetCommTimeouts(s->hcom, &cto)) {
2207 error_setg(errp, "Failed SetCommTimeouts");
2208 goto fail;
2209 }
2210
2211 if (!ClearCommError(s->hcom, &err, &comstat)) {
2212 error_setg(errp, "Failed ClearCommError");
2213 goto fail;
2214 }
2215 qemu_add_polling_cb(win_chr_poll, chr);
2216 return 0;
2217
2218 fail:
2219 win_chr_free(chr);
2220 return -1;
2221 }
2222
2223 /* Called with chr_write_lock held. */
2224 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2225 {
2226 WinCharState *s = chr->opaque;
2227 DWORD len, ret, size, err;
2228
2229 len = len1;
2230 ZeroMemory(&s->osend, sizeof(s->osend));
2231 s->osend.hEvent = s->hsend;
2232 while (len > 0) {
2233 if (s->hsend)
2234 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2235 else
2236 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2237 if (!ret) {
2238 err = GetLastError();
2239 if (err == ERROR_IO_PENDING) {
2240 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2241 if (ret) {
2242 buf += size;
2243 len -= size;
2244 } else {
2245 break;
2246 }
2247 } else {
2248 break;
2249 }
2250 } else {
2251 buf += size;
2252 len -= size;
2253 }
2254 }
2255 return len1 - len;
2256 }
2257
2258 static int win_chr_read_poll(CharDriverState *chr)
2259 {
2260 WinCharState *s = chr->opaque;
2261
2262 s->max_size = qemu_chr_be_can_write(chr);
2263 return s->max_size;
2264 }
2265
2266 static void win_chr_readfile(CharDriverState *chr)
2267 {
2268 WinCharState *s = chr->opaque;
2269 int ret, err;
2270 uint8_t buf[READ_BUF_LEN];
2271 DWORD size;
2272
2273 ZeroMemory(&s->orecv, sizeof(s->orecv));
2274 s->orecv.hEvent = s->hrecv;
2275 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2276 if (!ret) {
2277 err = GetLastError();
2278 if (err == ERROR_IO_PENDING) {
2279 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2280 }
2281 }
2282
2283 if (size > 0) {
2284 qemu_chr_be_write(chr, buf, size);
2285 }
2286 }
2287
2288 static void win_chr_read(CharDriverState *chr)
2289 {
2290 WinCharState *s = chr->opaque;
2291
2292 if (s->len > s->max_size)
2293 s->len = s->max_size;
2294 if (s->len == 0)
2295 return;
2296
2297 win_chr_readfile(chr);
2298 }
2299
2300 static int win_chr_poll(void *opaque)
2301 {
2302 CharDriverState *chr = opaque;
2303 WinCharState *s = chr->opaque;
2304 COMSTAT status;
2305 DWORD comerr;
2306
2307 ClearCommError(s->hcom, &comerr, &status);
2308 if (status.cbInQue > 0) {
2309 s->len = status.cbInQue;
2310 win_chr_read_poll(chr);
2311 win_chr_read(chr);
2312 return 1;
2313 }
2314 return 0;
2315 }
2316
2317 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2318 ChardevCommon *backend,
2319 Error **errp)
2320 {
2321 CharDriverState *chr;
2322 WinCharState *s;
2323
2324 chr = qemu_chr_alloc(backend, errp);
2325 if (!chr) {
2326 return NULL;
2327 }
2328 s = g_new0(WinCharState, 1);
2329 chr->opaque = s;
2330 chr->chr_write = win_chr_write;
2331 chr->chr_free = win_chr_free;
2332
2333 if (win_chr_init(chr, filename, errp) < 0) {
2334 g_free(s);
2335 qemu_chr_free_common(chr);
2336 return NULL;
2337 }
2338 return chr;
2339 }
2340
2341 static int win_chr_pipe_poll(void *opaque)
2342 {
2343 CharDriverState *chr = opaque;
2344 WinCharState *s = chr->opaque;
2345 DWORD size;
2346
2347 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2348 if (size > 0) {
2349 s->len = size;
2350 win_chr_read_poll(chr);
2351 win_chr_read(chr);
2352 return 1;
2353 }
2354 return 0;
2355 }
2356
2357 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2358 Error **errp)
2359 {
2360 WinCharState *s = chr->opaque;
2361 OVERLAPPED ov;
2362 int ret;
2363 DWORD size;
2364 char *openname;
2365
2366 s->fpipe = TRUE;
2367
2368 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2369 if (!s->hsend) {
2370 error_setg(errp, "Failed CreateEvent");
2371 goto fail;
2372 }
2373 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2374 if (!s->hrecv) {
2375 error_setg(errp, "Failed CreateEvent");
2376 goto fail;
2377 }
2378
2379 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2380 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2381 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2382 PIPE_WAIT,
2383 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2384 g_free(openname);
2385 if (s->hcom == INVALID_HANDLE_VALUE) {
2386 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2387 s->hcom = NULL;
2388 goto fail;
2389 }
2390
2391 ZeroMemory(&ov, sizeof(ov));
2392 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2393 ret = ConnectNamedPipe(s->hcom, &ov);
2394 if (ret) {
2395 error_setg(errp, "Failed ConnectNamedPipe");
2396 goto fail;
2397 }
2398
2399 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2400 if (!ret) {
2401 error_setg(errp, "Failed GetOverlappedResult");
2402 if (ov.hEvent) {
2403 CloseHandle(ov.hEvent);
2404 ov.hEvent = NULL;
2405 }
2406 goto fail;
2407 }
2408
2409 if (ov.hEvent) {
2410 CloseHandle(ov.hEvent);
2411 ov.hEvent = NULL;
2412 }
2413 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2414 return 0;
2415
2416 fail:
2417 win_chr_free(chr);
2418 return -1;
2419 }
2420
2421
2422 static CharDriverState *qemu_chr_open_pipe(const char *id,
2423 ChardevBackend *backend,
2424 ChardevReturn *ret,
2425 bool *be_opened,
2426 Error **errp)
2427 {
2428 ChardevHostdev *opts = backend->u.pipe.data;
2429 const char *filename = opts->device;
2430 CharDriverState *chr;
2431 WinCharState *s;
2432 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2433
2434 chr = qemu_chr_alloc(common, errp);
2435 if (!chr) {
2436 return NULL;
2437 }
2438 s = g_new0(WinCharState, 1);
2439 chr->opaque = s;
2440 chr->chr_write = win_chr_write;
2441 chr->chr_free = win_chr_free;
2442
2443 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2444 g_free(s);
2445 qemu_chr_free_common(chr);
2446 return NULL;
2447 }
2448 return chr;
2449 }
2450
2451 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2452 ChardevCommon *backend,
2453 Error **errp)
2454 {
2455 CharDriverState *chr;
2456 WinCharState *s;
2457
2458 chr = qemu_chr_alloc(backend, errp);
2459 if (!chr) {
2460 return NULL;
2461 }
2462 s = g_new0(WinCharState, 1);
2463 s->hcom = fd_out;
2464 chr->opaque = s;
2465 chr->chr_write = win_chr_write;
2466 return chr;
2467 }
2468
2469 static CharDriverState *qemu_chr_open_win_con(const char *id,
2470 ChardevBackend *backend,
2471 ChardevReturn *ret,
2472 bool *be_opened,
2473 Error **errp)
2474 {
2475 ChardevCommon *common = backend->u.console.data;
2476 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2477 common, errp);
2478 }
2479
2480 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2481 {
2482 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2483 DWORD dwSize;
2484 int len1;
2485
2486 len1 = len;
2487
2488 while (len1 > 0) {
2489 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2490 break;
2491 }
2492 buf += dwSize;
2493 len1 -= dwSize;
2494 }
2495
2496 return len - len1;
2497 }
2498
2499 static void win_stdio_wait_func(void *opaque)
2500 {
2501 CharDriverState *chr = opaque;
2502 WinStdioCharState *stdio = chr->opaque;
2503 INPUT_RECORD buf[4];
2504 int ret;
2505 DWORD dwSize;
2506 int i;
2507
2508 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2509
2510 if (!ret) {
2511 /* Avoid error storm */
2512 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2513 return;
2514 }
2515
2516 for (i = 0; i < dwSize; i++) {
2517 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2518
2519 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2520 int j;
2521 if (kev->uChar.AsciiChar != 0) {
2522 for (j = 0; j < kev->wRepeatCount; j++) {
2523 if (qemu_chr_be_can_write(chr)) {
2524 uint8_t c = kev->uChar.AsciiChar;
2525 qemu_chr_be_write(chr, &c, 1);
2526 }
2527 }
2528 }
2529 }
2530 }
2531 }
2532
2533 static DWORD WINAPI win_stdio_thread(LPVOID param)
2534 {
2535 CharDriverState *chr = param;
2536 WinStdioCharState *stdio = chr->opaque;
2537 int ret;
2538 DWORD dwSize;
2539
2540 while (1) {
2541
2542 /* Wait for one byte */
2543 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2544
2545 /* Exit in case of error, continue if nothing read */
2546 if (!ret) {
2547 break;
2548 }
2549 if (!dwSize) {
2550 continue;
2551 }
2552
2553 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2554 if (stdio->win_stdio_buf == '\r') {
2555 continue;
2556 }
2557
2558 /* Signal the main thread and wait until the byte was eaten */
2559 if (!SetEvent(stdio->hInputReadyEvent)) {
2560 break;
2561 }
2562 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2563 != WAIT_OBJECT_0) {
2564 break;
2565 }
2566 }
2567
2568 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2569 return 0;
2570 }
2571
2572 static void win_stdio_thread_wait_func(void *opaque)
2573 {
2574 CharDriverState *chr = opaque;
2575 WinStdioCharState *stdio = chr->opaque;
2576
2577 if (qemu_chr_be_can_write(chr)) {
2578 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2579 }
2580
2581 SetEvent(stdio->hInputDoneEvent);
2582 }
2583
2584 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2585 {
2586 WinStdioCharState *stdio = chr->opaque;
2587 DWORD dwMode = 0;
2588
2589 GetConsoleMode(stdio->hStdIn, &dwMode);
2590
2591 if (echo) {
2592 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2593 } else {
2594 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2595 }
2596 }
2597
2598 static void win_stdio_free(CharDriverState *chr)
2599 {
2600 WinStdioCharState *stdio = chr->opaque;
2601
2602 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2603 CloseHandle(stdio->hInputReadyEvent);
2604 }
2605 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2606 CloseHandle(stdio->hInputDoneEvent);
2607 }
2608 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2609 TerminateThread(stdio->hInputThread, 0);
2610 }
2611
2612 g_free(chr->opaque);
2613 }
2614
2615 static CharDriverState *qemu_chr_open_stdio(const char *id,
2616 ChardevBackend *backend,
2617 ChardevReturn *ret,
2618 bool *be_opened,
2619 Error **errp)
2620 {
2621 CharDriverState *chr;
2622 WinStdioCharState *stdio;
2623 DWORD dwMode;
2624 int is_console = 0;
2625 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio.data);
2626
2627 chr = qemu_chr_alloc(common, errp);
2628 if (!chr) {
2629 return NULL;
2630 }
2631 stdio = g_new0(WinStdioCharState, 1);
2632
2633 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2634 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2635 error_setg(errp, "cannot open stdio: invalid handle");
2636 return NULL;
2637 }
2638
2639 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2640
2641 chr->opaque = stdio;
2642 chr->chr_write = win_stdio_write;
2643 chr->chr_free = win_stdio_free;
2644
2645 if (is_console) {
2646 if (qemu_add_wait_object(stdio->hStdIn,
2647 win_stdio_wait_func, chr)) {
2648 error_setg(errp, "qemu_add_wait_object: failed");
2649 goto err1;
2650 }
2651 } else {
2652 DWORD dwId;
2653
2654 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2655 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2656 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2657 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2658 error_setg(errp, "cannot create event");
2659 goto err2;
2660 }
2661 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2662 win_stdio_thread_wait_func, chr)) {
2663 error_setg(errp, "qemu_add_wait_object: failed");
2664 goto err2;
2665 }
2666 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2667 chr, 0, &dwId);
2668
2669 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2670 error_setg(errp, "cannot create stdio thread");
2671 goto err3;
2672 }
2673 }
2674
2675 dwMode |= ENABLE_LINE_INPUT;
2676
2677 if (is_console) {
2678 /* set the terminal in raw mode */
2679 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2680 dwMode |= ENABLE_PROCESSED_INPUT;
2681 }
2682
2683 SetConsoleMode(stdio->hStdIn, dwMode);
2684
2685 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2686 qemu_chr_set_echo_win_stdio(chr, false);
2687
2688 return chr;
2689
2690 err3:
2691 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2692 err2:
2693 CloseHandle(stdio->hInputReadyEvent);
2694 CloseHandle(stdio->hInputDoneEvent);
2695 err1:
2696 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2697 return NULL;
2698 }
2699 #endif /* !_WIN32 */
2700
2701 /***********************************************************/
2702 /* UDP Net console */
2703
2704 typedef struct {
2705 QIOChannel *ioc;
2706 uint8_t buf[READ_BUF_LEN];
2707 int bufcnt;
2708 int bufptr;
2709 int max_size;
2710 } NetCharDriver;
2711
2712 /* Called with chr_write_lock held. */
2713 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2714 {
2715 NetCharDriver *s = chr->opaque;
2716
2717 return qio_channel_write(
2718 s->ioc, (const char *)buf, len, NULL);
2719 }
2720
2721 static int udp_chr_read_poll(void *opaque)
2722 {
2723 CharDriverState *chr = opaque;
2724 NetCharDriver *s = chr->opaque;
2725
2726 s->max_size = qemu_chr_be_can_write(chr);
2727
2728 /* If there were any stray characters in the queue process them
2729 * first
2730 */
2731 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2732 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2733 s->bufptr++;
2734 s->max_size = qemu_chr_be_can_write(chr);
2735 }
2736 return s->max_size;
2737 }
2738
2739 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2740 {
2741 CharDriverState *chr = opaque;
2742 NetCharDriver *s = chr->opaque;
2743 ssize_t ret;
2744
2745 if (s->max_size == 0) {
2746 return TRUE;
2747 }
2748 ret = qio_channel_read(
2749 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2750 if (ret <= 0) {
2751 remove_fd_in_watch(chr);
2752 return FALSE;
2753 }
2754 s->bufcnt = ret;
2755
2756 s->bufptr = 0;
2757 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2758 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2759 s->bufptr++;
2760 s->max_size = qemu_chr_be_can_write(chr);
2761 }
2762
2763 return TRUE;
2764 }
2765
2766 static void udp_chr_update_read_handler(CharDriverState *chr,
2767 GMainContext *context)
2768 {
2769 NetCharDriver *s = chr->opaque;
2770
2771 remove_fd_in_watch(chr);
2772 if (s->ioc) {
2773 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
2774 udp_chr_read_poll,
2775 udp_chr_read, chr,
2776 context);
2777 }
2778 }
2779
2780 static void udp_chr_free(CharDriverState *chr)
2781 {
2782 NetCharDriver *s = chr->opaque;
2783
2784 remove_fd_in_watch(chr);
2785 if (s->ioc) {
2786 object_unref(OBJECT(s->ioc));
2787 }
2788 g_free(s);
2789 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2790 }
2791
2792 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2793 ChardevCommon *backend,
2794 bool *be_opened,
2795 Error **errp)
2796 {
2797 CharDriverState *chr = NULL;
2798 NetCharDriver *s = NULL;
2799
2800 chr = qemu_chr_alloc(backend, errp);
2801 if (!chr) {
2802 return NULL;
2803 }
2804 s = g_new0(NetCharDriver, 1);
2805
2806 s->ioc = QIO_CHANNEL(sioc);
2807 s->bufcnt = 0;
2808 s->bufptr = 0;
2809 chr->opaque = s;
2810 chr->chr_write = udp_chr_write;
2811 chr->chr_update_read_handler = udp_chr_update_read_handler;
2812 chr->chr_free = udp_chr_free;
2813 /* be isn't opened until we get a connection */
2814 *be_opened = false;
2815 return chr;
2816 }
2817
2818 /***********************************************************/
2819 /* TCP Net console */
2820
2821 typedef struct {
2822 QIOChannel *ioc; /* Client I/O channel */
2823 QIOChannelSocket *sioc; /* Client master channel */
2824 QIOChannelSocket *listen_ioc;
2825 guint listen_tag;
2826 QCryptoTLSCreds *tls_creds;
2827 int connected;
2828 int max_size;
2829 int do_telnetopt;
2830 int do_nodelay;
2831 int is_unix;
2832 int *read_msgfds;
2833 size_t read_msgfds_num;
2834 int *write_msgfds;
2835 size_t write_msgfds_num;
2836
2837 SocketAddress *addr;
2838 bool is_listen;
2839 bool is_telnet;
2840
2841 guint reconnect_timer;
2842 int64_t reconnect_time;
2843 bool connect_err_reported;
2844 } TCPCharDriver;
2845
2846 static gboolean socket_reconnect_timeout(gpointer opaque);
2847
2848 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2849 {
2850 TCPCharDriver *s = chr->opaque;
2851 char *name;
2852 assert(s->connected == 0);
2853 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2854 socket_reconnect_timeout, chr);
2855 name = g_strdup_printf("chardev-socket-reconnect-%s", chr->label);
2856 g_source_set_name_by_id(s->reconnect_timer, name);
2857 g_free(name);
2858 }
2859
2860 static void check_report_connect_error(CharDriverState *chr,
2861 Error *err)
2862 {
2863 TCPCharDriver *s = chr->opaque;
2864
2865 if (!s->connect_err_reported) {
2866 error_report("Unable to connect character device %s: %s",
2867 chr->label, error_get_pretty(err));
2868 s->connect_err_reported = true;
2869 }
2870 qemu_chr_socket_restart_timer(chr);
2871 }
2872
2873 static gboolean tcp_chr_accept(QIOChannel *chan,
2874 GIOCondition cond,
2875 void *opaque);
2876
2877 /* Called with chr_write_lock held. */
2878 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2879 {
2880 TCPCharDriver *s = chr->opaque;
2881 if (s->connected) {
2882 int ret = io_channel_send_full(s->ioc, buf, len,
2883 s->write_msgfds,
2884 s->write_msgfds_num);
2885
2886 /* free the written msgfds, no matter what */
2887 if (s->write_msgfds_num) {
2888 g_free(s->write_msgfds);
2889 s->write_msgfds = 0;
2890 s->write_msgfds_num = 0;
2891 }
2892
2893 return ret;
2894 } else {
2895 /* XXX: indicate an error ? */
2896 return len;
2897 }
2898 }
2899
2900 static int tcp_chr_read_poll(void *opaque)
2901 {
2902 CharDriverState *chr = opaque;
2903 TCPCharDriver *s = chr->opaque;
2904 if (!s->connected)
2905 return 0;
2906 s->max_size = qemu_chr_be_can_write(chr);
2907 return s->max_size;
2908 }
2909
2910 #define IAC 255
2911 #define IAC_BREAK 243
2912 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2913 TCPCharDriver *s,
2914 uint8_t *buf, int *size)
2915 {
2916 /* Handle any telnet client's basic IAC options to satisfy char by
2917 * char mode with no echo. All IAC options will be removed from
2918 * the buf and the do_telnetopt variable will be used to track the
2919 * state of the width of the IAC information.
2920 *
2921 * IAC commands come in sets of 3 bytes with the exception of the
2922 * "IAC BREAK" command and the double IAC.
2923 */
2924
2925 int i;
2926 int j = 0;
2927
2928 for (i = 0; i < *size; i++) {
2929 if (s->do_telnetopt > 1) {
2930 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2931 /* Double IAC means send an IAC */
2932 if (j != i)
2933 buf[j] = buf[i];
2934 j++;
2935 s->do_telnetopt = 1;
2936 } else {
2937 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2938 /* Handle IAC break commands by sending a serial break */
2939 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2940 s->do_telnetopt++;
2941 }
2942 s->do_telnetopt++;
2943 }
2944 if (s->do_telnetopt >= 4) {
2945 s->do_telnetopt = 1;
2946 }
2947 } else {
2948 if ((unsigned char)buf[i] == IAC) {
2949 s->do_telnetopt = 2;
2950 } else {
2951 if (j != i)
2952 buf[j] = buf[i];
2953 j++;
2954 }
2955 }
2956 }
2957 *size = j;
2958 }
2959
2960 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2961 {
2962 TCPCharDriver *s = chr->opaque;
2963 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2964
2965 assert(num <= TCP_MAX_FDS);
2966
2967 if (to_copy) {
2968 int i;
2969
2970 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2971
2972 /* Close unused fds */
2973 for (i = to_copy; i < s->read_msgfds_num; i++) {
2974 close(s->read_msgfds[i]);
2975 }
2976
2977 g_free(s->read_msgfds);
2978 s->read_msgfds = 0;
2979 s->read_msgfds_num = 0;
2980 }
2981
2982 return to_copy;
2983 }
2984
2985 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2986 {
2987 TCPCharDriver *s = chr->opaque;
2988
2989 /* clear old pending fd array */
2990 g_free(s->write_msgfds);
2991 s->write_msgfds = NULL;
2992 s->write_msgfds_num = 0;
2993
2994 if (!s->connected ||
2995 !qio_channel_has_feature(s->ioc,
2996 QIO_CHANNEL_FEATURE_FD_PASS)) {
2997 return -1;
2998 }
2999
3000 if (num) {
3001 s->write_msgfds = g_new(int, num);
3002 memcpy(s->write_msgfds, fds, num * sizeof(int));
3003 }
3004
3005 s->write_msgfds_num = num;
3006
3007 return 0;
3008 }
3009
3010 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
3011 {
3012 TCPCharDriver *s = chr->opaque;
3013 struct iovec iov = { .iov_base = buf, .iov_len = len };
3014 int ret;
3015 size_t i;
3016 int *msgfds = NULL;
3017 size_t msgfds_num = 0;
3018
3019 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
3020 ret = qio_channel_readv_full(s->ioc, &iov, 1,
3021 &msgfds, &msgfds_num,
3022 NULL);
3023 } else {
3024 ret = qio_channel_readv_full(s->ioc, &iov, 1,
3025 NULL, NULL,
3026 NULL);
3027 }
3028
3029 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3030 errno = EAGAIN;
3031 ret = -1;
3032 } else if (ret == -1) {
3033 errno = EIO;
3034 }
3035
3036 if (msgfds_num) {
3037 /* close and clean read_msgfds */
3038 for (i = 0; i < s->read_msgfds_num; i++) {
3039 close(s->read_msgfds[i]);
3040 }
3041
3042 if (s->read_msgfds_num) {
3043 g_free(s->read_msgfds);
3044 }
3045
3046 s->read_msgfds = msgfds;
3047 s->read_msgfds_num = msgfds_num;
3048 }
3049
3050 for (i = 0; i < s->read_msgfds_num; i++) {
3051 int fd = s->read_msgfds[i];
3052 if (fd < 0) {
3053 continue;
3054 }
3055
3056 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
3057 qemu_set_block(fd);
3058
3059 #ifndef MSG_CMSG_CLOEXEC
3060 qemu_set_cloexec(fd);
3061 #endif
3062 }
3063
3064 return ret;
3065 }
3066
3067 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
3068 {
3069 TCPCharDriver *s = chr->opaque;
3070 return qio_channel_create_watch(s->ioc, cond);
3071 }
3072
3073 static void tcp_chr_free_connection(CharDriverState *chr)
3074 {
3075 TCPCharDriver *s = chr->opaque;
3076 int i;
3077
3078 if (!s->connected) {
3079 return;
3080 }
3081
3082 if (s->read_msgfds_num) {
3083 for (i = 0; i < s->read_msgfds_num; i++) {
3084 close(s->read_msgfds[i]);
3085 }
3086 g_free(s->read_msgfds);
3087 s->read_msgfds = NULL;
3088 s->read_msgfds_num = 0;
3089 }
3090
3091 tcp_set_msgfds(chr, NULL, 0);
3092 remove_fd_in_watch(chr);
3093 object_unref(OBJECT(s->sioc));
3094 s->sioc = NULL;
3095 object_unref(OBJECT(s->ioc));
3096 s->ioc = NULL;
3097 g_free(chr->filename);
3098 chr->filename = NULL;
3099 s->connected = 0;
3100 }
3101
3102 static void tcp_chr_disconnect(CharDriverState *chr)
3103 {
3104 TCPCharDriver *s = chr->opaque;
3105
3106 if (!s->connected) {
3107 return;
3108 }
3109
3110 tcp_chr_free_connection(chr);
3111
3112 if (s->listen_ioc) {
3113 s->listen_tag = qio_channel_add_watch(
3114 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
3115 }
3116 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
3117 s->is_listen, s->is_telnet);
3118 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3119 if (s->reconnect_time) {
3120 qemu_chr_socket_restart_timer(chr);
3121 }
3122 }
3123
3124 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
3125 {
3126 CharDriverState *chr = opaque;
3127 TCPCharDriver *s = chr->opaque;
3128 uint8_t buf[READ_BUF_LEN];
3129 int len, size;
3130
3131 if (!s->connected || s->max_size <= 0) {
3132 return TRUE;
3133 }
3134 len = sizeof(buf);
3135 if (len > s->max_size)
3136 len = s->max_size;
3137 size = tcp_chr_recv(chr, (void *)buf, len);
3138 if (size == 0 || size == -1) {
3139 /* connection closed */
3140 tcp_chr_disconnect(chr);
3141 } else if (size > 0) {
3142 if (s->do_telnetopt)
3143 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3144 if (size > 0)
3145 qemu_chr_be_write(chr, buf, size);
3146 }
3147
3148 return TRUE;
3149 }
3150
3151 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
3152 {
3153 TCPCharDriver *s = chr->opaque;
3154 int size;
3155
3156 if (!s->connected) {
3157 return 0;
3158 }
3159
3160 size = tcp_chr_recv(chr, (void *) buf, len);
3161 if (size == 0) {
3162 /* connection closed */
3163 tcp_chr_disconnect(chr);
3164 }
3165
3166 return size;
3167 }
3168
3169 static void tcp_chr_connect(void *opaque)
3170 {
3171 CharDriverState *chr = opaque;
3172 TCPCharDriver *s = chr->opaque;
3173
3174 g_free(chr->filename);
3175 chr->filename = sockaddr_to_str(
3176 &s->sioc->localAddr, s->sioc->localAddrLen,
3177 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
3178 s->is_listen, s->is_telnet);
3179
3180 s->connected = 1;
3181 if (s->ioc) {
3182 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
3183 tcp_chr_read_poll,
3184 tcp_chr_read,
3185 chr, NULL);
3186 }
3187 qemu_chr_be_generic_open(chr);
3188 }
3189
3190 static void tcp_chr_update_read_handler(CharDriverState *chr,
3191 GMainContext *context)
3192 {
3193 TCPCharDriver *s = chr->opaque;
3194
3195 if (!s->connected) {
3196 return;
3197 }
3198
3199 remove_fd_in_watch(chr);
3200 if (s->ioc) {
3201 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
3202 tcp_chr_read_poll,
3203 tcp_chr_read, chr,
3204 context);
3205 }
3206 }
3207
3208 typedef struct {
3209 CharDriverState *chr;
3210 char buf[12];
3211 size_t buflen;
3212 } TCPCharDriverTelnetInit;
3213
3214 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
3215 GIOCondition cond G_GNUC_UNUSED,
3216 gpointer user_data)
3217 {
3218 TCPCharDriverTelnetInit *init = user_data;
3219 ssize_t ret;
3220
3221 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
3222 if (ret < 0) {
3223 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3224 ret = 0;
3225 } else {
3226 tcp_chr_disconnect(init->chr);
3227 return FALSE;
3228 }
3229 }
3230 init->buflen -= ret;
3231
3232 if (init->buflen == 0) {
3233 tcp_chr_connect(init->chr);
3234 return FALSE;
3235 }
3236
3237 memmove(init->buf, init->buf + ret, init->buflen);
3238
3239 return TRUE;
3240 }
3241
3242 static void tcp_chr_telnet_init(CharDriverState *chr)
3243 {
3244 TCPCharDriver *s = chr->opaque;
3245 TCPCharDriverTelnetInit *init =
3246 g_new0(TCPCharDriverTelnetInit, 1);
3247 size_t n = 0;
3248
3249 init->chr = chr;
3250 init->buflen = 12;
3251
3252 #define IACSET(x, a, b, c) \
3253 do { \
3254 x[n++] = a; \
3255 x[n++] = b; \
3256 x[n++] = c; \
3257 } while (0)
3258
3259 /* Prep the telnet negotion to put telnet in binary,
3260 * no echo, single char mode */
3261 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3262 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3263 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3264 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3265
3266 #undef IACSET
3267
3268 qio_channel_add_watch(
3269 s->ioc, G_IO_OUT,
3270 tcp_chr_telnet_init_io,
3271 init, NULL);
3272 }
3273
3274
3275 static void tcp_chr_tls_handshake(Object *source,
3276 Error *err,
3277 gpointer user_data)
3278 {
3279 CharDriverState *chr = user_data;
3280 TCPCharDriver *s = chr->opaque;
3281
3282 if (err) {
3283 tcp_chr_disconnect(chr);
3284 } else {
3285 if (s->do_telnetopt) {
3286 tcp_chr_telnet_init(chr);
3287 } else {
3288 tcp_chr_connect(chr);
3289 }
3290 }
3291 }
3292
3293
3294 static void tcp_chr_tls_init(CharDriverState *chr)
3295 {
3296 TCPCharDriver *s = chr->opaque;
3297 QIOChannelTLS *tioc;
3298 Error *err = NULL;
3299 gchar *name;
3300
3301 if (s->is_listen) {
3302 tioc = qio_channel_tls_new_server(
3303 s->ioc, s->tls_creds,
3304 NULL, /* XXX Use an ACL */
3305 &err);
3306 } else {
3307 tioc = qio_channel_tls_new_client(
3308 s->ioc, s->tls_creds,
3309 s->addr->u.inet.data->host,
3310 &err);
3311 }
3312 if (tioc == NULL) {
3313 error_free(err);
3314 tcp_chr_disconnect(chr);
3315 return;
3316 }
3317 name = g_strdup_printf("chardev-tls-%s-%s",
3318 s->is_listen ? "server" : "client",
3319 chr->label);
3320 qio_channel_set_name(QIO_CHANNEL(tioc), name);
3321 g_free(name);
3322 object_unref(OBJECT(s->ioc));
3323 s->ioc = QIO_CHANNEL(tioc);
3324
3325 qio_channel_tls_handshake(tioc,
3326 tcp_chr_tls_handshake,
3327 chr,
3328 NULL);
3329 }
3330
3331
3332 static void tcp_chr_set_client_ioc_name(CharDriverState *chr,
3333 QIOChannelSocket *sioc)
3334 {
3335 TCPCharDriver *s = chr->opaque;
3336 char *name;
3337 name = g_strdup_printf("chardev-tcp-%s-%s",
3338 s->is_listen ? "server" : "client",
3339 chr->label);
3340 qio_channel_set_name(QIO_CHANNEL(sioc), name);
3341 g_free(name);
3342
3343 }
3344
3345 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3346 {
3347 TCPCharDriver *s = chr->opaque;
3348 if (s->ioc != NULL) {
3349 return -1;
3350 }
3351
3352 s->ioc = QIO_CHANNEL(sioc);
3353 object_ref(OBJECT(sioc));
3354 s->sioc = sioc;
3355 object_ref(OBJECT(sioc));
3356
3357 qio_channel_set_blocking(s->ioc, false, NULL);
3358
3359 if (s->do_nodelay) {
3360 qio_channel_set_delay(s->ioc, false);
3361 }
3362 if (s->listen_tag) {
3363 g_source_remove(s->listen_tag);
3364 s->listen_tag = 0;
3365 }
3366
3367 if (s->tls_creds) {
3368 tcp_chr_tls_init(chr);
3369 } else {
3370 if (s->do_telnetopt) {
3371 tcp_chr_telnet_init(chr);
3372 } else {
3373 tcp_chr_connect(chr);
3374 }
3375 }
3376
3377 return 0;
3378 }
3379
3380
3381 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3382 {
3383 int ret;
3384 QIOChannelSocket *sioc;
3385
3386 sioc = qio_channel_socket_new_fd(fd, NULL);
3387 if (!sioc) {
3388 return -1;
3389 }
3390 tcp_chr_set_client_ioc_name(chr, sioc);
3391 ret = tcp_chr_new_client(chr, sioc);
3392 object_unref(OBJECT(sioc));
3393 return ret;
3394 }
3395
3396 static gboolean tcp_chr_accept(QIOChannel *channel,
3397 GIOCondition cond,
3398 void *opaque)
3399 {
3400 CharDriverState *chr = opaque;
3401 QIOChannelSocket *sioc;
3402
3403 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3404 NULL);
3405 if (!sioc) {
3406 return TRUE;
3407 }
3408
3409 tcp_chr_new_client(chr, sioc);
3410
3411 object_unref(OBJECT(sioc));
3412
3413 return TRUE;
3414 }
3415
3416 static int tcp_chr_wait_connected(CharDriverState *chr, Error **errp)
3417 {
3418 TCPCharDriver *s = chr->opaque;
3419 QIOChannelSocket *sioc;
3420
3421 /* It can't wait on s->connected, since it is set asynchronously
3422 * in TLS and telnet cases, only wait for an accepted socket */
3423 while (!s->ioc) {
3424 if (s->is_listen) {
3425 fprintf(stderr, "QEMU waiting for connection on: %s\n",
3426 chr->filename);
3427 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), true, NULL);
3428 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
3429 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
3430 } else {
3431 sioc = qio_channel_socket_new();
3432 tcp_chr_set_client_ioc_name(chr, sioc);
3433 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3434 object_unref(OBJECT(sioc));
3435 return -1;
3436 }
3437 tcp_chr_new_client(chr, sioc);
3438 object_unref(OBJECT(sioc));
3439 }
3440 }
3441
3442 return 0;
3443 }
3444
3445 static int qemu_chr_wait_connected(CharDriverState *chr, Error **errp)
3446 {
3447 if (chr->chr_wait_connected) {
3448 return chr->chr_wait_connected(chr, errp);
3449 }
3450
3451 return 0;
3452 }
3453
3454 int qemu_chr_fe_wait_connected(CharBackend *be, Error **errp)
3455 {
3456 if (!be->chr) {
3457 error_setg(errp, "missing associated backend");
3458 return -1;
3459 }
3460
3461 return qemu_chr_wait_connected(be->chr, errp);
3462 }
3463
3464 static void tcp_chr_free(CharDriverState *chr)
3465 {
3466 TCPCharDriver *s = chr->opaque;
3467
3468 tcp_chr_free_connection(chr);
3469
3470 if (s->reconnect_timer) {
3471 g_source_remove(s->reconnect_timer);
3472 s->reconnect_timer = 0;
3473 }
3474 qapi_free_SocketAddress(s->addr);
3475 if (s->listen_tag) {
3476 g_source_remove(s->listen_tag);
3477 s->listen_tag = 0;
3478