qemu-iotests: Test block-stream operations in parallel
[qemu.git] / qemu-char.c
blob1e5a0e8cb96135a63cf8102e22e2e4b6147f3024
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(MuxDriver *d, 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(d, (d->focus + 1) % d->mux_cnt);
670 break;
671 case 't':
672 d->timestamps = !d->timestamps;
673 d->timestamps_start = -1;
674 d->linestart = 0;
675 break;
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 void mux_chr_event(void *opaque, int event)
740 CharDriverState *chr = opaque;
741 MuxDriver *d = chr->opaque;
742 int i;
744 /* Send the event to all registered listeners */
745 for (i = 0; i < d->mux_cnt; i++)
746 mux_chr_send_event(d, i, event);
749 static bool muxes_realized;
752 * Called after processing of default and command-line-specified
753 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
754 * to a mux chardev. This is done here to ensure that
755 * output/prompts/banners are only displayed for the FE that has
756 * focus when initial command-line processing/machine init is
757 * completed.
759 * After this point, any new FE attached to any new or existing
760 * mux will receive CHR_EVENT_OPENED notifications for the BE
761 * immediately.
763 static void muxes_realize_done(Notifier *notifier, void *unused)
765 CharDriverState *chr;
767 QTAILQ_FOREACH(chr, &chardevs, next) {
768 if (chr->is_mux) {
769 MuxDriver *d = chr->opaque;
770 int i;
772 /* send OPENED to all already-attached FEs */
773 for (i = 0; i < d->mux_cnt; i++) {
774 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
776 /* mark mux as OPENED so any new FEs will immediately receive
777 * OPENED event
779 qemu_chr_be_generic_open(chr);
782 muxes_realized = true;
785 static Notifier muxes_realize_notify = {
786 .notify = muxes_realize_done,
789 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
791 MuxDriver *d = s->opaque;
792 CharDriverState *chr = qemu_chr_fe_get_driver(&d->chr);
794 return chr->chr_add_watch(chr, cond);
797 static void mux_chr_free(struct CharDriverState *chr)
799 MuxDriver *d = chr->opaque;
800 int i;
802 for (i = 0; i < d->mux_cnt; i++) {
803 CharBackend *be = d->backends[i];
804 if (be) {
805 be->chr = NULL;
808 qemu_chr_fe_deinit(&d->chr);
809 g_free(d);
812 static void mux_chr_set_handlers(CharDriverState *chr, GMainContext *context)
814 MuxDriver *d = chr->opaque;
816 /* Fix up the real driver with mux routines */
817 qemu_chr_fe_set_handlers(&d->chr,
818 mux_chr_can_read,
819 mux_chr_read,
820 mux_chr_event,
821 chr,
822 context, true);
825 static void mux_set_focus(MuxDriver *d, int focus)
827 assert(focus >= 0);
828 assert(focus < d->mux_cnt);
830 if (d->focus != -1) {
831 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
834 d->focus = focus;
835 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
838 static CharDriverState *qemu_chr_open_mux(const char *id,
839 ChardevBackend *backend,
840 ChardevReturn *ret,
841 bool *be_opened,
842 Error **errp)
844 ChardevMux *mux = backend->u.mux.data;
845 CharDriverState *chr, *drv;
846 MuxDriver *d;
847 ChardevCommon *common = qapi_ChardevMux_base(mux);
849 drv = qemu_chr_find(mux->chardev);
850 if (drv == NULL) {
851 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
852 return NULL;
855 chr = qemu_chr_alloc(common, errp);
856 if (!chr) {
857 return NULL;
859 d = g_new0(MuxDriver, 1);
861 chr->opaque = d;
862 d->focus = -1;
863 chr->chr_free = mux_chr_free;
864 chr->chr_write = mux_chr_write;
865 chr->chr_accept_input = mux_chr_accept_input;
866 /* Frontend guest-open / -close notification is not support with muxes */
867 chr->chr_set_fe_open = NULL;
868 if (drv->chr_add_watch) {
869 chr->chr_add_watch = mux_chr_add_watch;
871 /* only default to opened state if we've realized the initial
872 * set of muxes
874 *be_opened = muxes_realized;
875 chr->is_mux = 1;
876 if (!qemu_chr_fe_init(&d->chr, drv, errp)) {
877 qemu_chr_free(chr);
878 return NULL;
881 return chr;
884 CharDriverState *qemu_chr_fe_get_driver(CharBackend *be)
886 return be->chr;
889 bool qemu_chr_fe_init(CharBackend *b, CharDriverState *s, Error **errp)
891 int tag = 0;
893 if (s->is_mux) {
894 MuxDriver *d = s->opaque;
896 if (d->mux_cnt >= MAX_MUX) {
897 goto unavailable;
900 d->backends[d->mux_cnt] = b;
901 tag = d->mux_cnt++;
902 } else if (s->be) {
903 goto unavailable;
904 } else {
905 s->be = b;
908 b->fe_open = false;
909 b->tag = tag;
910 b->chr = s;
911 return true;
913 unavailable:
914 error_setg(errp, QERR_DEVICE_IN_USE, s->label);
915 return false;
918 static bool qemu_chr_is_busy(CharDriverState *s)
920 if (s->is_mux) {
921 MuxDriver *d = s->opaque;
922 return d->mux_cnt >= 0;
923 } else {
924 return s->be != NULL;
928 void qemu_chr_fe_deinit(CharBackend *b)
930 assert(b);
932 if (b->chr) {
933 qemu_chr_fe_set_handlers(b, NULL, NULL, NULL, NULL, NULL, true);
934 b->chr->be = NULL;
935 if (b->chr->is_mux) {
936 MuxDriver *d = b->chr->opaque;
937 d->backends[b->tag] = NULL;
939 b->chr = NULL;
943 void qemu_chr_fe_set_handlers(CharBackend *b,
944 IOCanReadHandler *fd_can_read,
945 IOReadHandler *fd_read,
946 IOEventHandler *fd_event,
947 void *opaque,
948 GMainContext *context,
949 bool set_open)
951 CharDriverState *s;
952 int fe_open;
954 s = b->chr;
955 if (!s) {
956 return;
959 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
960 fe_open = 0;
961 remove_fd_in_watch(s);
962 } else {
963 fe_open = 1;
965 b->chr_can_read = fd_can_read;
966 b->chr_read = fd_read;
967 b->chr_event = fd_event;
968 b->opaque = opaque;
969 if (s->chr_update_read_handler) {
970 s->chr_update_read_handler(s, context);
973 if (set_open) {
974 qemu_chr_fe_set_open(b, fe_open);
977 if (fe_open) {
978 qemu_chr_fe_take_focus(b);
979 /* We're connecting to an already opened device, so let's make sure we
980 also get the open event */
981 if (s->be_open) {
982 qemu_chr_be_generic_open(s);
986 if (s->is_mux) {
987 mux_chr_set_handlers(s, context);
991 void qemu_chr_fe_take_focus(CharBackend *b)
993 if (!b->chr) {
994 return;
997 if (b->chr->is_mux) {
998 mux_set_focus(b->chr->opaque, b->tag);
1002 typedef struct IOWatchPoll
1004 GSource parent;
1006 QIOChannel *ioc;
1007 GSource *src;
1009 IOCanReadHandler *fd_can_read;
1010 GSourceFunc fd_read;
1011 void *opaque;
1012 GMainContext *context;
1013 } IOWatchPoll;
1015 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
1017 return container_of(source, IOWatchPoll, parent);
1020 static gboolean io_watch_poll_prepare(GSource *source,
1021 gint *timeout_)
1023 IOWatchPoll *iwp = io_watch_poll_from_source(source);
1024 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
1025 bool was_active = iwp->src != NULL;
1026 if (was_active == now_active) {
1027 return FALSE;
1030 if (now_active) {
1031 iwp->src = qio_channel_create_watch(
1032 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
1033 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
1034 g_source_attach(iwp->src, iwp->context);
1035 } else {
1036 g_source_destroy(iwp->src);
1037 g_source_unref(iwp->src);
1038 iwp->src = NULL;
1040 return FALSE;
1043 static gboolean io_watch_poll_check(GSource *source)
1045 return FALSE;
1048 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
1049 gpointer user_data)
1051 abort();
1054 static void io_watch_poll_finalize(GSource *source)
1056 /* Due to a glib bug, removing the last reference to a source
1057 * inside a finalize callback causes recursive locking (and a
1058 * deadlock). This is not a problem inside other callbacks,
1059 * including dispatch callbacks, so we call io_remove_watch_poll
1060 * to remove this source. At this point, iwp->src must
1061 * be NULL, or we would leak it.
1063 * This would be solved much more elegantly by child sources,
1064 * but we support older glib versions that do not have them.
1066 IOWatchPoll *iwp = io_watch_poll_from_source(source);
1067 assert(iwp->src == NULL);
1070 static GSourceFuncs io_watch_poll_funcs = {
1071 .prepare = io_watch_poll_prepare,
1072 .check = io_watch_poll_check,
1073 .dispatch = io_watch_poll_dispatch,
1074 .finalize = io_watch_poll_finalize,
1077 /* Can only be used for read */
1078 static guint io_add_watch_poll(CharDriverState *chr,
1079 QIOChannel *ioc,
1080 IOCanReadHandler *fd_can_read,
1081 QIOChannelFunc fd_read,
1082 gpointer user_data,
1083 GMainContext *context)
1085 IOWatchPoll *iwp;
1086 int tag;
1087 char *name;
1089 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs,
1090 sizeof(IOWatchPoll));
1091 iwp->fd_can_read = fd_can_read;
1092 iwp->opaque = user_data;
1093 iwp->ioc = ioc;
1094 iwp->fd_read = (GSourceFunc) fd_read;
1095 iwp->src = NULL;
1096 iwp->context = context;
1098 name = g_strdup_printf("chardev-iowatch-%s", chr->label);
1099 g_source_set_name((GSource *)iwp, name);
1100 g_free(name);
1102 tag = g_source_attach(&iwp->parent, context);
1103 g_source_unref(&iwp->parent);
1104 return tag;
1107 static void io_remove_watch_poll(guint tag)
1109 GSource *source;
1110 IOWatchPoll *iwp;
1112 g_return_if_fail (tag > 0);
1114 source = g_main_context_find_source_by_id(NULL, tag);
1115 g_return_if_fail (source != NULL);
1117 iwp = io_watch_poll_from_source(source);
1118 if (iwp->src) {
1119 g_source_destroy(iwp->src);
1120 g_source_unref(iwp->src);
1121 iwp->src = NULL;
1123 g_source_destroy(&iwp->parent);
1126 static void remove_fd_in_watch(CharDriverState *chr)
1128 if (chr->fd_in_tag) {
1129 io_remove_watch_poll(chr->fd_in_tag);
1130 chr->fd_in_tag = 0;
1135 static int io_channel_send_full(QIOChannel *ioc,
1136 const void *buf, size_t len,
1137 int *fds, size_t nfds)
1139 size_t offset = 0;
1141 while (offset < len) {
1142 ssize_t ret = 0;
1143 struct iovec iov = { .iov_base = (char *)buf + offset,
1144 .iov_len = len - offset };
1146 ret = qio_channel_writev_full(
1147 ioc, &iov, 1,
1148 fds, nfds, NULL);
1149 if (ret == QIO_CHANNEL_ERR_BLOCK) {
1150 if (offset) {
1151 return offset;
1154 errno = EAGAIN;
1155 return -1;
1156 } else if (ret < 0) {
1157 errno = EINVAL;
1158 return -1;
1161 offset += ret;
1164 return offset;
1168 #ifndef _WIN32
1169 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
1171 return io_channel_send_full(ioc, buf, len, NULL, 0);
1175 typedef struct FDCharDriver {
1176 CharDriverState *chr;
1177 QIOChannel *ioc_in, *ioc_out;
1178 int max_size;
1179 } FDCharDriver;
1181 /* Called with chr_write_lock held. */
1182 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1184 FDCharDriver *s = chr->opaque;
1186 return io_channel_send(s->ioc_out, buf, len);
1189 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1191 CharDriverState *chr = opaque;
1192 FDCharDriver *s = chr->opaque;
1193 int len;
1194 uint8_t buf[READ_BUF_LEN];
1195 ssize_t ret;
1197 len = sizeof(buf);
1198 if (len > s->max_size) {
1199 len = s->max_size;
1201 if (len == 0) {
1202 return TRUE;
1205 ret = qio_channel_read(
1206 chan, (gchar *)buf, len, NULL);
1207 if (ret == 0) {
1208 remove_fd_in_watch(chr);
1209 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1210 return FALSE;
1212 if (ret > 0) {
1213 qemu_chr_be_write(chr, buf, ret);
1216 return TRUE;
1219 static int fd_chr_read_poll(void *opaque)
1221 CharDriverState *chr = opaque;
1222 FDCharDriver *s = chr->opaque;
1224 s->max_size = qemu_chr_be_can_write(chr);
1225 return s->max_size;
1228 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1230 FDCharDriver *s = chr->opaque;
1231 return qio_channel_create_watch(s->ioc_out, cond);
1234 static void fd_chr_update_read_handler(CharDriverState *chr,
1235 GMainContext *context)
1237 FDCharDriver *s = chr->opaque;
1239 remove_fd_in_watch(chr);
1240 if (s->ioc_in) {
1241 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc_in,
1242 fd_chr_read_poll,
1243 fd_chr_read, chr,
1244 context);
1248 static void fd_chr_free(struct CharDriverState *chr)
1250 FDCharDriver *s = chr->opaque;
1252 remove_fd_in_watch(chr);
1253 if (s->ioc_in) {
1254 object_unref(OBJECT(s->ioc_in));
1256 if (s->ioc_out) {
1257 object_unref(OBJECT(s->ioc_out));
1260 g_free(s);
1261 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1264 /* open a character device to a unix fd */
1265 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1266 ChardevCommon *backend, Error **errp)
1268 CharDriverState *chr;
1269 FDCharDriver *s;
1270 char *name;
1272 chr = qemu_chr_alloc(backend, errp);
1273 if (!chr) {
1274 return NULL;
1276 s = g_new0(FDCharDriver, 1);
1277 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1278 name = g_strdup_printf("chardev-file-in-%s", chr->label);
1279 qio_channel_set_name(QIO_CHANNEL(s->ioc_in), name);
1280 g_free(name);
1281 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1282 name = g_strdup_printf("chardev-file-out-%s", chr->label);
1283 qio_channel_set_name(QIO_CHANNEL(s->ioc_out), name);
1284 g_free(name);
1285 qemu_set_nonblock(fd_out);
1286 s->chr = chr;
1287 chr->opaque = s;
1288 chr->chr_add_watch = fd_chr_add_watch;
1289 chr->chr_write = fd_chr_write;
1290 chr->chr_update_read_handler = fd_chr_update_read_handler;
1291 chr->chr_free = fd_chr_free;
1293 return chr;
1296 static CharDriverState *qemu_chr_open_pipe(const char *id,
1297 ChardevBackend *backend,
1298 ChardevReturn *ret,
1299 bool *be_opened,
1300 Error **errp)
1302 ChardevHostdev *opts = backend->u.pipe.data;
1303 int fd_in, fd_out;
1304 char *filename_in;
1305 char *filename_out;
1306 const char *filename = opts->device;
1307 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1310 filename_in = g_strdup_printf("%s.in", filename);
1311 filename_out = g_strdup_printf("%s.out", filename);
1312 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1313 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1314 g_free(filename_in);
1315 g_free(filename_out);
1316 if (fd_in < 0 || fd_out < 0) {
1317 if (fd_in >= 0)
1318 close(fd_in);
1319 if (fd_out >= 0)
1320 close(fd_out);
1321 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1322 if (fd_in < 0) {
1323 error_setg_file_open(errp, errno, filename);
1324 return NULL;
1327 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1330 /* init terminal so that we can grab keys */
1331 static struct termios oldtty;
1332 static int old_fd0_flags;
1333 static bool stdio_in_use;
1334 static bool stdio_allow_signal;
1335 static bool stdio_echo_state;
1337 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1339 static void term_exit(void)
1341 tcsetattr (0, TCSANOW, &oldtty);
1342 fcntl(0, F_SETFL, old_fd0_flags);
1345 static void term_stdio_handler(int sig)
1347 /* restore echo after resume from suspend. */
1348 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1351 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1353 struct termios tty;
1355 stdio_echo_state = echo;
1356 tty = oldtty;
1357 if (!echo) {
1358 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1359 |INLCR|IGNCR|ICRNL|IXON);
1360 tty.c_oflag |= OPOST;
1361 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1362 tty.c_cflag &= ~(CSIZE|PARENB);
1363 tty.c_cflag |= CS8;
1364 tty.c_cc[VMIN] = 1;
1365 tty.c_cc[VTIME] = 0;
1367 if (!stdio_allow_signal)
1368 tty.c_lflag &= ~ISIG;
1370 tcsetattr (0, TCSANOW, &tty);
1373 static void qemu_chr_free_stdio(struct CharDriverState *chr)
1375 term_exit();
1376 fd_chr_free(chr);
1379 static CharDriverState *qemu_chr_open_stdio(const char *id,
1380 ChardevBackend *backend,
1381 ChardevReturn *ret,
1382 bool *be_opened,
1383 Error **errp)
1385 ChardevStdio *opts = backend->u.stdio.data;
1386 CharDriverState *chr;
1387 struct sigaction act;
1388 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1390 if (is_daemonized()) {
1391 error_setg(errp, "cannot use stdio with -daemonize");
1392 return NULL;
1395 if (stdio_in_use) {
1396 error_setg(errp, "cannot use stdio by multiple character devices");
1397 return NULL;
1400 stdio_in_use = true;
1401 old_fd0_flags = fcntl(0, F_GETFL);
1402 tcgetattr(0, &oldtty);
1403 qemu_set_nonblock(0);
1404 atexit(term_exit);
1406 memset(&act, 0, sizeof(act));
1407 act.sa_handler = term_stdio_handler;
1408 sigaction(SIGCONT, &act, NULL);
1410 chr = qemu_chr_open_fd(0, 1, common, errp);
1411 if (!chr) {
1412 return NULL;
1414 chr->chr_free = qemu_chr_free_stdio;
1415 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1416 if (opts->has_signal) {
1417 stdio_allow_signal = opts->signal;
1419 qemu_chr_set_echo_stdio(chr, false);
1421 return chr;
1424 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1425 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1426 || defined(__GLIBC__)
1428 #define HAVE_CHARDEV_SERIAL 1
1429 #define HAVE_CHARDEV_PTY 1
1431 typedef struct {
1432 QIOChannel *ioc;
1433 int read_bytes;
1435 /* Protected by the CharDriverState chr_write_lock. */
1436 int connected;
1437 guint timer_tag;
1438 guint open_tag;
1439 } PtyCharDriver;
1441 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1442 static void pty_chr_state(CharDriverState *chr, int connected);
1444 static gboolean pty_chr_timer(gpointer opaque)
1446 struct CharDriverState *chr = opaque;
1447 PtyCharDriver *s = chr->opaque;
1449 qemu_mutex_lock(&chr->chr_write_lock);
1450 s->timer_tag = 0;
1451 s->open_tag = 0;
1452 if (!s->connected) {
1453 /* Next poll ... */
1454 pty_chr_update_read_handler_locked(chr);
1456 qemu_mutex_unlock(&chr->chr_write_lock);
1457 return FALSE;
1460 /* Called with chr_write_lock held. */
1461 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1463 PtyCharDriver *s = chr->opaque;
1464 char *name;
1466 if (s->timer_tag) {
1467 g_source_remove(s->timer_tag);
1468 s->timer_tag = 0;
1471 if (ms == 1000) {
1472 name = g_strdup_printf("pty-timer-secs-%s", chr->label);
1473 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1474 } else {
1475 name = g_strdup_printf("pty-timer-ms-%s", chr->label);
1476 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1478 g_source_set_name_by_id(s->timer_tag, name);
1479 g_free(name);
1482 /* Called with chr_write_lock held. */
1483 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1485 PtyCharDriver *s = chr->opaque;
1486 GPollFD pfd;
1487 int rc;
1488 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1490 pfd.fd = fioc->fd;
1491 pfd.events = G_IO_OUT;
1492 pfd.revents = 0;
1493 do {
1494 rc = g_poll(&pfd, 1, 0);
1495 } while (rc == -1 && errno == EINTR);
1496 assert(rc >= 0);
1498 if (pfd.revents & G_IO_HUP) {
1499 pty_chr_state(chr, 0);
1500 } else {
1501 pty_chr_state(chr, 1);
1505 static void pty_chr_update_read_handler(CharDriverState *chr,
1506 GMainContext *context)
1508 qemu_mutex_lock(&chr->chr_write_lock);
1509 pty_chr_update_read_handler_locked(chr);
1510 qemu_mutex_unlock(&chr->chr_write_lock);
1513 /* Called with chr_write_lock held. */
1514 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1516 PtyCharDriver *s = chr->opaque;
1518 if (!s->connected) {
1519 /* guest sends data, check for (re-)connect */
1520 pty_chr_update_read_handler_locked(chr);
1521 if (!s->connected) {
1522 return 0;
1525 return io_channel_send(s->ioc, buf, len);
1528 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1530 PtyCharDriver *s = chr->opaque;
1531 if (!s->connected) {
1532 return NULL;
1534 return qio_channel_create_watch(s->ioc, cond);
1537 static int pty_chr_read_poll(void *opaque)
1539 CharDriverState *chr = opaque;
1540 PtyCharDriver *s = chr->opaque;
1542 s->read_bytes = qemu_chr_be_can_write(chr);
1543 return s->read_bytes;
1546 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1548 CharDriverState *chr = opaque;
1549 PtyCharDriver *s = chr->opaque;
1550 gsize len;
1551 uint8_t buf[READ_BUF_LEN];
1552 ssize_t ret;
1554 len = sizeof(buf);
1555 if (len > s->read_bytes)
1556 len = s->read_bytes;
1557 if (len == 0) {
1558 return TRUE;
1560 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1561 if (ret <= 0) {
1562 pty_chr_state(chr, 0);
1563 return FALSE;
1564 } else {
1565 pty_chr_state(chr, 1);
1566 qemu_chr_be_write(chr, buf, ret);
1568 return TRUE;
1571 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1573 CharDriverState *chr = opaque;
1574 PtyCharDriver *s = chr->opaque;
1576 s->open_tag = 0;
1577 qemu_chr_be_generic_open(chr);
1578 return FALSE;
1581 /* Called with chr_write_lock held. */
1582 static void pty_chr_state(CharDriverState *chr, int connected)
1584 PtyCharDriver *s = chr->opaque;
1586 if (!connected) {
1587 if (s->open_tag) {
1588 g_source_remove(s->open_tag);
1589 s->open_tag = 0;
1591 remove_fd_in_watch(chr);
1592 s->connected = 0;
1593 /* (re-)connect poll interval for idle guests: once per second.
1594 * We check more frequently in case the guests sends data to
1595 * the virtual device linked to our pty. */
1596 pty_chr_rearm_timer(chr, 1000);
1597 } else {
1598 if (s->timer_tag) {
1599 g_source_remove(s->timer_tag);
1600 s->timer_tag = 0;
1602 if (!s->connected) {
1603 g_assert(s->open_tag == 0);
1604 s->connected = 1;
1605 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1607 if (!chr->fd_in_tag) {
1608 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
1609 pty_chr_read_poll,
1610 pty_chr_read,
1611 chr, NULL);
1616 static void pty_chr_free(struct CharDriverState *chr)
1618 PtyCharDriver *s = chr->opaque;
1620 qemu_mutex_lock(&chr->chr_write_lock);
1621 pty_chr_state(chr, 0);
1622 object_unref(OBJECT(s->ioc));
1623 if (s->timer_tag) {
1624 g_source_remove(s->timer_tag);
1625 s->timer_tag = 0;
1627 qemu_mutex_unlock(&chr->chr_write_lock);
1628 g_free(s);
1629 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1632 static CharDriverState *qemu_chr_open_pty(const char *id,
1633 ChardevBackend *backend,
1634 ChardevReturn *ret,
1635 bool *be_opened,
1636 Error **errp)
1638 CharDriverState *chr;
1639 PtyCharDriver *s;
1640 int master_fd, slave_fd;
1641 char pty_name[PATH_MAX];
1642 ChardevCommon *common = backend->u.pty.data;
1643 char *name;
1645 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1646 if (master_fd < 0) {
1647 error_setg_errno(errp, errno, "Failed to create PTY");
1648 return NULL;
1651 close(slave_fd);
1652 qemu_set_nonblock(master_fd);
1654 chr = qemu_chr_alloc(common, errp);
1655 if (!chr) {
1656 close(master_fd);
1657 return NULL;
1660 chr->filename = g_strdup_printf("pty:%s", pty_name);
1661 ret->pty = g_strdup(pty_name);
1662 ret->has_pty = true;
1664 fprintf(stderr, "char device redirected to %s (label %s)\n",
1665 pty_name, id);
1667 s = g_new0(PtyCharDriver, 1);
1668 chr->opaque = s;
1669 chr->chr_write = pty_chr_write;
1670 chr->chr_update_read_handler = pty_chr_update_read_handler;
1671 chr->chr_free = pty_chr_free;
1672 chr->chr_add_watch = pty_chr_add_watch;
1673 *be_opened = false;
1675 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1676 name = g_strdup_printf("chardev-pty-%s", chr->label);
1677 qio_channel_set_name(QIO_CHANNEL(s->ioc), name);
1678 g_free(name);
1679 s->timer_tag = 0;
1681 return chr;
1684 static void tty_serial_init(int fd, int speed,
1685 int parity, int data_bits, int stop_bits)
1687 struct termios tty;
1688 speed_t spd;
1690 #if 0
1691 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1692 speed, parity, data_bits, stop_bits);
1693 #endif
1694 tcgetattr (fd, &tty);
1696 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1697 speed = speed * 10 / 11;
1698 do {
1699 check_speed(50);
1700 check_speed(75);
1701 check_speed(110);
1702 check_speed(134);
1703 check_speed(150);
1704 check_speed(200);
1705 check_speed(300);
1706 check_speed(600);
1707 check_speed(1200);
1708 check_speed(1800);
1709 check_speed(2400);
1710 check_speed(4800);
1711 check_speed(9600);
1712 check_speed(19200);
1713 check_speed(38400);
1714 /* Non-Posix values follow. They may be unsupported on some systems. */
1715 check_speed(57600);
1716 check_speed(115200);
1717 #ifdef B230400
1718 check_speed(230400);
1719 #endif
1720 #ifdef B460800
1721 check_speed(460800);
1722 #endif
1723 #ifdef B500000
1724 check_speed(500000);
1725 #endif
1726 #ifdef B576000
1727 check_speed(576000);
1728 #endif
1729 #ifdef B921600
1730 check_speed(921600);
1731 #endif
1732 #ifdef B1000000
1733 check_speed(1000000);
1734 #endif
1735 #ifdef B1152000
1736 check_speed(1152000);
1737 #endif
1738 #ifdef B1500000
1739 check_speed(1500000);
1740 #endif
1741 #ifdef B2000000
1742 check_speed(2000000);
1743 #endif
1744 #ifdef B2500000
1745 check_speed(2500000);
1746 #endif
1747 #ifdef B3000000
1748 check_speed(3000000);
1749 #endif
1750 #ifdef B3500000
1751 check_speed(3500000);
1752 #endif
1753 #ifdef B4000000
1754 check_speed(4000000);
1755 #endif
1756 spd = B115200;
1757 } while (0);
1759 cfsetispeed(&tty, spd);
1760 cfsetospeed(&tty, spd);
1762 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1763 |INLCR|IGNCR|ICRNL|IXON);
1764 tty.c_oflag |= OPOST;
1765 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1766 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1767 switch(data_bits) {
1768 default:
1769 case 8:
1770 tty.c_cflag |= CS8;
1771 break;
1772 case 7:
1773 tty.c_cflag |= CS7;
1774 break;
1775 case 6:
1776 tty.c_cflag |= CS6;
1777 break;
1778 case 5:
1779 tty.c_cflag |= CS5;
1780 break;
1782 switch(parity) {
1783 default:
1784 case 'N':
1785 break;
1786 case 'E':
1787 tty.c_cflag |= PARENB;
1788 break;
1789 case 'O':
1790 tty.c_cflag |= PARENB | PARODD;
1791 break;
1793 if (stop_bits == 2)
1794 tty.c_cflag |= CSTOPB;
1796 tcsetattr (fd, TCSANOW, &tty);
1799 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1801 FDCharDriver *s = chr->opaque;
1802 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1804 switch(cmd) {
1805 case CHR_IOCTL_SERIAL_SET_PARAMS:
1807 QEMUSerialSetParams *ssp = arg;
1808 tty_serial_init(fioc->fd,
1809 ssp->speed, ssp->parity,
1810 ssp->data_bits, ssp->stop_bits);
1812 break;
1813 case CHR_IOCTL_SERIAL_SET_BREAK:
1815 int enable = *(int *)arg;
1816 if (enable) {
1817 tcsendbreak(fioc->fd, 1);
1820 break;
1821 case CHR_IOCTL_SERIAL_GET_TIOCM:
1823 int sarg = 0;
1824 int *targ = (int *)arg;
1825 ioctl(fioc->fd, TIOCMGET, &sarg);
1826 *targ = 0;
1827 if (sarg & TIOCM_CTS)
1828 *targ |= CHR_TIOCM_CTS;
1829 if (sarg & TIOCM_CAR)
1830 *targ |= CHR_TIOCM_CAR;
1831 if (sarg & TIOCM_DSR)
1832 *targ |= CHR_TIOCM_DSR;
1833 if (sarg & TIOCM_RI)
1834 *targ |= CHR_TIOCM_RI;
1835 if (sarg & TIOCM_DTR)
1836 *targ |= CHR_TIOCM_DTR;
1837 if (sarg & TIOCM_RTS)
1838 *targ |= CHR_TIOCM_RTS;
1840 break;
1841 case CHR_IOCTL_SERIAL_SET_TIOCM:
1843 int sarg = *(int *)arg;
1844 int targ = 0;
1845 ioctl(fioc->fd, TIOCMGET, &targ);
1846 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1847 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1848 if (sarg & CHR_TIOCM_CTS)
1849 targ |= TIOCM_CTS;
1850 if (sarg & CHR_TIOCM_CAR)
1851 targ |= TIOCM_CAR;
1852 if (sarg & CHR_TIOCM_DSR)
1853 targ |= TIOCM_DSR;
1854 if (sarg & CHR_TIOCM_RI)
1855 targ |= TIOCM_RI;
1856 if (sarg & CHR_TIOCM_DTR)
1857 targ |= TIOCM_DTR;
1858 if (sarg & CHR_TIOCM_RTS)
1859 targ |= TIOCM_RTS;
1860 ioctl(fioc->fd, TIOCMSET, &targ);
1862 break;
1863 default:
1864 return -ENOTSUP;
1866 return 0;
1869 static void qemu_chr_free_tty(CharDriverState *chr)
1871 fd_chr_free(chr);
1874 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1875 ChardevCommon *backend,
1876 bool *be_opened,
1877 Error **errp)
1879 CharDriverState *chr;
1881 tty_serial_init(fd, 115200, 'N', 8, 1);
1882 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1883 if (!chr) {
1884 return NULL;
1886 chr->chr_ioctl = tty_serial_ioctl;
1887 chr->chr_free = qemu_chr_free_tty;
1888 return chr;
1890 #endif /* __linux__ || __sun__ */
1892 #if defined(__linux__)
1894 #define HAVE_CHARDEV_PARPORT 1
1896 typedef struct {
1897 int fd;
1898 int mode;
1899 } ParallelCharDriver;
1901 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1903 if (s->mode != mode) {
1904 int m = mode;
1905 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1906 return 0;
1907 s->mode = mode;
1909 return 1;
1912 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1914 ParallelCharDriver *drv = chr->opaque;
1915 int fd = drv->fd;
1916 uint8_t b;
1918 switch(cmd) {
1919 case CHR_IOCTL_PP_READ_DATA:
1920 if (ioctl(fd, PPRDATA, &b) < 0)
1921 return -ENOTSUP;
1922 *(uint8_t *)arg = b;
1923 break;
1924 case CHR_IOCTL_PP_WRITE_DATA:
1925 b = *(uint8_t *)arg;
1926 if (ioctl(fd, PPWDATA, &b) < 0)
1927 return -ENOTSUP;
1928 break;
1929 case CHR_IOCTL_PP_READ_CONTROL:
1930 if (ioctl(fd, PPRCONTROL, &b) < 0)
1931 return -ENOTSUP;
1932 /* Linux gives only the lowest bits, and no way to know data
1933 direction! For better compatibility set the fixed upper
1934 bits. */
1935 *(uint8_t *)arg = b | 0xc0;
1936 break;
1937 case CHR_IOCTL_PP_WRITE_CONTROL:
1938 b = *(uint8_t *)arg;
1939 if (ioctl(fd, PPWCONTROL, &b) < 0)
1940 return -ENOTSUP;
1941 break;
1942 case CHR_IOCTL_PP_READ_STATUS:
1943 if (ioctl(fd, PPRSTATUS, &b) < 0)
1944 return -ENOTSUP;
1945 *(uint8_t *)arg = b;
1946 break;
1947 case CHR_IOCTL_PP_DATA_DIR:
1948 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1949 return -ENOTSUP;
1950 break;
1951 case CHR_IOCTL_PP_EPP_READ_ADDR:
1952 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1953 struct ParallelIOArg *parg = arg;
1954 int n = read(fd, parg->buffer, parg->count);
1955 if (n != parg->count) {
1956 return -EIO;
1959 break;
1960 case CHR_IOCTL_PP_EPP_READ:
1961 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
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_WRITE_ADDR:
1970 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1971 struct ParallelIOArg *parg = arg;
1972 int n = write(fd, parg->buffer, parg->count);
1973 if (n != parg->count) {
1974 return -EIO;
1977 break;
1978 case CHR_IOCTL_PP_EPP_WRITE:
1979 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
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 default:
1988 return -ENOTSUP;
1990 return 0;
1993 static void pp_free(CharDriverState *chr)
1995 ParallelCharDriver *drv = chr->opaque;
1996 int fd = drv->fd;
1998 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1999 ioctl(fd, PPRELEASE);
2000 close(fd);
2001 g_free(drv);
2002 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2005 static CharDriverState *qemu_chr_open_pp_fd(int fd,
2006 ChardevCommon *backend,
2007 bool *be_opened,
2008 Error **errp)
2010 CharDriverState *chr;
2011 ParallelCharDriver *drv;
2013 if (ioctl(fd, PPCLAIM) < 0) {
2014 error_setg_errno(errp, errno, "not a parallel port");
2015 close(fd);
2016 return NULL;
2019 chr = qemu_chr_alloc(backend, errp);
2020 if (!chr) {
2021 return NULL;
2024 drv = g_new0(ParallelCharDriver, 1);
2025 chr->opaque = drv;
2026 chr->chr_write = null_chr_write;
2027 chr->chr_ioctl = pp_ioctl;
2028 chr->chr_free = pp_free;
2030 drv->fd = fd;
2031 drv->mode = IEEE1284_MODE_COMPAT;
2033 return chr;
2035 #endif /* __linux__ */
2037 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
2039 #define HAVE_CHARDEV_PARPORT 1
2041 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2043 int fd = (int)(intptr_t)chr->opaque;
2044 uint8_t b;
2046 switch(cmd) {
2047 case CHR_IOCTL_PP_READ_DATA:
2048 if (ioctl(fd, PPIGDATA, &b) < 0)
2049 return -ENOTSUP;
2050 *(uint8_t *)arg = b;
2051 break;
2052 case CHR_IOCTL_PP_WRITE_DATA:
2053 b = *(uint8_t *)arg;
2054 if (ioctl(fd, PPISDATA, &b) < 0)
2055 return -ENOTSUP;
2056 break;
2057 case CHR_IOCTL_PP_READ_CONTROL:
2058 if (ioctl(fd, PPIGCTRL, &b) < 0)
2059 return -ENOTSUP;
2060 *(uint8_t *)arg = b;
2061 break;
2062 case CHR_IOCTL_PP_WRITE_CONTROL:
2063 b = *(uint8_t *)arg;
2064 if (ioctl(fd, PPISCTRL, &b) < 0)
2065 return -ENOTSUP;
2066 break;
2067 case CHR_IOCTL_PP_READ_STATUS:
2068 if (ioctl(fd, PPIGSTATUS, &b) < 0)
2069 return -ENOTSUP;
2070 *(uint8_t *)arg = b;
2071 break;
2072 default:
2073 return -ENOTSUP;
2075 return 0;
2078 static CharDriverState *qemu_chr_open_pp_fd(int fd,
2079 ChardevCommon *backend,
2080 bool *be_opened,
2081 Error **errp)
2083 CharDriverState *chr;
2085 chr = qemu_chr_alloc(backend, errp);
2086 if (!chr) {
2087 return NULL;
2089 chr->opaque = (void *)(intptr_t)fd;
2090 chr->chr_write = null_chr_write;
2091 chr->chr_ioctl = pp_ioctl;
2092 *be_opened = false;
2093 return chr;
2095 #endif
2097 #else /* _WIN32 */
2099 #define HAVE_CHARDEV_SERIAL 1
2101 typedef struct {
2102 int max_size;
2103 HANDLE hcom, hrecv, hsend;
2104 OVERLAPPED orecv;
2105 BOOL fpipe;
2106 DWORD len;
2108 /* Protected by the CharDriverState chr_write_lock. */
2109 OVERLAPPED osend;
2110 } WinCharState;
2112 typedef struct {
2113 HANDLE hStdIn;
2114 HANDLE hInputReadyEvent;
2115 HANDLE hInputDoneEvent;
2116 HANDLE hInputThread;
2117 uint8_t win_stdio_buf;
2118 } WinStdioCharState;
2120 #define NSENDBUF 2048
2121 #define NRECVBUF 2048
2122 #define MAXCONNECT 1
2123 #define NTIMEOUT 5000
2125 static int win_chr_poll(void *opaque);
2126 static int win_chr_pipe_poll(void *opaque);
2128 static void win_chr_free(CharDriverState *chr)
2130 WinCharState *s = chr->opaque;
2132 if (s->hsend) {
2133 CloseHandle(s->hsend);
2134 s->hsend = NULL;
2136 if (s->hrecv) {
2137 CloseHandle(s->hrecv);
2138 s->hrecv = NULL;
2140 if (s->hcom) {
2141 CloseHandle(s->hcom);
2142 s->hcom = NULL;
2144 if (s->fpipe)
2145 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2146 else
2147 qemu_del_polling_cb(win_chr_poll, chr);
2149 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2152 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
2154 WinCharState *s = chr->opaque;
2155 COMMCONFIG comcfg;
2156 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2157 COMSTAT comstat;
2158 DWORD size;
2159 DWORD err;
2161 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2162 if (!s->hsend) {
2163 error_setg(errp, "Failed CreateEvent");
2164 goto fail;
2166 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2167 if (!s->hrecv) {
2168 error_setg(errp, "Failed CreateEvent");
2169 goto fail;
2172 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2173 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2174 if (s->hcom == INVALID_HANDLE_VALUE) {
2175 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
2176 s->hcom = NULL;
2177 goto fail;
2180 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2181 error_setg(errp, "Failed SetupComm");
2182 goto fail;
2185 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2186 size = sizeof(COMMCONFIG);
2187 GetDefaultCommConfig(filename, &comcfg, &size);
2188 comcfg.dcb.DCBlength = sizeof(DCB);
2189 CommConfigDialog(filename, NULL, &comcfg);
2191 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2192 error_setg(errp, "Failed SetCommState");
2193 goto fail;
2196 if (!SetCommMask(s->hcom, EV_ERR)) {
2197 error_setg(errp, "Failed SetCommMask");
2198 goto fail;
2201 cto.ReadIntervalTimeout = MAXDWORD;
2202 if (!SetCommTimeouts(s->hcom, &cto)) {
2203 error_setg(errp, "Failed SetCommTimeouts");
2204 goto fail;
2207 if (!ClearCommError(s->hcom, &err, &comstat)) {
2208 error_setg(errp, "Failed ClearCommError");
2209 goto fail;
2211 qemu_add_polling_cb(win_chr_poll, chr);
2212 return 0;
2214 fail:
2215 win_chr_free(chr);
2216 return -1;
2219 /* Called with chr_write_lock held. */
2220 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2222 WinCharState *s = chr->opaque;
2223 DWORD len, ret, size, err;
2225 len = len1;
2226 ZeroMemory(&s->osend, sizeof(s->osend));
2227 s->osend.hEvent = s->hsend;
2228 while (len > 0) {
2229 if (s->hsend)
2230 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2231 else
2232 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2233 if (!ret) {
2234 err = GetLastError();
2235 if (err == ERROR_IO_PENDING) {
2236 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2237 if (ret) {
2238 buf += size;
2239 len -= size;
2240 } else {
2241 break;
2243 } else {
2244 break;
2246 } else {
2247 buf += size;
2248 len -= size;
2251 return len1 - len;
2254 static int win_chr_read_poll(CharDriverState *chr)
2256 WinCharState *s = chr->opaque;
2258 s->max_size = qemu_chr_be_can_write(chr);
2259 return s->max_size;
2262 static void win_chr_readfile(CharDriverState *chr)
2264 WinCharState *s = chr->opaque;
2265 int ret, err;
2266 uint8_t buf[READ_BUF_LEN];
2267 DWORD size;
2269 ZeroMemory(&s->orecv, sizeof(s->orecv));
2270 s->orecv.hEvent = s->hrecv;
2271 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2272 if (!ret) {
2273 err = GetLastError();
2274 if (err == ERROR_IO_PENDING) {
2275 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2279 if (size > 0) {
2280 qemu_chr_be_write(chr, buf, size);
2284 static void win_chr_read(CharDriverState *chr)
2286 WinCharState *s = chr->opaque;
2288 if (s->len > s->max_size)
2289 s->len = s->max_size;
2290 if (s->len == 0)
2291 return;
2293 win_chr_readfile(chr);
2296 static int win_chr_poll(void *opaque)
2298 CharDriverState *chr = opaque;
2299 WinCharState *s = chr->opaque;
2300 COMSTAT status;
2301 DWORD comerr;
2303 ClearCommError(s->hcom, &comerr, &status);
2304 if (status.cbInQue > 0) {
2305 s->len = status.cbInQue;
2306 win_chr_read_poll(chr);
2307 win_chr_read(chr);
2308 return 1;
2310 return 0;
2313 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2314 ChardevCommon *backend,
2315 Error **errp)
2317 CharDriverState *chr;
2318 WinCharState *s;
2320 chr = qemu_chr_alloc(backend, errp);
2321 if (!chr) {
2322 return NULL;
2324 s = g_new0(WinCharState, 1);
2325 chr->opaque = s;
2326 chr->chr_write = win_chr_write;
2327 chr->chr_free = win_chr_free;
2329 if (win_chr_init(chr, filename, errp) < 0) {
2330 g_free(s);
2331 qemu_chr_free_common(chr);
2332 return NULL;
2334 return chr;
2337 static int win_chr_pipe_poll(void *opaque)
2339 CharDriverState *chr = opaque;
2340 WinCharState *s = chr->opaque;
2341 DWORD size;
2343 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2344 if (size > 0) {
2345 s->len = size;
2346 win_chr_read_poll(chr);
2347 win_chr_read(chr);
2348 return 1;
2350 return 0;
2353 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2354 Error **errp)
2356 WinCharState *s = chr->opaque;
2357 OVERLAPPED ov;
2358 int ret;
2359 DWORD size;
2360 char *openname;
2362 s->fpipe = TRUE;
2364 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2365 if (!s->hsend) {
2366 error_setg(errp, "Failed CreateEvent");
2367 goto fail;
2369 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2370 if (!s->hrecv) {
2371 error_setg(errp, "Failed CreateEvent");
2372 goto fail;
2375 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2376 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2377 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2378 PIPE_WAIT,
2379 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2380 g_free(openname);
2381 if (s->hcom == INVALID_HANDLE_VALUE) {
2382 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2383 s->hcom = NULL;
2384 goto fail;
2387 ZeroMemory(&ov, sizeof(ov));
2388 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2389 ret = ConnectNamedPipe(s->hcom, &ov);
2390 if (ret) {
2391 error_setg(errp, "Failed ConnectNamedPipe");
2392 goto fail;
2395 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2396 if (!ret) {
2397 error_setg(errp, "Failed GetOverlappedResult");
2398 if (ov.hEvent) {
2399 CloseHandle(ov.hEvent);
2400 ov.hEvent = NULL;
2402 goto fail;
2405 if (ov.hEvent) {
2406 CloseHandle(ov.hEvent);
2407 ov.hEvent = NULL;
2409 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2410 return 0;
2412 fail:
2413 win_chr_free(chr);
2414 return -1;
2418 static CharDriverState *qemu_chr_open_pipe(const char *id,
2419 ChardevBackend *backend,
2420 ChardevReturn *ret,
2421 bool *be_opened,
2422 Error **errp)
2424 ChardevHostdev *opts = backend->u.pipe.data;
2425 const char *filename = opts->device;
2426 CharDriverState *chr;
2427 WinCharState *s;
2428 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2430 chr = qemu_chr_alloc(common, errp);
2431 if (!chr) {
2432 return NULL;
2434 s = g_new0(WinCharState, 1);
2435 chr->opaque = s;
2436 chr->chr_write = win_chr_write;
2437 chr->chr_free = win_chr_free;
2439 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2440 g_free(s);
2441 qemu_chr_free_common(chr);
2442 return NULL;
2444 return chr;
2447 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2448 ChardevCommon *backend,
2449 Error **errp)
2451 CharDriverState *chr;
2452 WinCharState *s;
2454 chr = qemu_chr_alloc(backend, errp);
2455 if (!chr) {
2456 return NULL;
2458 s = g_new0(WinCharState, 1);
2459 s->hcom = fd_out;
2460 chr->opaque = s;
2461 chr->chr_write = win_chr_write;
2462 return chr;
2465 static CharDriverState *qemu_chr_open_win_con(const char *id,
2466 ChardevBackend *backend,
2467 ChardevReturn *ret,
2468 bool *be_opened,
2469 Error **errp)
2471 ChardevCommon *common = backend->u.console.data;
2472 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2473 common, errp);
2476 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2478 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2479 DWORD dwSize;
2480 int len1;
2482 len1 = len;
2484 while (len1 > 0) {
2485 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2486 break;
2488 buf += dwSize;
2489 len1 -= dwSize;
2492 return len - len1;
2495 static void win_stdio_wait_func(void *opaque)
2497 CharDriverState *chr = opaque;
2498 WinStdioCharState *stdio = chr->opaque;
2499 INPUT_RECORD buf[4];
2500 int ret;
2501 DWORD dwSize;
2502 int i;
2504 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2506 if (!ret) {
2507 /* Avoid error storm */
2508 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2509 return;
2512 for (i = 0; i < dwSize; i++) {
2513 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2515 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2516 int j;
2517 if (kev->uChar.AsciiChar != 0) {
2518 for (j = 0; j < kev->wRepeatCount; j++) {
2519 if (qemu_chr_be_can_write(chr)) {
2520 uint8_t c = kev->uChar.AsciiChar;
2521 qemu_chr_be_write(chr, &c, 1);
2529 static DWORD WINAPI win_stdio_thread(LPVOID param)
2531 CharDriverState *chr = param;
2532 WinStdioCharState *stdio = chr->opaque;
2533 int ret;
2534 DWORD dwSize;
2536 while (1) {
2538 /* Wait for one byte */
2539 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2541 /* Exit in case of error, continue if nothing read */
2542 if (!ret) {
2543 break;
2545 if (!dwSize) {
2546 continue;
2549 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2550 if (stdio->win_stdio_buf == '\r') {
2551 continue;
2554 /* Signal the main thread and wait until the byte was eaten */
2555 if (!SetEvent(stdio->hInputReadyEvent)) {
2556 break;
2558 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2559 != WAIT_OBJECT_0) {
2560 break;
2564 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2565 return 0;
2568 static void win_stdio_thread_wait_func(void *opaque)
2570 CharDriverState *chr = opaque;
2571 WinStdioCharState *stdio = chr->opaque;
2573 if (qemu_chr_be_can_write(chr)) {
2574 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2577 SetEvent(stdio->hInputDoneEvent);
2580 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2582 WinStdioCharState *stdio = chr->opaque;
2583 DWORD dwMode = 0;
2585 GetConsoleMode(stdio->hStdIn, &dwMode);
2587 if (echo) {
2588 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2589 } else {
2590 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2594 static void win_stdio_free(CharDriverState *chr)
2596 WinStdioCharState *stdio = chr->opaque;
2598 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2599 CloseHandle(stdio->hInputReadyEvent);
2601 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2602 CloseHandle(stdio->hInputDoneEvent);
2604 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2605 TerminateThread(stdio->hInputThread, 0);
2608 g_free(chr->opaque);
2611 static CharDriverState *qemu_chr_open_stdio(const char *id,
2612 ChardevBackend *backend,
2613 ChardevReturn *ret,
2614 bool *be_opened,
2615 Error **errp)
2617 CharDriverState *chr;
2618 WinStdioCharState *stdio;
2619 DWORD dwMode;
2620 int is_console = 0;
2621 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio.data);
2623 chr = qemu_chr_alloc(common, errp);
2624 if (!chr) {
2625 return NULL;
2627 stdio = g_new0(WinStdioCharState, 1);
2629 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2630 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2631 error_setg(errp, "cannot open stdio: invalid handle");
2632 return NULL;
2635 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2637 chr->opaque = stdio;
2638 chr->chr_write = win_stdio_write;
2639 chr->chr_free = win_stdio_free;
2641 if (is_console) {
2642 if (qemu_add_wait_object(stdio->hStdIn,
2643 win_stdio_wait_func, chr)) {
2644 error_setg(errp, "qemu_add_wait_object: failed");
2645 goto err1;
2647 } else {
2648 DWORD dwId;
2650 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2651 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2652 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2653 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2654 error_setg(errp, "cannot create event");
2655 goto err2;
2657 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2658 win_stdio_thread_wait_func, chr)) {
2659 error_setg(errp, "qemu_add_wait_object: failed");
2660 goto err2;
2662 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2663 chr, 0, &dwId);
2665 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2666 error_setg(errp, "cannot create stdio thread");
2667 goto err3;
2671 dwMode |= ENABLE_LINE_INPUT;
2673 if (is_console) {
2674 /* set the terminal in raw mode */
2675 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2676 dwMode |= ENABLE_PROCESSED_INPUT;
2679 SetConsoleMode(stdio->hStdIn, dwMode);
2681 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2682 qemu_chr_set_echo_win_stdio(chr, false);
2684 return chr;
2686 err3:
2687 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2688 err2:
2689 CloseHandle(stdio->hInputReadyEvent);
2690 CloseHandle(stdio->hInputDoneEvent);
2691 err1:
2692 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2693 return NULL;
2695 #endif /* !_WIN32 */
2697 /***********************************************************/
2698 /* UDP Net console */
2700 typedef struct {
2701 QIOChannel *ioc;
2702 uint8_t buf[READ_BUF_LEN];
2703 int bufcnt;
2704 int bufptr;
2705 int max_size;
2706 } NetCharDriver;
2708 /* Called with chr_write_lock held. */
2709 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2711 NetCharDriver *s = chr->opaque;
2713 return qio_channel_write(
2714 s->ioc, (const char *)buf, len, NULL);
2717 static int udp_chr_read_poll(void *opaque)
2719 CharDriverState *chr = opaque;
2720 NetCharDriver *s = chr->opaque;
2722 s->max_size = qemu_chr_be_can_write(chr);
2724 /* If there were any stray characters in the queue process them
2725 * first
2727 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2728 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2729 s->bufptr++;
2730 s->max_size = qemu_chr_be_can_write(chr);
2732 return s->max_size;
2735 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2737 CharDriverState *chr = opaque;
2738 NetCharDriver *s = chr->opaque;
2739 ssize_t ret;
2741 if (s->max_size == 0) {
2742 return TRUE;
2744 ret = qio_channel_read(
2745 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2746 if (ret <= 0) {
2747 remove_fd_in_watch(chr);
2748 return FALSE;
2750 s->bufcnt = ret;
2752 s->bufptr = 0;
2753 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2754 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2755 s->bufptr++;
2756 s->max_size = qemu_chr_be_can_write(chr);
2759 return TRUE;
2762 static void udp_chr_update_read_handler(CharDriverState *chr,
2763 GMainContext *context)
2765 NetCharDriver *s = chr->opaque;
2767 remove_fd_in_watch(chr);
2768 if (s->ioc) {
2769 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
2770 udp_chr_read_poll,
2771 udp_chr_read, chr,
2772 context);
2776 static void udp_chr_free(CharDriverState *chr)
2778 NetCharDriver *s = chr->opaque;
2780 remove_fd_in_watch(chr);
2781 if (s->ioc) {
2782 object_unref(OBJECT(s->ioc));
2784 g_free(s);
2785 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2788 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2789 ChardevCommon *backend,
2790 bool *be_opened,
2791 Error **errp)
2793 CharDriverState *chr = NULL;
2794 NetCharDriver *s = NULL;
2796 chr = qemu_chr_alloc(backend, errp);
2797 if (!chr) {
2798 return NULL;
2800 s = g_new0(NetCharDriver, 1);
2802 s->ioc = QIO_CHANNEL(sioc);
2803 s->bufcnt = 0;
2804 s->bufptr = 0;
2805 chr->opaque = s;
2806 chr->chr_write = udp_chr_write;
2807 chr->chr_update_read_handler = udp_chr_update_read_handler;
2808 chr->chr_free = udp_chr_free;
2809 /* be isn't opened until we get a connection */
2810 *be_opened = false;
2811 return chr;
2814 /***********************************************************/
2815 /* TCP Net console */
2817 typedef struct {
2818 QIOChannel *ioc; /* Client I/O channel */
2819 QIOChannelSocket *sioc; /* Client master channel */
2820 QIOChannelSocket *listen_ioc;
2821 guint listen_tag;
2822 QCryptoTLSCreds *tls_creds;
2823 int connected;
2824 int max_size;
2825 int do_telnetopt;
2826 int do_nodelay;
2827 int is_unix;
2828 int *read_msgfds;
2829 size_t read_msgfds_num;
2830 int *write_msgfds;
2831 size_t write_msgfds_num;
2833 SocketAddress *addr;
2834 bool is_listen;
2835 bool is_telnet;
2837 guint reconnect_timer;
2838 int64_t reconnect_time;
2839 bool connect_err_reported;
2840 } TCPCharDriver;
2842 static gboolean socket_reconnect_timeout(gpointer opaque);
2844 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2846 TCPCharDriver *s = chr->opaque;
2847 char *name;
2848 assert(s->connected == 0);
2849 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2850 socket_reconnect_timeout, chr);
2851 name = g_strdup_printf("chardev-socket-reconnect-%s", chr->label);
2852 g_source_set_name_by_id(s->reconnect_timer, name);
2853 g_free(name);
2856 static void check_report_connect_error(CharDriverState *chr,
2857 Error *err)
2859 TCPCharDriver *s = chr->opaque;
2861 if (!s->connect_err_reported) {
2862 error_report("Unable to connect character device %s: %s",
2863 chr->label, error_get_pretty(err));
2864 s->connect_err_reported = true;
2866 qemu_chr_socket_restart_timer(chr);
2869 static gboolean tcp_chr_accept(QIOChannel *chan,
2870 GIOCondition cond,
2871 void *opaque);
2873 /* Called with chr_write_lock held. */
2874 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2876 TCPCharDriver *s = chr->opaque;
2877 if (s->connected) {
2878 int ret = io_channel_send_full(s->ioc, buf, len,
2879 s->write_msgfds,
2880 s->write_msgfds_num);
2882 /* free the written msgfds, no matter what */
2883 if (s->write_msgfds_num) {
2884 g_free(s->write_msgfds);
2885 s->write_msgfds = 0;
2886 s->write_msgfds_num = 0;
2889 return ret;
2890 } else {
2891 /* XXX: indicate an error ? */
2892 return len;
2896 static int tcp_chr_read_poll(void *opaque)
2898 CharDriverState *chr = opaque;
2899 TCPCharDriver *s = chr->opaque;
2900 if (!s->connected)
2901 return 0;
2902 s->max_size = qemu_chr_be_can_write(chr);
2903 return s->max_size;
2906 #define IAC 255
2907 #define IAC_BREAK 243
2908 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2909 TCPCharDriver *s,
2910 uint8_t *buf, int *size)
2912 /* Handle any telnet client's basic IAC options to satisfy char by
2913 * char mode with no echo. All IAC options will be removed from
2914 * the buf and the do_telnetopt variable will be used to track the
2915 * state of the width of the IAC information.
2917 * IAC commands come in sets of 3 bytes with the exception of the
2918 * "IAC BREAK" command and the double IAC.
2921 int i;
2922 int j = 0;
2924 for (i = 0; i < *size; i++) {
2925 if (s->do_telnetopt > 1) {
2926 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2927 /* Double IAC means send an IAC */
2928 if (j != i)
2929 buf[j] = buf[i];
2930 j++;
2931 s->do_telnetopt = 1;
2932 } else {
2933 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2934 /* Handle IAC break commands by sending a serial break */
2935 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2936 s->do_telnetopt++;
2938 s->do_telnetopt++;
2940 if (s->do_telnetopt >= 4) {
2941 s->do_telnetopt = 1;
2943 } else {
2944 if ((unsigned char)buf[i] == IAC) {
2945 s->do_telnetopt = 2;
2946 } else {
2947 if (j != i)
2948 buf[j] = buf[i];
2949 j++;
2953 *size = j;
2956 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2958 TCPCharDriver *s = chr->opaque;
2959 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2961 assert(num <= TCP_MAX_FDS);
2963 if (to_copy) {
2964 int i;
2966 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2968 /* Close unused fds */
2969 for (i = to_copy; i < s->read_msgfds_num; i++) {
2970 close(s->read_msgfds[i]);
2973 g_free(s->read_msgfds);
2974 s->read_msgfds = 0;
2975 s->read_msgfds_num = 0;
2978 return to_copy;
2981 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2983 TCPCharDriver *s = chr->opaque;
2985 /* clear old pending fd array */
2986 g_free(s->write_msgfds);
2987 s->write_msgfds = NULL;
2988 s->write_msgfds_num = 0;
2990 if (!s->connected ||
2991 !qio_channel_has_feature(s->ioc,
2992 QIO_CHANNEL_FEATURE_FD_PASS)) {
2993 return -1;
2996 if (num) {
2997 s->write_msgfds = g_new(int, num);
2998 memcpy(s->write_msgfds, fds, num * sizeof(int));
3001 s->write_msgfds_num = num;
3003 return 0;
3006 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
3008 TCPCharDriver *s = chr->opaque;
3009 struct iovec iov = { .iov_base = buf, .iov_len = len };
3010 int ret;
3011 size_t i;
3012 int *msgfds = NULL;
3013 size_t msgfds_num = 0;
3015 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
3016 ret = qio_channel_readv_full(s->ioc, &iov, 1,
3017 &msgfds, &msgfds_num,
3018 NULL);
3019 } else {
3020 ret = qio_channel_readv_full(s->ioc, &iov, 1,
3021 NULL, NULL,
3022 NULL);
3025 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3026 errno = EAGAIN;
3027 ret = -1;
3028 } else if (ret == -1) {
3029 errno = EIO;
3032 if (msgfds_num) {
3033 /* close and clean read_msgfds */
3034 for (i = 0; i < s->read_msgfds_num; i++) {
3035 close(s->read_msgfds[i]);
3038 if (s->read_msgfds_num) {
3039 g_free(s->read_msgfds);
3042 s->read_msgfds = msgfds;
3043 s->read_msgfds_num = msgfds_num;
3046 for (i = 0; i < s->read_msgfds_num; i++) {
3047 int fd = s->read_msgfds[i];
3048 if (fd < 0) {
3049 continue;
3052 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
3053 qemu_set_block(fd);
3055 #ifndef MSG_CMSG_CLOEXEC
3056 qemu_set_cloexec(fd);
3057 #endif
3060 return ret;
3063 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
3065 TCPCharDriver *s = chr->opaque;
3066 return qio_channel_create_watch(s->ioc, cond);
3069 static void tcp_chr_free_connection(CharDriverState *chr)
3071 TCPCharDriver *s = chr->opaque;
3072 int i;
3074 if (!s->connected) {
3075 return;
3078 if (s->read_msgfds_num) {
3079 for (i = 0; i < s->read_msgfds_num; i++) {
3080 close(s->read_msgfds[i]);
3082 g_free(s->read_msgfds);
3083 s->read_msgfds = NULL;
3084 s->read_msgfds_num = 0;
3087 tcp_set_msgfds(chr, NULL, 0);
3088 remove_fd_in_watch(chr);
3089 object_unref(OBJECT(s->sioc));
3090 s->sioc = NULL;
3091 object_unref(OBJECT(s->ioc));
3092 s->ioc = NULL;
3093 g_free(chr->filename);
3094 chr->filename = NULL;
3095 s->connected = 0;
3098 static void tcp_chr_disconnect(CharDriverState *chr)
3100 TCPCharDriver *s = chr->opaque;
3102 if (!s->connected) {
3103 return;
3106 tcp_chr_free_connection(chr);
3108 if (s->listen_ioc) {
3109 s->listen_tag = qio_channel_add_watch(
3110 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
3112 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
3113 s->is_listen, s->is_telnet);
3114 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3115 if (s->reconnect_time) {
3116 qemu_chr_socket_restart_timer(chr);
3120 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
3122 CharDriverState *chr = opaque;
3123 TCPCharDriver *s = chr->opaque;
3124 uint8_t buf[READ_BUF_LEN];
3125 int len, size;
3127 if (!s->connected || s->max_size <= 0) {
3128 return TRUE;
3130 len = sizeof(buf);
3131 if (len > s->max_size)
3132 len = s->max_size;
3133 size = tcp_chr_recv(chr, (void *)buf, len);
3134 if (size == 0 || size == -1) {
3135 /* connection closed */
3136 tcp_chr_disconnect(chr);
3137 } else if (size > 0) {
3138 if (s->do_telnetopt)
3139 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3140 if (size > 0)
3141 qemu_chr_be_write(chr, buf, size);
3144 return TRUE;
3147 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
3149 TCPCharDriver *s = chr->opaque;
3150 int size;
3152 if (!s->connected) {
3153 return 0;
3156 size = tcp_chr_recv(chr, (void *) buf, len);
3157 if (size == 0) {
3158 /* connection closed */
3159 tcp_chr_disconnect(chr);
3162 return size;
3165 static void tcp_chr_connect(void *opaque)
3167 CharDriverState *chr = opaque;
3168 TCPCharDriver *s = chr->opaque;
3170 g_free(chr->filename);
3171 chr->filename = sockaddr_to_str(
3172 &s->sioc->localAddr, s->sioc->localAddrLen,
3173 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
3174 s->is_listen, s->is_telnet);
3176 s->connected = 1;
3177 if (s->ioc) {
3178 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
3179 tcp_chr_read_poll,
3180 tcp_chr_read,
3181 chr, NULL);
3183 qemu_chr_be_generic_open(chr);
3186 static void tcp_chr_update_read_handler(CharDriverState *chr,
3187 GMainContext *context)
3189 TCPCharDriver *s = chr->opaque;
3191 if (!s->connected) {
3192 return;
3195 remove_fd_in_watch(chr);
3196 if (s->ioc) {
3197 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
3198 tcp_chr_read_poll,
3199 tcp_chr_read, chr,
3200 context);
3204 typedef struct {
3205 CharDriverState *chr;
3206 char buf[12];
3207 size_t buflen;
3208 } TCPCharDriverTelnetInit;
3210 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
3211 GIOCondition cond G_GNUC_UNUSED,
3212 gpointer user_data)
3214 TCPCharDriverTelnetInit *init = user_data;
3215 ssize_t ret;
3217 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
3218 if (ret < 0) {
3219 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3220 ret = 0;
3221 } else {
3222 tcp_chr_disconnect(init->chr);
3223 return FALSE;
3226 init->buflen -= ret;
3228 if (init->buflen == 0) {
3229 tcp_chr_connect(init->chr);
3230 return FALSE;
3233 memmove(init->buf, init->buf + ret, init->buflen);
3235 return TRUE;
3238 static void tcp_chr_telnet_init(CharDriverState *chr)
3240 TCPCharDriver *s = chr->opaque;
3241 TCPCharDriverTelnetInit *init =
3242 g_new0(TCPCharDriverTelnetInit, 1);
3243 size_t n = 0;
3245 init->chr = chr;
3246 init->buflen = 12;
3248 #define IACSET(x, a, b, c) \
3249 do { \
3250 x[n++] = a; \
3251 x[n++] = b; \
3252 x[n++] = c; \
3253 } while (0)
3255 /* Prep the telnet negotion to put telnet in binary,
3256 * no echo, single char mode */
3257 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3258 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3259 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3260 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3262 #undef IACSET
3264 qio_channel_add_watch(
3265 s->ioc, G_IO_OUT,
3266 tcp_chr_telnet_init_io,
3267 init, NULL);
3271 static void tcp_chr_tls_handshake(Object *source,
3272 Error *err,
3273 gpointer user_data)
3275 CharDriverState *chr = user_data;
3276 TCPCharDriver *s = chr->opaque;
3278 if (err) {
3279 tcp_chr_disconnect(chr);
3280 } else {
3281 if (s->do_telnetopt) {
3282 tcp_chr_telnet_init(chr);
3283 } else {
3284 tcp_chr_connect(chr);
3290 static void tcp_chr_tls_init(CharDriverState *chr)
3292 TCPCharDriver *s = chr->opaque;
3293 QIOChannelTLS *tioc;
3294 Error *err = NULL;
3295 gchar *name;
3297 if (s->is_listen) {
3298 tioc = qio_channel_tls_new_server(
3299 s->ioc, s->tls_creds,
3300 NULL, /* XXX Use an ACL */
3301 &err);
3302 } else {
3303 tioc = qio_channel_tls_new_client(
3304 s->ioc, s->tls_creds,
3305 s->addr->u.inet.data->host,
3306 &err);
3308 if (tioc == NULL) {
3309 error_free(err);
3310 tcp_chr_disconnect(chr);
3311 return;
3313 name = g_strdup_printf("chardev-tls-%s-%s",
3314 s->is_listen ? "server" : "client",
3315 chr->label);
3316 qio_channel_set_name(QIO_CHANNEL(tioc), name);
3317 g_free(name);
3318 object_unref(OBJECT(s->ioc));
3319 s->ioc = QIO_CHANNEL(tioc);
3321 qio_channel_tls_handshake(tioc,
3322 tcp_chr_tls_handshake,
3323 chr,
3324 NULL);
3328 static void tcp_chr_set_client_ioc_name(CharDriverState *chr,
3329 QIOChannelSocket *sioc)
3331 TCPCharDriver *s = chr->opaque;
3332 char *name;
3333 name = g_strdup_printf("chardev-tcp-%s-%s",
3334 s->is_listen ? "server" : "client",
3335 chr->label);
3336 qio_channel_set_name(QIO_CHANNEL(sioc), name);
3337 g_free(name);
3341 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3343 TCPCharDriver *s = chr->opaque;
3344 if (s->ioc != NULL) {
3345 return -1;
3348 s->ioc = QIO_CHANNEL(sioc);
3349 object_ref(OBJECT(sioc));
3350 s->sioc = sioc;
3351 object_ref(OBJECT(sioc));
3353 qio_channel_set_blocking(s->ioc, false, NULL);
3355 if (s->do_nodelay) {
3356 qio_channel_set_delay(s->ioc, false);
3358 if (s->listen_tag) {
3359 g_source_remove(s->listen_tag);
3360 s->listen_tag = 0;
3363 if (s->tls_creds) {
3364 tcp_chr_tls_init(chr);
3365 } else {
3366 if (s->do_telnetopt) {
3367 tcp_chr_telnet_init(chr);
3368 } else {
3369 tcp_chr_connect(chr);
3373 return 0;
3377 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3379 int ret;
3380 QIOChannelSocket *sioc;
3382 sioc = qio_channel_socket_new_fd(fd, NULL);
3383 if (!sioc) {
3384 return -1;
3386 tcp_chr_set_client_ioc_name(chr, sioc);
3387 ret = tcp_chr_new_client(chr, sioc);
3388 object_unref(OBJECT(sioc));
3389 return ret;
3392 static gboolean tcp_chr_accept(QIOChannel *channel,
3393 GIOCondition cond,
3394 void *opaque)
3396 CharDriverState *chr = opaque;
3397 QIOChannelSocket *sioc;
3399 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3400 NULL);
3401 if (!sioc) {
3402 return TRUE;
3405 tcp_chr_new_client(chr, sioc);
3407 object_unref(OBJECT(sioc));
3409 return TRUE;
3412 static int tcp_chr_wait_connected(CharDriverState *chr, Error **errp)
3414 TCPCharDriver *s = chr->opaque;
3415 QIOChannelSocket *sioc;
3417 /* It can't wait on s->connected, since it is set asynchronously
3418 * in TLS and telnet cases, only wait for an accepted socket */
3419 while (!s->ioc) {
3420 if (s->is_listen) {
3421 fprintf(stderr, "QEMU waiting for connection on: %s\n",
3422 chr->filename);
3423 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), true, NULL);
3424 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
3425 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
3426 } else {
3427 sioc = qio_channel_socket_new();
3428 tcp_chr_set_client_ioc_name(chr, sioc);
3429 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3430 object_unref(OBJECT(sioc));
3431 return -1;
3433 tcp_chr_new_client(chr, sioc);
3434 object_unref(OBJECT(sioc));
3438 return 0;
3441 static int qemu_chr_wait_connected(CharDriverState *chr, Error **errp)
3443 if (chr->chr_wait_connected) {
3444 return chr->chr_wait_connected(chr, errp);
3447 return 0;
3450 int qemu_chr_fe_wait_connected(CharBackend *be, Error **errp)
3452 if (!be->chr) {
3453 error_setg(errp, "missing associated backend");
3454 return -1;
3457 return qemu_chr_wait_connected(be->chr, errp);
3460 static void tcp_chr_free(CharDriverState *chr)
3462 TCPCharDriver *s = chr->opaque;
3464 tcp_chr_free_connection(chr);
3466 if (s->reconnect_timer) {
3467 g_source_remove(s->reconnect_timer);
3468 s->reconnect_timer = 0;
3470 qapi_free_SocketAddress(s->addr);
3471 if (s->listen_tag) {
3472 g_source_remove(s->listen_tag);
3473 s->listen_tag = 0;
3475 if (s->listen_ioc) {
3476 object_unref(OBJECT(s->listen_ioc));
3478 if (s->tls_creds) {
3479 object_unref(OBJECT(s->tls_creds));
3481 g_free(s);
3482 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3486 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3488 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3489 CharDriverState *chr = opaque;
3490 TCPCharDriver *s = chr->opaque;
3492 if (err) {
3493 check_report_connect_error(chr, err);
3494 object_unref(src);
3495 return;
3498 s->connect_err_reported = false;
3499 tcp_chr_new_client(chr, sioc);
3500 object_unref(OBJECT(sioc));
3504 /*********************************************************/
3505 /* Ring buffer chardev */
3507 typedef struct {
3508 size_t size;
3509 size_t prod;
3510 size_t cons;
3511 uint8_t *cbuf;
3512 } RingBufCharDriver;
3514 static size_t ringbuf_count(const CharDriverState *chr)
3516 const RingBufCharDriver *d = chr->opaque;
3518 return d->prod - d->cons;
3521 /* Called with chr_write_lock held. */
3522 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3524 RingBufCharDriver *d = chr->opaque;
3525 int i;
3527 if (!buf || (len < 0)) {
3528 return -1;
3531 for (i = 0; i < len; i++ ) {
3532 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3533 if (d->prod - d->cons > d->size) {
3534 d->cons = d->prod - d->size;
3538 return len;
3541 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3543 RingBufCharDriver *d = chr->opaque;
3544 int i;
3546 qemu_mutex_lock(&chr->chr_write_lock);
3547 for (i = 0; i < len && d->cons != d->prod; i++) {
3548 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3550 qemu_mutex_unlock(&chr->chr_write_lock);
3552 return i;
3555 static void ringbuf_chr_free(struct CharDriverState *chr)
3557 RingBufCharDriver *d = chr->opaque;
3559 g_free(d->cbuf);
3560 g_free(d);
3561 chr->opaque = NULL;
3564 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3565 ChardevBackend *backend,
3566 ChardevReturn *ret,
3567 bool *be_opened,
3568 Error **errp)
3570 ChardevRingbuf *opts = backend->u.ringbuf.data;
3571 ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
3572 CharDriverState *chr;
3573 RingBufCharDriver *d;
3575 chr = qemu_chr_alloc(common, errp);
3576 if (!chr) {
3577 return NULL;
3579 d = g_malloc(sizeof(*d));
3581 d->size = opts->has_size ? opts->size : 65536;
3583 /* The size must be power of 2 */
3584 if (d->size & (d->size - 1)) {
3585 error_setg(errp, "size of ringbuf chardev must be power of two");
3586 goto fail;
3589 d->prod = 0;
3590 d->cons = 0;
3591 d->cbuf = g_malloc0(d->size);
3593 chr->opaque = d;
3594 chr->chr_write = ringbuf_chr_write;
3595 chr->chr_free = ringbuf_chr_free;
3597 return chr;
3599 fail:
3600 g_free(d);
3601 qemu_chr_free_common(chr);
3602 return NULL;
3605 bool chr_is_ringbuf(const CharDriverState *chr)
3607 return chr->chr_write == ringbuf_chr_write;
3610 void qmp_ringbuf_write(const char *device, const char *data,
3611 bool has_format, enum DataFormat format,
3612 Error **errp)
3614 CharDriverState *chr;
3615 const uint8_t *write_data;
3616 int ret;
3617 gsize write_count;
3619 chr = qemu_chr_find(device);
3620 if (!chr) {
3621 error_setg(errp, "Device '%s' not found", device);
3622 return;
3625 if (!chr_is_ringbuf(chr)) {
3626 error_setg(errp,"%s is not a ringbuf device", device);
3627 return;
3630 if (has_format && (format == DATA_FORMAT_BASE64)) {
3631 write_data = qbase64_decode(data, -1,
3632 &write_count,
3633 errp);
3634 if (!write_data) {
3635 return;
3637 } else {
3638 write_data = (uint8_t *)data;
3639 write_count = strlen(data);
3642 ret = ringbuf_chr_write(chr, write_data, write_count);
3644 if (write_data != (uint8_t *)data) {
3645 g_free((void *)write_data);
3648 if (ret < 0) {
3649 error_setg(errp, "Failed to write to device %s", device);
3650 return;
3654 char *qmp_ringbuf_read(const char *device, int64_t size,
3655 bool has_format, enum DataFormat format,
3656 Error **errp)
3658 CharDriverState *chr;
3659 uint8_t *read_data;
3660 size_t count;
3661 char *data;
3663 chr = qemu_chr_find(device);
3664 if (!chr) {
3665 error_setg(errp, "Device '%s' not found", device);
3666 return NULL;
3669 if (!chr_is_ringbuf(chr)) {
3670 error_setg(errp,"%s is not a ringbuf device", device);
3671 return NULL;
3674 if (size <= 0) {
3675 error_setg(errp, "size must be greater than zero");
3676 return NULL;
3679 count = ringbuf_count(chr);
3680 size = size > count ? count : size;
3681 read_data = g_malloc(size + 1);
3683 ringbuf_chr_read(chr, read_data, size);
3685 if (has_format && (format == DATA_FORMAT_BASE64)) {
3686 data = g_base64_encode(read_data, size);
3687 g_free(read_data);
3688 } else {
3690 * FIXME should read only complete, valid UTF-8 characters up
3691 * to @size bytes. Invalid sequences should be replaced by a
3692 * suitable replacement character. Except when (and only
3693 * when) ring buffer lost characters since last read, initial
3694 * continuation characters should be dropped.
3696 read_data[size] = 0;
3697 data = (char *)read_data;
3700 return data;
3703 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3705 char host[65], port[33], width[8], height[8];
3706 int pos;
3707 const char *p;
3708 QemuOpts *opts;
3709 Error *local_err = NULL;
3711 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3712 if (local_err) {
3713 error_report_err(local_err);
3714 return NULL;
3717 if (strstart(filename, "mon:", &p)) {
3718 filename = p;
3719 qemu_opt_set(opts, "mux", "on", &error_abort);
3720 if (strcmp(filename, "stdio") == 0) {
3721 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3722 * but pass it to the guest. Handle this only for compat syntax,
3723 * for -chardev syntax we have special option for this.
3724 * This is what -nographic did, redirecting+muxing serial+monitor
3725 * to stdio causing Ctrl+C to be passed to guest. */
3726 qemu_opt_set(opts, "signal", "off", &error_abort);
3730 if (strcmp(filename, "null") == 0 ||
3731 strcmp(filename, "pty") == 0 ||
3732 strcmp(filename, "msmouse") == 0 ||
3733 strcmp(filename, "braille") == 0 ||
3734 strcmp(filename, "testdev") == 0 ||
3735 strcmp(filename, "stdio") == 0) {
3736 qemu_opt_set(opts, "backend", filename, &error_abort);
3737 return opts;
3739 if (strstart(filename, "vc", &p)) {
3740 qemu_opt_set(opts, "backend", "vc", &error_abort);
3741 if (*p == ':') {
3742 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3743 /* pixels */
3744 qemu_opt_set(opts, "width", width, &error_abort);
3745 qemu_opt_set(opts, "height", height, &error_abort);
3746 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3747 /* chars */
3748 qemu_opt_set(opts, "cols", width, &error_abort);
3749 qemu_opt_set(opts, "rows", height, &error_abort);
3750 } else {
3751 goto fail;
3754 return opts;
3756 if (strcmp(filename, "con:") == 0) {
3757 qemu_opt_set(opts, "backend", "console", &error_abort);
3758 return opts;
3760 if (strstart(filename, "COM", NULL)) {
3761 qemu_opt_set(opts, "backend", "serial", &error_abort);
3762 qemu_opt_set(opts, "path", filename, &error_abort);
3763 return opts;
3765 if (strstart(filename, "file:", &p)) {
3766 qemu_opt_set(opts, "backend", "file", &error_abort);
3767 qemu_opt_set(opts, "path", p, &error_abort);
3768 return opts;
3770 if (strstart(filename, "pipe:", &p)) {
3771 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3772 qemu_opt_set(opts, "path", p, &error_abort);
3773 return opts;
3775 if (strstart(filename, "tcp:", &p) ||
3776 strstart(filename, "telnet:", &p)) {
3777 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3778 host[0] = 0;
3779 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3780 goto fail;
3782 qemu_opt_set(opts, "backend", "socket", &error_abort);
3783 qemu_opt_set(opts, "host", host, &error_abort);
3784 qemu_opt_set(opts, "port", port, &error_abort);
3785 if (p[pos] == ',') {
3786 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3787 if (local_err) {
3788 error_report_err(local_err);
3789 goto fail;
3792 if (strstart(filename, "telnet:", &p))
3793 qemu_opt_set(opts, "telnet", "on", &error_abort);
3794 return opts;
3796 if (strstart(filename, "udp:", &p)) {
3797 qemu_opt_set(opts, "backend", "udp", &error_abort);
3798 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3799 host[0] = 0;
3800 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3801 goto fail;
3804 qemu_opt_set(opts, "host", host, &error_abort);
3805 qemu_opt_set(opts, "port", port, &error_abort);
3806 if (p[pos] == '@') {
3807 p += pos + 1;
3808 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3809 host[0] = 0;
3810 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3811 goto fail;
3814 qemu_opt_set(opts, "localaddr", host, &error_abort);
3815 qemu_opt_set(opts, "localport", port, &error_abort);
3817 return opts;
3819 if (strstart(filename, "unix:", &p)) {
3820 qemu_opt_set(opts, "backend", "socket", &error_abort);
3821 qemu_opts_do_parse(opts, p, "path", &local_err);
3822 if (local_err) {
3823 error_report_err(local_err);
3824 goto fail;
3826 return opts;
3828 if (strstart(filename, "/dev/parport", NULL) ||
3829 strstart(filename, "/dev/ppi", NULL)) {
3830 qemu_opt_set(opts, "backend", "parport", &error_abort);
3831 qemu_opt_set(opts, "path", filename, &error_abort);
3832 return opts;
3834 if (strstart(filename, "/dev/", NULL)) {
3835 qemu_opt_set(opts, "backend", "tty", &error_abort);
3836 qemu_opt_set(opts, "path", filename, &error_abort);
3837 return opts;
3840 fail:
3841 qemu_opts_del(opts);
3842 return NULL;
3845 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3847 const char *logfile = qemu_opt_get(opts, "logfile");
3849 backend->has_logfile = logfile != NULL;
3850 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3852 backend->has_logappend = true;
3853 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3857 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3858 Error **errp)
3860 const char *path = qemu_opt_get(opts, "path");
3861 ChardevFile *file;
3863 if (path == NULL) {
3864 error_setg(errp, "chardev: file: no filename given");
3865 return;
3867 file = backend->u.file.data = g_new0(ChardevFile, 1);
3868 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3869 file->out = g_strdup(path);
3871 file->has_append = true;
3872 file->append = qemu_opt_get_bool(opts, "append", false);
3875 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3876 Error **errp)
3878 ChardevStdio *stdio;
3880 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3881 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3882 stdio->has_signal = true;
3883 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3886 #ifdef HAVE_CHARDEV_SERIAL
3887 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3888 Error **errp)
3890 const char *device = qemu_opt_get(opts, "path");
3891 ChardevHostdev *serial;
3893 if (device == NULL) {
3894 error_setg(errp, "chardev: serial/tty: no device path given");
3895 return;
3897 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3898 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3899 serial->device = g_strdup(device);
3901 #endif
3903 #ifdef HAVE_CHARDEV_PARPORT
3904 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3905 Error **errp)
3907 const char *device = qemu_opt_get(opts, "path");
3908 ChardevHostdev *parallel;
3910 if (device == NULL) {
3911 error_setg(errp, "chardev: parallel: no device path given");
3912 return;
3914 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3915 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3916 parallel->device = g_strdup(device);
3918 #endif
3920 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3921 Error **errp)
3923 const char *device = qemu_opt_get(opts, "path");
3924 ChardevHostdev *dev;
3926 if (device == NULL) {
3927 error_setg(errp, "chardev: pipe: no device path given");
3928 return;
3930 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3931 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3932 dev->device = g_strdup(device);
3935 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3936 Error **errp)
3938 int val;
3939 ChardevRingbuf *ringbuf;
3941 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3942 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3944 val = qemu_opt_get_size(opts, "size", 0);
3945 if (val != 0) {
3946 ringbuf->has_size = true;
3947 ringbuf->size = val;
3951 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3952 Error **errp)
3954 const char *chardev = qemu_opt_get(opts, "chardev");
3955 ChardevMux *mux;
3957 if (chardev == NULL) {
3958 error_setg(errp, "chardev: mux: no chardev given");
3959 return;
3961 mux = backend->u.mux.data = g_new0(ChardevMux, 1);
3962 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
3963 mux->chardev = g_strdup(chardev);
3966 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3967 Error **errp)
3969 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3970 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3971 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3972 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3973 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3974 const char *path = qemu_opt_get(opts, "path");
3975 const char *host = qemu_opt_get(opts, "host");
3976 const char *port = qemu_opt_get(opts, "port");
3977 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3978 SocketAddress *addr;
3979 ChardevSocket *sock;
3981 if (!path) {
3982 if (!host) {
3983 error_setg(errp, "chardev: socket: no host given");
3984 return;
3986 if (!port) {
3987 error_setg(errp, "chardev: socket: no port given");
3988 return;
3990 } else {
3991 if (tls_creds) {
3992 error_setg(errp, "TLS can only be used over TCP socket");
3993 return;
3997 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
3998 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
4000 sock->has_nodelay = true;
4001 sock->nodelay = do_nodelay;
4002 sock->has_server = true;
4003 sock->server = is_listen;
4004 sock->has_telnet = true;
4005 sock->telnet = is_telnet;
4006 sock->has_wait = true;
4007 sock->wait = is_waitconnect;
4008 sock->has_reconnect = true;
4009 sock->reconnect = reconnect;
4010 sock->tls_creds = g_strdup(tls_creds);
4012 addr = g_new0(SocketAddress, 1);
4013 if (path) {
4014 UnixSocketAddress *q_unix;
4015 addr->type = SOCKET_ADDRESS_KIND_UNIX;
4016 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
4017 q_unix->path = g_strdup(path);
4018 } else {
4019 addr->type = SOCKET_ADDRESS_KIND_INET;
4020 addr->u.inet.data = g_new(InetSocketAddress, 1);
4021 *addr->u.inet.data = (InetSocketAddress) {
4022 .host = g_strdup(host),
4023 .port = g_strdup(port),
4024 .has_to = qemu_opt_get(opts, "to"),
4025 .to = qemu_opt_get_number(opts, "to", 0),
4026 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
4027 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
4028 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
4029 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
4032 sock->addr = addr;
4035 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
4036 Error **errp)
4038 const char *host = qemu_opt_get(opts, "host");
4039 const char *port = qemu_opt_get(opts, "port");
4040 const char *localaddr = qemu_opt_get(opts, "localaddr");
4041 const char *localport = qemu_opt_get(opts, "localport");
4042 bool has_local = false;
4043 SocketAddress *addr;
4044 ChardevUdp *udp;
4046 if (host == NULL || strlen(host) == 0) {
4047 host = "localhost";
4049 if (port == NULL || strlen(port) == 0) {
4050 error_setg(errp, "chardev: udp: remote port not specified");
4051 return;
4053 if (localport == NULL || strlen(localport) == 0) {
4054 localport = "0";
4055 } else {
4056 has_local = true;
4058 if (localaddr == NULL || strlen(localaddr) == 0) {
4059 localaddr = "";
4060 } else {
4061 has_local = true;
4064 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
4065 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
4067 addr = g_new0(SocketAddress, 1);
4068 addr->type = SOCKET_ADDRESS_KIND_INET;
4069 addr->u.inet.data = g_new(InetSocketAddress, 1);
4070 *addr->u.inet.data = (InetSocketAddress) {
4071 .host = g_strdup(host),
4072 .port = g_strdup(port),
4073 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
4074 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
4075 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
4076 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
4078 udp->remote = addr;
4080 if (has_local) {
4081 udp->has_local = true;
4082 addr = g_new0(SocketAddress, 1);
4083 addr->type = SOCKET_ADDRESS_KIND_INET;
4084 addr->u.inet.data = g_new(InetSocketAddress, 1);
4085 *addr->u.inet.data = (InetSocketAddress) {
4086 .host = g_strdup(localaddr),
4087 .port = g_strdup(localport),
4089 udp->local = addr;
4093 typedef struct CharDriver {
4094 const char *name;
4095 ChardevBackendKind kind;
4096 CharDriverParse *parse;
4097 CharDriverCreate *create;
4098 } CharDriver;
4100 static GSList *backends;
4102 void register_char_driver(const char *name, ChardevBackendKind kind,
4103 CharDriverParse *parse, CharDriverCreate *create)
4105 CharDriver *s;
4107 s = g_malloc0(sizeof(*s));
4108 s->name = g_strdup(name);
4109 s->kind = kind;
4110 s->parse = parse;
4111 s->create = create;
4113 backends = g_slist_append(backends, s);
4116 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
4117 Error **errp)
4119 Error *local_err = NULL;
4120 CharDriver *cd;
4121 CharDriverState *chr;
4122 GSList *i;
4123 ChardevReturn *ret = NULL;
4124 ChardevBackend *backend;
4125 const char *id = qemu_opts_id(opts);
4126 char *bid = NULL;
4128 if (qemu_opt_get(opts, "backend") == NULL) {
4129 error_setg(errp, "chardev: \"%s\" missing backend",
4130 qemu_opts_id(opts));
4131 goto err;
4134 if (is_help_option(qemu_opt_get(opts, "backend"))) {
4135 fprintf(stderr, "Available chardev backend types:\n");
4136 for (i = backends; i; i = i->next) {
4137 cd = i->data;
4138 fprintf(stderr, "%s\n", cd->name);
4140 exit(!is_help_option(qemu_opt_get(opts, "backend")));
4143 if (id == NULL) {
4144 error_setg(errp, "chardev: no id specified");
4145 goto err;
4148 for (i = backends; i; i = i->next) {
4149 cd = i->data;
4151 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
4152 break;
4155 if (i == NULL) {
4156 error_setg(errp, "chardev: backend \"%s\" not found",
4157 qemu_opt_get(opts, "backend"));
4158 goto err;
4161 backend = g_new0(ChardevBackend, 1);
4163 if (qemu_opt_get_bool(opts, "mux", 0)) {
4164 bid = g_strdup_printf("%s-base", id);
4167 chr = NULL;
4168 backend->type = cd->kind;
4169 if (cd->parse) {
4170 cd->parse(opts, backend, &local_err);
4171 if (local_err) {
4172 error_propagate(errp, local_err);
4173 goto qapi_out;
4175 } else {
4176 ChardevCommon *cc = g_new0(ChardevCommon, 1);
4177 qemu_chr_parse_common(opts, cc);
4178 backend->u.null.data = cc; /* Any ChardevCommon member would work */
4181 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
4182 if (!ret) {
4183 goto qapi_out;
4186 if (bid) {
4187 qapi_free_ChardevBackend(backend);
4188 qapi_free_ChardevReturn(ret);
4189 backend = g_new0(ChardevBackend, 1);
4190 backend->u.mux.data = g_new0(ChardevMux, 1);
4191 backend->type = CHARDEV_BACKEND_KIND_MUX;
4192 backend->u.mux.data->chardev = g_strdup(bid);
4193 ret = qmp_chardev_add(id, backend, errp);
4194 if (!ret) {
4195 chr = qemu_chr_find(bid);
4196 qemu_chr_delete(chr);
4197 chr = NULL;
4198 goto qapi_out;
4202 chr = qemu_chr_find(id);
4204 qapi_out:
4205 qapi_free_ChardevBackend(backend);
4206 qapi_free_ChardevReturn(ret);
4207 g_free(bid);
4208 return chr;
4210 err:
4211 return NULL;
4214 CharDriverState *qemu_chr_new_noreplay(const char *label, const char *filename)
4216 const char *p;
4217 CharDriverState *chr;
4218 QemuOpts *opts;
4219 Error *err = NULL;
4221 if (strstart(filename, "chardev:", &p)) {
4222 return qemu_chr_find(p);
4225 opts = qemu_chr_parse_compat(label, filename);
4226 if (!opts)
4227 return NULL;
4229 chr = qemu_chr_new_from_opts(opts, &err);
4230 if (err) {
4231 error_report_err(err);
4233 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
4234 monitor_init(chr, MONITOR_USE_READLINE);
4236 qemu_opts_del(opts);
4237 return chr;
4240 CharDriverState *qemu_chr_new(const char *label, const char *filename)
4242 CharDriverState *chr;
4243 chr = qemu_chr_new_noreplay(label, filename);
4244 if (chr) {
4245 chr->replay = replay_mode != REPLAY_MODE_NONE;
4246 if (chr->replay && chr->chr_ioctl) {
4247 fprintf(stderr,
4248 "Replay: ioctl is not supported for serial devices yet\n");
4250 replay_register_char_driver(chr);
4252 return chr;
4255 void qemu_chr_fe_set_echo(CharBackend *be, bool echo)
4257 CharDriverState *chr = be->chr;
4259 if (chr && chr->chr_set_echo) {
4260 chr->chr_set_echo(chr, echo);
4264 void qemu_chr_fe_set_open(CharBackend *be, int fe_open)
4266 CharDriverState *chr = be->chr;
4268 if (!chr) {
4269 return;
4272 if (be->fe_open == fe_open) {
4273 return;
4275 be->fe_open = fe_open;
4276 if (chr->chr_set_fe_open) {
4277 chr->chr_set_fe_open(chr, fe_open);
4281 guint qemu_chr_fe_add_watch(CharBackend *be, GIOCondition cond,
4282 GIOFunc func, void *user_data)
4284 CharDriverState *s = be->chr;
4285 GSource *src;
4286 guint tag;
4288 if (!s || s->chr_add_watch == NULL) {
4289 return 0;
4292 src = s->chr_add_watch(s, cond);
4293 if (!src) {
4294 return 0;
4297 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
4298 tag = g_source_attach(src, NULL);
4299 g_source_unref(src);
4301 return tag;
4304 void qemu_chr_fe_disconnect(CharBackend *be)
4306 CharDriverState *chr = be->chr;
4308 if (chr && chr->chr_disconnect) {
4309 chr->chr_disconnect(chr);
4313 static void qemu_chr_free_common(CharDriverState *chr)
4315 if (chr->be) {
4316 chr->be->chr = NULL;
4318 g_free(chr->filename);
4319 g_free(chr->label);
4320 if (chr->logfd != -1) {
4321 close(chr->logfd);
4323 qemu_mutex_destroy(&chr->chr_write_lock);
4324 g_free(chr);
4327 void qemu_chr_free(CharDriverState *chr)
4329 if (chr->chr_free) {
4330 chr->chr_free(chr);
4332 qemu_chr_free_common(chr);
4335 void qemu_chr_delete(CharDriverState *chr)
4337 QTAILQ_REMOVE(&chardevs, chr, next);
4338 qemu_chr_free(chr);
4341 ChardevInfoList *qmp_query_chardev(Error **errp)
4343 ChardevInfoList *chr_list = NULL;
4344 CharDriverState *chr;
4346 QTAILQ_FOREACH(chr, &chardevs, next) {
4347 ChardevInfoList *info = g_malloc0(sizeof(*info));
4348 info->value = g_malloc0(sizeof(*info->value));
4349 info->value->label = g_strdup(chr->label);
4350 info->value->filename = g_strdup(chr->filename);
4351 info->value->frontend_open = chr->be && chr->be->fe_open;
4353 info->next = chr_list;
4354 chr_list = info;
4357 return chr_list;
4360 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4362 ChardevBackendInfoList *backend_list = NULL;
4363 CharDriver *c = NULL;
4364 GSList *i = NULL;
4366 for (i = backends; i; i = i->next) {
4367 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4368 c = i->data;
4369 info->value = g_malloc0(sizeof(*info->value));
4370 info->value->name = g_strdup(c->name);
4372 info->next = backend_list;
4373 backend_list = info;
4376 return backend_list;
4379 CharDriverState *qemu_chr_find(const char *name)
4381 CharDriverState *chr;
4383 QTAILQ_FOREACH(chr, &chardevs, next) {
4384 if (strcmp(chr->label, name) != 0)
4385 continue;
4386 return chr;
4388 return NULL;
4391 QemuOptsList qemu_chardev_opts = {
4392 .name = "chardev",
4393 .implied_opt_name = "backend",
4394 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4395 .desc = {
4397 .name = "backend",
4398 .type = QEMU_OPT_STRING,
4400 .name = "path",
4401 .type = QEMU_OPT_STRING,
4403 .name = "host",
4404 .type = QEMU_OPT_STRING,
4406 .name = "port",
4407 .type = QEMU_OPT_STRING,
4409 .name = "localaddr",
4410 .type = QEMU_OPT_STRING,
4412 .name = "localport",
4413 .type = QEMU_OPT_STRING,
4415 .name = "to",
4416 .type = QEMU_OPT_NUMBER,
4418 .name = "ipv4",
4419 .type = QEMU_OPT_BOOL,
4421 .name = "ipv6",
4422 .type = QEMU_OPT_BOOL,
4424 .name = "wait",
4425 .type = QEMU_OPT_BOOL,
4427 .name = "server",
4428 .type = QEMU_OPT_BOOL,
4430 .name = "delay",
4431 .type = QEMU_OPT_BOOL,
4433 .name = "reconnect",
4434 .type = QEMU_OPT_NUMBER,
4436 .name = "telnet",
4437 .type = QEMU_OPT_BOOL,
4439 .name = "tls-creds",
4440 .type = QEMU_OPT_STRING,
4442 .name = "width",
4443 .type = QEMU_OPT_NUMBER,
4445 .name = "height",
4446 .type = QEMU_OPT_NUMBER,
4448 .name = "cols",
4449 .type = QEMU_OPT_NUMBER,
4451 .name = "rows",
4452 .type = QEMU_OPT_NUMBER,
4454 .name = "mux",
4455 .type = QEMU_OPT_BOOL,
4457 .name = "signal",
4458 .type = QEMU_OPT_BOOL,
4460 .name = "name",
4461 .type = QEMU_OPT_STRING,
4463 .name = "debug",
4464 .type = QEMU_OPT_NUMBER,
4466 .name = "size",
4467 .type = QEMU_OPT_SIZE,
4469 .name = "chardev",
4470 .type = QEMU_OPT_STRING,
4472 .name = "append",
4473 .type = QEMU_OPT_BOOL,
4475 .name = "logfile",
4476 .type = QEMU_OPT_STRING,
4478 .name = "logappend",
4479 .type = QEMU_OPT_BOOL,
4481 { /* end of list */ }
4485 #ifdef _WIN32
4487 static CharDriverState *qmp_chardev_open_file(const char *id,
4488 ChardevBackend *backend,
4489 ChardevReturn *ret,
4490 bool *be_opened,
4491 Error **errp)
4493 ChardevFile *file = backend->u.file.data;
4494 ChardevCommon *common = qapi_ChardevFile_base(file);
4495 HANDLE out;
4496 DWORD accessmode;
4497 DWORD flags;
4499 if (file->has_in) {
4500 error_setg(errp, "input file not supported");
4501 return NULL;
4504 if (file->has_append && file->append) {
4505 /* Append to file if it already exists. */
4506 accessmode = FILE_GENERIC_WRITE & ~FILE_WRITE_DATA;
4507 flags = OPEN_ALWAYS;
4508 } else {
4509 /* Truncate file if it already exists. */
4510 accessmode = GENERIC_WRITE;
4511 flags = CREATE_ALWAYS;
4514 out = CreateFile(file->out, accessmode, FILE_SHARE_READ, NULL, flags,
4515 FILE_ATTRIBUTE_NORMAL, NULL);
4516 if (out == INVALID_HANDLE_VALUE) {
4517 error_setg(errp, "open %s failed", file->out);
4518 return NULL;
4520 return qemu_chr_open_win_file(out, common, errp);
4523 static CharDriverState *qmp_chardev_open_serial(const char *id,
4524 ChardevBackend *backend,
4525 ChardevReturn *ret,
4526 bool *be_opened,
4527 Error **errp)
4529 ChardevHostdev *serial = backend->u.serial.data;
4530 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4531 return qemu_chr_open_win_path(serial->device, common, errp);
4534 #else /* WIN32 */
4536 static int qmp_chardev_open_file_source(char *src, int flags,
4537 Error **errp)
4539 int fd = -1;
4541 TFR(fd = qemu_open(src, flags, 0666));
4542 if (fd == -1) {
4543 error_setg_file_open(errp, errno, src);
4545 return fd;
4548 static CharDriverState *qmp_chardev_open_file(const char *id,
4549 ChardevBackend *backend,
4550 ChardevReturn *ret,
4551 bool *be_opened,
4552 Error **errp)
4554 ChardevFile *file = backend->u.file.data;
4555 ChardevCommon *common = qapi_ChardevFile_base(file);
4556 int flags, in = -1, out;
4558 flags = O_WRONLY | O_CREAT | O_BINARY;
4559 if (file->has_append && file->append) {
4560 flags |= O_APPEND;
4561 } else {
4562 flags |= O_TRUNC;
4565 out = qmp_chardev_open_file_source(file->out, flags, errp);
4566 if (out < 0) {
4567 return NULL;
4570 if (file->has_in) {
4571 flags = O_RDONLY;
4572 in = qmp_chardev_open_file_source(file->in, flags, errp);
4573 if (in < 0) {
4574 qemu_close(out);
4575 return NULL;
4579 return qemu_chr_open_fd(in, out, common, errp);
4582 #ifdef HAVE_CHARDEV_SERIAL
4583 static CharDriverState *qmp_chardev_open_serial(const char *id,
4584 ChardevBackend *backend,
4585 ChardevReturn *ret,
4586 bool *be_opened,
4587 Error **errp)
4589 ChardevHostdev *serial = backend->u.serial.data;
4590 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4591 int fd;
4593 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4594 if (fd < 0) {
4595 return NULL;
4597 qemu_set_nonblock(fd);
4598 return qemu_chr_open_tty_fd(fd, common, be_opened, errp);
4600 #endif
4602 #ifdef HAVE_CHARDEV_PARPORT
4603 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4604 ChardevBackend *backend,
4605 ChardevReturn *ret,
4606 bool *be_opened,
4607 Error **errp)
4609 ChardevHostdev *parallel = backend->u.parallel.data;
4610 ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
4611 int fd;
4613 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4614 if (fd < 0) {
4615 return NULL;
4617 return qemu_chr_open_pp_fd(fd, common, be_opened, errp);
4619 #endif
4621 #endif /* WIN32 */
4623 static gboolean socket_reconnect_timeout(gpointer opaque)
4625 CharDriverState *chr = opaque;
4626 TCPCharDriver *s = chr->opaque;
4627 QIOChannelSocket *sioc;
4629 s->reconnect_timer = 0;
4631 if (chr->be_open) {
4632 return false;
4635 sioc = qio_channel_socket_new();
4636 tcp_chr_set_client_ioc_name(chr, sioc);
4637 qio_channel_socket_connect_async(sioc, s->addr,
4638 qemu_chr_socket_connected,
4639 chr, NULL);
4641 return false;
4644 static CharDriverState *qmp_chardev_open_socket(const char *id,
4645 ChardevBackend *backend,
4646 ChardevReturn *ret,
4647 bool *be_opened,
4648 Error **errp)
4650 CharDriverState *chr;
4651 TCPCharDriver *s;
4652 ChardevSocket *sock = backend->u.socket.data;
4653 SocketAddress *addr = sock->addr;
4654 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4655 bool is_listen = sock->has_server ? sock->server : true;
4656 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4657 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4658 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4659 ChardevCommon *common = qapi_ChardevSocket_base(sock);
4660 QIOChannelSocket *sioc = NULL;
4662 chr = qemu_chr_alloc(common, errp);
4663 if (!chr) {
4664 return NULL;
4666 s = g_new0(TCPCharDriver, 1);
4668 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4669 s->is_listen = is_listen;
4670 s->is_telnet = is_telnet;
4671 s->do_nodelay = do_nodelay;
4672 if (sock->tls_creds) {
4673 Object *creds;
4674 creds = object_resolve_path_component(
4675 object_get_objects_root(), sock->tls_creds);
4676 if (!creds) {
4677 error_setg(errp, "No TLS credentials with id '%s'",
4678 sock->tls_creds);
4679 goto error;
4681 s->tls_creds = (QCryptoTLSCreds *)
4682 object_dynamic_cast(creds,
4683 TYPE_QCRYPTO_TLS_CREDS);
4684 if (!s->tls_creds) {
4685 error_setg(errp, "Object with id '%s' is not TLS credentials",
4686 sock->tls_creds);
4687 goto error;
4689 object_ref(OBJECT(s->tls_creds));
4690 if (is_listen) {
4691 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4692 error_setg(errp, "%s",
4693 "Expected TLS credentials for server endpoint");
4694 goto error;
4696 } else {
4697 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4698 error_setg(errp, "%s",
4699 "Expected TLS credentials for client endpoint");
4700 goto error;
4705 s->addr = QAPI_CLONE(SocketAddress, sock->addr);
4707 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_RECONNECTABLE);
4708 if (s->is_unix) {
4709 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_FD_PASS);
4712 chr->opaque = s;
4713 chr->chr_wait_connected = tcp_chr_wait_connected;
4714 chr->chr_write = tcp_chr_write;
4715 chr->chr_sync_read = tcp_chr_sync_read;
4716 chr->chr_free = tcp_chr_free;
4717 chr->chr_disconnect = tcp_chr_disconnect;
4718 chr->get_msgfds = tcp_get_msgfds;
4719 chr->set_msgfds = tcp_set_msgfds;
4720 chr->chr_add_client = tcp_chr_add_client;
4721 chr->chr_add_watch = tcp_chr_add_watch;
4722 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4723 /* be isn't opened until we get a connection */
4724 *be_opened = false;
4726 chr->filename = SocketAddress_to_str("disconnected:",
4727 addr, is_listen, is_telnet);
4729 if (is_listen) {
4730 if (is_telnet) {
4731 s->do_telnetopt = 1;
4733 } else if (reconnect > 0) {
4734 s->reconnect_time = reconnect;
4737 if (s->reconnect_time) {
4738 sioc = qio_channel_socket_new();
4739 tcp_chr_set_client_ioc_name(chr, sioc);
4740 qio_channel_socket_connect_async(sioc, s->addr,
4741 qemu_chr_socket_connected,
4742 chr, NULL);
4743 } else {
4744 if (s->is_listen) {
4745 char *name;
4746 sioc = qio_channel_socket_new();
4748 name = g_strdup_printf("chardev-tcp-listener-%s", chr->label);
4749 qio_channel_set_name(QIO_CHANNEL(sioc), name);
4750 g_free(name);
4752 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4753 goto error;
4755 s->listen_ioc = sioc;
4756 if (is_waitconnect &&
4757 qemu_chr_wait_connected(chr, errp) < 0) {
4758 goto error;
4760 if (!s->ioc) {
4761 s->listen_tag = qio_channel_add_watch(
4762 QIO_CHANNEL(s->listen_ioc), G_IO_IN,
4763 tcp_chr_accept, chr, NULL);
4765 } else if (qemu_chr_wait_connected(chr, errp) < 0) {
4766 goto error;
4770 return chr;
4772 error:
4773 if (sioc) {
4774 object_unref(OBJECT(sioc));
4776 if (s->tls_creds) {
4777 object_unref(OBJECT(s->tls_creds));
4779 g_free(s);
4780 qemu_chr_free_common(chr);
4781 return NULL;
4784 static CharDriverState *qmp_chardev_open_udp(const char *id,
4785 ChardevBackend *backend,
4786 ChardevReturn *ret,
4787 bool *be_opened,
4788 Error **errp)
4790 ChardevUdp *udp = backend->u.udp.data;
4791 ChardevCommon *common = qapi_ChardevUdp_base(udp);
4792 QIOChannelSocket *sioc = qio_channel_socket_new();
4793 char *name;
4794 CharDriverState *chr;
4796 if (qio_channel_socket_dgram_sync(sioc,
4797 udp->local, udp->remote,
4798 errp) < 0) {
4799 object_unref(OBJECT(sioc));
4800 return NULL;
4802 chr = qemu_chr_open_udp(sioc, common, be_opened, errp);
4804 name = g_strdup_printf("chardev-udp-%s", chr->label);
4805 qio_channel_set_name(QIO_CHANNEL(sioc), name);
4806 g_free(name);
4808 return chr;
4812 bool qemu_chr_has_feature(CharDriverState *chr,
4813 CharDriverFeature feature)
4815 return test_bit(feature, chr->features);
4818 void qemu_chr_set_feature(CharDriverState *chr,
4819 CharDriverFeature feature)
4821 return set_bit(feature, chr->features);
4824 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4825 Error **errp)
4827 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4828 CharDriverState *chr = NULL;
4829 Error *local_err = NULL;
4830 GSList *i;
4831 CharDriver *cd;
4832 bool be_opened = true;
4834 chr = qemu_chr_find(id);
4835 if (chr) {
4836 error_setg(errp, "Chardev '%s' already exists", id);
4837 goto out_error;
4840 for (i = backends; i; i = i->next) {
4841 cd = i->data;
4843 if (cd->kind == backend->type) {
4844 chr = cd->create(id, backend, ret, &be_opened, &local_err);
4845 if (local_err) {
4846 error_propagate(errp, local_err);
4847 goto out_error;
4849 break;
4853 if (chr == NULL) {
4854 assert(!i);
4855 error_setg(errp, "chardev backend not available");
4856 goto out_error;
4859 chr->label = g_strdup(id);
4860 if (!chr->filename) {
4861 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4863 if (be_opened) {
4864 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4866 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4867 return ret;
4869 out_error:
4870 g_free(ret);
4871 return NULL;
4874 void qmp_chardev_remove(const char *id, Error **errp)
4876 CharDriverState *chr;
4878 chr = qemu_chr_find(id);
4879 if (chr == NULL) {
4880 error_setg(errp, "Chardev '%s' not found", id);
4881 return;
4883 if (qemu_chr_is_busy(chr)) {
4884 error_setg(errp, "Chardev '%s' is busy", id);
4885 return;
4887 if (chr->replay) {
4888 error_setg(errp,
4889 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4890 return;
4892 qemu_chr_delete(chr);
4895 void qemu_chr_cleanup(void)
4897 CharDriverState *chr, *tmp;
4899 QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
4900 qemu_chr_delete(chr);
4904 static void register_types(void)
4906 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4907 qemu_chr_open_null);
4908 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4909 qemu_chr_parse_socket, qmp_chardev_open_socket);
4910 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4911 qmp_chardev_open_udp);
4912 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4913 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4914 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4915 qemu_chr_parse_file_out, qmp_chardev_open_file);
4916 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4917 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4918 #if defined HAVE_CHARDEV_SERIAL
4919 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4920 qemu_chr_parse_serial, qmp_chardev_open_serial);
4921 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4922 qemu_chr_parse_serial, qmp_chardev_open_serial);
4923 #endif
4924 #ifdef HAVE_CHARDEV_PARPORT
4925 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4926 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4927 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4928 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4929 #endif
4930 #ifdef HAVE_CHARDEV_PTY
4931 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4932 qemu_chr_open_pty);
4933 #endif
4934 #ifdef _WIN32
4935 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4936 qemu_chr_open_win_con);
4937 #endif
4938 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4939 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4940 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4941 qemu_chr_open_mux);
4942 /* Bug-compatibility: */
4943 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4944 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4945 /* this must be done after machine init, since we register FEs with muxes
4946 * as part of realize functions like serial_isa_realizefn when -nographic
4947 * is specified
4949 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4952 type_init(register_types);