cutils: Move buffer_is_zero and subroutines to a new file
[qemu/ar7.git] / qemu-char.c
blob7fa87a8b6eeacd3f9a2a5d631a283c597e4f409e
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(CharDriverState *s,
453 IOCanReadHandler *fd_can_read,
454 IOReadHandler *fd_read,
455 IOEventHandler *fd_event,
456 void *opaque)
458 int fe_open;
460 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
461 fe_open = 0;
462 remove_fd_in_watch(s);
463 } else {
464 fe_open = 1;
466 s->chr_can_read = fd_can_read;
467 s->chr_read = fd_read;
468 s->chr_event = fd_event;
469 s->handler_opaque = opaque;
470 if (fe_open && s->chr_update_read_handler)
471 s->chr_update_read_handler(s);
473 if (!s->explicit_fe_open) {
474 qemu_chr_fe_set_open(s, fe_open);
477 /* We're connecting to an already opened device, so let's make sure we
478 also get the open event */
479 if (fe_open && s->be_open) {
480 qemu_chr_be_generic_open(s);
484 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
486 return len;
489 static CharDriverState *qemu_chr_open_null(const char *id,
490 ChardevBackend *backend,
491 ChardevReturn *ret,
492 Error **errp)
494 CharDriverState *chr;
495 ChardevCommon *common = backend->u.null.data;
497 chr = qemu_chr_alloc(common, errp);
498 if (!chr) {
499 return NULL;
501 chr->chr_write = null_chr_write;
502 chr->explicit_be_open = true;
503 return chr;
506 /* MUX driver for serial I/O splitting */
507 #define MAX_MUX 4
508 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
509 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
510 typedef struct {
511 IOCanReadHandler *chr_can_read[MAX_MUX];
512 IOReadHandler *chr_read[MAX_MUX];
513 IOEventHandler *chr_event[MAX_MUX];
514 void *ext_opaque[MAX_MUX];
515 CharDriverState *drv;
516 int focus;
517 int mux_cnt;
518 int term_got_escape;
519 int max_size;
520 /* Intermediate input buffer allows to catch escape sequences even if the
521 currently active device is not accepting any input - but only until it
522 is full as well. */
523 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
524 int prod[MAX_MUX];
525 int cons[MAX_MUX];
526 int timestamps;
528 /* Protected by the CharDriverState chr_write_lock. */
529 int linestart;
530 int64_t timestamps_start;
531 } MuxDriver;
534 /* Called with chr_write_lock held. */
535 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
537 MuxDriver *d = chr->opaque;
538 int ret;
539 if (!d->timestamps) {
540 ret = qemu_chr_fe_write(d->drv, buf, len);
541 } else {
542 int i;
544 ret = 0;
545 for (i = 0; i < len; i++) {
546 if (d->linestart) {
547 char buf1[64];
548 int64_t ti;
549 int secs;
551 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
552 if (d->timestamps_start == -1)
553 d->timestamps_start = ti;
554 ti -= d->timestamps_start;
555 secs = ti / 1000;
556 snprintf(buf1, sizeof(buf1),
557 "[%02d:%02d:%02d.%03d] ",
558 secs / 3600,
559 (secs / 60) % 60,
560 secs % 60,
561 (int)(ti % 1000));
562 /* XXX this blocks entire thread. Rewrite to use
563 * qemu_chr_fe_write and background I/O callbacks */
564 qemu_chr_fe_write_all(d->drv, (uint8_t *)buf1, strlen(buf1));
565 d->linestart = 0;
567 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
568 if (buf[i] == '\n') {
569 d->linestart = 1;
573 return ret;
576 static const char * const mux_help[] = {
577 "% h print this help\n\r",
578 "% x exit emulator\n\r",
579 "% s save disk data back to file (if -snapshot)\n\r",
580 "% t toggle console timestamps\n\r",
581 "% b send break (magic sysrq)\n\r",
582 "% c switch between console and monitor\n\r",
583 "% % sends %\n\r",
584 NULL
587 int term_escape_char = 0x01; /* ctrl-a is used for escape */
588 static void mux_print_help(CharDriverState *chr)
590 int i, j;
591 char ebuf[15] = "Escape-Char";
592 char cbuf[50] = "\n\r";
594 if (term_escape_char > 0 && term_escape_char < 26) {
595 snprintf(cbuf, sizeof(cbuf), "\n\r");
596 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
597 } else {
598 snprintf(cbuf, sizeof(cbuf),
599 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
600 term_escape_char);
602 /* XXX this blocks entire thread. Rewrite to use
603 * qemu_chr_fe_write and background I/O callbacks */
604 qemu_chr_fe_write_all(chr, (uint8_t *)cbuf, strlen(cbuf));
605 for (i = 0; mux_help[i] != NULL; i++) {
606 for (j=0; mux_help[i][j] != '\0'; j++) {
607 if (mux_help[i][j] == '%')
608 qemu_chr_fe_write_all(chr, (uint8_t *)ebuf, strlen(ebuf));
609 else
610 qemu_chr_fe_write_all(chr, (uint8_t *)&mux_help[i][j], 1);
615 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
617 if (d->chr_event[mux_nr])
618 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
621 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
623 if (d->term_got_escape) {
624 d->term_got_escape = 0;
625 if (ch == term_escape_char)
626 goto send_char;
627 switch(ch) {
628 case '?':
629 case 'h':
630 mux_print_help(chr);
631 break;
632 case 'x':
634 const char *term = "QEMU: Terminated\n\r";
635 qemu_chr_fe_write_all(chr, (uint8_t *)term, strlen(term));
636 exit(0);
637 break;
639 case 's':
640 blk_commit_all();
641 break;
642 case 'b':
643 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
644 break;
645 case 'c':
646 /* Switch to the next registered device */
647 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
648 d->focus++;
649 if (d->focus >= d->mux_cnt)
650 d->focus = 0;
651 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
652 break;
653 case 't':
654 d->timestamps = !d->timestamps;
655 d->timestamps_start = -1;
656 d->linestart = 0;
657 break;
659 } else if (ch == term_escape_char) {
660 d->term_got_escape = 1;
661 } else {
662 send_char:
663 return 1;
665 return 0;
668 static void mux_chr_accept_input(CharDriverState *chr)
670 MuxDriver *d = chr->opaque;
671 int m = d->focus;
673 while (d->prod[m] != d->cons[m] &&
674 d->chr_can_read[m] &&
675 d->chr_can_read[m](d->ext_opaque[m])) {
676 d->chr_read[m](d->ext_opaque[m],
677 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
681 static int mux_chr_can_read(void *opaque)
683 CharDriverState *chr = opaque;
684 MuxDriver *d = chr->opaque;
685 int m = d->focus;
687 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
688 return 1;
689 if (d->chr_can_read[m])
690 return d->chr_can_read[m](d->ext_opaque[m]);
691 return 0;
694 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
696 CharDriverState *chr = opaque;
697 MuxDriver *d = chr->opaque;
698 int m = d->focus;
699 int i;
701 mux_chr_accept_input (opaque);
703 for(i = 0; i < size; i++)
704 if (mux_proc_byte(chr, d, buf[i])) {
705 if (d->prod[m] == d->cons[m] &&
706 d->chr_can_read[m] &&
707 d->chr_can_read[m](d->ext_opaque[m]))
708 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
709 else
710 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
714 static void mux_chr_event(void *opaque, int event)
716 CharDriverState *chr = opaque;
717 MuxDriver *d = chr->opaque;
718 int i;
720 /* Send the event to all registered listeners */
721 for (i = 0; i < d->mux_cnt; i++)
722 mux_chr_send_event(d, i, event);
725 static void mux_chr_update_read_handler(CharDriverState *chr)
727 MuxDriver *d = chr->opaque;
729 if (d->mux_cnt >= MAX_MUX) {
730 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
731 return;
733 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
734 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
735 d->chr_read[d->mux_cnt] = chr->chr_read;
736 d->chr_event[d->mux_cnt] = chr->chr_event;
737 /* Fix up the real driver with mux routines */
738 if (d->mux_cnt == 0) {
739 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
740 mux_chr_event, chr);
742 if (d->focus != -1) {
743 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
745 d->focus = d->mux_cnt;
746 d->mux_cnt++;
747 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
750 static bool muxes_realized;
753 * Called after processing of default and command-line-specified
754 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
755 * to a mux chardev. This is done here to ensure that
756 * output/prompts/banners are only displayed for the FE that has
757 * focus when initial command-line processing/machine init is
758 * completed.
760 * After this point, any new FE attached to any new or existing
761 * mux will receive CHR_EVENT_OPENED notifications for the BE
762 * immediately.
764 static void muxes_realize_done(Notifier *notifier, void *unused)
766 CharDriverState *chr;
768 QTAILQ_FOREACH(chr, &chardevs, next) {
769 if (chr->is_mux) {
770 MuxDriver *d = chr->opaque;
771 int i;
773 /* send OPENED to all already-attached FEs */
774 for (i = 0; i < d->mux_cnt; i++) {
775 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
777 /* mark mux as OPENED so any new FEs will immediately receive
778 * OPENED event
780 qemu_chr_be_generic_open(chr);
783 muxes_realized = true;
786 static Notifier muxes_realize_notify = {
787 .notify = muxes_realize_done,
790 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
792 MuxDriver *d = s->opaque;
793 return d->drv->chr_add_watch(d->drv, cond);
796 static void mux_chr_close(struct CharDriverState *chr)
798 MuxDriver *d = chr->opaque;
800 g_free(d);
803 static CharDriverState *qemu_chr_open_mux(const char *id,
804 ChardevBackend *backend,
805 ChardevReturn *ret, Error **errp)
807 ChardevMux *mux = backend->u.mux.data;
808 CharDriverState *chr, *drv;
809 MuxDriver *d;
810 ChardevCommon *common = qapi_ChardevMux_base(mux);
812 drv = qemu_chr_find(mux->chardev);
813 if (drv == NULL) {
814 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
815 return NULL;
818 chr = qemu_chr_alloc(common, errp);
819 if (!chr) {
820 return NULL;
822 d = g_new0(MuxDriver, 1);
824 chr->opaque = d;
825 d->drv = drv;
826 d->focus = -1;
827 chr->chr_close = mux_chr_close;
828 chr->chr_write = mux_chr_write;
829 chr->chr_update_read_handler = mux_chr_update_read_handler;
830 chr->chr_accept_input = mux_chr_accept_input;
831 /* Frontend guest-open / -close notification is not support with muxes */
832 chr->chr_set_fe_open = NULL;
833 if (drv->chr_add_watch) {
834 chr->chr_add_watch = mux_chr_add_watch;
836 /* only default to opened state if we've realized the initial
837 * set of muxes
839 chr->explicit_be_open = muxes_realized ? 0 : 1;
840 chr->is_mux = 1;
842 return chr;
846 typedef struct IOWatchPoll
848 GSource parent;
850 QIOChannel *ioc;
851 GSource *src;
853 IOCanReadHandler *fd_can_read;
854 GSourceFunc fd_read;
855 void *opaque;
856 } IOWatchPoll;
858 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
860 return container_of(source, IOWatchPoll, parent);
863 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
865 IOWatchPoll *iwp = io_watch_poll_from_source(source);
866 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
867 bool was_active = iwp->src != NULL;
868 if (was_active == now_active) {
869 return FALSE;
872 if (now_active) {
873 iwp->src = qio_channel_create_watch(
874 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
875 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
876 g_source_attach(iwp->src, NULL);
877 } else {
878 g_source_destroy(iwp->src);
879 g_source_unref(iwp->src);
880 iwp->src = NULL;
882 return FALSE;
885 static gboolean io_watch_poll_check(GSource *source)
887 return FALSE;
890 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
891 gpointer user_data)
893 abort();
896 static void io_watch_poll_finalize(GSource *source)
898 /* Due to a glib bug, removing the last reference to a source
899 * inside a finalize callback causes recursive locking (and a
900 * deadlock). This is not a problem inside other callbacks,
901 * including dispatch callbacks, so we call io_remove_watch_poll
902 * to remove this source. At this point, iwp->src must
903 * be NULL, or we would leak it.
905 * This would be solved much more elegantly by child sources,
906 * but we support older glib versions that do not have them.
908 IOWatchPoll *iwp = io_watch_poll_from_source(source);
909 assert(iwp->src == NULL);
912 static GSourceFuncs io_watch_poll_funcs = {
913 .prepare = io_watch_poll_prepare,
914 .check = io_watch_poll_check,
915 .dispatch = io_watch_poll_dispatch,
916 .finalize = io_watch_poll_finalize,
919 /* Can only be used for read */
920 static guint io_add_watch_poll(QIOChannel *ioc,
921 IOCanReadHandler *fd_can_read,
922 QIOChannelFunc fd_read,
923 gpointer user_data)
925 IOWatchPoll *iwp;
926 int tag;
928 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
929 iwp->fd_can_read = fd_can_read;
930 iwp->opaque = user_data;
931 iwp->ioc = ioc;
932 iwp->fd_read = (GSourceFunc) fd_read;
933 iwp->src = NULL;
935 tag = g_source_attach(&iwp->parent, NULL);
936 g_source_unref(&iwp->parent);
937 return tag;
940 static void io_remove_watch_poll(guint tag)
942 GSource *source;
943 IOWatchPoll *iwp;
945 g_return_if_fail (tag > 0);
947 source = g_main_context_find_source_by_id(NULL, tag);
948 g_return_if_fail (source != NULL);
950 iwp = io_watch_poll_from_source(source);
951 if (iwp->src) {
952 g_source_destroy(iwp->src);
953 g_source_unref(iwp->src);
954 iwp->src = NULL;
956 g_source_destroy(&iwp->parent);
959 static void remove_fd_in_watch(CharDriverState *chr)
961 if (chr->fd_in_tag) {
962 io_remove_watch_poll(chr->fd_in_tag);
963 chr->fd_in_tag = 0;
968 static int io_channel_send_full(QIOChannel *ioc,
969 const void *buf, size_t len,
970 int *fds, size_t nfds)
972 size_t offset = 0;
974 while (offset < len) {
975 ssize_t ret = 0;
976 struct iovec iov = { .iov_base = (char *)buf + offset,
977 .iov_len = len - offset };
979 ret = qio_channel_writev_full(
980 ioc, &iov, 1,
981 fds, nfds, NULL);
982 if (ret == QIO_CHANNEL_ERR_BLOCK) {
983 if (offset) {
984 return offset;
987 errno = EAGAIN;
988 return -1;
989 } else if (ret < 0) {
990 errno = EINVAL;
991 return -1;
994 offset += ret;
997 return offset;
1001 #ifndef _WIN32
1002 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
1004 return io_channel_send_full(ioc, buf, len, NULL, 0);
1008 typedef struct FDCharDriver {
1009 CharDriverState *chr;
1010 QIOChannel *ioc_in, *ioc_out;
1011 int max_size;
1012 } FDCharDriver;
1014 /* Called with chr_write_lock held. */
1015 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1017 FDCharDriver *s = chr->opaque;
1019 return io_channel_send(s->ioc_out, buf, len);
1022 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1024 CharDriverState *chr = opaque;
1025 FDCharDriver *s = chr->opaque;
1026 int len;
1027 uint8_t buf[READ_BUF_LEN];
1028 ssize_t ret;
1030 len = sizeof(buf);
1031 if (len > s->max_size) {
1032 len = s->max_size;
1034 if (len == 0) {
1035 return TRUE;
1038 ret = qio_channel_read(
1039 chan, (gchar *)buf, len, NULL);
1040 if (ret == 0) {
1041 remove_fd_in_watch(chr);
1042 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1043 return FALSE;
1045 if (ret > 0) {
1046 qemu_chr_be_write(chr, buf, ret);
1049 return TRUE;
1052 static int fd_chr_read_poll(void *opaque)
1054 CharDriverState *chr = opaque;
1055 FDCharDriver *s = chr->opaque;
1057 s->max_size = qemu_chr_be_can_write(chr);
1058 return s->max_size;
1061 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1063 FDCharDriver *s = chr->opaque;
1064 return qio_channel_create_watch(s->ioc_out, cond);
1067 static void fd_chr_update_read_handler(CharDriverState *chr)
1069 FDCharDriver *s = chr->opaque;
1071 remove_fd_in_watch(chr);
1072 if (s->ioc_in) {
1073 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
1074 fd_chr_read_poll,
1075 fd_chr_read, chr);
1079 static void fd_chr_close(struct CharDriverState *chr)
1081 FDCharDriver *s = chr->opaque;
1083 remove_fd_in_watch(chr);
1084 if (s->ioc_in) {
1085 object_unref(OBJECT(s->ioc_in));
1087 if (s->ioc_out) {
1088 object_unref(OBJECT(s->ioc_out));
1091 g_free(s);
1092 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1095 /* open a character device to a unix fd */
1096 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1097 ChardevCommon *backend, Error **errp)
1099 CharDriverState *chr;
1100 FDCharDriver *s;
1102 chr = qemu_chr_alloc(backend, errp);
1103 if (!chr) {
1104 return NULL;
1106 s = g_new0(FDCharDriver, 1);
1107 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1108 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1109 qemu_set_nonblock(fd_out);
1110 s->chr = chr;
1111 chr->opaque = s;
1112 chr->chr_add_watch = fd_chr_add_watch;
1113 chr->chr_write = fd_chr_write;
1114 chr->chr_update_read_handler = fd_chr_update_read_handler;
1115 chr->chr_close = fd_chr_close;
1117 return chr;
1120 static CharDriverState *qemu_chr_open_pipe(const char *id,
1121 ChardevBackend *backend,
1122 ChardevReturn *ret,
1123 Error **errp)
1125 ChardevHostdev *opts = backend->u.pipe.data;
1126 int fd_in, fd_out;
1127 char *filename_in;
1128 char *filename_out;
1129 const char *filename = opts->device;
1130 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1133 filename_in = g_strdup_printf("%s.in", filename);
1134 filename_out = g_strdup_printf("%s.out", filename);
1135 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1136 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1137 g_free(filename_in);
1138 g_free(filename_out);
1139 if (fd_in < 0 || fd_out < 0) {
1140 if (fd_in >= 0)
1141 close(fd_in);
1142 if (fd_out >= 0)
1143 close(fd_out);
1144 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1145 if (fd_in < 0) {
1146 error_setg_file_open(errp, errno, filename);
1147 return NULL;
1150 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1153 /* init terminal so that we can grab keys */
1154 static struct termios oldtty;
1155 static int old_fd0_flags;
1156 static bool stdio_in_use;
1157 static bool stdio_allow_signal;
1158 static bool stdio_echo_state;
1160 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1162 static void term_exit(void)
1164 tcsetattr (0, TCSANOW, &oldtty);
1165 fcntl(0, F_SETFL, old_fd0_flags);
1168 static void term_stdio_handler(int sig)
1170 /* restore echo after resume from suspend. */
1171 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1174 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1176 struct termios tty;
1178 stdio_echo_state = echo;
1179 tty = oldtty;
1180 if (!echo) {
1181 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1182 |INLCR|IGNCR|ICRNL|IXON);
1183 tty.c_oflag |= OPOST;
1184 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1185 tty.c_cflag &= ~(CSIZE|PARENB);
1186 tty.c_cflag |= CS8;
1187 tty.c_cc[VMIN] = 1;
1188 tty.c_cc[VTIME] = 0;
1190 if (!stdio_allow_signal)
1191 tty.c_lflag &= ~ISIG;
1193 tcsetattr (0, TCSANOW, &tty);
1196 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1198 term_exit();
1199 fd_chr_close(chr);
1202 static CharDriverState *qemu_chr_open_stdio(const char *id,
1203 ChardevBackend *backend,
1204 ChardevReturn *ret,
1205 Error **errp)
1207 ChardevStdio *opts = backend->u.stdio.data;
1208 CharDriverState *chr;
1209 struct sigaction act;
1210 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1212 if (is_daemonized()) {
1213 error_setg(errp, "cannot use stdio with -daemonize");
1214 return NULL;
1217 if (stdio_in_use) {
1218 error_setg(errp, "cannot use stdio by multiple character devices");
1219 return NULL;
1222 stdio_in_use = true;
1223 old_fd0_flags = fcntl(0, F_GETFL);
1224 tcgetattr(0, &oldtty);
1225 qemu_set_nonblock(0);
1226 atexit(term_exit);
1228 memset(&act, 0, sizeof(act));
1229 act.sa_handler = term_stdio_handler;
1230 sigaction(SIGCONT, &act, NULL);
1232 chr = qemu_chr_open_fd(0, 1, common, errp);
1233 chr->chr_close = qemu_chr_close_stdio;
1234 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1235 if (opts->has_signal) {
1236 stdio_allow_signal = opts->signal;
1238 qemu_chr_fe_set_echo(chr, false);
1240 return chr;
1243 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1244 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1245 || defined(__GLIBC__)
1247 #define HAVE_CHARDEV_SERIAL 1
1248 #define HAVE_CHARDEV_PTY 1
1250 typedef struct {
1251 QIOChannel *ioc;
1252 int read_bytes;
1254 /* Protected by the CharDriverState chr_write_lock. */
1255 int connected;
1256 guint timer_tag;
1257 guint open_tag;
1258 } PtyCharDriver;
1260 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1261 static void pty_chr_state(CharDriverState *chr, int connected);
1263 static gboolean pty_chr_timer(gpointer opaque)
1265 struct CharDriverState *chr = opaque;
1266 PtyCharDriver *s = chr->opaque;
1268 qemu_mutex_lock(&chr->chr_write_lock);
1269 s->timer_tag = 0;
1270 s->open_tag = 0;
1271 if (!s->connected) {
1272 /* Next poll ... */
1273 pty_chr_update_read_handler_locked(chr);
1275 qemu_mutex_unlock(&chr->chr_write_lock);
1276 return FALSE;
1279 /* Called with chr_write_lock held. */
1280 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1282 PtyCharDriver *s = chr->opaque;
1284 if (s->timer_tag) {
1285 g_source_remove(s->timer_tag);
1286 s->timer_tag = 0;
1289 if (ms == 1000) {
1290 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1291 } else {
1292 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1296 /* Called with chr_write_lock held. */
1297 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1299 PtyCharDriver *s = chr->opaque;
1300 GPollFD pfd;
1301 int rc;
1302 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1304 pfd.fd = fioc->fd;
1305 pfd.events = G_IO_OUT;
1306 pfd.revents = 0;
1307 do {
1308 rc = g_poll(&pfd, 1, 0);
1309 } while (rc == -1 && errno == EINTR);
1310 assert(rc >= 0);
1312 if (pfd.revents & G_IO_HUP) {
1313 pty_chr_state(chr, 0);
1314 } else {
1315 pty_chr_state(chr, 1);
1319 static void pty_chr_update_read_handler(CharDriverState *chr)
1321 qemu_mutex_lock(&chr->chr_write_lock);
1322 pty_chr_update_read_handler_locked(chr);
1323 qemu_mutex_unlock(&chr->chr_write_lock);
1326 /* Called with chr_write_lock held. */
1327 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1329 PtyCharDriver *s = chr->opaque;
1331 if (!s->connected) {
1332 /* guest sends data, check for (re-)connect */
1333 pty_chr_update_read_handler_locked(chr);
1334 if (!s->connected) {
1335 return 0;
1338 return io_channel_send(s->ioc, buf, len);
1341 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1343 PtyCharDriver *s = chr->opaque;
1344 if (!s->connected) {
1345 return NULL;
1347 return qio_channel_create_watch(s->ioc, cond);
1350 static int pty_chr_read_poll(void *opaque)
1352 CharDriverState *chr = opaque;
1353 PtyCharDriver *s = chr->opaque;
1355 s->read_bytes = qemu_chr_be_can_write(chr);
1356 return s->read_bytes;
1359 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1361 CharDriverState *chr = opaque;
1362 PtyCharDriver *s = chr->opaque;
1363 gsize len;
1364 uint8_t buf[READ_BUF_LEN];
1365 ssize_t ret;
1367 len = sizeof(buf);
1368 if (len > s->read_bytes)
1369 len = s->read_bytes;
1370 if (len == 0) {
1371 return TRUE;
1373 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1374 if (ret <= 0) {
1375 pty_chr_state(chr, 0);
1376 return FALSE;
1377 } else {
1378 pty_chr_state(chr, 1);
1379 qemu_chr_be_write(chr, buf, ret);
1381 return TRUE;
1384 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1386 CharDriverState *chr = opaque;
1387 PtyCharDriver *s = chr->opaque;
1389 s->open_tag = 0;
1390 qemu_chr_be_generic_open(chr);
1391 return FALSE;
1394 /* Called with chr_write_lock held. */
1395 static void pty_chr_state(CharDriverState *chr, int connected)
1397 PtyCharDriver *s = chr->opaque;
1399 if (!connected) {
1400 if (s->open_tag) {
1401 g_source_remove(s->open_tag);
1402 s->open_tag = 0;
1404 remove_fd_in_watch(chr);
1405 s->connected = 0;
1406 /* (re-)connect poll interval for idle guests: once per second.
1407 * We check more frequently in case the guests sends data to
1408 * the virtual device linked to our pty. */
1409 pty_chr_rearm_timer(chr, 1000);
1410 } else {
1411 if (s->timer_tag) {
1412 g_source_remove(s->timer_tag);
1413 s->timer_tag = 0;
1415 if (!s->connected) {
1416 g_assert(s->open_tag == 0);
1417 s->connected = 1;
1418 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1420 if (!chr->fd_in_tag) {
1421 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1422 pty_chr_read_poll,
1423 pty_chr_read, chr);
1428 static void pty_chr_close(struct CharDriverState *chr)
1430 PtyCharDriver *s = chr->opaque;
1432 qemu_mutex_lock(&chr->chr_write_lock);
1433 pty_chr_state(chr, 0);
1434 object_unref(OBJECT(s->ioc));
1435 if (s->timer_tag) {
1436 g_source_remove(s->timer_tag);
1437 s->timer_tag = 0;
1439 qemu_mutex_unlock(&chr->chr_write_lock);
1440 g_free(s);
1441 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1444 static CharDriverState *qemu_chr_open_pty(const char *id,
1445 ChardevBackend *backend,
1446 ChardevReturn *ret,
1447 Error **errp)
1449 CharDriverState *chr;
1450 PtyCharDriver *s;
1451 int master_fd, slave_fd;
1452 char pty_name[PATH_MAX];
1453 ChardevCommon *common = backend->u.pty.data;
1455 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1456 if (master_fd < 0) {
1457 error_setg_errno(errp, errno, "Failed to create PTY");
1458 return NULL;
1461 close(slave_fd);
1462 qemu_set_nonblock(master_fd);
1464 chr = qemu_chr_alloc(common, errp);
1465 if (!chr) {
1466 close(master_fd);
1467 return NULL;
1470 chr->filename = g_strdup_printf("pty:%s", pty_name);
1471 ret->pty = g_strdup(pty_name);
1472 ret->has_pty = true;
1474 fprintf(stderr, "char device redirected to %s (label %s)\n",
1475 pty_name, id);
1477 s = g_new0(PtyCharDriver, 1);
1478 chr->opaque = s;
1479 chr->chr_write = pty_chr_write;
1480 chr->chr_update_read_handler = pty_chr_update_read_handler;
1481 chr->chr_close = pty_chr_close;
1482 chr->chr_add_watch = pty_chr_add_watch;
1483 chr->explicit_be_open = true;
1485 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1486 s->timer_tag = 0;
1488 return chr;
1491 static void tty_serial_init(int fd, int speed,
1492 int parity, int data_bits, int stop_bits)
1494 struct termios tty;
1495 speed_t spd;
1497 #if 0
1498 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1499 speed, parity, data_bits, stop_bits);
1500 #endif
1501 tcgetattr (fd, &tty);
1503 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1504 speed = speed * 10 / 11;
1505 do {
1506 check_speed(50);
1507 check_speed(75);
1508 check_speed(110);
1509 check_speed(134);
1510 check_speed(150);
1511 check_speed(200);
1512 check_speed(300);
1513 check_speed(600);
1514 check_speed(1200);
1515 check_speed(1800);
1516 check_speed(2400);
1517 check_speed(4800);
1518 check_speed(9600);
1519 check_speed(19200);
1520 check_speed(38400);
1521 /* Non-Posix values follow. They may be unsupported on some systems. */
1522 check_speed(57600);
1523 check_speed(115200);
1524 #ifdef B230400
1525 check_speed(230400);
1526 #endif
1527 #ifdef B460800
1528 check_speed(460800);
1529 #endif
1530 #ifdef B500000
1531 check_speed(500000);
1532 #endif
1533 #ifdef B576000
1534 check_speed(576000);
1535 #endif
1536 #ifdef B921600
1537 check_speed(921600);
1538 #endif
1539 #ifdef B1000000
1540 check_speed(1000000);
1541 #endif
1542 #ifdef B1152000
1543 check_speed(1152000);
1544 #endif
1545 #ifdef B1500000
1546 check_speed(1500000);
1547 #endif
1548 #ifdef B2000000
1549 check_speed(2000000);
1550 #endif
1551 #ifdef B2500000
1552 check_speed(2500000);
1553 #endif
1554 #ifdef B3000000
1555 check_speed(3000000);
1556 #endif
1557 #ifdef B3500000
1558 check_speed(3500000);
1559 #endif
1560 #ifdef B4000000
1561 check_speed(4000000);
1562 #endif
1563 spd = B115200;
1564 } while (0);
1566 cfsetispeed(&tty, spd);
1567 cfsetospeed(&tty, spd);
1569 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1570 |INLCR|IGNCR|ICRNL|IXON);
1571 tty.c_oflag |= OPOST;
1572 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1573 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1574 switch(data_bits) {
1575 default:
1576 case 8:
1577 tty.c_cflag |= CS8;
1578 break;
1579 case 7:
1580 tty.c_cflag |= CS7;
1581 break;
1582 case 6:
1583 tty.c_cflag |= CS6;
1584 break;
1585 case 5:
1586 tty.c_cflag |= CS5;
1587 break;
1589 switch(parity) {
1590 default:
1591 case 'N':
1592 break;
1593 case 'E':
1594 tty.c_cflag |= PARENB;
1595 break;
1596 case 'O':
1597 tty.c_cflag |= PARENB | PARODD;
1598 break;
1600 if (stop_bits == 2)
1601 tty.c_cflag |= CSTOPB;
1603 tcsetattr (fd, TCSANOW, &tty);
1606 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1608 FDCharDriver *s = chr->opaque;
1609 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1611 switch(cmd) {
1612 case CHR_IOCTL_SERIAL_SET_PARAMS:
1614 QEMUSerialSetParams *ssp = arg;
1615 tty_serial_init(fioc->fd,
1616 ssp->speed, ssp->parity,
1617 ssp->data_bits, ssp->stop_bits);
1619 break;
1620 case CHR_IOCTL_SERIAL_SET_BREAK:
1622 int enable = *(int *)arg;
1623 if (enable) {
1624 tcsendbreak(fioc->fd, 1);
1627 break;
1628 case CHR_IOCTL_SERIAL_GET_TIOCM:
1630 int sarg = 0;
1631 int *targ = (int *)arg;
1632 ioctl(fioc->fd, TIOCMGET, &sarg);
1633 *targ = 0;
1634 if (sarg & TIOCM_CTS)
1635 *targ |= CHR_TIOCM_CTS;
1636 if (sarg & TIOCM_CAR)
1637 *targ |= CHR_TIOCM_CAR;
1638 if (sarg & TIOCM_DSR)
1639 *targ |= CHR_TIOCM_DSR;
1640 if (sarg & TIOCM_RI)
1641 *targ |= CHR_TIOCM_RI;
1642 if (sarg & TIOCM_DTR)
1643 *targ |= CHR_TIOCM_DTR;
1644 if (sarg & TIOCM_RTS)
1645 *targ |= CHR_TIOCM_RTS;
1647 break;
1648 case CHR_IOCTL_SERIAL_SET_TIOCM:
1650 int sarg = *(int *)arg;
1651 int targ = 0;
1652 ioctl(fioc->fd, TIOCMGET, &targ);
1653 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1654 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1655 if (sarg & CHR_TIOCM_CTS)
1656 targ |= TIOCM_CTS;
1657 if (sarg & CHR_TIOCM_CAR)
1658 targ |= TIOCM_CAR;
1659 if (sarg & CHR_TIOCM_DSR)
1660 targ |= TIOCM_DSR;
1661 if (sarg & CHR_TIOCM_RI)
1662 targ |= TIOCM_RI;
1663 if (sarg & CHR_TIOCM_DTR)
1664 targ |= TIOCM_DTR;
1665 if (sarg & CHR_TIOCM_RTS)
1666 targ |= TIOCM_RTS;
1667 ioctl(fioc->fd, TIOCMSET, &targ);
1669 break;
1670 default:
1671 return -ENOTSUP;
1673 return 0;
1676 static void qemu_chr_close_tty(CharDriverState *chr)
1678 fd_chr_close(chr);
1681 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1682 ChardevCommon *backend,
1683 Error **errp)
1685 CharDriverState *chr;
1687 tty_serial_init(fd, 115200, 'N', 8, 1);
1688 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1689 chr->chr_ioctl = tty_serial_ioctl;
1690 chr->chr_close = qemu_chr_close_tty;
1691 return chr;
1693 #endif /* __linux__ || __sun__ */
1695 #if defined(__linux__)
1697 #define HAVE_CHARDEV_PARPORT 1
1699 typedef struct {
1700 int fd;
1701 int mode;
1702 } ParallelCharDriver;
1704 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1706 if (s->mode != mode) {
1707 int m = mode;
1708 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1709 return 0;
1710 s->mode = mode;
1712 return 1;
1715 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1717 ParallelCharDriver *drv = chr->opaque;
1718 int fd = drv->fd;
1719 uint8_t b;
1721 switch(cmd) {
1722 case CHR_IOCTL_PP_READ_DATA:
1723 if (ioctl(fd, PPRDATA, &b) < 0)
1724 return -ENOTSUP;
1725 *(uint8_t *)arg = b;
1726 break;
1727 case CHR_IOCTL_PP_WRITE_DATA:
1728 b = *(uint8_t *)arg;
1729 if (ioctl(fd, PPWDATA, &b) < 0)
1730 return -ENOTSUP;
1731 break;
1732 case CHR_IOCTL_PP_READ_CONTROL:
1733 if (ioctl(fd, PPRCONTROL, &b) < 0)
1734 return -ENOTSUP;
1735 /* Linux gives only the lowest bits, and no way to know data
1736 direction! For better compatibility set the fixed upper
1737 bits. */
1738 *(uint8_t *)arg = b | 0xc0;
1739 break;
1740 case CHR_IOCTL_PP_WRITE_CONTROL:
1741 b = *(uint8_t *)arg;
1742 if (ioctl(fd, PPWCONTROL, &b) < 0)
1743 return -ENOTSUP;
1744 break;
1745 case CHR_IOCTL_PP_READ_STATUS:
1746 if (ioctl(fd, PPRSTATUS, &b) < 0)
1747 return -ENOTSUP;
1748 *(uint8_t *)arg = b;
1749 break;
1750 case CHR_IOCTL_PP_DATA_DIR:
1751 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1752 return -ENOTSUP;
1753 break;
1754 case CHR_IOCTL_PP_EPP_READ_ADDR:
1755 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1756 struct ParallelIOArg *parg = arg;
1757 int n = read(fd, parg->buffer, parg->count);
1758 if (n != parg->count) {
1759 return -EIO;
1762 break;
1763 case CHR_IOCTL_PP_EPP_READ:
1764 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1765 struct ParallelIOArg *parg = arg;
1766 int n = read(fd, parg->buffer, parg->count);
1767 if (n != parg->count) {
1768 return -EIO;
1771 break;
1772 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1773 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1774 struct ParallelIOArg *parg = arg;
1775 int n = write(fd, parg->buffer, parg->count);
1776 if (n != parg->count) {
1777 return -EIO;
1780 break;
1781 case CHR_IOCTL_PP_EPP_WRITE:
1782 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1783 struct ParallelIOArg *parg = arg;
1784 int n = write(fd, parg->buffer, parg->count);
1785 if (n != parg->count) {
1786 return -EIO;
1789 break;
1790 default:
1791 return -ENOTSUP;
1793 return 0;
1796 static void pp_close(CharDriverState *chr)
1798 ParallelCharDriver *drv = chr->opaque;
1799 int fd = drv->fd;
1801 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1802 ioctl(fd, PPRELEASE);
1803 close(fd);
1804 g_free(drv);
1805 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1808 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1809 ChardevCommon *backend,
1810 Error **errp)
1812 CharDriverState *chr;
1813 ParallelCharDriver *drv;
1815 if (ioctl(fd, PPCLAIM) < 0) {
1816 error_setg_errno(errp, errno, "not a parallel port");
1817 close(fd);
1818 return NULL;
1821 chr = qemu_chr_alloc(backend, errp);
1822 if (!chr) {
1823 return NULL;
1826 drv = g_new0(ParallelCharDriver, 1);
1827 chr->opaque = drv;
1828 chr->chr_write = null_chr_write;
1829 chr->chr_ioctl = pp_ioctl;
1830 chr->chr_close = pp_close;
1832 drv->fd = fd;
1833 drv->mode = IEEE1284_MODE_COMPAT;
1835 return chr;
1837 #endif /* __linux__ */
1839 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1841 #define HAVE_CHARDEV_PARPORT 1
1843 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1845 int fd = (int)(intptr_t)chr->opaque;
1846 uint8_t b;
1848 switch(cmd) {
1849 case CHR_IOCTL_PP_READ_DATA:
1850 if (ioctl(fd, PPIGDATA, &b) < 0)
1851 return -ENOTSUP;
1852 *(uint8_t *)arg = b;
1853 break;
1854 case CHR_IOCTL_PP_WRITE_DATA:
1855 b = *(uint8_t *)arg;
1856 if (ioctl(fd, PPISDATA, &b) < 0)
1857 return -ENOTSUP;
1858 break;
1859 case CHR_IOCTL_PP_READ_CONTROL:
1860 if (ioctl(fd, PPIGCTRL, &b) < 0)
1861 return -ENOTSUP;
1862 *(uint8_t *)arg = b;
1863 break;
1864 case CHR_IOCTL_PP_WRITE_CONTROL:
1865 b = *(uint8_t *)arg;
1866 if (ioctl(fd, PPISCTRL, &b) < 0)
1867 return -ENOTSUP;
1868 break;
1869 case CHR_IOCTL_PP_READ_STATUS:
1870 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1871 return -ENOTSUP;
1872 *(uint8_t *)arg = b;
1873 break;
1874 default:
1875 return -ENOTSUP;
1877 return 0;
1880 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1881 ChardevCommon *backend,
1882 Error **errp)
1884 CharDriverState *chr;
1886 chr = qemu_chr_alloc(backend, errp);
1887 if (!chr) {
1888 return NULL;
1890 chr->opaque = (void *)(intptr_t)fd;
1891 chr->chr_write = null_chr_write;
1892 chr->chr_ioctl = pp_ioctl;
1893 chr->explicit_be_open = true;
1894 return chr;
1896 #endif
1898 #else /* _WIN32 */
1900 #define HAVE_CHARDEV_SERIAL 1
1902 typedef struct {
1903 int max_size;
1904 HANDLE hcom, hrecv, hsend;
1905 OVERLAPPED orecv;
1906 BOOL fpipe;
1907 DWORD len;
1909 /* Protected by the CharDriverState chr_write_lock. */
1910 OVERLAPPED osend;
1911 } WinCharState;
1913 typedef struct {
1914 HANDLE hStdIn;
1915 HANDLE hInputReadyEvent;
1916 HANDLE hInputDoneEvent;
1917 HANDLE hInputThread;
1918 uint8_t win_stdio_buf;
1919 } WinStdioCharState;
1921 #define NSENDBUF 2048
1922 #define NRECVBUF 2048
1923 #define MAXCONNECT 1
1924 #define NTIMEOUT 5000
1926 static int win_chr_poll(void *opaque);
1927 static int win_chr_pipe_poll(void *opaque);
1929 static void win_chr_close(CharDriverState *chr)
1931 WinCharState *s = chr->opaque;
1933 if (s->hsend) {
1934 CloseHandle(s->hsend);
1935 s->hsend = NULL;
1937 if (s->hrecv) {
1938 CloseHandle(s->hrecv);
1939 s->hrecv = NULL;
1941 if (s->hcom) {
1942 CloseHandle(s->hcom);
1943 s->hcom = NULL;
1945 if (s->fpipe)
1946 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1947 else
1948 qemu_del_polling_cb(win_chr_poll, chr);
1950 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1953 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1955 WinCharState *s = chr->opaque;
1956 COMMCONFIG comcfg;
1957 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1958 COMSTAT comstat;
1959 DWORD size;
1960 DWORD err;
1962 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1963 if (!s->hsend) {
1964 error_setg(errp, "Failed CreateEvent");
1965 goto fail;
1967 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1968 if (!s->hrecv) {
1969 error_setg(errp, "Failed CreateEvent");
1970 goto fail;
1973 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1974 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1975 if (s->hcom == INVALID_HANDLE_VALUE) {
1976 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1977 s->hcom = NULL;
1978 goto fail;
1981 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1982 error_setg(errp, "Failed SetupComm");
1983 goto fail;
1986 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1987 size = sizeof(COMMCONFIG);
1988 GetDefaultCommConfig(filename, &comcfg, &size);
1989 comcfg.dcb.DCBlength = sizeof(DCB);
1990 CommConfigDialog(filename, NULL, &comcfg);
1992 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1993 error_setg(errp, "Failed SetCommState");
1994 goto fail;
1997 if (!SetCommMask(s->hcom, EV_ERR)) {
1998 error_setg(errp, "Failed SetCommMask");
1999 goto fail;
2002 cto.ReadIntervalTimeout = MAXDWORD;
2003 if (!SetCommTimeouts(s->hcom, &cto)) {
2004 error_setg(errp, "Failed SetCommTimeouts");
2005 goto fail;
2008 if (!ClearCommError(s->hcom, &err, &comstat)) {
2009 error_setg(errp, "Failed ClearCommError");
2010 goto fail;
2012 qemu_add_polling_cb(win_chr_poll, chr);
2013 return 0;
2015 fail:
2016 win_chr_close(chr);
2017 return -1;
2020 /* Called with chr_write_lock held. */
2021 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2023 WinCharState *s = chr->opaque;
2024 DWORD len, ret, size, err;
2026 len = len1;
2027 ZeroMemory(&s->osend, sizeof(s->osend));
2028 s->osend.hEvent = s->hsend;
2029 while (len > 0) {
2030 if (s->hsend)
2031 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2032 else
2033 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2034 if (!ret) {
2035 err = GetLastError();
2036 if (err == ERROR_IO_PENDING) {
2037 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2038 if (ret) {
2039 buf += size;
2040 len -= size;
2041 } else {
2042 break;
2044 } else {
2045 break;
2047 } else {
2048 buf += size;
2049 len -= size;
2052 return len1 - len;
2055 static int win_chr_read_poll(CharDriverState *chr)
2057 WinCharState *s = chr->opaque;
2059 s->max_size = qemu_chr_be_can_write(chr);
2060 return s->max_size;
2063 static void win_chr_readfile(CharDriverState *chr)
2065 WinCharState *s = chr->opaque;
2066 int ret, err;
2067 uint8_t buf[READ_BUF_LEN];
2068 DWORD size;
2070 ZeroMemory(&s->orecv, sizeof(s->orecv));
2071 s->orecv.hEvent = s->hrecv;
2072 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2073 if (!ret) {
2074 err = GetLastError();
2075 if (err == ERROR_IO_PENDING) {
2076 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2080 if (size > 0) {
2081 qemu_chr_be_write(chr, buf, size);
2085 static void win_chr_read(CharDriverState *chr)
2087 WinCharState *s = chr->opaque;
2089 if (s->len > s->max_size)
2090 s->len = s->max_size;
2091 if (s->len == 0)
2092 return;
2094 win_chr_readfile(chr);
2097 static int win_chr_poll(void *opaque)
2099 CharDriverState *chr = opaque;
2100 WinCharState *s = chr->opaque;
2101 COMSTAT status;
2102 DWORD comerr;
2104 ClearCommError(s->hcom, &comerr, &status);
2105 if (status.cbInQue > 0) {
2106 s->len = status.cbInQue;
2107 win_chr_read_poll(chr);
2108 win_chr_read(chr);
2109 return 1;
2111 return 0;
2114 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2115 ChardevCommon *backend,
2116 Error **errp)
2118 CharDriverState *chr;
2119 WinCharState *s;
2121 chr = qemu_chr_alloc(backend, errp);
2122 if (!chr) {
2123 return NULL;
2125 s = g_new0(WinCharState, 1);
2126 chr->opaque = s;
2127 chr->chr_write = win_chr_write;
2128 chr->chr_close = win_chr_close;
2130 if (win_chr_init(chr, filename, errp) < 0) {
2131 g_free(s);
2132 qemu_chr_free_common(chr);
2133 return NULL;
2135 return chr;
2138 static int win_chr_pipe_poll(void *opaque)
2140 CharDriverState *chr = opaque;
2141 WinCharState *s = chr->opaque;
2142 DWORD size;
2144 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2145 if (size > 0) {
2146 s->len = size;
2147 win_chr_read_poll(chr);
2148 win_chr_read(chr);
2149 return 1;
2151 return 0;
2154 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2155 Error **errp)
2157 WinCharState *s = chr->opaque;
2158 OVERLAPPED ov;
2159 int ret;
2160 DWORD size;
2161 char *openname;
2163 s->fpipe = TRUE;
2165 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2166 if (!s->hsend) {
2167 error_setg(errp, "Failed CreateEvent");
2168 goto fail;
2170 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2171 if (!s->hrecv) {
2172 error_setg(errp, "Failed CreateEvent");
2173 goto fail;
2176 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2177 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2178 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2179 PIPE_WAIT,
2180 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2181 g_free(openname);
2182 if (s->hcom == INVALID_HANDLE_VALUE) {
2183 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2184 s->hcom = NULL;
2185 goto fail;
2188 ZeroMemory(&ov, sizeof(ov));
2189 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2190 ret = ConnectNamedPipe(s->hcom, &ov);
2191 if (ret) {
2192 error_setg(errp, "Failed ConnectNamedPipe");
2193 goto fail;
2196 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2197 if (!ret) {
2198 error_setg(errp, "Failed GetOverlappedResult");
2199 if (ov.hEvent) {
2200 CloseHandle(ov.hEvent);
2201 ov.hEvent = NULL;
2203 goto fail;
2206 if (ov.hEvent) {
2207 CloseHandle(ov.hEvent);
2208 ov.hEvent = NULL;
2210 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2211 return 0;
2213 fail:
2214 win_chr_close(chr);
2215 return -1;
2219 static CharDriverState *qemu_chr_open_pipe(const char *id,
2220 ChardevBackend *backend,
2221 ChardevReturn *ret,
2222 Error **errp)
2224 ChardevHostdev *opts = backend->u.pipe.data;
2225 const char *filename = opts->device;
2226 CharDriverState *chr;
2227 WinCharState *s;
2228 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2230 chr = qemu_chr_alloc(common, errp);
2231 if (!chr) {
2232 return NULL;
2234 s = g_new0(WinCharState, 1);
2235 chr->opaque = s;
2236 chr->chr_write = win_chr_write;
2237 chr->chr_close = win_chr_close;
2239 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2240 g_free(s);
2241 qemu_chr_free_common(chr);
2242 return NULL;
2244 return chr;
2247 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2248 ChardevCommon *backend,
2249 Error **errp)
2251 CharDriverState *chr;
2252 WinCharState *s;
2254 chr = qemu_chr_alloc(backend, errp);
2255 if (!chr) {
2256 return NULL;
2258 s = g_new0(WinCharState, 1);
2259 s->hcom = fd_out;
2260 chr->opaque = s;
2261 chr->chr_write = win_chr_write;
2262 return chr;
2265 static CharDriverState *qemu_chr_open_win_con(const char *id,
2266 ChardevBackend *backend,
2267 ChardevReturn *ret,
2268 Error **errp)
2270 ChardevCommon *common = backend->u.console.data;
2271 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2272 common, errp);
2275 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2277 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2278 DWORD dwSize;
2279 int len1;
2281 len1 = len;
2283 while (len1 > 0) {
2284 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2285 break;
2287 buf += dwSize;
2288 len1 -= dwSize;
2291 return len - len1;
2294 static void win_stdio_wait_func(void *opaque)
2296 CharDriverState *chr = opaque;
2297 WinStdioCharState *stdio = chr->opaque;
2298 INPUT_RECORD buf[4];
2299 int ret;
2300 DWORD dwSize;
2301 int i;
2303 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2305 if (!ret) {
2306 /* Avoid error storm */
2307 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2308 return;
2311 for (i = 0; i < dwSize; i++) {
2312 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2314 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2315 int j;
2316 if (kev->uChar.AsciiChar != 0) {
2317 for (j = 0; j < kev->wRepeatCount; j++) {
2318 if (qemu_chr_be_can_write(chr)) {
2319 uint8_t c = kev->uChar.AsciiChar;
2320 qemu_chr_be_write(chr, &c, 1);
2328 static DWORD WINAPI win_stdio_thread(LPVOID param)
2330 CharDriverState *chr = param;
2331 WinStdioCharState *stdio = chr->opaque;
2332 int ret;
2333 DWORD dwSize;
2335 while (1) {
2337 /* Wait for one byte */
2338 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2340 /* Exit in case of error, continue if nothing read */
2341 if (!ret) {
2342 break;
2344 if (!dwSize) {
2345 continue;
2348 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2349 if (stdio->win_stdio_buf == '\r') {
2350 continue;
2353 /* Signal the main thread and wait until the byte was eaten */
2354 if (!SetEvent(stdio->hInputReadyEvent)) {
2355 break;
2357 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2358 != WAIT_OBJECT_0) {
2359 break;
2363 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2364 return 0;
2367 static void win_stdio_thread_wait_func(void *opaque)
2369 CharDriverState *chr = opaque;
2370 WinStdioCharState *stdio = chr->opaque;
2372 if (qemu_chr_be_can_write(chr)) {
2373 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2376 SetEvent(stdio->hInputDoneEvent);
2379 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2381 WinStdioCharState *stdio = chr->opaque;
2382 DWORD dwMode = 0;
2384 GetConsoleMode(stdio->hStdIn, &dwMode);
2386 if (echo) {
2387 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2388 } else {
2389 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2393 static void win_stdio_close(CharDriverState *chr)
2395 WinStdioCharState *stdio = chr->opaque;
2397 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2398 CloseHandle(stdio->hInputReadyEvent);
2400 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2401 CloseHandle(stdio->hInputDoneEvent);
2403 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2404 TerminateThread(stdio->hInputThread, 0);
2407 g_free(chr->opaque);
2408 g_free(chr);
2411 static CharDriverState *qemu_chr_open_stdio(const char *id,
2412 ChardevBackend *backend,
2413 ChardevReturn *ret,
2414 Error **errp)
2416 CharDriverState *chr;
2417 WinStdioCharState *stdio;
2418 DWORD dwMode;
2419 int is_console = 0;
2420 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio.data);
2422 chr = qemu_chr_alloc(common, errp);
2423 if (!chr) {
2424 return NULL;
2426 stdio = g_new0(WinStdioCharState, 1);
2428 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2429 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2430 error_setg(errp, "cannot open stdio: invalid handle");
2431 return NULL;
2434 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2436 chr->opaque = stdio;
2437 chr->chr_write = win_stdio_write;
2438 chr->chr_close = win_stdio_close;
2440 if (is_console) {
2441 if (qemu_add_wait_object(stdio->hStdIn,
2442 win_stdio_wait_func, chr)) {
2443 error_setg(errp, "qemu_add_wait_object: failed");
2444 goto err1;
2446 } else {
2447 DWORD dwId;
2449 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2450 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2451 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2452 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2453 error_setg(errp, "cannot create event");
2454 goto err2;
2456 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2457 win_stdio_thread_wait_func, chr)) {
2458 error_setg(errp, "qemu_add_wait_object: failed");
2459 goto err2;
2461 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2462 chr, 0, &dwId);
2464 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2465 error_setg(errp, "cannot create stdio thread");
2466 goto err3;
2470 dwMode |= ENABLE_LINE_INPUT;
2472 if (is_console) {
2473 /* set the terminal in raw mode */
2474 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2475 dwMode |= ENABLE_PROCESSED_INPUT;
2478 SetConsoleMode(stdio->hStdIn, dwMode);
2480 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2481 qemu_chr_fe_set_echo(chr, false);
2483 return chr;
2485 err3:
2486 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2487 err2:
2488 CloseHandle(stdio->hInputReadyEvent);
2489 CloseHandle(stdio->hInputDoneEvent);
2490 err1:
2491 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2492 return NULL;
2494 #endif /* !_WIN32 */
2497 /***********************************************************/
2498 /* UDP Net console */
2500 typedef struct {
2501 QIOChannel *ioc;
2502 uint8_t buf[READ_BUF_LEN];
2503 int bufcnt;
2504 int bufptr;
2505 int max_size;
2506 } NetCharDriver;
2508 /* Called with chr_write_lock held. */
2509 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2511 NetCharDriver *s = chr->opaque;
2513 return qio_channel_write(
2514 s->ioc, (const char *)buf, len, NULL);
2517 static int udp_chr_read_poll(void *opaque)
2519 CharDriverState *chr = opaque;
2520 NetCharDriver *s = chr->opaque;
2522 s->max_size = qemu_chr_be_can_write(chr);
2524 /* If there were any stray characters in the queue process them
2525 * first
2527 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2528 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2529 s->bufptr++;
2530 s->max_size = qemu_chr_be_can_write(chr);
2532 return s->max_size;
2535 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2537 CharDriverState *chr = opaque;
2538 NetCharDriver *s = chr->opaque;
2539 ssize_t ret;
2541 if (s->max_size == 0) {
2542 return TRUE;
2544 ret = qio_channel_read(
2545 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2546 if (ret <= 0) {
2547 remove_fd_in_watch(chr);
2548 return FALSE;
2550 s->bufcnt = ret;
2552 s->bufptr = 0;
2553 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2554 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2555 s->bufptr++;
2556 s->max_size = qemu_chr_be_can_write(chr);
2559 return TRUE;
2562 static void udp_chr_update_read_handler(CharDriverState *chr)
2564 NetCharDriver *s = chr->opaque;
2566 remove_fd_in_watch(chr);
2567 if (s->ioc) {
2568 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2569 udp_chr_read_poll,
2570 udp_chr_read, chr);
2574 static void udp_chr_close(CharDriverState *chr)
2576 NetCharDriver *s = chr->opaque;
2578 remove_fd_in_watch(chr);
2579 if (s->ioc) {
2580 object_unref(OBJECT(s->ioc));
2582 g_free(s);
2583 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2586 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2587 ChardevCommon *backend,
2588 Error **errp)
2590 CharDriverState *chr = NULL;
2591 NetCharDriver *s = NULL;
2593 chr = qemu_chr_alloc(backend, errp);
2594 if (!chr) {
2595 return NULL;
2597 s = g_new0(NetCharDriver, 1);
2599 s->ioc = QIO_CHANNEL(sioc);
2600 s->bufcnt = 0;
2601 s->bufptr = 0;
2602 chr->opaque = s;
2603 chr->chr_write = udp_chr_write;
2604 chr->chr_update_read_handler = udp_chr_update_read_handler;
2605 chr->chr_close = udp_chr_close;
2606 /* be isn't opened until we get a connection */
2607 chr->explicit_be_open = true;
2608 return chr;
2611 /***********************************************************/
2612 /* TCP Net console */
2614 typedef struct {
2615 QIOChannel *ioc; /* Client I/O channel */
2616 QIOChannelSocket *sioc; /* Client master channel */
2617 QIOChannelSocket *listen_ioc;
2618 guint listen_tag;
2619 QCryptoTLSCreds *tls_creds;
2620 int connected;
2621 int max_size;
2622 int do_telnetopt;
2623 int do_nodelay;
2624 int is_unix;
2625 int *read_msgfds;
2626 size_t read_msgfds_num;
2627 int *write_msgfds;
2628 size_t write_msgfds_num;
2630 SocketAddress *addr;
2631 bool is_listen;
2632 bool is_telnet;
2634 guint reconnect_timer;
2635 int64_t reconnect_time;
2636 bool connect_err_reported;
2637 } TCPCharDriver;
2639 static gboolean socket_reconnect_timeout(gpointer opaque);
2641 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2643 TCPCharDriver *s = chr->opaque;
2644 assert(s->connected == 0);
2645 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2646 socket_reconnect_timeout, chr);
2649 static void check_report_connect_error(CharDriverState *chr,
2650 Error *err)
2652 TCPCharDriver *s = chr->opaque;
2654 if (!s->connect_err_reported) {
2655 error_report("Unable to connect character device %s: %s",
2656 chr->label, error_get_pretty(err));
2657 s->connect_err_reported = true;
2659 qemu_chr_socket_restart_timer(chr);
2662 static gboolean tcp_chr_accept(QIOChannel *chan,
2663 GIOCondition cond,
2664 void *opaque);
2666 /* Called with chr_write_lock held. */
2667 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2669 TCPCharDriver *s = chr->opaque;
2670 if (s->connected) {
2671 int ret = io_channel_send_full(s->ioc, buf, len,
2672 s->write_msgfds,
2673 s->write_msgfds_num);
2675 /* free the written msgfds, no matter what */
2676 if (s->write_msgfds_num) {
2677 g_free(s->write_msgfds);
2678 s->write_msgfds = 0;
2679 s->write_msgfds_num = 0;
2682 return ret;
2683 } else {
2684 /* XXX: indicate an error ? */
2685 return len;
2689 static int tcp_chr_read_poll(void *opaque)
2691 CharDriverState *chr = opaque;
2692 TCPCharDriver *s = chr->opaque;
2693 if (!s->connected)
2694 return 0;
2695 s->max_size = qemu_chr_be_can_write(chr);
2696 return s->max_size;
2699 #define IAC 255
2700 #define IAC_BREAK 243
2701 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2702 TCPCharDriver *s,
2703 uint8_t *buf, int *size)
2705 /* Handle any telnet client's basic IAC options to satisfy char by
2706 * char mode with no echo. All IAC options will be removed from
2707 * the buf and the do_telnetopt variable will be used to track the
2708 * state of the width of the IAC information.
2710 * IAC commands come in sets of 3 bytes with the exception of the
2711 * "IAC BREAK" command and the double IAC.
2714 int i;
2715 int j = 0;
2717 for (i = 0; i < *size; i++) {
2718 if (s->do_telnetopt > 1) {
2719 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2720 /* Double IAC means send an IAC */
2721 if (j != i)
2722 buf[j] = buf[i];
2723 j++;
2724 s->do_telnetopt = 1;
2725 } else {
2726 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2727 /* Handle IAC break commands by sending a serial break */
2728 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2729 s->do_telnetopt++;
2731 s->do_telnetopt++;
2733 if (s->do_telnetopt >= 4) {
2734 s->do_telnetopt = 1;
2736 } else {
2737 if ((unsigned char)buf[i] == IAC) {
2738 s->do_telnetopt = 2;
2739 } else {
2740 if (j != i)
2741 buf[j] = buf[i];
2742 j++;
2746 *size = j;
2749 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2751 TCPCharDriver *s = chr->opaque;
2752 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2754 assert(num <= TCP_MAX_FDS);
2756 if (to_copy) {
2757 int i;
2759 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2761 /* Close unused fds */
2762 for (i = to_copy; i < s->read_msgfds_num; i++) {
2763 close(s->read_msgfds[i]);
2766 g_free(s->read_msgfds);
2767 s->read_msgfds = 0;
2768 s->read_msgfds_num = 0;
2771 return to_copy;
2774 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2776 TCPCharDriver *s = chr->opaque;
2778 /* clear old pending fd array */
2779 g_free(s->write_msgfds);
2780 s->write_msgfds = NULL;
2781 s->write_msgfds_num = 0;
2783 if (!s->connected ||
2784 !qio_channel_has_feature(s->ioc,
2785 QIO_CHANNEL_FEATURE_FD_PASS)) {
2786 return -1;
2789 if (num) {
2790 s->write_msgfds = g_new(int, num);
2791 memcpy(s->write_msgfds, fds, num * sizeof(int));
2794 s->write_msgfds_num = num;
2796 return 0;
2799 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2801 TCPCharDriver *s = chr->opaque;
2802 struct iovec iov = { .iov_base = buf, .iov_len = len };
2803 int ret;
2804 size_t i;
2805 int *msgfds = NULL;
2806 size_t msgfds_num = 0;
2808 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2809 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2810 &msgfds, &msgfds_num,
2811 NULL);
2812 } else {
2813 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2814 NULL, NULL,
2815 NULL);
2818 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2819 errno = EAGAIN;
2820 ret = -1;
2821 } else if (ret == -1) {
2822 errno = EIO;
2825 if (msgfds_num) {
2826 /* close and clean read_msgfds */
2827 for (i = 0; i < s->read_msgfds_num; i++) {
2828 close(s->read_msgfds[i]);
2831 if (s->read_msgfds_num) {
2832 g_free(s->read_msgfds);
2835 s->read_msgfds = msgfds;
2836 s->read_msgfds_num = msgfds_num;
2839 for (i = 0; i < s->read_msgfds_num; i++) {
2840 int fd = s->read_msgfds[i];
2841 if (fd < 0) {
2842 continue;
2845 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2846 qemu_set_block(fd);
2848 #ifndef MSG_CMSG_CLOEXEC
2849 qemu_set_cloexec(fd);
2850 #endif
2853 return ret;
2856 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2858 TCPCharDriver *s = chr->opaque;
2859 return qio_channel_create_watch(s->ioc, cond);
2862 static void tcp_chr_free_connection(CharDriverState *chr)
2864 TCPCharDriver *s = chr->opaque;
2865 int i;
2867 if (!s->connected) {
2868 return;
2871 if (s->read_msgfds_num) {
2872 for (i = 0; i < s->read_msgfds_num; i++) {
2873 close(s->read_msgfds[i]);
2875 g_free(s->read_msgfds);
2876 s->read_msgfds = NULL;
2877 s->read_msgfds_num = 0;
2880 tcp_set_msgfds(chr, NULL, 0);
2881 remove_fd_in_watch(chr);
2882 object_unref(OBJECT(s->sioc));
2883 s->sioc = NULL;
2884 object_unref(OBJECT(s->ioc));
2885 s->ioc = NULL;
2886 g_free(chr->filename);
2887 chr->filename = NULL;
2888 s->connected = 0;
2891 static void tcp_chr_disconnect(CharDriverState *chr)
2893 TCPCharDriver *s = chr->opaque;
2895 if (!s->connected) {
2896 return;
2899 tcp_chr_free_connection(chr);
2901 if (s->listen_ioc) {
2902 s->listen_tag = qio_channel_add_watch(
2903 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
2905 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
2906 s->is_listen, s->is_telnet);
2907 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2908 if (s->reconnect_time) {
2909 qemu_chr_socket_restart_timer(chr);
2913 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2915 CharDriverState *chr = opaque;
2916 TCPCharDriver *s = chr->opaque;
2917 uint8_t buf[READ_BUF_LEN];
2918 int len, size;
2920 if (!s->connected || s->max_size <= 0) {
2921 return TRUE;
2923 len = sizeof(buf);
2924 if (len > s->max_size)
2925 len = s->max_size;
2926 size = tcp_chr_recv(chr, (void *)buf, len);
2927 if (size == 0 || size == -1) {
2928 /* connection closed */
2929 tcp_chr_disconnect(chr);
2930 } else if (size > 0) {
2931 if (s->do_telnetopt)
2932 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2933 if (size > 0)
2934 qemu_chr_be_write(chr, buf, size);
2937 return TRUE;
2940 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2942 TCPCharDriver *s = chr->opaque;
2943 int size;
2945 if (!s->connected) {
2946 return 0;
2949 size = tcp_chr_recv(chr, (void *) buf, len);
2950 if (size == 0) {
2951 /* connection closed */
2952 tcp_chr_disconnect(chr);
2955 return size;
2958 static void tcp_chr_connect(void *opaque)
2960 CharDriverState *chr = opaque;
2961 TCPCharDriver *s = chr->opaque;
2963 g_free(chr->filename);
2964 chr->filename = sockaddr_to_str(
2965 &s->sioc->localAddr, s->sioc->localAddrLen,
2966 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
2967 s->is_listen, s->is_telnet);
2969 s->connected = 1;
2970 if (s->ioc) {
2971 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2972 tcp_chr_read_poll,
2973 tcp_chr_read, chr);
2975 qemu_chr_be_generic_open(chr);
2978 static void tcp_chr_update_read_handler(CharDriverState *chr)
2980 TCPCharDriver *s = chr->opaque;
2982 if (!s->connected) {
2983 return;
2986 remove_fd_in_watch(chr);
2987 if (s->ioc) {
2988 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2989 tcp_chr_read_poll,
2990 tcp_chr_read, chr);
2994 typedef struct {
2995 CharDriverState *chr;
2996 char buf[12];
2997 size_t buflen;
2998 } TCPCharDriverTelnetInit;
3000 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
3001 GIOCondition cond G_GNUC_UNUSED,
3002 gpointer user_data)
3004 TCPCharDriverTelnetInit *init = user_data;
3005 ssize_t ret;
3007 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
3008 if (ret < 0) {
3009 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3010 ret = 0;
3011 } else {
3012 tcp_chr_disconnect(init->chr);
3013 return FALSE;
3016 init->buflen -= ret;
3018 if (init->buflen == 0) {
3019 tcp_chr_connect(init->chr);
3020 return FALSE;
3023 memmove(init->buf, init->buf + ret, init->buflen);
3025 return TRUE;
3028 static void tcp_chr_telnet_init(CharDriverState *chr)
3030 TCPCharDriver *s = chr->opaque;
3031 TCPCharDriverTelnetInit *init =
3032 g_new0(TCPCharDriverTelnetInit, 1);
3033 size_t n = 0;
3035 init->chr = chr;
3036 init->buflen = 12;
3038 #define IACSET(x, a, b, c) \
3039 do { \
3040 x[n++] = a; \
3041 x[n++] = b; \
3042 x[n++] = c; \
3043 } while (0)
3045 /* Prep the telnet negotion to put telnet in binary,
3046 * no echo, single char mode */
3047 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3048 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3049 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3050 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3052 #undef IACSET
3054 qio_channel_add_watch(
3055 s->ioc, G_IO_OUT,
3056 tcp_chr_telnet_init_io,
3057 init, NULL);
3061 static void tcp_chr_tls_handshake(Object *source,
3062 Error *err,
3063 gpointer user_data)
3065 CharDriverState *chr = user_data;
3066 TCPCharDriver *s = chr->opaque;
3068 if (err) {
3069 tcp_chr_disconnect(chr);
3070 } else {
3071 if (s->do_telnetopt) {
3072 tcp_chr_telnet_init(chr);
3073 } else {
3074 tcp_chr_connect(chr);
3080 static void tcp_chr_tls_init(CharDriverState *chr)
3082 TCPCharDriver *s = chr->opaque;
3083 QIOChannelTLS *tioc;
3084 Error *err = NULL;
3086 if (s->is_listen) {
3087 tioc = qio_channel_tls_new_server(
3088 s->ioc, s->tls_creds,
3089 NULL, /* XXX Use an ACL */
3090 &err);
3091 } else {
3092 tioc = qio_channel_tls_new_client(
3093 s->ioc, s->tls_creds,
3094 s->addr->u.inet.data->host,
3095 &err);
3097 if (tioc == NULL) {
3098 error_free(err);
3099 tcp_chr_disconnect(chr);
3101 object_unref(OBJECT(s->ioc));
3102 s->ioc = QIO_CHANNEL(tioc);
3104 qio_channel_tls_handshake(tioc,
3105 tcp_chr_tls_handshake,
3106 chr,
3107 NULL);
3111 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3113 TCPCharDriver *s = chr->opaque;
3114 if (s->ioc != NULL) {
3115 return -1;
3118 s->ioc = QIO_CHANNEL(sioc);
3119 object_ref(OBJECT(sioc));
3120 s->sioc = sioc;
3121 object_ref(OBJECT(sioc));
3123 qio_channel_set_blocking(s->ioc, false, NULL);
3125 if (s->do_nodelay) {
3126 qio_channel_set_delay(s->ioc, false);
3128 if (s->listen_tag) {
3129 g_source_remove(s->listen_tag);
3130 s->listen_tag = 0;
3133 if (s->tls_creds) {
3134 tcp_chr_tls_init(chr);
3135 } else {
3136 if (s->do_telnetopt) {
3137 tcp_chr_telnet_init(chr);
3138 } else {
3139 tcp_chr_connect(chr);
3143 return 0;
3147 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3149 int ret;
3150 QIOChannelSocket *sioc;
3152 sioc = qio_channel_socket_new_fd(fd, NULL);
3153 if (!sioc) {
3154 return -1;
3156 ret = tcp_chr_new_client(chr, sioc);
3157 object_unref(OBJECT(sioc));
3158 return ret;
3161 static gboolean tcp_chr_accept(QIOChannel *channel,
3162 GIOCondition cond,
3163 void *opaque)
3165 CharDriverState *chr = opaque;
3166 QIOChannelSocket *sioc;
3168 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3169 NULL);
3170 if (!sioc) {
3171 return TRUE;
3174 tcp_chr_new_client(chr, sioc);
3176 object_unref(OBJECT(sioc));
3178 return TRUE;
3181 static int tcp_chr_wait_connected(CharDriverState *chr, Error **errp)
3183 TCPCharDriver *s = chr->opaque;
3184 QIOChannelSocket *sioc;
3186 /* It can't wait on s->connected, since it is set asynchronously
3187 * in TLS and telnet cases, only wait for an accepted socket */
3188 while (!s->ioc) {
3189 if (s->is_listen) {
3190 fprintf(stderr, "QEMU waiting for connection on: %s\n",
3191 chr->filename);
3192 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), true, NULL);
3193 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
3194 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
3195 } else {
3196 sioc = qio_channel_socket_new();
3197 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3198 object_unref(OBJECT(sioc));
3199 return -1;
3201 tcp_chr_new_client(chr, sioc);
3202 object_unref(OBJECT(sioc));
3206 return 0;
3209 int qemu_chr_wait_connected(CharDriverState *chr, Error **errp)
3211 if (chr->chr_wait_connected) {
3212 return chr->chr_wait_connected(chr, errp);
3215 return 0;
3218 static void tcp_chr_close(CharDriverState *chr)
3220 TCPCharDriver *s = chr->opaque;
3222 tcp_chr_free_connection(chr);
3224 if (s->reconnect_timer) {
3225 g_source_remove(s->reconnect_timer);
3226 s->reconnect_timer = 0;
3228 qapi_free_SocketAddress(s->addr);
3229 if (s->listen_tag) {
3230 g_source_remove(s->listen_tag);
3231 s->listen_tag = 0;
3233 if (s->listen_ioc) {
3234 object_unref(OBJECT(s->listen_ioc));
3236 if (s->tls_creds) {
3237 object_unref(OBJECT(s->tls_creds));
3239 g_free(s);
3240 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3244 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3246 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3247 CharDriverState *chr = opaque;
3248 TCPCharDriver *s = chr->opaque;
3250 if (err) {
3251 check_report_connect_error(chr, err);
3252 object_unref(src);
3253 return;
3256 s->connect_err_reported = false;
3257 tcp_chr_new_client(chr, sioc);
3258 object_unref(OBJECT(sioc));
3262 /*********************************************************/
3263 /* Ring buffer chardev */
3265 typedef struct {
3266 size_t size;
3267 size_t prod;
3268 size_t cons;
3269 uint8_t *cbuf;
3270 } RingBufCharDriver;
3272 static size_t ringbuf_count(const CharDriverState *chr)
3274 const RingBufCharDriver *d = chr->opaque;
3276 return d->prod - d->cons;
3279 /* Called with chr_write_lock held. */
3280 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3282 RingBufCharDriver *d = chr->opaque;
3283 int i;
3285 if (!buf || (len < 0)) {
3286 return -1;
3289 for (i = 0; i < len; i++ ) {
3290 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3291 if (d->prod - d->cons > d->size) {
3292 d->cons = d->prod - d->size;
3296 return 0;
3299 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3301 RingBufCharDriver *d = chr->opaque;
3302 int i;
3304 qemu_mutex_lock(&chr->chr_write_lock);
3305 for (i = 0; i < len && d->cons != d->prod; i++) {
3306 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3308 qemu_mutex_unlock(&chr->chr_write_lock);
3310 return i;
3313 static void ringbuf_chr_close(struct CharDriverState *chr)
3315 RingBufCharDriver *d = chr->opaque;
3317 g_free(d->cbuf);
3318 g_free(d);
3319 chr->opaque = NULL;
3322 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3323 ChardevBackend *backend,
3324 ChardevReturn *ret,
3325 Error **errp)
3327 ChardevRingbuf *opts = backend->u.ringbuf.data;
3328 ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
3329 CharDriverState *chr;
3330 RingBufCharDriver *d;
3332 chr = qemu_chr_alloc(common, errp);
3333 if (!chr) {
3334 return NULL;
3336 d = g_malloc(sizeof(*d));
3338 d->size = opts->has_size ? opts->size : 65536;
3340 /* The size must be power of 2 */
3341 if (d->size & (d->size - 1)) {
3342 error_setg(errp, "size of ringbuf chardev must be power of two");
3343 goto fail;
3346 d->prod = 0;
3347 d->cons = 0;
3348 d->cbuf = g_malloc0(d->size);
3350 chr->opaque = d;
3351 chr->chr_write = ringbuf_chr_write;
3352 chr->chr_close = ringbuf_chr_close;
3354 return chr;
3356 fail:
3357 g_free(d);
3358 qemu_chr_free_common(chr);
3359 return NULL;
3362 bool chr_is_ringbuf(const CharDriverState *chr)
3364 return chr->chr_write == ringbuf_chr_write;
3367 void qmp_ringbuf_write(const char *device, const char *data,
3368 bool has_format, enum DataFormat format,
3369 Error **errp)
3371 CharDriverState *chr;
3372 const uint8_t *write_data;
3373 int ret;
3374 gsize write_count;
3376 chr = qemu_chr_find(device);
3377 if (!chr) {
3378 error_setg(errp, "Device '%s' not found", device);
3379 return;
3382 if (!chr_is_ringbuf(chr)) {
3383 error_setg(errp,"%s is not a ringbuf device", device);
3384 return;
3387 if (has_format && (format == DATA_FORMAT_BASE64)) {
3388 write_data = qbase64_decode(data, -1,
3389 &write_count,
3390 errp);
3391 if (!write_data) {
3392 return;
3394 } else {
3395 write_data = (uint8_t *)data;
3396 write_count = strlen(data);
3399 ret = ringbuf_chr_write(chr, write_data, write_count);
3401 if (write_data != (uint8_t *)data) {
3402 g_free((void *)write_data);
3405 if (ret < 0) {
3406 error_setg(errp, "Failed to write to device %s", device);
3407 return;
3411 char *qmp_ringbuf_read(const char *device, int64_t size,
3412 bool has_format, enum DataFormat format,
3413 Error **errp)
3415 CharDriverState *chr;
3416 uint8_t *read_data;
3417 size_t count;
3418 char *data;
3420 chr = qemu_chr_find(device);
3421 if (!chr) {
3422 error_setg(errp, "Device '%s' not found", device);
3423 return NULL;
3426 if (!chr_is_ringbuf(chr)) {
3427 error_setg(errp,"%s is not a ringbuf device", device);
3428 return NULL;
3431 if (size <= 0) {
3432 error_setg(errp, "size must be greater than zero");
3433 return NULL;
3436 count = ringbuf_count(chr);
3437 size = size > count ? count : size;
3438 read_data = g_malloc(size + 1);
3440 ringbuf_chr_read(chr, read_data, size);
3442 if (has_format && (format == DATA_FORMAT_BASE64)) {
3443 data = g_base64_encode(read_data, size);
3444 g_free(read_data);
3445 } else {
3447 * FIXME should read only complete, valid UTF-8 characters up
3448 * to @size bytes. Invalid sequences should be replaced by a
3449 * suitable replacement character. Except when (and only
3450 * when) ring buffer lost characters since last read, initial
3451 * continuation characters should be dropped.
3453 read_data[size] = 0;
3454 data = (char *)read_data;
3457 return data;
3460 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3462 char host[65], port[33], width[8], height[8];
3463 int pos;
3464 const char *p;
3465 QemuOpts *opts;
3466 Error *local_err = NULL;
3468 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3469 if (local_err) {
3470 error_report_err(local_err);
3471 return NULL;
3474 if (strstart(filename, "mon:", &p)) {
3475 filename = p;
3476 qemu_opt_set(opts, "mux", "on", &error_abort);
3477 if (strcmp(filename, "stdio") == 0) {
3478 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3479 * but pass it to the guest. Handle this only for compat syntax,
3480 * for -chardev syntax we have special option for this.
3481 * This is what -nographic did, redirecting+muxing serial+monitor
3482 * to stdio causing Ctrl+C to be passed to guest. */
3483 qemu_opt_set(opts, "signal", "off", &error_abort);
3487 if (strcmp(filename, "null") == 0 ||
3488 strcmp(filename, "pty") == 0 ||
3489 strcmp(filename, "msmouse") == 0 ||
3490 strcmp(filename, "braille") == 0 ||
3491 strcmp(filename, "testdev") == 0 ||
3492 strcmp(filename, "stdio") == 0) {
3493 qemu_opt_set(opts, "backend", filename, &error_abort);
3494 return opts;
3496 if (strstart(filename, "vc", &p)) {
3497 qemu_opt_set(opts, "backend", "vc", &error_abort);
3498 if (*p == ':') {
3499 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3500 /* pixels */
3501 qemu_opt_set(opts, "width", width, &error_abort);
3502 qemu_opt_set(opts, "height", height, &error_abort);
3503 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3504 /* chars */
3505 qemu_opt_set(opts, "cols", width, &error_abort);
3506 qemu_opt_set(opts, "rows", height, &error_abort);
3507 } else {
3508 goto fail;
3511 return opts;
3513 if (strcmp(filename, "con:") == 0) {
3514 qemu_opt_set(opts, "backend", "console", &error_abort);
3515 return opts;
3517 if (strstart(filename, "COM", NULL)) {
3518 qemu_opt_set(opts, "backend", "serial", &error_abort);
3519 qemu_opt_set(opts, "path", filename, &error_abort);
3520 return opts;
3522 if (strstart(filename, "file:", &p)) {
3523 qemu_opt_set(opts, "backend", "file", &error_abort);
3524 qemu_opt_set(opts, "path", p, &error_abort);
3525 return opts;
3527 if (strstart(filename, "pipe:", &p)) {
3528 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3529 qemu_opt_set(opts, "path", p, &error_abort);
3530 return opts;
3532 if (strstart(filename, "tcp:", &p) ||
3533 strstart(filename, "telnet:", &p)) {
3534 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3535 host[0] = 0;
3536 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3537 goto fail;
3539 qemu_opt_set(opts, "backend", "socket", &error_abort);
3540 qemu_opt_set(opts, "host", host, &error_abort);
3541 qemu_opt_set(opts, "port", port, &error_abort);
3542 if (p[pos] == ',') {
3543 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3544 if (local_err) {
3545 error_report_err(local_err);
3546 goto fail;
3549 if (strstart(filename, "telnet:", &p))
3550 qemu_opt_set(opts, "telnet", "on", &error_abort);
3551 return opts;
3553 if (strstart(filename, "udp:", &p)) {
3554 qemu_opt_set(opts, "backend", "udp", &error_abort);
3555 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3556 host[0] = 0;
3557 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3558 goto fail;
3561 qemu_opt_set(opts, "host", host, &error_abort);
3562 qemu_opt_set(opts, "port", port, &error_abort);
3563 if (p[pos] == '@') {
3564 p += pos + 1;
3565 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3566 host[0] = 0;
3567 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3568 goto fail;
3571 qemu_opt_set(opts, "localaddr", host, &error_abort);
3572 qemu_opt_set(opts, "localport", port, &error_abort);
3574 return opts;
3576 if (strstart(filename, "unix:", &p)) {
3577 qemu_opt_set(opts, "backend", "socket", &error_abort);
3578 qemu_opts_do_parse(opts, p, "path", &local_err);
3579 if (local_err) {
3580 error_report_err(local_err);
3581 goto fail;
3583 return opts;
3585 if (strstart(filename, "/dev/parport", NULL) ||
3586 strstart(filename, "/dev/ppi", NULL)) {
3587 qemu_opt_set(opts, "backend", "parport", &error_abort);
3588 qemu_opt_set(opts, "path", filename, &error_abort);
3589 return opts;
3591 if (strstart(filename, "/dev/", NULL)) {
3592 qemu_opt_set(opts, "backend", "tty", &error_abort);
3593 qemu_opt_set(opts, "path", filename, &error_abort);
3594 return opts;
3597 fail:
3598 qemu_opts_del(opts);
3599 return NULL;
3602 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3604 const char *logfile = qemu_opt_get(opts, "logfile");
3606 backend->has_logfile = logfile != NULL;
3607 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3609 backend->has_logappend = true;
3610 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3614 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3615 Error **errp)
3617 const char *path = qemu_opt_get(opts, "path");
3618 ChardevFile *file;
3620 if (path == NULL) {
3621 error_setg(errp, "chardev: file: no filename given");
3622 return;
3624 file = backend->u.file.data = g_new0(ChardevFile, 1);
3625 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3626 file->out = g_strdup(path);
3628 file->has_append = true;
3629 file->append = qemu_opt_get_bool(opts, "append", false);
3632 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3633 Error **errp)
3635 ChardevStdio *stdio;
3637 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3638 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3639 stdio->has_signal = true;
3640 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3643 #ifdef HAVE_CHARDEV_SERIAL
3644 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3645 Error **errp)
3647 const char *device = qemu_opt_get(opts, "path");
3648 ChardevHostdev *serial;
3650 if (device == NULL) {
3651 error_setg(errp, "chardev: serial/tty: no device path given");
3652 return;
3654 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3655 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3656 serial->device = g_strdup(device);
3658 #endif
3660 #ifdef HAVE_CHARDEV_PARPORT
3661 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3662 Error **errp)
3664 const char *device = qemu_opt_get(opts, "path");
3665 ChardevHostdev *parallel;
3667 if (device == NULL) {
3668 error_setg(errp, "chardev: parallel: no device path given");
3669 return;
3671 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3672 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3673 parallel->device = g_strdup(device);
3675 #endif
3677 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3678 Error **errp)
3680 const char *device = qemu_opt_get(opts, "path");
3681 ChardevHostdev *dev;
3683 if (device == NULL) {
3684 error_setg(errp, "chardev: pipe: no device path given");
3685 return;
3687 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3688 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3689 dev->device = g_strdup(device);
3692 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3693 Error **errp)
3695 int val;
3696 ChardevRingbuf *ringbuf;
3698 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3699 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3701 val = qemu_opt_get_size(opts, "size", 0);
3702 if (val != 0) {
3703 ringbuf->has_size = true;
3704 ringbuf->size = val;
3708 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3709 Error **errp)
3711 const char *chardev = qemu_opt_get(opts, "chardev");
3712 ChardevMux *mux;
3714 if (chardev == NULL) {
3715 error_setg(errp, "chardev: mux: no chardev given");
3716 return;
3718 mux = backend->u.mux.data = g_new0(ChardevMux, 1);
3719 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
3720 mux->chardev = g_strdup(chardev);
3723 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3724 Error **errp)
3726 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3727 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3728 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3729 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3730 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3731 const char *path = qemu_opt_get(opts, "path");
3732 const char *host = qemu_opt_get(opts, "host");
3733 const char *port = qemu_opt_get(opts, "port");
3734 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3735 SocketAddress *addr;
3736 ChardevSocket *sock;
3738 if (!path) {
3739 if (!host) {
3740 error_setg(errp, "chardev: socket: no host given");
3741 return;
3743 if (!port) {
3744 error_setg(errp, "chardev: socket: no port given");
3745 return;
3747 } else {
3748 if (tls_creds) {
3749 error_setg(errp, "TLS can only be used over TCP socket");
3750 return;
3754 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
3755 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
3757 sock->has_nodelay = true;
3758 sock->nodelay = do_nodelay;
3759 sock->has_server = true;
3760 sock->server = is_listen;
3761 sock->has_telnet = true;
3762 sock->telnet = is_telnet;
3763 sock->has_wait = true;
3764 sock->wait = is_waitconnect;
3765 sock->has_reconnect = true;
3766 sock->reconnect = reconnect;
3767 sock->tls_creds = g_strdup(tls_creds);
3769 addr = g_new0(SocketAddress, 1);
3770 if (path) {
3771 UnixSocketAddress *q_unix;
3772 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3773 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
3774 q_unix->path = g_strdup(path);
3775 } else {
3776 addr->type = SOCKET_ADDRESS_KIND_INET;
3777 addr->u.inet.data = g_new(InetSocketAddress, 1);
3778 *addr->u.inet.data = (InetSocketAddress) {
3779 .host = g_strdup(host),
3780 .port = g_strdup(port),
3781 .has_to = qemu_opt_get(opts, "to"),
3782 .to = qemu_opt_get_number(opts, "to", 0),
3783 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3784 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3785 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3786 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3789 sock->addr = addr;
3792 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3793 Error **errp)
3795 const char *host = qemu_opt_get(opts, "host");
3796 const char *port = qemu_opt_get(opts, "port");
3797 const char *localaddr = qemu_opt_get(opts, "localaddr");
3798 const char *localport = qemu_opt_get(opts, "localport");
3799 bool has_local = false;
3800 SocketAddress *addr;
3801 ChardevUdp *udp;
3803 if (host == NULL || strlen(host) == 0) {
3804 host = "localhost";
3806 if (port == NULL || strlen(port) == 0) {
3807 error_setg(errp, "chardev: udp: remote port not specified");
3808 return;
3810 if (localport == NULL || strlen(localport) == 0) {
3811 localport = "0";
3812 } else {
3813 has_local = true;
3815 if (localaddr == NULL || strlen(localaddr) == 0) {
3816 localaddr = "";
3817 } else {
3818 has_local = true;
3821 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
3822 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
3824 addr = g_new0(SocketAddress, 1);
3825 addr->type = SOCKET_ADDRESS_KIND_INET;
3826 addr->u.inet.data = g_new(InetSocketAddress, 1);
3827 *addr->u.inet.data = (InetSocketAddress) {
3828 .host = g_strdup(host),
3829 .port = g_strdup(port),
3830 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3831 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3832 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3833 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3835 udp->remote = addr;
3837 if (has_local) {
3838 udp->has_local = true;
3839 addr = g_new0(SocketAddress, 1);
3840 addr->type = SOCKET_ADDRESS_KIND_INET;
3841 addr->u.inet.data = g_new(InetSocketAddress, 1);
3842 *addr->u.inet.data = (InetSocketAddress) {
3843 .host = g_strdup(localaddr),
3844 .port = g_strdup(localport),
3846 udp->local = addr;
3850 typedef struct CharDriver {
3851 const char *name;
3852 ChardevBackendKind kind;
3853 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3854 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3855 ChardevReturn *ret, Error **errp);
3856 } CharDriver;
3858 static GSList *backends;
3860 void register_char_driver(const char *name, ChardevBackendKind kind,
3861 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3862 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3863 ChardevReturn *ret, Error **errp))
3865 CharDriver *s;
3867 s = g_malloc0(sizeof(*s));
3868 s->name = g_strdup(name);
3869 s->kind = kind;
3870 s->parse = parse;
3871 s->create = create;
3873 backends = g_slist_append(backends, s);
3876 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3877 void (*init)(struct CharDriverState *s),
3878 Error **errp)
3880 Error *local_err = NULL;
3881 CharDriver *cd;
3882 CharDriverState *chr;
3883 GSList *i;
3884 ChardevReturn *ret = NULL;
3885 ChardevBackend *backend;
3886 const char *id = qemu_opts_id(opts);
3887 char *bid = NULL;
3889 if (qemu_opt_get(opts, "backend") == NULL) {
3890 error_setg(errp, "chardev: \"%s\" missing backend",
3891 qemu_opts_id(opts));
3892 goto err;
3895 if (is_help_option(qemu_opt_get(opts, "backend"))) {
3896 fprintf(stderr, "Available chardev backend types:\n");
3897 for (i = backends; i; i = i->next) {
3898 cd = i->data;
3899 fprintf(stderr, "%s\n", cd->name);
3901 exit(!is_help_option(qemu_opt_get(opts, "backend")));
3904 if (id == NULL) {
3905 error_setg(errp, "chardev: no id specified");
3906 goto err;
3909 for (i = backends; i; i = i->next) {
3910 cd = i->data;
3912 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3913 break;
3916 if (i == NULL) {
3917 error_setg(errp, "chardev: backend \"%s\" not found",
3918 qemu_opt_get(opts, "backend"));
3919 goto err;
3922 backend = g_new0(ChardevBackend, 1);
3924 if (qemu_opt_get_bool(opts, "mux", 0)) {
3925 bid = g_strdup_printf("%s-base", id);
3928 chr = NULL;
3929 backend->type = cd->kind;
3930 if (cd->parse) {
3931 cd->parse(opts, backend, &local_err);
3932 if (local_err) {
3933 error_propagate(errp, local_err);
3934 goto qapi_out;
3936 } else {
3937 ChardevCommon *cc = g_new0(ChardevCommon, 1);
3938 qemu_chr_parse_common(opts, cc);
3939 backend->u.null.data = cc; /* Any ChardevCommon member would work */
3942 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3943 if (!ret) {
3944 goto qapi_out;
3947 if (bid) {
3948 qapi_free_ChardevBackend(backend);
3949 qapi_free_ChardevReturn(ret);
3950 backend = g_new0(ChardevBackend, 1);
3951 backend->u.mux.data = g_new0(ChardevMux, 1);
3952 backend->type = CHARDEV_BACKEND_KIND_MUX;
3953 backend->u.mux.data->chardev = g_strdup(bid);
3954 ret = qmp_chardev_add(id, backend, errp);
3955 if (!ret) {
3956 chr = qemu_chr_find(bid);
3957 qemu_chr_delete(chr);
3958 chr = NULL;
3959 goto qapi_out;
3963 chr = qemu_chr_find(id);
3964 chr->opts = opts;
3966 qapi_out:
3967 qapi_free_ChardevBackend(backend);
3968 qapi_free_ChardevReturn(ret);
3969 g_free(bid);
3970 return chr;
3972 err:
3973 qemu_opts_del(opts);
3974 return NULL;
3977 CharDriverState *qemu_chr_new_noreplay(const char *label, const char *filename,
3978 void (*init)(struct CharDriverState *s))
3980 const char *p;
3981 CharDriverState *chr;
3982 QemuOpts *opts;
3983 Error *err = NULL;
3985 if (strstart(filename, "chardev:", &p)) {
3986 return qemu_chr_find(p);
3989 opts = qemu_chr_parse_compat(label, filename);
3990 if (!opts)
3991 return NULL;
3993 chr = qemu_chr_new_from_opts(opts, init, &err);
3994 if (err) {
3995 error_report_err(err);
3997 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3998 qemu_chr_fe_claim_no_fail(chr);
3999 monitor_init(chr, MONITOR_USE_READLINE);
4001 return chr;
4004 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
4006 CharDriverState *chr;
4007 chr = qemu_chr_new_noreplay(label, filename, init);
4008 if (chr) {
4009 chr->replay = replay_mode != REPLAY_MODE_NONE;
4010 if (chr->replay && chr->chr_ioctl) {
4011 fprintf(stderr,
4012 "Replay: ioctl is not supported for serial devices yet\n");
4014 replay_register_char_driver(chr);
4016 return chr;
4019 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
4021 if (chr->chr_set_echo) {
4022 chr->chr_set_echo(chr, echo);
4026 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
4028 if (chr->fe_open == fe_open) {
4029 return;
4031 chr->fe_open = fe_open;
4032 if (chr->chr_set_fe_open) {
4033 chr->chr_set_fe_open(chr, fe_open);
4037 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
4039 if (chr->chr_fe_event) {
4040 chr->chr_fe_event(chr, event);
4044 guint qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
4045 GIOFunc func, void *user_data)
4047 GSource *src;
4048 guint tag;
4050 if (s->chr_add_watch == NULL) {
4051 return 0;
4054 src = s->chr_add_watch(s, cond);
4055 if (!src) {
4056 return 0;
4059 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
4060 tag = g_source_attach(src, NULL);
4061 g_source_unref(src);
4063 return tag;
4066 int qemu_chr_fe_claim(CharDriverState *s)
4068 if (s->avail_connections < 1) {
4069 return -1;
4071 s->avail_connections--;
4072 return 0;
4075 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
4077 if (qemu_chr_fe_claim(s) != 0) {
4078 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
4079 __func__, s->label);
4080 exit(1);
4084 void qemu_chr_fe_release(CharDriverState *s)
4086 s->avail_connections++;
4089 void qemu_chr_disconnect(CharDriverState *chr)
4091 if (chr->chr_disconnect) {
4092 chr->chr_disconnect(chr);
4096 static void qemu_chr_free_common(CharDriverState *chr)
4098 g_free(chr->filename);
4099 g_free(chr->label);
4100 qemu_opts_del(chr->opts);
4101 if (chr->logfd != -1) {
4102 close(chr->logfd);
4104 qemu_mutex_destroy(&chr->chr_write_lock);
4105 g_free(chr);
4108 void qemu_chr_free(CharDriverState *chr)
4110 if (chr->chr_close) {
4111 chr->chr_close(chr);
4113 qemu_chr_free_common(chr);
4116 void qemu_chr_delete(CharDriverState *chr)
4118 QTAILQ_REMOVE(&chardevs, chr, next);
4119 qemu_chr_free(chr);
4122 ChardevInfoList *qmp_query_chardev(Error **errp)
4124 ChardevInfoList *chr_list = NULL;
4125 CharDriverState *chr;
4127 QTAILQ_FOREACH(chr, &chardevs, next) {
4128 ChardevInfoList *info = g_malloc0(sizeof(*info));
4129 info->value = g_malloc0(sizeof(*info->value));
4130 info->value->label = g_strdup(chr->label);
4131 info->value->filename = g_strdup(chr->filename);
4132 info->value->frontend_open = chr->fe_open;
4134 info->next = chr_list;
4135 chr_list = info;
4138 return chr_list;
4141 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4143 ChardevBackendInfoList *backend_list = NULL;
4144 CharDriver *c = NULL;
4145 GSList *i = NULL;
4147 for (i = backends; i; i = i->next) {
4148 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4149 c = i->data;
4150 info->value = g_malloc0(sizeof(*info->value));
4151 info->value->name = g_strdup(c->name);
4153 info->next = backend_list;
4154 backend_list = info;
4157 return backend_list;
4160 CharDriverState *qemu_chr_find(const char *name)
4162 CharDriverState *chr;
4164 QTAILQ_FOREACH(chr, &chardevs, next) {
4165 if (strcmp(chr->label, name) != 0)
4166 continue;
4167 return chr;
4169 return NULL;
4172 QemuOptsList qemu_chardev_opts = {
4173 .name = "chardev",
4174 .implied_opt_name = "backend",
4175 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4176 .desc = {
4178 .name = "backend",
4179 .type = QEMU_OPT_STRING,
4181 .name = "path",
4182 .type = QEMU_OPT_STRING,
4184 .name = "host",
4185 .type = QEMU_OPT_STRING,
4187 .name = "port",
4188 .type = QEMU_OPT_STRING,
4190 .name = "localaddr",
4191 .type = QEMU_OPT_STRING,
4193 .name = "localport",
4194 .type = QEMU_OPT_STRING,
4196 .name = "to",
4197 .type = QEMU_OPT_NUMBER,
4199 .name = "ipv4",
4200 .type = QEMU_OPT_BOOL,
4202 .name = "ipv6",
4203 .type = QEMU_OPT_BOOL,
4205 .name = "wait",
4206 .type = QEMU_OPT_BOOL,
4208 .name = "server",
4209 .type = QEMU_OPT_BOOL,
4211 .name = "delay",
4212 .type = QEMU_OPT_BOOL,
4214 .name = "reconnect",
4215 .type = QEMU_OPT_NUMBER,
4217 .name = "telnet",
4218 .type = QEMU_OPT_BOOL,
4220 .name = "tls-creds",
4221 .type = QEMU_OPT_STRING,
4223 .name = "width",
4224 .type = QEMU_OPT_NUMBER,
4226 .name = "height",
4227 .type = QEMU_OPT_NUMBER,
4229 .name = "cols",
4230 .type = QEMU_OPT_NUMBER,
4232 .name = "rows",
4233 .type = QEMU_OPT_NUMBER,
4235 .name = "mux",
4236 .type = QEMU_OPT_BOOL,
4238 .name = "signal",
4239 .type = QEMU_OPT_BOOL,
4241 .name = "name",
4242 .type = QEMU_OPT_STRING,
4244 .name = "debug",
4245 .type = QEMU_OPT_NUMBER,
4247 .name = "size",
4248 .type = QEMU_OPT_SIZE,
4250 .name = "chardev",
4251 .type = QEMU_OPT_STRING,
4253 .name = "append",
4254 .type = QEMU_OPT_BOOL,
4256 .name = "logfile",
4257 .type = QEMU_OPT_STRING,
4259 .name = "logappend",
4260 .type = QEMU_OPT_BOOL,
4262 { /* end of list */ }
4266 #ifdef _WIN32
4268 static CharDriverState *qmp_chardev_open_file(const char *id,
4269 ChardevBackend *backend,
4270 ChardevReturn *ret,
4271 Error **errp)
4273 ChardevFile *file = backend->u.file.data;
4274 ChardevCommon *common = qapi_ChardevFile_base(file);
4275 HANDLE out;
4276 DWORD accessmode;
4277 DWORD flags;
4279 if (file->has_in) {
4280 error_setg(errp, "input file not supported");
4281 return NULL;
4284 if (file->has_append && file->append) {
4285 /* Append to file if it already exists. */
4286 accessmode = FILE_GENERIC_WRITE & ~FILE_WRITE_DATA;
4287 flags = OPEN_ALWAYS;
4288 } else {
4289 /* Truncate file if it already exists. */
4290 accessmode = GENERIC_WRITE;
4291 flags = CREATE_ALWAYS;
4294 out = CreateFile(file->out, accessmode, FILE_SHARE_READ, NULL, flags,
4295 FILE_ATTRIBUTE_NORMAL, NULL);
4296 if (out == INVALID_HANDLE_VALUE) {
4297 error_setg(errp, "open %s failed", file->out);
4298 return NULL;
4300 return qemu_chr_open_win_file(out, common, errp);
4303 static CharDriverState *qmp_chardev_open_serial(const char *id,
4304 ChardevBackend *backend,
4305 ChardevReturn *ret,
4306 Error **errp)
4308 ChardevHostdev *serial = backend->u.serial.data;
4309 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4310 return qemu_chr_open_win_path(serial->device, common, errp);
4313 #else /* WIN32 */
4315 static int qmp_chardev_open_file_source(char *src, int flags,
4316 Error **errp)
4318 int fd = -1;
4320 TFR(fd = qemu_open(src, flags, 0666));
4321 if (fd == -1) {
4322 error_setg_file_open(errp, errno, src);
4324 return fd;
4327 static CharDriverState *qmp_chardev_open_file(const char *id,
4328 ChardevBackend *backend,
4329 ChardevReturn *ret,
4330 Error **errp)
4332 ChardevFile *file = backend->u.file.data;
4333 ChardevCommon *common = qapi_ChardevFile_base(file);
4334 int flags, in = -1, out;
4336 flags = O_WRONLY | O_CREAT | O_BINARY;
4337 if (file->has_append && file->append) {
4338 flags |= O_APPEND;
4339 } else {
4340 flags |= O_TRUNC;
4343 out = qmp_chardev_open_file_source(file->out, flags, errp);
4344 if (out < 0) {
4345 return NULL;
4348 if (file->has_in) {
4349 flags = O_RDONLY;
4350 in = qmp_chardev_open_file_source(file->in, flags, errp);
4351 if (in < 0) {
4352 qemu_close(out);
4353 return NULL;
4357 return qemu_chr_open_fd(in, out, common, errp);
4360 #ifdef HAVE_CHARDEV_SERIAL
4361 static CharDriverState *qmp_chardev_open_serial(const char *id,
4362 ChardevBackend *backend,
4363 ChardevReturn *ret,
4364 Error **errp)
4366 ChardevHostdev *serial = backend->u.serial.data;
4367 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4368 int fd;
4370 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4371 if (fd < 0) {
4372 return NULL;
4374 qemu_set_nonblock(fd);
4375 return qemu_chr_open_tty_fd(fd, common, errp);
4377 #endif
4379 #ifdef HAVE_CHARDEV_PARPORT
4380 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4381 ChardevBackend *backend,
4382 ChardevReturn *ret,
4383 Error **errp)
4385 ChardevHostdev *parallel = backend->u.parallel.data;
4386 ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
4387 int fd;
4389 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4390 if (fd < 0) {
4391 return NULL;
4393 return qemu_chr_open_pp_fd(fd, common, errp);
4395 #endif
4397 #endif /* WIN32 */
4399 static gboolean socket_reconnect_timeout(gpointer opaque)
4401 CharDriverState *chr = opaque;
4402 TCPCharDriver *s = chr->opaque;
4403 QIOChannelSocket *sioc;
4405 s->reconnect_timer = 0;
4407 if (chr->be_open) {
4408 return false;
4411 sioc = qio_channel_socket_new();
4412 qio_channel_socket_connect_async(sioc, s->addr,
4413 qemu_chr_socket_connected,
4414 chr, NULL);
4416 return false;
4419 static CharDriverState *qmp_chardev_open_socket(const char *id,
4420 ChardevBackend *backend,
4421 ChardevReturn *ret,
4422 Error **errp)
4424 CharDriverState *chr;
4425 TCPCharDriver *s;
4426 ChardevSocket *sock = backend->u.socket.data;
4427 SocketAddress *addr = sock->addr;
4428 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4429 bool is_listen = sock->has_server ? sock->server : true;
4430 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4431 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4432 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4433 ChardevCommon *common = qapi_ChardevSocket_base(sock);
4434 QIOChannelSocket *sioc = NULL;
4436 chr = qemu_chr_alloc(common, errp);
4437 if (!chr) {
4438 return NULL;
4440 s = g_new0(TCPCharDriver, 1);
4442 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4443 s->is_listen = is_listen;
4444 s->is_telnet = is_telnet;
4445 s->do_nodelay = do_nodelay;
4446 if (sock->tls_creds) {
4447 Object *creds;
4448 creds = object_resolve_path_component(
4449 object_get_objects_root(), sock->tls_creds);
4450 if (!creds) {
4451 error_setg(errp, "No TLS credentials with id '%s'",
4452 sock->tls_creds);
4453 goto error;
4455 s->tls_creds = (QCryptoTLSCreds *)
4456 object_dynamic_cast(creds,
4457 TYPE_QCRYPTO_TLS_CREDS);
4458 if (!s->tls_creds) {
4459 error_setg(errp, "Object with id '%s' is not TLS credentials",
4460 sock->tls_creds);
4461 goto error;
4463 object_ref(OBJECT(s->tls_creds));
4464 if (is_listen) {
4465 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4466 error_setg(errp, "%s",
4467 "Expected TLS credentials for server endpoint");
4468 goto error;
4470 } else {
4471 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4472 error_setg(errp, "%s",
4473 "Expected TLS credentials for client endpoint");
4474 goto error;
4479 s->addr = QAPI_CLONE(SocketAddress, sock->addr);
4481 chr->opaque = s;
4482 chr->chr_wait_connected = tcp_chr_wait_connected;
4483 chr->chr_write = tcp_chr_write;
4484 chr->chr_sync_read = tcp_chr_sync_read;
4485 chr->chr_close = tcp_chr_close;
4486 chr->chr_disconnect = tcp_chr_disconnect;
4487 chr->get_msgfds = tcp_get_msgfds;
4488 chr->set_msgfds = tcp_set_msgfds;
4489 chr->chr_add_client = tcp_chr_add_client;
4490 chr->chr_add_watch = tcp_chr_add_watch;
4491 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4492 /* be isn't opened until we get a connection */
4493 chr->explicit_be_open = true;
4495 chr->filename = SocketAddress_to_str("disconnected:",
4496 addr, is_listen, is_telnet);
4498 if (is_listen) {
4499 if (is_telnet) {
4500 s->do_telnetopt = 1;
4502 } else if (reconnect > 0) {
4503 s->reconnect_time = reconnect;
4506 if (s->reconnect_time) {
4507 sioc = qio_channel_socket_new();
4508 qio_channel_socket_connect_async(sioc, s->addr,
4509 qemu_chr_socket_connected,
4510 chr, NULL);
4511 } else {
4512 if (s->is_listen) {
4513 sioc = qio_channel_socket_new();
4514 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4515 goto error;
4517 s->listen_ioc = sioc;
4518 if (is_waitconnect &&
4519 qemu_chr_wait_connected(chr, errp) < 0) {
4520 goto error;
4522 if (!s->ioc) {
4523 s->listen_tag = qio_channel_add_watch(
4524 QIO_CHANNEL(s->listen_ioc), G_IO_IN,
4525 tcp_chr_accept, chr, NULL);
4527 } else if (qemu_chr_wait_connected(chr, errp) < 0) {
4528 goto error;
4532 return chr;
4534 error:
4535 if (sioc) {
4536 object_unref(OBJECT(sioc));
4538 if (s->tls_creds) {
4539 object_unref(OBJECT(s->tls_creds));
4541 g_free(s);
4542 qemu_chr_free_common(chr);
4543 return NULL;
4546 static CharDriverState *qmp_chardev_open_udp(const char *id,
4547 ChardevBackend *backend,
4548 ChardevReturn *ret,
4549 Error **errp)
4551 ChardevUdp *udp = backend->u.udp.data;
4552 ChardevCommon *common = qapi_ChardevUdp_base(udp);
4553 QIOChannelSocket *sioc = qio_channel_socket_new();
4555 if (qio_channel_socket_dgram_sync(sioc,
4556 udp->local, udp->remote,
4557 errp) < 0) {
4558 object_unref(OBJECT(sioc));
4559 return NULL;
4561 return qemu_chr_open_udp(sioc, common, errp);
4564 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4565 Error **errp)
4567 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4568 CharDriverState *chr = NULL;
4569 Error *local_err = NULL;
4570 GSList *i;
4571 CharDriver *cd;
4573 chr = qemu_chr_find(id);
4574 if (chr) {
4575 error_setg(errp, "Chardev '%s' already exists", id);
4576 g_free(ret);
4577 return NULL;
4580 for (i = backends; i; i = i->next) {
4581 cd = i->data;
4583 if (cd->kind == backend->type) {
4584 chr = cd->create(id, backend, ret, &local_err);
4585 if (local_err) {
4586 error_propagate(errp, local_err);
4587 goto out_error;
4589 break;
4593 if (chr == NULL) {
4594 assert(!i);
4595 error_setg(errp, "chardev backend not available");
4596 goto out_error;
4599 chr->label = g_strdup(id);
4600 chr->avail_connections =
4601 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4602 if (!chr->filename) {
4603 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4605 if (!chr->explicit_be_open) {
4606 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4608 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4609 return ret;
4611 out_error:
4612 g_free(ret);
4613 return NULL;
4616 void qmp_chardev_remove(const char *id, Error **errp)
4618 CharDriverState *chr;
4620 chr = qemu_chr_find(id);
4621 if (chr == NULL) {
4622 error_setg(errp, "Chardev '%s' not found", id);
4623 return;
4625 if (chr->chr_can_read || chr->chr_read ||
4626 chr->chr_event || chr->handler_opaque) {
4627 error_setg(errp, "Chardev '%s' is busy", id);
4628 return;
4630 if (chr->replay) {
4631 error_setg(errp,
4632 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4633 return;
4635 qemu_chr_delete(chr);
4638 void qemu_chr_cleanup(void)
4640 CharDriverState *chr, *tmp;
4642 QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
4643 qemu_chr_delete(chr);
4647 static void register_types(void)
4649 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4650 qemu_chr_open_null);
4651 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4652 qemu_chr_parse_socket, qmp_chardev_open_socket);
4653 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4654 qmp_chardev_open_udp);
4655 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4656 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4657 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4658 qemu_chr_parse_file_out, qmp_chardev_open_file);
4659 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4660 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4661 #if defined HAVE_CHARDEV_SERIAL
4662 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4663 qemu_chr_parse_serial, qmp_chardev_open_serial);
4664 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4665 qemu_chr_parse_serial, qmp_chardev_open_serial);
4666 #endif
4667 #ifdef HAVE_CHARDEV_PARPORT
4668 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4669 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4670 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4671 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4672 #endif
4673 #ifdef HAVE_CHARDEV_PTY
4674 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4675 qemu_chr_open_pty);
4676 #endif
4677 #ifdef _WIN32
4678 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4679 qemu_chr_open_win_con);
4680 #endif
4681 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4682 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4683 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4684 qemu_chr_open_mux);
4685 /* Bug-compatibility: */
4686 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4687 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4688 /* this must be done after machine init, since we register FEs with muxes
4689 * as part of realize functions like serial_isa_realizefn when -nographic
4690 * is specified
4692 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4695 type_init(register_types);