ppc/pnv: add skeleton PowerNV platform
[qemu/rayw.git] / qemu-char.c
blob6dd779fc3c8c707257709e6d30941b9fc32e1802
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(QIOChannel *ioc,
1079 IOCanReadHandler *fd_can_read,
1080 QIOChannelFunc fd_read,
1081 gpointer user_data,
1082 GMainContext *context)
1084 IOWatchPoll *iwp;
1085 int tag;
1087 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs,
1088 sizeof(IOWatchPoll));
1089 iwp->fd_can_read = fd_can_read;
1090 iwp->opaque = user_data;
1091 iwp->ioc = ioc;
1092 iwp->fd_read = (GSourceFunc) fd_read;
1093 iwp->src = NULL;
1094 iwp->context = context;
1096 tag = g_source_attach(&iwp->parent, context);
1097 g_source_unref(&iwp->parent);
1098 return tag;
1101 static void io_remove_watch_poll(guint tag)
1103 GSource *source;
1104 IOWatchPoll *iwp;
1106 g_return_if_fail (tag > 0);
1108 source = g_main_context_find_source_by_id(NULL, tag);
1109 g_return_if_fail (source != NULL);
1111 iwp = io_watch_poll_from_source(source);
1112 if (iwp->src) {
1113 g_source_destroy(iwp->src);
1114 g_source_unref(iwp->src);
1115 iwp->src = NULL;
1117 g_source_destroy(&iwp->parent);
1120 static void remove_fd_in_watch(CharDriverState *chr)
1122 if (chr->fd_in_tag) {
1123 io_remove_watch_poll(chr->fd_in_tag);
1124 chr->fd_in_tag = 0;
1129 static int io_channel_send_full(QIOChannel *ioc,
1130 const void *buf, size_t len,
1131 int *fds, size_t nfds)
1133 size_t offset = 0;
1135 while (offset < len) {
1136 ssize_t ret = 0;
1137 struct iovec iov = { .iov_base = (char *)buf + offset,
1138 .iov_len = len - offset };
1140 ret = qio_channel_writev_full(
1141 ioc, &iov, 1,
1142 fds, nfds, NULL);
1143 if (ret == QIO_CHANNEL_ERR_BLOCK) {
1144 if (offset) {
1145 return offset;
1148 errno = EAGAIN;
1149 return -1;
1150 } else if (ret < 0) {
1151 errno = EINVAL;
1152 return -1;
1155 offset += ret;
1158 return offset;
1162 #ifndef _WIN32
1163 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
1165 return io_channel_send_full(ioc, buf, len, NULL, 0);
1169 typedef struct FDCharDriver {
1170 CharDriverState *chr;
1171 QIOChannel *ioc_in, *ioc_out;
1172 int max_size;
1173 } FDCharDriver;
1175 /* Called with chr_write_lock held. */
1176 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1178 FDCharDriver *s = chr->opaque;
1180 return io_channel_send(s->ioc_out, buf, len);
1183 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1185 CharDriverState *chr = opaque;
1186 FDCharDriver *s = chr->opaque;
1187 int len;
1188 uint8_t buf[READ_BUF_LEN];
1189 ssize_t ret;
1191 len = sizeof(buf);
1192 if (len > s->max_size) {
1193 len = s->max_size;
1195 if (len == 0) {
1196 return TRUE;
1199 ret = qio_channel_read(
1200 chan, (gchar *)buf, len, NULL);
1201 if (ret == 0) {
1202 remove_fd_in_watch(chr);
1203 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1204 return FALSE;
1206 if (ret > 0) {
1207 qemu_chr_be_write(chr, buf, ret);
1210 return TRUE;
1213 static int fd_chr_read_poll(void *opaque)
1215 CharDriverState *chr = opaque;
1216 FDCharDriver *s = chr->opaque;
1218 s->max_size = qemu_chr_be_can_write(chr);
1219 return s->max_size;
1222 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1224 FDCharDriver *s = chr->opaque;
1225 return qio_channel_create_watch(s->ioc_out, cond);
1228 static void fd_chr_update_read_handler(CharDriverState *chr,
1229 GMainContext *context)
1231 FDCharDriver *s = chr->opaque;
1233 remove_fd_in_watch(chr);
1234 if (s->ioc_in) {
1235 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
1236 fd_chr_read_poll,
1237 fd_chr_read, chr,
1238 context);
1242 static void fd_chr_free(struct CharDriverState *chr)
1244 FDCharDriver *s = chr->opaque;
1246 remove_fd_in_watch(chr);
1247 if (s->ioc_in) {
1248 object_unref(OBJECT(s->ioc_in));
1250 if (s->ioc_out) {
1251 object_unref(OBJECT(s->ioc_out));
1254 g_free(s);
1255 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1258 /* open a character device to a unix fd */
1259 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1260 ChardevCommon *backend, Error **errp)
1262 CharDriverState *chr;
1263 FDCharDriver *s;
1265 chr = qemu_chr_alloc(backend, errp);
1266 if (!chr) {
1267 return NULL;
1269 s = g_new0(FDCharDriver, 1);
1270 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1271 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1272 qemu_set_nonblock(fd_out);
1273 s->chr = chr;
1274 chr->opaque = s;
1275 chr->chr_add_watch = fd_chr_add_watch;
1276 chr->chr_write = fd_chr_write;
1277 chr->chr_update_read_handler = fd_chr_update_read_handler;
1278 chr->chr_free = fd_chr_free;
1280 return chr;
1283 static CharDriverState *qemu_chr_open_pipe(const char *id,
1284 ChardevBackend *backend,
1285 ChardevReturn *ret,
1286 bool *be_opened,
1287 Error **errp)
1289 ChardevHostdev *opts = backend->u.pipe.data;
1290 int fd_in, fd_out;
1291 char *filename_in;
1292 char *filename_out;
1293 const char *filename = opts->device;
1294 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1297 filename_in = g_strdup_printf("%s.in", filename);
1298 filename_out = g_strdup_printf("%s.out", filename);
1299 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1300 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1301 g_free(filename_in);
1302 g_free(filename_out);
1303 if (fd_in < 0 || fd_out < 0) {
1304 if (fd_in >= 0)
1305 close(fd_in);
1306 if (fd_out >= 0)
1307 close(fd_out);
1308 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1309 if (fd_in < 0) {
1310 error_setg_file_open(errp, errno, filename);
1311 return NULL;
1314 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1317 /* init terminal so that we can grab keys */
1318 static struct termios oldtty;
1319 static int old_fd0_flags;
1320 static bool stdio_in_use;
1321 static bool stdio_allow_signal;
1322 static bool stdio_echo_state;
1324 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1326 static void term_exit(void)
1328 tcsetattr (0, TCSANOW, &oldtty);
1329 fcntl(0, F_SETFL, old_fd0_flags);
1332 static void term_stdio_handler(int sig)
1334 /* restore echo after resume from suspend. */
1335 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1338 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1340 struct termios tty;
1342 stdio_echo_state = echo;
1343 tty = oldtty;
1344 if (!echo) {
1345 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1346 |INLCR|IGNCR|ICRNL|IXON);
1347 tty.c_oflag |= OPOST;
1348 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1349 tty.c_cflag &= ~(CSIZE|PARENB);
1350 tty.c_cflag |= CS8;
1351 tty.c_cc[VMIN] = 1;
1352 tty.c_cc[VTIME] = 0;
1354 if (!stdio_allow_signal)
1355 tty.c_lflag &= ~ISIG;
1357 tcsetattr (0, TCSANOW, &tty);
1360 static void qemu_chr_free_stdio(struct CharDriverState *chr)
1362 term_exit();
1363 fd_chr_free(chr);
1366 static CharDriverState *qemu_chr_open_stdio(const char *id,
1367 ChardevBackend *backend,
1368 ChardevReturn *ret,
1369 bool *be_opened,
1370 Error **errp)
1372 ChardevStdio *opts = backend->u.stdio.data;
1373 CharDriverState *chr;
1374 struct sigaction act;
1375 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1377 if (is_daemonized()) {
1378 error_setg(errp, "cannot use stdio with -daemonize");
1379 return NULL;
1382 if (stdio_in_use) {
1383 error_setg(errp, "cannot use stdio by multiple character devices");
1384 return NULL;
1387 stdio_in_use = true;
1388 old_fd0_flags = fcntl(0, F_GETFL);
1389 tcgetattr(0, &oldtty);
1390 qemu_set_nonblock(0);
1391 atexit(term_exit);
1393 memset(&act, 0, sizeof(act));
1394 act.sa_handler = term_stdio_handler;
1395 sigaction(SIGCONT, &act, NULL);
1397 chr = qemu_chr_open_fd(0, 1, common, errp);
1398 if (!chr) {
1399 return NULL;
1401 chr->chr_free = qemu_chr_free_stdio;
1402 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1403 if (opts->has_signal) {
1404 stdio_allow_signal = opts->signal;
1406 qemu_chr_set_echo_stdio(chr, false);
1408 return chr;
1411 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1412 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1413 || defined(__GLIBC__)
1415 #define HAVE_CHARDEV_SERIAL 1
1416 #define HAVE_CHARDEV_PTY 1
1418 typedef struct {
1419 QIOChannel *ioc;
1420 int read_bytes;
1422 /* Protected by the CharDriverState chr_write_lock. */
1423 int connected;
1424 guint timer_tag;
1425 guint open_tag;
1426 } PtyCharDriver;
1428 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1429 static void pty_chr_state(CharDriverState *chr, int connected);
1431 static gboolean pty_chr_timer(gpointer opaque)
1433 struct CharDriverState *chr = opaque;
1434 PtyCharDriver *s = chr->opaque;
1436 qemu_mutex_lock(&chr->chr_write_lock);
1437 s->timer_tag = 0;
1438 s->open_tag = 0;
1439 if (!s->connected) {
1440 /* Next poll ... */
1441 pty_chr_update_read_handler_locked(chr);
1443 qemu_mutex_unlock(&chr->chr_write_lock);
1444 return FALSE;
1447 /* Called with chr_write_lock held. */
1448 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1450 PtyCharDriver *s = chr->opaque;
1452 if (s->timer_tag) {
1453 g_source_remove(s->timer_tag);
1454 s->timer_tag = 0;
1457 if (ms == 1000) {
1458 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1459 } else {
1460 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1464 /* Called with chr_write_lock held. */
1465 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1467 PtyCharDriver *s = chr->opaque;
1468 GPollFD pfd;
1469 int rc;
1470 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1472 pfd.fd = fioc->fd;
1473 pfd.events = G_IO_OUT;
1474 pfd.revents = 0;
1475 do {
1476 rc = g_poll(&pfd, 1, 0);
1477 } while (rc == -1 && errno == EINTR);
1478 assert(rc >= 0);
1480 if (pfd.revents & G_IO_HUP) {
1481 pty_chr_state(chr, 0);
1482 } else {
1483 pty_chr_state(chr, 1);
1487 static void pty_chr_update_read_handler(CharDriverState *chr,
1488 GMainContext *context)
1490 qemu_mutex_lock(&chr->chr_write_lock);
1491 pty_chr_update_read_handler_locked(chr);
1492 qemu_mutex_unlock(&chr->chr_write_lock);
1495 /* Called with chr_write_lock held. */
1496 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1498 PtyCharDriver *s = chr->opaque;
1500 if (!s->connected) {
1501 /* guest sends data, check for (re-)connect */
1502 pty_chr_update_read_handler_locked(chr);
1503 if (!s->connected) {
1504 return 0;
1507 return io_channel_send(s->ioc, buf, len);
1510 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1512 PtyCharDriver *s = chr->opaque;
1513 if (!s->connected) {
1514 return NULL;
1516 return qio_channel_create_watch(s->ioc, cond);
1519 static int pty_chr_read_poll(void *opaque)
1521 CharDriverState *chr = opaque;
1522 PtyCharDriver *s = chr->opaque;
1524 s->read_bytes = qemu_chr_be_can_write(chr);
1525 return s->read_bytes;
1528 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1530 CharDriverState *chr = opaque;
1531 PtyCharDriver *s = chr->opaque;
1532 gsize len;
1533 uint8_t buf[READ_BUF_LEN];
1534 ssize_t ret;
1536 len = sizeof(buf);
1537 if (len > s->read_bytes)
1538 len = s->read_bytes;
1539 if (len == 0) {
1540 return TRUE;
1542 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1543 if (ret <= 0) {
1544 pty_chr_state(chr, 0);
1545 return FALSE;
1546 } else {
1547 pty_chr_state(chr, 1);
1548 qemu_chr_be_write(chr, buf, ret);
1550 return TRUE;
1553 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1555 CharDriverState *chr = opaque;
1556 PtyCharDriver *s = chr->opaque;
1558 s->open_tag = 0;
1559 qemu_chr_be_generic_open(chr);
1560 return FALSE;
1563 /* Called with chr_write_lock held. */
1564 static void pty_chr_state(CharDriverState *chr, int connected)
1566 PtyCharDriver *s = chr->opaque;
1568 if (!connected) {
1569 if (s->open_tag) {
1570 g_source_remove(s->open_tag);
1571 s->open_tag = 0;
1573 remove_fd_in_watch(chr);
1574 s->connected = 0;
1575 /* (re-)connect poll interval for idle guests: once per second.
1576 * We check more frequently in case the guests sends data to
1577 * the virtual device linked to our pty. */
1578 pty_chr_rearm_timer(chr, 1000);
1579 } else {
1580 if (s->timer_tag) {
1581 g_source_remove(s->timer_tag);
1582 s->timer_tag = 0;
1584 if (!s->connected) {
1585 g_assert(s->open_tag == 0);
1586 s->connected = 1;
1587 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1589 if (!chr->fd_in_tag) {
1590 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1591 pty_chr_read_poll,
1592 pty_chr_read,
1593 chr, NULL);
1598 static void pty_chr_free(struct CharDriverState *chr)
1600 PtyCharDriver *s = chr->opaque;
1602 qemu_mutex_lock(&chr->chr_write_lock);
1603 pty_chr_state(chr, 0);
1604 object_unref(OBJECT(s->ioc));
1605 if (s->timer_tag) {
1606 g_source_remove(s->timer_tag);
1607 s->timer_tag = 0;
1609 qemu_mutex_unlock(&chr->chr_write_lock);
1610 g_free(s);
1611 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1614 static CharDriverState *qemu_chr_open_pty(const char *id,
1615 ChardevBackend *backend,
1616 ChardevReturn *ret,
1617 bool *be_opened,
1618 Error **errp)
1620 CharDriverState *chr;
1621 PtyCharDriver *s;
1622 int master_fd, slave_fd;
1623 char pty_name[PATH_MAX];
1624 ChardevCommon *common = backend->u.pty.data;
1626 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1627 if (master_fd < 0) {
1628 error_setg_errno(errp, errno, "Failed to create PTY");
1629 return NULL;
1632 close(slave_fd);
1633 qemu_set_nonblock(master_fd);
1635 chr = qemu_chr_alloc(common, errp);
1636 if (!chr) {
1637 close(master_fd);
1638 return NULL;
1641 chr->filename = g_strdup_printf("pty:%s", pty_name);
1642 ret->pty = g_strdup(pty_name);
1643 ret->has_pty = true;
1645 fprintf(stderr, "char device redirected to %s (label %s)\n",
1646 pty_name, id);
1648 s = g_new0(PtyCharDriver, 1);
1649 chr->opaque = s;
1650 chr->chr_write = pty_chr_write;
1651 chr->chr_update_read_handler = pty_chr_update_read_handler;
1652 chr->chr_free = pty_chr_free;
1653 chr->chr_add_watch = pty_chr_add_watch;
1654 *be_opened = false;
1656 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1657 s->timer_tag = 0;
1659 return chr;
1662 static void tty_serial_init(int fd, int speed,
1663 int parity, int data_bits, int stop_bits)
1665 struct termios tty;
1666 speed_t spd;
1668 #if 0
1669 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1670 speed, parity, data_bits, stop_bits);
1671 #endif
1672 tcgetattr (fd, &tty);
1674 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1675 speed = speed * 10 / 11;
1676 do {
1677 check_speed(50);
1678 check_speed(75);
1679 check_speed(110);
1680 check_speed(134);
1681 check_speed(150);
1682 check_speed(200);
1683 check_speed(300);
1684 check_speed(600);
1685 check_speed(1200);
1686 check_speed(1800);
1687 check_speed(2400);
1688 check_speed(4800);
1689 check_speed(9600);
1690 check_speed(19200);
1691 check_speed(38400);
1692 /* Non-Posix values follow. They may be unsupported on some systems. */
1693 check_speed(57600);
1694 check_speed(115200);
1695 #ifdef B230400
1696 check_speed(230400);
1697 #endif
1698 #ifdef B460800
1699 check_speed(460800);
1700 #endif
1701 #ifdef B500000
1702 check_speed(500000);
1703 #endif
1704 #ifdef B576000
1705 check_speed(576000);
1706 #endif
1707 #ifdef B921600
1708 check_speed(921600);
1709 #endif
1710 #ifdef B1000000
1711 check_speed(1000000);
1712 #endif
1713 #ifdef B1152000
1714 check_speed(1152000);
1715 #endif
1716 #ifdef B1500000
1717 check_speed(1500000);
1718 #endif
1719 #ifdef B2000000
1720 check_speed(2000000);
1721 #endif
1722 #ifdef B2500000
1723 check_speed(2500000);
1724 #endif
1725 #ifdef B3000000
1726 check_speed(3000000);
1727 #endif
1728 #ifdef B3500000
1729 check_speed(3500000);
1730 #endif
1731 #ifdef B4000000
1732 check_speed(4000000);
1733 #endif
1734 spd = B115200;
1735 } while (0);
1737 cfsetispeed(&tty, spd);
1738 cfsetospeed(&tty, spd);
1740 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1741 |INLCR|IGNCR|ICRNL|IXON);
1742 tty.c_oflag |= OPOST;
1743 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1744 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1745 switch(data_bits) {
1746 default:
1747 case 8:
1748 tty.c_cflag |= CS8;
1749 break;
1750 case 7:
1751 tty.c_cflag |= CS7;
1752 break;
1753 case 6:
1754 tty.c_cflag |= CS6;
1755 break;
1756 case 5:
1757 tty.c_cflag |= CS5;
1758 break;
1760 switch(parity) {
1761 default:
1762 case 'N':
1763 break;
1764 case 'E':
1765 tty.c_cflag |= PARENB;
1766 break;
1767 case 'O':
1768 tty.c_cflag |= PARENB | PARODD;
1769 break;
1771 if (stop_bits == 2)
1772 tty.c_cflag |= CSTOPB;
1774 tcsetattr (fd, TCSANOW, &tty);
1777 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1779 FDCharDriver *s = chr->opaque;
1780 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1782 switch(cmd) {
1783 case CHR_IOCTL_SERIAL_SET_PARAMS:
1785 QEMUSerialSetParams *ssp = arg;
1786 tty_serial_init(fioc->fd,
1787 ssp->speed, ssp->parity,
1788 ssp->data_bits, ssp->stop_bits);
1790 break;
1791 case CHR_IOCTL_SERIAL_SET_BREAK:
1793 int enable = *(int *)arg;
1794 if (enable) {
1795 tcsendbreak(fioc->fd, 1);
1798 break;
1799 case CHR_IOCTL_SERIAL_GET_TIOCM:
1801 int sarg = 0;
1802 int *targ = (int *)arg;
1803 ioctl(fioc->fd, TIOCMGET, &sarg);
1804 *targ = 0;
1805 if (sarg & TIOCM_CTS)
1806 *targ |= CHR_TIOCM_CTS;
1807 if (sarg & TIOCM_CAR)
1808 *targ |= CHR_TIOCM_CAR;
1809 if (sarg & TIOCM_DSR)
1810 *targ |= CHR_TIOCM_DSR;
1811 if (sarg & TIOCM_RI)
1812 *targ |= CHR_TIOCM_RI;
1813 if (sarg & TIOCM_DTR)
1814 *targ |= CHR_TIOCM_DTR;
1815 if (sarg & TIOCM_RTS)
1816 *targ |= CHR_TIOCM_RTS;
1818 break;
1819 case CHR_IOCTL_SERIAL_SET_TIOCM:
1821 int sarg = *(int *)arg;
1822 int targ = 0;
1823 ioctl(fioc->fd, TIOCMGET, &targ);
1824 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1825 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1826 if (sarg & CHR_TIOCM_CTS)
1827 targ |= TIOCM_CTS;
1828 if (sarg & CHR_TIOCM_CAR)
1829 targ |= TIOCM_CAR;
1830 if (sarg & CHR_TIOCM_DSR)
1831 targ |= TIOCM_DSR;
1832 if (sarg & CHR_TIOCM_RI)
1833 targ |= TIOCM_RI;
1834 if (sarg & CHR_TIOCM_DTR)
1835 targ |= TIOCM_DTR;
1836 if (sarg & CHR_TIOCM_RTS)
1837 targ |= TIOCM_RTS;
1838 ioctl(fioc->fd, TIOCMSET, &targ);
1840 break;
1841 default:
1842 return -ENOTSUP;
1844 return 0;
1847 static void qemu_chr_free_tty(CharDriverState *chr)
1849 fd_chr_free(chr);
1852 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1853 ChardevCommon *backend,
1854 bool *be_opened,
1855 Error **errp)
1857 CharDriverState *chr;
1859 tty_serial_init(fd, 115200, 'N', 8, 1);
1860 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1861 if (!chr) {
1862 return NULL;
1864 chr->chr_ioctl = tty_serial_ioctl;
1865 chr->chr_free = qemu_chr_free_tty;
1866 return chr;
1868 #endif /* __linux__ || __sun__ */
1870 #if defined(__linux__)
1872 #define HAVE_CHARDEV_PARPORT 1
1874 typedef struct {
1875 int fd;
1876 int mode;
1877 } ParallelCharDriver;
1879 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1881 if (s->mode != mode) {
1882 int m = mode;
1883 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1884 return 0;
1885 s->mode = mode;
1887 return 1;
1890 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1892 ParallelCharDriver *drv = chr->opaque;
1893 int fd = drv->fd;
1894 uint8_t b;
1896 switch(cmd) {
1897 case CHR_IOCTL_PP_READ_DATA:
1898 if (ioctl(fd, PPRDATA, &b) < 0)
1899 return -ENOTSUP;
1900 *(uint8_t *)arg = b;
1901 break;
1902 case CHR_IOCTL_PP_WRITE_DATA:
1903 b = *(uint8_t *)arg;
1904 if (ioctl(fd, PPWDATA, &b) < 0)
1905 return -ENOTSUP;
1906 break;
1907 case CHR_IOCTL_PP_READ_CONTROL:
1908 if (ioctl(fd, PPRCONTROL, &b) < 0)
1909 return -ENOTSUP;
1910 /* Linux gives only the lowest bits, and no way to know data
1911 direction! For better compatibility set the fixed upper
1912 bits. */
1913 *(uint8_t *)arg = b | 0xc0;
1914 break;
1915 case CHR_IOCTL_PP_WRITE_CONTROL:
1916 b = *(uint8_t *)arg;
1917 if (ioctl(fd, PPWCONTROL, &b) < 0)
1918 return -ENOTSUP;
1919 break;
1920 case CHR_IOCTL_PP_READ_STATUS:
1921 if (ioctl(fd, PPRSTATUS, &b) < 0)
1922 return -ENOTSUP;
1923 *(uint8_t *)arg = b;
1924 break;
1925 case CHR_IOCTL_PP_DATA_DIR:
1926 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1927 return -ENOTSUP;
1928 break;
1929 case CHR_IOCTL_PP_EPP_READ_ADDR:
1930 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1931 struct ParallelIOArg *parg = arg;
1932 int n = read(fd, parg->buffer, parg->count);
1933 if (n != parg->count) {
1934 return -EIO;
1937 break;
1938 case CHR_IOCTL_PP_EPP_READ:
1939 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1940 struct ParallelIOArg *parg = arg;
1941 int n = read(fd, parg->buffer, parg->count);
1942 if (n != parg->count) {
1943 return -EIO;
1946 break;
1947 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1948 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1949 struct ParallelIOArg *parg = arg;
1950 int n = write(fd, parg->buffer, parg->count);
1951 if (n != parg->count) {
1952 return -EIO;
1955 break;
1956 case CHR_IOCTL_PP_EPP_WRITE:
1957 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1958 struct ParallelIOArg *parg = arg;
1959 int n = write(fd, parg->buffer, parg->count);
1960 if (n != parg->count) {
1961 return -EIO;
1964 break;
1965 default:
1966 return -ENOTSUP;
1968 return 0;
1971 static void pp_free(CharDriverState *chr)
1973 ParallelCharDriver *drv = chr->opaque;
1974 int fd = drv->fd;
1976 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1977 ioctl(fd, PPRELEASE);
1978 close(fd);
1979 g_free(drv);
1980 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1983 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1984 ChardevCommon *backend,
1985 bool *be_opened,
1986 Error **errp)
1988 CharDriverState *chr;
1989 ParallelCharDriver *drv;
1991 if (ioctl(fd, PPCLAIM) < 0) {
1992 error_setg_errno(errp, errno, "not a parallel port");
1993 close(fd);
1994 return NULL;
1997 chr = qemu_chr_alloc(backend, errp);
1998 if (!chr) {
1999 return NULL;
2002 drv = g_new0(ParallelCharDriver, 1);
2003 chr->opaque = drv;
2004 chr->chr_write = null_chr_write;
2005 chr->chr_ioctl = pp_ioctl;
2006 chr->chr_free = pp_free;
2008 drv->fd = fd;
2009 drv->mode = IEEE1284_MODE_COMPAT;
2011 return chr;
2013 #endif /* __linux__ */
2015 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
2017 #define HAVE_CHARDEV_PARPORT 1
2019 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2021 int fd = (int)(intptr_t)chr->opaque;
2022 uint8_t b;
2024 switch(cmd) {
2025 case CHR_IOCTL_PP_READ_DATA:
2026 if (ioctl(fd, PPIGDATA, &b) < 0)
2027 return -ENOTSUP;
2028 *(uint8_t *)arg = b;
2029 break;
2030 case CHR_IOCTL_PP_WRITE_DATA:
2031 b = *(uint8_t *)arg;
2032 if (ioctl(fd, PPISDATA, &b) < 0)
2033 return -ENOTSUP;
2034 break;
2035 case CHR_IOCTL_PP_READ_CONTROL:
2036 if (ioctl(fd, PPIGCTRL, &b) < 0)
2037 return -ENOTSUP;
2038 *(uint8_t *)arg = b;
2039 break;
2040 case CHR_IOCTL_PP_WRITE_CONTROL:
2041 b = *(uint8_t *)arg;
2042 if (ioctl(fd, PPISCTRL, &b) < 0)
2043 return -ENOTSUP;
2044 break;
2045 case CHR_IOCTL_PP_READ_STATUS:
2046 if (ioctl(fd, PPIGSTATUS, &b) < 0)
2047 return -ENOTSUP;
2048 *(uint8_t *)arg = b;
2049 break;
2050 default:
2051 return -ENOTSUP;
2053 return 0;
2056 static CharDriverState *qemu_chr_open_pp_fd(int fd,
2057 ChardevCommon *backend,
2058 bool *be_opened,
2059 Error **errp)
2061 CharDriverState *chr;
2063 chr = qemu_chr_alloc(backend, errp);
2064 if (!chr) {
2065 return NULL;
2067 chr->opaque = (void *)(intptr_t)fd;
2068 chr->chr_write = null_chr_write;
2069 chr->chr_ioctl = pp_ioctl;
2070 *be_opened = false;
2071 return chr;
2073 #endif
2075 #else /* _WIN32 */
2077 #define HAVE_CHARDEV_SERIAL 1
2079 typedef struct {
2080 int max_size;
2081 HANDLE hcom, hrecv, hsend;
2082 OVERLAPPED orecv;
2083 BOOL fpipe;
2084 DWORD len;
2086 /* Protected by the CharDriverState chr_write_lock. */
2087 OVERLAPPED osend;
2088 } WinCharState;
2090 typedef struct {
2091 HANDLE hStdIn;
2092 HANDLE hInputReadyEvent;
2093 HANDLE hInputDoneEvent;
2094 HANDLE hInputThread;
2095 uint8_t win_stdio_buf;
2096 } WinStdioCharState;
2098 #define NSENDBUF 2048
2099 #define NRECVBUF 2048
2100 #define MAXCONNECT 1
2101 #define NTIMEOUT 5000
2103 static int win_chr_poll(void *opaque);
2104 static int win_chr_pipe_poll(void *opaque);
2106 static void win_chr_free(CharDriverState *chr)
2108 WinCharState *s = chr->opaque;
2110 if (s->hsend) {
2111 CloseHandle(s->hsend);
2112 s->hsend = NULL;
2114 if (s->hrecv) {
2115 CloseHandle(s->hrecv);
2116 s->hrecv = NULL;
2118 if (s->hcom) {
2119 CloseHandle(s->hcom);
2120 s->hcom = NULL;
2122 if (s->fpipe)
2123 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2124 else
2125 qemu_del_polling_cb(win_chr_poll, chr);
2127 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2130 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
2132 WinCharState *s = chr->opaque;
2133 COMMCONFIG comcfg;
2134 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2135 COMSTAT comstat;
2136 DWORD size;
2137 DWORD err;
2139 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2140 if (!s->hsend) {
2141 error_setg(errp, "Failed CreateEvent");
2142 goto fail;
2144 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2145 if (!s->hrecv) {
2146 error_setg(errp, "Failed CreateEvent");
2147 goto fail;
2150 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2151 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2152 if (s->hcom == INVALID_HANDLE_VALUE) {
2153 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
2154 s->hcom = NULL;
2155 goto fail;
2158 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2159 error_setg(errp, "Failed SetupComm");
2160 goto fail;
2163 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2164 size = sizeof(COMMCONFIG);
2165 GetDefaultCommConfig(filename, &comcfg, &size);
2166 comcfg.dcb.DCBlength = sizeof(DCB);
2167 CommConfigDialog(filename, NULL, &comcfg);
2169 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2170 error_setg(errp, "Failed SetCommState");
2171 goto fail;
2174 if (!SetCommMask(s->hcom, EV_ERR)) {
2175 error_setg(errp, "Failed SetCommMask");
2176 goto fail;
2179 cto.ReadIntervalTimeout = MAXDWORD;
2180 if (!SetCommTimeouts(s->hcom, &cto)) {
2181 error_setg(errp, "Failed SetCommTimeouts");
2182 goto fail;
2185 if (!ClearCommError(s->hcom, &err, &comstat)) {
2186 error_setg(errp, "Failed ClearCommError");
2187 goto fail;
2189 qemu_add_polling_cb(win_chr_poll, chr);
2190 return 0;
2192 fail:
2193 win_chr_free(chr);
2194 return -1;
2197 /* Called with chr_write_lock held. */
2198 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2200 WinCharState *s = chr->opaque;
2201 DWORD len, ret, size, err;
2203 len = len1;
2204 ZeroMemory(&s->osend, sizeof(s->osend));
2205 s->osend.hEvent = s->hsend;
2206 while (len > 0) {
2207 if (s->hsend)
2208 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2209 else
2210 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2211 if (!ret) {
2212 err = GetLastError();
2213 if (err == ERROR_IO_PENDING) {
2214 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2215 if (ret) {
2216 buf += size;
2217 len -= size;
2218 } else {
2219 break;
2221 } else {
2222 break;
2224 } else {
2225 buf += size;
2226 len -= size;
2229 return len1 - len;
2232 static int win_chr_read_poll(CharDriverState *chr)
2234 WinCharState *s = chr->opaque;
2236 s->max_size = qemu_chr_be_can_write(chr);
2237 return s->max_size;
2240 static void win_chr_readfile(CharDriverState *chr)
2242 WinCharState *s = chr->opaque;
2243 int ret, err;
2244 uint8_t buf[READ_BUF_LEN];
2245 DWORD size;
2247 ZeroMemory(&s->orecv, sizeof(s->orecv));
2248 s->orecv.hEvent = s->hrecv;
2249 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2250 if (!ret) {
2251 err = GetLastError();
2252 if (err == ERROR_IO_PENDING) {
2253 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2257 if (size > 0) {
2258 qemu_chr_be_write(chr, buf, size);
2262 static void win_chr_read(CharDriverState *chr)
2264 WinCharState *s = chr->opaque;
2266 if (s->len > s->max_size)
2267 s->len = s->max_size;
2268 if (s->len == 0)
2269 return;
2271 win_chr_readfile(chr);
2274 static int win_chr_poll(void *opaque)
2276 CharDriverState *chr = opaque;
2277 WinCharState *s = chr->opaque;
2278 COMSTAT status;
2279 DWORD comerr;
2281 ClearCommError(s->hcom, &comerr, &status);
2282 if (status.cbInQue > 0) {
2283 s->len = status.cbInQue;
2284 win_chr_read_poll(chr);
2285 win_chr_read(chr);
2286 return 1;
2288 return 0;
2291 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2292 ChardevCommon *backend,
2293 Error **errp)
2295 CharDriverState *chr;
2296 WinCharState *s;
2298 chr = qemu_chr_alloc(backend, errp);
2299 if (!chr) {
2300 return NULL;
2302 s = g_new0(WinCharState, 1);
2303 chr->opaque = s;
2304 chr->chr_write = win_chr_write;
2305 chr->chr_free = win_chr_free;
2307 if (win_chr_init(chr, filename, errp) < 0) {
2308 g_free(s);
2309 qemu_chr_free_common(chr);
2310 return NULL;
2312 return chr;
2315 static int win_chr_pipe_poll(void *opaque)
2317 CharDriverState *chr = opaque;
2318 WinCharState *s = chr->opaque;
2319 DWORD size;
2321 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2322 if (size > 0) {
2323 s->len = size;
2324 win_chr_read_poll(chr);
2325 win_chr_read(chr);
2326 return 1;
2328 return 0;
2331 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2332 Error **errp)
2334 WinCharState *s = chr->opaque;
2335 OVERLAPPED ov;
2336 int ret;
2337 DWORD size;
2338 char *openname;
2340 s->fpipe = TRUE;
2342 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2343 if (!s->hsend) {
2344 error_setg(errp, "Failed CreateEvent");
2345 goto fail;
2347 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2348 if (!s->hrecv) {
2349 error_setg(errp, "Failed CreateEvent");
2350 goto fail;
2353 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2354 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2355 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2356 PIPE_WAIT,
2357 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2358 g_free(openname);
2359 if (s->hcom == INVALID_HANDLE_VALUE) {
2360 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2361 s->hcom = NULL;
2362 goto fail;
2365 ZeroMemory(&ov, sizeof(ov));
2366 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2367 ret = ConnectNamedPipe(s->hcom, &ov);
2368 if (ret) {
2369 error_setg(errp, "Failed ConnectNamedPipe");
2370 goto fail;
2373 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2374 if (!ret) {
2375 error_setg(errp, "Failed GetOverlappedResult");
2376 if (ov.hEvent) {
2377 CloseHandle(ov.hEvent);
2378 ov.hEvent = NULL;
2380 goto fail;
2383 if (ov.hEvent) {
2384 CloseHandle(ov.hEvent);
2385 ov.hEvent = NULL;
2387 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2388 return 0;
2390 fail:
2391 win_chr_free(chr);
2392 return -1;
2396 static CharDriverState *qemu_chr_open_pipe(const char *id,
2397 ChardevBackend *backend,
2398 ChardevReturn *ret,
2399 bool *be_opened,
2400 Error **errp)
2402 ChardevHostdev *opts = backend->u.pipe.data;
2403 const char *filename = opts->device;
2404 CharDriverState *chr;
2405 WinCharState *s;
2406 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2408 chr = qemu_chr_alloc(common, errp);
2409 if (!chr) {
2410 return NULL;
2412 s = g_new0(WinCharState, 1);
2413 chr->opaque = s;
2414 chr->chr_write = win_chr_write;
2415 chr->chr_free = win_chr_free;
2417 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2418 g_free(s);
2419 qemu_chr_free_common(chr);
2420 return NULL;
2422 return chr;
2425 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2426 ChardevCommon *backend,
2427 Error **errp)
2429 CharDriverState *chr;
2430 WinCharState *s;
2432 chr = qemu_chr_alloc(backend, errp);
2433 if (!chr) {
2434 return NULL;
2436 s = g_new0(WinCharState, 1);
2437 s->hcom = fd_out;
2438 chr->opaque = s;
2439 chr->chr_write = win_chr_write;
2440 return chr;
2443 static CharDriverState *qemu_chr_open_win_con(const char *id,
2444 ChardevBackend *backend,
2445 ChardevReturn *ret,
2446 bool *be_opened,
2447 Error **errp)
2449 ChardevCommon *common = backend->u.console.data;
2450 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2451 common, errp);
2454 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2456 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2457 DWORD dwSize;
2458 int len1;
2460 len1 = len;
2462 while (len1 > 0) {
2463 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2464 break;
2466 buf += dwSize;
2467 len1 -= dwSize;
2470 return len - len1;
2473 static void win_stdio_wait_func(void *opaque)
2475 CharDriverState *chr = opaque;
2476 WinStdioCharState *stdio = chr->opaque;
2477 INPUT_RECORD buf[4];
2478 int ret;
2479 DWORD dwSize;
2480 int i;
2482 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2484 if (!ret) {
2485 /* Avoid error storm */
2486 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2487 return;
2490 for (i = 0; i < dwSize; i++) {
2491 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2493 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2494 int j;
2495 if (kev->uChar.AsciiChar != 0) {
2496 for (j = 0; j < kev->wRepeatCount; j++) {
2497 if (qemu_chr_be_can_write(chr)) {
2498 uint8_t c = kev->uChar.AsciiChar;
2499 qemu_chr_be_write(chr, &c, 1);
2507 static DWORD WINAPI win_stdio_thread(LPVOID param)
2509 CharDriverState *chr = param;
2510 WinStdioCharState *stdio = chr->opaque;
2511 int ret;
2512 DWORD dwSize;
2514 while (1) {
2516 /* Wait for one byte */
2517 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2519 /* Exit in case of error, continue if nothing read */
2520 if (!ret) {
2521 break;
2523 if (!dwSize) {
2524 continue;
2527 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2528 if (stdio->win_stdio_buf == '\r') {
2529 continue;
2532 /* Signal the main thread and wait until the byte was eaten */
2533 if (!SetEvent(stdio->hInputReadyEvent)) {
2534 break;
2536 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2537 != WAIT_OBJECT_0) {
2538 break;
2542 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2543 return 0;
2546 static void win_stdio_thread_wait_func(void *opaque)
2548 CharDriverState *chr = opaque;
2549 WinStdioCharState *stdio = chr->opaque;
2551 if (qemu_chr_be_can_write(chr)) {
2552 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2555 SetEvent(stdio->hInputDoneEvent);
2558 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2560 WinStdioCharState *stdio = chr->opaque;
2561 DWORD dwMode = 0;
2563 GetConsoleMode(stdio->hStdIn, &dwMode);
2565 if (echo) {
2566 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2567 } else {
2568 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2572 static void win_stdio_free(CharDriverState *chr)
2574 WinStdioCharState *stdio = chr->opaque;
2576 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2577 CloseHandle(stdio->hInputReadyEvent);
2579 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2580 CloseHandle(stdio->hInputDoneEvent);
2582 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2583 TerminateThread(stdio->hInputThread, 0);
2586 g_free(chr->opaque);
2589 static CharDriverState *qemu_chr_open_stdio(const char *id,
2590 ChardevBackend *backend,
2591 ChardevReturn *ret,
2592 bool *be_opened,
2593 Error **errp)
2595 CharDriverState *chr;
2596 WinStdioCharState *stdio;
2597 DWORD dwMode;
2598 int is_console = 0;
2599 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio.data);
2601 chr = qemu_chr_alloc(common, errp);
2602 if (!chr) {
2603 return NULL;
2605 stdio = g_new0(WinStdioCharState, 1);
2607 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2608 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2609 error_setg(errp, "cannot open stdio: invalid handle");
2610 return NULL;
2613 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2615 chr->opaque = stdio;
2616 chr->chr_write = win_stdio_write;
2617 chr->chr_free = win_stdio_free;
2619 if (is_console) {
2620 if (qemu_add_wait_object(stdio->hStdIn,
2621 win_stdio_wait_func, chr)) {
2622 error_setg(errp, "qemu_add_wait_object: failed");
2623 goto err1;
2625 } else {
2626 DWORD dwId;
2628 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2629 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2630 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2631 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2632 error_setg(errp, "cannot create event");
2633 goto err2;
2635 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2636 win_stdio_thread_wait_func, chr)) {
2637 error_setg(errp, "qemu_add_wait_object: failed");
2638 goto err2;
2640 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2641 chr, 0, &dwId);
2643 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2644 error_setg(errp, "cannot create stdio thread");
2645 goto err3;
2649 dwMode |= ENABLE_LINE_INPUT;
2651 if (is_console) {
2652 /* set the terminal in raw mode */
2653 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2654 dwMode |= ENABLE_PROCESSED_INPUT;
2657 SetConsoleMode(stdio->hStdIn, dwMode);
2659 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2660 qemu_chr_set_echo_win_stdio(chr, false);
2662 return chr;
2664 err3:
2665 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2666 err2:
2667 CloseHandle(stdio->hInputReadyEvent);
2668 CloseHandle(stdio->hInputDoneEvent);
2669 err1:
2670 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2671 return NULL;
2673 #endif /* !_WIN32 */
2675 /***********************************************************/
2676 /* UDP Net console */
2678 typedef struct {
2679 QIOChannel *ioc;
2680 uint8_t buf[READ_BUF_LEN];
2681 int bufcnt;
2682 int bufptr;
2683 int max_size;
2684 } NetCharDriver;
2686 /* Called with chr_write_lock held. */
2687 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2689 NetCharDriver *s = chr->opaque;
2691 return qio_channel_write(
2692 s->ioc, (const char *)buf, len, NULL);
2695 static int udp_chr_read_poll(void *opaque)
2697 CharDriverState *chr = opaque;
2698 NetCharDriver *s = chr->opaque;
2700 s->max_size = qemu_chr_be_can_write(chr);
2702 /* If there were any stray characters in the queue process them
2703 * first
2705 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2706 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2707 s->bufptr++;
2708 s->max_size = qemu_chr_be_can_write(chr);
2710 return s->max_size;
2713 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2715 CharDriverState *chr = opaque;
2716 NetCharDriver *s = chr->opaque;
2717 ssize_t ret;
2719 if (s->max_size == 0) {
2720 return TRUE;
2722 ret = qio_channel_read(
2723 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2724 if (ret <= 0) {
2725 remove_fd_in_watch(chr);
2726 return FALSE;
2728 s->bufcnt = ret;
2730 s->bufptr = 0;
2731 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2732 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2733 s->bufptr++;
2734 s->max_size = qemu_chr_be_can_write(chr);
2737 return TRUE;
2740 static void udp_chr_update_read_handler(CharDriverState *chr,
2741 GMainContext *context)
2743 NetCharDriver *s = chr->opaque;
2745 remove_fd_in_watch(chr);
2746 if (s->ioc) {
2747 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2748 udp_chr_read_poll,
2749 udp_chr_read, chr,
2750 context);
2754 static void udp_chr_free(CharDriverState *chr)
2756 NetCharDriver *s = chr->opaque;
2758 remove_fd_in_watch(chr);
2759 if (s->ioc) {
2760 object_unref(OBJECT(s->ioc));
2762 g_free(s);
2763 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2766 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2767 ChardevCommon *backend,
2768 bool *be_opened,
2769 Error **errp)
2771 CharDriverState *chr = NULL;
2772 NetCharDriver *s = NULL;
2774 chr = qemu_chr_alloc(backend, errp);
2775 if (!chr) {
2776 return NULL;
2778 s = g_new0(NetCharDriver, 1);
2780 s->ioc = QIO_CHANNEL(sioc);
2781 s->bufcnt = 0;
2782 s->bufptr = 0;
2783 chr->opaque = s;
2784 chr->chr_write = udp_chr_write;
2785 chr->chr_update_read_handler = udp_chr_update_read_handler;
2786 chr->chr_free = udp_chr_free;
2787 /* be isn't opened until we get a connection */
2788 *be_opened = false;
2789 return chr;
2792 /***********************************************************/
2793 /* TCP Net console */
2795 typedef struct {
2796 QIOChannel *ioc; /* Client I/O channel */
2797 QIOChannelSocket *sioc; /* Client master channel */
2798 QIOChannelSocket *listen_ioc;
2799 guint listen_tag;
2800 QCryptoTLSCreds *tls_creds;
2801 int connected;
2802 int max_size;
2803 int do_telnetopt;
2804 int do_nodelay;
2805 int is_unix;
2806 int *read_msgfds;
2807 size_t read_msgfds_num;
2808 int *write_msgfds;
2809 size_t write_msgfds_num;
2811 SocketAddress *addr;
2812 bool is_listen;
2813 bool is_telnet;
2815 guint reconnect_timer;
2816 int64_t reconnect_time;
2817 bool connect_err_reported;
2818 } TCPCharDriver;
2820 static gboolean socket_reconnect_timeout(gpointer opaque);
2822 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2824 TCPCharDriver *s = chr->opaque;
2825 assert(s->connected == 0);
2826 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2827 socket_reconnect_timeout, chr);
2830 static void check_report_connect_error(CharDriverState *chr,
2831 Error *err)
2833 TCPCharDriver *s = chr->opaque;
2835 if (!s->connect_err_reported) {
2836 error_report("Unable to connect character device %s: %s",
2837 chr->label, error_get_pretty(err));
2838 s->connect_err_reported = true;
2840 qemu_chr_socket_restart_timer(chr);
2843 static gboolean tcp_chr_accept(QIOChannel *chan,
2844 GIOCondition cond,
2845 void *opaque);
2847 /* Called with chr_write_lock held. */
2848 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2850 TCPCharDriver *s = chr->opaque;
2851 if (s->connected) {
2852 int ret = io_channel_send_full(s->ioc, buf, len,
2853 s->write_msgfds,
2854 s->write_msgfds_num);
2856 /* free the written msgfds, no matter what */
2857 if (s->write_msgfds_num) {
2858 g_free(s->write_msgfds);
2859 s->write_msgfds = 0;
2860 s->write_msgfds_num = 0;
2863 return ret;
2864 } else {
2865 /* XXX: indicate an error ? */
2866 return len;
2870 static int tcp_chr_read_poll(void *opaque)
2872 CharDriverState *chr = opaque;
2873 TCPCharDriver *s = chr->opaque;
2874 if (!s->connected)
2875 return 0;
2876 s->max_size = qemu_chr_be_can_write(chr);
2877 return s->max_size;
2880 #define IAC 255
2881 #define IAC_BREAK 243
2882 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2883 TCPCharDriver *s,
2884 uint8_t *buf, int *size)
2886 /* Handle any telnet client's basic IAC options to satisfy char by
2887 * char mode with no echo. All IAC options will be removed from
2888 * the buf and the do_telnetopt variable will be used to track the
2889 * state of the width of the IAC information.
2891 * IAC commands come in sets of 3 bytes with the exception of the
2892 * "IAC BREAK" command and the double IAC.
2895 int i;
2896 int j = 0;
2898 for (i = 0; i < *size; i++) {
2899 if (s->do_telnetopt > 1) {
2900 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2901 /* Double IAC means send an IAC */
2902 if (j != i)
2903 buf[j] = buf[i];
2904 j++;
2905 s->do_telnetopt = 1;
2906 } else {
2907 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2908 /* Handle IAC break commands by sending a serial break */
2909 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2910 s->do_telnetopt++;
2912 s->do_telnetopt++;
2914 if (s->do_telnetopt >= 4) {
2915 s->do_telnetopt = 1;
2917 } else {
2918 if ((unsigned char)buf[i] == IAC) {
2919 s->do_telnetopt = 2;
2920 } else {
2921 if (j != i)
2922 buf[j] = buf[i];
2923 j++;
2927 *size = j;
2930 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2932 TCPCharDriver *s = chr->opaque;
2933 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2935 assert(num <= TCP_MAX_FDS);
2937 if (to_copy) {
2938 int i;
2940 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2942 /* Close unused fds */
2943 for (i = to_copy; i < s->read_msgfds_num; i++) {
2944 close(s->read_msgfds[i]);
2947 g_free(s->read_msgfds);
2948 s->read_msgfds = 0;
2949 s->read_msgfds_num = 0;
2952 return to_copy;
2955 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2957 TCPCharDriver *s = chr->opaque;
2959 /* clear old pending fd array */
2960 g_free(s->write_msgfds);
2961 s->write_msgfds = NULL;
2962 s->write_msgfds_num = 0;
2964 if (!s->connected ||
2965 !qio_channel_has_feature(s->ioc,
2966 QIO_CHANNEL_FEATURE_FD_PASS)) {
2967 return -1;
2970 if (num) {
2971 s->write_msgfds = g_new(int, num);
2972 memcpy(s->write_msgfds, fds, num * sizeof(int));
2975 s->write_msgfds_num = num;
2977 return 0;
2980 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2982 TCPCharDriver *s = chr->opaque;
2983 struct iovec iov = { .iov_base = buf, .iov_len = len };
2984 int ret;
2985 size_t i;
2986 int *msgfds = NULL;
2987 size_t msgfds_num = 0;
2989 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2990 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2991 &msgfds, &msgfds_num,
2992 NULL);
2993 } else {
2994 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2995 NULL, NULL,
2996 NULL);
2999 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3000 errno = EAGAIN;
3001 ret = -1;
3002 } else if (ret == -1) {
3003 errno = EIO;
3006 if (msgfds_num) {
3007 /* close and clean read_msgfds */
3008 for (i = 0; i < s->read_msgfds_num; i++) {
3009 close(s->read_msgfds[i]);
3012 if (s->read_msgfds_num) {
3013 g_free(s->read_msgfds);
3016 s->read_msgfds = msgfds;
3017 s->read_msgfds_num = msgfds_num;
3020 for (i = 0; i < s->read_msgfds_num; i++) {
3021 int fd = s->read_msgfds[i];
3022 if (fd < 0) {
3023 continue;
3026 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
3027 qemu_set_block(fd);
3029 #ifndef MSG_CMSG_CLOEXEC
3030 qemu_set_cloexec(fd);
3031 #endif
3034 return ret;
3037 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
3039 TCPCharDriver *s = chr->opaque;
3040 return qio_channel_create_watch(s->ioc, cond);
3043 static void tcp_chr_free_connection(CharDriverState *chr)
3045 TCPCharDriver *s = chr->opaque;
3046 int i;
3048 if (!s->connected) {
3049 return;
3052 if (s->read_msgfds_num) {
3053 for (i = 0; i < s->read_msgfds_num; i++) {
3054 close(s->read_msgfds[i]);
3056 g_free(s->read_msgfds);
3057 s->read_msgfds = NULL;
3058 s->read_msgfds_num = 0;
3061 tcp_set_msgfds(chr, NULL, 0);
3062 remove_fd_in_watch(chr);
3063 object_unref(OBJECT(s->sioc));
3064 s->sioc = NULL;
3065 object_unref(OBJECT(s->ioc));
3066 s->ioc = NULL;
3067 g_free(chr->filename);
3068 chr->filename = NULL;
3069 s->connected = 0;
3072 static void tcp_chr_disconnect(CharDriverState *chr)
3074 TCPCharDriver *s = chr->opaque;
3076 if (!s->connected) {
3077 return;
3080 tcp_chr_free_connection(chr);
3082 if (s->listen_ioc) {
3083 s->listen_tag = qio_channel_add_watch(
3084 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
3086 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
3087 s->is_listen, s->is_telnet);
3088 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3089 if (s->reconnect_time) {
3090 qemu_chr_socket_restart_timer(chr);
3094 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
3096 CharDriverState *chr = opaque;
3097 TCPCharDriver *s = chr->opaque;
3098 uint8_t buf[READ_BUF_LEN];
3099 int len, size;
3101 if (!s->connected || s->max_size <= 0) {
3102 return TRUE;
3104 len = sizeof(buf);
3105 if (len > s->max_size)
3106 len = s->max_size;
3107 size = tcp_chr_recv(chr, (void *)buf, len);
3108 if (size == 0 || size == -1) {
3109 /* connection closed */
3110 tcp_chr_disconnect(chr);
3111 } else if (size > 0) {
3112 if (s->do_telnetopt)
3113 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3114 if (size > 0)
3115 qemu_chr_be_write(chr, buf, size);
3118 return TRUE;
3121 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
3123 TCPCharDriver *s = chr->opaque;
3124 int size;
3126 if (!s->connected) {
3127 return 0;
3130 size = tcp_chr_recv(chr, (void *) buf, len);
3131 if (size == 0) {
3132 /* connection closed */
3133 tcp_chr_disconnect(chr);
3136 return size;
3139 static void tcp_chr_connect(void *opaque)
3141 CharDriverState *chr = opaque;
3142 TCPCharDriver *s = chr->opaque;
3144 g_free(chr->filename);
3145 chr->filename = sockaddr_to_str(
3146 &s->sioc->localAddr, s->sioc->localAddrLen,
3147 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
3148 s->is_listen, s->is_telnet);
3150 s->connected = 1;
3151 if (s->ioc) {
3152 chr->fd_in_tag = io_add_watch_poll(s->ioc,
3153 tcp_chr_read_poll,
3154 tcp_chr_read,
3155 chr, NULL);
3157 qemu_chr_be_generic_open(chr);
3160 static void tcp_chr_update_read_handler(CharDriverState *chr,
3161 GMainContext *context)
3163 TCPCharDriver *s = chr->opaque;
3165 if (!s->connected) {
3166 return;
3169 remove_fd_in_watch(chr);
3170 if (s->ioc) {
3171 chr->fd_in_tag = io_add_watch_poll(s->ioc,
3172 tcp_chr_read_poll,
3173 tcp_chr_read, chr,
3174 context);
3178 typedef struct {
3179 CharDriverState *chr;
3180 char buf[12];
3181 size_t buflen;
3182 } TCPCharDriverTelnetInit;
3184 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
3185 GIOCondition cond G_GNUC_UNUSED,
3186 gpointer user_data)
3188 TCPCharDriverTelnetInit *init = user_data;
3189 ssize_t ret;
3191 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
3192 if (ret < 0) {
3193 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3194 ret = 0;
3195 } else {
3196 tcp_chr_disconnect(init->chr);
3197 return FALSE;
3200 init->buflen -= ret;
3202 if (init->buflen == 0) {
3203 tcp_chr_connect(init->chr);
3204 return FALSE;
3207 memmove(init->buf, init->buf + ret, init->buflen);
3209 return TRUE;
3212 static void tcp_chr_telnet_init(CharDriverState *chr)
3214 TCPCharDriver *s = chr->opaque;
3215 TCPCharDriverTelnetInit *init =
3216 g_new0(TCPCharDriverTelnetInit, 1);
3217 size_t n = 0;
3219 init->chr = chr;
3220 init->buflen = 12;
3222 #define IACSET(x, a, b, c) \
3223 do { \
3224 x[n++] = a; \
3225 x[n++] = b; \
3226 x[n++] = c; \
3227 } while (0)
3229 /* Prep the telnet negotion to put telnet in binary,
3230 * no echo, single char mode */
3231 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3232 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3233 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3234 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3236 #undef IACSET
3238 qio_channel_add_watch(
3239 s->ioc, G_IO_OUT,
3240 tcp_chr_telnet_init_io,
3241 init, NULL);
3245 static void tcp_chr_tls_handshake(Object *source,
3246 Error *err,
3247 gpointer user_data)
3249 CharDriverState *chr = user_data;
3250 TCPCharDriver *s = chr->opaque;
3252 if (err) {
3253 tcp_chr_disconnect(chr);
3254 } else {
3255 if (s->do_telnetopt) {
3256 tcp_chr_telnet_init(chr);
3257 } else {
3258 tcp_chr_connect(chr);
3264 static void tcp_chr_tls_init(CharDriverState *chr)
3266 TCPCharDriver *s = chr->opaque;
3267 QIOChannelTLS *tioc;
3268 Error *err = NULL;
3270 if (s->is_listen) {
3271 tioc = qio_channel_tls_new_server(
3272 s->ioc, s->tls_creds,
3273 NULL, /* XXX Use an ACL */
3274 &err);
3275 } else {
3276 tioc = qio_channel_tls_new_client(
3277 s->ioc, s->tls_creds,
3278 s->addr->u.inet.data->host,
3279 &err);
3281 if (tioc == NULL) {
3282 error_free(err);
3283 tcp_chr_disconnect(chr);
3284 return;
3286 object_unref(OBJECT(s->ioc));
3287 s->ioc = QIO_CHANNEL(tioc);
3289 qio_channel_tls_handshake(tioc,
3290 tcp_chr_tls_handshake,
3291 chr,
3292 NULL);
3296 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3298 TCPCharDriver *s = chr->opaque;
3299 if (s->ioc != NULL) {
3300 return -1;
3303 s->ioc = QIO_CHANNEL(sioc);
3304 object_ref(OBJECT(sioc));
3305 s->sioc = sioc;
3306 object_ref(OBJECT(sioc));
3308 qio_channel_set_blocking(s->ioc, false, NULL);
3310 if (s->do_nodelay) {
3311 qio_channel_set_delay(s->ioc, false);
3313 if (s->listen_tag) {
3314 g_source_remove(s->listen_tag);
3315 s->listen_tag = 0;
3318 if (s->tls_creds) {
3319 tcp_chr_tls_init(chr);
3320 } else {
3321 if (s->do_telnetopt) {
3322 tcp_chr_telnet_init(chr);
3323 } else {
3324 tcp_chr_connect(chr);
3328 return 0;
3332 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3334 int ret;
3335 QIOChannelSocket *sioc;
3337 sioc = qio_channel_socket_new_fd(fd, NULL);
3338 if (!sioc) {
3339 return -1;
3341 ret = tcp_chr_new_client(chr, sioc);
3342 object_unref(OBJECT(sioc));
3343 return ret;
3346 static gboolean tcp_chr_accept(QIOChannel *channel,
3347 GIOCondition cond,
3348 void *opaque)
3350 CharDriverState *chr = opaque;
3351 QIOChannelSocket *sioc;
3353 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3354 NULL);
3355 if (!sioc) {
3356 return TRUE;
3359 tcp_chr_new_client(chr, sioc);
3361 object_unref(OBJECT(sioc));
3363 return TRUE;
3366 static int tcp_chr_wait_connected(CharDriverState *chr, Error **errp)
3368 TCPCharDriver *s = chr->opaque;
3369 QIOChannelSocket *sioc;
3371 /* It can't wait on s->connected, since it is set asynchronously
3372 * in TLS and telnet cases, only wait for an accepted socket */
3373 while (!s->ioc) {
3374 if (s->is_listen) {
3375 fprintf(stderr, "QEMU waiting for connection on: %s\n",
3376 chr->filename);
3377 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), true, NULL);
3378 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
3379 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
3380 } else {
3381 sioc = qio_channel_socket_new();
3382 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3383 object_unref(OBJECT(sioc));
3384 return -1;
3386 tcp_chr_new_client(chr, sioc);
3387 object_unref(OBJECT(sioc));
3391 return 0;
3394 static int qemu_chr_wait_connected(CharDriverState *chr, Error **errp)
3396 if (chr->chr_wait_connected) {
3397 return chr->chr_wait_connected(chr, errp);
3400 return 0;
3403 int qemu_chr_fe_wait_connected(CharBackend *be, Error **errp)
3405 if (!be->chr) {
3406 error_setg(errp, "missing associated backend");
3407 return -1;
3410 return qemu_chr_wait_connected(be->chr, errp);
3413 static void tcp_chr_free(CharDriverState *chr)
3415 TCPCharDriver *s = chr->opaque;
3417 tcp_chr_free_connection(chr);
3419 if (s->reconnect_timer) {
3420 g_source_remove(s->reconnect_timer);
3421 s->reconnect_timer = 0;
3423 qapi_free_SocketAddress(s->addr);
3424 if (s->listen_tag) {
3425 g_source_remove(s->listen_tag);
3426 s->listen_tag = 0;
3428 if (s->listen_ioc) {
3429 object_unref(OBJECT(s->listen_ioc));
3431 if (s->tls_creds) {
3432 object_unref(OBJECT(s->tls_creds));
3434 g_free(s);
3435 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3439 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3441 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3442 CharDriverState *chr = opaque;
3443 TCPCharDriver *s = chr->opaque;
3445 if (err) {
3446 check_report_connect_error(chr, err);
3447 object_unref(src);
3448 return;
3451 s->connect_err_reported = false;
3452 tcp_chr_new_client(chr, sioc);
3453 object_unref(OBJECT(sioc));
3457 /*********************************************************/
3458 /* Ring buffer chardev */
3460 typedef struct {
3461 size_t size;
3462 size_t prod;
3463 size_t cons;
3464 uint8_t *cbuf;
3465 } RingBufCharDriver;
3467 static size_t ringbuf_count(const CharDriverState *chr)
3469 const RingBufCharDriver *d = chr->opaque;
3471 return d->prod - d->cons;
3474 /* Called with chr_write_lock held. */
3475 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3477 RingBufCharDriver *d = chr->opaque;
3478 int i;
3480 if (!buf || (len < 0)) {
3481 return -1;
3484 for (i = 0; i < len; i++ ) {
3485 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3486 if (d->prod - d->cons > d->size) {
3487 d->cons = d->prod - d->size;
3491 return len;
3494 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3496 RingBufCharDriver *d = chr->opaque;
3497 int i;
3499 qemu_mutex_lock(&chr->chr_write_lock);
3500 for (i = 0; i < len && d->cons != d->prod; i++) {
3501 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3503 qemu_mutex_unlock(&chr->chr_write_lock);
3505 return i;
3508 static void ringbuf_chr_free(struct CharDriverState *chr)
3510 RingBufCharDriver *d = chr->opaque;
3512 g_free(d->cbuf);
3513 g_free(d);
3514 chr->opaque = NULL;
3517 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3518 ChardevBackend *backend,
3519 ChardevReturn *ret,
3520 bool *be_opened,
3521 Error **errp)
3523 ChardevRingbuf *opts = backend->u.ringbuf.data;
3524 ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
3525 CharDriverState *chr;
3526 RingBufCharDriver *d;
3528 chr = qemu_chr_alloc(common, errp);
3529 if (!chr) {
3530 return NULL;
3532 d = g_malloc(sizeof(*d));
3534 d->size = opts->has_size ? opts->size : 65536;
3536 /* The size must be power of 2 */
3537 if (d->size & (d->size - 1)) {
3538 error_setg(errp, "size of ringbuf chardev must be power of two");
3539 goto fail;
3542 d->prod = 0;
3543 d->cons = 0;
3544 d->cbuf = g_malloc0(d->size);
3546 chr->opaque = d;
3547 chr->chr_write = ringbuf_chr_write;
3548 chr->chr_free = ringbuf_chr_free;
3550 return chr;
3552 fail:
3553 g_free(d);
3554 qemu_chr_free_common(chr);
3555 return NULL;
3558 bool chr_is_ringbuf(const CharDriverState *chr)
3560 return chr->chr_write == ringbuf_chr_write;
3563 void qmp_ringbuf_write(const char *device, const char *data,
3564 bool has_format, enum DataFormat format,
3565 Error **errp)
3567 CharDriverState *chr;
3568 const uint8_t *write_data;
3569 int ret;
3570 gsize write_count;
3572 chr = qemu_chr_find(device);
3573 if (!chr) {
3574 error_setg(errp, "Device '%s' not found", device);
3575 return;
3578 if (!chr_is_ringbuf(chr)) {
3579 error_setg(errp,"%s is not a ringbuf device", device);
3580 return;
3583 if (has_format && (format == DATA_FORMAT_BASE64)) {
3584 write_data = qbase64_decode(data, -1,
3585 &write_count,
3586 errp);
3587 if (!write_data) {
3588 return;
3590 } else {
3591 write_data = (uint8_t *)data;
3592 write_count = strlen(data);
3595 ret = ringbuf_chr_write(chr, write_data, write_count);
3597 if (write_data != (uint8_t *)data) {
3598 g_free((void *)write_data);
3601 if (ret < 0) {
3602 error_setg(errp, "Failed to write to device %s", device);
3603 return;
3607 char *qmp_ringbuf_read(const char *device, int64_t size,
3608 bool has_format, enum DataFormat format,
3609 Error **errp)
3611 CharDriverState *chr;
3612 uint8_t *read_data;
3613 size_t count;
3614 char *data;
3616 chr = qemu_chr_find(device);
3617 if (!chr) {
3618 error_setg(errp, "Device '%s' not found", device);
3619 return NULL;
3622 if (!chr_is_ringbuf(chr)) {
3623 error_setg(errp,"%s is not a ringbuf device", device);
3624 return NULL;
3627 if (size <= 0) {
3628 error_setg(errp, "size must be greater than zero");
3629 return NULL;
3632 count = ringbuf_count(chr);
3633 size = size > count ? count : size;
3634 read_data = g_malloc(size + 1);
3636 ringbuf_chr_read(chr, read_data, size);
3638 if (has_format && (format == DATA_FORMAT_BASE64)) {
3639 data = g_base64_encode(read_data, size);
3640 g_free(read_data);
3641 } else {
3643 * FIXME should read only complete, valid UTF-8 characters up
3644 * to @size bytes. Invalid sequences should be replaced by a
3645 * suitable replacement character. Except when (and only
3646 * when) ring buffer lost characters since last read, initial
3647 * continuation characters should be dropped.
3649 read_data[size] = 0;
3650 data = (char *)read_data;
3653 return data;
3656 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3658 char host[65], port[33], width[8], height[8];
3659 int pos;
3660 const char *p;
3661 QemuOpts *opts;
3662 Error *local_err = NULL;
3664 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3665 if (local_err) {
3666 error_report_err(local_err);
3667 return NULL;
3670 if (strstart(filename, "mon:", &p)) {
3671 filename = p;
3672 qemu_opt_set(opts, "mux", "on", &error_abort);
3673 if (strcmp(filename, "stdio") == 0) {
3674 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3675 * but pass it to the guest. Handle this only for compat syntax,
3676 * for -chardev syntax we have special option for this.
3677 * This is what -nographic did, redirecting+muxing serial+monitor
3678 * to stdio causing Ctrl+C to be passed to guest. */
3679 qemu_opt_set(opts, "signal", "off", &error_abort);
3683 if (strcmp(filename, "null") == 0 ||
3684 strcmp(filename, "pty") == 0 ||
3685 strcmp(filename, "msmouse") == 0 ||
3686 strcmp(filename, "braille") == 0 ||
3687 strcmp(filename, "testdev") == 0 ||
3688 strcmp(filename, "stdio") == 0) {
3689 qemu_opt_set(opts, "backend", filename, &error_abort);
3690 return opts;
3692 if (strstart(filename, "vc", &p)) {
3693 qemu_opt_set(opts, "backend", "vc", &error_abort);
3694 if (*p == ':') {
3695 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3696 /* pixels */
3697 qemu_opt_set(opts, "width", width, &error_abort);
3698 qemu_opt_set(opts, "height", height, &error_abort);
3699 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3700 /* chars */
3701 qemu_opt_set(opts, "cols", width, &error_abort);
3702 qemu_opt_set(opts, "rows", height, &error_abort);
3703 } else {
3704 goto fail;
3707 return opts;
3709 if (strcmp(filename, "con:") == 0) {
3710 qemu_opt_set(opts, "backend", "console", &error_abort);
3711 return opts;
3713 if (strstart(filename, "COM", NULL)) {
3714 qemu_opt_set(opts, "backend", "serial", &error_abort);
3715 qemu_opt_set(opts, "path", filename, &error_abort);
3716 return opts;
3718 if (strstart(filename, "file:", &p)) {
3719 qemu_opt_set(opts, "backend", "file", &error_abort);
3720 qemu_opt_set(opts, "path", p, &error_abort);
3721 return opts;
3723 if (strstart(filename, "pipe:", &p)) {
3724 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3725 qemu_opt_set(opts, "path", p, &error_abort);
3726 return opts;
3728 if (strstart(filename, "tcp:", &p) ||
3729 strstart(filename, "telnet:", &p)) {
3730 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3731 host[0] = 0;
3732 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3733 goto fail;
3735 qemu_opt_set(opts, "backend", "socket", &error_abort);
3736 qemu_opt_set(opts, "host", host, &error_abort);
3737 qemu_opt_set(opts, "port", port, &error_abort);
3738 if (p[pos] == ',') {
3739 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3740 if (local_err) {
3741 error_report_err(local_err);
3742 goto fail;
3745 if (strstart(filename, "telnet:", &p))
3746 qemu_opt_set(opts, "telnet", "on", &error_abort);
3747 return opts;
3749 if (strstart(filename, "udp:", &p)) {
3750 qemu_opt_set(opts, "backend", "udp", &error_abort);
3751 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3752 host[0] = 0;
3753 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3754 goto fail;
3757 qemu_opt_set(opts, "host", host, &error_abort);
3758 qemu_opt_set(opts, "port", port, &error_abort);
3759 if (p[pos] == '@') {
3760 p += pos + 1;
3761 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3762 host[0] = 0;
3763 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3764 goto fail;
3767 qemu_opt_set(opts, "localaddr", host, &error_abort);
3768 qemu_opt_set(opts, "localport", port, &error_abort);
3770 return opts;
3772 if (strstart(filename, "unix:", &p)) {
3773 qemu_opt_set(opts, "backend", "socket", &error_abort);
3774 qemu_opts_do_parse(opts, p, "path", &local_err);
3775 if (local_err) {
3776 error_report_err(local_err);
3777 goto fail;
3779 return opts;
3781 if (strstart(filename, "/dev/parport", NULL) ||
3782 strstart(filename, "/dev/ppi", NULL)) {
3783 qemu_opt_set(opts, "backend", "parport", &error_abort);
3784 qemu_opt_set(opts, "path", filename, &error_abort);
3785 return opts;
3787 if (strstart(filename, "/dev/", NULL)) {
3788 qemu_opt_set(opts, "backend", "tty", &error_abort);
3789 qemu_opt_set(opts, "path", filename, &error_abort);
3790 return opts;
3793 fail:
3794 qemu_opts_del(opts);
3795 return NULL;
3798 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3800 const char *logfile = qemu_opt_get(opts, "logfile");
3802 backend->has_logfile = logfile != NULL;
3803 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3805 backend->has_logappend = true;
3806 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3810 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3811 Error **errp)
3813 const char *path = qemu_opt_get(opts, "path");
3814 ChardevFile *file;
3816 if (path == NULL) {
3817 error_setg(errp, "chardev: file: no filename given");
3818 return;
3820 file = backend->u.file.data = g_new0(ChardevFile, 1);
3821 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3822 file->out = g_strdup(path);
3824 file->has_append = true;
3825 file->append = qemu_opt_get_bool(opts, "append", false);
3828 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3829 Error **errp)
3831 ChardevStdio *stdio;
3833 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3834 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3835 stdio->has_signal = true;
3836 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3839 #ifdef HAVE_CHARDEV_SERIAL
3840 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3841 Error **errp)
3843 const char *device = qemu_opt_get(opts, "path");
3844 ChardevHostdev *serial;
3846 if (device == NULL) {
3847 error_setg(errp, "chardev: serial/tty: no device path given");
3848 return;
3850 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3851 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3852 serial->device = g_strdup(device);
3854 #endif
3856 #ifdef HAVE_CHARDEV_PARPORT
3857 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3858 Error **errp)
3860 const char *device = qemu_opt_get(opts, "path");
3861 ChardevHostdev *parallel;
3863 if (device == NULL) {
3864 error_setg(errp, "chardev: parallel: no device path given");
3865 return;
3867 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3868 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3869 parallel->device = g_strdup(device);
3871 #endif
3873 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3874 Error **errp)
3876 const char *device = qemu_opt_get(opts, "path");
3877 ChardevHostdev *dev;
3879 if (device == NULL) {
3880 error_setg(errp, "chardev: pipe: no device path given");
3881 return;
3883 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3884 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3885 dev->device = g_strdup(device);
3888 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3889 Error **errp)
3891 int val;
3892 ChardevRingbuf *ringbuf;
3894 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3895 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3897 val = qemu_opt_get_size(opts, "size", 0);
3898 if (val != 0) {
3899 ringbuf->has_size = true;
3900 ringbuf->size = val;
3904 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3905 Error **errp)
3907 const char *chardev = qemu_opt_get(opts, "chardev");
3908 ChardevMux *mux;
3910 if (chardev == NULL) {
3911 error_setg(errp, "chardev: mux: no chardev given");
3912 return;
3914 mux = backend->u.mux.data = g_new0(ChardevMux, 1);
3915 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
3916 mux->chardev = g_strdup(chardev);
3919 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3920 Error **errp)
3922 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3923 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3924 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3925 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3926 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3927 const char *path = qemu_opt_get(opts, "path");
3928 const char *host = qemu_opt_get(opts, "host");
3929 const char *port = qemu_opt_get(opts, "port");
3930 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3931 SocketAddress *addr;
3932 ChardevSocket *sock;
3934 if (!path) {
3935 if (!host) {
3936 error_setg(errp, "chardev: socket: no host given");
3937 return;
3939 if (!port) {
3940 error_setg(errp, "chardev: socket: no port given");
3941 return;
3943 } else {
3944 if (tls_creds) {
3945 error_setg(errp, "TLS can only be used over TCP socket");
3946 return;
3950 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
3951 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
3953 sock->has_nodelay = true;
3954 sock->nodelay = do_nodelay;
3955 sock->has_server = true;
3956 sock->server = is_listen;
3957 sock->has_telnet = true;
3958 sock->telnet = is_telnet;
3959 sock->has_wait = true;
3960 sock->wait = is_waitconnect;
3961 sock->has_reconnect = true;
3962 sock->reconnect = reconnect;
3963 sock->tls_creds = g_strdup(tls_creds);
3965 addr = g_new0(SocketAddress, 1);
3966 if (path) {
3967 UnixSocketAddress *q_unix;
3968 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3969 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
3970 q_unix->path = g_strdup(path);
3971 } else {
3972 addr->type = SOCKET_ADDRESS_KIND_INET;
3973 addr->u.inet.data = g_new(InetSocketAddress, 1);
3974 *addr->u.inet.data = (InetSocketAddress) {
3975 .host = g_strdup(host),
3976 .port = g_strdup(port),
3977 .has_to = qemu_opt_get(opts, "to"),
3978 .to = qemu_opt_get_number(opts, "to", 0),
3979 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3980 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3981 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3982 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3985 sock->addr = addr;
3988 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3989 Error **errp)
3991 const char *host = qemu_opt_get(opts, "host");
3992 const char *port = qemu_opt_get(opts, "port");
3993 const char *localaddr = qemu_opt_get(opts, "localaddr");
3994 const char *localport = qemu_opt_get(opts, "localport");
3995 bool has_local = false;
3996 SocketAddress *addr;
3997 ChardevUdp *udp;
3999 if (host == NULL || strlen(host) == 0) {
4000 host = "localhost";
4002 if (port == NULL || strlen(port) == 0) {
4003 error_setg(errp, "chardev: udp: remote port not specified");
4004 return;
4006 if (localport == NULL || strlen(localport) == 0) {
4007 localport = "0";
4008 } else {
4009 has_local = true;
4011 if (localaddr == NULL || strlen(localaddr) == 0) {
4012 localaddr = "";
4013 } else {
4014 has_local = true;
4017 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
4018 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
4020 addr = g_new0(SocketAddress, 1);
4021 addr->type = SOCKET_ADDRESS_KIND_INET;
4022 addr->u.inet.data = g_new(InetSocketAddress, 1);
4023 *addr->u.inet.data = (InetSocketAddress) {
4024 .host = g_strdup(host),
4025 .port = g_strdup(port),
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),
4031 udp->remote = addr;
4033 if (has_local) {
4034 udp->has_local = true;
4035 addr = g_new0(SocketAddress, 1);
4036 addr->type = SOCKET_ADDRESS_KIND_INET;
4037 addr->u.inet.data = g_new(InetSocketAddress, 1);
4038 *addr->u.inet.data = (InetSocketAddress) {
4039 .host = g_strdup(localaddr),
4040 .port = g_strdup(localport),
4042 udp->local = addr;
4046 typedef struct CharDriver {
4047 const char *name;
4048 ChardevBackendKind kind;
4049 CharDriverParse *parse;
4050 CharDriverCreate *create;
4051 } CharDriver;
4053 static GSList *backends;
4055 void register_char_driver(const char *name, ChardevBackendKind kind,
4056 CharDriverParse *parse, CharDriverCreate *create)
4058 CharDriver *s;
4060 s = g_malloc0(sizeof(*s));
4061 s->name = g_strdup(name);
4062 s->kind = kind;
4063 s->parse = parse;
4064 s->create = create;
4066 backends = g_slist_append(backends, s);
4069 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
4070 Error **errp)
4072 Error *local_err = NULL;
4073 CharDriver *cd;
4074 CharDriverState *chr;
4075 GSList *i;
4076 ChardevReturn *ret = NULL;
4077 ChardevBackend *backend;
4078 const char *id = qemu_opts_id(opts);
4079 char *bid = NULL;
4081 if (qemu_opt_get(opts, "backend") == NULL) {
4082 error_setg(errp, "chardev: \"%s\" missing backend",
4083 qemu_opts_id(opts));
4084 goto err;
4087 if (is_help_option(qemu_opt_get(opts, "backend"))) {
4088 fprintf(stderr, "Available chardev backend types:\n");
4089 for (i = backends; i; i = i->next) {
4090 cd = i->data;
4091 fprintf(stderr, "%s\n", cd->name);
4093 exit(!is_help_option(qemu_opt_get(opts, "backend")));
4096 if (id == NULL) {
4097 error_setg(errp, "chardev: no id specified");
4098 goto err;
4101 for (i = backends; i; i = i->next) {
4102 cd = i->data;
4104 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
4105 break;
4108 if (i == NULL) {
4109 error_setg(errp, "chardev: backend \"%s\" not found",
4110 qemu_opt_get(opts, "backend"));
4111 goto err;
4114 backend = g_new0(ChardevBackend, 1);
4116 if (qemu_opt_get_bool(opts, "mux", 0)) {
4117 bid = g_strdup_printf("%s-base", id);
4120 chr = NULL;
4121 backend->type = cd->kind;
4122 if (cd->parse) {
4123 cd->parse(opts, backend, &local_err);
4124 if (local_err) {
4125 error_propagate(errp, local_err);
4126 goto qapi_out;
4128 } else {
4129 ChardevCommon *cc = g_new0(ChardevCommon, 1);
4130 qemu_chr_parse_common(opts, cc);
4131 backend->u.null.data = cc; /* Any ChardevCommon member would work */
4134 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
4135 if (!ret) {
4136 goto qapi_out;
4139 if (bid) {
4140 qapi_free_ChardevBackend(backend);
4141 qapi_free_ChardevReturn(ret);
4142 backend = g_new0(ChardevBackend, 1);
4143 backend->u.mux.data = g_new0(ChardevMux, 1);
4144 backend->type = CHARDEV_BACKEND_KIND_MUX;
4145 backend->u.mux.data->chardev = g_strdup(bid);
4146 ret = qmp_chardev_add(id, backend, errp);
4147 if (!ret) {
4148 chr = qemu_chr_find(bid);
4149 qemu_chr_delete(chr);
4150 chr = NULL;
4151 goto qapi_out;
4155 chr = qemu_chr_find(id);
4157 qapi_out:
4158 qapi_free_ChardevBackend(backend);
4159 qapi_free_ChardevReturn(ret);
4160 g_free(bid);
4161 return chr;
4163 err:
4164 return NULL;
4167 CharDriverState *qemu_chr_new_noreplay(const char *label, const char *filename)
4169 const char *p;
4170 CharDriverState *chr;
4171 QemuOpts *opts;
4172 Error *err = NULL;
4174 if (strstart(filename, "chardev:", &p)) {
4175 return qemu_chr_find(p);
4178 opts = qemu_chr_parse_compat(label, filename);
4179 if (!opts)
4180 return NULL;
4182 chr = qemu_chr_new_from_opts(opts, &err);
4183 if (err) {
4184 error_report_err(err);
4186 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
4187 monitor_init(chr, MONITOR_USE_READLINE);
4189 qemu_opts_del(opts);
4190 return chr;
4193 CharDriverState *qemu_chr_new(const char *label, const char *filename)
4195 CharDriverState *chr;
4196 chr = qemu_chr_new_noreplay(label, filename);
4197 if (chr) {
4198 chr->replay = replay_mode != REPLAY_MODE_NONE;
4199 if (chr->replay && chr->chr_ioctl) {
4200 fprintf(stderr,
4201 "Replay: ioctl is not supported for serial devices yet\n");
4203 replay_register_char_driver(chr);
4205 return chr;
4208 void qemu_chr_fe_set_echo(CharBackend *be, bool echo)
4210 CharDriverState *chr = be->chr;
4212 if (chr && chr->chr_set_echo) {
4213 chr->chr_set_echo(chr, echo);
4217 void qemu_chr_fe_set_open(CharBackend *be, int fe_open)
4219 CharDriverState *chr = be->chr;
4221 if (!chr) {
4222 return;
4225 if (be->fe_open == fe_open) {
4226 return;
4228 be->fe_open = fe_open;
4229 if (chr->chr_set_fe_open) {
4230 chr->chr_set_fe_open(chr, fe_open);
4234 guint qemu_chr_fe_add_watch(CharBackend *be, GIOCondition cond,
4235 GIOFunc func, void *user_data)
4237 CharDriverState *s = be->chr;
4238 GSource *src;
4239 guint tag;
4241 if (!s || s->chr_add_watch == NULL) {
4242 return 0;
4245 src = s->chr_add_watch(s, cond);
4246 if (!src) {
4247 return 0;
4250 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
4251 tag = g_source_attach(src, NULL);
4252 g_source_unref(src);
4254 return tag;
4257 void qemu_chr_fe_disconnect(CharBackend *be)
4259 CharDriverState *chr = be->chr;
4261 if (chr && chr->chr_disconnect) {
4262 chr->chr_disconnect(chr);
4266 static void qemu_chr_free_common(CharDriverState *chr)
4268 if (chr->be) {
4269 chr->be->chr = NULL;
4271 g_free(chr->filename);
4272 g_free(chr->label);
4273 if (chr->logfd != -1) {
4274 close(chr->logfd);
4276 qemu_mutex_destroy(&chr->chr_write_lock);
4277 g_free(chr);
4280 void qemu_chr_free(CharDriverState *chr)
4282 if (chr->chr_free) {
4283 chr->chr_free(chr);
4285 qemu_chr_free_common(chr);
4288 void qemu_chr_delete(CharDriverState *chr)
4290 QTAILQ_REMOVE(&chardevs, chr, next);
4291 qemu_chr_free(chr);
4294 ChardevInfoList *qmp_query_chardev(Error **errp)
4296 ChardevInfoList *chr_list = NULL;
4297 CharDriverState *chr;
4299 QTAILQ_FOREACH(chr, &chardevs, next) {
4300 ChardevInfoList *info = g_malloc0(sizeof(*info));
4301 info->value = g_malloc0(sizeof(*info->value));
4302 info->value->label = g_strdup(chr->label);
4303 info->value->filename = g_strdup(chr->filename);
4304 info->value->frontend_open = chr->be && chr->be->fe_open;
4306 info->next = chr_list;
4307 chr_list = info;
4310 return chr_list;
4313 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4315 ChardevBackendInfoList *backend_list = NULL;
4316 CharDriver *c = NULL;
4317 GSList *i = NULL;
4319 for (i = backends; i; i = i->next) {
4320 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4321 c = i->data;
4322 info->value = g_malloc0(sizeof(*info->value));
4323 info->value->name = g_strdup(c->name);
4325 info->next = backend_list;
4326 backend_list = info;
4329 return backend_list;
4332 CharDriverState *qemu_chr_find(const char *name)
4334 CharDriverState *chr;
4336 QTAILQ_FOREACH(chr, &chardevs, next) {
4337 if (strcmp(chr->label, name) != 0)
4338 continue;
4339 return chr;
4341 return NULL;
4344 QemuOptsList qemu_chardev_opts = {
4345 .name = "chardev",
4346 .implied_opt_name = "backend",
4347 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4348 .desc = {
4350 .name = "backend",
4351 .type = QEMU_OPT_STRING,
4353 .name = "path",
4354 .type = QEMU_OPT_STRING,
4356 .name = "host",
4357 .type = QEMU_OPT_STRING,
4359 .name = "port",
4360 .type = QEMU_OPT_STRING,
4362 .name = "localaddr",
4363 .type = QEMU_OPT_STRING,
4365 .name = "localport",
4366 .type = QEMU_OPT_STRING,
4368 .name = "to",
4369 .type = QEMU_OPT_NUMBER,
4371 .name = "ipv4",
4372 .type = QEMU_OPT_BOOL,
4374 .name = "ipv6",
4375 .type = QEMU_OPT_BOOL,
4377 .name = "wait",
4378 .type = QEMU_OPT_BOOL,
4380 .name = "server",
4381 .type = QEMU_OPT_BOOL,
4383 .name = "delay",
4384 .type = QEMU_OPT_BOOL,
4386 .name = "reconnect",
4387 .type = QEMU_OPT_NUMBER,
4389 .name = "telnet",
4390 .type = QEMU_OPT_BOOL,
4392 .name = "tls-creds",
4393 .type = QEMU_OPT_STRING,
4395 .name = "width",
4396 .type = QEMU_OPT_NUMBER,
4398 .name = "height",
4399 .type = QEMU_OPT_NUMBER,
4401 .name = "cols",
4402 .type = QEMU_OPT_NUMBER,
4404 .name = "rows",
4405 .type = QEMU_OPT_NUMBER,
4407 .name = "mux",
4408 .type = QEMU_OPT_BOOL,
4410 .name = "signal",
4411 .type = QEMU_OPT_BOOL,
4413 .name = "name",
4414 .type = QEMU_OPT_STRING,
4416 .name = "debug",
4417 .type = QEMU_OPT_NUMBER,
4419 .name = "size",
4420 .type = QEMU_OPT_SIZE,
4422 .name = "chardev",
4423 .type = QEMU_OPT_STRING,
4425 .name = "append",
4426 .type = QEMU_OPT_BOOL,
4428 .name = "logfile",
4429 .type = QEMU_OPT_STRING,
4431 .name = "logappend",
4432 .type = QEMU_OPT_BOOL,
4434 { /* end of list */ }
4438 #ifdef _WIN32
4440 static CharDriverState *qmp_chardev_open_file(const char *id,
4441 ChardevBackend *backend,
4442 ChardevReturn *ret,
4443 bool *be_opened,
4444 Error **errp)
4446 ChardevFile *file = backend->u.file.data;
4447 ChardevCommon *common = qapi_ChardevFile_base(file);
4448 HANDLE out;
4449 DWORD accessmode;
4450 DWORD flags;
4452 if (file->has_in) {
4453 error_setg(errp, "input file not supported");
4454 return NULL;
4457 if (file->has_append && file->append) {
4458 /* Append to file if it already exists. */
4459 accessmode = FILE_GENERIC_WRITE & ~FILE_WRITE_DATA;
4460 flags = OPEN_ALWAYS;
4461 } else {
4462 /* Truncate file if it already exists. */
4463 accessmode = GENERIC_WRITE;
4464 flags = CREATE_ALWAYS;
4467 out = CreateFile(file->out, accessmode, FILE_SHARE_READ, NULL, flags,
4468 FILE_ATTRIBUTE_NORMAL, NULL);
4469 if (out == INVALID_HANDLE_VALUE) {
4470 error_setg(errp, "open %s failed", file->out);
4471 return NULL;
4473 return qemu_chr_open_win_file(out, common, errp);
4476 static CharDriverState *qmp_chardev_open_serial(const char *id,
4477 ChardevBackend *backend,
4478 ChardevReturn *ret,
4479 bool *be_opened,
4480 Error **errp)
4482 ChardevHostdev *serial = backend->u.serial.data;
4483 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4484 return qemu_chr_open_win_path(serial->device, common, errp);
4487 #else /* WIN32 */
4489 static int qmp_chardev_open_file_source(char *src, int flags,
4490 Error **errp)
4492 int fd = -1;
4494 TFR(fd = qemu_open(src, flags, 0666));
4495 if (fd == -1) {
4496 error_setg_file_open(errp, errno, src);
4498 return fd;
4501 static CharDriverState *qmp_chardev_open_file(const char *id,
4502 ChardevBackend *backend,
4503 ChardevReturn *ret,
4504 bool *be_opened,
4505 Error **errp)
4507 ChardevFile *file = backend->u.file.data;
4508 ChardevCommon *common = qapi_ChardevFile_base(file);
4509 int flags, in = -1, out;
4511 flags = O_WRONLY | O_CREAT | O_BINARY;
4512 if (file->has_append && file->append) {
4513 flags |= O_APPEND;
4514 } else {
4515 flags |= O_TRUNC;
4518 out = qmp_chardev_open_file_source(file->out, flags, errp);
4519 if (out < 0) {
4520 return NULL;
4523 if (file->has_in) {
4524 flags = O_RDONLY;
4525 in = qmp_chardev_open_file_source(file->in, flags, errp);
4526 if (in < 0) {
4527 qemu_close(out);
4528 return NULL;
4532 return qemu_chr_open_fd(in, out, common, errp);
4535 #ifdef HAVE_CHARDEV_SERIAL
4536 static CharDriverState *qmp_chardev_open_serial(const char *id,
4537 ChardevBackend *backend,
4538 ChardevReturn *ret,
4539 bool *be_opened,
4540 Error **errp)
4542 ChardevHostdev *serial = backend->u.serial.data;
4543 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4544 int fd;
4546 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4547 if (fd < 0) {
4548 return NULL;
4550 qemu_set_nonblock(fd);
4551 return qemu_chr_open_tty_fd(fd, common, be_opened, errp);
4553 #endif
4555 #ifdef HAVE_CHARDEV_PARPORT
4556 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4557 ChardevBackend *backend,
4558 ChardevReturn *ret,
4559 bool *be_opened,
4560 Error **errp)
4562 ChardevHostdev *parallel = backend->u.parallel.data;
4563 ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
4564 int fd;
4566 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4567 if (fd < 0) {
4568 return NULL;
4570 return qemu_chr_open_pp_fd(fd, common, be_opened, errp);
4572 #endif
4574 #endif /* WIN32 */
4576 static gboolean socket_reconnect_timeout(gpointer opaque)
4578 CharDriverState *chr = opaque;
4579 TCPCharDriver *s = chr->opaque;
4580 QIOChannelSocket *sioc;
4582 s->reconnect_timer = 0;
4584 if (chr->be_open) {
4585 return false;
4588 sioc = qio_channel_socket_new();
4589 qio_channel_socket_connect_async(sioc, s->addr,
4590 qemu_chr_socket_connected,
4591 chr, NULL);
4593 return false;
4596 static CharDriverState *qmp_chardev_open_socket(const char *id,
4597 ChardevBackend *backend,
4598 ChardevReturn *ret,
4599 bool *be_opened,
4600 Error **errp)
4602 CharDriverState *chr;
4603 TCPCharDriver *s;
4604 ChardevSocket *sock = backend->u.socket.data;
4605 SocketAddress *addr = sock->addr;
4606 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4607 bool is_listen = sock->has_server ? sock->server : true;
4608 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4609 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4610 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4611 ChardevCommon *common = qapi_ChardevSocket_base(sock);
4612 QIOChannelSocket *sioc = NULL;
4614 chr = qemu_chr_alloc(common, errp);
4615 if (!chr) {
4616 return NULL;
4618 s = g_new0(TCPCharDriver, 1);
4620 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4621 s->is_listen = is_listen;
4622 s->is_telnet = is_telnet;
4623 s->do_nodelay = do_nodelay;
4624 if (sock->tls_creds) {
4625 Object *creds;
4626 creds = object_resolve_path_component(
4627 object_get_objects_root(), sock->tls_creds);
4628 if (!creds) {
4629 error_setg(errp, "No TLS credentials with id '%s'",
4630 sock->tls_creds);
4631 goto error;
4633 s->tls_creds = (QCryptoTLSCreds *)
4634 object_dynamic_cast(creds,
4635 TYPE_QCRYPTO_TLS_CREDS);
4636 if (!s->tls_creds) {
4637 error_setg(errp, "Object with id '%s' is not TLS credentials",
4638 sock->tls_creds);
4639 goto error;
4641 object_ref(OBJECT(s->tls_creds));
4642 if (is_listen) {
4643 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4644 error_setg(errp, "%s",
4645 "Expected TLS credentials for server endpoint");
4646 goto error;
4648 } else {
4649 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4650 error_setg(errp, "%s",
4651 "Expected TLS credentials for client endpoint");
4652 goto error;
4657 s->addr = QAPI_CLONE(SocketAddress, sock->addr);
4659 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_RECONNECTABLE);
4660 if (s->is_unix) {
4661 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_FD_PASS);
4664 chr->opaque = s;
4665 chr->chr_wait_connected = tcp_chr_wait_connected;
4666 chr->chr_write = tcp_chr_write;
4667 chr->chr_sync_read = tcp_chr_sync_read;
4668 chr->chr_free = tcp_chr_free;
4669 chr->chr_disconnect = tcp_chr_disconnect;
4670 chr->get_msgfds = tcp_get_msgfds;
4671 chr->set_msgfds = tcp_set_msgfds;
4672 chr->chr_add_client = tcp_chr_add_client;
4673 chr->chr_add_watch = tcp_chr_add_watch;
4674 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4675 /* be isn't opened until we get a connection */
4676 *be_opened = false;
4678 chr->filename = SocketAddress_to_str("disconnected:",
4679 addr, is_listen, is_telnet);
4681 if (is_listen) {
4682 if (is_telnet) {
4683 s->do_telnetopt = 1;
4685 } else if (reconnect > 0) {
4686 s->reconnect_time = reconnect;
4689 if (s->reconnect_time) {
4690 sioc = qio_channel_socket_new();
4691 qio_channel_socket_connect_async(sioc, s->addr,
4692 qemu_chr_socket_connected,
4693 chr, NULL);
4694 } else {
4695 if (s->is_listen) {
4696 sioc = qio_channel_socket_new();
4697 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4698 goto error;
4700 s->listen_ioc = sioc;
4701 if (is_waitconnect &&
4702 qemu_chr_wait_connected(chr, errp) < 0) {
4703 goto error;
4705 if (!s->ioc) {
4706 s->listen_tag = qio_channel_add_watch(
4707 QIO_CHANNEL(s->listen_ioc), G_IO_IN,
4708 tcp_chr_accept, chr, NULL);
4710 } else if (qemu_chr_wait_connected(chr, errp) < 0) {
4711 goto error;
4715 return chr;
4717 error:
4718 if (sioc) {
4719 object_unref(OBJECT(sioc));
4721 if (s->tls_creds) {
4722 object_unref(OBJECT(s->tls_creds));
4724 g_free(s);
4725 qemu_chr_free_common(chr);
4726 return NULL;
4729 static CharDriverState *qmp_chardev_open_udp(const char *id,
4730 ChardevBackend *backend,
4731 ChardevReturn *ret,
4732 bool *be_opened,
4733 Error **errp)
4735 ChardevUdp *udp = backend->u.udp.data;
4736 ChardevCommon *common = qapi_ChardevUdp_base(udp);
4737 QIOChannelSocket *sioc = qio_channel_socket_new();
4739 if (qio_channel_socket_dgram_sync(sioc,
4740 udp->local, udp->remote,
4741 errp) < 0) {
4742 object_unref(OBJECT(sioc));
4743 return NULL;
4745 return qemu_chr_open_udp(sioc, common, be_opened, errp);
4749 bool qemu_chr_has_feature(CharDriverState *chr,
4750 CharDriverFeature feature)
4752 return test_bit(feature, chr->features);
4755 void qemu_chr_set_feature(CharDriverState *chr,
4756 CharDriverFeature feature)
4758 return set_bit(feature, chr->features);
4761 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4762 Error **errp)
4764 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4765 CharDriverState *chr = NULL;
4766 Error *local_err = NULL;
4767 GSList *i;
4768 CharDriver *cd;
4769 bool be_opened = true;
4771 chr = qemu_chr_find(id);
4772 if (chr) {
4773 error_setg(errp, "Chardev '%s' already exists", id);
4774 goto out_error;
4777 for (i = backends; i; i = i->next) {
4778 cd = i->data;
4780 if (cd->kind == backend->type) {
4781 chr = cd->create(id, backend, ret, &be_opened, &local_err);
4782 if (local_err) {
4783 error_propagate(errp, local_err);
4784 goto out_error;
4786 break;
4790 if (chr == NULL) {
4791 assert(!i);
4792 error_setg(errp, "chardev backend not available");
4793 goto out_error;
4796 chr->label = g_strdup(id);
4797 if (!chr->filename) {
4798 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4800 if (be_opened) {
4801 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4803 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4804 return ret;
4806 out_error:
4807 g_free(ret);
4808 return NULL;
4811 void qmp_chardev_remove(const char *id, Error **errp)
4813 CharDriverState *chr;
4815 chr = qemu_chr_find(id);
4816 if (chr == NULL) {
4817 error_setg(errp, "Chardev '%s' not found", id);
4818 return;
4820 if (qemu_chr_is_busy(chr)) {
4821 error_setg(errp, "Chardev '%s' is busy", id);
4822 return;
4824 if (chr->replay) {
4825 error_setg(errp,
4826 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4827 return;
4829 qemu_chr_delete(chr);
4832 void qemu_chr_cleanup(void)
4834 CharDriverState *chr, *tmp;
4836 QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
4837 qemu_chr_delete(chr);
4841 static void register_types(void)
4843 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4844 qemu_chr_open_null);
4845 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4846 qemu_chr_parse_socket, qmp_chardev_open_socket);
4847 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4848 qmp_chardev_open_udp);
4849 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4850 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4851 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4852 qemu_chr_parse_file_out, qmp_chardev_open_file);
4853 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4854 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4855 #if defined HAVE_CHARDEV_SERIAL
4856 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4857 qemu_chr_parse_serial, qmp_chardev_open_serial);
4858 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4859 qemu_chr_parse_serial, qmp_chardev_open_serial);
4860 #endif
4861 #ifdef HAVE_CHARDEV_PARPORT
4862 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4863 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4864 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4865 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4866 #endif
4867 #ifdef HAVE_CHARDEV_PTY
4868 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4869 qemu_chr_open_pty);
4870 #endif
4871 #ifdef _WIN32
4872 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4873 qemu_chr_open_win_con);
4874 #endif
4875 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4876 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4877 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4878 qemu_chr_open_mux);
4879 /* Bug-compatibility: */
4880 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4881 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4882 /* this must be done after machine init, since we register FEs with muxes
4883 * as part of realize functions like serial_isa_realizefn when -nographic
4884 * is specified
4886 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4889 type_init(register_types);