Merge remote-tracking branch 'remotes/bonzini/tags/for-upstream' into staging
[qemu/ar7.git] / qemu-char.c
blobfb456cec345b10b12a051d44067cce29cb1bdf44
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
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"
44 #include <zlib.h>
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
85 #include "qemu/sockets.h"
86 #include "ui/qemu-spice.h"
88 #define READ_BUF_LEN 4096
89 #define READ_RETRIES 10
90 #define TCP_MAX_FDS 16
92 /***********************************************************/
93 /* Socket address helpers */
95 static char *SocketAddress_to_str(const char *prefix, SocketAddress *addr,
96 bool is_listen, bool is_telnet)
98 switch (addr->type) {
99 case SOCKET_ADDRESS_KIND_INET:
100 return g_strdup_printf("%s%s:%s:%s%s", prefix,
101 is_telnet ? "telnet" : "tcp",
102 addr->u.inet.data->host,
103 addr->u.inet.data->port,
104 is_listen ? ",server" : "");
105 break;
106 case SOCKET_ADDRESS_KIND_UNIX:
107 return g_strdup_printf("%sunix:%s%s", prefix,
108 addr->u.q_unix.data->path,
109 is_listen ? ",server" : "");
110 break;
111 case SOCKET_ADDRESS_KIND_FD:
112 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd.data->str,
113 is_listen ? ",server" : "");
114 break;
115 default:
116 abort();
120 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
121 struct sockaddr_storage *ps, socklen_t ps_len,
122 bool is_listen, bool is_telnet)
124 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
125 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
126 const char *left = "", *right = "";
128 switch (ss->ss_family) {
129 #ifndef _WIN32
130 case AF_UNIX:
131 return g_strdup_printf("unix:%s%s",
132 ((struct sockaddr_un *)(ss))->sun_path,
133 is_listen ? ",server" : "");
134 #endif
135 case AF_INET6:
136 left = "[";
137 right = "]";
138 /* fall through */
139 case AF_INET:
140 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
141 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
142 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
143 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
144 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
145 is_telnet ? "telnet" : "tcp",
146 left, shost, right, sserv,
147 is_listen ? ",server" : "",
148 left, phost, right, pserv);
150 default:
151 return g_strdup_printf("unknown");
155 /***********************************************************/
156 /* character device */
158 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
159 QTAILQ_HEAD_INITIALIZER(chardevs);
161 static void qemu_chr_free_common(CharDriverState *chr);
163 CharDriverState *qemu_chr_alloc(ChardevCommon *backend, Error **errp)
165 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
166 qemu_mutex_init(&chr->chr_write_lock);
168 if (backend->has_logfile) {
169 int flags = O_WRONLY | O_CREAT;
170 if (backend->has_logappend &&
171 backend->logappend) {
172 flags |= O_APPEND;
173 } else {
174 flags |= O_TRUNC;
176 chr->logfd = qemu_open(backend->logfile, flags, 0666);
177 if (chr->logfd < 0) {
178 error_setg_errno(errp, errno,
179 "Unable to open logfile %s",
180 backend->logfile);
181 g_free(chr);
182 return NULL;
184 } else {
185 chr->logfd = -1;
188 return chr;
191 void qemu_chr_be_event(CharDriverState *s, int event)
193 /* Keep track if the char device is open */
194 switch (event) {
195 case CHR_EVENT_OPENED:
196 s->be_open = 1;
197 break;
198 case CHR_EVENT_CLOSED:
199 s->be_open = 0;
200 break;
203 if (!s->chr_event)
204 return;
205 s->chr_event(s->handler_opaque, event);
208 void qemu_chr_be_generic_open(CharDriverState *s)
210 qemu_chr_be_event(s, CHR_EVENT_OPENED);
214 /* Not reporting errors from writing to logfile, as logs are
215 * defined to be "best effort" only */
216 static void qemu_chr_fe_write_log(CharDriverState *s,
217 const uint8_t *buf, size_t len)
219 size_t done = 0;
220 ssize_t ret;
222 if (s->logfd < 0) {
223 return;
226 while (done < len) {
227 retry:
228 ret = write(s->logfd, buf + done, len - done);
229 if (ret == -1 && errno == EAGAIN) {
230 g_usleep(100);
231 goto retry;
234 if (ret <= 0) {
235 return;
237 done += ret;
241 static int qemu_chr_fe_write_buffer(CharDriverState *s, const uint8_t *buf, int len, int *offset)
243 int res = 0;
244 *offset = 0;
246 qemu_mutex_lock(&s->chr_write_lock);
247 while (*offset < len) {
248 retry:
249 res = s->chr_write(s, buf + *offset, len - *offset);
250 if (res < 0 && errno == EAGAIN) {
251 g_usleep(100);
252 goto retry;
255 if (res <= 0) {
256 break;
259 *offset += res;
261 if (*offset > 0) {
262 qemu_chr_fe_write_log(s, buf, *offset);
264 qemu_mutex_unlock(&s->chr_write_lock);
266 return res;
269 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
271 int ret;
273 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
274 int offset;
275 replay_char_write_event_load(&ret, &offset);
276 assert(offset <= len);
277 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
278 return ret;
281 qemu_mutex_lock(&s->chr_write_lock);
282 ret = s->chr_write(s, buf, len);
284 if (ret > 0) {
285 qemu_chr_fe_write_log(s, buf, ret);
288 qemu_mutex_unlock(&s->chr_write_lock);
290 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
291 replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
294 return ret;
297 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
299 int offset;
300 int res;
302 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
303 replay_char_write_event_load(&res, &offset);
304 assert(offset <= len);
305 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
306 return res;
309 res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
311 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
312 replay_char_write_event_save(res, offset);
315 if (res < 0) {
316 return res;
318 return offset;
321 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
323 int offset = 0, counter = 10;
324 int res;
326 if (!s->chr_sync_read) {
327 return 0;
330 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
331 return replay_char_read_all_load(buf);
334 while (offset < len) {
335 retry:
336 res = s->chr_sync_read(s, buf + offset, len - offset);
337 if (res == -1 && errno == EAGAIN) {
338 g_usleep(100);
339 goto retry;
342 if (res == 0) {
343 break;
346 if (res < 0) {
347 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
348 replay_char_read_all_save_error(res);
350 return res;
353 offset += res;
355 if (!counter--) {
356 break;
360 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
361 replay_char_read_all_save_buf(buf, offset);
363 return offset;
366 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
368 int res;
369 if (!s->chr_ioctl || s->replay) {
370 res = -ENOTSUP;
371 } else {
372 res = s->chr_ioctl(s, cmd, arg);
375 return res;
378 int qemu_chr_be_can_write(CharDriverState *s)
380 if (!s->chr_can_read)
381 return 0;
382 return s->chr_can_read(s->handler_opaque);
385 void qemu_chr_be_write_impl(CharDriverState *s, uint8_t *buf, int len)
387 if (s->chr_read) {
388 s->chr_read(s->handler_opaque, buf, len);
392 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
394 if (s->replay) {
395 if (replay_mode == REPLAY_MODE_PLAY) {
396 return;
398 replay_chr_be_write(s, buf, len);
399 } else {
400 qemu_chr_be_write_impl(s, buf, len);
404 int qemu_chr_fe_get_msgfd(CharDriverState *s)
406 int fd;
407 int res = (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
408 if (s->replay) {
409 fprintf(stderr,
410 "Replay: get msgfd is not supported for serial devices yet\n");
411 exit(1);
413 return res;
416 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
418 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
421 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
423 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
426 int qemu_chr_add_client(CharDriverState *s, int fd)
428 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
431 void qemu_chr_accept_input(CharDriverState *s)
433 if (s->chr_accept_input)
434 s->chr_accept_input(s);
435 qemu_notify_event();
438 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
440 char buf[READ_BUF_LEN];
441 va_list ap;
442 va_start(ap, fmt);
443 vsnprintf(buf, sizeof(buf), fmt, ap);
444 /* XXX this blocks entire thread. Rewrite to use
445 * qemu_chr_fe_write and background I/O callbacks */
446 qemu_chr_fe_write_all(s, (uint8_t *)buf, strlen(buf));
447 va_end(ap);
450 static void remove_fd_in_watch(CharDriverState *chr);
452 void qemu_chr_add_handlers_full(CharDriverState *s,
453 IOCanReadHandler *fd_can_read,
454 IOReadHandler *fd_read,
455 IOEventHandler *fd_event,
456 void *opaque,
457 GMainContext *context)
459 int fe_open;
461 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
462 fe_open = 0;
463 remove_fd_in_watch(s);
464 } else {
465 fe_open = 1;
467 s->chr_can_read = fd_can_read;
468 s->chr_read = fd_read;
469 s->chr_event = fd_event;
470 s->handler_opaque = opaque;
471 if (fe_open && s->chr_update_read_handler) {
472 s->chr_update_read_handler(s, context);
475 if (!s->explicit_fe_open) {
476 qemu_chr_fe_set_open(s, fe_open);
479 /* We're connecting to an already opened device, so let's make sure we
480 also get the open event */
481 if (fe_open && s->be_open) {
482 qemu_chr_be_generic_open(s);
486 void qemu_chr_add_handlers(CharDriverState *s,
487 IOCanReadHandler *fd_can_read,
488 IOReadHandler *fd_read,
489 IOEventHandler *fd_event,
490 void *opaque)
492 qemu_chr_add_handlers_full(s, fd_can_read, fd_read,
493 fd_event, opaque, NULL);
496 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
498 return len;
501 static CharDriverState *qemu_chr_open_null(const char *id,
502 ChardevBackend *backend,
503 ChardevReturn *ret,
504 Error **errp)
506 CharDriverState *chr;
507 ChardevCommon *common = backend->u.null.data;
509 chr = qemu_chr_alloc(common, errp);
510 if (!chr) {
511 return NULL;
513 chr->chr_write = null_chr_write;
514 chr->explicit_be_open = true;
515 return chr;
518 /* MUX driver for serial I/O splitting */
519 #define MAX_MUX 4
520 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
521 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
522 typedef struct {
523 IOCanReadHandler *chr_can_read[MAX_MUX];
524 IOReadHandler *chr_read[MAX_MUX];
525 IOEventHandler *chr_event[MAX_MUX];
526 void *ext_opaque[MAX_MUX];
527 CharDriverState *drv;
528 int focus;
529 int mux_cnt;
530 int term_got_escape;
531 int max_size;
532 /* Intermediate input buffer allows to catch escape sequences even if the
533 currently active device is not accepting any input - but only until it
534 is full as well. */
535 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
536 int prod[MAX_MUX];
537 int cons[MAX_MUX];
538 int timestamps;
540 /* Protected by the CharDriverState chr_write_lock. */
541 int linestart;
542 int64_t timestamps_start;
543 } MuxDriver;
546 /* Called with chr_write_lock held. */
547 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
549 MuxDriver *d = chr->opaque;
550 int ret;
551 if (!d->timestamps) {
552 ret = qemu_chr_fe_write(d->drv, buf, len);
553 } else {
554 int i;
556 ret = 0;
557 for (i = 0; i < len; i++) {
558 if (d->linestart) {
559 char buf1[64];
560 int64_t ti;
561 int secs;
563 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
564 if (d->timestamps_start == -1)
565 d->timestamps_start = ti;
566 ti -= d->timestamps_start;
567 secs = ti / 1000;
568 snprintf(buf1, sizeof(buf1),
569 "[%02d:%02d:%02d.%03d] ",
570 secs / 3600,
571 (secs / 60) % 60,
572 secs % 60,
573 (int)(ti % 1000));
574 /* XXX this blocks entire thread. Rewrite to use
575 * qemu_chr_fe_write and background I/O callbacks */
576 qemu_chr_fe_write_all(d->drv, (uint8_t *)buf1, strlen(buf1));
577 d->linestart = 0;
579 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
580 if (buf[i] == '\n') {
581 d->linestart = 1;
585 return ret;
588 static const char * const mux_help[] = {
589 "% h print this help\n\r",
590 "% x exit emulator\n\r",
591 "% s save disk data back to file (if -snapshot)\n\r",
592 "% t toggle console timestamps\n\r",
593 "% b send break (magic sysrq)\n\r",
594 "% c switch between console and monitor\n\r",
595 "% % sends %\n\r",
596 NULL
599 int term_escape_char = 0x01; /* ctrl-a is used for escape */
600 static void mux_print_help(CharDriverState *chr)
602 int i, j;
603 char ebuf[15] = "Escape-Char";
604 char cbuf[50] = "\n\r";
606 if (term_escape_char > 0 && term_escape_char < 26) {
607 snprintf(cbuf, sizeof(cbuf), "\n\r");
608 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
609 } else {
610 snprintf(cbuf, sizeof(cbuf),
611 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
612 term_escape_char);
614 /* XXX this blocks entire thread. Rewrite to use
615 * qemu_chr_fe_write and background I/O callbacks */
616 qemu_chr_fe_write_all(chr, (uint8_t *)cbuf, strlen(cbuf));
617 for (i = 0; mux_help[i] != NULL; i++) {
618 for (j=0; mux_help[i][j] != '\0'; j++) {
619 if (mux_help[i][j] == '%')
620 qemu_chr_fe_write_all(chr, (uint8_t *)ebuf, strlen(ebuf));
621 else
622 qemu_chr_fe_write_all(chr, (uint8_t *)&mux_help[i][j], 1);
627 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
629 if (d->chr_event[mux_nr])
630 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
633 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
635 if (d->term_got_escape) {
636 d->term_got_escape = 0;
637 if (ch == term_escape_char)
638 goto send_char;
639 switch(ch) {
640 case '?':
641 case 'h':
642 mux_print_help(chr);
643 break;
644 case 'x':
646 const char *term = "QEMU: Terminated\n\r";
647 qemu_chr_fe_write_all(chr, (uint8_t *)term, strlen(term));
648 exit(0);
649 break;
651 case 's':
652 blk_commit_all();
653 break;
654 case 'b':
655 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
656 break;
657 case 'c':
658 /* Switch to the next registered device */
659 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
660 d->focus++;
661 if (d->focus >= d->mux_cnt)
662 d->focus = 0;
663 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
664 break;
665 case 't':
666 d->timestamps = !d->timestamps;
667 d->timestamps_start = -1;
668 d->linestart = 0;
669 break;
671 } else if (ch == term_escape_char) {
672 d->term_got_escape = 1;
673 } else {
674 send_char:
675 return 1;
677 return 0;
680 static void mux_chr_accept_input(CharDriverState *chr)
682 MuxDriver *d = chr->opaque;
683 int m = d->focus;
685 while (d->prod[m] != d->cons[m] &&
686 d->chr_can_read[m] &&
687 d->chr_can_read[m](d->ext_opaque[m])) {
688 d->chr_read[m](d->ext_opaque[m],
689 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
693 static int mux_chr_can_read(void *opaque)
695 CharDriverState *chr = opaque;
696 MuxDriver *d = chr->opaque;
697 int m = d->focus;
699 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
700 return 1;
701 if (d->chr_can_read[m])
702 return d->chr_can_read[m](d->ext_opaque[m]);
703 return 0;
706 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
708 CharDriverState *chr = opaque;
709 MuxDriver *d = chr->opaque;
710 int m = d->focus;
711 int i;
713 mux_chr_accept_input (opaque);
715 for(i = 0; i < size; i++)
716 if (mux_proc_byte(chr, d, buf[i])) {
717 if (d->prod[m] == d->cons[m] &&
718 d->chr_can_read[m] &&
719 d->chr_can_read[m](d->ext_opaque[m]))
720 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
721 else
722 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
726 static void mux_chr_event(void *opaque, int event)
728 CharDriverState *chr = opaque;
729 MuxDriver *d = chr->opaque;
730 int i;
732 /* Send the event to all registered listeners */
733 for (i = 0; i < d->mux_cnt; i++)
734 mux_chr_send_event(d, i, event);
737 static void mux_chr_update_read_handler(CharDriverState *chr,
738 GMainContext *context)
740 MuxDriver *d = chr->opaque;
742 if (d->mux_cnt >= MAX_MUX) {
743 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
744 return;
746 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
747 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
748 d->chr_read[d->mux_cnt] = chr->chr_read;
749 d->chr_event[d->mux_cnt] = chr->chr_event;
750 /* Fix up the real driver with mux routines */
751 if (d->mux_cnt == 0) {
752 qemu_chr_add_handlers_full(d->drv, mux_chr_can_read,
753 mux_chr_read,
754 mux_chr_event,
755 chr, context);
757 if (d->focus != -1) {
758 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
760 d->focus = d->mux_cnt;
761 d->mux_cnt++;
762 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
765 static bool muxes_realized;
768 * Called after processing of default and command-line-specified
769 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
770 * to a mux chardev. This is done here to ensure that
771 * output/prompts/banners are only displayed for the FE that has
772 * focus when initial command-line processing/machine init is
773 * completed.
775 * After this point, any new FE attached to any new or existing
776 * mux will receive CHR_EVENT_OPENED notifications for the BE
777 * immediately.
779 static void muxes_realize_done(Notifier *notifier, void *unused)
781 CharDriverState *chr;
783 QTAILQ_FOREACH(chr, &chardevs, next) {
784 if (chr->is_mux) {
785 MuxDriver *d = chr->opaque;
786 int i;
788 /* send OPENED to all already-attached FEs */
789 for (i = 0; i < d->mux_cnt; i++) {
790 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
792 /* mark mux as OPENED so any new FEs will immediately receive
793 * OPENED event
795 qemu_chr_be_generic_open(chr);
798 muxes_realized = true;
801 static Notifier muxes_realize_notify = {
802 .notify = muxes_realize_done,
805 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
807 MuxDriver *d = s->opaque;
808 return d->drv->chr_add_watch(d->drv, cond);
811 static void mux_chr_close(struct CharDriverState *chr)
813 MuxDriver *d = chr->opaque;
815 g_free(d);
818 static CharDriverState *qemu_chr_open_mux(const char *id,
819 ChardevBackend *backend,
820 ChardevReturn *ret, Error **errp)
822 ChardevMux *mux = backend->u.mux.data;
823 CharDriverState *chr, *drv;
824 MuxDriver *d;
825 ChardevCommon *common = qapi_ChardevMux_base(mux);
827 drv = qemu_chr_find(mux->chardev);
828 if (drv == NULL) {
829 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
830 return NULL;
833 chr = qemu_chr_alloc(common, errp);
834 if (!chr) {
835 return NULL;
837 d = g_new0(MuxDriver, 1);
839 chr->opaque = d;
840 d->drv = drv;
841 d->focus = -1;
842 chr->chr_close = mux_chr_close;
843 chr->chr_write = mux_chr_write;
844 chr->chr_update_read_handler = mux_chr_update_read_handler;
845 chr->chr_accept_input = mux_chr_accept_input;
846 /* Frontend guest-open / -close notification is not support with muxes */
847 chr->chr_set_fe_open = NULL;
848 if (drv->chr_add_watch) {
849 chr->chr_add_watch = mux_chr_add_watch;
851 /* only default to opened state if we've realized the initial
852 * set of muxes
854 chr->explicit_be_open = muxes_realized ? 0 : 1;
855 chr->is_mux = 1;
857 return chr;
861 typedef struct IOWatchPoll
863 GSource parent;
865 QIOChannel *ioc;
866 GSource *src;
868 IOCanReadHandler *fd_can_read;
869 GSourceFunc fd_read;
870 void *opaque;
871 GMainContext *context;
872 } IOWatchPoll;
874 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
876 return container_of(source, IOWatchPoll, parent);
879 static gboolean io_watch_poll_prepare(GSource *source,
880 gint *timeout_)
882 IOWatchPoll *iwp = io_watch_poll_from_source(source);
883 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
884 bool was_active = iwp->src != NULL;
885 if (was_active == now_active) {
886 return FALSE;
889 if (now_active) {
890 iwp->src = qio_channel_create_watch(
891 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
892 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
893 g_source_attach(iwp->src, iwp->context);
894 } else {
895 g_source_destroy(iwp->src);
896 g_source_unref(iwp->src);
897 iwp->src = NULL;
899 return FALSE;
902 static gboolean io_watch_poll_check(GSource *source)
904 return FALSE;
907 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
908 gpointer user_data)
910 abort();
913 static void io_watch_poll_finalize(GSource *source)
915 /* Due to a glib bug, removing the last reference to a source
916 * inside a finalize callback causes recursive locking (and a
917 * deadlock). This is not a problem inside other callbacks,
918 * including dispatch callbacks, so we call io_remove_watch_poll
919 * to remove this source. At this point, iwp->src must
920 * be NULL, or we would leak it.
922 * This would be solved much more elegantly by child sources,
923 * but we support older glib versions that do not have them.
925 IOWatchPoll *iwp = io_watch_poll_from_source(source);
926 assert(iwp->src == NULL);
929 static GSourceFuncs io_watch_poll_funcs = {
930 .prepare = io_watch_poll_prepare,
931 .check = io_watch_poll_check,
932 .dispatch = io_watch_poll_dispatch,
933 .finalize = io_watch_poll_finalize,
936 /* Can only be used for read */
937 static guint io_add_watch_poll(QIOChannel *ioc,
938 IOCanReadHandler *fd_can_read,
939 QIOChannelFunc fd_read,
940 gpointer user_data,
941 GMainContext *context)
943 IOWatchPoll *iwp;
944 int tag;
946 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs,
947 sizeof(IOWatchPoll));
948 iwp->fd_can_read = fd_can_read;
949 iwp->opaque = user_data;
950 iwp->ioc = ioc;
951 iwp->fd_read = (GSourceFunc) fd_read;
952 iwp->src = NULL;
953 iwp->context = context;
955 tag = g_source_attach(&iwp->parent, context);
956 g_source_unref(&iwp->parent);
957 return tag;
960 static void io_remove_watch_poll(guint tag)
962 GSource *source;
963 IOWatchPoll *iwp;
965 g_return_if_fail (tag > 0);
967 source = g_main_context_find_source_by_id(NULL, tag);
968 g_return_if_fail (source != NULL);
970 iwp = io_watch_poll_from_source(source);
971 if (iwp->src) {
972 g_source_destroy(iwp->src);
973 g_source_unref(iwp->src);
974 iwp->src = NULL;
976 g_source_destroy(&iwp->parent);
979 static void remove_fd_in_watch(CharDriverState *chr)
981 if (chr->fd_in_tag) {
982 io_remove_watch_poll(chr->fd_in_tag);
983 chr->fd_in_tag = 0;
988 static int io_channel_send_full(QIOChannel *ioc,
989 const void *buf, size_t len,
990 int *fds, size_t nfds)
992 size_t offset = 0;
994 while (offset < len) {
995 ssize_t ret = 0;
996 struct iovec iov = { .iov_base = (char *)buf + offset,
997 .iov_len = len - offset };
999 ret = qio_channel_writev_full(
1000 ioc, &iov, 1,
1001 fds, nfds, NULL);
1002 if (ret == QIO_CHANNEL_ERR_BLOCK) {
1003 if (offset) {
1004 return offset;
1007 errno = EAGAIN;
1008 return -1;
1009 } else if (ret < 0) {
1010 errno = EINVAL;
1011 return -1;
1014 offset += ret;
1017 return offset;
1021 #ifndef _WIN32
1022 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
1024 return io_channel_send_full(ioc, buf, len, NULL, 0);
1028 typedef struct FDCharDriver {
1029 CharDriverState *chr;
1030 QIOChannel *ioc_in, *ioc_out;
1031 int max_size;
1032 } FDCharDriver;
1034 /* Called with chr_write_lock held. */
1035 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1037 FDCharDriver *s = chr->opaque;
1039 return io_channel_send(s->ioc_out, buf, len);
1042 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1044 CharDriverState *chr = opaque;
1045 FDCharDriver *s = chr->opaque;
1046 int len;
1047 uint8_t buf[READ_BUF_LEN];
1048 ssize_t ret;
1050 len = sizeof(buf);
1051 if (len > s->max_size) {
1052 len = s->max_size;
1054 if (len == 0) {
1055 return TRUE;
1058 ret = qio_channel_read(
1059 chan, (gchar *)buf, len, NULL);
1060 if (ret == 0) {
1061 remove_fd_in_watch(chr);
1062 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1063 return FALSE;
1065 if (ret > 0) {
1066 qemu_chr_be_write(chr, buf, ret);
1069 return TRUE;
1072 static int fd_chr_read_poll(void *opaque)
1074 CharDriverState *chr = opaque;
1075 FDCharDriver *s = chr->opaque;
1077 s->max_size = qemu_chr_be_can_write(chr);
1078 return s->max_size;
1081 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1083 FDCharDriver *s = chr->opaque;
1084 return qio_channel_create_watch(s->ioc_out, cond);
1087 static void fd_chr_update_read_handler(CharDriverState *chr,
1088 GMainContext *context)
1090 FDCharDriver *s = chr->opaque;
1092 remove_fd_in_watch(chr);
1093 if (s->ioc_in) {
1094 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
1095 fd_chr_read_poll,
1096 fd_chr_read, chr,
1097 context);
1101 static void fd_chr_close(struct CharDriverState *chr)
1103 FDCharDriver *s = chr->opaque;
1105 remove_fd_in_watch(chr);
1106 if (s->ioc_in) {
1107 object_unref(OBJECT(s->ioc_in));
1109 if (s->ioc_out) {
1110 object_unref(OBJECT(s->ioc_out));
1113 g_free(s);
1114 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1117 /* open a character device to a unix fd */
1118 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1119 ChardevCommon *backend, Error **errp)
1121 CharDriverState *chr;
1122 FDCharDriver *s;
1124 chr = qemu_chr_alloc(backend, errp);
1125 if (!chr) {
1126 return NULL;
1128 s = g_new0(FDCharDriver, 1);
1129 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1130 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1131 qemu_set_nonblock(fd_out);
1132 s->chr = chr;
1133 chr->opaque = s;
1134 chr->chr_add_watch = fd_chr_add_watch;
1135 chr->chr_write = fd_chr_write;
1136 chr->chr_update_read_handler = fd_chr_update_read_handler;
1137 chr->chr_close = fd_chr_close;
1139 return chr;
1142 static CharDriverState *qemu_chr_open_pipe(const char *id,
1143 ChardevBackend *backend,
1144 ChardevReturn *ret,
1145 Error **errp)
1147 ChardevHostdev *opts = backend->u.pipe.data;
1148 int fd_in, fd_out;
1149 char *filename_in;
1150 char *filename_out;
1151 const char *filename = opts->device;
1152 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1155 filename_in = g_strdup_printf("%s.in", filename);
1156 filename_out = g_strdup_printf("%s.out", filename);
1157 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1158 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1159 g_free(filename_in);
1160 g_free(filename_out);
1161 if (fd_in < 0 || fd_out < 0) {
1162 if (fd_in >= 0)
1163 close(fd_in);
1164 if (fd_out >= 0)
1165 close(fd_out);
1166 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1167 if (fd_in < 0) {
1168 error_setg_file_open(errp, errno, filename);
1169 return NULL;
1172 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1175 /* init terminal so that we can grab keys */
1176 static struct termios oldtty;
1177 static int old_fd0_flags;
1178 static bool stdio_in_use;
1179 static bool stdio_allow_signal;
1180 static bool stdio_echo_state;
1182 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1184 static void term_exit(void)
1186 tcsetattr (0, TCSANOW, &oldtty);
1187 fcntl(0, F_SETFL, old_fd0_flags);
1190 static void term_stdio_handler(int sig)
1192 /* restore echo after resume from suspend. */
1193 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1196 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1198 struct termios tty;
1200 stdio_echo_state = echo;
1201 tty = oldtty;
1202 if (!echo) {
1203 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1204 |INLCR|IGNCR|ICRNL|IXON);
1205 tty.c_oflag |= OPOST;
1206 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1207 tty.c_cflag &= ~(CSIZE|PARENB);
1208 tty.c_cflag |= CS8;
1209 tty.c_cc[VMIN] = 1;
1210 tty.c_cc[VTIME] = 0;
1212 if (!stdio_allow_signal)
1213 tty.c_lflag &= ~ISIG;
1215 tcsetattr (0, TCSANOW, &tty);
1218 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1220 term_exit();
1221 fd_chr_close(chr);
1224 static CharDriverState *qemu_chr_open_stdio(const char *id,
1225 ChardevBackend *backend,
1226 ChardevReturn *ret,
1227 Error **errp)
1229 ChardevStdio *opts = backend->u.stdio.data;
1230 CharDriverState *chr;
1231 struct sigaction act;
1232 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1234 if (is_daemonized()) {
1235 error_setg(errp, "cannot use stdio with -daemonize");
1236 return NULL;
1239 if (stdio_in_use) {
1240 error_setg(errp, "cannot use stdio by multiple character devices");
1241 return NULL;
1244 stdio_in_use = true;
1245 old_fd0_flags = fcntl(0, F_GETFL);
1246 tcgetattr(0, &oldtty);
1247 qemu_set_nonblock(0);
1248 atexit(term_exit);
1250 memset(&act, 0, sizeof(act));
1251 act.sa_handler = term_stdio_handler;
1252 sigaction(SIGCONT, &act, NULL);
1254 chr = qemu_chr_open_fd(0, 1, common, errp);
1255 if (!chr) {
1256 return NULL;
1258 chr->chr_close = qemu_chr_close_stdio;
1259 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1260 if (opts->has_signal) {
1261 stdio_allow_signal = opts->signal;
1263 qemu_chr_fe_set_echo(chr, false);
1265 return chr;
1268 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1269 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1270 || defined(__GLIBC__)
1272 #define HAVE_CHARDEV_SERIAL 1
1273 #define HAVE_CHARDEV_PTY 1
1275 typedef struct {
1276 QIOChannel *ioc;
1277 int read_bytes;
1279 /* Protected by the CharDriverState chr_write_lock. */
1280 int connected;
1281 guint timer_tag;
1282 guint open_tag;
1283 } PtyCharDriver;
1285 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1286 static void pty_chr_state(CharDriverState *chr, int connected);
1288 static gboolean pty_chr_timer(gpointer opaque)
1290 struct CharDriverState *chr = opaque;
1291 PtyCharDriver *s = chr->opaque;
1293 qemu_mutex_lock(&chr->chr_write_lock);
1294 s->timer_tag = 0;
1295 s->open_tag = 0;
1296 if (!s->connected) {
1297 /* Next poll ... */
1298 pty_chr_update_read_handler_locked(chr);
1300 qemu_mutex_unlock(&chr->chr_write_lock);
1301 return FALSE;
1304 /* Called with chr_write_lock held. */
1305 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1307 PtyCharDriver *s = chr->opaque;
1309 if (s->timer_tag) {
1310 g_source_remove(s->timer_tag);
1311 s->timer_tag = 0;
1314 if (ms == 1000) {
1315 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1316 } else {
1317 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1321 /* Called with chr_write_lock held. */
1322 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1324 PtyCharDriver *s = chr->opaque;
1325 GPollFD pfd;
1326 int rc;
1327 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1329 pfd.fd = fioc->fd;
1330 pfd.events = G_IO_OUT;
1331 pfd.revents = 0;
1332 do {
1333 rc = g_poll(&pfd, 1, 0);
1334 } while (rc == -1 && errno == EINTR);
1335 assert(rc >= 0);
1337 if (pfd.revents & G_IO_HUP) {
1338 pty_chr_state(chr, 0);
1339 } else {
1340 pty_chr_state(chr, 1);
1344 static void pty_chr_update_read_handler(CharDriverState *chr,
1345 GMainContext *context)
1347 qemu_mutex_lock(&chr->chr_write_lock);
1348 pty_chr_update_read_handler_locked(chr);
1349 qemu_mutex_unlock(&chr->chr_write_lock);
1352 /* Called with chr_write_lock held. */
1353 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1355 PtyCharDriver *s = chr->opaque;
1357 if (!s->connected) {
1358 /* guest sends data, check for (re-)connect */
1359 pty_chr_update_read_handler_locked(chr);
1360 if (!s->connected) {
1361 return 0;
1364 return io_channel_send(s->ioc, buf, len);
1367 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1369 PtyCharDriver *s = chr->opaque;
1370 if (!s->connected) {
1371 return NULL;
1373 return qio_channel_create_watch(s->ioc, cond);
1376 static int pty_chr_read_poll(void *opaque)
1378 CharDriverState *chr = opaque;
1379 PtyCharDriver *s = chr->opaque;
1381 s->read_bytes = qemu_chr_be_can_write(chr);
1382 return s->read_bytes;
1385 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1387 CharDriverState *chr = opaque;
1388 PtyCharDriver *s = chr->opaque;
1389 gsize len;
1390 uint8_t buf[READ_BUF_LEN];
1391 ssize_t ret;
1393 len = sizeof(buf);
1394 if (len > s->read_bytes)
1395 len = s->read_bytes;
1396 if (len == 0) {
1397 return TRUE;
1399 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1400 if (ret <= 0) {
1401 pty_chr_state(chr, 0);
1402 return FALSE;
1403 } else {
1404 pty_chr_state(chr, 1);
1405 qemu_chr_be_write(chr, buf, ret);
1407 return TRUE;
1410 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1412 CharDriverState *chr = opaque;
1413 PtyCharDriver *s = chr->opaque;
1415 s->open_tag = 0;
1416 qemu_chr_be_generic_open(chr);
1417 return FALSE;
1420 /* Called with chr_write_lock held. */
1421 static void pty_chr_state(CharDriverState *chr, int connected)
1423 PtyCharDriver *s = chr->opaque;
1425 if (!connected) {
1426 if (s->open_tag) {
1427 g_source_remove(s->open_tag);
1428 s->open_tag = 0;
1430 remove_fd_in_watch(chr);
1431 s->connected = 0;
1432 /* (re-)connect poll interval for idle guests: once per second.
1433 * We check more frequently in case the guests sends data to
1434 * the virtual device linked to our pty. */
1435 pty_chr_rearm_timer(chr, 1000);
1436 } else {
1437 if (s->timer_tag) {
1438 g_source_remove(s->timer_tag);
1439 s->timer_tag = 0;
1441 if (!s->connected) {
1442 g_assert(s->open_tag == 0);
1443 s->connected = 1;
1444 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1446 if (!chr->fd_in_tag) {
1447 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1448 pty_chr_read_poll,
1449 pty_chr_read,
1450 chr, NULL);
1455 static void pty_chr_close(struct CharDriverState *chr)
1457 PtyCharDriver *s = chr->opaque;
1459 qemu_mutex_lock(&chr->chr_write_lock);
1460 pty_chr_state(chr, 0);
1461 object_unref(OBJECT(s->ioc));
1462 if (s->timer_tag) {
1463 g_source_remove(s->timer_tag);
1464 s->timer_tag = 0;
1466 qemu_mutex_unlock(&chr->chr_write_lock);
1467 g_free(s);
1468 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1471 static CharDriverState *qemu_chr_open_pty(const char *id,
1472 ChardevBackend *backend,
1473 ChardevReturn *ret,
1474 Error **errp)
1476 CharDriverState *chr;
1477 PtyCharDriver *s;
1478 int master_fd, slave_fd;
1479 char pty_name[PATH_MAX];
1480 ChardevCommon *common = backend->u.pty.data;
1482 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1483 if (master_fd < 0) {
1484 error_setg_errno(errp, errno, "Failed to create PTY");
1485 return NULL;
1488 close(slave_fd);
1489 qemu_set_nonblock(master_fd);
1491 chr = qemu_chr_alloc(common, errp);
1492 if (!chr) {
1493 close(master_fd);
1494 return NULL;
1497 chr->filename = g_strdup_printf("pty:%s", pty_name);
1498 ret->pty = g_strdup(pty_name);
1499 ret->has_pty = true;
1501 fprintf(stderr, "char device redirected to %s (label %s)\n",
1502 pty_name, id);
1504 s = g_new0(PtyCharDriver, 1);
1505 chr->opaque = s;
1506 chr->chr_write = pty_chr_write;
1507 chr->chr_update_read_handler = pty_chr_update_read_handler;
1508 chr->chr_close = pty_chr_close;
1509 chr->chr_add_watch = pty_chr_add_watch;
1510 chr->explicit_be_open = true;
1512 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1513 s->timer_tag = 0;
1515 return chr;
1518 static void tty_serial_init(int fd, int speed,
1519 int parity, int data_bits, int stop_bits)
1521 struct termios tty;
1522 speed_t spd;
1524 #if 0
1525 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1526 speed, parity, data_bits, stop_bits);
1527 #endif
1528 tcgetattr (fd, &tty);
1530 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1531 speed = speed * 10 / 11;
1532 do {
1533 check_speed(50);
1534 check_speed(75);
1535 check_speed(110);
1536 check_speed(134);
1537 check_speed(150);
1538 check_speed(200);
1539 check_speed(300);
1540 check_speed(600);
1541 check_speed(1200);
1542 check_speed(1800);
1543 check_speed(2400);
1544 check_speed(4800);
1545 check_speed(9600);
1546 check_speed(19200);
1547 check_speed(38400);
1548 /* Non-Posix values follow. They may be unsupported on some systems. */
1549 check_speed(57600);
1550 check_speed(115200);
1551 #ifdef B230400
1552 check_speed(230400);
1553 #endif
1554 #ifdef B460800
1555 check_speed(460800);
1556 #endif
1557 #ifdef B500000
1558 check_speed(500000);
1559 #endif
1560 #ifdef B576000
1561 check_speed(576000);
1562 #endif
1563 #ifdef B921600
1564 check_speed(921600);
1565 #endif
1566 #ifdef B1000000
1567 check_speed(1000000);
1568 #endif
1569 #ifdef B1152000
1570 check_speed(1152000);
1571 #endif
1572 #ifdef B1500000
1573 check_speed(1500000);
1574 #endif
1575 #ifdef B2000000
1576 check_speed(2000000);
1577 #endif
1578 #ifdef B2500000
1579 check_speed(2500000);
1580 #endif
1581 #ifdef B3000000
1582 check_speed(3000000);
1583 #endif
1584 #ifdef B3500000
1585 check_speed(3500000);
1586 #endif
1587 #ifdef B4000000
1588 check_speed(4000000);
1589 #endif
1590 spd = B115200;
1591 } while (0);
1593 cfsetispeed(&tty, spd);
1594 cfsetospeed(&tty, spd);
1596 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1597 |INLCR|IGNCR|ICRNL|IXON);
1598 tty.c_oflag |= OPOST;
1599 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1600 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1601 switch(data_bits) {
1602 default:
1603 case 8:
1604 tty.c_cflag |= CS8;
1605 break;
1606 case 7:
1607 tty.c_cflag |= CS7;
1608 break;
1609 case 6:
1610 tty.c_cflag |= CS6;
1611 break;
1612 case 5:
1613 tty.c_cflag |= CS5;
1614 break;
1616 switch(parity) {
1617 default:
1618 case 'N':
1619 break;
1620 case 'E':
1621 tty.c_cflag |= PARENB;
1622 break;
1623 case 'O':
1624 tty.c_cflag |= PARENB | PARODD;
1625 break;
1627 if (stop_bits == 2)
1628 tty.c_cflag |= CSTOPB;
1630 tcsetattr (fd, TCSANOW, &tty);
1633 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1635 FDCharDriver *s = chr->opaque;
1636 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1638 switch(cmd) {
1639 case CHR_IOCTL_SERIAL_SET_PARAMS:
1641 QEMUSerialSetParams *ssp = arg;
1642 tty_serial_init(fioc->fd,
1643 ssp->speed, ssp->parity,
1644 ssp->data_bits, ssp->stop_bits);
1646 break;
1647 case CHR_IOCTL_SERIAL_SET_BREAK:
1649 int enable = *(int *)arg;
1650 if (enable) {
1651 tcsendbreak(fioc->fd, 1);
1654 break;
1655 case CHR_IOCTL_SERIAL_GET_TIOCM:
1657 int sarg = 0;
1658 int *targ = (int *)arg;
1659 ioctl(fioc->fd, TIOCMGET, &sarg);
1660 *targ = 0;
1661 if (sarg & TIOCM_CTS)
1662 *targ |= CHR_TIOCM_CTS;
1663 if (sarg & TIOCM_CAR)
1664 *targ |= CHR_TIOCM_CAR;
1665 if (sarg & TIOCM_DSR)
1666 *targ |= CHR_TIOCM_DSR;
1667 if (sarg & TIOCM_RI)
1668 *targ |= CHR_TIOCM_RI;
1669 if (sarg & TIOCM_DTR)
1670 *targ |= CHR_TIOCM_DTR;
1671 if (sarg & TIOCM_RTS)
1672 *targ |= CHR_TIOCM_RTS;
1674 break;
1675 case CHR_IOCTL_SERIAL_SET_TIOCM:
1677 int sarg = *(int *)arg;
1678 int targ = 0;
1679 ioctl(fioc->fd, TIOCMGET, &targ);
1680 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1681 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1682 if (sarg & CHR_TIOCM_CTS)
1683 targ |= TIOCM_CTS;
1684 if (sarg & CHR_TIOCM_CAR)
1685 targ |= TIOCM_CAR;
1686 if (sarg & CHR_TIOCM_DSR)
1687 targ |= TIOCM_DSR;
1688 if (sarg & CHR_TIOCM_RI)
1689 targ |= TIOCM_RI;
1690 if (sarg & CHR_TIOCM_DTR)
1691 targ |= TIOCM_DTR;
1692 if (sarg & CHR_TIOCM_RTS)
1693 targ |= TIOCM_RTS;
1694 ioctl(fioc->fd, TIOCMSET, &targ);
1696 break;
1697 default:
1698 return -ENOTSUP;
1700 return 0;
1703 static void qemu_chr_close_tty(CharDriverState *chr)
1705 fd_chr_close(chr);
1708 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1709 ChardevCommon *backend,
1710 Error **errp)
1712 CharDriverState *chr;
1714 tty_serial_init(fd, 115200, 'N', 8, 1);
1715 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1716 if (!chr) {
1717 return NULL;
1719 chr->chr_ioctl = tty_serial_ioctl;
1720 chr->chr_close = qemu_chr_close_tty;
1721 return chr;
1723 #endif /* __linux__ || __sun__ */
1725 #if defined(__linux__)
1727 #define HAVE_CHARDEV_PARPORT 1
1729 typedef struct {
1730 int fd;
1731 int mode;
1732 } ParallelCharDriver;
1734 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1736 if (s->mode != mode) {
1737 int m = mode;
1738 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1739 return 0;
1740 s->mode = mode;
1742 return 1;
1745 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1747 ParallelCharDriver *drv = chr->opaque;
1748 int fd = drv->fd;
1749 uint8_t b;
1751 switch(cmd) {
1752 case CHR_IOCTL_PP_READ_DATA:
1753 if (ioctl(fd, PPRDATA, &b) < 0)
1754 return -ENOTSUP;
1755 *(uint8_t *)arg = b;
1756 break;
1757 case CHR_IOCTL_PP_WRITE_DATA:
1758 b = *(uint8_t *)arg;
1759 if (ioctl(fd, PPWDATA, &b) < 0)
1760 return -ENOTSUP;
1761 break;
1762 case CHR_IOCTL_PP_READ_CONTROL:
1763 if (ioctl(fd, PPRCONTROL, &b) < 0)
1764 return -ENOTSUP;
1765 /* Linux gives only the lowest bits, and no way to know data
1766 direction! For better compatibility set the fixed upper
1767 bits. */
1768 *(uint8_t *)arg = b | 0xc0;
1769 break;
1770 case CHR_IOCTL_PP_WRITE_CONTROL:
1771 b = *(uint8_t *)arg;
1772 if (ioctl(fd, PPWCONTROL, &b) < 0)
1773 return -ENOTSUP;
1774 break;
1775 case CHR_IOCTL_PP_READ_STATUS:
1776 if (ioctl(fd, PPRSTATUS, &b) < 0)
1777 return -ENOTSUP;
1778 *(uint8_t *)arg = b;
1779 break;
1780 case CHR_IOCTL_PP_DATA_DIR:
1781 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1782 return -ENOTSUP;
1783 break;
1784 case CHR_IOCTL_PP_EPP_READ_ADDR:
1785 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1786 struct ParallelIOArg *parg = arg;
1787 int n = read(fd, parg->buffer, parg->count);
1788 if (n != parg->count) {
1789 return -EIO;
1792 break;
1793 case CHR_IOCTL_PP_EPP_READ:
1794 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1795 struct ParallelIOArg *parg = arg;
1796 int n = read(fd, parg->buffer, parg->count);
1797 if (n != parg->count) {
1798 return -EIO;
1801 break;
1802 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1803 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1804 struct ParallelIOArg *parg = arg;
1805 int n = write(fd, parg->buffer, parg->count);
1806 if (n != parg->count) {
1807 return -EIO;
1810 break;
1811 case CHR_IOCTL_PP_EPP_WRITE:
1812 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1813 struct ParallelIOArg *parg = arg;
1814 int n = write(fd, parg->buffer, parg->count);
1815 if (n != parg->count) {
1816 return -EIO;
1819 break;
1820 default:
1821 return -ENOTSUP;
1823 return 0;
1826 static void pp_close(CharDriverState *chr)
1828 ParallelCharDriver *drv = chr->opaque;
1829 int fd = drv->fd;
1831 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1832 ioctl(fd, PPRELEASE);
1833 close(fd);
1834 g_free(drv);
1835 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1838 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1839 ChardevCommon *backend,
1840 Error **errp)
1842 CharDriverState *chr;
1843 ParallelCharDriver *drv;
1845 if (ioctl(fd, PPCLAIM) < 0) {
1846 error_setg_errno(errp, errno, "not a parallel port");
1847 close(fd);
1848 return NULL;
1851 chr = qemu_chr_alloc(backend, errp);
1852 if (!chr) {
1853 return NULL;
1856 drv = g_new0(ParallelCharDriver, 1);
1857 chr->opaque = drv;
1858 chr->chr_write = null_chr_write;
1859 chr->chr_ioctl = pp_ioctl;
1860 chr->chr_close = pp_close;
1862 drv->fd = fd;
1863 drv->mode = IEEE1284_MODE_COMPAT;
1865 return chr;
1867 #endif /* __linux__ */
1869 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1871 #define HAVE_CHARDEV_PARPORT 1
1873 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1875 int fd = (int)(intptr_t)chr->opaque;
1876 uint8_t b;
1878 switch(cmd) {
1879 case CHR_IOCTL_PP_READ_DATA:
1880 if (ioctl(fd, PPIGDATA, &b) < 0)
1881 return -ENOTSUP;
1882 *(uint8_t *)arg = b;
1883 break;
1884 case CHR_IOCTL_PP_WRITE_DATA:
1885 b = *(uint8_t *)arg;
1886 if (ioctl(fd, PPISDATA, &b) < 0)
1887 return -ENOTSUP;
1888 break;
1889 case CHR_IOCTL_PP_READ_CONTROL:
1890 if (ioctl(fd, PPIGCTRL, &b) < 0)
1891 return -ENOTSUP;
1892 *(uint8_t *)arg = b;
1893 break;
1894 case CHR_IOCTL_PP_WRITE_CONTROL:
1895 b = *(uint8_t *)arg;
1896 if (ioctl(fd, PPISCTRL, &b) < 0)
1897 return -ENOTSUP;
1898 break;
1899 case CHR_IOCTL_PP_READ_STATUS:
1900 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1901 return -ENOTSUP;
1902 *(uint8_t *)arg = b;
1903 break;
1904 default:
1905 return -ENOTSUP;
1907 return 0;
1910 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1911 ChardevCommon *backend,
1912 Error **errp)
1914 CharDriverState *chr;
1916 chr = qemu_chr_alloc(backend, errp);
1917 if (!chr) {
1918 return NULL;
1920 chr->opaque = (void *)(intptr_t)fd;
1921 chr->chr_write = null_chr_write;
1922 chr->chr_ioctl = pp_ioctl;
1923 chr->explicit_be_open = true;
1924 return chr;
1926 #endif
1928 #else /* _WIN32 */
1930 #define HAVE_CHARDEV_SERIAL 1
1932 typedef struct {
1933 int max_size;
1934 HANDLE hcom, hrecv, hsend;
1935 OVERLAPPED orecv;
1936 BOOL fpipe;
1937 DWORD len;
1939 /* Protected by the CharDriverState chr_write_lock. */
1940 OVERLAPPED osend;
1941 } WinCharState;
1943 typedef struct {
1944 HANDLE hStdIn;
1945 HANDLE hInputReadyEvent;
1946 HANDLE hInputDoneEvent;
1947 HANDLE hInputThread;
1948 uint8_t win_stdio_buf;
1949 } WinStdioCharState;
1951 #define NSENDBUF 2048
1952 #define NRECVBUF 2048
1953 #define MAXCONNECT 1
1954 #define NTIMEOUT 5000
1956 static int win_chr_poll(void *opaque);
1957 static int win_chr_pipe_poll(void *opaque);
1959 static void win_chr_close(CharDriverState *chr)
1961 WinCharState *s = chr->opaque;
1963 if (s->hsend) {
1964 CloseHandle(s->hsend);
1965 s->hsend = NULL;
1967 if (s->hrecv) {
1968 CloseHandle(s->hrecv);
1969 s->hrecv = NULL;
1971 if (s->hcom) {
1972 CloseHandle(s->hcom);
1973 s->hcom = NULL;
1975 if (s->fpipe)
1976 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1977 else
1978 qemu_del_polling_cb(win_chr_poll, chr);
1980 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1983 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1985 WinCharState *s = chr->opaque;
1986 COMMCONFIG comcfg;
1987 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1988 COMSTAT comstat;
1989 DWORD size;
1990 DWORD err;
1992 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1993 if (!s->hsend) {
1994 error_setg(errp, "Failed CreateEvent");
1995 goto fail;
1997 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1998 if (!s->hrecv) {
1999 error_setg(errp, "Failed CreateEvent");
2000 goto fail;
2003 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2004 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2005 if (s->hcom == INVALID_HANDLE_VALUE) {
2006 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
2007 s->hcom = NULL;
2008 goto fail;
2011 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2012 error_setg(errp, "Failed SetupComm");
2013 goto fail;
2016 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2017 size = sizeof(COMMCONFIG);
2018 GetDefaultCommConfig(filename, &comcfg, &size);
2019 comcfg.dcb.DCBlength = sizeof(DCB);
2020 CommConfigDialog(filename, NULL, &comcfg);
2022 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2023 error_setg(errp, "Failed SetCommState");
2024 goto fail;
2027 if (!SetCommMask(s->hcom, EV_ERR)) {
2028 error_setg(errp, "Failed SetCommMask");
2029 goto fail;
2032 cto.ReadIntervalTimeout = MAXDWORD;
2033 if (!SetCommTimeouts(s->hcom, &cto)) {
2034 error_setg(errp, "Failed SetCommTimeouts");
2035 goto fail;
2038 if (!ClearCommError(s->hcom, &err, &comstat)) {
2039 error_setg(errp, "Failed ClearCommError");
2040 goto fail;
2042 qemu_add_polling_cb(win_chr_poll, chr);
2043 return 0;
2045 fail:
2046 win_chr_close(chr);
2047 return -1;
2050 /* Called with chr_write_lock held. */
2051 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2053 WinCharState *s = chr->opaque;
2054 DWORD len, ret, size, err;
2056 len = len1;
2057 ZeroMemory(&s->osend, sizeof(s->osend));
2058 s->osend.hEvent = s->hsend;
2059 while (len > 0) {
2060 if (s->hsend)
2061 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2062 else
2063 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2064 if (!ret) {
2065 err = GetLastError();
2066 if (err == ERROR_IO_PENDING) {
2067 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2068 if (ret) {
2069 buf += size;
2070 len -= size;
2071 } else {
2072 break;
2074 } else {
2075 break;
2077 } else {
2078 buf += size;
2079 len -= size;
2082 return len1 - len;
2085 static int win_chr_read_poll(CharDriverState *chr)
2087 WinCharState *s = chr->opaque;
2089 s->max_size = qemu_chr_be_can_write(chr);
2090 return s->max_size;
2093 static void win_chr_readfile(CharDriverState *chr)
2095 WinCharState *s = chr->opaque;
2096 int ret, err;
2097 uint8_t buf[READ_BUF_LEN];
2098 DWORD size;
2100 ZeroMemory(&s->orecv, sizeof(s->orecv));
2101 s->orecv.hEvent = s->hrecv;
2102 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2103 if (!ret) {
2104 err = GetLastError();
2105 if (err == ERROR_IO_PENDING) {
2106 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2110 if (size > 0) {
2111 qemu_chr_be_write(chr, buf, size);
2115 static void win_chr_read(CharDriverState *chr)
2117 WinCharState *s = chr->opaque;
2119 if (s->len > s->max_size)
2120 s->len = s->max_size;
2121 if (s->len == 0)
2122 return;
2124 win_chr_readfile(chr);
2127 static int win_chr_poll(void *opaque)
2129 CharDriverState *chr = opaque;
2130 WinCharState *s = chr->opaque;
2131 COMSTAT status;
2132 DWORD comerr;
2134 ClearCommError(s->hcom, &comerr, &status);
2135 if (status.cbInQue > 0) {
2136 s->len = status.cbInQue;
2137 win_chr_read_poll(chr);
2138 win_chr_read(chr);
2139 return 1;
2141 return 0;
2144 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2145 ChardevCommon *backend,
2146 Error **errp)
2148 CharDriverState *chr;
2149 WinCharState *s;
2151 chr = qemu_chr_alloc(backend, errp);
2152 if (!chr) {
2153 return NULL;
2155 s = g_new0(WinCharState, 1);
2156 chr->opaque = s;
2157 chr->chr_write = win_chr_write;
2158 chr->chr_close = win_chr_close;
2160 if (win_chr_init(chr, filename, errp) < 0) {
2161 g_free(s);
2162 qemu_chr_free_common(chr);
2163 return NULL;
2165 return chr;
2168 static int win_chr_pipe_poll(void *opaque)
2170 CharDriverState *chr = opaque;
2171 WinCharState *s = chr->opaque;
2172 DWORD size;
2174 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2175 if (size > 0) {
2176 s->len = size;
2177 win_chr_read_poll(chr);
2178 win_chr_read(chr);
2179 return 1;
2181 return 0;
2184 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2185 Error **errp)
2187 WinCharState *s = chr->opaque;
2188 OVERLAPPED ov;
2189 int ret;
2190 DWORD size;
2191 char *openname;
2193 s->fpipe = TRUE;
2195 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2196 if (!s->hsend) {
2197 error_setg(errp, "Failed CreateEvent");
2198 goto fail;
2200 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2201 if (!s->hrecv) {
2202 error_setg(errp, "Failed CreateEvent");
2203 goto fail;
2206 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2207 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2208 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2209 PIPE_WAIT,
2210 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2211 g_free(openname);
2212 if (s->hcom == INVALID_HANDLE_VALUE) {
2213 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2214 s->hcom = NULL;
2215 goto fail;
2218 ZeroMemory(&ov, sizeof(ov));
2219 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2220 ret = ConnectNamedPipe(s->hcom, &ov);
2221 if (ret) {
2222 error_setg(errp, "Failed ConnectNamedPipe");
2223 goto fail;
2226 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2227 if (!ret) {
2228 error_setg(errp, "Failed GetOverlappedResult");
2229 if (ov.hEvent) {
2230 CloseHandle(ov.hEvent);
2231 ov.hEvent = NULL;
2233 goto fail;
2236 if (ov.hEvent) {
2237 CloseHandle(ov.hEvent);
2238 ov.hEvent = NULL;
2240 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2241 return 0;
2243 fail:
2244 win_chr_close(chr);
2245 return -1;
2249 static CharDriverState *qemu_chr_open_pipe(const char *id,
2250 ChardevBackend *backend,
2251 ChardevReturn *ret,
2252 Error **errp)
2254 ChardevHostdev *opts = backend->u.pipe.data;
2255 const char *filename = opts->device;
2256 CharDriverState *chr;
2257 WinCharState *s;
2258 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2260 chr = qemu_chr_alloc(common, errp);
2261 if (!chr) {
2262 return NULL;
2264 s = g_new0(WinCharState, 1);
2265 chr->opaque = s;
2266 chr->chr_write = win_chr_write;
2267 chr->chr_close = win_chr_close;
2269 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2270 g_free(s);
2271 qemu_chr_free_common(chr);
2272 return NULL;
2274 return chr;
2277 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2278 ChardevCommon *backend,
2279 Error **errp)
2281 CharDriverState *chr;
2282 WinCharState *s;
2284 chr = qemu_chr_alloc(backend, errp);
2285 if (!chr) {
2286 return NULL;
2288 s = g_new0(WinCharState, 1);
2289 s->hcom = fd_out;
2290 chr->opaque = s;
2291 chr->chr_write = win_chr_write;
2292 return chr;
2295 static CharDriverState *qemu_chr_open_win_con(const char *id,
2296 ChardevBackend *backend,
2297 ChardevReturn *ret,
2298 Error **errp)
2300 ChardevCommon *common = backend->u.console.data;
2301 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2302 common, errp);
2305 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2307 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2308 DWORD dwSize;
2309 int len1;
2311 len1 = len;
2313 while (len1 > 0) {
2314 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2315 break;
2317 buf += dwSize;
2318 len1 -= dwSize;
2321 return len - len1;
2324 static void win_stdio_wait_func(void *opaque)
2326 CharDriverState *chr = opaque;
2327 WinStdioCharState *stdio = chr->opaque;
2328 INPUT_RECORD buf[4];
2329 int ret;
2330 DWORD dwSize;
2331 int i;
2333 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2335 if (!ret) {
2336 /* Avoid error storm */
2337 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2338 return;
2341 for (i = 0; i < dwSize; i++) {
2342 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2344 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2345 int j;
2346 if (kev->uChar.AsciiChar != 0) {
2347 for (j = 0; j < kev->wRepeatCount; j++) {
2348 if (qemu_chr_be_can_write(chr)) {
2349 uint8_t c = kev->uChar.AsciiChar;
2350 qemu_chr_be_write(chr, &c, 1);
2358 static DWORD WINAPI win_stdio_thread(LPVOID param)
2360 CharDriverState *chr = param;
2361 WinStdioCharState *stdio = chr->opaque;
2362 int ret;
2363 DWORD dwSize;
2365 while (1) {
2367 /* Wait for one byte */
2368 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2370 /* Exit in case of error, continue if nothing read */
2371 if (!ret) {
2372 break;
2374 if (!dwSize) {
2375 continue;
2378 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2379 if (stdio->win_stdio_buf == '\r') {
2380 continue;
2383 /* Signal the main thread and wait until the byte was eaten */
2384 if (!SetEvent(stdio->hInputReadyEvent)) {
2385 break;
2387 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2388 != WAIT_OBJECT_0) {
2389 break;
2393 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2394 return 0;
2397 static void win_stdio_thread_wait_func(void *opaque)
2399 CharDriverState *chr = opaque;
2400 WinStdioCharState *stdio = chr->opaque;
2402 if (qemu_chr_be_can_write(chr)) {
2403 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2406 SetEvent(stdio->hInputDoneEvent);
2409 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2411 WinStdioCharState *stdio = chr->opaque;
2412 DWORD dwMode = 0;
2414 GetConsoleMode(stdio->hStdIn, &dwMode);
2416 if (echo) {
2417 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2418 } else {
2419 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2423 static void win_stdio_close(CharDriverState *chr)
2425 WinStdioCharState *stdio = chr->opaque;
2427 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2428 CloseHandle(stdio->hInputReadyEvent);
2430 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2431 CloseHandle(stdio->hInputDoneEvent);
2433 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2434 TerminateThread(stdio->hInputThread, 0);
2437 g_free(chr->opaque);
2438 g_free(chr);
2441 static CharDriverState *qemu_chr_open_stdio(const char *id,
2442 ChardevBackend *backend,
2443 ChardevReturn *ret,
2444 Error **errp)
2446 CharDriverState *chr;
2447 WinStdioCharState *stdio;
2448 DWORD dwMode;
2449 int is_console = 0;
2450 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio.data);
2452 chr = qemu_chr_alloc(common, errp);
2453 if (!chr) {
2454 return NULL;
2456 stdio = g_new0(WinStdioCharState, 1);
2458 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2459 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2460 error_setg(errp, "cannot open stdio: invalid handle");
2461 return NULL;
2464 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2466 chr->opaque = stdio;
2467 chr->chr_write = win_stdio_write;
2468 chr->chr_close = win_stdio_close;
2470 if (is_console) {
2471 if (qemu_add_wait_object(stdio->hStdIn,
2472 win_stdio_wait_func, chr)) {
2473 error_setg(errp, "qemu_add_wait_object: failed");
2474 goto err1;
2476 } else {
2477 DWORD dwId;
2479 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2480 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2481 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2482 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2483 error_setg(errp, "cannot create event");
2484 goto err2;
2486 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2487 win_stdio_thread_wait_func, chr)) {
2488 error_setg(errp, "qemu_add_wait_object: failed");
2489 goto err2;
2491 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2492 chr, 0, &dwId);
2494 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2495 error_setg(errp, "cannot create stdio thread");
2496 goto err3;
2500 dwMode |= ENABLE_LINE_INPUT;
2502 if (is_console) {
2503 /* set the terminal in raw mode */
2504 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2505 dwMode |= ENABLE_PROCESSED_INPUT;
2508 SetConsoleMode(stdio->hStdIn, dwMode);
2510 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2511 qemu_chr_fe_set_echo(chr, false);
2513 return chr;
2515 err3:
2516 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2517 err2:
2518 CloseHandle(stdio->hInputReadyEvent);
2519 CloseHandle(stdio->hInputDoneEvent);
2520 err1:
2521 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2522 return NULL;
2524 #endif /* !_WIN32 */
2527 /***********************************************************/
2528 /* UDP Net console */
2530 typedef struct {
2531 QIOChannel *ioc;
2532 uint8_t buf[READ_BUF_LEN];
2533 int bufcnt;
2534 int bufptr;
2535 int max_size;
2536 } NetCharDriver;
2538 /* Called with chr_write_lock held. */
2539 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2541 NetCharDriver *s = chr->opaque;
2543 return qio_channel_write(
2544 s->ioc, (const char *)buf, len, NULL);
2547 static int udp_chr_read_poll(void *opaque)
2549 CharDriverState *chr = opaque;
2550 NetCharDriver *s = chr->opaque;
2552 s->max_size = qemu_chr_be_can_write(chr);
2554 /* If there were any stray characters in the queue process them
2555 * first
2557 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2558 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2559 s->bufptr++;
2560 s->max_size = qemu_chr_be_can_write(chr);
2562 return s->max_size;
2565 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2567 CharDriverState *chr = opaque;
2568 NetCharDriver *s = chr->opaque;
2569 ssize_t ret;
2571 if (s->max_size == 0) {
2572 return TRUE;
2574 ret = qio_channel_read(
2575 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2576 if (ret <= 0) {
2577 remove_fd_in_watch(chr);
2578 return FALSE;
2580 s->bufcnt = ret;
2582 s->bufptr = 0;
2583 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2584 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2585 s->bufptr++;
2586 s->max_size = qemu_chr_be_can_write(chr);
2589 return TRUE;
2592 static void udp_chr_update_read_handler(CharDriverState *chr,
2593 GMainContext *context)
2595 NetCharDriver *s = chr->opaque;
2597 remove_fd_in_watch(chr);
2598 if (s->ioc) {
2599 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2600 udp_chr_read_poll,
2601 udp_chr_read, chr,
2602 context);
2606 static void udp_chr_close(CharDriverState *chr)
2608 NetCharDriver *s = chr->opaque;
2610 remove_fd_in_watch(chr);
2611 if (s->ioc) {
2612 object_unref(OBJECT(s->ioc));
2614 g_free(s);
2615 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2618 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2619 ChardevCommon *backend,
2620 Error **errp)
2622 CharDriverState *chr = NULL;
2623 NetCharDriver *s = NULL;
2625 chr = qemu_chr_alloc(backend, errp);
2626 if (!chr) {
2627 return NULL;
2629 s = g_new0(NetCharDriver, 1);
2631 s->ioc = QIO_CHANNEL(sioc);
2632 s->bufcnt = 0;
2633 s->bufptr = 0;
2634 chr->opaque = s;
2635 chr->chr_write = udp_chr_write;
2636 chr->chr_update_read_handler = udp_chr_update_read_handler;
2637 chr->chr_close = udp_chr_close;
2638 /* be isn't opened until we get a connection */
2639 chr->explicit_be_open = true;
2640 return chr;
2643 /***********************************************************/
2644 /* TCP Net console */
2646 typedef struct {
2647 QIOChannel *ioc; /* Client I/O channel */
2648 QIOChannelSocket *sioc; /* Client master channel */
2649 QIOChannelSocket *listen_ioc;
2650 guint listen_tag;
2651 QCryptoTLSCreds *tls_creds;
2652 int connected;
2653 int max_size;
2654 int do_telnetopt;
2655 int do_nodelay;
2656 int is_unix;
2657 int *read_msgfds;
2658 size_t read_msgfds_num;
2659 int *write_msgfds;
2660 size_t write_msgfds_num;
2662 SocketAddress *addr;
2663 bool is_listen;
2664 bool is_telnet;
2666 guint reconnect_timer;
2667 int64_t reconnect_time;
2668 bool connect_err_reported;
2669 } TCPCharDriver;
2671 static gboolean socket_reconnect_timeout(gpointer opaque);
2673 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2675 TCPCharDriver *s = chr->opaque;
2676 assert(s->connected == 0);
2677 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2678 socket_reconnect_timeout, chr);
2681 static void check_report_connect_error(CharDriverState *chr,
2682 Error *err)
2684 TCPCharDriver *s = chr->opaque;
2686 if (!s->connect_err_reported) {
2687 error_report("Unable to connect character device %s: %s",
2688 chr->label, error_get_pretty(err));
2689 s->connect_err_reported = true;
2691 qemu_chr_socket_restart_timer(chr);
2694 static gboolean tcp_chr_accept(QIOChannel *chan,
2695 GIOCondition cond,
2696 void *opaque);
2698 /* Called with chr_write_lock held. */
2699 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2701 TCPCharDriver *s = chr->opaque;
2702 if (s->connected) {
2703 int ret = io_channel_send_full(s->ioc, buf, len,
2704 s->write_msgfds,
2705 s->write_msgfds_num);
2707 /* free the written msgfds, no matter what */
2708 if (s->write_msgfds_num) {
2709 g_free(s->write_msgfds);
2710 s->write_msgfds = 0;
2711 s->write_msgfds_num = 0;
2714 return ret;
2715 } else {
2716 /* XXX: indicate an error ? */
2717 return len;
2721 static int tcp_chr_read_poll(void *opaque)
2723 CharDriverState *chr = opaque;
2724 TCPCharDriver *s = chr->opaque;
2725 if (!s->connected)
2726 return 0;
2727 s->max_size = qemu_chr_be_can_write(chr);
2728 return s->max_size;
2731 #define IAC 255
2732 #define IAC_BREAK 243
2733 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2734 TCPCharDriver *s,
2735 uint8_t *buf, int *size)
2737 /* Handle any telnet client's basic IAC options to satisfy char by
2738 * char mode with no echo. All IAC options will be removed from
2739 * the buf and the do_telnetopt variable will be used to track the
2740 * state of the width of the IAC information.
2742 * IAC commands come in sets of 3 bytes with the exception of the
2743 * "IAC BREAK" command and the double IAC.
2746 int i;
2747 int j = 0;
2749 for (i = 0; i < *size; i++) {
2750 if (s->do_telnetopt > 1) {
2751 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2752 /* Double IAC means send an IAC */
2753 if (j != i)
2754 buf[j] = buf[i];
2755 j++;
2756 s->do_telnetopt = 1;
2757 } else {
2758 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2759 /* Handle IAC break commands by sending a serial break */
2760 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2761 s->do_telnetopt++;
2763 s->do_telnetopt++;
2765 if (s->do_telnetopt >= 4) {
2766 s->do_telnetopt = 1;
2768 } else {
2769 if ((unsigned char)buf[i] == IAC) {
2770 s->do_telnetopt = 2;
2771 } else {
2772 if (j != i)
2773 buf[j] = buf[i];
2774 j++;
2778 *size = j;
2781 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2783 TCPCharDriver *s = chr->opaque;
2784 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2786 assert(num <= TCP_MAX_FDS);
2788 if (to_copy) {
2789 int i;
2791 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2793 /* Close unused fds */
2794 for (i = to_copy; i < s->read_msgfds_num; i++) {
2795 close(s->read_msgfds[i]);
2798 g_free(s->read_msgfds);
2799 s->read_msgfds = 0;
2800 s->read_msgfds_num = 0;
2803 return to_copy;
2806 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2808 TCPCharDriver *s = chr->opaque;
2810 /* clear old pending fd array */
2811 g_free(s->write_msgfds);
2812 s->write_msgfds = NULL;
2813 s->write_msgfds_num = 0;
2815 if (!s->connected ||
2816 !qio_channel_has_feature(s->ioc,
2817 QIO_CHANNEL_FEATURE_FD_PASS)) {
2818 return -1;
2821 if (num) {
2822 s->write_msgfds = g_new(int, num);
2823 memcpy(s->write_msgfds, fds, num * sizeof(int));
2826 s->write_msgfds_num = num;
2828 return 0;
2831 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2833 TCPCharDriver *s = chr->opaque;
2834 struct iovec iov = { .iov_base = buf, .iov_len = len };
2835 int ret;
2836 size_t i;
2837 int *msgfds = NULL;
2838 size_t msgfds_num = 0;
2840 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2841 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2842 &msgfds, &msgfds_num,
2843 NULL);
2844 } else {
2845 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2846 NULL, NULL,
2847 NULL);
2850 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2851 errno = EAGAIN;
2852 ret = -1;
2853 } else if (ret == -1) {
2854 errno = EIO;
2857 if (msgfds_num) {
2858 /* close and clean read_msgfds */
2859 for (i = 0; i < s->read_msgfds_num; i++) {
2860 close(s->read_msgfds[i]);
2863 if (s->read_msgfds_num) {
2864 g_free(s->read_msgfds);
2867 s->read_msgfds = msgfds;
2868 s->read_msgfds_num = msgfds_num;
2871 for (i = 0; i < s->read_msgfds_num; i++) {
2872 int fd = s->read_msgfds[i];
2873 if (fd < 0) {
2874 continue;
2877 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2878 qemu_set_block(fd);
2880 #ifndef MSG_CMSG_CLOEXEC
2881 qemu_set_cloexec(fd);
2882 #endif
2885 return ret;
2888 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2890 TCPCharDriver *s = chr->opaque;
2891 return qio_channel_create_watch(s->ioc, cond);
2894 static void tcp_chr_free_connection(CharDriverState *chr)
2896 TCPCharDriver *s = chr->opaque;
2897 int i;
2899 if (!s->connected) {
2900 return;
2903 if (s->read_msgfds_num) {
2904 for (i = 0; i < s->read_msgfds_num; i++) {
2905 close(s->read_msgfds[i]);
2907 g_free(s->read_msgfds);
2908 s->read_msgfds = NULL;
2909 s->read_msgfds_num = 0;
2912 tcp_set_msgfds(chr, NULL, 0);
2913 remove_fd_in_watch(chr);
2914 object_unref(OBJECT(s->sioc));
2915 s->sioc = NULL;
2916 object_unref(OBJECT(s->ioc));
2917 s->ioc = NULL;
2918 g_free(chr->filename);
2919 chr->filename = NULL;
2920 s->connected = 0;
2923 static void tcp_chr_disconnect(CharDriverState *chr)
2925 TCPCharDriver *s = chr->opaque;
2927 if (!s->connected) {
2928 return;
2931 tcp_chr_free_connection(chr);
2933 if (s->listen_ioc) {
2934 s->listen_tag = qio_channel_add_watch(
2935 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
2937 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
2938 s->is_listen, s->is_telnet);
2939 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2940 if (s->reconnect_time) {
2941 qemu_chr_socket_restart_timer(chr);
2945 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2947 CharDriverState *chr = opaque;
2948 TCPCharDriver *s = chr->opaque;
2949 uint8_t buf[READ_BUF_LEN];
2950 int len, size;
2952 if (!s->connected || s->max_size <= 0) {
2953 return TRUE;
2955 len = sizeof(buf);
2956 if (len > s->max_size)
2957 len = s->max_size;
2958 size = tcp_chr_recv(chr, (void *)buf, len);
2959 if (size == 0 || size == -1) {
2960 /* connection closed */
2961 tcp_chr_disconnect(chr);
2962 } else if (size > 0) {
2963 if (s->do_telnetopt)
2964 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2965 if (size > 0)
2966 qemu_chr_be_write(chr, buf, size);
2969 return TRUE;
2972 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2974 TCPCharDriver *s = chr->opaque;
2975 int size;
2977 if (!s->connected) {
2978 return 0;
2981 size = tcp_chr_recv(chr, (void *) buf, len);
2982 if (size == 0) {
2983 /* connection closed */
2984 tcp_chr_disconnect(chr);
2987 return size;
2990 static void tcp_chr_connect(void *opaque)
2992 CharDriverState *chr = opaque;
2993 TCPCharDriver *s = chr->opaque;
2995 g_free(chr->filename);
2996 chr->filename = sockaddr_to_str(
2997 &s->sioc->localAddr, s->sioc->localAddrLen,
2998 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
2999 s->is_listen, s->is_telnet);
3001 s->connected = 1;
3002 if (s->ioc) {
3003 chr->fd_in_tag = io_add_watch_poll(s->ioc,
3004 tcp_chr_read_poll,
3005 tcp_chr_read,
3006 chr, NULL);
3008 qemu_chr_be_generic_open(chr);
3011 static void tcp_chr_update_read_handler(CharDriverState *chr,
3012 GMainContext *context)
3014 TCPCharDriver *s = chr->opaque;
3016 if (!s->connected) {
3017 return;
3020 remove_fd_in_watch(chr);
3021 if (s->ioc) {
3022 chr->fd_in_tag = io_add_watch_poll(s->ioc,
3023 tcp_chr_read_poll,
3024 tcp_chr_read, chr,
3025 context);
3029 typedef struct {
3030 CharDriverState *chr;
3031 char buf[12];
3032 size_t buflen;
3033 } TCPCharDriverTelnetInit;
3035 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
3036 GIOCondition cond G_GNUC_UNUSED,
3037 gpointer user_data)
3039 TCPCharDriverTelnetInit *init = user_data;
3040 ssize_t ret;
3042 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
3043 if (ret < 0) {
3044 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3045 ret = 0;
3046 } else {
3047 tcp_chr_disconnect(init->chr);
3048 return FALSE;
3051 init->buflen -= ret;
3053 if (init->buflen == 0) {
3054 tcp_chr_connect(init->chr);
3055 return FALSE;
3058 memmove(init->buf, init->buf + ret, init->buflen);
3060 return TRUE;
3063 static void tcp_chr_telnet_init(CharDriverState *chr)
3065 TCPCharDriver *s = chr->opaque;
3066 TCPCharDriverTelnetInit *init =
3067 g_new0(TCPCharDriverTelnetInit, 1);
3068 size_t n = 0;
3070 init->chr = chr;
3071 init->buflen = 12;
3073 #define IACSET(x, a, b, c) \
3074 do { \
3075 x[n++] = a; \
3076 x[n++] = b; \
3077 x[n++] = c; \
3078 } while (0)
3080 /* Prep the telnet negotion to put telnet in binary,
3081 * no echo, single char mode */
3082 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3083 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3084 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3085 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3087 #undef IACSET
3089 qio_channel_add_watch(
3090 s->ioc, G_IO_OUT,
3091 tcp_chr_telnet_init_io,
3092 init, NULL);
3096 static void tcp_chr_tls_handshake(Object *source,
3097 Error *err,
3098 gpointer user_data)
3100 CharDriverState *chr = user_data;
3101 TCPCharDriver *s = chr->opaque;
3103 if (err) {
3104 tcp_chr_disconnect(chr);
3105 } else {
3106 if (s->do_telnetopt) {
3107 tcp_chr_telnet_init(chr);
3108 } else {
3109 tcp_chr_connect(chr);
3115 static void tcp_chr_tls_init(CharDriverState *chr)
3117 TCPCharDriver *s = chr->opaque;
3118 QIOChannelTLS *tioc;
3119 Error *err = NULL;
3121 if (s->is_listen) {
3122 tioc = qio_channel_tls_new_server(
3123 s->ioc, s->tls_creds,
3124 NULL, /* XXX Use an ACL */
3125 &err);
3126 } else {
3127 tioc = qio_channel_tls_new_client(
3128 s->ioc, s->tls_creds,
3129 s->addr->u.inet.data->host,
3130 &err);
3132 if (tioc == NULL) {
3133 error_free(err);
3134 tcp_chr_disconnect(chr);
3136 object_unref(OBJECT(s->ioc));
3137 s->ioc = QIO_CHANNEL(tioc);
3139 qio_channel_tls_handshake(tioc,
3140 tcp_chr_tls_handshake,
3141 chr,
3142 NULL);
3146 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3148 TCPCharDriver *s = chr->opaque;
3149 if (s->ioc != NULL) {
3150 return -1;
3153 s->ioc = QIO_CHANNEL(sioc);
3154 object_ref(OBJECT(sioc));
3155 s->sioc = sioc;
3156 object_ref(OBJECT(sioc));
3158 qio_channel_set_blocking(s->ioc, false, NULL);
3160 if (s->do_nodelay) {
3161 qio_channel_set_delay(s->ioc, false);
3163 if (s->listen_tag) {
3164 g_source_remove(s->listen_tag);
3165 s->listen_tag = 0;
3168 if (s->tls_creds) {
3169 tcp_chr_tls_init(chr);
3170 } else {
3171 if (s->do_telnetopt) {
3172 tcp_chr_telnet_init(chr);
3173 } else {
3174 tcp_chr_connect(chr);
3178 return 0;
3182 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3184 int ret;
3185 QIOChannelSocket *sioc;
3187 sioc = qio_channel_socket_new_fd(fd, NULL);
3188 if (!sioc) {
3189 return -1;
3191 ret = tcp_chr_new_client(chr, sioc);
3192 object_unref(OBJECT(sioc));
3193 return ret;
3196 static gboolean tcp_chr_accept(QIOChannel *channel,
3197 GIOCondition cond,
3198 void *opaque)
3200 CharDriverState *chr = opaque;
3201 QIOChannelSocket *sioc;
3203 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3204 NULL);
3205 if (!sioc) {
3206 return TRUE;
3209 tcp_chr_new_client(chr, sioc);
3211 object_unref(OBJECT(sioc));
3213 return TRUE;
3216 static int tcp_chr_wait_connected(CharDriverState *chr, Error **errp)
3218 TCPCharDriver *s = chr->opaque;
3219 QIOChannelSocket *sioc;
3221 /* It can't wait on s->connected, since it is set asynchronously
3222 * in TLS and telnet cases, only wait for an accepted socket */
3223 while (!s->ioc) {
3224 if (s->is_listen) {
3225 fprintf(stderr, "QEMU waiting for connection on: %s\n",
3226 chr->filename);
3227 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), true, NULL);
3228 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
3229 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
3230 } else {
3231 sioc = qio_channel_socket_new();
3232 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3233 object_unref(OBJECT(sioc));
3234 return -1;
3236 tcp_chr_new_client(chr, sioc);
3237 object_unref(OBJECT(sioc));
3241 return 0;
3244 int qemu_chr_wait_connected(CharDriverState *chr, Error **errp)
3246 if (chr->chr_wait_connected) {
3247 return chr->chr_wait_connected(chr, errp);
3250 return 0;
3253 static void tcp_chr_close(CharDriverState *chr)
3255 TCPCharDriver *s = chr->opaque;
3257 tcp_chr_free_connection(chr);
3259 if (s->reconnect_timer) {
3260 g_source_remove(s->reconnect_timer);
3261 s->reconnect_timer = 0;
3263 qapi_free_SocketAddress(s->addr);
3264 if (s->listen_tag) {
3265 g_source_remove(s->listen_tag);
3266 s->listen_tag = 0;
3268 if (s->listen_ioc) {
3269 object_unref(OBJECT(s->listen_ioc));
3271 if (s->tls_creds) {
3272 object_unref(OBJECT(s->tls_creds));
3274 g_free(s);
3275 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3279 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3281 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3282 CharDriverState *chr = opaque;
3283 TCPCharDriver *s = chr->opaque;
3285 if (err) {
3286 check_report_connect_error(chr, err);
3287 object_unref(src);
3288 return;
3291 s->connect_err_reported = false;
3292 tcp_chr_new_client(chr, sioc);
3293 object_unref(OBJECT(sioc));
3297 /*********************************************************/
3298 /* Ring buffer chardev */
3300 typedef struct {
3301 size_t size;
3302 size_t prod;
3303 size_t cons;
3304 uint8_t *cbuf;
3305 } RingBufCharDriver;
3307 static size_t ringbuf_count(const CharDriverState *chr)
3309 const RingBufCharDriver *d = chr->opaque;
3311 return d->prod - d->cons;
3314 /* Called with chr_write_lock held. */
3315 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3317 RingBufCharDriver *d = chr->opaque;
3318 int i;
3320 if (!buf || (len < 0)) {
3321 return -1;
3324 for (i = 0; i < len; i++ ) {
3325 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3326 if (d->prod - d->cons > d->size) {
3327 d->cons = d->prod - d->size;
3331 return 0;
3334 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3336 RingBufCharDriver *d = chr->opaque;
3337 int i;
3339 qemu_mutex_lock(&chr->chr_write_lock);
3340 for (i = 0; i < len && d->cons != d->prod; i++) {
3341 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3343 qemu_mutex_unlock(&chr->chr_write_lock);
3345 return i;
3348 static void ringbuf_chr_close(struct CharDriverState *chr)
3350 RingBufCharDriver *d = chr->opaque;
3352 g_free(d->cbuf);
3353 g_free(d);
3354 chr->opaque = NULL;
3357 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3358 ChardevBackend *backend,
3359 ChardevReturn *ret,
3360 Error **errp)
3362 ChardevRingbuf *opts = backend->u.ringbuf.data;
3363 ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
3364 CharDriverState *chr;
3365 RingBufCharDriver *d;
3367 chr = qemu_chr_alloc(common, errp);
3368 if (!chr) {
3369 return NULL;
3371 d = g_malloc(sizeof(*d));
3373 d->size = opts->has_size ? opts->size : 65536;
3375 /* The size must be power of 2 */
3376 if (d->size & (d->size - 1)) {
3377 error_setg(errp, "size of ringbuf chardev must be power of two");
3378 goto fail;
3381 d->prod = 0;
3382 d->cons = 0;
3383 d->cbuf = g_malloc0(d->size);
3385 chr->opaque = d;
3386 chr->chr_write = ringbuf_chr_write;
3387 chr->chr_close = ringbuf_chr_close;
3389 return chr;
3391 fail:
3392 g_free(d);
3393 qemu_chr_free_common(chr);
3394 return NULL;
3397 bool chr_is_ringbuf(const CharDriverState *chr)
3399 return chr->chr_write == ringbuf_chr_write;
3402 void qmp_ringbuf_write(const char *device, const char *data,
3403 bool has_format, enum DataFormat format,
3404 Error **errp)
3406 CharDriverState *chr;
3407 const uint8_t *write_data;
3408 int ret;
3409 gsize write_count;
3411 chr = qemu_chr_find(device);
3412 if (!chr) {
3413 error_setg(errp, "Device '%s' not found", device);
3414 return;
3417 if (!chr_is_ringbuf(chr)) {
3418 error_setg(errp,"%s is not a ringbuf device", device);
3419 return;
3422 if (has_format && (format == DATA_FORMAT_BASE64)) {
3423 write_data = qbase64_decode(data, -1,
3424 &write_count,
3425 errp);
3426 if (!write_data) {
3427 return;
3429 } else {
3430 write_data = (uint8_t *)data;
3431 write_count = strlen(data);
3434 ret = ringbuf_chr_write(chr, write_data, write_count);
3436 if (write_data != (uint8_t *)data) {
3437 g_free((void *)write_data);
3440 if (ret < 0) {
3441 error_setg(errp, "Failed to write to device %s", device);
3442 return;
3446 char *qmp_ringbuf_read(const char *device, int64_t size,
3447 bool has_format, enum DataFormat format,
3448 Error **errp)
3450 CharDriverState *chr;
3451 uint8_t *read_data;
3452 size_t count;
3453 char *data;
3455 chr = qemu_chr_find(device);
3456 if (!chr) {
3457 error_setg(errp, "Device '%s' not found", device);
3458 return NULL;
3461 if (!chr_is_ringbuf(chr)) {
3462 error_setg(errp,"%s is not a ringbuf device", device);
3463 return NULL;
3466 if (size <= 0) {
3467 error_setg(errp, "size must be greater than zero");
3468 return NULL;
3471 count = ringbuf_count(chr);
3472 size = size > count ? count : size;
3473 read_data = g_malloc(size + 1);
3475 ringbuf_chr_read(chr, read_data, size);
3477 if (has_format && (format == DATA_FORMAT_BASE64)) {
3478 data = g_base64_encode(read_data, size);
3479 g_free(read_data);
3480 } else {
3482 * FIXME should read only complete, valid UTF-8 characters up
3483 * to @size bytes. Invalid sequences should be replaced by a
3484 * suitable replacement character. Except when (and only
3485 * when) ring buffer lost characters since last read, initial
3486 * continuation characters should be dropped.
3488 read_data[size] = 0;
3489 data = (char *)read_data;
3492 return data;
3495 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3497 char host[65], port[33], width[8], height[8];
3498 int pos;
3499 const char *p;
3500 QemuOpts *opts;
3501 Error *local_err = NULL;
3503 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3504 if (local_err) {
3505 error_report_err(local_err);
3506 return NULL;
3509 if (strstart(filename, "mon:", &p)) {
3510 filename = p;
3511 qemu_opt_set(opts, "mux", "on", &error_abort);
3512 if (strcmp(filename, "stdio") == 0) {
3513 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3514 * but pass it to the guest. Handle this only for compat syntax,
3515 * for -chardev syntax we have special option for this.
3516 * This is what -nographic did, redirecting+muxing serial+monitor
3517 * to stdio causing Ctrl+C to be passed to guest. */
3518 qemu_opt_set(opts, "signal", "off", &error_abort);
3522 if (strcmp(filename, "null") == 0 ||
3523 strcmp(filename, "pty") == 0 ||
3524 strcmp(filename, "msmouse") == 0 ||
3525 strcmp(filename, "braille") == 0 ||
3526 strcmp(filename, "testdev") == 0 ||
3527 strcmp(filename, "stdio") == 0) {
3528 qemu_opt_set(opts, "backend", filename, &error_abort);
3529 return opts;
3531 if (strstart(filename, "vc", &p)) {
3532 qemu_opt_set(opts, "backend", "vc", &error_abort);
3533 if (*p == ':') {
3534 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3535 /* pixels */
3536 qemu_opt_set(opts, "width", width, &error_abort);
3537 qemu_opt_set(opts, "height", height, &error_abort);
3538 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3539 /* chars */
3540 qemu_opt_set(opts, "cols", width, &error_abort);
3541 qemu_opt_set(opts, "rows", height, &error_abort);
3542 } else {
3543 goto fail;
3546 return opts;
3548 if (strcmp(filename, "con:") == 0) {
3549 qemu_opt_set(opts, "backend", "console", &error_abort);
3550 return opts;
3552 if (strstart(filename, "COM", NULL)) {
3553 qemu_opt_set(opts, "backend", "serial", &error_abort);
3554 qemu_opt_set(opts, "path", filename, &error_abort);
3555 return opts;
3557 if (strstart(filename, "file:", &p)) {
3558 qemu_opt_set(opts, "backend", "file", &error_abort);
3559 qemu_opt_set(opts, "path", p, &error_abort);
3560 return opts;
3562 if (strstart(filename, "pipe:", &p)) {
3563 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3564 qemu_opt_set(opts, "path", p, &error_abort);
3565 return opts;
3567 if (strstart(filename, "tcp:", &p) ||
3568 strstart(filename, "telnet:", &p)) {
3569 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3570 host[0] = 0;
3571 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3572 goto fail;
3574 qemu_opt_set(opts, "backend", "socket", &error_abort);
3575 qemu_opt_set(opts, "host", host, &error_abort);
3576 qemu_opt_set(opts, "port", port, &error_abort);
3577 if (p[pos] == ',') {
3578 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3579 if (local_err) {
3580 error_report_err(local_err);
3581 goto fail;
3584 if (strstart(filename, "telnet:", &p))
3585 qemu_opt_set(opts, "telnet", "on", &error_abort);
3586 return opts;
3588 if (strstart(filename, "udp:", &p)) {
3589 qemu_opt_set(opts, "backend", "udp", &error_abort);
3590 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3591 host[0] = 0;
3592 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3593 goto fail;
3596 qemu_opt_set(opts, "host", host, &error_abort);
3597 qemu_opt_set(opts, "port", port, &error_abort);
3598 if (p[pos] == '@') {
3599 p += pos + 1;
3600 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3601 host[0] = 0;
3602 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3603 goto fail;
3606 qemu_opt_set(opts, "localaddr", host, &error_abort);
3607 qemu_opt_set(opts, "localport", port, &error_abort);
3609 return opts;
3611 if (strstart(filename, "unix:", &p)) {
3612 qemu_opt_set(opts, "backend", "socket", &error_abort);
3613 qemu_opts_do_parse(opts, p, "path", &local_err);
3614 if (local_err) {
3615 error_report_err(local_err);
3616 goto fail;
3618 return opts;
3620 if (strstart(filename, "/dev/parport", NULL) ||
3621 strstart(filename, "/dev/ppi", NULL)) {
3622 qemu_opt_set(opts, "backend", "parport", &error_abort);
3623 qemu_opt_set(opts, "path", filename, &error_abort);
3624 return opts;
3626 if (strstart(filename, "/dev/", NULL)) {
3627 qemu_opt_set(opts, "backend", "tty", &error_abort);
3628 qemu_opt_set(opts, "path", filename, &error_abort);
3629 return opts;
3632 fail:
3633 qemu_opts_del(opts);
3634 return NULL;
3637 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3639 const char *logfile = qemu_opt_get(opts, "logfile");
3641 backend->has_logfile = logfile != NULL;
3642 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3644 backend->has_logappend = true;
3645 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3649 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3650 Error **errp)
3652 const char *path = qemu_opt_get(opts, "path");
3653 ChardevFile *file;
3655 if (path == NULL) {
3656 error_setg(errp, "chardev: file: no filename given");
3657 return;
3659 file = backend->u.file.data = g_new0(ChardevFile, 1);
3660 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3661 file->out = g_strdup(path);
3663 file->has_append = true;
3664 file->append = qemu_opt_get_bool(opts, "append", false);
3667 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3668 Error **errp)
3670 ChardevStdio *stdio;
3672 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3673 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3674 stdio->has_signal = true;
3675 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3678 #ifdef HAVE_CHARDEV_SERIAL
3679 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3680 Error **errp)
3682 const char *device = qemu_opt_get(opts, "path");
3683 ChardevHostdev *serial;
3685 if (device == NULL) {
3686 error_setg(errp, "chardev: serial/tty: no device path given");
3687 return;
3689 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3690 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3691 serial->device = g_strdup(device);
3693 #endif
3695 #ifdef HAVE_CHARDEV_PARPORT
3696 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3697 Error **errp)
3699 const char *device = qemu_opt_get(opts, "path");
3700 ChardevHostdev *parallel;
3702 if (device == NULL) {
3703 error_setg(errp, "chardev: parallel: no device path given");
3704 return;
3706 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3707 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3708 parallel->device = g_strdup(device);
3710 #endif
3712 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3713 Error **errp)
3715 const char *device = qemu_opt_get(opts, "path");
3716 ChardevHostdev *dev;
3718 if (device == NULL) {
3719 error_setg(errp, "chardev: pipe: no device path given");
3720 return;
3722 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3723 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3724 dev->device = g_strdup(device);
3727 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3728 Error **errp)
3730 int val;
3731 ChardevRingbuf *ringbuf;
3733 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3734 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3736 val = qemu_opt_get_size(opts, "size", 0);
3737 if (val != 0) {
3738 ringbuf->has_size = true;
3739 ringbuf->size = val;
3743 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3744 Error **errp)
3746 const char *chardev = qemu_opt_get(opts, "chardev");
3747 ChardevMux *mux;
3749 if (chardev == NULL) {
3750 error_setg(errp, "chardev: mux: no chardev given");
3751 return;
3753 mux = backend->u.mux.data = g_new0(ChardevMux, 1);
3754 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
3755 mux->chardev = g_strdup(chardev);
3758 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3759 Error **errp)
3761 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3762 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3763 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3764 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3765 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3766 const char *path = qemu_opt_get(opts, "path");
3767 const char *host = qemu_opt_get(opts, "host");
3768 const char *port = qemu_opt_get(opts, "port");
3769 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3770 SocketAddress *addr;
3771 ChardevSocket *sock;
3773 if (!path) {
3774 if (!host) {
3775 error_setg(errp, "chardev: socket: no host given");
3776 return;
3778 if (!port) {
3779 error_setg(errp, "chardev: socket: no port given");
3780 return;
3782 } else {
3783 if (tls_creds) {
3784 error_setg(errp, "TLS can only be used over TCP socket");
3785 return;
3789 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
3790 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
3792 sock->has_nodelay = true;
3793 sock->nodelay = do_nodelay;
3794 sock->has_server = true;
3795 sock->server = is_listen;
3796 sock->has_telnet = true;
3797 sock->telnet = is_telnet;
3798 sock->has_wait = true;
3799 sock->wait = is_waitconnect;
3800 sock->has_reconnect = true;
3801 sock->reconnect = reconnect;
3802 sock->tls_creds = g_strdup(tls_creds);
3804 addr = g_new0(SocketAddress, 1);
3805 if (path) {
3806 UnixSocketAddress *q_unix;
3807 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3808 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
3809 q_unix->path = g_strdup(path);
3810 } else {
3811 addr->type = SOCKET_ADDRESS_KIND_INET;
3812 addr->u.inet.data = g_new(InetSocketAddress, 1);
3813 *addr->u.inet.data = (InetSocketAddress) {
3814 .host = g_strdup(host),
3815 .port = g_strdup(port),
3816 .has_to = qemu_opt_get(opts, "to"),
3817 .to = qemu_opt_get_number(opts, "to", 0),
3818 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3819 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3820 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3821 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3824 sock->addr = addr;
3827 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3828 Error **errp)
3830 const char *host = qemu_opt_get(opts, "host");
3831 const char *port = qemu_opt_get(opts, "port");
3832 const char *localaddr = qemu_opt_get(opts, "localaddr");
3833 const char *localport = qemu_opt_get(opts, "localport");
3834 bool has_local = false;
3835 SocketAddress *addr;
3836 ChardevUdp *udp;
3838 if (host == NULL || strlen(host) == 0) {
3839 host = "localhost";
3841 if (port == NULL || strlen(port) == 0) {
3842 error_setg(errp, "chardev: udp: remote port not specified");
3843 return;
3845 if (localport == NULL || strlen(localport) == 0) {
3846 localport = "0";
3847 } else {
3848 has_local = true;
3850 if (localaddr == NULL || strlen(localaddr) == 0) {
3851 localaddr = "";
3852 } else {
3853 has_local = true;
3856 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
3857 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
3859 addr = g_new0(SocketAddress, 1);
3860 addr->type = SOCKET_ADDRESS_KIND_INET;
3861 addr->u.inet.data = g_new(InetSocketAddress, 1);
3862 *addr->u.inet.data = (InetSocketAddress) {
3863 .host = g_strdup(host),
3864 .port = g_strdup(port),
3865 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3866 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3867 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3868 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3870 udp->remote = addr;
3872 if (has_local) {
3873 udp->has_local = true;
3874 addr = g_new0(SocketAddress, 1);
3875 addr->type = SOCKET_ADDRESS_KIND_INET;
3876 addr->u.inet.data = g_new(InetSocketAddress, 1);
3877 *addr->u.inet.data = (InetSocketAddress) {
3878 .host = g_strdup(localaddr),
3879 .port = g_strdup(localport),
3881 udp->local = addr;
3885 typedef struct CharDriver {
3886 const char *name;
3887 ChardevBackendKind kind;
3888 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3889 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3890 ChardevReturn *ret, Error **errp);
3891 } CharDriver;
3893 static GSList *backends;
3895 void register_char_driver(const char *name, ChardevBackendKind kind,
3896 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3897 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3898 ChardevReturn *ret, Error **errp))
3900 CharDriver *s;
3902 s = g_malloc0(sizeof(*s));
3903 s->name = g_strdup(name);
3904 s->kind = kind;
3905 s->parse = parse;
3906 s->create = create;
3908 backends = g_slist_append(backends, s);
3911 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3912 void (*init)(struct CharDriverState *s),
3913 Error **errp)
3915 Error *local_err = NULL;
3916 CharDriver *cd;
3917 CharDriverState *chr;
3918 GSList *i;
3919 ChardevReturn *ret = NULL;
3920 ChardevBackend *backend;
3921 const char *id = qemu_opts_id(opts);
3922 char *bid = NULL;
3924 if (qemu_opt_get(opts, "backend") == NULL) {
3925 error_setg(errp, "chardev: \"%s\" missing backend",
3926 qemu_opts_id(opts));
3927 goto err;
3930 if (is_help_option(qemu_opt_get(opts, "backend"))) {
3931 fprintf(stderr, "Available chardev backend types:\n");
3932 for (i = backends; i; i = i->next) {
3933 cd = i->data;
3934 fprintf(stderr, "%s\n", cd->name);
3936 exit(!is_help_option(qemu_opt_get(opts, "backend")));
3939 if (id == NULL) {
3940 error_setg(errp, "chardev: no id specified");
3941 goto err;
3944 for (i = backends; i; i = i->next) {
3945 cd = i->data;
3947 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3948 break;
3951 if (i == NULL) {
3952 error_setg(errp, "chardev: backend \"%s\" not found",
3953 qemu_opt_get(opts, "backend"));
3954 goto err;
3957 backend = g_new0(ChardevBackend, 1);
3959 if (qemu_opt_get_bool(opts, "mux", 0)) {
3960 bid = g_strdup_printf("%s-base", id);
3963 chr = NULL;
3964 backend->type = cd->kind;
3965 if (cd->parse) {
3966 cd->parse(opts, backend, &local_err);
3967 if (local_err) {
3968 error_propagate(errp, local_err);
3969 goto qapi_out;
3971 } else {
3972 ChardevCommon *cc = g_new0(ChardevCommon, 1);
3973 qemu_chr_parse_common(opts, cc);
3974 backend->u.null.data = cc; /* Any ChardevCommon member would work */
3977 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3978 if (!ret) {
3979 goto qapi_out;
3982 if (bid) {
3983 qapi_free_ChardevBackend(backend);
3984 qapi_free_ChardevReturn(ret);
3985 backend = g_new0(ChardevBackend, 1);
3986 backend->u.mux.data = g_new0(ChardevMux, 1);
3987 backend->type = CHARDEV_BACKEND_KIND_MUX;
3988 backend->u.mux.data->chardev = g_strdup(bid);
3989 ret = qmp_chardev_add(id, backend, errp);
3990 if (!ret) {
3991 chr = qemu_chr_find(bid);
3992 qemu_chr_delete(chr);
3993 chr = NULL;
3994 goto qapi_out;
3998 chr = qemu_chr_find(id);
3999 chr->opts = opts;
4001 qapi_out:
4002 qapi_free_ChardevBackend(backend);
4003 qapi_free_ChardevReturn(ret);
4004 g_free(bid);
4005 return chr;
4007 err:
4008 qemu_opts_del(opts);
4009 return NULL;
4012 CharDriverState *qemu_chr_new_noreplay(const char *label, const char *filename,
4013 void (*init)(struct CharDriverState *s))
4015 const char *p;
4016 CharDriverState *chr;
4017 QemuOpts *opts;
4018 Error *err = NULL;
4020 if (strstart(filename, "chardev:", &p)) {
4021 return qemu_chr_find(p);
4024 opts = qemu_chr_parse_compat(label, filename);
4025 if (!opts)
4026 return NULL;
4028 chr = qemu_chr_new_from_opts(opts, init, &err);
4029 if (err) {
4030 error_report_err(err);
4032 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
4033 qemu_chr_fe_claim_no_fail(chr);
4034 monitor_init(chr, MONITOR_USE_READLINE);
4036 return chr;
4039 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
4041 CharDriverState *chr;
4042 chr = qemu_chr_new_noreplay(label, filename, init);
4043 if (chr) {
4044 chr->replay = replay_mode != REPLAY_MODE_NONE;
4045 if (chr->replay && chr->chr_ioctl) {
4046 fprintf(stderr,
4047 "Replay: ioctl is not supported for serial devices yet\n");
4049 replay_register_char_driver(chr);
4051 return chr;
4054 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
4056 if (chr->chr_set_echo) {
4057 chr->chr_set_echo(chr, echo);
4061 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
4063 if (chr->fe_open == fe_open) {
4064 return;
4066 chr->fe_open = fe_open;
4067 if (chr->chr_set_fe_open) {
4068 chr->chr_set_fe_open(chr, fe_open);
4072 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
4074 if (chr->chr_fe_event) {
4075 chr->chr_fe_event(chr, event);
4079 guint qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
4080 GIOFunc func, void *user_data)
4082 GSource *src;
4083 guint tag;
4085 if (s->chr_add_watch == NULL) {
4086 return 0;
4089 src = s->chr_add_watch(s, cond);
4090 if (!src) {
4091 return 0;
4094 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
4095 tag = g_source_attach(src, NULL);
4096 g_source_unref(src);
4098 return tag;
4101 int qemu_chr_fe_claim(CharDriverState *s)
4103 if (s->avail_connections < 1) {
4104 return -1;
4106 s->avail_connections--;
4107 return 0;
4110 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
4112 if (qemu_chr_fe_claim(s) != 0) {
4113 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
4114 __func__, s->label);
4115 exit(1);
4119 void qemu_chr_fe_release(CharDriverState *s)
4121 s->avail_connections++;
4124 void qemu_chr_disconnect(CharDriverState *chr)
4126 if (chr->chr_disconnect) {
4127 chr->chr_disconnect(chr);
4131 static void qemu_chr_free_common(CharDriverState *chr)
4133 g_free(chr->filename);
4134 g_free(chr->label);
4135 qemu_opts_del(chr->opts);
4136 if (chr->logfd != -1) {
4137 close(chr->logfd);
4139 qemu_mutex_destroy(&chr->chr_write_lock);
4140 g_free(chr);
4143 void qemu_chr_free(CharDriverState *chr)
4145 if (chr->chr_close) {
4146 chr->chr_close(chr);
4148 qemu_chr_free_common(chr);
4151 void qemu_chr_delete(CharDriverState *chr)
4153 QTAILQ_REMOVE(&chardevs, chr, next);
4154 qemu_chr_free(chr);
4157 ChardevInfoList *qmp_query_chardev(Error **errp)
4159 ChardevInfoList *chr_list = NULL;
4160 CharDriverState *chr;
4162 QTAILQ_FOREACH(chr, &chardevs, next) {
4163 ChardevInfoList *info = g_malloc0(sizeof(*info));
4164 info->value = g_malloc0(sizeof(*info->value));
4165 info->value->label = g_strdup(chr->label);
4166 info->value->filename = g_strdup(chr->filename);
4167 info->value->frontend_open = chr->fe_open;
4169 info->next = chr_list;
4170 chr_list = info;
4173 return chr_list;
4176 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4178 ChardevBackendInfoList *backend_list = NULL;
4179 CharDriver *c = NULL;
4180 GSList *i = NULL;
4182 for (i = backends; i; i = i->next) {
4183 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4184 c = i->data;
4185 info->value = g_malloc0(sizeof(*info->value));
4186 info->value->name = g_strdup(c->name);
4188 info->next = backend_list;
4189 backend_list = info;
4192 return backend_list;
4195 CharDriverState *qemu_chr_find(const char *name)
4197 CharDriverState *chr;
4199 QTAILQ_FOREACH(chr, &chardevs, next) {
4200 if (strcmp(chr->label, name) != 0)
4201 continue;
4202 return chr;
4204 return NULL;
4207 QemuOptsList qemu_chardev_opts = {
4208 .name = "chardev",
4209 .implied_opt_name = "backend",
4210 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4211 .desc = {
4213 .name = "backend",
4214 .type = QEMU_OPT_STRING,
4216 .name = "path",
4217 .type = QEMU_OPT_STRING,
4219 .name = "host",
4220 .type = QEMU_OPT_STRING,
4222 .name = "port",
4223 .type = QEMU_OPT_STRING,
4225 .name = "localaddr",
4226 .type = QEMU_OPT_STRING,
4228 .name = "localport",
4229 .type = QEMU_OPT_STRING,
4231 .name = "to",
4232 .type = QEMU_OPT_NUMBER,
4234 .name = "ipv4",
4235 .type = QEMU_OPT_BOOL,
4237 .name = "ipv6",
4238 .type = QEMU_OPT_BOOL,
4240 .name = "wait",
4241 .type = QEMU_OPT_BOOL,
4243 .name = "server",
4244 .type = QEMU_OPT_BOOL,
4246 .name = "delay",
4247 .type = QEMU_OPT_BOOL,
4249 .name = "reconnect",
4250 .type = QEMU_OPT_NUMBER,
4252 .name = "telnet",
4253 .type = QEMU_OPT_BOOL,
4255 .name = "tls-creds",
4256 .type = QEMU_OPT_STRING,
4258 .name = "width",
4259 .type = QEMU_OPT_NUMBER,
4261 .name = "height",
4262 .type = QEMU_OPT_NUMBER,
4264 .name = "cols",
4265 .type = QEMU_OPT_NUMBER,
4267 .name = "rows",
4268 .type = QEMU_OPT_NUMBER,
4270 .name = "mux",
4271 .type = QEMU_OPT_BOOL,
4273 .name = "signal",
4274 .type = QEMU_OPT_BOOL,
4276 .name = "name",
4277 .type = QEMU_OPT_STRING,
4279 .name = "debug",
4280 .type = QEMU_OPT_NUMBER,
4282 .name = "size",
4283 .type = QEMU_OPT_SIZE,
4285 .name = "chardev",
4286 .type = QEMU_OPT_STRING,
4288 .name = "append",
4289 .type = QEMU_OPT_BOOL,
4291 .name = "logfile",
4292 .type = QEMU_OPT_STRING,
4294 .name = "logappend",
4295 .type = QEMU_OPT_BOOL,
4297 { /* end of list */ }
4301 #ifdef _WIN32
4303 static CharDriverState *qmp_chardev_open_file(const char *id,
4304 ChardevBackend *backend,
4305 ChardevReturn *ret,
4306 Error **errp)
4308 ChardevFile *file = backend->u.file.data;
4309 ChardevCommon *common = qapi_ChardevFile_base(file);
4310 HANDLE out;
4311 DWORD accessmode;
4312 DWORD flags;
4314 if (file->has_in) {
4315 error_setg(errp, "input file not supported");
4316 return NULL;
4319 if (file->has_append && file->append) {
4320 /* Append to file if it already exists. */
4321 accessmode = FILE_GENERIC_WRITE & ~FILE_WRITE_DATA;
4322 flags = OPEN_ALWAYS;
4323 } else {
4324 /* Truncate file if it already exists. */
4325 accessmode = GENERIC_WRITE;
4326 flags = CREATE_ALWAYS;
4329 out = CreateFile(file->out, accessmode, FILE_SHARE_READ, NULL, flags,
4330 FILE_ATTRIBUTE_NORMAL, NULL);
4331 if (out == INVALID_HANDLE_VALUE) {
4332 error_setg(errp, "open %s failed", file->out);
4333 return NULL;
4335 return qemu_chr_open_win_file(out, common, errp);
4338 static CharDriverState *qmp_chardev_open_serial(const char *id,
4339 ChardevBackend *backend,
4340 ChardevReturn *ret,
4341 Error **errp)
4343 ChardevHostdev *serial = backend->u.serial.data;
4344 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4345 return qemu_chr_open_win_path(serial->device, common, errp);
4348 #else /* WIN32 */
4350 static int qmp_chardev_open_file_source(char *src, int flags,
4351 Error **errp)
4353 int fd = -1;
4355 TFR(fd = qemu_open(src, flags, 0666));
4356 if (fd == -1) {
4357 error_setg_file_open(errp, errno, src);
4359 return fd;
4362 static CharDriverState *qmp_chardev_open_file(const char *id,
4363 ChardevBackend *backend,
4364 ChardevReturn *ret,
4365 Error **errp)
4367 ChardevFile *file = backend->u.file.data;
4368 ChardevCommon *common = qapi_ChardevFile_base(file);
4369 int flags, in = -1, out;
4371 flags = O_WRONLY | O_CREAT | O_BINARY;
4372 if (file->has_append && file->append) {
4373 flags |= O_APPEND;
4374 } else {
4375 flags |= O_TRUNC;
4378 out = qmp_chardev_open_file_source(file->out, flags, errp);
4379 if (out < 0) {
4380 return NULL;
4383 if (file->has_in) {
4384 flags = O_RDONLY;
4385 in = qmp_chardev_open_file_source(file->in, flags, errp);
4386 if (in < 0) {
4387 qemu_close(out);
4388 return NULL;
4392 return qemu_chr_open_fd(in, out, common, errp);
4395 #ifdef HAVE_CHARDEV_SERIAL
4396 static CharDriverState *qmp_chardev_open_serial(const char *id,
4397 ChardevBackend *backend,
4398 ChardevReturn *ret,
4399 Error **errp)
4401 ChardevHostdev *serial = backend->u.serial.data;
4402 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4403 int fd;
4405 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4406 if (fd < 0) {
4407 return NULL;
4409 qemu_set_nonblock(fd);
4410 return qemu_chr_open_tty_fd(fd, common, errp);
4412 #endif
4414 #ifdef HAVE_CHARDEV_PARPORT
4415 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4416 ChardevBackend *backend,
4417 ChardevReturn *ret,
4418 Error **errp)
4420 ChardevHostdev *parallel = backend->u.parallel.data;
4421 ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
4422 int fd;
4424 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4425 if (fd < 0) {
4426 return NULL;
4428 return qemu_chr_open_pp_fd(fd, common, errp);
4430 #endif
4432 #endif /* WIN32 */
4434 static gboolean socket_reconnect_timeout(gpointer opaque)
4436 CharDriverState *chr = opaque;
4437 TCPCharDriver *s = chr->opaque;
4438 QIOChannelSocket *sioc;
4440 s->reconnect_timer = 0;
4442 if (chr->be_open) {
4443 return false;
4446 sioc = qio_channel_socket_new();
4447 qio_channel_socket_connect_async(sioc, s->addr,
4448 qemu_chr_socket_connected,
4449 chr, NULL);
4451 return false;
4454 static CharDriverState *qmp_chardev_open_socket(const char *id,
4455 ChardevBackend *backend,
4456 ChardevReturn *ret,
4457 Error **errp)
4459 CharDriverState *chr;
4460 TCPCharDriver *s;
4461 ChardevSocket *sock = backend->u.socket.data;
4462 SocketAddress *addr = sock->addr;
4463 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4464 bool is_listen = sock->has_server ? sock->server : true;
4465 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4466 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4467 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4468 ChardevCommon *common = qapi_ChardevSocket_base(sock);
4469 QIOChannelSocket *sioc = NULL;
4471 chr = qemu_chr_alloc(common, errp);
4472 if (!chr) {
4473 return NULL;
4475 s = g_new0(TCPCharDriver, 1);
4477 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4478 s->is_listen = is_listen;
4479 s->is_telnet = is_telnet;
4480 s->do_nodelay = do_nodelay;
4481 if (sock->tls_creds) {
4482 Object *creds;
4483 creds = object_resolve_path_component(
4484 object_get_objects_root(), sock->tls_creds);
4485 if (!creds) {
4486 error_setg(errp, "No TLS credentials with id '%s'",
4487 sock->tls_creds);
4488 goto error;
4490 s->tls_creds = (QCryptoTLSCreds *)
4491 object_dynamic_cast(creds,
4492 TYPE_QCRYPTO_TLS_CREDS);
4493 if (!s->tls_creds) {
4494 error_setg(errp, "Object with id '%s' is not TLS credentials",
4495 sock->tls_creds);
4496 goto error;
4498 object_ref(OBJECT(s->tls_creds));
4499 if (is_listen) {
4500 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4501 error_setg(errp, "%s",
4502 "Expected TLS credentials for server endpoint");
4503 goto error;
4505 } else {
4506 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4507 error_setg(errp, "%s",
4508 "Expected TLS credentials for client endpoint");
4509 goto error;
4514 s->addr = QAPI_CLONE(SocketAddress, sock->addr);
4516 chr->opaque = s;
4517 chr->chr_wait_connected = tcp_chr_wait_connected;
4518 chr->chr_write = tcp_chr_write;
4519 chr->chr_sync_read = tcp_chr_sync_read;
4520 chr->chr_close = tcp_chr_close;
4521 chr->chr_disconnect = tcp_chr_disconnect;
4522 chr->get_msgfds = tcp_get_msgfds;
4523 chr->set_msgfds = tcp_set_msgfds;
4524 chr->chr_add_client = tcp_chr_add_client;
4525 chr->chr_add_watch = tcp_chr_add_watch;
4526 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4527 /* be isn't opened until we get a connection */
4528 chr->explicit_be_open = true;
4530 chr->filename = SocketAddress_to_str("disconnected:",
4531 addr, is_listen, is_telnet);
4533 if (is_listen) {
4534 if (is_telnet) {
4535 s->do_telnetopt = 1;
4537 } else if (reconnect > 0) {
4538 s->reconnect_time = reconnect;
4541 if (s->reconnect_time) {
4542 sioc = qio_channel_socket_new();
4543 qio_channel_socket_connect_async(sioc, s->addr,
4544 qemu_chr_socket_connected,
4545 chr, NULL);
4546 } else {
4547 if (s->is_listen) {
4548 sioc = qio_channel_socket_new();
4549 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4550 goto error;
4552 s->listen_ioc = sioc;
4553 if (is_waitconnect &&
4554 qemu_chr_wait_connected(chr, errp) < 0) {
4555 goto error;
4557 if (!s->ioc) {
4558 s->listen_tag = qio_channel_add_watch(
4559 QIO_CHANNEL(s->listen_ioc), G_IO_IN,
4560 tcp_chr_accept, chr, NULL);
4562 } else if (qemu_chr_wait_connected(chr, errp) < 0) {
4563 goto error;
4567 return chr;
4569 error:
4570 if (sioc) {
4571 object_unref(OBJECT(sioc));
4573 if (s->tls_creds) {
4574 object_unref(OBJECT(s->tls_creds));
4576 g_free(s);
4577 qemu_chr_free_common(chr);
4578 return NULL;
4581 static CharDriverState *qmp_chardev_open_udp(const char *id,
4582 ChardevBackend *backend,
4583 ChardevReturn *ret,
4584 Error **errp)
4586 ChardevUdp *udp = backend->u.udp.data;
4587 ChardevCommon *common = qapi_ChardevUdp_base(udp);
4588 QIOChannelSocket *sioc = qio_channel_socket_new();
4590 if (qio_channel_socket_dgram_sync(sioc,
4591 udp->local, udp->remote,
4592 errp) < 0) {
4593 object_unref(OBJECT(sioc));
4594 return NULL;
4596 return qemu_chr_open_udp(sioc, common, errp);
4599 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4600 Error **errp)
4602 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4603 CharDriverState *chr = NULL;
4604 Error *local_err = NULL;
4605 GSList *i;
4606 CharDriver *cd;
4608 chr = qemu_chr_find(id);
4609 if (chr) {
4610 error_setg(errp, "Chardev '%s' already exists", id);
4611 g_free(ret);
4612 return NULL;
4615 for (i = backends; i; i = i->next) {
4616 cd = i->data;
4618 if (cd->kind == backend->type) {
4619 chr = cd->create(id, backend, ret, &local_err);
4620 if (local_err) {
4621 error_propagate(errp, local_err);
4622 goto out_error;
4624 break;
4628 if (chr == NULL) {
4629 assert(!i);
4630 error_setg(errp, "chardev backend not available");
4631 goto out_error;
4634 chr->label = g_strdup(id);
4635 chr->avail_connections =
4636 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4637 if (!chr->filename) {
4638 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4640 if (!chr->explicit_be_open) {
4641 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4643 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4644 return ret;
4646 out_error:
4647 g_free(ret);
4648 return NULL;
4651 void qmp_chardev_remove(const char *id, Error **errp)
4653 CharDriverState *chr;
4655 chr = qemu_chr_find(id);
4656 if (chr == NULL) {
4657 error_setg(errp, "Chardev '%s' not found", id);
4658 return;
4660 if (chr->chr_can_read || chr->chr_read ||
4661 chr->chr_event || chr->handler_opaque) {
4662 error_setg(errp, "Chardev '%s' is busy", id);
4663 return;
4665 if (chr->replay) {
4666 error_setg(errp,
4667 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4668 return;
4670 qemu_chr_delete(chr);
4673 void qemu_chr_cleanup(void)
4675 CharDriverState *chr, *tmp;
4677 QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
4678 qemu_chr_delete(chr);
4682 static void register_types(void)
4684 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4685 qemu_chr_open_null);
4686 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4687 qemu_chr_parse_socket, qmp_chardev_open_socket);
4688 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4689 qmp_chardev_open_udp);
4690 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4691 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4692 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4693 qemu_chr_parse_file_out, qmp_chardev_open_file);
4694 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4695 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4696 #if defined HAVE_CHARDEV_SERIAL
4697 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4698 qemu_chr_parse_serial, qmp_chardev_open_serial);
4699 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4700 qemu_chr_parse_serial, qmp_chardev_open_serial);
4701 #endif
4702 #ifdef HAVE_CHARDEV_PARPORT
4703 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4704 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4705 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4706 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4707 #endif
4708 #ifdef HAVE_CHARDEV_PTY
4709 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4710 qemu_chr_open_pty);
4711 #endif
4712 #ifdef _WIN32
4713 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4714 qemu_chr_open_win_con);
4715 #endif
4716 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4717 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4718 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4719 qemu_chr_open_mux);
4720 /* Bug-compatibility: */
4721 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4722 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4723 /* this must be done after machine init, since we register FEs with muxes
4724 * as part of realize functions like serial_isa_realizefn when -nographic
4725 * is specified
4727 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4730 type_init(register_types);