Merge remote-tracking branch 'remotes/kevin/tags/for-upstream' into staging
[qemu/ar7.git] / qemu-char.c
blob8a0ab05a7bd140f1180604782b99890487b4a6a5
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"
43 #include <zlib.h>
45 #ifndef _WIN32
46 #include <sys/times.h>
47 #include <sys/wait.h>
48 #include <termios.h>
49 #include <sys/ioctl.h>
50 #include <sys/resource.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <net/if.h>
54 #include <arpa/inet.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef CONFIG_BSD
58 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
59 #include <dev/ppbus/ppi.h>
60 #include <dev/ppbus/ppbconf.h>
61 #elif defined(__DragonFly__)
62 #include <dev/misc/ppi/ppi.h>
63 #include <bus/ppbus/ppbconf.h>
64 #endif
65 #else
66 #ifdef __linux__
67 #include <linux/ppdev.h>
68 #include <linux/parport.h>
69 #endif
70 #ifdef __sun__
71 #include <sys/ethernet.h>
72 #include <sys/sockio.h>
73 #include <netinet/arp.h>
74 #include <netinet/in.h>
75 #include <netinet/in_systm.h>
76 #include <netinet/ip.h>
77 #include <netinet/ip_icmp.h> // must come after ip.h
78 #include <netinet/udp.h>
79 #include <netinet/tcp.h>
80 #endif
81 #endif
82 #endif
84 #include "qemu/sockets.h"
85 #include "ui/qemu-spice.h"
87 #define READ_BUF_LEN 4096
88 #define READ_RETRIES 10
89 #define TCP_MAX_FDS 16
91 /***********************************************************/
92 /* Socket address helpers */
94 static char *SocketAddress_to_str(const char *prefix, SocketAddress *addr,
95 bool is_listen, bool is_telnet)
97 switch (addr->type) {
98 case SOCKET_ADDRESS_KIND_INET:
99 return g_strdup_printf("%s%s:%s:%s%s", prefix,
100 is_telnet ? "telnet" : "tcp",
101 addr->u.inet.data->host,
102 addr->u.inet.data->port,
103 is_listen ? ",server" : "");
104 break;
105 case SOCKET_ADDRESS_KIND_UNIX:
106 return g_strdup_printf("%sunix:%s%s", prefix,
107 addr->u.q_unix.data->path,
108 is_listen ? ",server" : "");
109 break;
110 case SOCKET_ADDRESS_KIND_FD:
111 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd.data->str,
112 is_listen ? ",server" : "");
113 break;
114 default:
115 abort();
119 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
120 struct sockaddr_storage *ps, socklen_t ps_len,
121 bool is_listen, bool is_telnet)
123 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
124 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
125 const char *left = "", *right = "";
127 switch (ss->ss_family) {
128 #ifndef _WIN32
129 case AF_UNIX:
130 return g_strdup_printf("unix:%s%s",
131 ((struct sockaddr_un *)(ss))->sun_path,
132 is_listen ? ",server" : "");
133 #endif
134 case AF_INET6:
135 left = "[";
136 right = "]";
137 /* fall through */
138 case AF_INET:
139 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
140 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
141 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
142 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
143 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
144 is_telnet ? "telnet" : "tcp",
145 left, shost, right, sserv,
146 is_listen ? ",server" : "",
147 left, phost, right, pserv);
149 default:
150 return g_strdup_printf("unknown");
154 /***********************************************************/
155 /* character device */
157 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
158 QTAILQ_HEAD_INITIALIZER(chardevs);
160 static void qemu_chr_free_common(CharDriverState *chr);
162 CharDriverState *qemu_chr_alloc(ChardevCommon *backend, Error **errp)
164 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
165 qemu_mutex_init(&chr->chr_write_lock);
167 if (backend->has_logfile) {
168 int flags = O_WRONLY | O_CREAT;
169 if (backend->has_logappend &&
170 backend->logappend) {
171 flags |= O_APPEND;
172 } else {
173 flags |= O_TRUNC;
175 chr->logfd = qemu_open(backend->logfile, flags, 0666);
176 if (chr->logfd < 0) {
177 error_setg_errno(errp, errno,
178 "Unable to open logfile %s",
179 backend->logfile);
180 g_free(chr);
181 return NULL;
183 } else {
184 chr->logfd = -1;
187 return chr;
190 void qemu_chr_be_event(CharDriverState *s, int event)
192 /* Keep track if the char device is open */
193 switch (event) {
194 case CHR_EVENT_OPENED:
195 s->be_open = 1;
196 break;
197 case CHR_EVENT_CLOSED:
198 s->be_open = 0;
199 break;
202 if (!s->chr_event)
203 return;
204 s->chr_event(s->handler_opaque, event);
207 void qemu_chr_be_generic_open(CharDriverState *s)
209 qemu_chr_be_event(s, CHR_EVENT_OPENED);
213 /* Not reporting errors from writing to logfile, as logs are
214 * defined to be "best effort" only */
215 static void qemu_chr_fe_write_log(CharDriverState *s,
216 const uint8_t *buf, size_t len)
218 size_t done = 0;
219 ssize_t ret;
221 if (s->logfd < 0) {
222 return;
225 while (done < len) {
226 retry:
227 ret = write(s->logfd, buf + done, len - done);
228 if (ret == -1 && errno == EAGAIN) {
229 g_usleep(100);
230 goto retry;
233 if (ret <= 0) {
234 return;
236 done += ret;
240 static int qemu_chr_fe_write_buffer(CharDriverState *s, const uint8_t *buf, int len, int *offset)
242 int res = 0;
243 *offset = 0;
245 qemu_mutex_lock(&s->chr_write_lock);
246 while (*offset < len) {
247 retry:
248 res = s->chr_write(s, buf + *offset, len - *offset);
249 if (res < 0 && errno == EAGAIN) {
250 g_usleep(100);
251 goto retry;
254 if (res <= 0) {
255 break;
258 *offset += res;
260 if (*offset > 0) {
261 qemu_chr_fe_write_log(s, buf, *offset);
263 qemu_mutex_unlock(&s->chr_write_lock);
265 return res;
268 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
270 int ret;
272 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
273 int offset;
274 replay_char_write_event_load(&ret, &offset);
275 assert(offset <= len);
276 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
277 return ret;
280 qemu_mutex_lock(&s->chr_write_lock);
281 ret = s->chr_write(s, buf, len);
283 if (ret > 0) {
284 qemu_chr_fe_write_log(s, buf, ret);
287 qemu_mutex_unlock(&s->chr_write_lock);
289 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
290 replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
293 return ret;
296 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
298 int offset;
299 int res;
301 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
302 replay_char_write_event_load(&res, &offset);
303 assert(offset <= len);
304 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
305 return res;
308 res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
310 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
311 replay_char_write_event_save(res, offset);
314 if (res < 0) {
315 return res;
317 return offset;
320 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
322 int offset = 0, counter = 10;
323 int res;
325 if (!s->chr_sync_read) {
326 return 0;
329 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
330 return replay_char_read_all_load(buf);
333 while (offset < len) {
334 retry:
335 res = s->chr_sync_read(s, buf + offset, len - offset);
336 if (res == -1 && errno == EAGAIN) {
337 g_usleep(100);
338 goto retry;
341 if (res == 0) {
342 break;
345 if (res < 0) {
346 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
347 replay_char_read_all_save_error(res);
349 return res;
352 offset += res;
354 if (!counter--) {
355 break;
359 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
360 replay_char_read_all_save_buf(buf, offset);
362 return offset;
365 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
367 int res;
368 if (!s->chr_ioctl || s->replay) {
369 res = -ENOTSUP;
370 } else {
371 res = s->chr_ioctl(s, cmd, arg);
374 return res;
377 int qemu_chr_be_can_write(CharDriverState *s)
379 if (!s->chr_can_read)
380 return 0;
381 return s->chr_can_read(s->handler_opaque);
384 void qemu_chr_be_write_impl(CharDriverState *s, uint8_t *buf, int len)
386 if (s->chr_read) {
387 s->chr_read(s->handler_opaque, buf, len);
391 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
393 if (s->replay) {
394 if (replay_mode == REPLAY_MODE_PLAY) {
395 return;
397 replay_chr_be_write(s, buf, len);
398 } else {
399 qemu_chr_be_write_impl(s, buf, len);
403 int qemu_chr_fe_get_msgfd(CharDriverState *s)
405 int fd;
406 int res = (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
407 if (s->replay) {
408 fprintf(stderr,
409 "Replay: get msgfd is not supported for serial devices yet\n");
410 exit(1);
412 return res;
415 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
417 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
420 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
422 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
425 int qemu_chr_add_client(CharDriverState *s, int fd)
427 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
430 void qemu_chr_accept_input(CharDriverState *s)
432 if (s->chr_accept_input)
433 s->chr_accept_input(s);
434 qemu_notify_event();
437 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
439 char buf[READ_BUF_LEN];
440 va_list ap;
441 va_start(ap, fmt);
442 vsnprintf(buf, sizeof(buf), fmt, ap);
443 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
444 va_end(ap);
447 static void remove_fd_in_watch(CharDriverState *chr);
449 void qemu_chr_add_handlers(CharDriverState *s,
450 IOCanReadHandler *fd_can_read,
451 IOReadHandler *fd_read,
452 IOEventHandler *fd_event,
453 void *opaque)
455 int fe_open;
457 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
458 fe_open = 0;
459 remove_fd_in_watch(s);
460 } else {
461 fe_open = 1;
463 s->chr_can_read = fd_can_read;
464 s->chr_read = fd_read;
465 s->chr_event = fd_event;
466 s->handler_opaque = opaque;
467 if (fe_open && s->chr_update_read_handler)
468 s->chr_update_read_handler(s);
470 if (!s->explicit_fe_open) {
471 qemu_chr_fe_set_open(s, fe_open);
474 /* We're connecting to an already opened device, so let's make sure we
475 also get the open event */
476 if (fe_open && s->be_open) {
477 qemu_chr_be_generic_open(s);
481 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
483 return len;
486 static CharDriverState *qemu_chr_open_null(const char *id,
487 ChardevBackend *backend,
488 ChardevReturn *ret,
489 Error **errp)
491 CharDriverState *chr;
492 ChardevCommon *common = backend->u.null.data;
494 chr = qemu_chr_alloc(common, errp);
495 if (!chr) {
496 return NULL;
498 chr->chr_write = null_chr_write;
499 chr->explicit_be_open = true;
500 return chr;
503 /* MUX driver for serial I/O splitting */
504 #define MAX_MUX 4
505 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
506 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
507 typedef struct {
508 IOCanReadHandler *chr_can_read[MAX_MUX];
509 IOReadHandler *chr_read[MAX_MUX];
510 IOEventHandler *chr_event[MAX_MUX];
511 void *ext_opaque[MAX_MUX];
512 CharDriverState *drv;
513 int focus;
514 int mux_cnt;
515 int term_got_escape;
516 int max_size;
517 /* Intermediate input buffer allows to catch escape sequences even if the
518 currently active device is not accepting any input - but only until it
519 is full as well. */
520 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
521 int prod[MAX_MUX];
522 int cons[MAX_MUX];
523 int timestamps;
525 /* Protected by the CharDriverState chr_write_lock. */
526 int linestart;
527 int64_t timestamps_start;
528 } MuxDriver;
531 /* Called with chr_write_lock held. */
532 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
534 MuxDriver *d = chr->opaque;
535 int ret;
536 if (!d->timestamps) {
537 ret = qemu_chr_fe_write(d->drv, buf, len);
538 } else {
539 int i;
541 ret = 0;
542 for (i = 0; i < len; i++) {
543 if (d->linestart) {
544 char buf1[64];
545 int64_t ti;
546 int secs;
548 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
549 if (d->timestamps_start == -1)
550 d->timestamps_start = ti;
551 ti -= d->timestamps_start;
552 secs = ti / 1000;
553 snprintf(buf1, sizeof(buf1),
554 "[%02d:%02d:%02d.%03d] ",
555 secs / 3600,
556 (secs / 60) % 60,
557 secs % 60,
558 (int)(ti % 1000));
559 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
560 d->linestart = 0;
562 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
563 if (buf[i] == '\n') {
564 d->linestart = 1;
568 return ret;
571 static const char * const mux_help[] = {
572 "% h print this help\n\r",
573 "% x exit emulator\n\r",
574 "% s save disk data back to file (if -snapshot)\n\r",
575 "% t toggle console timestamps\n\r",
576 "% b send break (magic sysrq)\n\r",
577 "% c switch between console and monitor\n\r",
578 "% % sends %\n\r",
579 NULL
582 int term_escape_char = 0x01; /* ctrl-a is used for escape */
583 static void mux_print_help(CharDriverState *chr)
585 int i, j;
586 char ebuf[15] = "Escape-Char";
587 char cbuf[50] = "\n\r";
589 if (term_escape_char > 0 && term_escape_char < 26) {
590 snprintf(cbuf, sizeof(cbuf), "\n\r");
591 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
592 } else {
593 snprintf(cbuf, sizeof(cbuf),
594 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
595 term_escape_char);
597 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
598 for (i = 0; mux_help[i] != NULL; i++) {
599 for (j=0; mux_help[i][j] != '\0'; j++) {
600 if (mux_help[i][j] == '%')
601 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
602 else
603 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
608 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
610 if (d->chr_event[mux_nr])
611 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
614 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
616 if (d->term_got_escape) {
617 d->term_got_escape = 0;
618 if (ch == term_escape_char)
619 goto send_char;
620 switch(ch) {
621 case '?':
622 case 'h':
623 mux_print_help(chr);
624 break;
625 case 'x':
627 const char *term = "QEMU: Terminated\n\r";
628 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
629 exit(0);
630 break;
632 case 's':
633 blk_commit_all();
634 break;
635 case 'b':
636 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
637 break;
638 case 'c':
639 /* Switch to the next registered device */
640 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
641 d->focus++;
642 if (d->focus >= d->mux_cnt)
643 d->focus = 0;
644 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
645 break;
646 case 't':
647 d->timestamps = !d->timestamps;
648 d->timestamps_start = -1;
649 d->linestart = 0;
650 break;
652 } else if (ch == term_escape_char) {
653 d->term_got_escape = 1;
654 } else {
655 send_char:
656 return 1;
658 return 0;
661 static void mux_chr_accept_input(CharDriverState *chr)
663 MuxDriver *d = chr->opaque;
664 int m = d->focus;
666 while (d->prod[m] != d->cons[m] &&
667 d->chr_can_read[m] &&
668 d->chr_can_read[m](d->ext_opaque[m])) {
669 d->chr_read[m](d->ext_opaque[m],
670 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
674 static int mux_chr_can_read(void *opaque)
676 CharDriverState *chr = opaque;
677 MuxDriver *d = chr->opaque;
678 int m = d->focus;
680 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
681 return 1;
682 if (d->chr_can_read[m])
683 return d->chr_can_read[m](d->ext_opaque[m]);
684 return 0;
687 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
689 CharDriverState *chr = opaque;
690 MuxDriver *d = chr->opaque;
691 int m = d->focus;
692 int i;
694 mux_chr_accept_input (opaque);
696 for(i = 0; i < size; i++)
697 if (mux_proc_byte(chr, d, buf[i])) {
698 if (d->prod[m] == d->cons[m] &&
699 d->chr_can_read[m] &&
700 d->chr_can_read[m](d->ext_opaque[m]))
701 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
702 else
703 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
707 static void mux_chr_event(void *opaque, int event)
709 CharDriverState *chr = opaque;
710 MuxDriver *d = chr->opaque;
711 int i;
713 /* Send the event to all registered listeners */
714 for (i = 0; i < d->mux_cnt; i++)
715 mux_chr_send_event(d, i, event);
718 static void mux_chr_update_read_handler(CharDriverState *chr)
720 MuxDriver *d = chr->opaque;
722 if (d->mux_cnt >= MAX_MUX) {
723 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
724 return;
726 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
727 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
728 d->chr_read[d->mux_cnt] = chr->chr_read;
729 d->chr_event[d->mux_cnt] = chr->chr_event;
730 /* Fix up the real driver with mux routines */
731 if (d->mux_cnt == 0) {
732 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
733 mux_chr_event, chr);
735 if (d->focus != -1) {
736 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
738 d->focus = d->mux_cnt;
739 d->mux_cnt++;
740 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
743 static bool muxes_realized;
746 * Called after processing of default and command-line-specified
747 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
748 * to a mux chardev. This is done here to ensure that
749 * output/prompts/banners are only displayed for the FE that has
750 * focus when initial command-line processing/machine init is
751 * completed.
753 * After this point, any new FE attached to any new or existing
754 * mux will receive CHR_EVENT_OPENED notifications for the BE
755 * immediately.
757 static void muxes_realize_done(Notifier *notifier, void *unused)
759 CharDriverState *chr;
761 QTAILQ_FOREACH(chr, &chardevs, next) {
762 if (chr->is_mux) {
763 MuxDriver *d = chr->opaque;
764 int i;
766 /* send OPENED to all already-attached FEs */
767 for (i = 0; i < d->mux_cnt; i++) {
768 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
770 /* mark mux as OPENED so any new FEs will immediately receive
771 * OPENED event
773 qemu_chr_be_generic_open(chr);
776 muxes_realized = true;
779 static Notifier muxes_realize_notify = {
780 .notify = muxes_realize_done,
783 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
785 MuxDriver *d = s->opaque;
786 return d->drv->chr_add_watch(d->drv, cond);
789 static void mux_chr_close(struct CharDriverState *chr)
791 MuxDriver *d = chr->opaque;
793 g_free(d);
796 static CharDriverState *qemu_chr_open_mux(const char *id,
797 ChardevBackend *backend,
798 ChardevReturn *ret, Error **errp)
800 ChardevMux *mux = backend->u.mux.data;
801 CharDriverState *chr, *drv;
802 MuxDriver *d;
803 ChardevCommon *common = qapi_ChardevMux_base(mux);
805 drv = qemu_chr_find(mux->chardev);
806 if (drv == NULL) {
807 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
808 return NULL;
811 chr = qemu_chr_alloc(common, errp);
812 if (!chr) {
813 return NULL;
815 d = g_new0(MuxDriver, 1);
817 chr->opaque = d;
818 d->drv = drv;
819 d->focus = -1;
820 chr->chr_close = mux_chr_close;
821 chr->chr_write = mux_chr_write;
822 chr->chr_update_read_handler = mux_chr_update_read_handler;
823 chr->chr_accept_input = mux_chr_accept_input;
824 /* Frontend guest-open / -close notification is not support with muxes */
825 chr->chr_set_fe_open = NULL;
826 if (drv->chr_add_watch) {
827 chr->chr_add_watch = mux_chr_add_watch;
829 /* only default to opened state if we've realized the initial
830 * set of muxes
832 chr->explicit_be_open = muxes_realized ? 0 : 1;
833 chr->is_mux = 1;
835 return chr;
839 typedef struct IOWatchPoll
841 GSource parent;
843 QIOChannel *ioc;
844 GSource *src;
846 IOCanReadHandler *fd_can_read;
847 GSourceFunc fd_read;
848 void *opaque;
849 } IOWatchPoll;
851 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
853 return container_of(source, IOWatchPoll, parent);
856 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
858 IOWatchPoll *iwp = io_watch_poll_from_source(source);
859 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
860 bool was_active = iwp->src != NULL;
861 if (was_active == now_active) {
862 return FALSE;
865 if (now_active) {
866 iwp->src = qio_channel_create_watch(
867 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
868 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
869 g_source_attach(iwp->src, NULL);
870 } else {
871 g_source_destroy(iwp->src);
872 g_source_unref(iwp->src);
873 iwp->src = NULL;
875 return FALSE;
878 static gboolean io_watch_poll_check(GSource *source)
880 return FALSE;
883 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
884 gpointer user_data)
886 abort();
889 static void io_watch_poll_finalize(GSource *source)
891 /* Due to a glib bug, removing the last reference to a source
892 * inside a finalize callback causes recursive locking (and a
893 * deadlock). This is not a problem inside other callbacks,
894 * including dispatch callbacks, so we call io_remove_watch_poll
895 * to remove this source. At this point, iwp->src must
896 * be NULL, or we would leak it.
898 * This would be solved much more elegantly by child sources,
899 * but we support older glib versions that do not have them.
901 IOWatchPoll *iwp = io_watch_poll_from_source(source);
902 assert(iwp->src == NULL);
905 static GSourceFuncs io_watch_poll_funcs = {
906 .prepare = io_watch_poll_prepare,
907 .check = io_watch_poll_check,
908 .dispatch = io_watch_poll_dispatch,
909 .finalize = io_watch_poll_finalize,
912 /* Can only be used for read */
913 static guint io_add_watch_poll(QIOChannel *ioc,
914 IOCanReadHandler *fd_can_read,
915 QIOChannelFunc fd_read,
916 gpointer user_data)
918 IOWatchPoll *iwp;
919 int tag;
921 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
922 iwp->fd_can_read = fd_can_read;
923 iwp->opaque = user_data;
924 iwp->ioc = ioc;
925 iwp->fd_read = (GSourceFunc) fd_read;
926 iwp->src = NULL;
928 tag = g_source_attach(&iwp->parent, NULL);
929 g_source_unref(&iwp->parent);
930 return tag;
933 static void io_remove_watch_poll(guint tag)
935 GSource *source;
936 IOWatchPoll *iwp;
938 g_return_if_fail (tag > 0);
940 source = g_main_context_find_source_by_id(NULL, tag);
941 g_return_if_fail (source != NULL);
943 iwp = io_watch_poll_from_source(source);
944 if (iwp->src) {
945 g_source_destroy(iwp->src);
946 g_source_unref(iwp->src);
947 iwp->src = NULL;
949 g_source_destroy(&iwp->parent);
952 static void remove_fd_in_watch(CharDriverState *chr)
954 if (chr->fd_in_tag) {
955 io_remove_watch_poll(chr->fd_in_tag);
956 chr->fd_in_tag = 0;
961 static int io_channel_send_full(QIOChannel *ioc,
962 const void *buf, size_t len,
963 int *fds, size_t nfds)
965 size_t offset = 0;
967 while (offset < len) {
968 ssize_t ret = 0;
969 struct iovec iov = { .iov_base = (char *)buf + offset,
970 .iov_len = len - offset };
972 ret = qio_channel_writev_full(
973 ioc, &iov, 1,
974 fds, nfds, NULL);
975 if (ret == QIO_CHANNEL_ERR_BLOCK) {
976 if (offset) {
977 return offset;
980 errno = EAGAIN;
981 return -1;
982 } else if (ret < 0) {
983 errno = EINVAL;
984 return -1;
987 offset += ret;
990 return offset;
994 #ifndef _WIN32
995 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
997 return io_channel_send_full(ioc, buf, len, NULL, 0);
1001 typedef struct FDCharDriver {
1002 CharDriverState *chr;
1003 QIOChannel *ioc_in, *ioc_out;
1004 int max_size;
1005 } FDCharDriver;
1007 /* Called with chr_write_lock held. */
1008 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1010 FDCharDriver *s = chr->opaque;
1012 return io_channel_send(s->ioc_out, buf, len);
1015 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1017 CharDriverState *chr = opaque;
1018 FDCharDriver *s = chr->opaque;
1019 int len;
1020 uint8_t buf[READ_BUF_LEN];
1021 ssize_t ret;
1023 len = sizeof(buf);
1024 if (len > s->max_size) {
1025 len = s->max_size;
1027 if (len == 0) {
1028 return TRUE;
1031 ret = qio_channel_read(
1032 chan, (gchar *)buf, len, NULL);
1033 if (ret == 0) {
1034 remove_fd_in_watch(chr);
1035 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1036 return FALSE;
1038 if (ret > 0) {
1039 qemu_chr_be_write(chr, buf, ret);
1042 return TRUE;
1045 static int fd_chr_read_poll(void *opaque)
1047 CharDriverState *chr = opaque;
1048 FDCharDriver *s = chr->opaque;
1050 s->max_size = qemu_chr_be_can_write(chr);
1051 return s->max_size;
1054 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1056 FDCharDriver *s = chr->opaque;
1057 return qio_channel_create_watch(s->ioc_out, cond);
1060 static void fd_chr_update_read_handler(CharDriverState *chr)
1062 FDCharDriver *s = chr->opaque;
1064 remove_fd_in_watch(chr);
1065 if (s->ioc_in) {
1066 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
1067 fd_chr_read_poll,
1068 fd_chr_read, chr);
1072 static void fd_chr_close(struct CharDriverState *chr)
1074 FDCharDriver *s = chr->opaque;
1076 remove_fd_in_watch(chr);
1077 if (s->ioc_in) {
1078 object_unref(OBJECT(s->ioc_in));
1080 if (s->ioc_out) {
1081 object_unref(OBJECT(s->ioc_out));
1084 g_free(s);
1085 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1088 /* open a character device to a unix fd */
1089 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1090 ChardevCommon *backend, Error **errp)
1092 CharDriverState *chr;
1093 FDCharDriver *s;
1095 chr = qemu_chr_alloc(backend, errp);
1096 if (!chr) {
1097 return NULL;
1099 s = g_new0(FDCharDriver, 1);
1100 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1101 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1102 qemu_set_nonblock(fd_out);
1103 s->chr = chr;
1104 chr->opaque = s;
1105 chr->chr_add_watch = fd_chr_add_watch;
1106 chr->chr_write = fd_chr_write;
1107 chr->chr_update_read_handler = fd_chr_update_read_handler;
1108 chr->chr_close = fd_chr_close;
1110 return chr;
1113 static CharDriverState *qemu_chr_open_pipe(const char *id,
1114 ChardevBackend *backend,
1115 ChardevReturn *ret,
1116 Error **errp)
1118 ChardevHostdev *opts = backend->u.pipe.data;
1119 int fd_in, fd_out;
1120 char *filename_in;
1121 char *filename_out;
1122 const char *filename = opts->device;
1123 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1126 filename_in = g_strdup_printf("%s.in", filename);
1127 filename_out = g_strdup_printf("%s.out", filename);
1128 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1129 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1130 g_free(filename_in);
1131 g_free(filename_out);
1132 if (fd_in < 0 || fd_out < 0) {
1133 if (fd_in >= 0)
1134 close(fd_in);
1135 if (fd_out >= 0)
1136 close(fd_out);
1137 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1138 if (fd_in < 0) {
1139 error_setg_file_open(errp, errno, filename);
1140 return NULL;
1143 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1146 /* init terminal so that we can grab keys */
1147 static struct termios oldtty;
1148 static int old_fd0_flags;
1149 static bool stdio_in_use;
1150 static bool stdio_allow_signal;
1151 static bool stdio_echo_state;
1153 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1155 static void term_exit(void)
1157 tcsetattr (0, TCSANOW, &oldtty);
1158 fcntl(0, F_SETFL, old_fd0_flags);
1161 static void term_stdio_handler(int sig)
1163 /* restore echo after resume from suspend. */
1164 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1167 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1169 struct termios tty;
1171 stdio_echo_state = echo;
1172 tty = oldtty;
1173 if (!echo) {
1174 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1175 |INLCR|IGNCR|ICRNL|IXON);
1176 tty.c_oflag |= OPOST;
1177 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1178 tty.c_cflag &= ~(CSIZE|PARENB);
1179 tty.c_cflag |= CS8;
1180 tty.c_cc[VMIN] = 1;
1181 tty.c_cc[VTIME] = 0;
1183 if (!stdio_allow_signal)
1184 tty.c_lflag &= ~ISIG;
1186 tcsetattr (0, TCSANOW, &tty);
1189 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1191 term_exit();
1192 fd_chr_close(chr);
1195 static CharDriverState *qemu_chr_open_stdio(const char *id,
1196 ChardevBackend *backend,
1197 ChardevReturn *ret,
1198 Error **errp)
1200 ChardevStdio *opts = backend->u.stdio.data;
1201 CharDriverState *chr;
1202 struct sigaction act;
1203 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1205 if (is_daemonized()) {
1206 error_setg(errp, "cannot use stdio with -daemonize");
1207 return NULL;
1210 if (stdio_in_use) {
1211 error_setg(errp, "cannot use stdio by multiple character devices");
1212 return NULL;
1215 stdio_in_use = true;
1216 old_fd0_flags = fcntl(0, F_GETFL);
1217 tcgetattr(0, &oldtty);
1218 qemu_set_nonblock(0);
1219 atexit(term_exit);
1221 memset(&act, 0, sizeof(act));
1222 act.sa_handler = term_stdio_handler;
1223 sigaction(SIGCONT, &act, NULL);
1225 chr = qemu_chr_open_fd(0, 1, common, errp);
1226 chr->chr_close = qemu_chr_close_stdio;
1227 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1228 if (opts->has_signal) {
1229 stdio_allow_signal = opts->signal;
1231 qemu_chr_fe_set_echo(chr, false);
1233 return chr;
1236 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1237 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1238 || defined(__GLIBC__)
1240 #define HAVE_CHARDEV_SERIAL 1
1241 #define HAVE_CHARDEV_PTY 1
1243 typedef struct {
1244 QIOChannel *ioc;
1245 int read_bytes;
1247 /* Protected by the CharDriverState chr_write_lock. */
1248 int connected;
1249 guint timer_tag;
1250 guint open_tag;
1251 } PtyCharDriver;
1253 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1254 static void pty_chr_state(CharDriverState *chr, int connected);
1256 static gboolean pty_chr_timer(gpointer opaque)
1258 struct CharDriverState *chr = opaque;
1259 PtyCharDriver *s = chr->opaque;
1261 qemu_mutex_lock(&chr->chr_write_lock);
1262 s->timer_tag = 0;
1263 s->open_tag = 0;
1264 if (!s->connected) {
1265 /* Next poll ... */
1266 pty_chr_update_read_handler_locked(chr);
1268 qemu_mutex_unlock(&chr->chr_write_lock);
1269 return FALSE;
1272 /* Called with chr_write_lock held. */
1273 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1275 PtyCharDriver *s = chr->opaque;
1277 if (s->timer_tag) {
1278 g_source_remove(s->timer_tag);
1279 s->timer_tag = 0;
1282 if (ms == 1000) {
1283 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1284 } else {
1285 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1289 /* Called with chr_write_lock held. */
1290 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1292 PtyCharDriver *s = chr->opaque;
1293 GPollFD pfd;
1294 int rc;
1295 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1297 pfd.fd = fioc->fd;
1298 pfd.events = G_IO_OUT;
1299 pfd.revents = 0;
1300 do {
1301 rc = g_poll(&pfd, 1, 0);
1302 } while (rc == -1 && errno == EINTR);
1303 assert(rc >= 0);
1305 if (pfd.revents & G_IO_HUP) {
1306 pty_chr_state(chr, 0);
1307 } else {
1308 pty_chr_state(chr, 1);
1312 static void pty_chr_update_read_handler(CharDriverState *chr)
1314 qemu_mutex_lock(&chr->chr_write_lock);
1315 pty_chr_update_read_handler_locked(chr);
1316 qemu_mutex_unlock(&chr->chr_write_lock);
1319 /* Called with chr_write_lock held. */
1320 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1322 PtyCharDriver *s = chr->opaque;
1324 if (!s->connected) {
1325 /* guest sends data, check for (re-)connect */
1326 pty_chr_update_read_handler_locked(chr);
1327 if (!s->connected) {
1328 return 0;
1331 return io_channel_send(s->ioc, buf, len);
1334 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1336 PtyCharDriver *s = chr->opaque;
1337 if (!s->connected) {
1338 return NULL;
1340 return qio_channel_create_watch(s->ioc, cond);
1343 static int pty_chr_read_poll(void *opaque)
1345 CharDriverState *chr = opaque;
1346 PtyCharDriver *s = chr->opaque;
1348 s->read_bytes = qemu_chr_be_can_write(chr);
1349 return s->read_bytes;
1352 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1354 CharDriverState *chr = opaque;
1355 PtyCharDriver *s = chr->opaque;
1356 gsize len;
1357 uint8_t buf[READ_BUF_LEN];
1358 ssize_t ret;
1360 len = sizeof(buf);
1361 if (len > s->read_bytes)
1362 len = s->read_bytes;
1363 if (len == 0) {
1364 return TRUE;
1366 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1367 if (ret <= 0) {
1368 pty_chr_state(chr, 0);
1369 return FALSE;
1370 } else {
1371 pty_chr_state(chr, 1);
1372 qemu_chr_be_write(chr, buf, ret);
1374 return TRUE;
1377 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1379 CharDriverState *chr = opaque;
1380 PtyCharDriver *s = chr->opaque;
1382 s->open_tag = 0;
1383 qemu_chr_be_generic_open(chr);
1384 return FALSE;
1387 /* Called with chr_write_lock held. */
1388 static void pty_chr_state(CharDriverState *chr, int connected)
1390 PtyCharDriver *s = chr->opaque;
1392 if (!connected) {
1393 if (s->open_tag) {
1394 g_source_remove(s->open_tag);
1395 s->open_tag = 0;
1397 remove_fd_in_watch(chr);
1398 s->connected = 0;
1399 /* (re-)connect poll interval for idle guests: once per second.
1400 * We check more frequently in case the guests sends data to
1401 * the virtual device linked to our pty. */
1402 pty_chr_rearm_timer(chr, 1000);
1403 } else {
1404 if (s->timer_tag) {
1405 g_source_remove(s->timer_tag);
1406 s->timer_tag = 0;
1408 if (!s->connected) {
1409 g_assert(s->open_tag == 0);
1410 s->connected = 1;
1411 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1413 if (!chr->fd_in_tag) {
1414 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1415 pty_chr_read_poll,
1416 pty_chr_read, chr);
1421 static void pty_chr_close(struct CharDriverState *chr)
1423 PtyCharDriver *s = chr->opaque;
1425 qemu_mutex_lock(&chr->chr_write_lock);
1426 pty_chr_state(chr, 0);
1427 object_unref(OBJECT(s->ioc));
1428 if (s->timer_tag) {
1429 g_source_remove(s->timer_tag);
1430 s->timer_tag = 0;
1432 qemu_mutex_unlock(&chr->chr_write_lock);
1433 g_free(s);
1434 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1437 static CharDriverState *qemu_chr_open_pty(const char *id,
1438 ChardevBackend *backend,
1439 ChardevReturn *ret,
1440 Error **errp)
1442 CharDriverState *chr;
1443 PtyCharDriver *s;
1444 int master_fd, slave_fd;
1445 char pty_name[PATH_MAX];
1446 ChardevCommon *common = backend->u.pty.data;
1448 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1449 if (master_fd < 0) {
1450 error_setg_errno(errp, errno, "Failed to create PTY");
1451 return NULL;
1454 close(slave_fd);
1455 qemu_set_nonblock(master_fd);
1457 chr = qemu_chr_alloc(common, errp);
1458 if (!chr) {
1459 close(master_fd);
1460 return NULL;
1463 chr->filename = g_strdup_printf("pty:%s", pty_name);
1464 ret->pty = g_strdup(pty_name);
1465 ret->has_pty = true;
1467 fprintf(stderr, "char device redirected to %s (label %s)\n",
1468 pty_name, id);
1470 s = g_new0(PtyCharDriver, 1);
1471 chr->opaque = s;
1472 chr->chr_write = pty_chr_write;
1473 chr->chr_update_read_handler = pty_chr_update_read_handler;
1474 chr->chr_close = pty_chr_close;
1475 chr->chr_add_watch = pty_chr_add_watch;
1476 chr->explicit_be_open = true;
1478 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1479 s->timer_tag = 0;
1481 return chr;
1484 static void tty_serial_init(int fd, int speed,
1485 int parity, int data_bits, int stop_bits)
1487 struct termios tty;
1488 speed_t spd;
1490 #if 0
1491 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1492 speed, parity, data_bits, stop_bits);
1493 #endif
1494 tcgetattr (fd, &tty);
1496 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1497 speed = speed * 10 / 11;
1498 do {
1499 check_speed(50);
1500 check_speed(75);
1501 check_speed(110);
1502 check_speed(134);
1503 check_speed(150);
1504 check_speed(200);
1505 check_speed(300);
1506 check_speed(600);
1507 check_speed(1200);
1508 check_speed(1800);
1509 check_speed(2400);
1510 check_speed(4800);
1511 check_speed(9600);
1512 check_speed(19200);
1513 check_speed(38400);
1514 /* Non-Posix values follow. They may be unsupported on some systems. */
1515 check_speed(57600);
1516 check_speed(115200);
1517 #ifdef B230400
1518 check_speed(230400);
1519 #endif
1520 #ifdef B460800
1521 check_speed(460800);
1522 #endif
1523 #ifdef B500000
1524 check_speed(500000);
1525 #endif
1526 #ifdef B576000
1527 check_speed(576000);
1528 #endif
1529 #ifdef B921600
1530 check_speed(921600);
1531 #endif
1532 #ifdef B1000000
1533 check_speed(1000000);
1534 #endif
1535 #ifdef B1152000
1536 check_speed(1152000);
1537 #endif
1538 #ifdef B1500000
1539 check_speed(1500000);
1540 #endif
1541 #ifdef B2000000
1542 check_speed(2000000);
1543 #endif
1544 #ifdef B2500000
1545 check_speed(2500000);
1546 #endif
1547 #ifdef B3000000
1548 check_speed(3000000);
1549 #endif
1550 #ifdef B3500000
1551 check_speed(3500000);
1552 #endif
1553 #ifdef B4000000
1554 check_speed(4000000);
1555 #endif
1556 spd = B115200;
1557 } while (0);
1559 cfsetispeed(&tty, spd);
1560 cfsetospeed(&tty, spd);
1562 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1563 |INLCR|IGNCR|ICRNL|IXON);
1564 tty.c_oflag |= OPOST;
1565 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1566 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1567 switch(data_bits) {
1568 default:
1569 case 8:
1570 tty.c_cflag |= CS8;
1571 break;
1572 case 7:
1573 tty.c_cflag |= CS7;
1574 break;
1575 case 6:
1576 tty.c_cflag |= CS6;
1577 break;
1578 case 5:
1579 tty.c_cflag |= CS5;
1580 break;
1582 switch(parity) {
1583 default:
1584 case 'N':
1585 break;
1586 case 'E':
1587 tty.c_cflag |= PARENB;
1588 break;
1589 case 'O':
1590 tty.c_cflag |= PARENB | PARODD;
1591 break;
1593 if (stop_bits == 2)
1594 tty.c_cflag |= CSTOPB;
1596 tcsetattr (fd, TCSANOW, &tty);
1599 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1601 FDCharDriver *s = chr->opaque;
1602 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1604 switch(cmd) {
1605 case CHR_IOCTL_SERIAL_SET_PARAMS:
1607 QEMUSerialSetParams *ssp = arg;
1608 tty_serial_init(fioc->fd,
1609 ssp->speed, ssp->parity,
1610 ssp->data_bits, ssp->stop_bits);
1612 break;
1613 case CHR_IOCTL_SERIAL_SET_BREAK:
1615 int enable = *(int *)arg;
1616 if (enable) {
1617 tcsendbreak(fioc->fd, 1);
1620 break;
1621 case CHR_IOCTL_SERIAL_GET_TIOCM:
1623 int sarg = 0;
1624 int *targ = (int *)arg;
1625 ioctl(fioc->fd, TIOCMGET, &sarg);
1626 *targ = 0;
1627 if (sarg & TIOCM_CTS)
1628 *targ |= CHR_TIOCM_CTS;
1629 if (sarg & TIOCM_CAR)
1630 *targ |= CHR_TIOCM_CAR;
1631 if (sarg & TIOCM_DSR)
1632 *targ |= CHR_TIOCM_DSR;
1633 if (sarg & TIOCM_RI)
1634 *targ |= CHR_TIOCM_RI;
1635 if (sarg & TIOCM_DTR)
1636 *targ |= CHR_TIOCM_DTR;
1637 if (sarg & TIOCM_RTS)
1638 *targ |= CHR_TIOCM_RTS;
1640 break;
1641 case CHR_IOCTL_SERIAL_SET_TIOCM:
1643 int sarg = *(int *)arg;
1644 int targ = 0;
1645 ioctl(fioc->fd, TIOCMGET, &targ);
1646 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1647 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1648 if (sarg & CHR_TIOCM_CTS)
1649 targ |= TIOCM_CTS;
1650 if (sarg & CHR_TIOCM_CAR)
1651 targ |= TIOCM_CAR;
1652 if (sarg & CHR_TIOCM_DSR)
1653 targ |= TIOCM_DSR;
1654 if (sarg & CHR_TIOCM_RI)
1655 targ |= TIOCM_RI;
1656 if (sarg & CHR_TIOCM_DTR)
1657 targ |= TIOCM_DTR;
1658 if (sarg & CHR_TIOCM_RTS)
1659 targ |= TIOCM_RTS;
1660 ioctl(fioc->fd, TIOCMSET, &targ);
1662 break;
1663 default:
1664 return -ENOTSUP;
1666 return 0;
1669 static void qemu_chr_close_tty(CharDriverState *chr)
1671 fd_chr_close(chr);
1674 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1675 ChardevCommon *backend,
1676 Error **errp)
1678 CharDriverState *chr;
1680 tty_serial_init(fd, 115200, 'N', 8, 1);
1681 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1682 chr->chr_ioctl = tty_serial_ioctl;
1683 chr->chr_close = qemu_chr_close_tty;
1684 return chr;
1686 #endif /* __linux__ || __sun__ */
1688 #if defined(__linux__)
1690 #define HAVE_CHARDEV_PARPORT 1
1692 typedef struct {
1693 int fd;
1694 int mode;
1695 } ParallelCharDriver;
1697 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1699 if (s->mode != mode) {
1700 int m = mode;
1701 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1702 return 0;
1703 s->mode = mode;
1705 return 1;
1708 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1710 ParallelCharDriver *drv = chr->opaque;
1711 int fd = drv->fd;
1712 uint8_t b;
1714 switch(cmd) {
1715 case CHR_IOCTL_PP_READ_DATA:
1716 if (ioctl(fd, PPRDATA, &b) < 0)
1717 return -ENOTSUP;
1718 *(uint8_t *)arg = b;
1719 break;
1720 case CHR_IOCTL_PP_WRITE_DATA:
1721 b = *(uint8_t *)arg;
1722 if (ioctl(fd, PPWDATA, &b) < 0)
1723 return -ENOTSUP;
1724 break;
1725 case CHR_IOCTL_PP_READ_CONTROL:
1726 if (ioctl(fd, PPRCONTROL, &b) < 0)
1727 return -ENOTSUP;
1728 /* Linux gives only the lowest bits, and no way to know data
1729 direction! For better compatibility set the fixed upper
1730 bits. */
1731 *(uint8_t *)arg = b | 0xc0;
1732 break;
1733 case CHR_IOCTL_PP_WRITE_CONTROL:
1734 b = *(uint8_t *)arg;
1735 if (ioctl(fd, PPWCONTROL, &b) < 0)
1736 return -ENOTSUP;
1737 break;
1738 case CHR_IOCTL_PP_READ_STATUS:
1739 if (ioctl(fd, PPRSTATUS, &b) < 0)
1740 return -ENOTSUP;
1741 *(uint8_t *)arg = b;
1742 break;
1743 case CHR_IOCTL_PP_DATA_DIR:
1744 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1745 return -ENOTSUP;
1746 break;
1747 case CHR_IOCTL_PP_EPP_READ_ADDR:
1748 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1749 struct ParallelIOArg *parg = arg;
1750 int n = read(fd, parg->buffer, parg->count);
1751 if (n != parg->count) {
1752 return -EIO;
1755 break;
1756 case CHR_IOCTL_PP_EPP_READ:
1757 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1758 struct ParallelIOArg *parg = arg;
1759 int n = read(fd, parg->buffer, parg->count);
1760 if (n != parg->count) {
1761 return -EIO;
1764 break;
1765 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1766 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1767 struct ParallelIOArg *parg = arg;
1768 int n = write(fd, parg->buffer, parg->count);
1769 if (n != parg->count) {
1770 return -EIO;
1773 break;
1774 case CHR_IOCTL_PP_EPP_WRITE:
1775 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1776 struct ParallelIOArg *parg = arg;
1777 int n = write(fd, parg->buffer, parg->count);
1778 if (n != parg->count) {
1779 return -EIO;
1782 break;
1783 default:
1784 return -ENOTSUP;
1786 return 0;
1789 static void pp_close(CharDriverState *chr)
1791 ParallelCharDriver *drv = chr->opaque;
1792 int fd = drv->fd;
1794 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1795 ioctl(fd, PPRELEASE);
1796 close(fd);
1797 g_free(drv);
1798 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1801 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1802 ChardevCommon *backend,
1803 Error **errp)
1805 CharDriverState *chr;
1806 ParallelCharDriver *drv;
1808 if (ioctl(fd, PPCLAIM) < 0) {
1809 error_setg_errno(errp, errno, "not a parallel port");
1810 close(fd);
1811 return NULL;
1814 chr = qemu_chr_alloc(backend, errp);
1815 if (!chr) {
1816 return NULL;
1819 drv = g_new0(ParallelCharDriver, 1);
1820 chr->opaque = drv;
1821 chr->chr_write = null_chr_write;
1822 chr->chr_ioctl = pp_ioctl;
1823 chr->chr_close = pp_close;
1825 drv->fd = fd;
1826 drv->mode = IEEE1284_MODE_COMPAT;
1828 return chr;
1830 #endif /* __linux__ */
1832 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1834 #define HAVE_CHARDEV_PARPORT 1
1836 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1838 int fd = (int)(intptr_t)chr->opaque;
1839 uint8_t b;
1841 switch(cmd) {
1842 case CHR_IOCTL_PP_READ_DATA:
1843 if (ioctl(fd, PPIGDATA, &b) < 0)
1844 return -ENOTSUP;
1845 *(uint8_t *)arg = b;
1846 break;
1847 case CHR_IOCTL_PP_WRITE_DATA:
1848 b = *(uint8_t *)arg;
1849 if (ioctl(fd, PPISDATA, &b) < 0)
1850 return -ENOTSUP;
1851 break;
1852 case CHR_IOCTL_PP_READ_CONTROL:
1853 if (ioctl(fd, PPIGCTRL, &b) < 0)
1854 return -ENOTSUP;
1855 *(uint8_t *)arg = b;
1856 break;
1857 case CHR_IOCTL_PP_WRITE_CONTROL:
1858 b = *(uint8_t *)arg;
1859 if (ioctl(fd, PPISCTRL, &b) < 0)
1860 return -ENOTSUP;
1861 break;
1862 case CHR_IOCTL_PP_READ_STATUS:
1863 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1864 return -ENOTSUP;
1865 *(uint8_t *)arg = b;
1866 break;
1867 default:
1868 return -ENOTSUP;
1870 return 0;
1873 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1874 ChardevCommon *backend,
1875 Error **errp)
1877 CharDriverState *chr;
1879 chr = qemu_chr_alloc(backend, errp);
1880 if (!chr) {
1881 return NULL;
1883 chr->opaque = (void *)(intptr_t)fd;
1884 chr->chr_write = null_chr_write;
1885 chr->chr_ioctl = pp_ioctl;
1886 chr->explicit_be_open = true;
1887 return chr;
1889 #endif
1891 #else /* _WIN32 */
1893 #define HAVE_CHARDEV_SERIAL 1
1895 typedef struct {
1896 int max_size;
1897 HANDLE hcom, hrecv, hsend;
1898 OVERLAPPED orecv;
1899 BOOL fpipe;
1900 DWORD len;
1902 /* Protected by the CharDriverState chr_write_lock. */
1903 OVERLAPPED osend;
1904 } WinCharState;
1906 typedef struct {
1907 HANDLE hStdIn;
1908 HANDLE hInputReadyEvent;
1909 HANDLE hInputDoneEvent;
1910 HANDLE hInputThread;
1911 uint8_t win_stdio_buf;
1912 } WinStdioCharState;
1914 #define NSENDBUF 2048
1915 #define NRECVBUF 2048
1916 #define MAXCONNECT 1
1917 #define NTIMEOUT 5000
1919 static int win_chr_poll(void *opaque);
1920 static int win_chr_pipe_poll(void *opaque);
1922 static void win_chr_close(CharDriverState *chr)
1924 WinCharState *s = chr->opaque;
1926 if (s->hsend) {
1927 CloseHandle(s->hsend);
1928 s->hsend = NULL;
1930 if (s->hrecv) {
1931 CloseHandle(s->hrecv);
1932 s->hrecv = NULL;
1934 if (s->hcom) {
1935 CloseHandle(s->hcom);
1936 s->hcom = NULL;
1938 if (s->fpipe)
1939 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1940 else
1941 qemu_del_polling_cb(win_chr_poll, chr);
1943 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1946 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1948 WinCharState *s = chr->opaque;
1949 COMMCONFIG comcfg;
1950 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1951 COMSTAT comstat;
1952 DWORD size;
1953 DWORD err;
1955 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1956 if (!s->hsend) {
1957 error_setg(errp, "Failed CreateEvent");
1958 goto fail;
1960 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1961 if (!s->hrecv) {
1962 error_setg(errp, "Failed CreateEvent");
1963 goto fail;
1966 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1967 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1968 if (s->hcom == INVALID_HANDLE_VALUE) {
1969 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1970 s->hcom = NULL;
1971 goto fail;
1974 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1975 error_setg(errp, "Failed SetupComm");
1976 goto fail;
1979 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1980 size = sizeof(COMMCONFIG);
1981 GetDefaultCommConfig(filename, &comcfg, &size);
1982 comcfg.dcb.DCBlength = sizeof(DCB);
1983 CommConfigDialog(filename, NULL, &comcfg);
1985 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1986 error_setg(errp, "Failed SetCommState");
1987 goto fail;
1990 if (!SetCommMask(s->hcom, EV_ERR)) {
1991 error_setg(errp, "Failed SetCommMask");
1992 goto fail;
1995 cto.ReadIntervalTimeout = MAXDWORD;
1996 if (!SetCommTimeouts(s->hcom, &cto)) {
1997 error_setg(errp, "Failed SetCommTimeouts");
1998 goto fail;
2001 if (!ClearCommError(s->hcom, &err, &comstat)) {
2002 error_setg(errp, "Failed ClearCommError");
2003 goto fail;
2005 qemu_add_polling_cb(win_chr_poll, chr);
2006 return 0;
2008 fail:
2009 win_chr_close(chr);
2010 return -1;
2013 /* Called with chr_write_lock held. */
2014 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2016 WinCharState *s = chr->opaque;
2017 DWORD len, ret, size, err;
2019 len = len1;
2020 ZeroMemory(&s->osend, sizeof(s->osend));
2021 s->osend.hEvent = s->hsend;
2022 while (len > 0) {
2023 if (s->hsend)
2024 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2025 else
2026 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2027 if (!ret) {
2028 err = GetLastError();
2029 if (err == ERROR_IO_PENDING) {
2030 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2031 if (ret) {
2032 buf += size;
2033 len -= size;
2034 } else {
2035 break;
2037 } else {
2038 break;
2040 } else {
2041 buf += size;
2042 len -= size;
2045 return len1 - len;
2048 static int win_chr_read_poll(CharDriverState *chr)
2050 WinCharState *s = chr->opaque;
2052 s->max_size = qemu_chr_be_can_write(chr);
2053 return s->max_size;
2056 static void win_chr_readfile(CharDriverState *chr)
2058 WinCharState *s = chr->opaque;
2059 int ret, err;
2060 uint8_t buf[READ_BUF_LEN];
2061 DWORD size;
2063 ZeroMemory(&s->orecv, sizeof(s->orecv));
2064 s->orecv.hEvent = s->hrecv;
2065 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2066 if (!ret) {
2067 err = GetLastError();
2068 if (err == ERROR_IO_PENDING) {
2069 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2073 if (size > 0) {
2074 qemu_chr_be_write(chr, buf, size);
2078 static void win_chr_read(CharDriverState *chr)
2080 WinCharState *s = chr->opaque;
2082 if (s->len > s->max_size)
2083 s->len = s->max_size;
2084 if (s->len == 0)
2085 return;
2087 win_chr_readfile(chr);
2090 static int win_chr_poll(void *opaque)
2092 CharDriverState *chr = opaque;
2093 WinCharState *s = chr->opaque;
2094 COMSTAT status;
2095 DWORD comerr;
2097 ClearCommError(s->hcom, &comerr, &status);
2098 if (status.cbInQue > 0) {
2099 s->len = status.cbInQue;
2100 win_chr_read_poll(chr);
2101 win_chr_read(chr);
2102 return 1;
2104 return 0;
2107 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2108 ChardevCommon *backend,
2109 Error **errp)
2111 CharDriverState *chr;
2112 WinCharState *s;
2114 chr = qemu_chr_alloc(backend, errp);
2115 if (!chr) {
2116 return NULL;
2118 s = g_new0(WinCharState, 1);
2119 chr->opaque = s;
2120 chr->chr_write = win_chr_write;
2121 chr->chr_close = win_chr_close;
2123 if (win_chr_init(chr, filename, errp) < 0) {
2124 g_free(s);
2125 qemu_chr_free_common(chr);
2126 return NULL;
2128 return chr;
2131 static int win_chr_pipe_poll(void *opaque)
2133 CharDriverState *chr = opaque;
2134 WinCharState *s = chr->opaque;
2135 DWORD size;
2137 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2138 if (size > 0) {
2139 s->len = size;
2140 win_chr_read_poll(chr);
2141 win_chr_read(chr);
2142 return 1;
2144 return 0;
2147 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2148 Error **errp)
2150 WinCharState *s = chr->opaque;
2151 OVERLAPPED ov;
2152 int ret;
2153 DWORD size;
2154 char *openname;
2156 s->fpipe = TRUE;
2158 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2159 if (!s->hsend) {
2160 error_setg(errp, "Failed CreateEvent");
2161 goto fail;
2163 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2164 if (!s->hrecv) {
2165 error_setg(errp, "Failed CreateEvent");
2166 goto fail;
2169 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2170 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2171 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2172 PIPE_WAIT,
2173 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2174 g_free(openname);
2175 if (s->hcom == INVALID_HANDLE_VALUE) {
2176 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2177 s->hcom = NULL;
2178 goto fail;
2181 ZeroMemory(&ov, sizeof(ov));
2182 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2183 ret = ConnectNamedPipe(s->hcom, &ov);
2184 if (ret) {
2185 error_setg(errp, "Failed ConnectNamedPipe");
2186 goto fail;
2189 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2190 if (!ret) {
2191 error_setg(errp, "Failed GetOverlappedResult");
2192 if (ov.hEvent) {
2193 CloseHandle(ov.hEvent);
2194 ov.hEvent = NULL;
2196 goto fail;
2199 if (ov.hEvent) {
2200 CloseHandle(ov.hEvent);
2201 ov.hEvent = NULL;
2203 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2204 return 0;
2206 fail:
2207 win_chr_close(chr);
2208 return -1;
2212 static CharDriverState *qemu_chr_open_pipe(const char *id,
2213 ChardevBackend *backend,
2214 ChardevReturn *ret,
2215 Error **errp)
2217 ChardevHostdev *opts = backend->u.pipe.data;
2218 const char *filename = opts->device;
2219 CharDriverState *chr;
2220 WinCharState *s;
2221 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2223 chr = qemu_chr_alloc(common, errp);
2224 if (!chr) {
2225 return NULL;
2227 s = g_new0(WinCharState, 1);
2228 chr->opaque = s;
2229 chr->chr_write = win_chr_write;
2230 chr->chr_close = win_chr_close;
2232 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2233 g_free(s);
2234 qemu_chr_free_common(chr);
2235 return NULL;
2237 return chr;
2240 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2241 ChardevCommon *backend,
2242 Error **errp)
2244 CharDriverState *chr;
2245 WinCharState *s;
2247 chr = qemu_chr_alloc(backend, errp);
2248 if (!chr) {
2249 return NULL;
2251 s = g_new0(WinCharState, 1);
2252 s->hcom = fd_out;
2253 chr->opaque = s;
2254 chr->chr_write = win_chr_write;
2255 return chr;
2258 static CharDriverState *qemu_chr_open_win_con(const char *id,
2259 ChardevBackend *backend,
2260 ChardevReturn *ret,
2261 Error **errp)
2263 ChardevCommon *common = backend->u.console.data;
2264 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2265 common, errp);
2268 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2270 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2271 DWORD dwSize;
2272 int len1;
2274 len1 = len;
2276 while (len1 > 0) {
2277 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2278 break;
2280 buf += dwSize;
2281 len1 -= dwSize;
2284 return len - len1;
2287 static void win_stdio_wait_func(void *opaque)
2289 CharDriverState *chr = opaque;
2290 WinStdioCharState *stdio = chr->opaque;
2291 INPUT_RECORD buf[4];
2292 int ret;
2293 DWORD dwSize;
2294 int i;
2296 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2298 if (!ret) {
2299 /* Avoid error storm */
2300 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2301 return;
2304 for (i = 0; i < dwSize; i++) {
2305 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2307 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2308 int j;
2309 if (kev->uChar.AsciiChar != 0) {
2310 for (j = 0; j < kev->wRepeatCount; j++) {
2311 if (qemu_chr_be_can_write(chr)) {
2312 uint8_t c = kev->uChar.AsciiChar;
2313 qemu_chr_be_write(chr, &c, 1);
2321 static DWORD WINAPI win_stdio_thread(LPVOID param)
2323 CharDriverState *chr = param;
2324 WinStdioCharState *stdio = chr->opaque;
2325 int ret;
2326 DWORD dwSize;
2328 while (1) {
2330 /* Wait for one byte */
2331 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2333 /* Exit in case of error, continue if nothing read */
2334 if (!ret) {
2335 break;
2337 if (!dwSize) {
2338 continue;
2341 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2342 if (stdio->win_stdio_buf == '\r') {
2343 continue;
2346 /* Signal the main thread and wait until the byte was eaten */
2347 if (!SetEvent(stdio->hInputReadyEvent)) {
2348 break;
2350 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2351 != WAIT_OBJECT_0) {
2352 break;
2356 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2357 return 0;
2360 static void win_stdio_thread_wait_func(void *opaque)
2362 CharDriverState *chr = opaque;
2363 WinStdioCharState *stdio = chr->opaque;
2365 if (qemu_chr_be_can_write(chr)) {
2366 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2369 SetEvent(stdio->hInputDoneEvent);
2372 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2374 WinStdioCharState *stdio = chr->opaque;
2375 DWORD dwMode = 0;
2377 GetConsoleMode(stdio->hStdIn, &dwMode);
2379 if (echo) {
2380 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2381 } else {
2382 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2386 static void win_stdio_close(CharDriverState *chr)
2388 WinStdioCharState *stdio = chr->opaque;
2390 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2391 CloseHandle(stdio->hInputReadyEvent);
2393 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2394 CloseHandle(stdio->hInputDoneEvent);
2396 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2397 TerminateThread(stdio->hInputThread, 0);
2400 g_free(chr->opaque);
2401 g_free(chr);
2404 static CharDriverState *qemu_chr_open_stdio(const char *id,
2405 ChardevBackend *backend,
2406 ChardevReturn *ret,
2407 Error **errp)
2409 CharDriverState *chr;
2410 WinStdioCharState *stdio;
2411 DWORD dwMode;
2412 int is_console = 0;
2413 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio.data);
2415 chr = qemu_chr_alloc(common, errp);
2416 if (!chr) {
2417 return NULL;
2419 stdio = g_new0(WinStdioCharState, 1);
2421 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2422 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2423 error_setg(errp, "cannot open stdio: invalid handle");
2424 return NULL;
2427 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2429 chr->opaque = stdio;
2430 chr->chr_write = win_stdio_write;
2431 chr->chr_close = win_stdio_close;
2433 if (is_console) {
2434 if (qemu_add_wait_object(stdio->hStdIn,
2435 win_stdio_wait_func, chr)) {
2436 error_setg(errp, "qemu_add_wait_object: failed");
2437 goto err1;
2439 } else {
2440 DWORD dwId;
2442 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2443 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2444 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2445 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2446 error_setg(errp, "cannot create event");
2447 goto err2;
2449 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2450 win_stdio_thread_wait_func, chr)) {
2451 error_setg(errp, "qemu_add_wait_object: failed");
2452 goto err2;
2454 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2455 chr, 0, &dwId);
2457 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2458 error_setg(errp, "cannot create stdio thread");
2459 goto err3;
2463 dwMode |= ENABLE_LINE_INPUT;
2465 if (is_console) {
2466 /* set the terminal in raw mode */
2467 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2468 dwMode |= ENABLE_PROCESSED_INPUT;
2471 SetConsoleMode(stdio->hStdIn, dwMode);
2473 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2474 qemu_chr_fe_set_echo(chr, false);
2476 return chr;
2478 err3:
2479 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2480 err2:
2481 CloseHandle(stdio->hInputReadyEvent);
2482 CloseHandle(stdio->hInputDoneEvent);
2483 err1:
2484 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2485 return NULL;
2487 #endif /* !_WIN32 */
2490 /***********************************************************/
2491 /* UDP Net console */
2493 typedef struct {
2494 QIOChannel *ioc;
2495 uint8_t buf[READ_BUF_LEN];
2496 int bufcnt;
2497 int bufptr;
2498 int max_size;
2499 } NetCharDriver;
2501 /* Called with chr_write_lock held. */
2502 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2504 NetCharDriver *s = chr->opaque;
2506 return qio_channel_write(
2507 s->ioc, (const char *)buf, len, NULL);
2510 static int udp_chr_read_poll(void *opaque)
2512 CharDriverState *chr = opaque;
2513 NetCharDriver *s = chr->opaque;
2515 s->max_size = qemu_chr_be_can_write(chr);
2517 /* If there were any stray characters in the queue process them
2518 * first
2520 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2521 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2522 s->bufptr++;
2523 s->max_size = qemu_chr_be_can_write(chr);
2525 return s->max_size;
2528 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2530 CharDriverState *chr = opaque;
2531 NetCharDriver *s = chr->opaque;
2532 ssize_t ret;
2534 if (s->max_size == 0) {
2535 return TRUE;
2537 ret = qio_channel_read(
2538 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2539 if (ret <= 0) {
2540 remove_fd_in_watch(chr);
2541 return FALSE;
2543 s->bufcnt = ret;
2545 s->bufptr = 0;
2546 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2547 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2548 s->bufptr++;
2549 s->max_size = qemu_chr_be_can_write(chr);
2552 return TRUE;
2555 static void udp_chr_update_read_handler(CharDriverState *chr)
2557 NetCharDriver *s = chr->opaque;
2559 remove_fd_in_watch(chr);
2560 if (s->ioc) {
2561 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2562 udp_chr_read_poll,
2563 udp_chr_read, chr);
2567 static void udp_chr_close(CharDriverState *chr)
2569 NetCharDriver *s = chr->opaque;
2571 remove_fd_in_watch(chr);
2572 if (s->ioc) {
2573 object_unref(OBJECT(s->ioc));
2575 g_free(s);
2576 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2579 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2580 ChardevCommon *backend,
2581 Error **errp)
2583 CharDriverState *chr = NULL;
2584 NetCharDriver *s = NULL;
2586 chr = qemu_chr_alloc(backend, errp);
2587 if (!chr) {
2588 return NULL;
2590 s = g_new0(NetCharDriver, 1);
2592 s->ioc = QIO_CHANNEL(sioc);
2593 s->bufcnt = 0;
2594 s->bufptr = 0;
2595 chr->opaque = s;
2596 chr->chr_write = udp_chr_write;
2597 chr->chr_update_read_handler = udp_chr_update_read_handler;
2598 chr->chr_close = udp_chr_close;
2599 /* be isn't opened until we get a connection */
2600 chr->explicit_be_open = true;
2601 return chr;
2604 /***********************************************************/
2605 /* TCP Net console */
2607 typedef struct {
2608 QIOChannel *ioc; /* Client I/O channel */
2609 QIOChannelSocket *sioc; /* Client master channel */
2610 QIOChannelSocket *listen_ioc;
2611 guint listen_tag;
2612 QCryptoTLSCreds *tls_creds;
2613 int connected;
2614 int max_size;
2615 int do_telnetopt;
2616 int do_nodelay;
2617 int is_unix;
2618 int *read_msgfds;
2619 size_t read_msgfds_num;
2620 int *write_msgfds;
2621 size_t write_msgfds_num;
2623 SocketAddress *addr;
2624 bool is_listen;
2625 bool is_telnet;
2627 guint reconnect_timer;
2628 int64_t reconnect_time;
2629 bool connect_err_reported;
2630 } TCPCharDriver;
2632 static gboolean socket_reconnect_timeout(gpointer opaque);
2634 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2636 TCPCharDriver *s = chr->opaque;
2637 assert(s->connected == 0);
2638 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2639 socket_reconnect_timeout, chr);
2642 static void check_report_connect_error(CharDriverState *chr,
2643 Error *err)
2645 TCPCharDriver *s = chr->opaque;
2647 if (!s->connect_err_reported) {
2648 error_report("Unable to connect character device %s: %s",
2649 chr->label, error_get_pretty(err));
2650 s->connect_err_reported = true;
2652 qemu_chr_socket_restart_timer(chr);
2655 static gboolean tcp_chr_accept(QIOChannel *chan,
2656 GIOCondition cond,
2657 void *opaque);
2659 /* Called with chr_write_lock held. */
2660 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2662 TCPCharDriver *s = chr->opaque;
2663 if (s->connected) {
2664 int ret = io_channel_send_full(s->ioc, buf, len,
2665 s->write_msgfds,
2666 s->write_msgfds_num);
2668 /* free the written msgfds, no matter what */
2669 if (s->write_msgfds_num) {
2670 g_free(s->write_msgfds);
2671 s->write_msgfds = 0;
2672 s->write_msgfds_num = 0;
2675 return ret;
2676 } else {
2677 /* XXX: indicate an error ? */
2678 return len;
2682 static int tcp_chr_read_poll(void *opaque)
2684 CharDriverState *chr = opaque;
2685 TCPCharDriver *s = chr->opaque;
2686 if (!s->connected)
2687 return 0;
2688 s->max_size = qemu_chr_be_can_write(chr);
2689 return s->max_size;
2692 #define IAC 255
2693 #define IAC_BREAK 243
2694 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2695 TCPCharDriver *s,
2696 uint8_t *buf, int *size)
2698 /* Handle any telnet client's basic IAC options to satisfy char by
2699 * char mode with no echo. All IAC options will be removed from
2700 * the buf and the do_telnetopt variable will be used to track the
2701 * state of the width of the IAC information.
2703 * IAC commands come in sets of 3 bytes with the exception of the
2704 * "IAC BREAK" command and the double IAC.
2707 int i;
2708 int j = 0;
2710 for (i = 0; i < *size; i++) {
2711 if (s->do_telnetopt > 1) {
2712 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2713 /* Double IAC means send an IAC */
2714 if (j != i)
2715 buf[j] = buf[i];
2716 j++;
2717 s->do_telnetopt = 1;
2718 } else {
2719 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2720 /* Handle IAC break commands by sending a serial break */
2721 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2722 s->do_telnetopt++;
2724 s->do_telnetopt++;
2726 if (s->do_telnetopt >= 4) {
2727 s->do_telnetopt = 1;
2729 } else {
2730 if ((unsigned char)buf[i] == IAC) {
2731 s->do_telnetopt = 2;
2732 } else {
2733 if (j != i)
2734 buf[j] = buf[i];
2735 j++;
2739 *size = j;
2742 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2744 TCPCharDriver *s = chr->opaque;
2745 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2747 assert(num <= TCP_MAX_FDS);
2749 if (to_copy) {
2750 int i;
2752 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2754 /* Close unused fds */
2755 for (i = to_copy; i < s->read_msgfds_num; i++) {
2756 close(s->read_msgfds[i]);
2759 g_free(s->read_msgfds);
2760 s->read_msgfds = 0;
2761 s->read_msgfds_num = 0;
2764 return to_copy;
2767 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2769 TCPCharDriver *s = chr->opaque;
2771 /* clear old pending fd array */
2772 g_free(s->write_msgfds);
2773 s->write_msgfds = NULL;
2774 s->write_msgfds_num = 0;
2776 if (!s->connected ||
2777 !qio_channel_has_feature(s->ioc,
2778 QIO_CHANNEL_FEATURE_FD_PASS)) {
2779 return -1;
2782 if (num) {
2783 s->write_msgfds = g_new(int, num);
2784 memcpy(s->write_msgfds, fds, num * sizeof(int));
2787 s->write_msgfds_num = num;
2789 return 0;
2792 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2794 TCPCharDriver *s = chr->opaque;
2795 struct iovec iov = { .iov_base = buf, .iov_len = len };
2796 int ret;
2797 size_t i;
2798 int *msgfds = NULL;
2799 size_t msgfds_num = 0;
2801 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2802 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2803 &msgfds, &msgfds_num,
2804 NULL);
2805 } else {
2806 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2807 NULL, NULL,
2808 NULL);
2811 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2812 errno = EAGAIN;
2813 ret = -1;
2814 } else if (ret == -1) {
2815 errno = EIO;
2818 if (msgfds_num) {
2819 /* close and clean read_msgfds */
2820 for (i = 0; i < s->read_msgfds_num; i++) {
2821 close(s->read_msgfds[i]);
2824 if (s->read_msgfds_num) {
2825 g_free(s->read_msgfds);
2828 s->read_msgfds = msgfds;
2829 s->read_msgfds_num = msgfds_num;
2832 for (i = 0; i < s->read_msgfds_num; i++) {
2833 int fd = s->read_msgfds[i];
2834 if (fd < 0) {
2835 continue;
2838 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2839 qemu_set_block(fd);
2841 #ifndef MSG_CMSG_CLOEXEC
2842 qemu_set_cloexec(fd);
2843 #endif
2846 return ret;
2849 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2851 TCPCharDriver *s = chr->opaque;
2852 return qio_channel_create_watch(s->ioc, cond);
2855 static void tcp_chr_free_connection(CharDriverState *chr)
2857 TCPCharDriver *s = chr->opaque;
2858 int i;
2860 if (!s->connected) {
2861 return;
2864 if (s->read_msgfds_num) {
2865 for (i = 0; i < s->read_msgfds_num; i++) {
2866 close(s->read_msgfds[i]);
2868 g_free(s->read_msgfds);
2869 s->read_msgfds = NULL;
2870 s->read_msgfds_num = 0;
2873 tcp_set_msgfds(chr, NULL, 0);
2874 remove_fd_in_watch(chr);
2875 object_unref(OBJECT(s->sioc));
2876 s->sioc = NULL;
2877 object_unref(OBJECT(s->ioc));
2878 s->ioc = NULL;
2879 g_free(chr->filename);
2880 chr->filename = NULL;
2881 s->connected = 0;
2884 static void tcp_chr_disconnect(CharDriverState *chr)
2886 TCPCharDriver *s = chr->opaque;
2888 if (!s->connected) {
2889 return;
2892 tcp_chr_free_connection(chr);
2894 if (s->listen_ioc) {
2895 s->listen_tag = qio_channel_add_watch(
2896 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
2898 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
2899 s->is_listen, s->is_telnet);
2900 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2901 if (s->reconnect_time) {
2902 qemu_chr_socket_restart_timer(chr);
2906 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2908 CharDriverState *chr = opaque;
2909 TCPCharDriver *s = chr->opaque;
2910 uint8_t buf[READ_BUF_LEN];
2911 int len, size;
2913 if (!s->connected || s->max_size <= 0) {
2914 return TRUE;
2916 len = sizeof(buf);
2917 if (len > s->max_size)
2918 len = s->max_size;
2919 size = tcp_chr_recv(chr, (void *)buf, len);
2920 if (size == 0 || size == -1) {
2921 /* connection closed */
2922 tcp_chr_disconnect(chr);
2923 } else if (size > 0) {
2924 if (s->do_telnetopt)
2925 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2926 if (size > 0)
2927 qemu_chr_be_write(chr, buf, size);
2930 return TRUE;
2933 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2935 TCPCharDriver *s = chr->opaque;
2936 int size;
2938 if (!s->connected) {
2939 return 0;
2942 size = tcp_chr_recv(chr, (void *) buf, len);
2943 if (size == 0) {
2944 /* connection closed */
2945 tcp_chr_disconnect(chr);
2948 return size;
2951 static void tcp_chr_connect(void *opaque)
2953 CharDriverState *chr = opaque;
2954 TCPCharDriver *s = chr->opaque;
2956 g_free(chr->filename);
2957 chr->filename = sockaddr_to_str(
2958 &s->sioc->localAddr, s->sioc->localAddrLen,
2959 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
2960 s->is_listen, s->is_telnet);
2962 s->connected = 1;
2963 if (s->ioc) {
2964 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2965 tcp_chr_read_poll,
2966 tcp_chr_read, chr);
2968 qemu_chr_be_generic_open(chr);
2971 static void tcp_chr_update_read_handler(CharDriverState *chr)
2973 TCPCharDriver *s = chr->opaque;
2975 if (!s->connected) {
2976 return;
2979 remove_fd_in_watch(chr);
2980 if (s->ioc) {
2981 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2982 tcp_chr_read_poll,
2983 tcp_chr_read, chr);
2987 typedef struct {
2988 CharDriverState *chr;
2989 char buf[12];
2990 size_t buflen;
2991 } TCPCharDriverTelnetInit;
2993 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
2994 GIOCondition cond G_GNUC_UNUSED,
2995 gpointer user_data)
2997 TCPCharDriverTelnetInit *init = user_data;
2998 ssize_t ret;
3000 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
3001 if (ret < 0) {
3002 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3003 ret = 0;
3004 } else {
3005 tcp_chr_disconnect(init->chr);
3006 return FALSE;
3009 init->buflen -= ret;
3011 if (init->buflen == 0) {
3012 tcp_chr_connect(init->chr);
3013 return FALSE;
3016 memmove(init->buf, init->buf + ret, init->buflen);
3018 return TRUE;
3021 static void tcp_chr_telnet_init(CharDriverState *chr)
3023 TCPCharDriver *s = chr->opaque;
3024 TCPCharDriverTelnetInit *init =
3025 g_new0(TCPCharDriverTelnetInit, 1);
3026 size_t n = 0;
3028 init->chr = chr;
3029 init->buflen = 12;
3031 #define IACSET(x, a, b, c) \
3032 do { \
3033 x[n++] = a; \
3034 x[n++] = b; \
3035 x[n++] = c; \
3036 } while (0)
3038 /* Prep the telnet negotion to put telnet in binary,
3039 * no echo, single char mode */
3040 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3041 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3042 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3043 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3045 #undef IACSET
3047 qio_channel_add_watch(
3048 s->ioc, G_IO_OUT,
3049 tcp_chr_telnet_init_io,
3050 init, NULL);
3054 static void tcp_chr_tls_handshake(Object *source,
3055 Error *err,
3056 gpointer user_data)
3058 CharDriverState *chr = user_data;
3059 TCPCharDriver *s = chr->opaque;
3061 if (err) {
3062 tcp_chr_disconnect(chr);
3063 } else {
3064 if (s->do_telnetopt) {
3065 tcp_chr_telnet_init(chr);
3066 } else {
3067 tcp_chr_connect(chr);
3073 static void tcp_chr_tls_init(CharDriverState *chr)
3075 TCPCharDriver *s = chr->opaque;
3076 QIOChannelTLS *tioc;
3077 Error *err = NULL;
3079 if (s->is_listen) {
3080 tioc = qio_channel_tls_new_server(
3081 s->ioc, s->tls_creds,
3082 NULL, /* XXX Use an ACL */
3083 &err);
3084 } else {
3085 tioc = qio_channel_tls_new_client(
3086 s->ioc, s->tls_creds,
3087 s->addr->u.inet.data->host,
3088 &err);
3090 if (tioc == NULL) {
3091 error_free(err);
3092 tcp_chr_disconnect(chr);
3094 object_unref(OBJECT(s->ioc));
3095 s->ioc = QIO_CHANNEL(tioc);
3097 qio_channel_tls_handshake(tioc,
3098 tcp_chr_tls_handshake,
3099 chr,
3100 NULL);
3104 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3106 TCPCharDriver *s = chr->opaque;
3107 if (s->ioc != NULL) {
3108 return -1;
3111 s->ioc = QIO_CHANNEL(sioc);
3112 object_ref(OBJECT(sioc));
3113 s->sioc = sioc;
3114 object_ref(OBJECT(sioc));
3116 qio_channel_set_blocking(s->ioc, false, NULL);
3118 if (s->do_nodelay) {
3119 qio_channel_set_delay(s->ioc, false);
3121 if (s->listen_tag) {
3122 g_source_remove(s->listen_tag);
3123 s->listen_tag = 0;
3126 if (s->tls_creds) {
3127 tcp_chr_tls_init(chr);
3128 } else {
3129 if (s->do_telnetopt) {
3130 tcp_chr_telnet_init(chr);
3131 } else {
3132 tcp_chr_connect(chr);
3136 return 0;
3140 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3142 int ret;
3143 QIOChannelSocket *sioc;
3145 sioc = qio_channel_socket_new_fd(fd, NULL);
3146 if (!sioc) {
3147 return -1;
3149 ret = tcp_chr_new_client(chr, sioc);
3150 object_unref(OBJECT(sioc));
3151 return ret;
3154 static gboolean tcp_chr_accept(QIOChannel *channel,
3155 GIOCondition cond,
3156 void *opaque)
3158 CharDriverState *chr = opaque;
3159 QIOChannelSocket *sioc;
3161 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3162 NULL);
3163 if (!sioc) {
3164 return TRUE;
3167 tcp_chr_new_client(chr, sioc);
3169 object_unref(OBJECT(sioc));
3171 return TRUE;
3174 static int tcp_chr_wait_connected(CharDriverState *chr, Error **errp)
3176 TCPCharDriver *s = chr->opaque;
3177 QIOChannelSocket *sioc;
3179 while (!s->connected) {
3180 if (s->is_listen) {
3181 fprintf(stderr, "QEMU waiting for connection on: %s\n",
3182 chr->filename);
3183 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), true, NULL);
3184 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
3185 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
3186 } else {
3187 sioc = qio_channel_socket_new();
3188 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3189 object_unref(OBJECT(sioc));
3190 return -1;
3192 tcp_chr_new_client(chr, sioc);
3193 object_unref(OBJECT(sioc));
3197 return 0;
3200 int qemu_chr_wait_connected(CharDriverState *chr, Error **errp)
3202 if (chr->chr_wait_connected) {
3203 return chr->chr_wait_connected(chr, errp);
3206 return 0;
3209 static void tcp_chr_close(CharDriverState *chr)
3211 TCPCharDriver *s = chr->opaque;
3213 tcp_chr_free_connection(chr);
3215 if (s->reconnect_timer) {
3216 g_source_remove(s->reconnect_timer);
3217 s->reconnect_timer = 0;
3219 qapi_free_SocketAddress(s->addr);
3220 if (s->listen_tag) {
3221 g_source_remove(s->listen_tag);
3222 s->listen_tag = 0;
3224 if (s->listen_ioc) {
3225 object_unref(OBJECT(s->listen_ioc));
3227 if (s->tls_creds) {
3228 object_unref(OBJECT(s->tls_creds));
3230 g_free(s);
3231 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3235 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3237 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3238 CharDriverState *chr = opaque;
3239 TCPCharDriver *s = chr->opaque;
3241 if (err) {
3242 check_report_connect_error(chr, err);
3243 object_unref(src);
3244 return;
3247 s->connect_err_reported = false;
3248 tcp_chr_new_client(chr, sioc);
3249 object_unref(OBJECT(sioc));
3253 /*********************************************************/
3254 /* Ring buffer chardev */
3256 typedef struct {
3257 size_t size;
3258 size_t prod;
3259 size_t cons;
3260 uint8_t *cbuf;
3261 } RingBufCharDriver;
3263 static size_t ringbuf_count(const CharDriverState *chr)
3265 const RingBufCharDriver *d = chr->opaque;
3267 return d->prod - d->cons;
3270 /* Called with chr_write_lock held. */
3271 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3273 RingBufCharDriver *d = chr->opaque;
3274 int i;
3276 if (!buf || (len < 0)) {
3277 return -1;
3280 for (i = 0; i < len; i++ ) {
3281 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3282 if (d->prod - d->cons > d->size) {
3283 d->cons = d->prod - d->size;
3287 return 0;
3290 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3292 RingBufCharDriver *d = chr->opaque;
3293 int i;
3295 qemu_mutex_lock(&chr->chr_write_lock);
3296 for (i = 0; i < len && d->cons != d->prod; i++) {
3297 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3299 qemu_mutex_unlock(&chr->chr_write_lock);
3301 return i;
3304 static void ringbuf_chr_close(struct CharDriverState *chr)
3306 RingBufCharDriver *d = chr->opaque;
3308 g_free(d->cbuf);
3309 g_free(d);
3310 chr->opaque = NULL;
3313 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3314 ChardevBackend *backend,
3315 ChardevReturn *ret,
3316 Error **errp)
3318 ChardevRingbuf *opts = backend->u.ringbuf.data;
3319 ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
3320 CharDriverState *chr;
3321 RingBufCharDriver *d;
3323 chr = qemu_chr_alloc(common, errp);
3324 if (!chr) {
3325 return NULL;
3327 d = g_malloc(sizeof(*d));
3329 d->size = opts->has_size ? opts->size : 65536;
3331 /* The size must be power of 2 */
3332 if (d->size & (d->size - 1)) {
3333 error_setg(errp, "size of ringbuf chardev must be power of two");
3334 goto fail;
3337 d->prod = 0;
3338 d->cons = 0;
3339 d->cbuf = g_malloc0(d->size);
3341 chr->opaque = d;
3342 chr->chr_write = ringbuf_chr_write;
3343 chr->chr_close = ringbuf_chr_close;
3345 return chr;
3347 fail:
3348 g_free(d);
3349 qemu_chr_free_common(chr);
3350 return NULL;
3353 bool chr_is_ringbuf(const CharDriverState *chr)
3355 return chr->chr_write == ringbuf_chr_write;
3358 void qmp_ringbuf_write(const char *device, const char *data,
3359 bool has_format, enum DataFormat format,
3360 Error **errp)
3362 CharDriverState *chr;
3363 const uint8_t *write_data;
3364 int ret;
3365 gsize write_count;
3367 chr = qemu_chr_find(device);
3368 if (!chr) {
3369 error_setg(errp, "Device '%s' not found", device);
3370 return;
3373 if (!chr_is_ringbuf(chr)) {
3374 error_setg(errp,"%s is not a ringbuf device", device);
3375 return;
3378 if (has_format && (format == DATA_FORMAT_BASE64)) {
3379 write_data = qbase64_decode(data, -1,
3380 &write_count,
3381 errp);
3382 if (!write_data) {
3383 return;
3385 } else {
3386 write_data = (uint8_t *)data;
3387 write_count = strlen(data);
3390 ret = ringbuf_chr_write(chr, write_data, write_count);
3392 if (write_data != (uint8_t *)data) {
3393 g_free((void *)write_data);
3396 if (ret < 0) {
3397 error_setg(errp, "Failed to write to device %s", device);
3398 return;
3402 char *qmp_ringbuf_read(const char *device, int64_t size,
3403 bool has_format, enum DataFormat format,
3404 Error **errp)
3406 CharDriverState *chr;
3407 uint8_t *read_data;
3408 size_t count;
3409 char *data;
3411 chr = qemu_chr_find(device);
3412 if (!chr) {
3413 error_setg(errp, "Device '%s' not found", device);
3414 return NULL;
3417 if (!chr_is_ringbuf(chr)) {
3418 error_setg(errp,"%s is not a ringbuf device", device);
3419 return NULL;
3422 if (size <= 0) {
3423 error_setg(errp, "size must be greater than zero");
3424 return NULL;
3427 count = ringbuf_count(chr);
3428 size = size > count ? count : size;
3429 read_data = g_malloc(size + 1);
3431 ringbuf_chr_read(chr, read_data, size);
3433 if (has_format && (format == DATA_FORMAT_BASE64)) {
3434 data = g_base64_encode(read_data, size);
3435 g_free(read_data);
3436 } else {
3438 * FIXME should read only complete, valid UTF-8 characters up
3439 * to @size bytes. Invalid sequences should be replaced by a
3440 * suitable replacement character. Except when (and only
3441 * when) ring buffer lost characters since last read, initial
3442 * continuation characters should be dropped.
3444 read_data[size] = 0;
3445 data = (char *)read_data;
3448 return data;
3451 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3453 char host[65], port[33], width[8], height[8];
3454 int pos;
3455 const char *p;
3456 QemuOpts *opts;
3457 Error *local_err = NULL;
3459 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3460 if (local_err) {
3461 error_report_err(local_err);
3462 return NULL;
3465 if (strstart(filename, "mon:", &p)) {
3466 filename = p;
3467 qemu_opt_set(opts, "mux", "on", &error_abort);
3468 if (strcmp(filename, "stdio") == 0) {
3469 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3470 * but pass it to the guest. Handle this only for compat syntax,
3471 * for -chardev syntax we have special option for this.
3472 * This is what -nographic did, redirecting+muxing serial+monitor
3473 * to stdio causing Ctrl+C to be passed to guest. */
3474 qemu_opt_set(opts, "signal", "off", &error_abort);
3478 if (strcmp(filename, "null") == 0 ||
3479 strcmp(filename, "pty") == 0 ||
3480 strcmp(filename, "msmouse") == 0 ||
3481 strcmp(filename, "braille") == 0 ||
3482 strcmp(filename, "testdev") == 0 ||
3483 strcmp(filename, "stdio") == 0) {
3484 qemu_opt_set(opts, "backend", filename, &error_abort);
3485 return opts;
3487 if (strstart(filename, "vc", &p)) {
3488 qemu_opt_set(opts, "backend", "vc", &error_abort);
3489 if (*p == ':') {
3490 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3491 /* pixels */
3492 qemu_opt_set(opts, "width", width, &error_abort);
3493 qemu_opt_set(opts, "height", height, &error_abort);
3494 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3495 /* chars */
3496 qemu_opt_set(opts, "cols", width, &error_abort);
3497 qemu_opt_set(opts, "rows", height, &error_abort);
3498 } else {
3499 goto fail;
3502 return opts;
3504 if (strcmp(filename, "con:") == 0) {
3505 qemu_opt_set(opts, "backend", "console", &error_abort);
3506 return opts;
3508 if (strstart(filename, "COM", NULL)) {
3509 qemu_opt_set(opts, "backend", "serial", &error_abort);
3510 qemu_opt_set(opts, "path", filename, &error_abort);
3511 return opts;
3513 if (strstart(filename, "file:", &p)) {
3514 qemu_opt_set(opts, "backend", "file", &error_abort);
3515 qemu_opt_set(opts, "path", p, &error_abort);
3516 return opts;
3518 if (strstart(filename, "pipe:", &p)) {
3519 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3520 qemu_opt_set(opts, "path", p, &error_abort);
3521 return opts;
3523 if (strstart(filename, "tcp:", &p) ||
3524 strstart(filename, "telnet:", &p)) {
3525 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3526 host[0] = 0;
3527 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3528 goto fail;
3530 qemu_opt_set(opts, "backend", "socket", &error_abort);
3531 qemu_opt_set(opts, "host", host, &error_abort);
3532 qemu_opt_set(opts, "port", port, &error_abort);
3533 if (p[pos] == ',') {
3534 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3535 if (local_err) {
3536 error_report_err(local_err);
3537 goto fail;
3540 if (strstart(filename, "telnet:", &p))
3541 qemu_opt_set(opts, "telnet", "on", &error_abort);
3542 return opts;
3544 if (strstart(filename, "udp:", &p)) {
3545 qemu_opt_set(opts, "backend", "udp", &error_abort);
3546 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3547 host[0] = 0;
3548 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3549 goto fail;
3552 qemu_opt_set(opts, "host", host, &error_abort);
3553 qemu_opt_set(opts, "port", port, &error_abort);
3554 if (p[pos] == '@') {
3555 p += pos + 1;
3556 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3557 host[0] = 0;
3558 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3559 goto fail;
3562 qemu_opt_set(opts, "localaddr", host, &error_abort);
3563 qemu_opt_set(opts, "localport", port, &error_abort);
3565 return opts;
3567 if (strstart(filename, "unix:", &p)) {
3568 qemu_opt_set(opts, "backend", "socket", &error_abort);
3569 qemu_opts_do_parse(opts, p, "path", &local_err);
3570 if (local_err) {
3571 error_report_err(local_err);
3572 goto fail;
3574 return opts;
3576 if (strstart(filename, "/dev/parport", NULL) ||
3577 strstart(filename, "/dev/ppi", NULL)) {
3578 qemu_opt_set(opts, "backend", "parport", &error_abort);
3579 qemu_opt_set(opts, "path", filename, &error_abort);
3580 return opts;
3582 if (strstart(filename, "/dev/", NULL)) {
3583 qemu_opt_set(opts, "backend", "tty", &error_abort);
3584 qemu_opt_set(opts, "path", filename, &error_abort);
3585 return opts;
3588 fail:
3589 qemu_opts_del(opts);
3590 return NULL;
3593 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3595 const char *logfile = qemu_opt_get(opts, "logfile");
3597 backend->has_logfile = logfile != NULL;
3598 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3600 backend->has_logappend = true;
3601 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3605 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3606 Error **errp)
3608 const char *path = qemu_opt_get(opts, "path");
3609 ChardevFile *file;
3611 if (path == NULL) {
3612 error_setg(errp, "chardev: file: no filename given");
3613 return;
3615 file = backend->u.file.data = g_new0(ChardevFile, 1);
3616 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3617 file->out = g_strdup(path);
3619 file->has_append = true;
3620 file->append = qemu_opt_get_bool(opts, "append", false);
3623 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3624 Error **errp)
3626 ChardevStdio *stdio;
3628 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3629 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3630 stdio->has_signal = true;
3631 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3634 #ifdef HAVE_CHARDEV_SERIAL
3635 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3636 Error **errp)
3638 const char *device = qemu_opt_get(opts, "path");
3639 ChardevHostdev *serial;
3641 if (device == NULL) {
3642 error_setg(errp, "chardev: serial/tty: no device path given");
3643 return;
3645 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3646 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3647 serial->device = g_strdup(device);
3649 #endif
3651 #ifdef HAVE_CHARDEV_PARPORT
3652 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3653 Error **errp)
3655 const char *device = qemu_opt_get(opts, "path");
3656 ChardevHostdev *parallel;
3658 if (device == NULL) {
3659 error_setg(errp, "chardev: parallel: no device path given");
3660 return;
3662 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3663 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3664 parallel->device = g_strdup(device);
3666 #endif
3668 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3669 Error **errp)
3671 const char *device = qemu_opt_get(opts, "path");
3672 ChardevHostdev *dev;
3674 if (device == NULL) {
3675 error_setg(errp, "chardev: pipe: no device path given");
3676 return;
3678 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3679 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3680 dev->device = g_strdup(device);
3683 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3684 Error **errp)
3686 int val;
3687 ChardevRingbuf *ringbuf;
3689 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3690 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3692 val = qemu_opt_get_size(opts, "size", 0);
3693 if (val != 0) {
3694 ringbuf->has_size = true;
3695 ringbuf->size = val;
3699 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3700 Error **errp)
3702 const char *chardev = qemu_opt_get(opts, "chardev");
3703 ChardevMux *mux;
3705 if (chardev == NULL) {
3706 error_setg(errp, "chardev: mux: no chardev given");
3707 return;
3709 mux = backend->u.mux.data = g_new0(ChardevMux, 1);
3710 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
3711 mux->chardev = g_strdup(chardev);
3714 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3715 Error **errp)
3717 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3718 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3719 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3720 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3721 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3722 const char *path = qemu_opt_get(opts, "path");
3723 const char *host = qemu_opt_get(opts, "host");
3724 const char *port = qemu_opt_get(opts, "port");
3725 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3726 SocketAddress *addr;
3727 ChardevSocket *sock;
3729 if (!path) {
3730 if (!host) {
3731 error_setg(errp, "chardev: socket: no host given");
3732 return;
3734 if (!port) {
3735 error_setg(errp, "chardev: socket: no port given");
3736 return;
3738 } else {
3739 if (tls_creds) {
3740 error_setg(errp, "TLS can only be used over TCP socket");
3741 return;
3745 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
3746 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
3748 sock->has_nodelay = true;
3749 sock->nodelay = do_nodelay;
3750 sock->has_server = true;
3751 sock->server = is_listen;
3752 sock->has_telnet = true;
3753 sock->telnet = is_telnet;
3754 sock->has_wait = true;
3755 sock->wait = is_waitconnect;
3756 sock->has_reconnect = true;
3757 sock->reconnect = reconnect;
3758 sock->tls_creds = g_strdup(tls_creds);
3760 addr = g_new0(SocketAddress, 1);
3761 if (path) {
3762 UnixSocketAddress *q_unix;
3763 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3764 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
3765 q_unix->path = g_strdup(path);
3766 } else {
3767 addr->type = SOCKET_ADDRESS_KIND_INET;
3768 addr->u.inet.data = g_new(InetSocketAddress, 1);
3769 *addr->u.inet.data = (InetSocketAddress) {
3770 .host = g_strdup(host),
3771 .port = g_strdup(port),
3772 .has_to = qemu_opt_get(opts, "to"),
3773 .to = qemu_opt_get_number(opts, "to", 0),
3774 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3775 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3776 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3777 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3780 sock->addr = addr;
3783 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3784 Error **errp)
3786 const char *host = qemu_opt_get(opts, "host");
3787 const char *port = qemu_opt_get(opts, "port");
3788 const char *localaddr = qemu_opt_get(opts, "localaddr");
3789 const char *localport = qemu_opt_get(opts, "localport");
3790 bool has_local = false;
3791 SocketAddress *addr;
3792 ChardevUdp *udp;
3794 if (host == NULL || strlen(host) == 0) {
3795 host = "localhost";
3797 if (port == NULL || strlen(port) == 0) {
3798 error_setg(errp, "chardev: udp: remote port not specified");
3799 return;
3801 if (localport == NULL || strlen(localport) == 0) {
3802 localport = "0";
3803 } else {
3804 has_local = true;
3806 if (localaddr == NULL || strlen(localaddr) == 0) {
3807 localaddr = "";
3808 } else {
3809 has_local = true;
3812 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
3813 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
3815 addr = g_new0(SocketAddress, 1);
3816 addr->type = SOCKET_ADDRESS_KIND_INET;
3817 addr->u.inet.data = g_new(InetSocketAddress, 1);
3818 *addr->u.inet.data = (InetSocketAddress) {
3819 .host = g_strdup(host),
3820 .port = g_strdup(port),
3821 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3822 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3823 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3824 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3826 udp->remote = addr;
3828 if (has_local) {
3829 udp->has_local = true;
3830 addr = g_new0(SocketAddress, 1);
3831 addr->type = SOCKET_ADDRESS_KIND_INET;
3832 addr->u.inet.data = g_new(InetSocketAddress, 1);
3833 *addr->u.inet.data = (InetSocketAddress) {
3834 .host = g_strdup(localaddr),
3835 .port = g_strdup(localport),
3837 udp->local = addr;
3841 typedef struct CharDriver {
3842 const char *name;
3843 ChardevBackendKind kind;
3844 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3845 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3846 ChardevReturn *ret, Error **errp);
3847 } CharDriver;
3849 static GSList *backends;
3851 void register_char_driver(const char *name, ChardevBackendKind kind,
3852 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3853 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3854 ChardevReturn *ret, Error **errp))
3856 CharDriver *s;
3858 s = g_malloc0(sizeof(*s));
3859 s->name = g_strdup(name);
3860 s->kind = kind;
3861 s->parse = parse;
3862 s->create = create;
3864 backends = g_slist_append(backends, s);
3867 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3868 void (*init)(struct CharDriverState *s),
3869 Error **errp)
3871 Error *local_err = NULL;
3872 CharDriver *cd;
3873 CharDriverState *chr;
3874 GSList *i;
3875 ChardevReturn *ret = NULL;
3876 ChardevBackend *backend;
3877 const char *id = qemu_opts_id(opts);
3878 char *bid = NULL;
3880 if (id == NULL) {
3881 error_setg(errp, "chardev: no id specified");
3882 goto err;
3885 if (qemu_opt_get(opts, "backend") == NULL) {
3886 error_setg(errp, "chardev: \"%s\" missing backend",
3887 qemu_opts_id(opts));
3888 goto err;
3890 for (i = backends; i; i = i->next) {
3891 cd = i->data;
3893 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3894 break;
3897 if (i == NULL) {
3898 error_setg(errp, "chardev: backend \"%s\" not found",
3899 qemu_opt_get(opts, "backend"));
3900 goto err;
3903 backend = g_new0(ChardevBackend, 1);
3905 if (qemu_opt_get_bool(opts, "mux", 0)) {
3906 bid = g_strdup_printf("%s-base", id);
3909 chr = NULL;
3910 backend->type = cd->kind;
3911 if (cd->parse) {
3912 cd->parse(opts, backend, &local_err);
3913 if (local_err) {
3914 error_propagate(errp, local_err);
3915 goto qapi_out;
3917 } else {
3918 ChardevCommon *cc = g_new0(ChardevCommon, 1);
3919 qemu_chr_parse_common(opts, cc);
3920 backend->u.null.data = cc; /* Any ChardevCommon member would work */
3923 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3924 if (!ret) {
3925 goto qapi_out;
3928 if (bid) {
3929 qapi_free_ChardevBackend(backend);
3930 qapi_free_ChardevReturn(ret);
3931 backend = g_new0(ChardevBackend, 1);
3932 backend->u.mux.data = g_new0(ChardevMux, 1);
3933 backend->type = CHARDEV_BACKEND_KIND_MUX;
3934 backend->u.mux.data->chardev = g_strdup(bid);
3935 ret = qmp_chardev_add(id, backend, errp);
3936 if (!ret) {
3937 chr = qemu_chr_find(bid);
3938 qemu_chr_delete(chr);
3939 chr = NULL;
3940 goto qapi_out;
3944 chr = qemu_chr_find(id);
3945 chr->opts = opts;
3947 qapi_out:
3948 qapi_free_ChardevBackend(backend);
3949 qapi_free_ChardevReturn(ret);
3950 g_free(bid);
3951 return chr;
3953 err:
3954 qemu_opts_del(opts);
3955 return NULL;
3958 CharDriverState *qemu_chr_new_noreplay(const char *label, const char *filename,
3959 void (*init)(struct CharDriverState *s))
3961 const char *p;
3962 CharDriverState *chr;
3963 QemuOpts *opts;
3964 Error *err = NULL;
3966 if (strstart(filename, "chardev:", &p)) {
3967 return qemu_chr_find(p);
3970 opts = qemu_chr_parse_compat(label, filename);
3971 if (!opts)
3972 return NULL;
3974 chr = qemu_chr_new_from_opts(opts, init, &err);
3975 if (err) {
3976 error_report_err(err);
3978 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3979 qemu_chr_fe_claim_no_fail(chr);
3980 monitor_init(chr, MONITOR_USE_READLINE);
3982 return chr;
3985 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3987 CharDriverState *chr;
3988 chr = qemu_chr_new_noreplay(label, filename, init);
3989 if (chr) {
3990 chr->replay = replay_mode != REPLAY_MODE_NONE;
3991 if (chr->replay && chr->chr_ioctl) {
3992 fprintf(stderr,
3993 "Replay: ioctl is not supported for serial devices yet\n");
3995 replay_register_char_driver(chr);
3997 return chr;
4000 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
4002 if (chr->chr_set_echo) {
4003 chr->chr_set_echo(chr, echo);
4007 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
4009 if (chr->fe_open == fe_open) {
4010 return;
4012 chr->fe_open = fe_open;
4013 if (chr->chr_set_fe_open) {
4014 chr->chr_set_fe_open(chr, fe_open);
4018 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
4020 if (chr->chr_fe_event) {
4021 chr->chr_fe_event(chr, event);
4025 guint qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
4026 GIOFunc func, void *user_data)
4028 GSource *src;
4029 guint tag;
4031 if (s->chr_add_watch == NULL) {
4032 return 0;
4035 src = s->chr_add_watch(s, cond);
4036 if (!src) {
4037 return 0;
4040 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
4041 tag = g_source_attach(src, NULL);
4042 g_source_unref(src);
4044 return tag;
4047 int qemu_chr_fe_claim(CharDriverState *s)
4049 if (s->avail_connections < 1) {
4050 return -1;
4052 s->avail_connections--;
4053 return 0;
4056 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
4058 if (qemu_chr_fe_claim(s) != 0) {
4059 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
4060 __func__, s->label);
4061 exit(1);
4065 void qemu_chr_fe_release(CharDriverState *s)
4067 s->avail_connections++;
4070 void qemu_chr_disconnect(CharDriverState *chr)
4072 if (chr->chr_disconnect) {
4073 chr->chr_disconnect(chr);
4077 static void qemu_chr_free_common(CharDriverState *chr)
4079 g_free(chr->filename);
4080 g_free(chr->label);
4081 qemu_opts_del(chr->opts);
4082 if (chr->logfd != -1) {
4083 close(chr->logfd);
4085 qemu_mutex_destroy(&chr->chr_write_lock);
4086 g_free(chr);
4089 void qemu_chr_free(CharDriverState *chr)
4091 if (chr->chr_close) {
4092 chr->chr_close(chr);
4094 qemu_chr_free_common(chr);
4097 void qemu_chr_delete(CharDriverState *chr)
4099 QTAILQ_REMOVE(&chardevs, chr, next);
4100 qemu_chr_free(chr);
4103 ChardevInfoList *qmp_query_chardev(Error **errp)
4105 ChardevInfoList *chr_list = NULL;
4106 CharDriverState *chr;
4108 QTAILQ_FOREACH(chr, &chardevs, next) {
4109 ChardevInfoList *info = g_malloc0(sizeof(*info));
4110 info->value = g_malloc0(sizeof(*info->value));
4111 info->value->label = g_strdup(chr->label);
4112 info->value->filename = g_strdup(chr->filename);
4113 info->value->frontend_open = chr->fe_open;
4115 info->next = chr_list;
4116 chr_list = info;
4119 return chr_list;
4122 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4124 ChardevBackendInfoList *backend_list = NULL;
4125 CharDriver *c = NULL;
4126 GSList *i = NULL;
4128 for (i = backends; i; i = i->next) {
4129 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4130 c = i->data;
4131 info->value = g_malloc0(sizeof(*info->value));
4132 info->value->name = g_strdup(c->name);
4134 info->next = backend_list;
4135 backend_list = info;
4138 return backend_list;
4141 CharDriverState *qemu_chr_find(const char *name)
4143 CharDriverState *chr;
4145 QTAILQ_FOREACH(chr, &chardevs, next) {
4146 if (strcmp(chr->label, name) != 0)
4147 continue;
4148 return chr;
4150 return NULL;
4153 QemuOptsList qemu_chardev_opts = {
4154 .name = "chardev",
4155 .implied_opt_name = "backend",
4156 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4157 .desc = {
4159 .name = "backend",
4160 .type = QEMU_OPT_STRING,
4162 .name = "path",
4163 .type = QEMU_OPT_STRING,
4165 .name = "host",
4166 .type = QEMU_OPT_STRING,
4168 .name = "port",
4169 .type = QEMU_OPT_STRING,
4171 .name = "localaddr",
4172 .type = QEMU_OPT_STRING,
4174 .name = "localport",
4175 .type = QEMU_OPT_STRING,
4177 .name = "to",
4178 .type = QEMU_OPT_NUMBER,
4180 .name = "ipv4",
4181 .type = QEMU_OPT_BOOL,
4183 .name = "ipv6",
4184 .type = QEMU_OPT_BOOL,
4186 .name = "wait",
4187 .type = QEMU_OPT_BOOL,
4189 .name = "server",
4190 .type = QEMU_OPT_BOOL,
4192 .name = "delay",
4193 .type = QEMU_OPT_BOOL,
4195 .name = "reconnect",
4196 .type = QEMU_OPT_NUMBER,
4198 .name = "telnet",
4199 .type = QEMU_OPT_BOOL,
4201 .name = "tls-creds",
4202 .type = QEMU_OPT_STRING,
4204 .name = "width",
4205 .type = QEMU_OPT_NUMBER,
4207 .name = "height",
4208 .type = QEMU_OPT_NUMBER,
4210 .name = "cols",
4211 .type = QEMU_OPT_NUMBER,
4213 .name = "rows",
4214 .type = QEMU_OPT_NUMBER,
4216 .name = "mux",
4217 .type = QEMU_OPT_BOOL,
4219 .name = "signal",
4220 .type = QEMU_OPT_BOOL,
4222 .name = "name",
4223 .type = QEMU_OPT_STRING,
4225 .name = "debug",
4226 .type = QEMU_OPT_NUMBER,
4228 .name = "size",
4229 .type = QEMU_OPT_SIZE,
4231 .name = "chardev",
4232 .type = QEMU_OPT_STRING,
4234 .name = "append",
4235 .type = QEMU_OPT_BOOL,
4237 .name = "logfile",
4238 .type = QEMU_OPT_STRING,
4240 .name = "logappend",
4241 .type = QEMU_OPT_BOOL,
4243 { /* end of list */ }
4247 #ifdef _WIN32
4249 static CharDriverState *qmp_chardev_open_file(const char *id,
4250 ChardevBackend *backend,
4251 ChardevReturn *ret,
4252 Error **errp)
4254 ChardevFile *file = backend->u.file.data;
4255 ChardevCommon *common = qapi_ChardevFile_base(file);
4256 HANDLE out;
4257 DWORD accessmode;
4258 DWORD flags;
4260 if (file->has_in) {
4261 error_setg(errp, "input file not supported");
4262 return NULL;
4265 if (file->has_append && file->append) {
4266 /* Append to file if it already exists. */
4267 accessmode = FILE_GENERIC_WRITE & ~FILE_WRITE_DATA;
4268 flags = OPEN_ALWAYS;
4269 } else {
4270 /* Truncate file if it already exists. */
4271 accessmode = GENERIC_WRITE;
4272 flags = CREATE_ALWAYS;
4275 out = CreateFile(file->out, accessmode, FILE_SHARE_READ, NULL, flags,
4276 FILE_ATTRIBUTE_NORMAL, NULL);
4277 if (out == INVALID_HANDLE_VALUE) {
4278 error_setg(errp, "open %s failed", file->out);
4279 return NULL;
4281 return qemu_chr_open_win_file(out, common, errp);
4284 static CharDriverState *qmp_chardev_open_serial(const char *id,
4285 ChardevBackend *backend,
4286 ChardevReturn *ret,
4287 Error **errp)
4289 ChardevHostdev *serial = backend->u.serial.data;
4290 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4291 return qemu_chr_open_win_path(serial->device, common, errp);
4294 #else /* WIN32 */
4296 static int qmp_chardev_open_file_source(char *src, int flags,
4297 Error **errp)
4299 int fd = -1;
4301 TFR(fd = qemu_open(src, flags, 0666));
4302 if (fd == -1) {
4303 error_setg_file_open(errp, errno, src);
4305 return fd;
4308 static CharDriverState *qmp_chardev_open_file(const char *id,
4309 ChardevBackend *backend,
4310 ChardevReturn *ret,
4311 Error **errp)
4313 ChardevFile *file = backend->u.file.data;
4314 ChardevCommon *common = qapi_ChardevFile_base(file);
4315 int flags, in = -1, out;
4317 flags = O_WRONLY | O_CREAT | O_BINARY;
4318 if (file->has_append && file->append) {
4319 flags |= O_APPEND;
4320 } else {
4321 flags |= O_TRUNC;
4324 out = qmp_chardev_open_file_source(file->out, flags, errp);
4325 if (out < 0) {
4326 return NULL;
4329 if (file->has_in) {
4330 flags = O_RDONLY;
4331 in = qmp_chardev_open_file_source(file->in, flags, errp);
4332 if (in < 0) {
4333 qemu_close(out);
4334 return NULL;
4338 return qemu_chr_open_fd(in, out, common, errp);
4341 #ifdef HAVE_CHARDEV_SERIAL
4342 static CharDriverState *qmp_chardev_open_serial(const char *id,
4343 ChardevBackend *backend,
4344 ChardevReturn *ret,
4345 Error **errp)
4347 ChardevHostdev *serial = backend->u.serial.data;
4348 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4349 int fd;
4351 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4352 if (fd < 0) {
4353 return NULL;
4355 qemu_set_nonblock(fd);
4356 return qemu_chr_open_tty_fd(fd, common, errp);
4358 #endif
4360 #ifdef HAVE_CHARDEV_PARPORT
4361 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4362 ChardevBackend *backend,
4363 ChardevReturn *ret,
4364 Error **errp)
4366 ChardevHostdev *parallel = backend->u.parallel.data;
4367 ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
4368 int fd;
4370 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4371 if (fd < 0) {
4372 return NULL;
4374 return qemu_chr_open_pp_fd(fd, common, errp);
4376 #endif
4378 #endif /* WIN32 */
4380 static gboolean socket_reconnect_timeout(gpointer opaque)
4382 CharDriverState *chr = opaque;
4383 TCPCharDriver *s = chr->opaque;
4384 QIOChannelSocket *sioc;
4386 s->reconnect_timer = 0;
4388 if (chr->be_open) {
4389 return false;
4392 sioc = qio_channel_socket_new();
4393 qio_channel_socket_connect_async(sioc, s->addr,
4394 qemu_chr_socket_connected,
4395 chr, NULL);
4397 return false;
4400 static CharDriverState *qmp_chardev_open_socket(const char *id,
4401 ChardevBackend *backend,
4402 ChardevReturn *ret,
4403 Error **errp)
4405 CharDriverState *chr;
4406 TCPCharDriver *s;
4407 ChardevSocket *sock = backend->u.socket.data;
4408 SocketAddress *addr = sock->addr;
4409 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4410 bool is_listen = sock->has_server ? sock->server : true;
4411 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4412 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4413 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4414 ChardevCommon *common = qapi_ChardevSocket_base(sock);
4415 QIOChannelSocket *sioc = NULL;
4417 chr = qemu_chr_alloc(common, errp);
4418 if (!chr) {
4419 return NULL;
4421 s = g_new0(TCPCharDriver, 1);
4423 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4424 s->is_listen = is_listen;
4425 s->is_telnet = is_telnet;
4426 s->do_nodelay = do_nodelay;
4427 if (sock->tls_creds) {
4428 Object *creds;
4429 creds = object_resolve_path_component(
4430 object_get_objects_root(), sock->tls_creds);
4431 if (!creds) {
4432 error_setg(errp, "No TLS credentials with id '%s'",
4433 sock->tls_creds);
4434 goto error;
4436 s->tls_creds = (QCryptoTLSCreds *)
4437 object_dynamic_cast(creds,
4438 TYPE_QCRYPTO_TLS_CREDS);
4439 if (!s->tls_creds) {
4440 error_setg(errp, "Object with id '%s' is not TLS credentials",
4441 sock->tls_creds);
4442 goto error;
4444 object_ref(OBJECT(s->tls_creds));
4445 if (is_listen) {
4446 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4447 error_setg(errp, "%s",
4448 "Expected TLS credentials for server endpoint");
4449 goto error;
4451 } else {
4452 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4453 error_setg(errp, "%s",
4454 "Expected TLS credentials for client endpoint");
4455 goto error;
4460 s->addr = QAPI_CLONE(SocketAddress, sock->addr);
4462 chr->opaque = s;
4463 chr->chr_wait_connected = tcp_chr_wait_connected;
4464 chr->chr_write = tcp_chr_write;
4465 chr->chr_sync_read = tcp_chr_sync_read;
4466 chr->chr_close = tcp_chr_close;
4467 chr->chr_disconnect = tcp_chr_disconnect;
4468 chr->get_msgfds = tcp_get_msgfds;
4469 chr->set_msgfds = tcp_set_msgfds;
4470 chr->chr_add_client = tcp_chr_add_client;
4471 chr->chr_add_watch = tcp_chr_add_watch;
4472 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4473 /* be isn't opened until we get a connection */
4474 chr->explicit_be_open = true;
4476 chr->filename = SocketAddress_to_str("disconnected:",
4477 addr, is_listen, is_telnet);
4479 if (is_listen) {
4480 if (is_telnet) {
4481 s->do_telnetopt = 1;
4483 } else if (reconnect > 0) {
4484 s->reconnect_time = reconnect;
4487 if (s->reconnect_time) {
4488 sioc = qio_channel_socket_new();
4489 qio_channel_socket_connect_async(sioc, s->addr,
4490 qemu_chr_socket_connected,
4491 chr, NULL);
4492 } else {
4493 if (s->is_listen) {
4494 sioc = qio_channel_socket_new();
4495 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4496 goto error;
4498 s->listen_ioc = sioc;
4499 if (is_waitconnect &&
4500 qemu_chr_wait_connected(chr, errp) < 0) {
4501 goto error;
4503 if (!s->ioc) {
4504 s->listen_tag = qio_channel_add_watch(
4505 QIO_CHANNEL(s->listen_ioc), G_IO_IN,
4506 tcp_chr_accept, chr, NULL);
4508 } else if (qemu_chr_wait_connected(chr, errp) < 0) {
4509 goto error;
4513 return chr;
4515 error:
4516 if (sioc) {
4517 object_unref(OBJECT(sioc));
4519 if (s->tls_creds) {
4520 object_unref(OBJECT(s->tls_creds));
4522 g_free(s);
4523 qemu_chr_free_common(chr);
4524 return NULL;
4527 static CharDriverState *qmp_chardev_open_udp(const char *id,
4528 ChardevBackend *backend,
4529 ChardevReturn *ret,
4530 Error **errp)
4532 ChardevUdp *udp = backend->u.udp.data;
4533 ChardevCommon *common = qapi_ChardevUdp_base(udp);
4534 QIOChannelSocket *sioc = qio_channel_socket_new();
4536 if (qio_channel_socket_dgram_sync(sioc,
4537 udp->local, udp->remote,
4538 errp) < 0) {
4539 object_unref(OBJECT(sioc));
4540 return NULL;
4542 return qemu_chr_open_udp(sioc, common, errp);
4545 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4546 Error **errp)
4548 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4549 CharDriverState *chr = NULL;
4550 Error *local_err = NULL;
4551 GSList *i;
4552 CharDriver *cd;
4554 chr = qemu_chr_find(id);
4555 if (chr) {
4556 error_setg(errp, "Chardev '%s' already exists", id);
4557 g_free(ret);
4558 return NULL;
4561 for (i = backends; i; i = i->next) {
4562 cd = i->data;
4564 if (cd->kind == backend->type) {
4565 chr = cd->create(id, backend, ret, &local_err);
4566 if (local_err) {
4567 error_propagate(errp, local_err);
4568 goto out_error;
4570 break;
4574 if (chr == NULL) {
4575 assert(!i);
4576 error_setg(errp, "chardev backend not available");
4577 goto out_error;
4580 chr->label = g_strdup(id);
4581 chr->avail_connections =
4582 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4583 if (!chr->filename) {
4584 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4586 if (!chr->explicit_be_open) {
4587 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4589 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4590 return ret;
4592 out_error:
4593 g_free(ret);
4594 return NULL;
4597 void qmp_chardev_remove(const char *id, Error **errp)
4599 CharDriverState *chr;
4601 chr = qemu_chr_find(id);
4602 if (chr == NULL) {
4603 error_setg(errp, "Chardev '%s' not found", id);
4604 return;
4606 if (chr->chr_can_read || chr->chr_read ||
4607 chr->chr_event || chr->handler_opaque) {
4608 error_setg(errp, "Chardev '%s' is busy", id);
4609 return;
4611 if (chr->replay) {
4612 error_setg(errp,
4613 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4614 return;
4616 qemu_chr_delete(chr);
4619 void qemu_chr_cleanup(void)
4621 CharDriverState *chr, *tmp;
4623 QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
4624 qemu_chr_delete(chr);
4628 static void register_types(void)
4630 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4631 qemu_chr_open_null);
4632 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4633 qemu_chr_parse_socket, qmp_chardev_open_socket);
4634 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4635 qmp_chardev_open_udp);
4636 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4637 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4638 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4639 qemu_chr_parse_file_out, qmp_chardev_open_file);
4640 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4641 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4642 #if defined HAVE_CHARDEV_SERIAL
4643 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4644 qemu_chr_parse_serial, qmp_chardev_open_serial);
4645 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4646 qemu_chr_parse_serial, qmp_chardev_open_serial);
4647 #endif
4648 #ifdef HAVE_CHARDEV_PARPORT
4649 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4650 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4651 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4652 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4653 #endif
4654 #ifdef HAVE_CHARDEV_PTY
4655 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4656 qemu_chr_open_pty);
4657 #endif
4658 #ifdef _WIN32
4659 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4660 qemu_chr_open_win_con);
4661 #endif
4662 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4663 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4664 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4665 qemu_chr_open_mux);
4666 /* Bug-compatibility: */
4667 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4668 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4669 /* this must be done after machine init, since we register FEs with muxes
4670 * as part of realize functions like serial_isa_realizefn when -nographic
4671 * is specified
4673 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4676 type_init(register_types);