Merge remote-tracking branch 'remotes/berrange/tags/pull-qio-2017-01-26-1' into staging
[qemu/kevin.git] / qemu-char.c
blobd8da1677ffc30f24231296b8135c0d29fd03c5f2
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
25 #include "qemu-common.h"
26 #include "qemu/cutils.h"
27 #include "monitor/monitor.h"
28 #include "sysemu/sysemu.h"
29 #include "sysemu/block-backend.h"
30 #include "qemu/error-report.h"
31 #include "qemu/timer.h"
32 #include "sysemu/char.h"
33 #include "hw/usb.h"
34 #include "qmp-commands.h"
35 #include "qapi/clone-visitor.h"
36 #include "qapi-visit.h"
37 #include "qemu/base64.h"
38 #include "io/channel-socket.h"
39 #include "io/channel-file.h"
40 #include "io/channel-tls.h"
41 #include "sysemu/replay.h"
42 #include "qemu/help_option.h"
44 #include <zlib.h>
46 #ifndef _WIN32
47 #include <sys/times.h>
48 #include <sys/wait.h>
49 #include <termios.h>
50 #include <sys/ioctl.h>
51 #include <sys/resource.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
54 #include <net/if.h>
55 #include <arpa/inet.h>
56 #include <netdb.h>
57 #include <sys/select.h>
58 #ifdef CONFIG_BSD
59 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
60 #include <dev/ppbus/ppi.h>
61 #include <dev/ppbus/ppbconf.h>
62 #elif defined(__DragonFly__)
63 #include <dev/misc/ppi/ppi.h>
64 #include <bus/ppbus/ppbconf.h>
65 #endif
66 #else
67 #ifdef __linux__
68 #include <linux/ppdev.h>
69 #include <linux/parport.h>
70 #endif
71 #ifdef __sun__
72 #include <sys/ethernet.h>
73 #include <sys/sockio.h>
74 #include <netinet/arp.h>
75 #include <netinet/in.h>
76 #include <netinet/in_systm.h>
77 #include <netinet/ip.h>
78 #include <netinet/ip_icmp.h> // must come after ip.h
79 #include <netinet/udp.h>
80 #include <netinet/tcp.h>
81 #endif
82 #endif
83 #endif
85 #include "qemu/sockets.h"
86 #include "ui/qemu-spice.h"
88 #define READ_BUF_LEN 4096
89 #define READ_RETRIES 10
90 #define TCP_MAX_FDS 16
92 typedef struct MuxDriver MuxDriver;
94 /***********************************************************/
95 /* Socket address helpers */
97 static char *SocketAddress_to_str(const char *prefix, SocketAddress *addr,
98 bool is_listen, bool is_telnet)
100 switch (addr->type) {
101 case SOCKET_ADDRESS_KIND_INET:
102 return g_strdup_printf("%s%s:%s:%s%s", prefix,
103 is_telnet ? "telnet" : "tcp",
104 addr->u.inet.data->host,
105 addr->u.inet.data->port,
106 is_listen ? ",server" : "");
107 break;
108 case SOCKET_ADDRESS_KIND_UNIX:
109 return g_strdup_printf("%sunix:%s%s", prefix,
110 addr->u.q_unix.data->path,
111 is_listen ? ",server" : "");
112 break;
113 case SOCKET_ADDRESS_KIND_FD:
114 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd.data->str,
115 is_listen ? ",server" : "");
116 break;
117 default:
118 abort();
122 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
123 struct sockaddr_storage *ps, socklen_t ps_len,
124 bool is_listen, bool is_telnet)
126 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
127 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
128 const char *left = "", *right = "";
130 switch (ss->ss_family) {
131 #ifndef _WIN32
132 case AF_UNIX:
133 return g_strdup_printf("unix:%s%s",
134 ((struct sockaddr_un *)(ss))->sun_path,
135 is_listen ? ",server" : "");
136 #endif
137 case AF_INET6:
138 left = "[";
139 right = "]";
140 /* fall through */
141 case AF_INET:
142 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
143 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
144 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
145 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
146 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
147 is_telnet ? "telnet" : "tcp",
148 left, shost, right, sserv,
149 is_listen ? ",server" : "",
150 left, phost, right, pserv);
152 default:
153 return g_strdup_printf("unknown");
157 /***********************************************************/
158 /* character device */
160 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
161 QTAILQ_HEAD_INITIALIZER(chardevs);
163 static void qemu_chr_free_common(CharDriverState *chr);
165 CharDriverState *qemu_chr_alloc(ChardevCommon *backend, Error **errp)
167 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
168 qemu_mutex_init(&chr->chr_write_lock);
170 if (backend->has_logfile) {
171 int flags = O_WRONLY | O_CREAT;
172 if (backend->has_logappend &&
173 backend->logappend) {
174 flags |= O_APPEND;
175 } else {
176 flags |= O_TRUNC;
178 chr->logfd = qemu_open(backend->logfile, flags, 0666);
179 if (chr->logfd < 0) {
180 error_setg_errno(errp, errno,
181 "Unable to open logfile %s",
182 backend->logfile);
183 g_free(chr);
184 return NULL;
186 } else {
187 chr->logfd = -1;
190 return chr;
193 void qemu_chr_be_event(CharDriverState *s, int event)
195 CharBackend *be = s->be;
197 /* Keep track if the char device is open */
198 switch (event) {
199 case CHR_EVENT_OPENED:
200 s->be_open = 1;
201 break;
202 case CHR_EVENT_CLOSED:
203 s->be_open = 0;
204 break;
207 if (!be || !be->chr_event) {
208 return;
211 be->chr_event(be->opaque, event);
214 void qemu_chr_be_generic_open(CharDriverState *s)
216 qemu_chr_be_event(s, CHR_EVENT_OPENED);
220 /* Not reporting errors from writing to logfile, as logs are
221 * defined to be "best effort" only */
222 static void qemu_chr_fe_write_log(CharDriverState *s,
223 const uint8_t *buf, size_t len)
225 size_t done = 0;
226 ssize_t ret;
228 if (s->logfd < 0) {
229 return;
232 while (done < len) {
233 retry:
234 ret = write(s->logfd, buf + done, len - done);
235 if (ret == -1 && errno == EAGAIN) {
236 g_usleep(100);
237 goto retry;
240 if (ret <= 0) {
241 return;
243 done += ret;
247 static int qemu_chr_fe_write_buffer(CharDriverState *s, const uint8_t *buf, int len, int *offset)
249 int res = 0;
250 *offset = 0;
252 qemu_mutex_lock(&s->chr_write_lock);
253 while (*offset < len) {
254 retry:
255 res = s->chr_write(s, buf + *offset, len - *offset);
256 if (res < 0 && errno == EAGAIN) {
257 g_usleep(100);
258 goto retry;
261 if (res <= 0) {
262 break;
265 *offset += res;
267 if (*offset > 0) {
268 qemu_chr_fe_write_log(s, buf, *offset);
270 qemu_mutex_unlock(&s->chr_write_lock);
272 return res;
275 int qemu_chr_fe_write(CharBackend *be, const uint8_t *buf, int len)
277 CharDriverState *s = be->chr;
278 int ret;
280 if (!s) {
281 return 0;
284 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
285 int offset;
286 replay_char_write_event_load(&ret, &offset);
287 assert(offset <= len);
288 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
289 return ret;
292 qemu_mutex_lock(&s->chr_write_lock);
293 ret = s->chr_write(s, buf, len);
295 if (ret > 0) {
296 qemu_chr_fe_write_log(s, buf, ret);
299 qemu_mutex_unlock(&s->chr_write_lock);
301 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
302 replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
305 return ret;
308 static int qemu_chr_write_all(CharDriverState *s, const uint8_t *buf, int len)
310 int offset;
311 int res;
313 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
314 replay_char_write_event_load(&res, &offset);
315 assert(offset <= len);
316 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
317 return res;
320 res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
322 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
323 replay_char_write_event_save(res, offset);
326 if (res < 0) {
327 return res;
329 return offset;
332 int qemu_chr_fe_write_all(CharBackend *be, const uint8_t *buf, int len)
334 CharDriverState *s = be->chr;
336 if (!s) {
337 return 0;
340 return qemu_chr_write_all(s, buf, len);
343 int qemu_chr_fe_read_all(CharBackend *be, uint8_t *buf, int len)
345 CharDriverState *s = be->chr;
346 int offset = 0, counter = 10;
347 int res;
349 if (!s || !s->chr_sync_read) {
350 return 0;
353 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
354 return replay_char_read_all_load(buf);
357 while (offset < len) {
358 retry:
359 res = s->chr_sync_read(s, buf + offset, len - offset);
360 if (res == -1 && errno == EAGAIN) {
361 g_usleep(100);
362 goto retry;
365 if (res == 0) {
366 break;
369 if (res < 0) {
370 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
371 replay_char_read_all_save_error(res);
373 return res;
376 offset += res;
378 if (!counter--) {
379 break;
383 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
384 replay_char_read_all_save_buf(buf, offset);
386 return offset;
389 int qemu_chr_fe_ioctl(CharBackend *be, int cmd, void *arg)
391 CharDriverState *s = be->chr;
392 int res;
394 if (!s || !s->chr_ioctl || s->replay) {
395 res = -ENOTSUP;
396 } else {
397 res = s->chr_ioctl(s, cmd, arg);
400 return res;
403 int qemu_chr_be_can_write(CharDriverState *s)
405 CharBackend *be = s->be;
407 if (!be || !be->chr_can_read) {
408 return 0;
411 return be->chr_can_read(be->opaque);
414 void qemu_chr_be_write_impl(CharDriverState *s, uint8_t *buf, int len)
416 CharBackend *be = s->be;
418 if (be && be->chr_read) {
419 be->chr_read(be->opaque, buf, len);
423 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
425 if (s->replay) {
426 if (replay_mode == REPLAY_MODE_PLAY) {
427 return;
429 replay_chr_be_write(s, buf, len);
430 } else {
431 qemu_chr_be_write_impl(s, buf, len);
435 int qemu_chr_fe_get_msgfd(CharBackend *be)
437 CharDriverState *s = be->chr;
438 int fd;
439 int res = (qemu_chr_fe_get_msgfds(be, &fd, 1) == 1) ? fd : -1;
440 if (s && s->replay) {
441 fprintf(stderr,
442 "Replay: get msgfd is not supported for serial devices yet\n");
443 exit(1);
445 return res;
448 int qemu_chr_fe_get_msgfds(CharBackend *be, int *fds, int len)
450 CharDriverState *s = be->chr;
452 if (!s) {
453 return -1;
456 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
459 int qemu_chr_fe_set_msgfds(CharBackend *be, int *fds, int num)
461 CharDriverState *s = be->chr;
463 if (!s) {
464 return -1;
467 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
470 int qemu_chr_add_client(CharDriverState *s, int fd)
472 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
475 void qemu_chr_fe_accept_input(CharBackend *be)
477 CharDriverState *s = be->chr;
479 if (!s) {
480 return;
483 if (s->chr_accept_input)
484 s->chr_accept_input(s);
485 qemu_notify_event();
488 void qemu_chr_fe_printf(CharBackend *be, const char *fmt, ...)
490 char buf[READ_BUF_LEN];
491 va_list ap;
492 va_start(ap, fmt);
493 vsnprintf(buf, sizeof(buf), fmt, ap);
494 /* XXX this blocks entire thread. Rewrite to use
495 * qemu_chr_fe_write and background I/O callbacks */
496 qemu_chr_fe_write_all(be, (uint8_t *)buf, strlen(buf));
497 va_end(ap);
500 static void remove_fd_in_watch(CharDriverState *chr);
501 static void mux_chr_set_handlers(CharDriverState *chr, GMainContext *context);
502 static void mux_set_focus(CharDriverState *chr, int focus);
504 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
506 return len;
509 static CharDriverState *qemu_chr_open_null(const char *id,
510 ChardevBackend *backend,
511 ChardevReturn *ret,
512 bool *be_opened,
513 Error **errp)
515 CharDriverState *chr;
516 ChardevCommon *common = backend->u.null.data;
518 chr = qemu_chr_alloc(common, errp);
519 if (!chr) {
520 return NULL;
522 chr->chr_write = null_chr_write;
523 *be_opened = false;
524 return chr;
527 /* MUX driver for serial I/O splitting */
528 #define MAX_MUX 4
529 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
530 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
531 struct MuxDriver {
532 CharBackend *backends[MAX_MUX];
533 CharBackend chr;
534 int focus;
535 int mux_cnt;
536 int term_got_escape;
537 int max_size;
538 /* Intermediate input buffer allows to catch escape sequences even if the
539 currently active device is not accepting any input - but only until it
540 is full as well. */
541 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
542 int prod[MAX_MUX];
543 int cons[MAX_MUX];
544 int timestamps;
546 /* Protected by the CharDriverState chr_write_lock. */
547 int linestart;
548 int64_t timestamps_start;
551 /* Called with chr_write_lock held. */
552 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
554 MuxDriver *d = chr->opaque;
555 int ret;
556 if (!d->timestamps) {
557 ret = qemu_chr_fe_write(&d->chr, buf, len);
558 } else {
559 int i;
561 ret = 0;
562 for (i = 0; i < len; i++) {
563 if (d->linestart) {
564 char buf1[64];
565 int64_t ti;
566 int secs;
568 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
569 if (d->timestamps_start == -1)
570 d->timestamps_start = ti;
571 ti -= d->timestamps_start;
572 secs = ti / 1000;
573 snprintf(buf1, sizeof(buf1),
574 "[%02d:%02d:%02d.%03d] ",
575 secs / 3600,
576 (secs / 60) % 60,
577 secs % 60,
578 (int)(ti % 1000));
579 /* XXX this blocks entire thread. Rewrite to use
580 * qemu_chr_fe_write and background I/O callbacks */
581 qemu_chr_fe_write_all(&d->chr,
582 (uint8_t *)buf1, strlen(buf1));
583 d->linestart = 0;
585 ret += qemu_chr_fe_write(&d->chr, buf + i, 1);
586 if (buf[i] == '\n') {
587 d->linestart = 1;
591 return ret;
594 static const char * const mux_help[] = {
595 "% h print this help\n\r",
596 "% x exit emulator\n\r",
597 "% s save disk data back to file (if -snapshot)\n\r",
598 "% t toggle console timestamps\n\r",
599 "% b send break (magic sysrq)\n\r",
600 "% c switch between console and monitor\n\r",
601 "% % sends %\n\r",
602 NULL
605 int term_escape_char = 0x01; /* ctrl-a is used for escape */
606 static void mux_print_help(CharDriverState *chr)
608 int i, j;
609 char ebuf[15] = "Escape-Char";
610 char cbuf[50] = "\n\r";
612 if (term_escape_char > 0 && term_escape_char < 26) {
613 snprintf(cbuf, sizeof(cbuf), "\n\r");
614 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
615 } else {
616 snprintf(cbuf, sizeof(cbuf),
617 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
618 term_escape_char);
620 /* XXX this blocks entire thread. Rewrite to use
621 * qemu_chr_fe_write and background I/O callbacks */
622 qemu_chr_write_all(chr, (uint8_t *)cbuf, strlen(cbuf));
623 for (i = 0; mux_help[i] != NULL; i++) {
624 for (j=0; mux_help[i][j] != '\0'; j++) {
625 if (mux_help[i][j] == '%')
626 qemu_chr_write_all(chr, (uint8_t *)ebuf, strlen(ebuf));
627 else
628 qemu_chr_write_all(chr, (uint8_t *)&mux_help[i][j], 1);
633 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
635 CharBackend *be = d->backends[mux_nr];
637 if (be && be->chr_event) {
638 be->chr_event(be->opaque, event);
642 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
644 if (d->term_got_escape) {
645 d->term_got_escape = 0;
646 if (ch == term_escape_char)
647 goto send_char;
648 switch(ch) {
649 case '?':
650 case 'h':
651 mux_print_help(chr);
652 break;
653 case 'x':
655 const char *term = "QEMU: Terminated\n\r";
656 qemu_chr_write_all(chr, (uint8_t *)term, strlen(term));
657 exit(0);
658 break;
660 case 's':
661 blk_commit_all();
662 break;
663 case 'b':
664 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
665 break;
666 case 'c':
667 assert(d->mux_cnt > 0); /* handler registered with first fe */
668 /* Switch to the next registered device */
669 mux_set_focus(chr, (d->focus + 1) % d->mux_cnt);
670 break;
671 case 't':
672 d->timestamps = !d->timestamps;
673 d->timestamps_start = -1;
674 d->linestart = 0;
675 break;
677 } else if (ch == term_escape_char) {
678 d->term_got_escape = 1;
679 } else {
680 send_char:
681 return 1;
683 return 0;
686 static void mux_chr_accept_input(CharDriverState *chr)
688 MuxDriver *d = chr->opaque;
689 int m = d->focus;
690 CharBackend *be = d->backends[m];
692 while (be && d->prod[m] != d->cons[m] &&
693 be->chr_can_read && be->chr_can_read(be->opaque)) {
694 be->chr_read(be->opaque,
695 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
699 static int mux_chr_can_read(void *opaque)
701 CharDriverState *chr = opaque;
702 MuxDriver *d = chr->opaque;
703 int m = d->focus;
704 CharBackend *be = d->backends[m];
706 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE) {
707 return 1;
710 if (be && be->chr_can_read) {
711 return be->chr_can_read(be->opaque);
714 return 0;
717 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
719 CharDriverState *chr = opaque;
720 MuxDriver *d = chr->opaque;
721 int m = d->focus;
722 CharBackend *be = d->backends[m];
723 int i;
725 mux_chr_accept_input(opaque);
727 for (i = 0; i < size; i++)
728 if (mux_proc_byte(chr, d, buf[i])) {
729 if (d->prod[m] == d->cons[m] &&
730 be && be->chr_can_read &&
731 be->chr_can_read(be->opaque))
732 be->chr_read(be->opaque, &buf[i], 1);
733 else
734 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
738 static bool muxes_realized;
740 static void mux_chr_event(void *opaque, int event)
742 CharDriverState *chr = opaque;
743 MuxDriver *d = chr->opaque;
744 int i;
746 if (!muxes_realized) {
747 return;
750 /* Send the event to all registered listeners */
751 for (i = 0; i < d->mux_cnt; i++)
752 mux_chr_send_event(d, i, event);
756 * Called after processing of default and command-line-specified
757 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
758 * to a mux chardev. This is done here to ensure that
759 * output/prompts/banners are only displayed for the FE that has
760 * focus when initial command-line processing/machine init is
761 * completed.
763 * After this point, any new FE attached to any new or existing
764 * mux will receive CHR_EVENT_OPENED notifications for the BE
765 * immediately.
767 static void muxes_realize_done(Notifier *notifier, void *unused)
769 CharDriverState *chr;
771 QTAILQ_FOREACH(chr, &chardevs, next) {
772 if (chr->is_mux) {
773 MuxDriver *d = chr->opaque;
774 int i;
776 /* send OPENED to all already-attached FEs */
777 for (i = 0; i < d->mux_cnt; i++) {
778 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
780 /* mark mux as OPENED so any new FEs will immediately receive
781 * OPENED event
783 qemu_chr_be_generic_open(chr);
786 muxes_realized = true;
789 static Notifier muxes_realize_notify = {
790 .notify = muxes_realize_done,
793 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
795 MuxDriver *d = s->opaque;
796 CharDriverState *chr = qemu_chr_fe_get_driver(&d->chr);
798 return chr->chr_add_watch(chr, cond);
801 static void mux_chr_free(struct CharDriverState *chr)
803 MuxDriver *d = chr->opaque;
804 int i;
806 for (i = 0; i < d->mux_cnt; i++) {
807 CharBackend *be = d->backends[i];
808 if (be) {
809 be->chr = NULL;
812 qemu_chr_fe_deinit(&d->chr);
813 g_free(d);
816 static void mux_chr_set_handlers(CharDriverState *chr, GMainContext *context)
818 MuxDriver *d = chr->opaque;
820 /* Fix up the real driver with mux routines */
821 qemu_chr_fe_set_handlers(&d->chr,
822 mux_chr_can_read,
823 mux_chr_read,
824 mux_chr_event,
825 chr,
826 context, true);
829 static void mux_set_focus(CharDriverState *chr, int focus)
831 MuxDriver *d = chr->opaque;
833 assert(focus >= 0);
834 assert(focus < d->mux_cnt);
836 if (d->focus != -1) {
837 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
840 d->focus = focus;
841 chr->be = d->backends[focus];
842 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
845 static CharDriverState *qemu_chr_open_mux(const char *id,
846 ChardevBackend *backend,
847 ChardevReturn *ret,
848 bool *be_opened,
849 Error **errp)
851 ChardevMux *mux = backend->u.mux.data;
852 CharDriverState *chr, *drv;
853 MuxDriver *d;
854 ChardevCommon *common = qapi_ChardevMux_base(mux);
856 drv = qemu_chr_find(mux->chardev);
857 if (drv == NULL) {
858 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
859 return NULL;
862 chr = qemu_chr_alloc(common, errp);
863 if (!chr) {
864 return NULL;
866 d = g_new0(MuxDriver, 1);
868 chr->opaque = d;
869 d->focus = -1;
870 chr->chr_free = mux_chr_free;
871 chr->chr_write = mux_chr_write;
872 chr->chr_accept_input = mux_chr_accept_input;
873 /* Frontend guest-open / -close notification is not support with muxes */
874 chr->chr_set_fe_open = NULL;
875 if (drv->chr_add_watch) {
876 chr->chr_add_watch = mux_chr_add_watch;
878 /* only default to opened state if we've realized the initial
879 * set of muxes
881 *be_opened = muxes_realized;
882 chr->is_mux = 1;
883 if (!qemu_chr_fe_init(&d->chr, drv, errp)) {
884 qemu_chr_free(chr);
885 return NULL;
888 return chr;
891 CharDriverState *qemu_chr_fe_get_driver(CharBackend *be)
893 return be->chr;
896 bool qemu_chr_fe_init(CharBackend *b, CharDriverState *s, Error **errp)
898 int tag = 0;
900 if (s->is_mux) {
901 MuxDriver *d = s->opaque;
903 if (d->mux_cnt >= MAX_MUX) {
904 goto unavailable;
907 d->backends[d->mux_cnt] = b;
908 tag = d->mux_cnt++;
909 } else if (s->be) {
910 goto unavailable;
911 } else {
912 s->be = b;
915 b->fe_open = false;
916 b->tag = tag;
917 b->chr = s;
918 return true;
920 unavailable:
921 error_setg(errp, QERR_DEVICE_IN_USE, s->label);
922 return false;
925 static bool qemu_chr_is_busy(CharDriverState *s)
927 if (s->is_mux) {
928 MuxDriver *d = s->opaque;
929 return d->mux_cnt >= 0;
930 } else {
931 return s->be != NULL;
935 void qemu_chr_fe_deinit(CharBackend *b)
937 assert(b);
939 if (b->chr) {
940 qemu_chr_fe_set_handlers(b, NULL, NULL, NULL, NULL, NULL, true);
941 if (b->chr->be == b) {
942 b->chr->be = NULL;
944 if (b->chr->is_mux) {
945 MuxDriver *d = b->chr->opaque;
946 d->backends[b->tag] = NULL;
948 b->chr = NULL;
952 void qemu_chr_fe_set_handlers(CharBackend *b,
953 IOCanReadHandler *fd_can_read,
954 IOReadHandler *fd_read,
955 IOEventHandler *fd_event,
956 void *opaque,
957 GMainContext *context,
958 bool set_open)
960 CharDriverState *s;
961 int fe_open;
963 s = b->chr;
964 if (!s) {
965 return;
968 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
969 fe_open = 0;
970 remove_fd_in_watch(s);
971 } else {
972 fe_open = 1;
974 b->chr_can_read = fd_can_read;
975 b->chr_read = fd_read;
976 b->chr_event = fd_event;
977 b->opaque = opaque;
978 if (s->chr_update_read_handler) {
979 s->chr_update_read_handler(s, context);
982 if (set_open) {
983 qemu_chr_fe_set_open(b, fe_open);
986 if (fe_open) {
987 qemu_chr_fe_take_focus(b);
988 /* We're connecting to an already opened device, so let's make sure we
989 also get the open event */
990 if (s->be_open) {
991 qemu_chr_be_generic_open(s);
995 if (s->is_mux) {
996 mux_chr_set_handlers(s, context);
1000 void qemu_chr_fe_take_focus(CharBackend *b)
1002 if (!b->chr) {
1003 return;
1006 if (b->chr->is_mux) {
1007 mux_set_focus(b->chr, b->tag);
1011 typedef struct IOWatchPoll
1013 GSource parent;
1015 QIOChannel *ioc;
1016 GSource *src;
1018 IOCanReadHandler *fd_can_read;
1019 GSourceFunc fd_read;
1020 void *opaque;
1021 GMainContext *context;
1022 } IOWatchPoll;
1024 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
1026 return container_of(source, IOWatchPoll, parent);
1029 static gboolean io_watch_poll_prepare(GSource *source,
1030 gint *timeout_)
1032 IOWatchPoll *iwp = io_watch_poll_from_source(source);
1033 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
1034 bool was_active = iwp->src != NULL;
1035 if (was_active == now_active) {
1036 return FALSE;
1039 if (now_active) {
1040 iwp->src = qio_channel_create_watch(
1041 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
1042 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
1043 g_source_attach(iwp->src, iwp->context);
1044 } else {
1045 g_source_destroy(iwp->src);
1046 g_source_unref(iwp->src);
1047 iwp->src = NULL;
1049 return FALSE;
1052 static gboolean io_watch_poll_check(GSource *source)
1054 return FALSE;
1057 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
1058 gpointer user_data)
1060 abort();
1063 static void io_watch_poll_finalize(GSource *source)
1065 /* Due to a glib bug, removing the last reference to a source
1066 * inside a finalize callback causes recursive locking (and a
1067 * deadlock). This is not a problem inside other callbacks,
1068 * including dispatch callbacks, so we call io_remove_watch_poll
1069 * to remove this source. At this point, iwp->src must
1070 * be NULL, or we would leak it.
1072 * This would be solved much more elegantly by child sources,
1073 * but we support older glib versions that do not have them.
1075 IOWatchPoll *iwp = io_watch_poll_from_source(source);
1076 assert(iwp->src == NULL);
1079 static GSourceFuncs io_watch_poll_funcs = {
1080 .prepare = io_watch_poll_prepare,
1081 .check = io_watch_poll_check,
1082 .dispatch = io_watch_poll_dispatch,
1083 .finalize = io_watch_poll_finalize,
1086 /* Can only be used for read */
1087 static guint io_add_watch_poll(CharDriverState *chr,
1088 QIOChannel *ioc,
1089 IOCanReadHandler *fd_can_read,
1090 QIOChannelFunc fd_read,
1091 gpointer user_data,
1092 GMainContext *context)
1094 IOWatchPoll *iwp;
1095 int tag;
1096 char *name;
1098 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs,
1099 sizeof(IOWatchPoll));
1100 iwp->fd_can_read = fd_can_read;
1101 iwp->opaque = user_data;
1102 iwp->ioc = ioc;
1103 iwp->fd_read = (GSourceFunc) fd_read;
1104 iwp->src = NULL;
1105 iwp->context = context;
1107 name = g_strdup_printf("chardev-iowatch-%s", chr->label);
1108 g_source_set_name((GSource *)iwp, name);
1109 g_free(name);
1111 tag = g_source_attach(&iwp->parent, context);
1112 g_source_unref(&iwp->parent);
1113 return tag;
1116 static void io_remove_watch_poll(guint tag)
1118 GSource *source;
1119 IOWatchPoll *iwp;
1121 g_return_if_fail (tag > 0);
1123 source = g_main_context_find_source_by_id(NULL, tag);
1124 g_return_if_fail (source != NULL);
1126 iwp = io_watch_poll_from_source(source);
1127 if (iwp->src) {
1128 g_source_destroy(iwp->src);
1129 g_source_unref(iwp->src);
1130 iwp->src = NULL;
1132 g_source_destroy(&iwp->parent);
1135 static void remove_fd_in_watch(CharDriverState *chr)
1137 if (chr->fd_in_tag) {
1138 io_remove_watch_poll(chr->fd_in_tag);
1139 chr->fd_in_tag = 0;
1144 static int io_channel_send_full(QIOChannel *ioc,
1145 const void *buf, size_t len,
1146 int *fds, size_t nfds)
1148 size_t offset = 0;
1150 while (offset < len) {
1151 ssize_t ret = 0;
1152 struct iovec iov = { .iov_base = (char *)buf + offset,
1153 .iov_len = len - offset };
1155 ret = qio_channel_writev_full(
1156 ioc, &iov, 1,
1157 fds, nfds, NULL);
1158 if (ret == QIO_CHANNEL_ERR_BLOCK) {
1159 if (offset) {
1160 return offset;
1163 errno = EAGAIN;
1164 return -1;
1165 } else if (ret < 0) {
1166 errno = EINVAL;
1167 return -1;
1170 offset += ret;
1173 return offset;
1177 #ifndef _WIN32
1178 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
1180 return io_channel_send_full(ioc, buf, len, NULL, 0);
1184 typedef struct FDCharDriver {
1185 CharDriverState *chr;
1186 QIOChannel *ioc_in, *ioc_out;
1187 int max_size;
1188 } FDCharDriver;
1190 /* Called with chr_write_lock held. */
1191 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1193 FDCharDriver *s = chr->opaque;
1195 return io_channel_send(s->ioc_out, buf, len);
1198 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1200 CharDriverState *chr = opaque;
1201 FDCharDriver *s = chr->opaque;
1202 int len;
1203 uint8_t buf[READ_BUF_LEN];
1204 ssize_t ret;
1206 len = sizeof(buf);
1207 if (len > s->max_size) {
1208 len = s->max_size;
1210 if (len == 0) {
1211 return TRUE;
1214 ret = qio_channel_read(
1215 chan, (gchar *)buf, len, NULL);
1216 if (ret == 0) {
1217 remove_fd_in_watch(chr);
1218 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1219 return FALSE;
1221 if (ret > 0) {
1222 qemu_chr_be_write(chr, buf, ret);
1225 return TRUE;
1228 static int fd_chr_read_poll(void *opaque)
1230 CharDriverState *chr = opaque;
1231 FDCharDriver *s = chr->opaque;
1233 s->max_size = qemu_chr_be_can_write(chr);
1234 return s->max_size;
1237 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1239 FDCharDriver *s = chr->opaque;
1240 return qio_channel_create_watch(s->ioc_out, cond);
1243 static void fd_chr_update_read_handler(CharDriverState *chr,
1244 GMainContext *context)
1246 FDCharDriver *s = chr->opaque;
1248 remove_fd_in_watch(chr);
1249 if (s->ioc_in) {
1250 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc_in,
1251 fd_chr_read_poll,
1252 fd_chr_read, chr,
1253 context);
1257 static void fd_chr_free(struct CharDriverState *chr)
1259 FDCharDriver *s = chr->opaque;
1261 remove_fd_in_watch(chr);
1262 if (s->ioc_in) {
1263 object_unref(OBJECT(s->ioc_in));
1265 if (s->ioc_out) {
1266 object_unref(OBJECT(s->ioc_out));
1269 g_free(s);
1270 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1273 /* open a character device to a unix fd */
1274 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1275 ChardevCommon *backend, Error **errp)
1277 CharDriverState *chr;
1278 FDCharDriver *s;
1279 char *name;
1281 chr = qemu_chr_alloc(backend, errp);
1282 if (!chr) {
1283 return NULL;
1285 s = g_new0(FDCharDriver, 1);
1286 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1287 name = g_strdup_printf("chardev-file-in-%s", chr->label);
1288 qio_channel_set_name(QIO_CHANNEL(s->ioc_in), name);
1289 g_free(name);
1290 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1291 name = g_strdup_printf("chardev-file-out-%s", chr->label);
1292 qio_channel_set_name(QIO_CHANNEL(s->ioc_out), name);
1293 g_free(name);
1294 qemu_set_nonblock(fd_out);
1295 s->chr = chr;
1296 chr->opaque = s;
1297 chr->chr_add_watch = fd_chr_add_watch;
1298 chr->chr_write = fd_chr_write;
1299 chr->chr_update_read_handler = fd_chr_update_read_handler;
1300 chr->chr_free = fd_chr_free;
1302 return chr;
1305 static CharDriverState *qemu_chr_open_pipe(const char *id,
1306 ChardevBackend *backend,
1307 ChardevReturn *ret,
1308 bool *be_opened,
1309 Error **errp)
1311 ChardevHostdev *opts = backend->u.pipe.data;
1312 int fd_in, fd_out;
1313 char *filename_in;
1314 char *filename_out;
1315 const char *filename = opts->device;
1316 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1319 filename_in = g_strdup_printf("%s.in", filename);
1320 filename_out = g_strdup_printf("%s.out", filename);
1321 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1322 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1323 g_free(filename_in);
1324 g_free(filename_out);
1325 if (fd_in < 0 || fd_out < 0) {
1326 if (fd_in >= 0)
1327 close(fd_in);
1328 if (fd_out >= 0)
1329 close(fd_out);
1330 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1331 if (fd_in < 0) {
1332 error_setg_file_open(errp, errno, filename);
1333 return NULL;
1336 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1339 /* init terminal so that we can grab keys */
1340 static struct termios oldtty;
1341 static int old_fd0_flags;
1342 static bool stdio_in_use;
1343 static bool stdio_allow_signal;
1344 static bool stdio_echo_state;
1346 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1348 static void term_exit(void)
1350 tcsetattr (0, TCSANOW, &oldtty);
1351 fcntl(0, F_SETFL, old_fd0_flags);
1354 static void term_stdio_handler(int sig)
1356 /* restore echo after resume from suspend. */
1357 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1360 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1362 struct termios tty;
1364 stdio_echo_state = echo;
1365 tty = oldtty;
1366 if (!echo) {
1367 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1368 |INLCR|IGNCR|ICRNL|IXON);
1369 tty.c_oflag |= OPOST;
1370 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1371 tty.c_cflag &= ~(CSIZE|PARENB);
1372 tty.c_cflag |= CS8;
1373 tty.c_cc[VMIN] = 1;
1374 tty.c_cc[VTIME] = 0;
1376 if (!stdio_allow_signal)
1377 tty.c_lflag &= ~ISIG;
1379 tcsetattr (0, TCSANOW, &tty);
1382 static void qemu_chr_free_stdio(struct CharDriverState *chr)
1384 term_exit();
1385 fd_chr_free(chr);
1388 static CharDriverState *qemu_chr_open_stdio(const char *id,
1389 ChardevBackend *backend,
1390 ChardevReturn *ret,
1391 bool *be_opened,
1392 Error **errp)
1394 ChardevStdio *opts = backend->u.stdio.data;
1395 CharDriverState *chr;
1396 struct sigaction act;
1397 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1399 if (is_daemonized()) {
1400 error_setg(errp, "cannot use stdio with -daemonize");
1401 return NULL;
1404 if (stdio_in_use) {
1405 error_setg(errp, "cannot use stdio by multiple character devices");
1406 return NULL;
1409 stdio_in_use = true;
1410 old_fd0_flags = fcntl(0, F_GETFL);
1411 tcgetattr(0, &oldtty);
1412 qemu_set_nonblock(0);
1413 atexit(term_exit);
1415 memset(&act, 0, sizeof(act));
1416 act.sa_handler = term_stdio_handler;
1417 sigaction(SIGCONT, &act, NULL);
1419 chr = qemu_chr_open_fd(0, 1, common, errp);
1420 if (!chr) {
1421 return NULL;
1423 chr->chr_free = qemu_chr_free_stdio;
1424 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1425 if (opts->has_signal) {
1426 stdio_allow_signal = opts->signal;
1428 qemu_chr_set_echo_stdio(chr, false);
1430 return chr;
1433 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1434 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1435 || defined(__GLIBC__)
1437 #define HAVE_CHARDEV_SERIAL 1
1438 #define HAVE_CHARDEV_PTY 1
1440 typedef struct {
1441 QIOChannel *ioc;
1442 int read_bytes;
1444 /* Protected by the CharDriverState chr_write_lock. */
1445 int connected;
1446 guint timer_tag;
1447 guint open_tag;
1448 } PtyCharDriver;
1450 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1451 static void pty_chr_state(CharDriverState *chr, int connected);
1453 static gboolean pty_chr_timer(gpointer opaque)
1455 struct CharDriverState *chr = opaque;
1456 PtyCharDriver *s = chr->opaque;
1458 qemu_mutex_lock(&chr->chr_write_lock);
1459 s->timer_tag = 0;
1460 s->open_tag = 0;
1461 if (!s->connected) {
1462 /* Next poll ... */
1463 pty_chr_update_read_handler_locked(chr);
1465 qemu_mutex_unlock(&chr->chr_write_lock);
1466 return FALSE;
1469 /* Called with chr_write_lock held. */
1470 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1472 PtyCharDriver *s = chr->opaque;
1473 char *name;
1475 if (s->timer_tag) {
1476 g_source_remove(s->timer_tag);
1477 s->timer_tag = 0;
1480 if (ms == 1000) {
1481 name = g_strdup_printf("pty-timer-secs-%s", chr->label);
1482 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1483 } else {
1484 name = g_strdup_printf("pty-timer-ms-%s", chr->label);
1485 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1487 g_source_set_name_by_id(s->timer_tag, name);
1488 g_free(name);
1491 /* Called with chr_write_lock held. */
1492 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1494 PtyCharDriver *s = chr->opaque;
1495 GPollFD pfd;
1496 int rc;
1497 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1499 pfd.fd = fioc->fd;
1500 pfd.events = G_IO_OUT;
1501 pfd.revents = 0;
1502 do {
1503 rc = g_poll(&pfd, 1, 0);
1504 } while (rc == -1 && errno == EINTR);
1505 assert(rc >= 0);
1507 if (pfd.revents & G_IO_HUP) {
1508 pty_chr_state(chr, 0);
1509 } else {
1510 pty_chr_state(chr, 1);
1514 static void pty_chr_update_read_handler(CharDriverState *chr,
1515 GMainContext *context)
1517 qemu_mutex_lock(&chr->chr_write_lock);
1518 pty_chr_update_read_handler_locked(chr);
1519 qemu_mutex_unlock(&chr->chr_write_lock);
1522 /* Called with chr_write_lock held. */
1523 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1525 PtyCharDriver *s = chr->opaque;
1527 if (!s->connected) {
1528 /* guest sends data, check for (re-)connect */
1529 pty_chr_update_read_handler_locked(chr);
1530 if (!s->connected) {
1531 return 0;
1534 return io_channel_send(s->ioc, buf, len);
1537 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1539 PtyCharDriver *s = chr->opaque;
1540 if (!s->connected) {
1541 return NULL;
1543 return qio_channel_create_watch(s->ioc, cond);
1546 static int pty_chr_read_poll(void *opaque)
1548 CharDriverState *chr = opaque;
1549 PtyCharDriver *s = chr->opaque;
1551 s->read_bytes = qemu_chr_be_can_write(chr);
1552 return s->read_bytes;
1555 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1557 CharDriverState *chr = opaque;
1558 PtyCharDriver *s = chr->opaque;
1559 gsize len;
1560 uint8_t buf[READ_BUF_LEN];
1561 ssize_t ret;
1563 len = sizeof(buf);
1564 if (len > s->read_bytes)
1565 len = s->read_bytes;
1566 if (len == 0) {
1567 return TRUE;
1569 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1570 if (ret <= 0) {
1571 pty_chr_state(chr, 0);
1572 return FALSE;
1573 } else {
1574 pty_chr_state(chr, 1);
1575 qemu_chr_be_write(chr, buf, ret);
1577 return TRUE;
1580 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1582 CharDriverState *chr = opaque;
1583 PtyCharDriver *s = chr->opaque;
1585 s->open_tag = 0;
1586 qemu_chr_be_generic_open(chr);
1587 return FALSE;
1590 /* Called with chr_write_lock held. */
1591 static void pty_chr_state(CharDriverState *chr, int connected)
1593 PtyCharDriver *s = chr->opaque;
1595 if (!connected) {
1596 if (s->open_tag) {
1597 g_source_remove(s->open_tag);
1598 s->open_tag = 0;
1600 remove_fd_in_watch(chr);
1601 s->connected = 0;
1602 /* (re-)connect poll interval for idle guests: once per second.
1603 * We check more frequently in case the guests sends data to
1604 * the virtual device linked to our pty. */
1605 pty_chr_rearm_timer(chr, 1000);
1606 } else {
1607 if (s->timer_tag) {
1608 g_source_remove(s->timer_tag);
1609 s->timer_tag = 0;
1611 if (!s->connected) {
1612 g_assert(s->open_tag == 0);
1613 s->connected = 1;
1614 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1616 if (!chr->fd_in_tag) {
1617 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
1618 pty_chr_read_poll,
1619 pty_chr_read,
1620 chr, NULL);
1625 static void pty_chr_free(struct CharDriverState *chr)
1627 PtyCharDriver *s = chr->opaque;
1629 qemu_mutex_lock(&chr->chr_write_lock);
1630 pty_chr_state(chr, 0);
1631 object_unref(OBJECT(s->ioc));
1632 if (s->timer_tag) {
1633 g_source_remove(s->timer_tag);
1634 s->timer_tag = 0;
1636 qemu_mutex_unlock(&chr->chr_write_lock);
1637 g_free(s);
1638 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1641 static CharDriverState *qemu_chr_open_pty(const char *id,
1642 ChardevBackend *backend,
1643 ChardevReturn *ret,
1644 bool *be_opened,
1645 Error **errp)
1647 CharDriverState *chr;
1648 PtyCharDriver *s;
1649 int master_fd, slave_fd;
1650 char pty_name[PATH_MAX];
1651 ChardevCommon *common = backend->u.pty.data;
1652 char *name;
1654 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1655 if (master_fd < 0) {
1656 error_setg_errno(errp, errno, "Failed to create PTY");
1657 return NULL;
1660 close(slave_fd);
1661 qemu_set_nonblock(master_fd);
1663 chr = qemu_chr_alloc(common, errp);
1664 if (!chr) {
1665 close(master_fd);
1666 return NULL;
1669 chr->filename = g_strdup_printf("pty:%s", pty_name);
1670 ret->pty = g_strdup(pty_name);
1671 ret->has_pty = true;
1673 fprintf(stderr, "char device redirected to %s (label %s)\n",
1674 pty_name, id);
1676 s = g_new0(PtyCharDriver, 1);
1677 chr->opaque = s;
1678 chr->chr_write = pty_chr_write;
1679 chr->chr_update_read_handler = pty_chr_update_read_handler;
1680 chr->chr_free = pty_chr_free;
1681 chr->chr_add_watch = pty_chr_add_watch;
1682 *be_opened = false;
1684 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1685 name = g_strdup_printf("chardev-pty-%s", chr->label);
1686 qio_channel_set_name(QIO_CHANNEL(s->ioc), name);
1687 g_free(name);
1688 s->timer_tag = 0;
1690 return chr;
1693 static void tty_serial_init(int fd, int speed,
1694 int parity, int data_bits, int stop_bits)
1696 struct termios tty;
1697 speed_t spd;
1699 #if 0
1700 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1701 speed, parity, data_bits, stop_bits);
1702 #endif
1703 tcgetattr (fd, &tty);
1705 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1706 speed = speed * 10 / 11;
1707 do {
1708 check_speed(50);
1709 check_speed(75);
1710 check_speed(110);
1711 check_speed(134);
1712 check_speed(150);
1713 check_speed(200);
1714 check_speed(300);
1715 check_speed(600);
1716 check_speed(1200);
1717 check_speed(1800);
1718 check_speed(2400);
1719 check_speed(4800);
1720 check_speed(9600);
1721 check_speed(19200);
1722 check_speed(38400);
1723 /* Non-Posix values follow. They may be unsupported on some systems. */
1724 check_speed(57600);
1725 check_speed(115200);
1726 #ifdef B230400
1727 check_speed(230400);
1728 #endif
1729 #ifdef B460800
1730 check_speed(460800);
1731 #endif
1732 #ifdef B500000
1733 check_speed(500000);
1734 #endif
1735 #ifdef B576000
1736 check_speed(576000);
1737 #endif
1738 #ifdef B921600
1739 check_speed(921600);
1740 #endif
1741 #ifdef B1000000
1742 check_speed(1000000);
1743 #endif
1744 #ifdef B1152000
1745 check_speed(1152000);
1746 #endif
1747 #ifdef B1500000
1748 check_speed(1500000);
1749 #endif
1750 #ifdef B2000000
1751 check_speed(2000000);
1752 #endif
1753 #ifdef B2500000
1754 check_speed(2500000);
1755 #endif
1756 #ifdef B3000000
1757 check_speed(3000000);
1758 #endif
1759 #ifdef B3500000
1760 check_speed(3500000);
1761 #endif
1762 #ifdef B4000000
1763 check_speed(4000000);
1764 #endif
1765 spd = B115200;
1766 } while (0);
1768 cfsetispeed(&tty, spd);
1769 cfsetospeed(&tty, spd);
1771 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1772 |INLCR|IGNCR|ICRNL|IXON);
1773 tty.c_oflag |= OPOST;
1774 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1775 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1776 switch(data_bits) {
1777 default:
1778 case 8:
1779 tty.c_cflag |= CS8;
1780 break;
1781 case 7:
1782 tty.c_cflag |= CS7;
1783 break;
1784 case 6:
1785 tty.c_cflag |= CS6;
1786 break;
1787 case 5:
1788 tty.c_cflag |= CS5;
1789 break;
1791 switch(parity) {
1792 default:
1793 case 'N':
1794 break;
1795 case 'E':
1796 tty.c_cflag |= PARENB;
1797 break;
1798 case 'O':
1799 tty.c_cflag |= PARENB | PARODD;
1800 break;
1802 if (stop_bits == 2)
1803 tty.c_cflag |= CSTOPB;
1805 tcsetattr (fd, TCSANOW, &tty);
1808 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1810 FDCharDriver *s = chr->opaque;
1811 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1813 switch(cmd) {
1814 case CHR_IOCTL_SERIAL_SET_PARAMS:
1816 QEMUSerialSetParams *ssp = arg;
1817 tty_serial_init(fioc->fd,
1818 ssp->speed, ssp->parity,
1819 ssp->data_bits, ssp->stop_bits);
1821 break;
1822 case CHR_IOCTL_SERIAL_SET_BREAK:
1824 int enable = *(int *)arg;
1825 if (enable) {
1826 tcsendbreak(fioc->fd, 1);
1829 break;
1830 case CHR_IOCTL_SERIAL_GET_TIOCM:
1832 int sarg = 0;
1833 int *targ = (int *)arg;
1834 ioctl(fioc->fd, TIOCMGET, &sarg);
1835 *targ = 0;
1836 if (sarg & TIOCM_CTS)
1837 *targ |= CHR_TIOCM_CTS;
1838 if (sarg & TIOCM_CAR)
1839 *targ |= CHR_TIOCM_CAR;
1840 if (sarg & TIOCM_DSR)
1841 *targ |= CHR_TIOCM_DSR;
1842 if (sarg & TIOCM_RI)
1843 *targ |= CHR_TIOCM_RI;
1844 if (sarg & TIOCM_DTR)
1845 *targ |= CHR_TIOCM_DTR;
1846 if (sarg & TIOCM_RTS)
1847 *targ |= CHR_TIOCM_RTS;
1849 break;
1850 case CHR_IOCTL_SERIAL_SET_TIOCM:
1852 int sarg = *(int *)arg;
1853 int targ = 0;
1854 ioctl(fioc->fd, TIOCMGET, &targ);
1855 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1856 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1857 if (sarg & CHR_TIOCM_CTS)
1858 targ |= TIOCM_CTS;
1859 if (sarg & CHR_TIOCM_CAR)
1860 targ |= TIOCM_CAR;
1861 if (sarg & CHR_TIOCM_DSR)
1862 targ |= TIOCM_DSR;
1863 if (sarg & CHR_TIOCM_RI)
1864 targ |= TIOCM_RI;
1865 if (sarg & CHR_TIOCM_DTR)
1866 targ |= TIOCM_DTR;
1867 if (sarg & CHR_TIOCM_RTS)
1868 targ |= TIOCM_RTS;
1869 ioctl(fioc->fd, TIOCMSET, &targ);
1871 break;
1872 default:
1873 return -ENOTSUP;
1875 return 0;
1878 static void qemu_chr_free_tty(CharDriverState *chr)
1880 fd_chr_free(chr);
1883 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1884 ChardevCommon *backend,
1885 bool *be_opened,
1886 Error **errp)
1888 CharDriverState *chr;
1890 tty_serial_init(fd, 115200, 'N', 8, 1);
1891 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1892 if (!chr) {
1893 return NULL;
1895 chr->chr_ioctl = tty_serial_ioctl;
1896 chr->chr_free = qemu_chr_free_tty;
1897 return chr;
1899 #endif /* __linux__ || __sun__ */
1901 #if defined(__linux__)
1903 #define HAVE_CHARDEV_PARPORT 1
1905 typedef struct {
1906 int fd;
1907 int mode;
1908 } ParallelCharDriver;
1910 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1912 if (s->mode != mode) {
1913 int m = mode;
1914 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1915 return 0;
1916 s->mode = mode;
1918 return 1;
1921 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1923 ParallelCharDriver *drv = chr->opaque;
1924 int fd = drv->fd;
1925 uint8_t b;
1927 switch(cmd) {
1928 case CHR_IOCTL_PP_READ_DATA:
1929 if (ioctl(fd, PPRDATA, &b) < 0)
1930 return -ENOTSUP;
1931 *(uint8_t *)arg = b;
1932 break;
1933 case CHR_IOCTL_PP_WRITE_DATA:
1934 b = *(uint8_t *)arg;
1935 if (ioctl(fd, PPWDATA, &b) < 0)
1936 return -ENOTSUP;
1937 break;
1938 case CHR_IOCTL_PP_READ_CONTROL:
1939 if (ioctl(fd, PPRCONTROL, &b) < 0)
1940 return -ENOTSUP;
1941 /* Linux gives only the lowest bits, and no way to know data
1942 direction! For better compatibility set the fixed upper
1943 bits. */
1944 *(uint8_t *)arg = b | 0xc0;
1945 break;
1946 case CHR_IOCTL_PP_WRITE_CONTROL:
1947 b = *(uint8_t *)arg;
1948 if (ioctl(fd, PPWCONTROL, &b) < 0)
1949 return -ENOTSUP;
1950 break;
1951 case CHR_IOCTL_PP_READ_STATUS:
1952 if (ioctl(fd, PPRSTATUS, &b) < 0)
1953 return -ENOTSUP;
1954 *(uint8_t *)arg = b;
1955 break;
1956 case CHR_IOCTL_PP_DATA_DIR:
1957 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1958 return -ENOTSUP;
1959 break;
1960 case CHR_IOCTL_PP_EPP_READ_ADDR:
1961 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1962 struct ParallelIOArg *parg = arg;
1963 int n = read(fd, parg->buffer, parg->count);
1964 if (n != parg->count) {
1965 return -EIO;
1968 break;
1969 case CHR_IOCTL_PP_EPP_READ:
1970 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1971 struct ParallelIOArg *parg = arg;
1972 int n = read(fd, parg->buffer, parg->count);
1973 if (n != parg->count) {
1974 return -EIO;
1977 break;
1978 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1979 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1980 struct ParallelIOArg *parg = arg;
1981 int n = write(fd, parg->buffer, parg->count);
1982 if (n != parg->count) {
1983 return -EIO;
1986 break;
1987 case CHR_IOCTL_PP_EPP_WRITE:
1988 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1989 struct ParallelIOArg *parg = arg;
1990 int n = write(fd, parg->buffer, parg->count);
1991 if (n != parg->count) {
1992 return -EIO;
1995 break;
1996 default:
1997 return -ENOTSUP;
1999 return 0;
2002 static void pp_free(CharDriverState *chr)
2004 ParallelCharDriver *drv = chr->opaque;
2005 int fd = drv->fd;
2007 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2008 ioctl(fd, PPRELEASE);
2009 close(fd);
2010 g_free(drv);
2011 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2014 static CharDriverState *qemu_chr_open_pp_fd(int fd,
2015 ChardevCommon *backend,
2016 bool *be_opened,
2017 Error **errp)
2019 CharDriverState *chr;
2020 ParallelCharDriver *drv;
2022 if (ioctl(fd, PPCLAIM) < 0) {
2023 error_setg_errno(errp, errno, "not a parallel port");
2024 close(fd);
2025 return NULL;
2028 chr = qemu_chr_alloc(backend, errp);
2029 if (!chr) {
2030 return NULL;
2033 drv = g_new0(ParallelCharDriver, 1);
2034 chr->opaque = drv;
2035 chr->chr_write = null_chr_write;
2036 chr->chr_ioctl = pp_ioctl;
2037 chr->chr_free = pp_free;
2039 drv->fd = fd;
2040 drv->mode = IEEE1284_MODE_COMPAT;
2042 return chr;
2044 #endif /* __linux__ */
2046 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
2048 #define HAVE_CHARDEV_PARPORT 1
2050 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2052 int fd = (int)(intptr_t)chr->opaque;
2053 uint8_t b;
2055 switch(cmd) {
2056 case CHR_IOCTL_PP_READ_DATA:
2057 if (ioctl(fd, PPIGDATA, &b) < 0)
2058 return -ENOTSUP;
2059 *(uint8_t *)arg = b;
2060 break;
2061 case CHR_IOCTL_PP_WRITE_DATA:
2062 b = *(uint8_t *)arg;
2063 if (ioctl(fd, PPISDATA, &b) < 0)
2064 return -ENOTSUP;
2065 break;
2066 case CHR_IOCTL_PP_READ_CONTROL:
2067 if (ioctl(fd, PPIGCTRL, &b) < 0)
2068 return -ENOTSUP;
2069 *(uint8_t *)arg = b;
2070 break;
2071 case CHR_IOCTL_PP_WRITE_CONTROL:
2072 b = *(uint8_t *)arg;
2073 if (ioctl(fd, PPISCTRL, &b) < 0)
2074 return -ENOTSUP;
2075 break;
2076 case CHR_IOCTL_PP_READ_STATUS:
2077 if (ioctl(fd, PPIGSTATUS, &b) < 0)
2078 return -ENOTSUP;
2079 *(uint8_t *)arg = b;
2080 break;
2081 default:
2082 return -ENOTSUP;
2084 return 0;
2087 static CharDriverState *qemu_chr_open_pp_fd(int fd,
2088 ChardevCommon *backend,
2089 bool *be_opened,
2090 Error **errp)
2092 CharDriverState *chr;
2094 chr = qemu_chr_alloc(backend, errp);
2095 if (!chr) {
2096 return NULL;
2098 chr->opaque = (void *)(intptr_t)fd;
2099 chr->chr_write = null_chr_write;
2100 chr->chr_ioctl = pp_ioctl;
2101 *be_opened = false;
2102 return chr;
2104 #endif
2106 #else /* _WIN32 */
2108 #define HAVE_CHARDEV_SERIAL 1
2110 typedef struct {
2111 int max_size;
2112 HANDLE hcom, hrecv, hsend;
2113 OVERLAPPED orecv;
2114 BOOL fpipe;
2115 DWORD len;
2117 /* Protected by the CharDriverState chr_write_lock. */
2118 OVERLAPPED osend;
2119 } WinCharState;
2121 typedef struct {
2122 HANDLE hStdIn;
2123 HANDLE hInputReadyEvent;
2124 HANDLE hInputDoneEvent;
2125 HANDLE hInputThread;
2126 uint8_t win_stdio_buf;
2127 } WinStdioCharState;
2129 #define NSENDBUF 2048
2130 #define NRECVBUF 2048
2131 #define MAXCONNECT 1
2132 #define NTIMEOUT 5000
2134 static int win_chr_poll(void *opaque);
2135 static int win_chr_pipe_poll(void *opaque);
2137 static void win_chr_free(CharDriverState *chr)
2139 WinCharState *s = chr->opaque;
2141 if (s->hsend) {
2142 CloseHandle(s->hsend);
2143 s->hsend = NULL;
2145 if (s->hrecv) {
2146 CloseHandle(s->hrecv);
2147 s->hrecv = NULL;
2149 if (s->hcom) {
2150 CloseHandle(s->hcom);
2151 s->hcom = NULL;
2153 if (s->fpipe)
2154 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2155 else
2156 qemu_del_polling_cb(win_chr_poll, chr);
2158 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2161 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
2163 WinCharState *s = chr->opaque;
2164 COMMCONFIG comcfg;
2165 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2166 COMSTAT comstat;
2167 DWORD size;
2168 DWORD err;
2170 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2171 if (!s->hsend) {
2172 error_setg(errp, "Failed CreateEvent");
2173 goto fail;
2175 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2176 if (!s->hrecv) {
2177 error_setg(errp, "Failed CreateEvent");
2178 goto fail;
2181 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2182 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2183 if (s->hcom == INVALID_HANDLE_VALUE) {
2184 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
2185 s->hcom = NULL;
2186 goto fail;
2189 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2190 error_setg(errp, "Failed SetupComm");
2191 goto fail;
2194 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2195 size = sizeof(COMMCONFIG);
2196 GetDefaultCommConfig(filename, &comcfg, &size);
2197 comcfg.dcb.DCBlength = sizeof(DCB);
2198 CommConfigDialog(filename, NULL, &comcfg);
2200 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2201 error_setg(errp, "Failed SetCommState");
2202 goto fail;
2205 if (!SetCommMask(s->hcom, EV_ERR)) {
2206 error_setg(errp, "Failed SetCommMask");
2207 goto fail;
2210 cto.ReadIntervalTimeout = MAXDWORD;
2211 if (!SetCommTimeouts(s->hcom, &cto)) {
2212 error_setg(errp, "Failed SetCommTimeouts");
2213 goto fail;
2216 if (!ClearCommError(s->hcom, &err, &comstat)) {
2217 error_setg(errp, "Failed ClearCommError");
2218 goto fail;
2220 qemu_add_polling_cb(win_chr_poll, chr);
2221 return 0;
2223 fail:
2224 win_chr_free(chr);
2225 return -1;
2228 /* Called with chr_write_lock held. */
2229 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2231 WinCharState *s = chr->opaque;
2232 DWORD len, ret, size, err;
2234 len = len1;
2235 ZeroMemory(&s->osend, sizeof(s->osend));
2236 s->osend.hEvent = s->hsend;
2237 while (len > 0) {
2238 if (s->hsend)
2239 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2240 else
2241 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2242 if (!ret) {
2243 err = GetLastError();
2244 if (err == ERROR_IO_PENDING) {
2245 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2246 if (ret) {
2247 buf += size;
2248 len -= size;
2249 } else {
2250 break;
2252 } else {
2253 break;
2255 } else {
2256 buf += size;
2257 len -= size;
2260 return len1 - len;
2263 static int win_chr_read_poll(CharDriverState *chr)
2265 WinCharState *s = chr->opaque;
2267 s->max_size = qemu_chr_be_can_write(chr);
2268 return s->max_size;
2271 static void win_chr_readfile(CharDriverState *chr)
2273 WinCharState *s = chr->opaque;
2274 int ret, err;
2275 uint8_t buf[READ_BUF_LEN];
2276 DWORD size;
2278 ZeroMemory(&s->orecv, sizeof(s->orecv));
2279 s->orecv.hEvent = s->hrecv;
2280 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2281 if (!ret) {
2282 err = GetLastError();
2283 if (err == ERROR_IO_PENDING) {
2284 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2288 if (size > 0) {
2289 qemu_chr_be_write(chr, buf, size);
2293 static void win_chr_read(CharDriverState *chr)
2295 WinCharState *s = chr->opaque;
2297 if (s->len > s->max_size)
2298 s->len = s->max_size;
2299 if (s->len == 0)
2300 return;
2302 win_chr_readfile(chr);
2305 static int win_chr_poll(void *opaque)
2307 CharDriverState *chr = opaque;
2308 WinCharState *s = chr->opaque;
2309 COMSTAT status;
2310 DWORD comerr;
2312 ClearCommError(s->hcom, &comerr, &status);
2313 if (status.cbInQue > 0) {
2314 s->len = status.cbInQue;
2315 win_chr_read_poll(chr);
2316 win_chr_read(chr);
2317 return 1;
2319 return 0;
2322 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2323 ChardevCommon *backend,
2324 Error **errp)
2326 CharDriverState *chr;
2327 WinCharState *s;
2329 chr = qemu_chr_alloc(backend, errp);
2330 if (!chr) {
2331 return NULL;
2333 s = g_new0(WinCharState, 1);
2334 chr->opaque = s;
2335 chr->chr_write = win_chr_write;
2336 chr->chr_free = win_chr_free;
2338 if (win_chr_init(chr, filename, errp) < 0) {
2339 g_free(s);
2340 qemu_chr_free_common(chr);
2341 return NULL;
2343 return chr;
2346 static int win_chr_pipe_poll(void *opaque)
2348 CharDriverState *chr = opaque;
2349 WinCharState *s = chr->opaque;
2350 DWORD size;
2352 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2353 if (size > 0) {
2354 s->len = size;
2355 win_chr_read_poll(chr);
2356 win_chr_read(chr);
2357 return 1;
2359 return 0;
2362 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2363 Error **errp)
2365 WinCharState *s = chr->opaque;
2366 OVERLAPPED ov;
2367 int ret;
2368 DWORD size;
2369 char *openname;
2371 s->fpipe = TRUE;
2373 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2374 if (!s->hsend) {
2375 error_setg(errp, "Failed CreateEvent");
2376 goto fail;
2378 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2379 if (!s->hrecv) {
2380 error_setg(errp, "Failed CreateEvent");
2381 goto fail;
2384 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2385 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2386 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2387 PIPE_WAIT,
2388 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2389 g_free(openname);
2390 if (s->hcom == INVALID_HANDLE_VALUE) {
2391 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2392 s->hcom = NULL;
2393 goto fail;
2396 ZeroMemory(&ov, sizeof(ov));
2397 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2398 ret = ConnectNamedPipe(s->hcom, &ov);
2399 if (ret) {
2400 error_setg(errp, "Failed ConnectNamedPipe");
2401 goto fail;
2404 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2405 if (!ret) {
2406 error_setg(errp, "Failed GetOverlappedResult");
2407 if (ov.hEvent) {
2408 CloseHandle(ov.hEvent);
2409 ov.hEvent = NULL;
2411 goto fail;
2414 if (ov.hEvent) {
2415 CloseHandle(ov.hEvent);
2416 ov.hEvent = NULL;
2418 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2419 return 0;
2421 fail:
2422 win_chr_free(chr);
2423 return -1;
2427 static CharDriverState *qemu_chr_open_pipe(const char *id,
2428 ChardevBackend *backend,
2429 ChardevReturn *ret,
2430 bool *be_opened,
2431 Error **errp)
2433 ChardevHostdev *opts = backend->u.pipe.data;
2434 const char *filename = opts->device;
2435 CharDriverState *chr;
2436 WinCharState *s;
2437 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2439 chr = qemu_chr_alloc(common, errp);
2440 if (!chr) {
2441 return NULL;
2443 s = g_new0(WinCharState, 1);
2444 chr->opaque = s;
2445 chr->chr_write = win_chr_write;
2446 chr->chr_free = win_chr_free;
2448 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2449 g_free(s);
2450 qemu_chr_free_common(chr);
2451 return NULL;
2453 return chr;
2456 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2457 ChardevCommon *backend,
2458 Error **errp)
2460 CharDriverState *chr;
2461 WinCharState *s;
2463 chr = qemu_chr_alloc(backend, errp);
2464 if (!chr) {
2465 return NULL;
2467 s = g_new0(WinCharState, 1);
2468 s->hcom = fd_out;
2469 chr->opaque = s;
2470 chr->chr_write = win_chr_write;
2471 return chr;
2474 static CharDriverState *qemu_chr_open_win_con(const char *id,
2475 ChardevBackend *backend,
2476 ChardevReturn *ret,
2477 bool *be_opened,
2478 Error **errp)
2480 ChardevCommon *common = backend->u.console.data;
2481 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2482 common, errp);
2485 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2487 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2488 DWORD dwSize;
2489 int len1;
2491 len1 = len;
2493 while (len1 > 0) {
2494 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2495 break;
2497 buf += dwSize;
2498 len1 -= dwSize;
2501 return len - len1;
2504 static void win_stdio_wait_func(void *opaque)
2506 CharDriverState *chr = opaque;
2507 WinStdioCharState *stdio = chr->opaque;
2508 INPUT_RECORD buf[4];
2509 int ret;
2510 DWORD dwSize;
2511 int i;
2513 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2515 if (!ret) {
2516 /* Avoid error storm */
2517 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2518 return;
2521 for (i = 0; i < dwSize; i++) {
2522 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2524 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2525 int j;
2526 if (kev->uChar.AsciiChar != 0) {
2527 for (j = 0; j < kev->wRepeatCount; j++) {
2528 if (qemu_chr_be_can_write(chr)) {
2529 uint8_t c = kev->uChar.AsciiChar;
2530 qemu_chr_be_write(chr, &c, 1);
2538 static DWORD WINAPI win_stdio_thread(LPVOID param)
2540 CharDriverState *chr = param;
2541 WinStdioCharState *stdio = chr->opaque;
2542 int ret;
2543 DWORD dwSize;
2545 while (1) {
2547 /* Wait for one byte */
2548 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2550 /* Exit in case of error, continue if nothing read */
2551 if (!ret) {
2552 break;
2554 if (!dwSize) {
2555 continue;
2558 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2559 if (stdio->win_stdio_buf == '\r') {
2560 continue;
2563 /* Signal the main thread and wait until the byte was eaten */
2564 if (!SetEvent(stdio->hInputReadyEvent)) {
2565 break;
2567 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2568 != WAIT_OBJECT_0) {
2569 break;
2573 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2574 return 0;
2577 static void win_stdio_thread_wait_func(void *opaque)
2579 CharDriverState *chr = opaque;
2580 WinStdioCharState *stdio = chr->opaque;
2582 if (qemu_chr_be_can_write(chr)) {
2583 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2586 SetEvent(stdio->hInputDoneEvent);
2589 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2591 WinStdioCharState *stdio = chr->opaque;
2592 DWORD dwMode = 0;
2594 GetConsoleMode(stdio->hStdIn, &dwMode);
2596 if (echo) {
2597 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2598 } else {
2599 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2603 static void win_stdio_free(CharDriverState *chr)
2605 WinStdioCharState *stdio = chr->opaque;
2607 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2608 CloseHandle(stdio->hInputReadyEvent);
2610 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2611 CloseHandle(stdio->hInputDoneEvent);
2613 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2614 TerminateThread(stdio->hInputThread, 0);
2617 g_free(chr->opaque);
2620 static CharDriverState *qemu_chr_open_stdio(const char *id,
2621 ChardevBackend *backend,
2622 ChardevReturn *ret,
2623 bool *be_opened,
2624 Error **errp)
2626 CharDriverState *chr;
2627 WinStdioCharState *stdio;
2628 DWORD dwMode;
2629 int is_console = 0;
2630 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio.data);
2632 chr = qemu_chr_alloc(common, errp);
2633 if (!chr) {
2634 return NULL;
2636 stdio = g_new0(WinStdioCharState, 1);
2638 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2639 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2640 error_setg(errp, "cannot open stdio: invalid handle");
2641 return NULL;
2644 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2646 chr->opaque = stdio;
2647 chr->chr_write = win_stdio_write;
2648 chr->chr_free = win_stdio_free;
2650 if (is_console) {
2651 if (qemu_add_wait_object(stdio->hStdIn,
2652 win_stdio_wait_func, chr)) {
2653 error_setg(errp, "qemu_add_wait_object: failed");
2654 goto err1;
2656 } else {
2657 DWORD dwId;
2659 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2660 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2661 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2662 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2663 error_setg(errp, "cannot create event");
2664 goto err2;
2666 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2667 win_stdio_thread_wait_func, chr)) {
2668 error_setg(errp, "qemu_add_wait_object: failed");
2669 goto err2;
2671 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2672 chr, 0, &dwId);
2674 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2675 error_setg(errp, "cannot create stdio thread");
2676 goto err3;
2680 dwMode |= ENABLE_LINE_INPUT;
2682 if (is_console) {
2683 /* set the terminal in raw mode */
2684 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2685 dwMode |= ENABLE_PROCESSED_INPUT;
2688 SetConsoleMode(stdio->hStdIn, dwMode);
2690 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2691 qemu_chr_set_echo_win_stdio(chr, false);
2693 return chr;
2695 err3:
2696 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2697 err2:
2698 CloseHandle(stdio->hInputReadyEvent);
2699 CloseHandle(stdio->hInputDoneEvent);
2700 err1:
2701 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2702 return NULL;
2704 #endif /* !_WIN32 */
2706 /***********************************************************/
2707 /* UDP Net console */
2709 typedef struct {
2710 QIOChannel *ioc;
2711 uint8_t buf[READ_BUF_LEN];
2712 int bufcnt;
2713 int bufptr;
2714 int max_size;
2715 } NetCharDriver;
2717 /* Called with chr_write_lock held. */
2718 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2720 NetCharDriver *s = chr->opaque;
2722 return qio_channel_write(
2723 s->ioc, (const char *)buf, len, NULL);
2726 static int udp_chr_read_poll(void *opaque)
2728 CharDriverState *chr = opaque;
2729 NetCharDriver *s = chr->opaque;
2731 s->max_size = qemu_chr_be_can_write(chr);
2733 /* If there were any stray characters in the queue process them
2734 * first
2736 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2737 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2738 s->bufptr++;
2739 s->max_size = qemu_chr_be_can_write(chr);
2741 return s->max_size;
2744 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2746 CharDriverState *chr = opaque;
2747 NetCharDriver *s = chr->opaque;
2748 ssize_t ret;
2750 if (s->max_size == 0) {
2751 return TRUE;
2753 ret = qio_channel_read(
2754 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2755 if (ret <= 0) {
2756 remove_fd_in_watch(chr);
2757 return FALSE;
2759 s->bufcnt = ret;
2761 s->bufptr = 0;
2762 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2763 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2764 s->bufptr++;
2765 s->max_size = qemu_chr_be_can_write(chr);
2768 return TRUE;
2771 static void udp_chr_update_read_handler(CharDriverState *chr,
2772 GMainContext *context)
2774 NetCharDriver *s = chr->opaque;
2776 remove_fd_in_watch(chr);
2777 if (s->ioc) {
2778 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
2779 udp_chr_read_poll,
2780 udp_chr_read, chr,
2781 context);
2785 static void udp_chr_free(CharDriverState *chr)
2787 NetCharDriver *s = chr->opaque;
2789 remove_fd_in_watch(chr);
2790 if (s->ioc) {
2791 object_unref(OBJECT(s->ioc));
2793 g_free(s);
2794 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2797 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2798 ChardevCommon *backend,
2799 bool *be_opened,
2800 Error **errp)
2802 CharDriverState *chr = NULL;
2803 NetCharDriver *s = NULL;
2805 chr = qemu_chr_alloc(backend, errp);
2806 if (!chr) {
2807 return NULL;
2809 s = g_new0(NetCharDriver, 1);
2811 s->ioc = QIO_CHANNEL(sioc);
2812 s->bufcnt = 0;
2813 s->bufptr = 0;
2814 chr->opaque = s;
2815 chr->chr_write = udp_chr_write;
2816 chr->chr_update_read_handler = udp_chr_update_read_handler;
2817 chr->chr_free = udp_chr_free;
2818 /* be isn't opened until we get a connection */
2819 *be_opened = false;
2820 return chr;
2823 /***********************************************************/
2824 /* TCP Net console */
2826 typedef struct {
2827 QIOChannel *ioc; /* Client I/O channel */
2828 QIOChannelSocket *sioc; /* Client master channel */
2829 QIOChannelSocket *listen_ioc;
2830 guint listen_tag;
2831 QCryptoTLSCreds *tls_creds;
2832 int connected;
2833 int max_size;
2834 int do_telnetopt;
2835 int do_nodelay;
2836 int is_unix;
2837 int *read_msgfds;
2838 size_t read_msgfds_num;
2839 int *write_msgfds;
2840 size_t write_msgfds_num;
2842 SocketAddress *addr;
2843 bool is_listen;
2844 bool is_telnet;
2846 guint reconnect_timer;
2847 int64_t reconnect_time;
2848 bool connect_err_reported;
2849 } TCPCharDriver;
2851 static gboolean socket_reconnect_timeout(gpointer opaque);
2853 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2855 TCPCharDriver *s = chr->opaque;
2856 char *name;
2857 assert(s->connected == 0);
2858 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2859 socket_reconnect_timeout, chr);
2860 name = g_strdup_printf("chardev-socket-reconnect-%s", chr->label);
2861 g_source_set_name_by_id(s->reconnect_timer, name);
2862 g_free(name);
2865 static void check_report_connect_error(CharDriverState *chr,
2866 Error *err)
2868 TCPCharDriver *s = chr->opaque;
2870 if (!s->connect_err_reported) {
2871 error_report("Unable to connect character device %s: %s",
2872 chr->label, error_get_pretty(err));
2873 s->connect_err_reported = true;
2875 qemu_chr_socket_restart_timer(chr);
2878 static gboolean tcp_chr_accept(QIOChannel *chan,
2879 GIOCondition cond,
2880 void *opaque);
2882 /* Called with chr_write_lock held. */
2883 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2885 TCPCharDriver *s = chr->opaque;
2886 if (s->connected) {
2887 int ret = io_channel_send_full(s->ioc, buf, len,
2888 s->write_msgfds,
2889 s->write_msgfds_num);
2891 /* free the written msgfds, no matter what */
2892 if (s->write_msgfds_num) {
2893 g_free(s->write_msgfds);
2894 s->write_msgfds = 0;
2895 s->write_msgfds_num = 0;
2898 return ret;
2899 } else {
2900 /* XXX: indicate an error ? */
2901 return len;
2905 static int tcp_chr_read_poll(void *opaque)
2907 CharDriverState *chr = opaque;
2908 TCPCharDriver *s = chr->opaque;
2909 if (!s->connected)
2910 return 0;
2911 s->max_size = qemu_chr_be_can_write(chr);
2912 return s->max_size;
2915 #define IAC 255
2916 #define IAC_BREAK 243
2917 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2918 TCPCharDriver *s,
2919 uint8_t *buf, int *size)
2921 /* Handle any telnet client's basic IAC options to satisfy char by
2922 * char mode with no echo. All IAC options will be removed from
2923 * the buf and the do_telnetopt variable will be used to track the
2924 * state of the width of the IAC information.
2926 * IAC commands come in sets of 3 bytes with the exception of the
2927 * "IAC BREAK" command and the double IAC.
2930 int i;
2931 int j = 0;
2933 for (i = 0; i < *size; i++) {
2934 if (s->do_telnetopt > 1) {
2935 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2936 /* Double IAC means send an IAC */
2937 if (j != i)
2938 buf[j] = buf[i];
2939 j++;
2940 s->do_telnetopt = 1;
2941 } else {
2942 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2943 /* Handle IAC break commands by sending a serial break */
2944 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2945 s->do_telnetopt++;
2947 s->do_telnetopt++;
2949 if (s->do_telnetopt >= 4) {
2950 s->do_telnetopt = 1;
2952 } else {
2953 if ((unsigned char)buf[i] == IAC) {
2954 s->do_telnetopt = 2;
2955 } else {
2956 if (j != i)
2957 buf[j] = buf[i];
2958 j++;
2962 *size = j;
2965 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2967 TCPCharDriver *s = chr->opaque;
2968 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2970 assert(num <= TCP_MAX_FDS);
2972 if (to_copy) {
2973 int i;
2975 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2977 /* Close unused fds */
2978 for (i = to_copy; i < s->read_msgfds_num; i++) {
2979 close(s->read_msgfds[i]);
2982 g_free(s->read_msgfds);
2983 s->read_msgfds = 0;
2984 s->read_msgfds_num = 0;
2987 return to_copy;
2990 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2992 TCPCharDriver *s = chr->opaque;
2994 /* clear old pending fd array */
2995 g_free(s->write_msgfds);
2996 s->write_msgfds = NULL;
2997 s->write_msgfds_num = 0;
2999 if (!s->connected ||
3000 !qio_channel_has_feature(s->ioc,
3001 QIO_CHANNEL_FEATURE_FD_PASS)) {
3002 return -1;
3005 if (num) {
3006 s->write_msgfds = g_new(int, num);
3007 memcpy(s->write_msgfds, fds, num * sizeof(int));
3010 s->write_msgfds_num = num;
3012 return 0;
3015 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
3017 TCPCharDriver *s = chr->opaque;
3018 struct iovec iov = { .iov_base = buf, .iov_len = len };
3019 int ret;
3020 size_t i;
3021 int *msgfds = NULL;
3022 size_t msgfds_num = 0;
3024 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
3025 ret = qio_channel_readv_full(s->ioc, &iov, 1,
3026 &msgfds, &msgfds_num,
3027 NULL);
3028 } else {
3029 ret = qio_channel_readv_full(s->ioc, &iov, 1,
3030 NULL, NULL,
3031 NULL);
3034 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3035 errno = EAGAIN;
3036 ret = -1;
3037 } else if (ret == -1) {
3038 errno = EIO;
3041 if (msgfds_num) {
3042 /* close and clean read_msgfds */
3043 for (i = 0; i < s->read_msgfds_num; i++) {
3044 close(s->read_msgfds[i]);
3047 if (s->read_msgfds_num) {
3048 g_free(s->read_msgfds);
3051 s->read_msgfds = msgfds;
3052 s->read_msgfds_num = msgfds_num;
3055 for (i = 0; i < s->read_msgfds_num; i++) {
3056 int fd = s->read_msgfds[i];
3057 if (fd < 0) {
3058 continue;
3061 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
3062 qemu_set_block(fd);
3064 #ifndef MSG_CMSG_CLOEXEC
3065 qemu_set_cloexec(fd);
3066 #endif
3069 return ret;
3072 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
3074 TCPCharDriver *s = chr->opaque;
3075 return qio_channel_create_watch(s->ioc, cond);
3078 static void tcp_chr_free_connection(CharDriverState *chr)
3080 TCPCharDriver *s = chr->opaque;
3081 int i;
3083 if (!s->connected) {
3084 return;
3087 if (s->read_msgfds_num) {
3088 for (i = 0; i < s->read_msgfds_num; i++) {
3089 close(s->read_msgfds[i]);
3091 g_free(s->read_msgfds);
3092 s->read_msgfds = NULL;
3093 s->read_msgfds_num = 0;
3096 tcp_set_msgfds(chr, NULL, 0);
3097 remove_fd_in_watch(chr);
3098 object_unref(OBJECT(s->sioc));
3099 s->sioc = NULL;
3100 object_unref(OBJECT(s->ioc));
3101 s->ioc = NULL;
3102 g_free(chr->filename);
3103 chr->filename = NULL;
3104 s->connected = 0;
3107 static void tcp_chr_disconnect(CharDriverState *chr)
3109 TCPCharDriver *s = chr->opaque;
3111 if (!s->connected) {
3112 return;
3115 tcp_chr_free_connection(chr);
3117 if (s->listen_ioc) {
3118 s->listen_tag = qio_channel_add_watch(
3119 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
3121 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
3122 s->is_listen, s->is_telnet);
3123 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3124 if (s->reconnect_time) {
3125 qemu_chr_socket_restart_timer(chr);
3129 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
3131 CharDriverState *chr = opaque;
3132 TCPCharDriver *s = chr->opaque;
3133 uint8_t buf[READ_BUF_LEN];
3134 int len, size;
3136 if (!s->connected || s->max_size <= 0) {
3137 return TRUE;
3139 len = sizeof(buf);
3140 if (len > s->max_size)
3141 len = s->max_size;
3142 size = tcp_chr_recv(chr, (void *)buf, len);
3143 if (size == 0 || size == -1) {
3144 /* connection closed */
3145 tcp_chr_disconnect(chr);
3146 } else if (size > 0) {
3147 if (s->do_telnetopt)
3148 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3149 if (size > 0)
3150 qemu_chr_be_write(chr, buf, size);
3153 return TRUE;
3156 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
3158 TCPCharDriver *s = chr->opaque;
3159 int size;
3161 if (!s->connected) {
3162 return 0;
3165 size = tcp_chr_recv(chr, (void *) buf, len);
3166 if (size == 0) {
3167 /* connection closed */
3168 tcp_chr_disconnect(chr);
3171 return size;
3174 static void tcp_chr_connect(void *opaque)
3176 CharDriverState *chr = opaque;
3177 TCPCharDriver *s = chr->opaque;
3179 g_free(chr->filename);
3180 chr->filename = sockaddr_to_str(
3181 &s->sioc->localAddr, s->sioc->localAddrLen,
3182 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
3183 s->is_listen, s->is_telnet);
3185 s->connected = 1;
3186 if (s->ioc) {
3187 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
3188 tcp_chr_read_poll,
3189 tcp_chr_read,
3190 chr, NULL);
3192 qemu_chr_be_generic_open(chr);
3195 static void tcp_chr_update_read_handler(CharDriverState *chr,
3196 GMainContext *context)
3198 TCPCharDriver *s = chr->opaque;
3200 if (!s->connected) {
3201 return;
3204 remove_fd_in_watch(chr);
3205 if (s->ioc) {
3206 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
3207 tcp_chr_read_poll,
3208 tcp_chr_read, chr,
3209 context);
3213 typedef struct {
3214 CharDriverState *chr;
3215 char buf[12];
3216 size_t buflen;
3217 } TCPCharDriverTelnetInit;
3219 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
3220 GIOCondition cond G_GNUC_UNUSED,
3221 gpointer user_data)
3223 TCPCharDriverTelnetInit *init = user_data;
3224 ssize_t ret;
3226 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
3227 if (ret < 0) {
3228 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3229 ret = 0;
3230 } else {
3231 tcp_chr_disconnect(init->chr);
3232 return FALSE;
3235 init->buflen -= ret;
3237 if (init->buflen == 0) {
3238 tcp_chr_connect(init->chr);
3239 return FALSE;
3242 memmove(init->buf, init->buf + ret, init->buflen);
3244 return TRUE;
3247 static void tcp_chr_telnet_init(CharDriverState *chr)
3249 TCPCharDriver *s = chr->opaque;
3250 TCPCharDriverTelnetInit *init =
3251 g_new0(TCPCharDriverTelnetInit, 1);
3252 size_t n = 0;
3254 init->chr = chr;
3255 init->buflen = 12;
3257 #define IACSET(x, a, b, c) \
3258 do { \
3259 x[n++] = a; \
3260 x[n++] = b; \
3261 x[n++] = c; \
3262 } while (0)
3264 /* Prep the telnet negotion to put telnet in binary,
3265 * no echo, single char mode */
3266 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3267 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3268 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3269 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3271 #undef IACSET
3273 qio_channel_add_watch(
3274 s->ioc, G_IO_OUT,
3275 tcp_chr_telnet_init_io,
3276 init, NULL);
3280 static void tcp_chr_tls_handshake(QIOTask *task,
3281 gpointer user_data)
3283 CharDriverState *chr = user_data;
3284 TCPCharDriver *s = chr->opaque;
3286 if (qio_task_propagate_error(task, NULL)) {
3287 tcp_chr_disconnect(chr);
3288 } else {
3289 if (s->do_telnetopt) {
3290 tcp_chr_telnet_init(chr);
3291 } else {
3292 tcp_chr_connect(chr);
3298 static void tcp_chr_tls_init(CharDriverState *chr)
3300 TCPCharDriver *s = chr->opaque;
3301 QIOChannelTLS *tioc;
3302 Error *err = NULL;
3303 gchar *name;
3305 if (s->is_listen) {
3306 tioc = qio_channel_tls_new_server(
3307 s->ioc, s->tls_creds,
3308 NULL, /* XXX Use an ACL */
3309 &err);
3310 } else {
3311 tioc = qio_channel_tls_new_client(
3312 s->ioc, s->tls_creds,
3313 s->addr->u.inet.data->host,
3314 &err);
3316 if (tioc == NULL) {
3317 error_free(err);
3318 tcp_chr_disconnect(chr);
3319 return;
3321 name = g_strdup_printf("chardev-tls-%s-%s",
3322 s->is_listen ? "server" : "client",
3323 chr->label);
3324 qio_channel_set_name(QIO_CHANNEL(tioc), name);
3325 g_free(name);
3326 object_unref(OBJECT(s->ioc));
3327 s->ioc = QIO_CHANNEL(tioc);
3329 qio_channel_tls_handshake(tioc,
3330 tcp_chr_tls_handshake,
3331 chr,
3332 NULL);
3336 static void tcp_chr_set_client_ioc_name(CharDriverState *chr,
3337 QIOChannelSocket *sioc)
3339 TCPCharDriver *s = chr->opaque;
3340 char *name;
3341 name = g_strdup_printf("chardev-tcp-%s-%s",
3342 s->is_listen ? "server" : "client",
3343 chr->label);
3344 qio_channel_set_name(QIO_CHANNEL(sioc), name);
3345 g_free(name);
3349 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3351 TCPCharDriver *s = chr->opaque;
3352 if (s->ioc != NULL) {
3353 return -1;
3356 s->ioc = QIO_CHANNEL(sioc);
3357 object_ref(OBJECT(sioc));
3358 s->sioc = sioc;
3359 object_ref(OBJECT(sioc));
3361 qio_channel_set_blocking(s->ioc, false, NULL);
3363 if (s->do_nodelay) {
3364 qio_channel_set_delay(s->ioc, false);
3366 if (s->listen_tag) {
3367 g_source_remove(s->listen_tag);
3368 s->listen_tag = 0;
3371 if (s->tls_creds) {
3372 tcp_chr_tls_init(chr);
3373 } else {
3374 if (s->do_telnetopt) {
3375 tcp_chr_telnet_init(chr);
3376 } else {
3377 tcp_chr_connect(chr);
3381 return 0;
3385 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3387 int ret;
3388 QIOChannelSocket *sioc;
3390 sioc = qio_channel_socket_new_fd(fd, NULL);
3391 if (!sioc) {
3392 return -1;
3394 tcp_chr_set_client_ioc_name(chr, sioc);
3395 ret = tcp_chr_new_client(chr, sioc);
3396 object_unref(OBJECT(sioc));
3397 return ret;
3400 static gboolean tcp_chr_accept(QIOChannel *channel,
3401 GIOCondition cond,
3402 void *opaque)
3404 CharDriverState *chr = opaque;
3405 QIOChannelSocket *sioc;
3407 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3408 NULL);
3409 if (!sioc) {
3410 return TRUE;
3413 tcp_chr_new_client(chr, sioc);
3415 object_unref(OBJECT(sioc));
3417 return TRUE;
3420 static int tcp_chr_wait_connected(CharDriverState *chr, Error **errp)
3422 TCPCharDriver *s = chr->opaque;
3423 QIOChannelSocket *sioc;
3425 /* It can't wait on s->connected, since it is set asynchronously
3426 * in TLS and telnet cases, only wait for an accepted socket */
3427 while (!s->ioc) {
3428 if (s->is_listen) {
3429 fprintf(stderr, "QEMU waiting for connection on: %s\n",
3430 chr->filename);
3431 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), true, NULL);
3432 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
3433 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
3434 } else {
3435 sioc = qio_channel_socket_new();
3436 tcp_chr_set_client_ioc_name(chr, sioc);
3437 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3438 object_unref(OBJECT(sioc));
3439 return -1;
3441 tcp_chr_new_client(chr, sioc);
3442 object_unref(OBJECT(sioc));
3446 return 0;
3449 static int qemu_chr_wait_connected(CharDriverState *chr, Error **errp)
3451 if (chr->chr_wait_connected) {
3452 return chr->chr_wait_connected(chr, errp);
3455 return 0;
3458 int qemu_chr_fe_wait_connected(CharBackend *be, Error **errp)
3460 if (!be->chr) {
3461 error_setg(errp, "missing associated backend");
3462 return -1;
3465 return qemu_chr_wait_connected(be->chr, errp);
3468 static void tcp_chr_free(CharDriverState *chr)
3470 TCPCharDriver *s = chr->opaque;
3472 tcp_chr_free_connection(chr);
3474 if (s->reconnect_timer) {
3475 g_source_remove(s->reconnect_timer);
3476 s->reconnect_timer = 0;
3478 qapi_free_SocketAddress(s->addr);
3479 if (s->listen_tag) {
3480 g_source_remove(s->listen_tag);
3481 s->listen_tag = 0;
3483 if (s->listen_ioc) {
3484 object_unref(OBJECT(s->listen_ioc));
3486 if (s->tls_creds) {
3487 object_unref(OBJECT(s->tls_creds));
3489 g_free(s);
3490 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3494 static void qemu_chr_socket_connected(QIOTask *task, void *opaque)
3496 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(qio_task_get_source(task));
3497 CharDriverState *chr = opaque;
3498 TCPCharDriver *s = chr->opaque;
3499 Error *err = NULL;
3501 if (qio_task_propagate_error(task, &err)) {
3502 check_report_connect_error(chr, err);
3503 error_free(err);
3504 goto cleanup;
3507 s->connect_err_reported = false;
3508 tcp_chr_new_client(chr, sioc);
3510 cleanup:
3511 object_unref(OBJECT(sioc));
3515 /*********************************************************/
3516 /* Ring buffer chardev */
3518 typedef struct {
3519 size_t size;
3520 size_t prod;
3521 size_t cons;
3522 uint8_t *cbuf;
3523 } RingBufCharDriver;
3525 static size_t ringbuf_count(const CharDriverState *chr)
3527 const RingBufCharDriver *d = chr->opaque;
3529 return d->prod - d->cons;
3532 /* Called with chr_write_lock held. */
3533 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3535 RingBufCharDriver *d = chr->opaque;
3536 int i;
3538 if (!buf || (len < 0)) {
3539 return -1;
3542 for (i = 0; i < len; i++ ) {
3543 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3544 if (d->prod - d->cons > d->size) {
3545 d->cons = d->prod - d->size;
3549 return len;
3552 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3554 RingBufCharDriver *d = chr->opaque;
3555 int i;
3557 qemu_mutex_lock(&chr->chr_write_lock);
3558 for (i = 0; i < len && d->cons != d->prod; i++) {
3559 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3561 qemu_mutex_unlock(&chr->chr_write_lock);
3563 return i;
3566 static void ringbuf_chr_free(struct CharDriverState *chr)
3568 RingBufCharDriver *d = chr->opaque;
3570 g_free(d->cbuf);
3571 g_free(d);
3572 chr->opaque = NULL;
3575 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3576 ChardevBackend *backend,
3577 ChardevReturn *ret,
3578 bool *be_opened,
3579 Error **errp)
3581 ChardevRingbuf *opts = backend->u.ringbuf.data;
3582 ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
3583 CharDriverState *chr;
3584 RingBufCharDriver *d;
3586 chr = qemu_chr_alloc(common, errp);
3587 if (!chr) {
3588 return NULL;
3590 d = g_malloc(sizeof(*d));
3592 d->size = opts->has_size ? opts->size : 65536;
3594 /* The size must be power of 2 */
3595 if (d->size & (d->size - 1)) {
3596 error_setg(errp, "size of ringbuf chardev must be power of two");
3597 goto fail;
3600 d->prod = 0;
3601 d->cons = 0;
3602 d->cbuf = g_malloc0(d->size);
3604 chr->opaque = d;
3605 chr->chr_write = ringbuf_chr_write;
3606 chr->chr_free = ringbuf_chr_free;
3608 return chr;
3610 fail:
3611 g_free(d);
3612 qemu_chr_free_common(chr);
3613 return NULL;
3616 bool chr_is_ringbuf(const CharDriverState *chr)
3618 return chr->chr_write == ringbuf_chr_write;
3621 void qmp_ringbuf_write(const char *device, const char *data,
3622 bool has_format, enum DataFormat format,
3623 Error **errp)
3625 CharDriverState *chr;
3626 const uint8_t *write_data;
3627 int ret;
3628 gsize write_count;
3630 chr = qemu_chr_find(device);
3631 if (!chr) {
3632 error_setg(errp, "Device '%s' not found", device);
3633 return;
3636 if (!chr_is_ringbuf(chr)) {
3637 error_setg(errp,"%s is not a ringbuf device", device);
3638 return;
3641 if (has_format && (format == DATA_FORMAT_BASE64)) {
3642 write_data = qbase64_decode(data, -1,
3643 &write_count,
3644 errp);
3645 if (!write_data) {
3646 return;
3648 } else {
3649 write_data = (uint8_t *)data;
3650 write_count = strlen(data);
3653 ret = ringbuf_chr_write(chr, write_data, write_count);
3655 if (write_data != (uint8_t *)data) {
3656 g_free((void *)write_data);
3659 if (ret < 0) {
3660 error_setg(errp, "Failed to write to device %s", device);
3661 return;
3665 char *qmp_ringbuf_read(const char *device, int64_t size,
3666 bool has_format, enum DataFormat format,
3667 Error **errp)
3669 CharDriverState *chr;
3670 uint8_t *read_data;
3671 size_t count;
3672 char *data;
3674 chr = qemu_chr_find(device);
3675 if (!chr) {
3676 error_setg(errp, "Device '%s' not found", device);
3677 return NULL;
3680 if (!chr_is_ringbuf(chr)) {
3681 error_setg(errp,"%s is not a ringbuf device", device);
3682 return NULL;
3685 if (size <= 0) {
3686 error_setg(errp, "size must be greater than zero");
3687 return NULL;
3690 count = ringbuf_count(chr);
3691 size = size > count ? count : size;
3692 read_data = g_malloc(size + 1);
3694 ringbuf_chr_read(chr, read_data, size);
3696 if (has_format && (format == DATA_FORMAT_BASE64)) {
3697 data = g_base64_encode(read_data, size);
3698 g_free(read_data);
3699 } else {
3701 * FIXME should read only complete, valid UTF-8 characters up
3702 * to @size bytes. Invalid sequences should be replaced by a
3703 * suitable replacement character. Except when (and only
3704 * when) ring buffer lost characters since last read, initial
3705 * continuation characters should be dropped.
3707 read_data[size] = 0;
3708 data = (char *)read_data;
3711 return data;
3714 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3716 char host[65], port[33], width[8], height[8];
3717 int pos;
3718 const char *p;
3719 QemuOpts *opts;
3720 Error *local_err = NULL;
3722 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3723 if (local_err) {
3724 error_report_err(local_err);
3725 return NULL;
3728 if (strstart(filename, "mon:", &p)) {
3729 filename = p;
3730 qemu_opt_set(opts, "mux", "on", &error_abort);
3731 if (strcmp(filename, "stdio") == 0) {
3732 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3733 * but pass it to the guest. Handle this only for compat syntax,
3734 * for -chardev syntax we have special option for this.
3735 * This is what -nographic did, redirecting+muxing serial+monitor
3736 * to stdio causing Ctrl+C to be passed to guest. */
3737 qemu_opt_set(opts, "signal", "off", &error_abort);
3741 if (strcmp(filename, "null") == 0 ||
3742 strcmp(filename, "pty") == 0 ||
3743 strcmp(filename, "msmouse") == 0 ||
3744 strcmp(filename, "braille") == 0 ||
3745 strcmp(filename, "testdev") == 0 ||
3746 strcmp(filename, "stdio") == 0) {
3747 qemu_opt_set(opts, "backend", filename, &error_abort);
3748 return opts;
3750 if (strstart(filename, "vc", &p)) {
3751 qemu_opt_set(opts, "backend", "vc", &error_abort);
3752 if (*p == ':') {
3753 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3754 /* pixels */
3755 qemu_opt_set(opts, "width", width, &error_abort);
3756 qemu_opt_set(opts, "height", height, &error_abort);
3757 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3758 /* chars */
3759 qemu_opt_set(opts, "cols", width, &error_abort);
3760 qemu_opt_set(opts, "rows", height, &error_abort);
3761 } else {
3762 goto fail;
3765 return opts;
3767 if (strcmp(filename, "con:") == 0) {
3768 qemu_opt_set(opts, "backend", "console", &error_abort);
3769 return opts;
3771 if (strstart(filename, "COM", NULL)) {
3772 qemu_opt_set(opts, "backend", "serial", &error_abort);
3773 qemu_opt_set(opts, "path", filename, &error_abort);
3774 return opts;
3776 if (strstart(filename, "file:", &p)) {
3777 qemu_opt_set(opts, "backend", "file", &error_abort);
3778 qemu_opt_set(opts, "path", p, &error_abort);
3779 return opts;
3781 if (strstart(filename, "pipe:", &p)) {
3782 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3783 qemu_opt_set(opts, "path", p, &error_abort);
3784 return opts;
3786 if (strstart(filename, "tcp:", &p) ||
3787 strstart(filename, "telnet:", &p)) {
3788 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3789 host[0] = 0;
3790 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3791 goto fail;
3793 qemu_opt_set(opts, "backend", "socket", &error_abort);
3794 qemu_opt_set(opts, "host", host, &error_abort);
3795 qemu_opt_set(opts, "port", port, &error_abort);
3796 if (p[pos] == ',') {
3797 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3798 if (local_err) {
3799 error_report_err(local_err);
3800 goto fail;
3803 if (strstart(filename, "telnet:", &p))
3804 qemu_opt_set(opts, "telnet", "on", &error_abort);
3805 return opts;
3807 if (strstart(filename, "udp:", &p)) {
3808 qemu_opt_set(opts, "backend", "udp", &error_abort);
3809 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3810 host[0] = 0;
3811 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3812 goto fail;
3815 qemu_opt_set(opts, "host", host, &error_abort);
3816 qemu_opt_set(opts, "port", port, &error_abort);
3817 if (p[pos] == '@') {
3818 p += pos + 1;
3819 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3820 host[0] = 0;
3821 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3822 goto fail;
3825 qemu_opt_set(opts, "localaddr", host, &error_abort);
3826 qemu_opt_set(opts, "localport", port, &error_abort);
3828 return opts;
3830 if (strstart(filename, "unix:", &p)) {
3831 qemu_opt_set(opts, "backend", "socket", &error_abort);
3832 qemu_opts_do_parse(opts, p, "path", &local_err);
3833 if (local_err) {
3834 error_report_err(local_err);
3835 goto fail;
3837 return opts;
3839 if (strstart(filename, "/dev/parport", NULL) ||
3840 strstart(filename, "/dev/ppi", NULL)) {
3841 qemu_opt_set(opts, "backend", "parport", &error_abort);
3842 qemu_opt_set(opts, "path", filename, &error_abort);
3843 return opts;
3845 if (strstart(filename, "/dev/", NULL)) {
3846 qemu_opt_set(opts, "backend", "tty", &error_abort);
3847 qemu_opt_set(opts, "path", filename, &error_abort);
3848 return opts;
3851 fail:
3852 qemu_opts_del(opts);
3853 return NULL;
3856 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3858 const char *logfile = qemu_opt_get(opts, "logfile");
3860 backend->has_logfile = logfile != NULL;
3861 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3863 backend->has_logappend = true;
3864 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3868 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3869 Error **errp)
3871 const char *path = qemu_opt_get(opts, "path");
3872 ChardevFile *file;
3874 if (path == NULL) {
3875 error_setg(errp, "chardev: file: no filename given");
3876 return;
3878 file = backend->u.file.data = g_new0(ChardevFile, 1);
3879 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3880 file->out = g_strdup(path);
3882 file->has_append = true;
3883 file->append = qemu_opt_get_bool(opts, "append", false);
3886 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3887 Error **errp)
3889 ChardevStdio *stdio;
3891 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3892 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3893 stdio->has_signal = true;
3894 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3897 #ifdef HAVE_CHARDEV_SERIAL
3898 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3899 Error **errp)
3901 const char *device = qemu_opt_get(opts, "path");
3902 ChardevHostdev *serial;
3904 if (device == NULL) {
3905 error_setg(errp, "chardev: serial/tty: no device path given");
3906 return;
3908 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3909 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3910 serial->device = g_strdup(device);
3912 #endif
3914 #ifdef HAVE_CHARDEV_PARPORT
3915 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3916 Error **errp)
3918 const char *device = qemu_opt_get(opts, "path");
3919 ChardevHostdev *parallel;
3921 if (device == NULL) {
3922 error_setg(errp, "chardev: parallel: no device path given");
3923 return;
3925 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3926 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3927 parallel->device = g_strdup(device);
3929 #endif
3931 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3932 Error **errp)
3934 const char *device = qemu_opt_get(opts, "path");
3935 ChardevHostdev *dev;
3937 if (device == NULL) {
3938 error_setg(errp, "chardev: pipe: no device path given");
3939 return;
3941 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3942 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3943 dev->device = g_strdup(device);
3946 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3947 Error **errp)
3949 int val;
3950 ChardevRingbuf *ringbuf;
3952 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3953 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3955 val = qemu_opt_get_size(opts, "size", 0);
3956 if (val != 0) {
3957 ringbuf->has_size = true;
3958 ringbuf->size = val;
3962 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3963 Error **errp)
3965 const char *chardev = qemu_opt_get(opts, "chardev");
3966 ChardevMux *mux;
3968 if (chardev == NULL) {
3969 error_setg(errp, "chardev: mux: no chardev given");
3970 return;
3972 mux = backend->u.mux.data = g_new0(ChardevMux, 1);
3973 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
3974 mux->chardev = g_strdup(chardev);
3977 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3978 Error **errp)
3980 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3981 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3982 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3983 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3984 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3985 const char *path = qemu_opt_get(opts, "path");
3986 const char *host = qemu_opt_get(opts, "host");
3987 const char *port = qemu_opt_get(opts, "port");
3988 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3989 SocketAddress *addr;
3990 ChardevSocket *sock;
3992 if (!path) {
3993 if (!host) {
3994 error_setg(errp, "chardev: socket: no host given");
3995 return;
3997 if (!port) {
3998 error_setg(errp, "chardev: socket: no port given");
3999 return;
4001 } else {
4002 if (tls_creds) {
4003 error_setg(errp, "TLS can only be used over TCP socket");
4004 return;
4008 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
4009 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
4011 sock->has_nodelay = true;
4012 sock->nodelay = do_nodelay;
4013 sock->has_server = true;
4014 sock->server = is_listen;
4015 sock->has_telnet = true;
4016 sock->telnet = is_telnet;
4017 sock->has_wait = true;
4018 sock->wait = is_waitconnect;
4019 sock->has_reconnect = true;
4020 sock->reconnect = reconnect;
4021 sock->tls_creds = g_strdup(tls_creds);
4023 addr = g_new0(SocketAddress, 1);
4024 if (path) {
4025 UnixSocketAddress *q_unix;
4026 addr->type = SOCKET_ADDRESS_KIND_UNIX;
4027 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
4028 q_unix->path = g_strdup(path);
4029 } else {
4030 addr->type = SOCKET_ADDRESS_KIND_INET;
4031 addr->u.inet.data = g_new(InetSocketAddress, 1);
4032 *addr->u.inet.data = (InetSocketAddress) {
4033 .host = g_strdup(host),
4034 .port = g_strdup(port),
4035 .has_to = qemu_opt_get(opts, "to"),
4036 .to = qemu_opt_get_number(opts, "to", 0),
4037 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
4038 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
4039 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
4040 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
4043 sock->addr = addr;
4046 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
4047 Error **errp)
4049 const char *host = qemu_opt_get(opts, "host");
4050 const char *port = qemu_opt_get(opts, "port");
4051 const char *localaddr = qemu_opt_get(opts, "localaddr");
4052 const char *localport = qemu_opt_get(opts, "localport");
4053 bool has_local = false;
4054 SocketAddress *addr;
4055 ChardevUdp *udp;
4057 if (host == NULL || strlen(host) == 0) {
4058 host = "localhost";
4060 if (port == NULL || strlen(port) == 0) {
4061 error_setg(errp, "chardev: udp: remote port not specified");
4062 return;
4064 if (localport == NULL || strlen(localport) == 0) {
4065 localport = "0";
4066 } else {
4067 has_local = true;
4069 if (localaddr == NULL || strlen(localaddr) == 0) {
4070 localaddr = "";
4071 } else {
4072 has_local = true;
4075 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
4076 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
4078 addr = g_new0(SocketAddress, 1);
4079 addr->type = SOCKET_ADDRESS_KIND_INET;
4080 addr->u.inet.data = g_new(InetSocketAddress, 1);
4081 *addr->u.inet.data = (InetSocketAddress) {
4082 .host = g_strdup(host),
4083 .port = g_strdup(port),
4084 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
4085 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
4086 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
4087 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
4089 udp->remote = addr;
4091 if (has_local) {
4092 udp->has_local = true;
4093 addr = g_new0(SocketAddress, 1);
4094 addr->type = SOCKET_ADDRESS_KIND_INET;
4095 addr->u.inet.data = g_new(InetSocketAddress, 1);
4096 *addr->u.inet.data = (InetSocketAddress) {
4097 .host = g_strdup(localaddr),
4098 .port = g_strdup(localport),
4100 udp->local = addr;
4104 typedef struct CharDriver {
4105 const char *name;
4106 ChardevBackendKind kind;
4107 CharDriverParse *parse;
4108 CharDriverCreate *create;
4109 } CharDriver;
4111 static GSList *backends;
4113 void register_char_driver(const char *name, ChardevBackendKind kind,
4114 CharDriverParse *parse, CharDriverCreate *create)
4116 CharDriver *s;
4118 s = g_malloc0(sizeof(*s));
4119 s->name = g_strdup(name);
4120 s->kind = kind;
4121 s->parse = parse;
4122 s->create = create;
4124 backends = g_slist_append(backends, s);
4127 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
4128 Error **errp)
4130 Error *local_err = NULL;
4131 CharDriver *cd;
4132 CharDriverState *chr;
4133 GSList *i;
4134 ChardevReturn *ret = NULL;
4135 ChardevBackend *backend;
4136 const char *id = qemu_opts_id(opts);
4137 char *bid = NULL;
4139 if (qemu_opt_get(opts, "backend") == NULL) {
4140 error_setg(errp, "chardev: \"%s\" missing backend",
4141 qemu_opts_id(opts));
4142 goto err;
4145 if (is_help_option(qemu_opt_get(opts, "backend"))) {
4146 fprintf(stderr, "Available chardev backend types:\n");
4147 for (i = backends; i; i = i->next) {
4148 cd = i->data;
4149 fprintf(stderr, "%s\n", cd->name);
4151 exit(!is_help_option(qemu_opt_get(opts, "backend")));
4154 if (id == NULL) {
4155 error_setg(errp, "chardev: no id specified");
4156 goto err;
4159 for (i = backends; i; i = i->next) {
4160 cd = i->data;
4162 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
4163 break;
4166 if (i == NULL) {
4167 error_setg(errp, "chardev: backend \"%s\" not found",
4168 qemu_opt_get(opts, "backend"));
4169 goto err;
4172 backend = g_new0(ChardevBackend, 1);
4174 if (qemu_opt_get_bool(opts, "mux", 0)) {
4175 bid = g_strdup_printf("%s-base", id);
4178 chr = NULL;
4179 backend->type = cd->kind;
4180 if (cd->parse) {
4181 cd->parse(opts, backend, &local_err);
4182 if (local_err) {
4183 error_propagate(errp, local_err);
4184 goto qapi_out;
4186 } else {
4187 ChardevCommon *cc = g_new0(ChardevCommon, 1);
4188 qemu_chr_parse_common(opts, cc);
4189 backend->u.null.data = cc; /* Any ChardevCommon member would work */
4192 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
4193 if (!ret) {
4194 goto qapi_out;
4197 if (bid) {
4198 qapi_free_ChardevBackend(backend);
4199 qapi_free_ChardevReturn(ret);
4200 backend = g_new0(ChardevBackend, 1);
4201 backend->u.mux.data = g_new0(ChardevMux, 1);
4202 backend->type = CHARDEV_BACKEND_KIND_MUX;
4203 backend->u.mux.data->chardev = g_strdup(bid);
4204 ret = qmp_chardev_add(id, backend, errp);
4205 if (!ret) {
4206 chr = qemu_chr_find(bid);
4207 qemu_chr_delete(chr);
4208 chr = NULL;
4209 goto qapi_out;
4213 chr = qemu_chr_find(id);
4215 qapi_out:
4216 qapi_free_ChardevBackend(backend);
4217 qapi_free_ChardevReturn(ret);
4218 g_free(bid);
4219 return chr;
4221 err:
4222 return NULL;
4225 CharDriverState *qemu_chr_new_noreplay(const char *label, const char *filename)
4227 const char *p;
4228 CharDriverState *chr;
4229 QemuOpts *opts;
4230 Error *err = NULL;
4232 if (strstart(filename, "chardev:", &p)) {
4233 return qemu_chr_find(p);
4236 opts = qemu_chr_parse_compat(label, filename);
4237 if (!opts)
4238 return NULL;
4240 chr = qemu_chr_new_from_opts(opts, &err);
4241 if (err) {
4242 error_report_err(err);
4244 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
4245 monitor_init(chr, MONITOR_USE_READLINE);
4247 qemu_opts_del(opts);
4248 return chr;
4251 CharDriverState *qemu_chr_new(const char *label, const char *filename)
4253 CharDriverState *chr;
4254 chr = qemu_chr_new_noreplay(label, filename);
4255 if (chr) {
4256 chr->replay = replay_mode != REPLAY_MODE_NONE;
4257 if (chr->replay && chr->chr_ioctl) {
4258 fprintf(stderr,
4259 "Replay: ioctl is not supported for serial devices yet\n");
4261 replay_register_char_driver(chr);
4263 return chr;
4266 void qemu_chr_fe_set_echo(CharBackend *be, bool echo)
4268 CharDriverState *chr = be->chr;
4270 if (chr && chr->chr_set_echo) {
4271 chr->chr_set_echo(chr, echo);
4275 void qemu_chr_fe_set_open(CharBackend *be, int fe_open)
4277 CharDriverState *chr = be->chr;
4279 if (!chr) {
4280 return;
4283 if (be->fe_open == fe_open) {
4284 return;
4286 be->fe_open = fe_open;
4287 if (chr->chr_set_fe_open) {
4288 chr->chr_set_fe_open(chr, fe_open);
4292 guint qemu_chr_fe_add_watch(CharBackend *be, GIOCondition cond,
4293 GIOFunc func, void *user_data)
4295 CharDriverState *s = be->chr;
4296 GSource *src;
4297 guint tag;
4299 if (!s || s->chr_add_watch == NULL) {
4300 return 0;
4303 src = s->chr_add_watch(s, cond);
4304 if (!src) {
4305 return 0;
4308 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
4309 tag = g_source_attach(src, NULL);
4310 g_source_unref(src);
4312 return tag;
4315 void qemu_chr_fe_disconnect(CharBackend *be)
4317 CharDriverState *chr = be->chr;
4319 if (chr && chr->chr_disconnect) {
4320 chr->chr_disconnect(chr);
4324 static void qemu_chr_free_common(CharDriverState *chr)
4326 if (chr->be) {
4327 chr->be->chr = NULL;
4329 g_free(chr->filename);
4330 g_free(chr->label);
4331 if (chr->logfd != -1) {
4332 close(chr->logfd);
4334 qemu_mutex_destroy(&chr->chr_write_lock);
4335 g_free(chr);
4338 void qemu_chr_free(CharDriverState *chr)
4340 if (chr->chr_free) {
4341 chr->chr_free(chr);
4343 qemu_chr_free_common(chr);
4346 void qemu_chr_delete(CharDriverState *chr)
4348 QTAILQ_REMOVE(&chardevs, chr, next);
4349 qemu_chr_free(chr);
4352 ChardevInfoList *qmp_query_chardev(Error **errp)
4354 ChardevInfoList *chr_list = NULL;
4355 CharDriverState *chr;
4357 QTAILQ_FOREACH(chr, &chardevs, next) {
4358 ChardevInfoList *info = g_malloc0(sizeof(*info));
4359 info->value = g_malloc0(sizeof(*info->value));
4360 info->value->label = g_strdup(chr->label);
4361 info->value->filename = g_strdup(chr->filename);
4362 info->value->frontend_open = chr->be && chr->be->fe_open;
4364 info->next = chr_list;
4365 chr_list = info;
4368 return chr_list;
4371 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4373 ChardevBackendInfoList *backend_list = NULL;
4374 CharDriver *c = NULL;
4375 GSList *i = NULL;
4377 for (i = backends; i; i = i->next) {
4378 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4379 c = i->data;
4380 info->value = g_malloc0(sizeof(*info->value));
4381 info->value->name = g_strdup(c->name);
4383 info->next = backend_list;
4384 backend_list = info;
4387 return backend_list;
4390 CharDriverState *qemu_chr_find(const char *name)
4392 CharDriverState *chr;
4394 QTAILQ_FOREACH(chr, &chardevs, next) {
4395 if (strcmp(chr->label, name) != 0)
4396 continue;
4397 return chr;
4399 return NULL;
4402 QemuOptsList qemu_chardev_opts = {
4403 .name = "chardev",
4404 .implied_opt_name = "backend",
4405 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4406 .desc = {
4408 .name = "backend",
4409 .type = QEMU_OPT_STRING,
4411 .name = "path",
4412 .type = QEMU_OPT_STRING,
4414 .name = "host",
4415 .type = QEMU_OPT_STRING,
4417 .name = "port",
4418 .type = QEMU_OPT_STRING,
4420 .name = "localaddr",
4421 .type = QEMU_OPT_STRING,
4423 .name = "localport",
4424 .type = QEMU_OPT_STRING,
4426 .name = "to",
4427 .type = QEMU_OPT_NUMBER,
4429 .name = "ipv4",
4430 .type = QEMU_OPT_BOOL,
4432 .name = "ipv6",
4433 .type = QEMU_OPT_BOOL,
4435 .name = "wait",
4436 .type = QEMU_OPT_BOOL,
4438 .name = "server",
4439 .type = QEMU_OPT_BOOL,
4441 .name = "delay",
4442 .type = QEMU_OPT_BOOL,
4444 .name = "reconnect",
4445 .type = QEMU_OPT_NUMBER,
4447 .name = "telnet",
4448 .type = QEMU_OPT_BOOL,
4450 .name = "tls-creds",
4451 .type = QEMU_OPT_STRING,
4453 .name = "width",
4454 .type = QEMU_OPT_NUMBER,
4456 .name = "height",
4457 .type = QEMU_OPT_NUMBER,
4459 .name = "cols",
4460 .type = QEMU_OPT_NUMBER,
4462 .name = "rows",
4463 .type = QEMU_OPT_NUMBER,
4465 .name = "mux",
4466 .type = QEMU_OPT_BOOL,
4468 .name = "signal",
4469 .type = QEMU_OPT_BOOL,
4471 .name = "name",
4472 .type = QEMU_OPT_STRING,
4474 .name = "debug",
4475 .type = QEMU_OPT_NUMBER,
4477 .name = "size",
4478 .type = QEMU_OPT_SIZE,
4480 .name = "chardev",
4481 .type = QEMU_OPT_STRING,
4483 .name = "append",
4484 .type = QEMU_OPT_BOOL,
4486 .name = "logfile",
4487 .type = QEMU_OPT_STRING,
4489 .name = "logappend",
4490 .type = QEMU_OPT_BOOL,
4492 { /* end of list */ }
4496 #ifdef _WIN32
4498 static CharDriverState *qmp_chardev_open_file(const char *id,
4499 ChardevBackend *backend,
4500 ChardevReturn *ret,
4501 bool *be_opened,
4502 Error **errp)
4504 ChardevFile *file = backend->u.file.data;
4505 ChardevCommon *common = qapi_ChardevFile_base(file);
4506 HANDLE out;
4507 DWORD accessmode;
4508 DWORD flags;
4510 if (file->has_in) {
4511 error_setg(errp, "input file not supported");
4512 return NULL;
4515 if (file->has_append && file->append) {
4516 /* Append to file if it already exists. */
4517 accessmode = FILE_GENERIC_WRITE & ~FILE_WRITE_DATA;
4518 flags = OPEN_ALWAYS;
4519 } else {
4520 /* Truncate file if it already exists. */
4521 accessmode = GENERIC_WRITE;
4522 flags = CREATE_ALWAYS;
4525 out = CreateFile(file->out, accessmode, FILE_SHARE_READ, NULL, flags,
4526 FILE_ATTRIBUTE_NORMAL, NULL);
4527 if (out == INVALID_HANDLE_VALUE) {
4528 error_setg(errp, "open %s failed", file->out);
4529 return NULL;
4531 return qemu_chr_open_win_file(out, common, errp);
4534 static CharDriverState *qmp_chardev_open_serial(const char *id,
4535 ChardevBackend *backend,
4536 ChardevReturn *ret,
4537 bool *be_opened,
4538 Error **errp)
4540 ChardevHostdev *serial = backend->u.serial.data;
4541 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4542 return qemu_chr_open_win_path(serial->device, common, errp);
4545 #else /* WIN32 */
4547 static int qmp_chardev_open_file_source(char *src, int flags,
4548 Error **errp)
4550 int fd = -1;
4552 TFR(fd = qemu_open(src, flags, 0666));
4553 if (fd == -1) {
4554 error_setg_file_open(errp, errno, src);
4556 return fd;
4559 static CharDriverState *qmp_chardev_open_file(const char *id,
4560 ChardevBackend *backend,
4561 ChardevReturn *ret,
4562 bool *be_opened,
4563 Error **errp)
4565 ChardevFile *file = backend->u.file.data;
4566 ChardevCommon *common = qapi_ChardevFile_base(file);
4567 int flags, in = -1, out;
4569 flags = O_WRONLY | O_CREAT | O_BINARY;
4570 if (file->has_append && file->append) {
4571 flags |= O_APPEND;
4572 } else {
4573 flags |= O_TRUNC;
4576 out = qmp_chardev_open_file_source(file->out, flags, errp);
4577 if (out < 0) {
4578 return NULL;
4581 if (file->has_in) {
4582 flags = O_RDONLY;
4583 in = qmp_chardev_open_file_source(file->in, flags, errp);
4584 if (in < 0) {
4585 qemu_close(out);
4586 return NULL;
4590 return qemu_chr_open_fd(in, out, common, errp);
4593 #ifdef HAVE_CHARDEV_SERIAL
4594 static CharDriverState *qmp_chardev_open_serial(const char *id,
4595 ChardevBackend *backend,
4596 ChardevReturn *ret,
4597 bool *be_opened,
4598 Error **errp)
4600 ChardevHostdev *serial = backend->u.serial.data;
4601 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4602 int fd;
4604 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4605 if (fd < 0) {
4606 return NULL;
4608 qemu_set_nonblock(fd);
4609 return qemu_chr_open_tty_fd(fd, common, be_opened, errp);
4611 #endif
4613 #ifdef HAVE_CHARDEV_PARPORT
4614 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4615 ChardevBackend *backend,
4616 ChardevReturn *ret,
4617 bool *be_opened,
4618 Error **errp)
4620 ChardevHostdev *parallel = backend->u.parallel.data;
4621 ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
4622 int fd;
4624 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4625 if (fd < 0) {
4626 return NULL;
4628 return qemu_chr_open_pp_fd(fd, common, be_opened, errp);
4630 #endif
4632 #endif /* WIN32 */
4634 static gboolean socket_reconnect_timeout(gpointer opaque)
4636 CharDriverState *chr = opaque;
4637 TCPCharDriver *s = chr->opaque;
4638 QIOChannelSocket *sioc;
4640 s->reconnect_timer = 0;
4642 if (chr->be_open) {
4643 return false;
4646 sioc = qio_channel_socket_new();
4647 tcp_chr_set_client_ioc_name(chr, sioc);
4648 qio_channel_socket_connect_async(sioc, s->addr,
4649 qemu_chr_socket_connected,
4650 chr, NULL);
4652 return false;
4655 static CharDriverState *qmp_chardev_open_socket(const char *id,
4656 ChardevBackend *backend,
4657 ChardevReturn *ret,
4658 bool *be_opened,
4659 Error **errp)
4661 CharDriverState *chr;
4662 TCPCharDriver *s;
4663 ChardevSocket *sock = backend->u.socket.data;
4664 SocketAddress *addr = sock->addr;
4665 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4666 bool is_listen = sock->has_server ? sock->server : true;
4667 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4668 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4669 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4670 ChardevCommon *common = qapi_ChardevSocket_base(sock);
4671 QIOChannelSocket *sioc = NULL;
4673 chr = qemu_chr_alloc(common, errp);
4674 if (!chr) {
4675 return NULL;
4677 s = g_new0(TCPCharDriver, 1);
4679 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4680 s->is_listen = is_listen;
4681 s->is_telnet = is_telnet;
4682 s->do_nodelay = do_nodelay;
4683 if (sock->tls_creds) {
4684 Object *creds;
4685 creds = object_resolve_path_component(
4686 object_get_objects_root(), sock->tls_creds);
4687 if (!creds) {
4688 error_setg(errp, "No TLS credentials with id '%s'",
4689 sock->tls_creds);
4690 goto error;
4692 s->tls_creds = (QCryptoTLSCreds *)
4693 object_dynamic_cast(creds,
4694 TYPE_QCRYPTO_TLS_CREDS);
4695 if (!s->tls_creds) {
4696 error_setg(errp, "Object with id '%s' is not TLS credentials",
4697 sock->tls_creds);
4698 goto error;
4700 object_ref(OBJECT(s->tls_creds));
4701 if (is_listen) {
4702 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4703 error_setg(errp, "%s",
4704 "Expected TLS credentials for server endpoint");
4705 goto error;
4707 } else {
4708 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4709 error_setg(errp, "%s",
4710 "Expected TLS credentials for client endpoint");
4711 goto error;
4716 s->addr = QAPI_CLONE(SocketAddress, sock->addr);
4718 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_RECONNECTABLE);
4719 if (s->is_unix) {
4720 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_FD_PASS);
4723 chr->opaque = s;
4724 chr->chr_wait_connected = tcp_chr_wait_connected;
4725 chr->chr_write = tcp_chr_write;
4726 chr->chr_sync_read = tcp_chr_sync_read;
4727 chr->chr_free = tcp_chr_free;
4728 chr->chr_disconnect = tcp_chr_disconnect;
4729 chr->get_msgfds = tcp_get_msgfds;
4730 chr->set_msgfds = tcp_set_msgfds;
4731 chr->chr_add_client = tcp_chr_add_client;
4732 chr->chr_add_watch = tcp_chr_add_watch;
4733 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4734 /* be isn't opened until we get a connection */
4735 *be_opened = false;
4737 chr->filename = SocketAddress_to_str("disconnected:",
4738 addr, is_listen, is_telnet);
4740 if (is_listen) {
4741 if (is_telnet) {
4742 s->do_telnetopt = 1;
4744 } else if (reconnect > 0) {
4745 s->reconnect_time = reconnect;
4748 if (s->reconnect_time) {
4749 sioc = qio_channel_socket_new();
4750 tcp_chr_set_client_ioc_name(chr, sioc);
4751 qio_channel_socket_connect_async(sioc, s->addr,
4752 qemu_chr_socket_connected,
4753 chr, NULL);
4754 } else {
4755 if (s->is_listen) {
4756 char *name;
4757 sioc = qio_channel_socket_new();
4759 name = g_strdup_printf("chardev-tcp-listener-%s", chr->label);
4760 qio_channel_set_name(QIO_CHANNEL(sioc), name);
4761 g_free(name);
4763 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4764 goto error;
4766 s->listen_ioc = sioc;
4767 if (is_waitconnect &&
4768 qemu_chr_wait_connected(chr, errp) < 0) {
4769 goto error;
4771 if (!s->ioc) {
4772 s->listen_tag = qio_channel_add_watch(
4773 QIO_CHANNEL(s->listen_ioc), G_IO_IN,
4774 tcp_chr_accept, chr, NULL);
4776 } else if (qemu_chr_wait_connected(chr, errp) < 0) {
4777 goto error;
4781 return chr;
4783 error:
4784 if (sioc) {
4785 object_unref(OBJECT(sioc));
4787 if (s->tls_creds) {
4788 object_unref(OBJECT(s->tls_creds));
4790 g_free(s);
4791 qemu_chr_free_common(chr);
4792 return NULL;
4795 static CharDriverState *qmp_chardev_open_udp(const char *id,
4796 ChardevBackend *backend,
4797 ChardevReturn *ret,
4798 bool *be_opened,
4799 Error **errp)
4801 ChardevUdp *udp = backend->u.udp.data;
4802 ChardevCommon *common = qapi_ChardevUdp_base(udp);
4803 QIOChannelSocket *sioc = qio_channel_socket_new();
4804 char *name;
4805 CharDriverState *chr;
4807 if (qio_channel_socket_dgram_sync(sioc,
4808 udp->local, udp->remote,
4809 errp) < 0) {
4810 object_unref(OBJECT(sioc));
4811 return NULL;
4813 chr = qemu_chr_open_udp(sioc, common, be_opened, errp);
4815 name = g_strdup_printf("chardev-udp-%s", chr->label);
4816 qio_channel_set_name(QIO_CHANNEL(sioc), name);
4817 g_free(name);
4819 return chr;
4823 bool qemu_chr_has_feature(CharDriverState *chr,
4824 CharDriverFeature feature)
4826 return test_bit(feature, chr->features);
4829 void qemu_chr_set_feature(CharDriverState *chr,
4830 CharDriverFeature feature)
4832 return set_bit(feature, chr->features);
4835 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4836 Error **errp)
4838 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4839 CharDriverState *chr = NULL;
4840 Error *local_err = NULL;
4841 GSList *i;
4842 CharDriver *cd;
4843 bool be_opened = true;
4845 chr = qemu_chr_find(id);
4846 if (chr) {
4847 error_setg(errp, "Chardev '%s' already exists", id);
4848 goto out_error;
4851 for (i = backends; i; i = i->next) {
4852 cd = i->data;
4854 if (cd->kind == backend->type) {
4855 chr = cd->create(id, backend, ret, &be_opened, &local_err);
4856 if (local_err) {
4857 error_propagate(errp, local_err);
4858 goto out_error;
4860 break;
4864 if (chr == NULL) {
4865 assert(!i);
4866 error_setg(errp, "chardev backend not available");
4867 goto out_error;
4870 chr->label = g_strdup(id);
4871 if (!chr->filename) {
4872 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4874 if (be_opened) {
4875 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4877 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4878 return ret;
4880 out_error:
4881 g_free(ret);
4882 return NULL;
4885 void qmp_chardev_remove(const char *id, Error **errp)
4887 CharDriverState *chr;
4889 chr = qemu_chr_find(id);
4890 if (chr == NULL) {
4891 error_setg(errp, "Chardev '%s' not found", id);
4892 return;
4894 if (qemu_chr_is_busy(chr)) {
4895 error_setg(errp, "Chardev '%s' is busy", id);
4896 return;
4898 if (chr->replay) {
4899 error_setg(errp,
4900 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4901 return;
4903 qemu_chr_delete(chr);
4906 void qemu_chr_cleanup(void)
4908 CharDriverState *chr, *tmp;
4910 QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
4911 qemu_chr_delete(chr);
4915 static void register_types(void)
4917 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4918 qemu_chr_open_null);
4919 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4920 qemu_chr_parse_socket, qmp_chardev_open_socket);
4921 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4922 qmp_chardev_open_udp);
4923 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4924 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4925 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4926 qemu_chr_parse_file_out, qmp_chardev_open_file);
4927 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4928 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4929 #if defined HAVE_CHARDEV_SERIAL
4930 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4931 qemu_chr_parse_serial, qmp_chardev_open_serial);
4932 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4933 qemu_chr_parse_serial, qmp_chardev_open_serial);
4934 #endif
4935 #ifdef HAVE_CHARDEV_PARPORT
4936 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4937 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4938 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4939 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4940 #endif
4941 #ifdef HAVE_CHARDEV_PTY
4942 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4943 qemu_chr_open_pty);
4944 #endif
4945 #ifdef _WIN32
4946 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4947 qemu_chr_open_win_con);
4948 #endif
4949 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4950 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4951 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4952 qemu_chr_open_mux);
4953 /* Bug-compatibility: */
4954 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4955 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4956 /* this must be done after machine init, since we register FEs with muxes
4957 * as part of realize functions like serial_isa_realizefn when -nographic
4958 * is specified
4960 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4963 type_init(register_types);