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
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"
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"
47 #include <sys/times.h>
50 #include <sys/ioctl.h>
51 #include <sys/resource.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
55 #include <arpa/inet.h>
57 #include <sys/select.h>
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>
68 #include <linux/ppdev.h>
69 #include <linux/parport.h>
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>
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" : "");
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" : "");
113 case SOCKET_ADDRESS_KIND_FD:
114 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd.data->str,
115 is_listen ? ",server" : "");
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) {
133 return g_strdup_printf("unix:%s%s",
134 ((struct sockaddr_un *)(ss))->sun_path,
135 is_listen ? ",server" : "");
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);
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) {
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",
193 void qemu_chr_be_event(CharDriverState *s, int event)
195 /* Keep track if the char device is open */
197 case CHR_EVENT_OPENED:
200 case CHR_EVENT_CLOSED:
207 s->chr_event(s->handler_opaque, event);
210 void qemu_chr_be_generic_open(CharDriverState *s)
212 qemu_chr_be_event(s, CHR_EVENT_OPENED);
216 /* Not reporting errors from writing to logfile, as logs are
217 * defined to be "best effort" only */
218 static void qemu_chr_fe_write_log(CharDriverState *s,
219 const uint8_t *buf, size_t len)
230 ret = write(s->logfd, buf + done, len - done);
231 if (ret == -1 && errno == EAGAIN) {
243 static int qemu_chr_fe_write_buffer(CharDriverState *s, const uint8_t *buf, int len, int *offset)
248 qemu_mutex_lock(&s->chr_write_lock);
249 while (*offset < len) {
251 res = s->chr_write(s, buf + *offset, len - *offset);
252 if (res < 0 && errno == EAGAIN) {
264 qemu_chr_fe_write_log(s, buf, *offset);
266 qemu_mutex_unlock(&s->chr_write_lock);
271 int qemu_chr_fe_write(CharBackend *be, const uint8_t *buf, int len)
273 CharDriverState *s = be->chr;
276 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
278 replay_char_write_event_load(&ret, &offset);
279 assert(offset <= len);
280 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
284 qemu_mutex_lock(&s->chr_write_lock);
285 ret = s->chr_write(s, buf, len);
288 qemu_chr_fe_write_log(s, buf, ret);
291 qemu_mutex_unlock(&s->chr_write_lock);
293 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
294 replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
300 static int qemu_chr_write_all(CharDriverState *s, const uint8_t *buf, int len)
305 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
306 replay_char_write_event_load(&res, &offset);
307 assert(offset <= len);
308 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
312 res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
314 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
315 replay_char_write_event_save(res, offset);
324 int qemu_chr_fe_write_all(CharBackend *be, const uint8_t *buf, int len)
326 CharDriverState *s = be->chr;
328 return qemu_chr_write_all(s, buf, len);
331 int qemu_chr_fe_read_all(CharBackend *be, uint8_t *buf, int len)
333 CharDriverState *s = be->chr;
334 int offset = 0, counter = 10;
337 if (!s->chr_sync_read) {
341 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
342 return replay_char_read_all_load(buf);
345 while (offset < len) {
347 res = s->chr_sync_read(s, buf + offset, len - offset);
348 if (res == -1 && errno == EAGAIN) {
358 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
359 replay_char_read_all_save_error(res);
371 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
372 replay_char_read_all_save_buf(buf, offset);
377 int qemu_chr_fe_ioctl(CharBackend *be, int cmd, void *arg)
379 CharDriverState *s = be->chr;
381 if (!s->chr_ioctl || s->replay) {
384 res = s->chr_ioctl(s, cmd, arg);
390 int qemu_chr_be_can_write(CharDriverState *s)
392 if (!s->chr_can_read)
394 return s->chr_can_read(s->handler_opaque);
397 void qemu_chr_be_write_impl(CharDriverState *s, uint8_t *buf, int len)
400 s->chr_read(s->handler_opaque, buf, len);
404 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
407 if (replay_mode == REPLAY_MODE_PLAY) {
410 replay_chr_be_write(s, buf, len);
412 qemu_chr_be_write_impl(s, buf, len);
416 int qemu_chr_fe_get_msgfd(CharBackend *be)
418 CharDriverState *s = be->chr;
420 int res = (qemu_chr_fe_get_msgfds(be, &fd, 1) == 1) ? fd : -1;
423 "Replay: get msgfd is not supported for serial devices yet\n");
429 int qemu_chr_fe_get_msgfds(CharBackend *be, int *fds, int len)
431 CharDriverState *s = be->chr;
433 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
436 int qemu_chr_fe_set_msgfds(CharBackend *be, int *fds, int num)
438 CharDriverState *s = be->chr;
440 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
443 int qemu_chr_add_client(CharDriverState *s, int fd)
445 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
448 void qemu_chr_fe_accept_input(CharBackend *be)
450 CharDriverState *s = be->chr;
452 if (s->chr_accept_input)
453 s->chr_accept_input(s);
457 void qemu_chr_fe_printf(CharBackend *be, const char *fmt, ...)
459 char buf[READ_BUF_LEN];
462 vsnprintf(buf, sizeof(buf), fmt, ap);
463 /* XXX this blocks entire thread. Rewrite to use
464 * qemu_chr_fe_write and background I/O callbacks */
465 qemu_chr_fe_write_all(be, (uint8_t *)buf, strlen(buf));
469 static void remove_fd_in_watch(CharDriverState *chr);
472 qemu_chr_set_handlers(CharBackend *be,
473 IOCanReadHandler *fd_can_read,
474 IOReadHandler *fd_read,
475 IOEventHandler *fd_event,
477 GMainContext *context)
479 CharDriverState *s = be->chr;
482 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
484 remove_fd_in_watch(s);
488 s->chr_can_read = fd_can_read;
489 s->chr_read = fd_read;
490 s->chr_event = fd_event;
491 s->handler_opaque = opaque;
492 if (s->chr_update_read_handler) {
493 s->chr_update_read_handler(s, context, be->tag);
496 if (!s->explicit_fe_open) {
497 qemu_chr_fe_set_open(be, fe_open);
500 /* We're connecting to an already opened device, so let's make sure we
501 also get the open event */
503 qemu_chr_fe_take_focus(be);
505 qemu_chr_be_generic_open(s);
510 static int mux_chr_new_handler_tag(CharDriverState *chr, Error **errp);
511 static void mux_chr_set_handlers(CharDriverState *chr, GMainContext *context);
512 static void mux_set_focus(MuxDriver *d, int focus);
514 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
519 static CharDriverState *qemu_chr_open_null(const char *id,
520 ChardevBackend *backend,
524 CharDriverState *chr;
525 ChardevCommon *common = backend->u.null.data;
527 chr = qemu_chr_alloc(common, errp);
531 chr->chr_write = null_chr_write;
532 chr->explicit_be_open = true;
536 /* MUX driver for serial I/O splitting */
538 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
539 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
541 IOCanReadHandler *chr_can_read[MAX_MUX];
542 IOReadHandler *chr_read[MAX_MUX];
543 IOEventHandler *chr_event[MAX_MUX];
544 void *ext_opaque[MAX_MUX];
550 /* Intermediate input buffer allows to catch escape sequences even if the
551 currently active device is not accepting any input - but only until it
553 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
558 /* Protected by the CharDriverState chr_write_lock. */
560 int64_t timestamps_start;
563 /* Called with chr_write_lock held. */
564 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
566 MuxDriver *d = chr->opaque;
568 if (!d->timestamps) {
569 ret = qemu_chr_fe_write(&d->chr, buf, len);
574 for (i = 0; i < len; i++) {
580 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
581 if (d->timestamps_start == -1)
582 d->timestamps_start = ti;
583 ti -= d->timestamps_start;
585 snprintf(buf1, sizeof(buf1),
586 "[%02d:%02d:%02d.%03d] ",
591 /* XXX this blocks entire thread. Rewrite to use
592 * qemu_chr_fe_write and background I/O callbacks */
593 qemu_chr_fe_write_all(&d->chr,
594 (uint8_t *)buf1, strlen(buf1));
597 ret += qemu_chr_fe_write(&d->chr, buf + i, 1);
598 if (buf[i] == '\n') {
606 static const char * const mux_help[] = {
607 "% h print this help\n\r",
608 "% x exit emulator\n\r",
609 "% s save disk data back to file (if -snapshot)\n\r",
610 "% t toggle console timestamps\n\r",
611 "% b send break (magic sysrq)\n\r",
612 "% c switch between console and monitor\n\r",
617 int term_escape_char = 0x01; /* ctrl-a is used for escape */
618 static void mux_print_help(CharDriverState *chr)
621 char ebuf[15] = "Escape-Char";
622 char cbuf[50] = "\n\r";
624 if (term_escape_char > 0 && term_escape_char < 26) {
625 snprintf(cbuf, sizeof(cbuf), "\n\r");
626 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
628 snprintf(cbuf, sizeof(cbuf),
629 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
632 /* XXX this blocks entire thread. Rewrite to use
633 * qemu_chr_fe_write and background I/O callbacks */
634 qemu_chr_write_all(chr, (uint8_t *)cbuf, strlen(cbuf));
635 for (i = 0; mux_help[i] != NULL; i++) {
636 for (j=0; mux_help[i][j] != '\0'; j++) {
637 if (mux_help[i][j] == '%')
638 qemu_chr_write_all(chr, (uint8_t *)ebuf, strlen(ebuf));
640 qemu_chr_write_all(chr, (uint8_t *)&mux_help[i][j], 1);
645 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
647 if (d->chr_event[mux_nr])
648 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
651 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
653 if (d->term_got_escape) {
654 d->term_got_escape = 0;
655 if (ch == term_escape_char)
664 const char *term = "QEMU: Terminated\n\r";
665 qemu_chr_write_all(chr, (uint8_t *)term, strlen(term));
673 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
676 assert(d->mux_cnt > 0); /* handler registered with first fe */
677 /* Switch to the next registered device */
678 mux_set_focus(d, (d->focus + 1) % d->mux_cnt);
681 d->timestamps = !d->timestamps;
682 d->timestamps_start = -1;
686 } else if (ch == term_escape_char) {
687 d->term_got_escape = 1;
695 static void mux_chr_accept_input(CharDriverState *chr)
697 MuxDriver *d = chr->opaque;
700 while (d->prod[m] != d->cons[m] &&
701 d->chr_can_read[m] &&
702 d->chr_can_read[m](d->ext_opaque[m])) {
703 d->chr_read[m](d->ext_opaque[m],
704 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
708 static int mux_chr_can_read(void *opaque)
710 CharDriverState *chr = opaque;
711 MuxDriver *d = chr->opaque;
714 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
716 if (d->chr_can_read[m])
717 return d->chr_can_read[m](d->ext_opaque[m]);
721 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
723 CharDriverState *chr = opaque;
724 MuxDriver *d = chr->opaque;
728 mux_chr_accept_input (opaque);
730 for(i = 0; i < size; i++)
731 if (mux_proc_byte(chr, d, buf[i])) {
732 if (d->prod[m] == d->cons[m] &&
733 d->chr_can_read[m] &&
734 d->chr_can_read[m](d->ext_opaque[m]))
735 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
737 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
741 static void mux_chr_event(void *opaque, int event)
743 CharDriverState *chr = opaque;
744 MuxDriver *d = chr->opaque;
747 /* Send the event to all registered listeners */
748 for (i = 0; i < d->mux_cnt; i++)
749 mux_chr_send_event(d, i, event);
752 static void mux_chr_update_read_handler(CharDriverState *chr,
753 GMainContext *context,
756 MuxDriver *d = chr->opaque;
759 assert(tag < d->mux_cnt);
761 d->ext_opaque[tag] = chr->handler_opaque;
762 d->chr_can_read[tag] = chr->chr_can_read;
763 d->chr_read[tag] = chr->chr_read;
764 d->chr_event[tag] = chr->chr_event;
767 static bool muxes_realized;
770 * Called after processing of default and command-line-specified
771 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
772 * to a mux chardev. This is done here to ensure that
773 * output/prompts/banners are only displayed for the FE that has
774 * focus when initial command-line processing/machine init is
777 * After this point, any new FE attached to any new or existing
778 * mux will receive CHR_EVENT_OPENED notifications for the BE
781 static void muxes_realize_done(Notifier *notifier, void *unused)
783 CharDriverState *chr;
785 QTAILQ_FOREACH(chr, &chardevs, next) {
787 MuxDriver *d = chr->opaque;
790 /* send OPENED to all already-attached FEs */
791 for (i = 0; i < d->mux_cnt; i++) {
792 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
794 /* mark mux as OPENED so any new FEs will immediately receive
797 qemu_chr_be_generic_open(chr);
800 muxes_realized = true;
803 static Notifier muxes_realize_notify = {
804 .notify = muxes_realize_done,
807 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
809 MuxDriver *d = s->opaque;
810 CharDriverState *chr = qemu_chr_fe_get_driver(&d->chr);
812 return chr->chr_add_watch(chr, cond);
815 static void mux_chr_close(struct CharDriverState *chr)
817 MuxDriver *d = chr->opaque;
822 static int mux_chr_new_handler_tag(CharDriverState *chr, Error **errp)
824 MuxDriver *d = chr->opaque;
826 if (d->mux_cnt >= MAX_MUX) {
827 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
834 static void mux_chr_set_handlers(CharDriverState *chr, GMainContext *context)
836 MuxDriver *d = chr->opaque;
838 /* Fix up the real driver with mux routines */
839 qemu_chr_fe_set_handlers(&d->chr,
847 static void mux_set_focus(MuxDriver *d, int focus)
850 assert(focus < d->mux_cnt);
852 if (d->focus != -1) {
853 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
857 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
860 static CharDriverState *qemu_chr_open_mux(const char *id,
861 ChardevBackend *backend,
862 ChardevReturn *ret, Error **errp)
864 ChardevMux *mux = backend->u.mux.data;
865 CharDriverState *chr, *drv;
867 ChardevCommon *common = qapi_ChardevMux_base(mux);
869 drv = qemu_chr_find(mux->chardev);
871 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
875 chr = qemu_chr_alloc(common, errp);
879 d = g_new0(MuxDriver, 1);
883 chr->chr_close = mux_chr_close;
884 chr->chr_write = mux_chr_write;
885 chr->chr_update_read_handler = mux_chr_update_read_handler;
886 chr->chr_accept_input = mux_chr_accept_input;
887 /* Frontend guest-open / -close notification is not support with muxes */
888 chr->chr_set_fe_open = NULL;
889 if (drv->chr_add_watch) {
890 chr->chr_add_watch = mux_chr_add_watch;
892 /* only default to opened state if we've realized the initial
895 chr->explicit_be_open = muxes_realized ? 0 : 1;
897 if (!qemu_chr_fe_init(&d->chr, drv, errp)) {
905 CharDriverState *qemu_chr_fe_get_driver(CharBackend *be)
910 bool qemu_chr_fe_init(CharBackend *b, CharDriverState *s, Error **errp)
915 tag = mux_chr_new_handler_tag(s, errp);
927 void qemu_chr_fe_set_handlers(CharBackend *b,
928 IOCanReadHandler *fd_can_read,
929 IOReadHandler *fd_read,
930 IOEventHandler *fd_event,
932 GMainContext *context)
938 qemu_chr_set_handlers(b, fd_can_read, fd_read,
939 fd_event, opaque, context);
941 if (b->chr->is_mux) {
942 mux_chr_set_handlers(b->chr, context);
946 void qemu_chr_fe_take_focus(CharBackend *b)
948 if (b->chr->is_mux) {
949 mux_set_focus(b->chr->opaque, b->tag);
953 typedef struct IOWatchPoll
960 IOCanReadHandler *fd_can_read;
963 GMainContext *context;
966 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
968 return container_of(source, IOWatchPoll, parent);
971 static gboolean io_watch_poll_prepare(GSource *source,
974 IOWatchPoll *iwp = io_watch_poll_from_source(source);
975 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
976 bool was_active = iwp->src != NULL;
977 if (was_active == now_active) {
982 iwp->src = qio_channel_create_watch(
983 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
984 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
985 g_source_attach(iwp->src, iwp->context);
987 g_source_destroy(iwp->src);
988 g_source_unref(iwp->src);
994 static gboolean io_watch_poll_check(GSource *source)
999 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
1005 static void io_watch_poll_finalize(GSource *source)
1007 /* Due to a glib bug, removing the last reference to a source
1008 * inside a finalize callback causes recursive locking (and a
1009 * deadlock). This is not a problem inside other callbacks,
1010 * including dispatch callbacks, so we call io_remove_watch_poll
1011 * to remove this source. At this point, iwp->src must
1012 * be NULL, or we would leak it.
1014 * This would be solved much more elegantly by child sources,
1015 * but we support older glib versions that do not have them.
1017 IOWatchPoll *iwp = io_watch_poll_from_source(source);
1018 assert(iwp->src == NULL);
1021 static GSourceFuncs io_watch_poll_funcs = {
1022 .prepare = io_watch_poll_prepare,
1023 .check = io_watch_poll_check,
1024 .dispatch = io_watch_poll_dispatch,
1025 .finalize = io_watch_poll_finalize,
1028 /* Can only be used for read */
1029 static guint io_add_watch_poll(QIOChannel *ioc,
1030 IOCanReadHandler *fd_can_read,
1031 QIOChannelFunc fd_read,
1033 GMainContext *context)
1038 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs,
1039 sizeof(IOWatchPoll));
1040 iwp->fd_can_read = fd_can_read;
1041 iwp->opaque = user_data;
1043 iwp->fd_read = (GSourceFunc) fd_read;
1045 iwp->context = context;
1047 tag = g_source_attach(&iwp->parent, context);
1048 g_source_unref(&iwp->parent);
1052 static void io_remove_watch_poll(guint tag)
1057 g_return_if_fail (tag > 0);
1059 source = g_main_context_find_source_by_id(NULL, tag);
1060 g_return_if_fail (source != NULL);
1062 iwp = io_watch_poll_from_source(source);
1064 g_source_destroy(iwp->src);
1065 g_source_unref(iwp->src);
1068 g_source_destroy(&iwp->parent);
1071 static void remove_fd_in_watch(CharDriverState *chr)
1073 if (chr->fd_in_tag) {
1074 io_remove_watch_poll(chr->fd_in_tag);
1080 static int io_channel_send_full(QIOChannel *ioc,
1081 const void *buf, size_t len,
1082 int *fds, size_t nfds)
1086 while (offset < len) {
1088 struct iovec iov = { .iov_base = (char *)buf + offset,
1089 .iov_len = len - offset };
1091 ret = qio_channel_writev_full(
1094 if (ret == QIO_CHANNEL_ERR_BLOCK) {
1101 } else if (ret < 0) {
1114 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
1116 return io_channel_send_full(ioc, buf, len, NULL, 0);
1120 typedef struct FDCharDriver {
1121 CharDriverState *chr;
1122 QIOChannel *ioc_in, *ioc_out;
1126 /* Called with chr_write_lock held. */
1127 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1129 FDCharDriver *s = chr->opaque;
1131 return io_channel_send(s->ioc_out, buf, len);
1134 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1136 CharDriverState *chr = opaque;
1137 FDCharDriver *s = chr->opaque;
1139 uint8_t buf[READ_BUF_LEN];
1143 if (len > s->max_size) {
1150 ret = qio_channel_read(
1151 chan, (gchar *)buf, len, NULL);
1153 remove_fd_in_watch(chr);
1154 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1158 qemu_chr_be_write(chr, buf, ret);
1164 static int fd_chr_read_poll(void *opaque)
1166 CharDriverState *chr = opaque;
1167 FDCharDriver *s = chr->opaque;
1169 s->max_size = qemu_chr_be_can_write(chr);
1173 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1175 FDCharDriver *s = chr->opaque;
1176 return qio_channel_create_watch(s->ioc_out, cond);
1179 static void fd_chr_update_read_handler(CharDriverState *chr,
1180 GMainContext *context,
1183 FDCharDriver *s = chr->opaque;
1185 remove_fd_in_watch(chr);
1187 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
1194 static void fd_chr_close(struct CharDriverState *chr)
1196 FDCharDriver *s = chr->opaque;
1198 remove_fd_in_watch(chr);
1200 object_unref(OBJECT(s->ioc_in));
1203 object_unref(OBJECT(s->ioc_out));
1207 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1210 /* open a character device to a unix fd */
1211 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1212 ChardevCommon *backend, Error **errp)
1214 CharDriverState *chr;
1217 chr = qemu_chr_alloc(backend, errp);
1221 s = g_new0(FDCharDriver, 1);
1222 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1223 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1224 qemu_set_nonblock(fd_out);
1227 chr->chr_add_watch = fd_chr_add_watch;
1228 chr->chr_write = fd_chr_write;
1229 chr->chr_update_read_handler = fd_chr_update_read_handler;
1230 chr->chr_close = fd_chr_close;
1235 static CharDriverState *qemu_chr_open_pipe(const char *id,
1236 ChardevBackend *backend,
1240 ChardevHostdev *opts = backend->u.pipe.data;
1244 const char *filename = opts->device;
1245 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1248 filename_in = g_strdup_printf("%s.in", filename);
1249 filename_out = g_strdup_printf("%s.out", filename);
1250 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1251 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1252 g_free(filename_in);
1253 g_free(filename_out);
1254 if (fd_in < 0 || fd_out < 0) {
1259 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1261 error_setg_file_open(errp, errno, filename);
1265 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1268 /* init terminal so that we can grab keys */
1269 static struct termios oldtty;
1270 static int old_fd0_flags;
1271 static bool stdio_in_use;
1272 static bool stdio_allow_signal;
1273 static bool stdio_echo_state;
1275 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1277 static void term_exit(void)
1279 tcsetattr (0, TCSANOW, &oldtty);
1280 fcntl(0, F_SETFL, old_fd0_flags);
1283 static void term_stdio_handler(int sig)
1285 /* restore echo after resume from suspend. */
1286 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1289 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1293 stdio_echo_state = echo;
1296 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1297 |INLCR|IGNCR|ICRNL|IXON);
1298 tty.c_oflag |= OPOST;
1299 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1300 tty.c_cflag &= ~(CSIZE|PARENB);
1303 tty.c_cc[VTIME] = 0;
1305 if (!stdio_allow_signal)
1306 tty.c_lflag &= ~ISIG;
1308 tcsetattr (0, TCSANOW, &tty);
1311 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1317 static CharDriverState *qemu_chr_open_stdio(const char *id,
1318 ChardevBackend *backend,
1322 ChardevStdio *opts = backend->u.stdio.data;
1323 CharDriverState *chr;
1324 struct sigaction act;
1325 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1327 if (is_daemonized()) {
1328 error_setg(errp, "cannot use stdio with -daemonize");
1333 error_setg(errp, "cannot use stdio by multiple character devices");
1337 stdio_in_use = true;
1338 old_fd0_flags = fcntl(0, F_GETFL);
1339 tcgetattr(0, &oldtty);
1340 qemu_set_nonblock(0);
1343 memset(&act, 0, sizeof(act));
1344 act.sa_handler = term_stdio_handler;
1345 sigaction(SIGCONT, &act, NULL);
1347 chr = qemu_chr_open_fd(0, 1, common, errp);
1351 chr->chr_close = qemu_chr_close_stdio;
1352 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1353 if (opts->has_signal) {
1354 stdio_allow_signal = opts->signal;
1356 qemu_chr_set_echo_stdio(chr, false);
1361 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1362 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1363 || defined(__GLIBC__)
1365 #define HAVE_CHARDEV_SERIAL 1
1366 #define HAVE_CHARDEV_PTY 1
1372 /* Protected by the CharDriverState chr_write_lock. */
1378 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1379 static void pty_chr_state(CharDriverState *chr, int connected);
1381 static gboolean pty_chr_timer(gpointer opaque)
1383 struct CharDriverState *chr = opaque;
1384 PtyCharDriver *s = chr->opaque;
1386 qemu_mutex_lock(&chr->chr_write_lock);
1389 if (!s->connected) {
1391 pty_chr_update_read_handler_locked(chr);
1393 qemu_mutex_unlock(&chr->chr_write_lock);
1397 /* Called with chr_write_lock held. */
1398 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1400 PtyCharDriver *s = chr->opaque;
1403 g_source_remove(s->timer_tag);
1408 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1410 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1414 /* Called with chr_write_lock held. */
1415 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1417 PtyCharDriver *s = chr->opaque;
1420 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1423 pfd.events = G_IO_OUT;
1426 rc = g_poll(&pfd, 1, 0);
1427 } while (rc == -1 && errno == EINTR);
1430 if (pfd.revents & G_IO_HUP) {
1431 pty_chr_state(chr, 0);
1433 pty_chr_state(chr, 1);
1437 static void pty_chr_update_read_handler(CharDriverState *chr,
1438 GMainContext *context,
1441 qemu_mutex_lock(&chr->chr_write_lock);
1442 pty_chr_update_read_handler_locked(chr);
1443 qemu_mutex_unlock(&chr->chr_write_lock);
1446 /* Called with chr_write_lock held. */
1447 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1449 PtyCharDriver *s = chr->opaque;
1451 if (!s->connected) {
1452 /* guest sends data, check for (re-)connect */
1453 pty_chr_update_read_handler_locked(chr);
1454 if (!s->connected) {
1458 return io_channel_send(s->ioc, buf, len);
1461 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1463 PtyCharDriver *s = chr->opaque;
1464 if (!s->connected) {
1467 return qio_channel_create_watch(s->ioc, cond);
1470 static int pty_chr_read_poll(void *opaque)
1472 CharDriverState *chr = opaque;
1473 PtyCharDriver *s = chr->opaque;
1475 s->read_bytes = qemu_chr_be_can_write(chr);
1476 return s->read_bytes;
1479 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1481 CharDriverState *chr = opaque;
1482 PtyCharDriver *s = chr->opaque;
1484 uint8_t buf[READ_BUF_LEN];
1488 if (len > s->read_bytes)
1489 len = s->read_bytes;
1493 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1495 pty_chr_state(chr, 0);
1498 pty_chr_state(chr, 1);
1499 qemu_chr_be_write(chr, buf, ret);
1504 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1506 CharDriverState *chr = opaque;
1507 PtyCharDriver *s = chr->opaque;
1510 qemu_chr_be_generic_open(chr);
1514 /* Called with chr_write_lock held. */
1515 static void pty_chr_state(CharDriverState *chr, int connected)
1517 PtyCharDriver *s = chr->opaque;
1521 g_source_remove(s->open_tag);
1524 remove_fd_in_watch(chr);
1526 /* (re-)connect poll interval for idle guests: once per second.
1527 * We check more frequently in case the guests sends data to
1528 * the virtual device linked to our pty. */
1529 pty_chr_rearm_timer(chr, 1000);
1532 g_source_remove(s->timer_tag);
1535 if (!s->connected) {
1536 g_assert(s->open_tag == 0);
1538 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1540 if (!chr->fd_in_tag) {
1541 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1549 static void pty_chr_close(struct CharDriverState *chr)
1551 PtyCharDriver *s = chr->opaque;
1553 qemu_mutex_lock(&chr->chr_write_lock);
1554 pty_chr_state(chr, 0);
1555 object_unref(OBJECT(s->ioc));
1557 g_source_remove(s->timer_tag);
1560 qemu_mutex_unlock(&chr->chr_write_lock);
1562 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1565 static CharDriverState *qemu_chr_open_pty(const char *id,
1566 ChardevBackend *backend,
1570 CharDriverState *chr;
1572 int master_fd, slave_fd;
1573 char pty_name[PATH_MAX];
1574 ChardevCommon *common = backend->u.pty.data;
1576 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1577 if (master_fd < 0) {
1578 error_setg_errno(errp, errno, "Failed to create PTY");
1583 qemu_set_nonblock(master_fd);
1585 chr = qemu_chr_alloc(common, errp);
1591 chr->filename = g_strdup_printf("pty:%s", pty_name);
1592 ret->pty = g_strdup(pty_name);
1593 ret->has_pty = true;
1595 fprintf(stderr, "char device redirected to %s (label %s)\n",
1598 s = g_new0(PtyCharDriver, 1);
1600 chr->chr_write = pty_chr_write;
1601 chr->chr_update_read_handler = pty_chr_update_read_handler;
1602 chr->chr_close = pty_chr_close;
1603 chr->chr_add_watch = pty_chr_add_watch;
1604 chr->explicit_be_open = true;
1606 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1612 static void tty_serial_init(int fd, int speed,
1613 int parity, int data_bits, int stop_bits)
1619 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1620 speed, parity, data_bits, stop_bits);
1622 tcgetattr (fd, &tty);
1624 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1625 speed = speed * 10 / 11;
1642 /* Non-Posix values follow. They may be unsupported on some systems. */
1644 check_speed(115200);
1646 check_speed(230400);
1649 check_speed(460800);
1652 check_speed(500000);
1655 check_speed(576000);
1658 check_speed(921600);
1661 check_speed(1000000);
1664 check_speed(1152000);
1667 check_speed(1500000);
1670 check_speed(2000000);
1673 check_speed(2500000);
1676 check_speed(3000000);
1679 check_speed(3500000);
1682 check_speed(4000000);
1687 cfsetispeed(&tty, spd);
1688 cfsetospeed(&tty, spd);
1690 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1691 |INLCR|IGNCR|ICRNL|IXON);
1692 tty.c_oflag |= OPOST;
1693 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1694 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1715 tty.c_cflag |= PARENB;
1718 tty.c_cflag |= PARENB | PARODD;
1722 tty.c_cflag |= CSTOPB;
1724 tcsetattr (fd, TCSANOW, &tty);
1727 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1729 FDCharDriver *s = chr->opaque;
1730 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1733 case CHR_IOCTL_SERIAL_SET_PARAMS:
1735 QEMUSerialSetParams *ssp = arg;
1736 tty_serial_init(fioc->fd,
1737 ssp->speed, ssp->parity,
1738 ssp->data_bits, ssp->stop_bits);
1741 case CHR_IOCTL_SERIAL_SET_BREAK:
1743 int enable = *(int *)arg;
1745 tcsendbreak(fioc->fd, 1);
1749 case CHR_IOCTL_SERIAL_GET_TIOCM:
1752 int *targ = (int *)arg;
1753 ioctl(fioc->fd, TIOCMGET, &sarg);
1755 if (sarg & TIOCM_CTS)
1756 *targ |= CHR_TIOCM_CTS;
1757 if (sarg & TIOCM_CAR)
1758 *targ |= CHR_TIOCM_CAR;
1759 if (sarg & TIOCM_DSR)
1760 *targ |= CHR_TIOCM_DSR;
1761 if (sarg & TIOCM_RI)
1762 *targ |= CHR_TIOCM_RI;
1763 if (sarg & TIOCM_DTR)
1764 *targ |= CHR_TIOCM_DTR;
1765 if (sarg & TIOCM_RTS)
1766 *targ |= CHR_TIOCM_RTS;
1769 case CHR_IOCTL_SERIAL_SET_TIOCM:
1771 int sarg = *(int *)arg;
1773 ioctl(fioc->fd, TIOCMGET, &targ);
1774 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1775 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1776 if (sarg & CHR_TIOCM_CTS)
1778 if (sarg & CHR_TIOCM_CAR)
1780 if (sarg & CHR_TIOCM_DSR)
1782 if (sarg & CHR_TIOCM_RI)
1784 if (sarg & CHR_TIOCM_DTR)
1786 if (sarg & CHR_TIOCM_RTS)
1788 ioctl(fioc->fd, TIOCMSET, &targ);
1797 static void qemu_chr_close_tty(CharDriverState *chr)
1802 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1803 ChardevCommon *backend,
1806 CharDriverState *chr;
1808 tty_serial_init(fd, 115200, 'N', 8, 1);
1809 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1813 chr->chr_ioctl = tty_serial_ioctl;
1814 chr->chr_close = qemu_chr_close_tty;
1817 #endif /* __linux__ || __sun__ */
1819 #if defined(__linux__)
1821 #define HAVE_CHARDEV_PARPORT 1
1826 } ParallelCharDriver;
1828 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1830 if (s->mode != mode) {
1832 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1839 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1841 ParallelCharDriver *drv = chr->opaque;
1846 case CHR_IOCTL_PP_READ_DATA:
1847 if (ioctl(fd, PPRDATA, &b) < 0)
1849 *(uint8_t *)arg = b;
1851 case CHR_IOCTL_PP_WRITE_DATA:
1852 b = *(uint8_t *)arg;
1853 if (ioctl(fd, PPWDATA, &b) < 0)
1856 case CHR_IOCTL_PP_READ_CONTROL:
1857 if (ioctl(fd, PPRCONTROL, &b) < 0)
1859 /* Linux gives only the lowest bits, and no way to know data
1860 direction! For better compatibility set the fixed upper
1862 *(uint8_t *)arg = b | 0xc0;
1864 case CHR_IOCTL_PP_WRITE_CONTROL:
1865 b = *(uint8_t *)arg;
1866 if (ioctl(fd, PPWCONTROL, &b) < 0)
1869 case CHR_IOCTL_PP_READ_STATUS:
1870 if (ioctl(fd, PPRSTATUS, &b) < 0)
1872 *(uint8_t *)arg = b;
1874 case CHR_IOCTL_PP_DATA_DIR:
1875 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1878 case CHR_IOCTL_PP_EPP_READ_ADDR:
1879 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1880 struct ParallelIOArg *parg = arg;
1881 int n = read(fd, parg->buffer, parg->count);
1882 if (n != parg->count) {
1887 case CHR_IOCTL_PP_EPP_READ:
1888 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1889 struct ParallelIOArg *parg = arg;
1890 int n = read(fd, parg->buffer, parg->count);
1891 if (n != parg->count) {
1896 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1897 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1898 struct ParallelIOArg *parg = arg;
1899 int n = write(fd, parg->buffer, parg->count);
1900 if (n != parg->count) {
1905 case CHR_IOCTL_PP_EPP_WRITE:
1906 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1907 struct ParallelIOArg *parg = arg;
1908 int n = write(fd, parg->buffer, parg->count);
1909 if (n != parg->count) {
1920 static void pp_close(CharDriverState *chr)
1922 ParallelCharDriver *drv = chr->opaque;
1925 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1926 ioctl(fd, PPRELEASE);
1929 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1932 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1933 ChardevCommon *backend,
1936 CharDriverState *chr;
1937 ParallelCharDriver *drv;
1939 if (ioctl(fd, PPCLAIM) < 0) {
1940 error_setg_errno(errp, errno, "not a parallel port");
1945 chr = qemu_chr_alloc(backend, errp);
1950 drv = g_new0(ParallelCharDriver, 1);
1952 chr->chr_write = null_chr_write;
1953 chr->chr_ioctl = pp_ioctl;
1954 chr->chr_close = pp_close;
1957 drv->mode = IEEE1284_MODE_COMPAT;
1961 #endif /* __linux__ */
1963 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1965 #define HAVE_CHARDEV_PARPORT 1
1967 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1969 int fd = (int)(intptr_t)chr->opaque;
1973 case CHR_IOCTL_PP_READ_DATA:
1974 if (ioctl(fd, PPIGDATA, &b) < 0)
1976 *(uint8_t *)arg = b;
1978 case CHR_IOCTL_PP_WRITE_DATA:
1979 b = *(uint8_t *)arg;
1980 if (ioctl(fd, PPISDATA, &b) < 0)
1983 case CHR_IOCTL_PP_READ_CONTROL:
1984 if (ioctl(fd, PPIGCTRL, &b) < 0)
1986 *(uint8_t *)arg = b;
1988 case CHR_IOCTL_PP_WRITE_CONTROL:
1989 b = *(uint8_t *)arg;
1990 if (ioctl(fd, PPISCTRL, &b) < 0)
1993 case CHR_IOCTL_PP_READ_STATUS:
1994 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1996 *(uint8_t *)arg = b;
2004 static CharDriverState *qemu_chr_open_pp_fd(int fd,
2005 ChardevCommon *backend,
2008 CharDriverState *chr;
2010 chr = qemu_chr_alloc(backend, errp);
2014 chr->opaque = (void *)(intptr_t)fd;
2015 chr->chr_write = null_chr_write;
2016 chr->chr_ioctl = pp_ioctl;
2017 chr->explicit_be_open = true;
2024 #define HAVE_CHARDEV_SERIAL 1
2028 HANDLE hcom, hrecv, hsend;
2033 /* Protected by the CharDriverState chr_write_lock. */
2039 HANDLE hInputReadyEvent;
2040 HANDLE hInputDoneEvent;
2041 HANDLE hInputThread;
2042 uint8_t win_stdio_buf;
2043 } WinStdioCharState;
2045 #define NSENDBUF 2048
2046 #define NRECVBUF 2048
2047 #define MAXCONNECT 1
2048 #define NTIMEOUT 5000
2050 static int win_chr_poll(void *opaque);
2051 static int win_chr_pipe_poll(void *opaque);
2053 static void win_chr_close(CharDriverState *chr)
2055 WinCharState *s = chr->opaque;
2058 CloseHandle(s->hsend);
2062 CloseHandle(s->hrecv);
2066 CloseHandle(s->hcom);
2070 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2072 qemu_del_polling_cb(win_chr_poll, chr);
2074 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2077 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
2079 WinCharState *s = chr->opaque;
2081 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2086 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2088 error_setg(errp, "Failed CreateEvent");
2091 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2093 error_setg(errp, "Failed CreateEvent");
2097 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2098 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2099 if (s->hcom == INVALID_HANDLE_VALUE) {
2100 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
2105 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2106 error_setg(errp, "Failed SetupComm");
2110 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2111 size = sizeof(COMMCONFIG);
2112 GetDefaultCommConfig(filename, &comcfg, &size);
2113 comcfg.dcb.DCBlength = sizeof(DCB);
2114 CommConfigDialog(filename, NULL, &comcfg);
2116 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2117 error_setg(errp, "Failed SetCommState");
2121 if (!SetCommMask(s->hcom, EV_ERR)) {
2122 error_setg(errp, "Failed SetCommMask");
2126 cto.ReadIntervalTimeout = MAXDWORD;
2127 if (!SetCommTimeouts(s->hcom, &cto)) {
2128 error_setg(errp, "Failed SetCommTimeouts");
2132 if (!ClearCommError(s->hcom, &err, &comstat)) {
2133 error_setg(errp, "Failed ClearCommError");
2136 qemu_add_polling_cb(win_chr_poll, chr);
2144 /* Called with chr_write_lock held. */
2145 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2147 WinCharState *s = chr->opaque;
2148 DWORD len, ret, size, err;
2151 ZeroMemory(&s->osend, sizeof(s->osend));
2152 s->osend.hEvent = s->hsend;
2155 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2157 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2159 err = GetLastError();
2160 if (err == ERROR_IO_PENDING) {
2161 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2179 static int win_chr_read_poll(CharDriverState *chr)
2181 WinCharState *s = chr->opaque;
2183 s->max_size = qemu_chr_be_can_write(chr);
2187 static void win_chr_readfile(CharDriverState *chr)
2189 WinCharState *s = chr->opaque;
2191 uint8_t buf[READ_BUF_LEN];
2194 ZeroMemory(&s->orecv, sizeof(s->orecv));
2195 s->orecv.hEvent = s->hrecv;
2196 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2198 err = GetLastError();
2199 if (err == ERROR_IO_PENDING) {
2200 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2205 qemu_chr_be_write(chr, buf, size);
2209 static void win_chr_read(CharDriverState *chr)
2211 WinCharState *s = chr->opaque;
2213 if (s->len > s->max_size)
2214 s->len = s->max_size;
2218 win_chr_readfile(chr);
2221 static int win_chr_poll(void *opaque)
2223 CharDriverState *chr = opaque;
2224 WinCharState *s = chr->opaque;
2228 ClearCommError(s->hcom, &comerr, &status);
2229 if (status.cbInQue > 0) {
2230 s->len = status.cbInQue;
2231 win_chr_read_poll(chr);
2238 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2239 ChardevCommon *backend,
2242 CharDriverState *chr;
2245 chr = qemu_chr_alloc(backend, errp);
2249 s = g_new0(WinCharState, 1);
2251 chr->chr_write = win_chr_write;
2252 chr->chr_close = win_chr_close;
2254 if (win_chr_init(chr, filename, errp) < 0) {
2256 qemu_chr_free_common(chr);
2262 static int win_chr_pipe_poll(void *opaque)
2264 CharDriverState *chr = opaque;
2265 WinCharState *s = chr->opaque;
2268 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2271 win_chr_read_poll(chr);
2278 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2281 WinCharState *s = chr->opaque;
2289 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2291 error_setg(errp, "Failed CreateEvent");
2294 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2296 error_setg(errp, "Failed CreateEvent");
2300 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2301 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2302 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2304 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2306 if (s->hcom == INVALID_HANDLE_VALUE) {
2307 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2312 ZeroMemory(&ov, sizeof(ov));
2313 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2314 ret = ConnectNamedPipe(s->hcom, &ov);
2316 error_setg(errp, "Failed ConnectNamedPipe");
2320 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2322 error_setg(errp, "Failed GetOverlappedResult");
2324 CloseHandle(ov.hEvent);
2331 CloseHandle(ov.hEvent);
2334 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2343 static CharDriverState *qemu_chr_open_pipe(const char *id,
2344 ChardevBackend *backend,
2348 ChardevHostdev *opts = backend->u.pipe.data;
2349 const char *filename = opts->device;
2350 CharDriverState *chr;
2352 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2354 chr = qemu_chr_alloc(common, errp);
2358 s = g_new0(WinCharState, 1);
2360 chr->chr_write = win_chr_write;
2361 chr->chr_close = win_chr_close;
2363 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2365 qemu_chr_free_common(chr);
2371 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2372 ChardevCommon *backend,
2375 CharDriverState *chr;
2378 chr = qemu_chr_alloc(backend, errp);
2382 s = g_new0(WinCharState, 1);
2385 chr->chr_write = win_chr_write;
2389 static CharDriverState *qemu_chr_open_win_con(const char *id,
2390 ChardevBackend *backend,
2394 ChardevCommon *common = backend->u.console.data;
2395 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2399 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2401 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2408 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2418 static void win_stdio_wait_func(void *opaque)
2420 CharDriverState *chr = opaque;
2421 WinStdioCharState *stdio = chr->opaque;
2422 INPUT_RECORD buf[4];
2427 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2430 /* Avoid error storm */
2431 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2435 for (i = 0; i < dwSize; i++) {
2436 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2438 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2440 if (kev->uChar.AsciiChar != 0) {
2441 for (j = 0; j < kev->wRepeatCount; j++) {
2442 if (qemu_chr_be_can_write(chr)) {
2443 uint8_t c = kev->uChar.AsciiChar;
2444 qemu_chr_be_write(chr, &c, 1);
2452 static DWORD WINAPI win_stdio_thread(LPVOID param)
2454 CharDriverState *chr = param;
2455 WinStdioCharState *stdio = chr->opaque;
2461 /* Wait for one byte */
2462 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2464 /* Exit in case of error, continue if nothing read */
2472 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2473 if (stdio->win_stdio_buf == '\r') {
2477 /* Signal the main thread and wait until the byte was eaten */
2478 if (!SetEvent(stdio->hInputReadyEvent)) {
2481 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2487 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2491 static void win_stdio_thread_wait_func(void *opaque)
2493 CharDriverState *chr = opaque;
2494 WinStdioCharState *stdio = chr->opaque;
2496 if (qemu_chr_be_can_write(chr)) {
2497 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2500 SetEvent(stdio->hInputDoneEvent);
2503 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2505 WinStdioCharState *stdio = chr->opaque;
2508 GetConsoleMode(stdio->hStdIn, &dwMode);
2511 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2513 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2517 static void win_stdio_close(CharDriverState *chr)
2519 WinStdioCharState *stdio = chr->opaque;
2521 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2522 CloseHandle(stdio->hInputReadyEvent);
2524 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2525 CloseHandle(stdio->hInputDoneEvent);
2527 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2528 TerminateThread(stdio->hInputThread, 0);
2531 g_free(chr->opaque);
2534 static CharDriverState *qemu_chr_open_stdio(const char *id,
2535 ChardevBackend *backend,
2539 CharDriverState *chr;
2540 WinStdioCharState *stdio;
2543 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio.data);
2545 chr = qemu_chr_alloc(common, errp);
2549 stdio = g_new0(WinStdioCharState, 1);
2551 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2552 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2553 error_setg(errp, "cannot open stdio: invalid handle");
2557 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2559 chr->opaque = stdio;
2560 chr->chr_write = win_stdio_write;
2561 chr->chr_close = win_stdio_close;
2564 if (qemu_add_wait_object(stdio->hStdIn,
2565 win_stdio_wait_func, chr)) {
2566 error_setg(errp, "qemu_add_wait_object: failed");
2572 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2573 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2574 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2575 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2576 error_setg(errp, "cannot create event");
2579 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2580 win_stdio_thread_wait_func, chr)) {
2581 error_setg(errp, "qemu_add_wait_object: failed");
2584 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2587 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2588 error_setg(errp, "cannot create stdio thread");
2593 dwMode |= ENABLE_LINE_INPUT;
2596 /* set the terminal in raw mode */
2597 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2598 dwMode |= ENABLE_PROCESSED_INPUT;
2601 SetConsoleMode(stdio->hStdIn, dwMode);
2603 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2604 qemu_chr_set_echo_win_stdio(chr, false);
2609 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2611 CloseHandle(stdio->hInputReadyEvent);
2612 CloseHandle(stdio->hInputDoneEvent);
2614 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2617 #endif /* !_WIN32 */
2619 /***********************************************************/
2620 /* UDP Net console */
2624 uint8_t buf[READ_BUF_LEN];
2630 /* Called with chr_write_lock held. */
2631 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2633 NetCharDriver *s = chr->opaque;
2635 return qio_channel_write(
2636 s->ioc, (const char *)buf, len, NULL);
2639 static int udp_chr_read_poll(void *opaque)
2641 CharDriverState *chr = opaque;
2642 NetCharDriver *s = chr->opaque;
2644 s->max_size = qemu_chr_be_can_write(chr);
2646 /* If there were any stray characters in the queue process them
2649 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2650 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2652 s->max_size = qemu_chr_be_can_write(chr);
2657 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2659 CharDriverState *chr = opaque;
2660 NetCharDriver *s = chr->opaque;
2663 if (s->max_size == 0) {
2666 ret = qio_channel_read(
2667 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2669 remove_fd_in_watch(chr);
2675 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2676 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2678 s->max_size = qemu_chr_be_can_write(chr);
2684 static void udp_chr_update_read_handler(CharDriverState *chr,
2685 GMainContext *context,
2688 NetCharDriver *s = chr->opaque;
2690 remove_fd_in_watch(chr);
2692 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2699 static void udp_chr_close(CharDriverState *chr)
2701 NetCharDriver *s = chr->opaque;
2703 remove_fd_in_watch(chr);
2705 object_unref(OBJECT(s->ioc));
2708 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2711 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2712 ChardevCommon *backend,
2715 CharDriverState *chr = NULL;
2716 NetCharDriver *s = NULL;
2718 chr = qemu_chr_alloc(backend, errp);
2722 s = g_new0(NetCharDriver, 1);
2724 s->ioc = QIO_CHANNEL(sioc);
2728 chr->chr_write = udp_chr_write;
2729 chr->chr_update_read_handler = udp_chr_update_read_handler;
2730 chr->chr_close = udp_chr_close;
2731 /* be isn't opened until we get a connection */
2732 chr->explicit_be_open = true;
2736 /***********************************************************/
2737 /* TCP Net console */
2740 QIOChannel *ioc; /* Client I/O channel */
2741 QIOChannelSocket *sioc; /* Client master channel */
2742 QIOChannelSocket *listen_ioc;
2744 QCryptoTLSCreds *tls_creds;
2751 size_t read_msgfds_num;
2753 size_t write_msgfds_num;
2755 SocketAddress *addr;
2759 guint reconnect_timer;
2760 int64_t reconnect_time;
2761 bool connect_err_reported;
2764 static gboolean socket_reconnect_timeout(gpointer opaque);
2766 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2768 TCPCharDriver *s = chr->opaque;
2769 assert(s->connected == 0);
2770 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2771 socket_reconnect_timeout, chr);
2774 static void check_report_connect_error(CharDriverState *chr,
2777 TCPCharDriver *s = chr->opaque;
2779 if (!s->connect_err_reported) {
2780 error_report("Unable to connect character device %s: %s",
2781 chr->label, error_get_pretty(err));
2782 s->connect_err_reported = true;
2784 qemu_chr_socket_restart_timer(chr);
2787 static gboolean tcp_chr_accept(QIOChannel *chan,
2791 /* Called with chr_write_lock held. */
2792 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2794 TCPCharDriver *s = chr->opaque;
2796 int ret = io_channel_send_full(s->ioc, buf, len,
2798 s->write_msgfds_num);
2800 /* free the written msgfds, no matter what */
2801 if (s->write_msgfds_num) {
2802 g_free(s->write_msgfds);
2803 s->write_msgfds = 0;
2804 s->write_msgfds_num = 0;
2809 /* XXX: indicate an error ? */
2814 static int tcp_chr_read_poll(void *opaque)
2816 CharDriverState *chr = opaque;
2817 TCPCharDriver *s = chr->opaque;
2820 s->max_size = qemu_chr_be_can_write(chr);
2825 #define IAC_BREAK 243
2826 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2828 uint8_t *buf, int *size)
2830 /* Handle any telnet client's basic IAC options to satisfy char by
2831 * char mode with no echo. All IAC options will be removed from
2832 * the buf and the do_telnetopt variable will be used to track the
2833 * state of the width of the IAC information.
2835 * IAC commands come in sets of 3 bytes with the exception of the
2836 * "IAC BREAK" command and the double IAC.
2842 for (i = 0; i < *size; i++) {
2843 if (s->do_telnetopt > 1) {
2844 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2845 /* Double IAC means send an IAC */
2849 s->do_telnetopt = 1;
2851 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2852 /* Handle IAC break commands by sending a serial break */
2853 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2858 if (s->do_telnetopt >= 4) {
2859 s->do_telnetopt = 1;
2862 if ((unsigned char)buf[i] == IAC) {
2863 s->do_telnetopt = 2;
2874 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2876 TCPCharDriver *s = chr->opaque;
2877 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2879 assert(num <= TCP_MAX_FDS);
2884 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2886 /* Close unused fds */
2887 for (i = to_copy; i < s->read_msgfds_num; i++) {
2888 close(s->read_msgfds[i]);
2891 g_free(s->read_msgfds);
2893 s->read_msgfds_num = 0;
2899 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2901 TCPCharDriver *s = chr->opaque;
2903 /* clear old pending fd array */
2904 g_free(s->write_msgfds);
2905 s->write_msgfds = NULL;
2906 s->write_msgfds_num = 0;
2908 if (!s->connected ||
2909 !qio_channel_has_feature(s->ioc,
2910 QIO_CHANNEL_FEATURE_FD_PASS)) {
2915 s->write_msgfds = g_new(int, num);
2916 memcpy(s->write_msgfds, fds, num * sizeof(int));
2919 s->write_msgfds_num = num;
2924 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2926 TCPCharDriver *s = chr->opaque;
2927 struct iovec iov = { .iov_base = buf, .iov_len = len };
2931 size_t msgfds_num = 0;
2933 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2934 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2935 &msgfds, &msgfds_num,
2938 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2943 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2946 } else if (ret == -1) {
2951 /* close and clean read_msgfds */
2952 for (i = 0; i < s->read_msgfds_num; i++) {
2953 close(s->read_msgfds[i]);
2956 if (s->read_msgfds_num) {
2957 g_free(s->read_msgfds);
2960 s->read_msgfds = msgfds;
2961 s->read_msgfds_num = msgfds_num;
2964 for (i = 0; i < s->read_msgfds_num; i++) {
2965 int fd = s->read_msgfds[i];
2970 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2973 #ifndef MSG_CMSG_CLOEXEC
2974 qemu_set_cloexec(fd);
2981 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2983 TCPCharDriver *s = chr->opaque;
2984 return qio_channel_create_watch(s->ioc, cond);
2987 static void tcp_chr_free_connection(CharDriverState *chr)
2989 TCPCharDriver *s = chr->opaque;
2992 if (!s->connected) {
2996 if (s->read_msgfds_num) {
2997 for (i = 0; i < s->read_msgfds_num; i++) {
2998 close(s->read_msgfds[i]);
3000 g_free(s->read_msgfds);
3001 s->read_msgfds = NULL;
3002 s->read_msgfds_num = 0;
3005 tcp_set_msgfds(chr, NULL, 0);
3006 remove_fd_in_watch(chr);
3007 object_unref(OBJECT(s->sioc));
3009 object_unref(OBJECT(s->ioc));
3011 g_free(chr->filename);
3012 chr->filename = NULL;
3016 static void tcp_chr_disconnect(CharDriverState *chr)
3018 TCPCharDriver *s = chr->opaque;
3020 if (!s->connected) {
3024 tcp_chr_free_connection(chr);
3026 if (s->listen_ioc) {
3027 s->listen_tag = qio_channel_add_watch(
3028 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
3030 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
3031 s->is_listen, s->is_telnet);
3032 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3033 if (s->reconnect_time) {
3034 qemu_chr_socket_restart_timer(chr);
3038 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
3040 CharDriverState *chr = opaque;
3041 TCPCharDriver *s = chr->opaque;
3042 uint8_t buf[READ_BUF_LEN];
3045 if (!s->connected || s->max_size <= 0) {
3049 if (len > s->max_size)
3051 size = tcp_chr_recv(chr, (void *)buf, len);
3052 if (size == 0 || size == -1) {
3053 /* connection closed */
3054 tcp_chr_disconnect(chr);
3055 } else if (size > 0) {
3056 if (s->do_telnetopt)
3057 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3059 qemu_chr_be_write(chr, buf, size);
3065 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
3067 TCPCharDriver *s = chr->opaque;
3070 if (!s->connected) {
3074 size = tcp_chr_recv(chr, (void *) buf, len);
3076 /* connection closed */
3077 tcp_chr_disconnect(chr);
3083 static void tcp_chr_connect(void *opaque)
3085 CharDriverState *chr = opaque;
3086 TCPCharDriver *s = chr->opaque;
3088 g_free(chr->filename);
3089 chr->filename = sockaddr_to_str(
3090 &s->sioc->localAddr, s->sioc->localAddrLen,
3091 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
3092 s->is_listen, s->is_telnet);
3096 chr->fd_in_tag = io_add_watch_poll(s->ioc,
3101 qemu_chr_be_generic_open(chr);
3104 static void tcp_chr_update_read_handler(CharDriverState *chr,
3105 GMainContext *context,
3108 TCPCharDriver *s = chr->opaque;
3110 if (!s->connected) {
3114 remove_fd_in_watch(chr);
3116 chr->fd_in_tag = io_add_watch_poll(s->ioc,
3124 CharDriverState *chr;
3127 } TCPCharDriverTelnetInit;
3129 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
3130 GIOCondition cond G_GNUC_UNUSED,
3133 TCPCharDriverTelnetInit *init = user_data;
3136 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
3138 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3141 tcp_chr_disconnect(init->chr);
3145 init->buflen -= ret;
3147 if (init->buflen == 0) {
3148 tcp_chr_connect(init->chr);
3152 memmove(init->buf, init->buf + ret, init->buflen);
3157 static void tcp_chr_telnet_init(CharDriverState *chr)
3159 TCPCharDriver *s = chr->opaque;
3160 TCPCharDriverTelnetInit *init =
3161 g_new0(TCPCharDriverTelnetInit, 1);
3167 #define IACSET(x, a, b, c) \
3174 /* Prep the telnet negotion to put telnet in binary,
3175 * no echo, single char mode */
3176 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3177 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3178 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3179 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3183 qio_channel_add_watch(
3185 tcp_chr_telnet_init_io,
3190 static void tcp_chr_tls_handshake(Object *source,
3194 CharDriverState *chr = user_data;
3195 TCPCharDriver *s = chr->opaque;
3198 tcp_chr_disconnect(chr);
3200 if (s->do_telnetopt) {
3201 tcp_chr_telnet_init(chr);
3203 tcp_chr_connect(chr);
3209 static void tcp_chr_tls_init(CharDriverState *chr)
3211 TCPCharDriver *s = chr->opaque;
3212 QIOChannelTLS *tioc;
3216 tioc = qio_channel_tls_new_server(
3217 s->ioc, s->tls_creds,
3218 NULL, /* XXX Use an ACL */
3221 tioc = qio_channel_tls_new_client(
3222 s->ioc, s->tls_creds,
3223 s->addr->u.inet.data->host,
3228 tcp_chr_disconnect(chr);
3231 object_unref(OBJECT(s->ioc));
3232 s->ioc = QIO_CHANNEL(tioc);
3234 qio_channel_tls_handshake(tioc,
3235 tcp_chr_tls_handshake,
3241 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3243 TCPCharDriver *s = chr->opaque;
3244 if (s->ioc != NULL) {
3248 s->ioc = QIO_CHANNEL(sioc);
3249 object_ref(OBJECT(sioc));
3251 object_ref(OBJECT(sioc));
3253 qio_channel_set_blocking(s->ioc, false, NULL);
3255 if (s->do_nodelay) {
3256 qio_channel_set_delay(s->ioc, false);
3258 if (s->listen_tag) {
3259 g_source_remove(s->listen_tag);
3264 tcp_chr_tls_init(chr);
3266 if (s->do_telnetopt) {
3267 tcp_chr_telnet_init(chr);
3269 tcp_chr_connect(chr);
3277 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3280 QIOChannelSocket *sioc;
3282 sioc = qio_channel_socket_new_fd(fd, NULL);
3286 ret = tcp_chr_new_client(chr, sioc);
3287 object_unref(OBJECT(sioc));
3291 static gboolean tcp_chr_accept(QIOChannel *channel,
3295 CharDriverState *chr = opaque;
3296 QIOChannelSocket *sioc;
3298 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3304 tcp_chr_new_client(chr, sioc);
3306 object_unref(OBJECT(sioc));
3311 static int tcp_chr_wait_connected(CharDriverState *chr, Error **errp)
3313 TCPCharDriver *s = chr->opaque;
3314 QIOChannelSocket *sioc;
3316 /* It can't wait on s->connected, since it is set asynchronously
3317 * in TLS and telnet cases, only wait for an accepted socket */
3320 fprintf(stderr, "QEMU waiting for connection on: %s\n",
3322 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), true, NULL);
3323 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
3324 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
3326 sioc = qio_channel_socket_new();
3327 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3328 object_unref(OBJECT(sioc));
3331 tcp_chr_new_client(chr, sioc);
3332 object_unref(OBJECT(sioc));
3339 static int qemu_chr_wait_connected(CharDriverState *chr, Error **errp)
3341 if (chr->chr_wait_connected) {
3342 return chr->chr_wait_connected(chr, errp);
3348 int qemu_chr_fe_wait_connected(CharBackend *be, Error **errp)
3350 return qemu_chr_wait_connected(be->chr, errp);
3353 static void tcp_chr_close(CharDriverState *chr)
3355 TCPCharDriver *s = chr->opaque;
3357 tcp_chr_free_connection(chr);
3359 if (s->reconnect_timer) {
3360 g_source_remove(s->reconnect_timer);
3361 s->reconnect_timer = 0;
3363 qapi_free_SocketAddress(s->addr);
3364 if (s->listen_tag) {
3365 g_source_remove(s->listen_tag);
3368 if (s->listen_ioc) {
3369 object_unref(OBJECT(s->listen_ioc));
3372 object_unref(OBJECT(s->tls_creds));
3375 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3379 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3381 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3382 CharDriverState *chr = opaque;
3383 TCPCharDriver *s = chr->opaque;
3386 check_report_connect_error(chr, err);
3391 s->connect_err_reported = false;
3392 tcp_chr_new_client(chr, sioc);
3393 object_unref(OBJECT(sioc));
3397 /*********************************************************/
3398 /* Ring buffer chardev */
3405 } RingBufCharDriver;
3407 static size_t ringbuf_count(const CharDriverState *chr)
3409 const RingBufCharDriver *d = chr->opaque;
3411 return d->prod - d->cons;
3414 /* Called with chr_write_lock held. */
3415 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3417 RingBufCharDriver *d = chr->opaque;
3420 if (!buf || (len < 0)) {
3424 for (i = 0; i < len; i++ ) {
3425 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3426 if (d->prod - d->cons > d->size) {
3427 d->cons = d->prod - d->size;
3434 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3436 RingBufCharDriver *d = chr->opaque;
3439 qemu_mutex_lock(&chr->chr_write_lock);
3440 for (i = 0; i < len && d->cons != d->prod; i++) {
3441 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3443 qemu_mutex_unlock(&chr->chr_write_lock);
3448 static void ringbuf_chr_close(struct CharDriverState *chr)
3450 RingBufCharDriver *d = chr->opaque;
3457 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3458 ChardevBackend *backend,
3462 ChardevRingbuf *opts = backend->u.ringbuf.data;
3463 ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
3464 CharDriverState *chr;
3465 RingBufCharDriver *d;
3467 chr = qemu_chr_alloc(common, errp);
3471 d = g_malloc(sizeof(*d));
3473 d->size = opts->has_size ? opts->size : 65536;
3475 /* The size must be power of 2 */
3476 if (d->size & (d->size - 1)) {
3477 error_setg(errp, "size of ringbuf chardev must be power of two");
3483 d->cbuf = g_malloc0(d->size);
3486 chr->chr_write = ringbuf_chr_write;
3487 chr->chr_close = ringbuf_chr_close;
3493 qemu_chr_free_common(chr);
3497 bool chr_is_ringbuf(const CharDriverState *chr)
3499 return chr->chr_write == ringbuf_chr_write;
3502 void qmp_ringbuf_write(const char *device, const char *data,
3503 bool has_format, enum DataFormat format,
3506 CharDriverState *chr;
3507 const uint8_t *write_data;
3511 chr = qemu_chr_find(device);
3513 error_setg(errp, "Device '%s' not found", device);
3517 if (!chr_is_ringbuf(chr)) {
3518 error_setg(errp,"%s is not a ringbuf device", device);
3522 if (has_format && (format == DATA_FORMAT_BASE64)) {
3523 write_data = qbase64_decode(data, -1,
3530 write_data = (uint8_t *)data;
3531 write_count = strlen(data);
3534 ret = ringbuf_chr_write(chr, write_data, write_count);
3536 if (write_data != (uint8_t *)data) {
3537 g_free((void *)write_data);
3541 error_setg(errp, "Failed to write to device %s", device);
3546 char *qmp_ringbuf_read(const char *device, int64_t size,
3547 bool has_format, enum DataFormat format,
3550 CharDriverState *chr;
3555 chr = qemu_chr_find(device);
3557 error_setg(errp, "Device '%s' not found", device);
3561 if (!chr_is_ringbuf(chr)) {
3562 error_setg(errp,"%s is not a ringbuf device", device);
3567 error_setg(errp, "size must be greater than zero");
3571 count = ringbuf_count(chr);
3572 size = size > count ? count : size;
3573 read_data = g_malloc(size + 1);
3575 ringbuf_chr_read(chr, read_data, size);
3577 if (has_format && (format == DATA_FORMAT_BASE64)) {
3578 data = g_base64_encode(read_data, size);
3582 * FIXME should read only complete, valid UTF-8 characters up
3583 * to @size bytes. Invalid sequences should be replaced by a
3584 * suitable replacement character. Except when (and only
3585 * when) ring buffer lost characters since last read, initial
3586 * continuation characters should be dropped.
3588 read_data[size] = 0;
3589 data = (char *)read_data;
3595 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3597 char host[65], port[33], width[8], height[8];
3601 Error *local_err = NULL;
3603 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3605 error_report_err(local_err);
3609 if (strstart(filename, "mon:", &p)) {
3611 qemu_opt_set(opts, "mux", "on", &error_abort);
3612 if (strcmp(filename, "stdio") == 0) {
3613 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3614 * but pass it to the guest. Handle this only for compat syntax,
3615 * for -chardev syntax we have special option for this.
3616 * This is what -nographic did, redirecting+muxing serial+monitor
3617 * to stdio causing Ctrl+C to be passed to guest. */
3618 qemu_opt_set(opts, "signal", "off", &error_abort);
3622 if (strcmp(filename, "null") == 0 ||
3623 strcmp(filename, "pty") == 0 ||
3624 strcmp(filename, "msmouse") == 0 ||
3625 strcmp(filename, "braille") == 0 ||
3626 strcmp(filename, "testdev") == 0 ||
3627 strcmp(filename, "stdio") == 0) {
3628 qemu_opt_set(opts, "backend", filename, &error_abort);
3631 if (strstart(filename, "vc", &p)) {
3632 qemu_opt_set(opts, "backend", "vc", &error_abort);
3634 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3636 qemu_opt_set(opts, "width", width, &error_abort);
3637 qemu_opt_set(opts, "height", height, &error_abort);
3638 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3640 qemu_opt_set(opts, "cols", width, &error_abort);
3641 qemu_opt_set(opts, "rows", height, &error_abort);
3648 if (strcmp(filename, "con:") == 0) {
3649 qemu_opt_set(opts, "backend", "console", &error_abort);
3652 if (strstart(filename, "COM", NULL)) {
3653 qemu_opt_set(opts, "backend", "serial", &error_abort);
3654 qemu_opt_set(opts, "path", filename, &error_abort);
3657 if (strstart(filename, "file:", &p)) {
3658 qemu_opt_set(opts, "backend", "file", &error_abort);
3659 qemu_opt_set(opts, "path", p, &error_abort);
3662 if (strstart(filename, "pipe:", &p)) {
3663 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3664 qemu_opt_set(opts, "path", p, &error_abort);
3667 if (strstart(filename, "tcp:", &p) ||
3668 strstart(filename, "telnet:", &p)) {
3669 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3671 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3674 qemu_opt_set(opts, "backend", "socket", &error_abort);
3675 qemu_opt_set(opts, "host", host, &error_abort);
3676 qemu_opt_set(opts, "port", port, &error_abort);
3677 if (p[pos] == ',') {
3678 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3680 error_report_err(local_err);
3684 if (strstart(filename, "telnet:", &p))
3685 qemu_opt_set(opts, "telnet", "on", &error_abort);
3688 if (strstart(filename, "udp:", &p)) {
3689 qemu_opt_set(opts, "backend", "udp", &error_abort);
3690 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3692 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3696 qemu_opt_set(opts, "host", host, &error_abort);
3697 qemu_opt_set(opts, "port", port, &error_abort);
3698 if (p[pos] == '@') {
3700 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3702 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3706 qemu_opt_set(opts, "localaddr", host, &error_abort);
3707 qemu_opt_set(opts, "localport", port, &error_abort);
3711 if (strstart(filename, "unix:", &p)) {
3712 qemu_opt_set(opts, "backend", "socket", &error_abort);
3713 qemu_opts_do_parse(opts, p, "path", &local_err);
3715 error_report_err(local_err);
3720 if (strstart(filename, "/dev/parport", NULL) ||
3721 strstart(filename, "/dev/ppi", NULL)) {
3722 qemu_opt_set(opts, "backend", "parport", &error_abort);
3723 qemu_opt_set(opts, "path", filename, &error_abort);
3726 if (strstart(filename, "/dev/", NULL)) {
3727 qemu_opt_set(opts, "backend", "tty", &error_abort);
3728 qemu_opt_set(opts, "path", filename, &error_abort);
3733 qemu_opts_del(opts);
3737 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3739 const char *logfile = qemu_opt_get(opts, "logfile");
3741 backend->has_logfile = logfile != NULL;
3742 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3744 backend->has_logappend = true;
3745 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3749 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3752 const char *path = qemu_opt_get(opts, "path");
3756 error_setg(errp, "chardev: file: no filename given");
3759 file = backend->u.file.data = g_new0(ChardevFile, 1);
3760 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3761 file->out = g_strdup(path);
3763 file->has_append = true;
3764 file->append = qemu_opt_get_bool(opts, "append", false);
3767 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3770 ChardevStdio *stdio;
3772 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3773 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3774 stdio->has_signal = true;
3775 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3778 #ifdef HAVE_CHARDEV_SERIAL
3779 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3782 const char *device = qemu_opt_get(opts, "path");
3783 ChardevHostdev *serial;
3785 if (device == NULL) {
3786 error_setg(errp, "chardev: serial/tty: no device path given");
3789 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3790 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3791 serial->device = g_strdup(device);
3795 #ifdef HAVE_CHARDEV_PARPORT
3796 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3799 const char *device = qemu_opt_get(opts, "path");
3800 ChardevHostdev *parallel;
3802 if (device == NULL) {
3803 error_setg(errp, "chardev: parallel: no device path given");
3806 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3807 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3808 parallel->device = g_strdup(device);
3812 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3815 const char *device = qemu_opt_get(opts, "path");
3816 ChardevHostdev *dev;
3818 if (device == NULL) {
3819 error_setg(errp, "chardev: pipe: no device path given");
3822 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3823 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3824 dev->device = g_strdup(device);
3827 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3831 ChardevRingbuf *ringbuf;
3833 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3834 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3836 val = qemu_opt_get_size(opts, "size", 0);
3838 ringbuf->has_size = true;
3839 ringbuf->size = val;
3843 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3846 const char *chardev = qemu_opt_get(opts, "chardev");
3849 if (chardev == NULL) {
3850 error_setg(errp, "chardev: mux: no chardev given");
3853 mux = backend->u.mux.data = g_new0(ChardevMux, 1);
3854 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
3855 mux->chardev = g_strdup(chardev);
3858 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3861 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3862 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3863 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3864 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3865 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3866 const char *path = qemu_opt_get(opts, "path");
3867 const char *host = qemu_opt_get(opts, "host");
3868 const char *port = qemu_opt_get(opts, "port");
3869 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3870 SocketAddress *addr;
3871 ChardevSocket *sock;
3875 error_setg(errp, "chardev: socket: no host given");
3879 error_setg(errp, "chardev: socket: no port given");
3884 error_setg(errp, "TLS can only be used over TCP socket");
3889 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
3890 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
3892 sock->has_nodelay = true;
3893 sock->nodelay = do_nodelay;
3894 sock->has_server = true;
3895 sock->server = is_listen;
3896 sock->has_telnet = true;
3897 sock->telnet = is_telnet;
3898 sock->has_wait = true;
3899 sock->wait = is_waitconnect;
3900 sock->has_reconnect = true;
3901 sock->reconnect = reconnect;
3902 sock->tls_creds = g_strdup(tls_creds);
3904 addr = g_new0(SocketAddress, 1);
3906 UnixSocketAddress *q_unix;
3907 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3908 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
3909 q_unix->path = g_strdup(path);
3911 addr->type = SOCKET_ADDRESS_KIND_INET;
3912 addr->u.inet.data = g_new(InetSocketAddress, 1);
3913 *addr->u.inet.data = (InetSocketAddress) {
3914 .host = g_strdup(host),
3915 .port = g_strdup(port),
3916 .has_to = qemu_opt_get(opts, "to"),
3917 .to = qemu_opt_get_number(opts, "to", 0),
3918 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3919 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3920 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3921 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3927 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3930 const char *host = qemu_opt_get(opts, "host");
3931 const char *port = qemu_opt_get(opts, "port");
3932 const char *localaddr = qemu_opt_get(opts, "localaddr");
3933 const char *localport = qemu_opt_get(opts, "localport");
3934 bool has_local = false;
3935 SocketAddress *addr;
3938 if (host == NULL || strlen(host) == 0) {
3941 if (port == NULL || strlen(port) == 0) {
3942 error_setg(errp, "chardev: udp: remote port not specified");
3945 if (localport == NULL || strlen(localport) == 0) {
3950 if (localaddr == NULL || strlen(localaddr) == 0) {
3956 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
3957 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
3959 addr = g_new0(SocketAddress, 1);
3960 addr->type = SOCKET_ADDRESS_KIND_INET;
3961 addr->u.inet.data = g_new(InetSocketAddress, 1);
3962 *addr->u.inet.data = (InetSocketAddress) {
3963 .host = g_strdup(host),
3964 .port = g_strdup(port),
3965 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3966 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3967 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3968 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3973 udp->has_local = true;
3974 addr = g_new0(SocketAddress, 1);
3975 addr->type = SOCKET_ADDRESS_KIND_INET;
3976 addr->u.inet.data = g_new(InetSocketAddress, 1);
3977 *addr->u.inet.data = (InetSocketAddress) {
3978 .host = g_strdup(localaddr),
3979 .port = g_strdup(localport),
3985 typedef struct CharDriver {
3987 ChardevBackendKind kind;
3988 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3989 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3990 ChardevReturn *ret, Error **errp);
3993 static GSList *backends;
3995 void register_char_driver(const char *name, ChardevBackendKind kind,
3996 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3997 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3998 ChardevReturn *ret, Error **errp))
4002 s = g_malloc0(sizeof(*s));
4003 s->name = g_strdup(name);
4008 backends = g_slist_append(backends, s);
4011 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
4014 Error *local_err = NULL;
4016 CharDriverState *chr;
4018 ChardevReturn *ret = NULL;
4019 ChardevBackend *backend;
4020 const char *id = qemu_opts_id(opts);
4023 if (qemu_opt_get(opts, "backend") == NULL) {
4024 error_setg(errp, "chardev: \"%s\" missing backend",
4025 qemu_opts_id(opts));
4029 if (is_help_option(qemu_opt_get(opts, "backend"))) {
4030 fprintf(stderr, "Available chardev backend types:\n");
4031 for (i = backends; i; i = i->next) {
4033 fprintf(stderr, "%s\n", cd->name);
4035 exit(!is_help_option(qemu_opt_get(opts, "backend")));
4039 error_setg(errp, "chardev: no id specified");
4043 for (i = backends; i; i = i->next) {
4046 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
4051 error_setg(errp, "chardev: backend \"%s\" not found",
4052 qemu_opt_get(opts, "backend"));
4056 backend = g_new0(ChardevBackend, 1);
4058 if (qemu_opt_get_bool(opts, "mux", 0)) {
4059 bid = g_strdup_printf("%s-base", id);
4063 backend->type = cd->kind;
4065 cd->parse(opts, backend, &local_err);
4067 error_propagate(errp, local_err);
4071 ChardevCommon *cc = g_new0(ChardevCommon, 1);
4072 qemu_chr_parse_common(opts, cc);
4073 backend->u.null.data = cc; /* Any ChardevCommon member would work */
4076 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
4082 qapi_free_ChardevBackend(backend);
4083 qapi_free_ChardevReturn(ret);
4084 backend = g_new0(ChardevBackend, 1);
4085 backend->u.mux.data = g_new0(ChardevMux, 1);
4086 backend->type = CHARDEV_BACKEND_KIND_MUX;
4087 backend->u.mux.data->chardev = g_strdup(bid);
4088 ret = qmp_chardev_add(id, backend, errp);
4090 chr = qemu_chr_find(bid);
4091 qemu_chr_delete(chr);
4097 chr = qemu_chr_find(id);
4100 qapi_free_ChardevBackend(backend);
4101 qapi_free_ChardevReturn(ret);
4109 CharDriverState *qemu_chr_new_noreplay(const char *label, const char *filename)
4112 CharDriverState *chr;
4116 if (strstart(filename, "chardev:", &p)) {
4117 return qemu_chr_find(p);
4120 opts = qemu_chr_parse_compat(label, filename);
4124 chr = qemu_chr_new_from_opts(opts, &err);
4126 error_report_err(err);
4128 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
4129 qemu_chr_fe_claim_no_fail(chr);
4130 monitor_init(chr, MONITOR_USE_READLINE);
4132 qemu_opts_del(opts);
4136 CharDriverState *qemu_chr_new(const char *label, const char *filename)
4138 CharDriverState *chr;
4139 chr = qemu_chr_new_noreplay(label, filename);
4141 chr->replay = replay_mode != REPLAY_MODE_NONE;
4142 if (chr->replay && chr->chr_ioctl) {
4144 "Replay: ioctl is not supported for serial devices yet\n");
4146 replay_register_char_driver(chr);
4151 void qemu_chr_fe_set_echo(CharBackend *be, bool echo)
4153 CharDriverState *chr = be->chr;
4155 if (chr->chr_set_echo) {
4156 chr->chr_set_echo(chr, echo);
4160 void qemu_chr_fe_set_open(CharBackend *be, int fe_open)
4162 CharDriverState *chr = be->chr;
4164 if (chr->fe_open == fe_open) {
4167 chr->fe_open = fe_open;
4168 if (chr->chr_set_fe_open) {
4169 chr->chr_set_fe_open(chr, fe_open);
4173 void qemu_chr_fe_event(CharBackend *be, int event)
4175 CharDriverState *chr = be->chr;
4177 if (chr->chr_fe_event) {
4178 chr->chr_fe_event(chr, event);
4182 guint qemu_chr_fe_add_watch(CharBackend *be, GIOCondition cond,
4183 GIOFunc func, void *user_data)
4185 CharDriverState *s = be->chr;
4189 if (s->chr_add_watch == NULL) {
4193 src = s->chr_add_watch(s, cond);
4198 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
4199 tag = g_source_attach(src, NULL);
4200 g_source_unref(src);
4205 int qemu_chr_fe_claim(CharDriverState *s)
4207 if (s->avail_connections < 1) {
4210 s->avail_connections--;
4214 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
4216 if (qemu_chr_fe_claim(s) != 0) {
4217 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
4218 __func__, s->label);
4223 void qemu_chr_fe_release(CharDriverState *s)
4225 s->avail_connections++;
4228 void qemu_chr_fe_disconnect(CharBackend *be)
4230 CharDriverState *chr = be->chr;
4232 if (chr->chr_disconnect) {
4233 chr->chr_disconnect(chr);
4237 static void qemu_chr_free_common(CharDriverState *chr)
4239 g_free(chr->filename);
4241 if (chr->logfd != -1) {
4244 qemu_mutex_destroy(&chr->chr_write_lock);
4248 void qemu_chr_free(CharDriverState *chr)
4250 if (chr->chr_close) {
4251 chr->chr_close(chr);
4253 qemu_chr_free_common(chr);
4256 void qemu_chr_delete(CharDriverState *chr)
4258 QTAILQ_REMOVE(&chardevs, chr, next);
4262 ChardevInfoList *qmp_query_chardev(Error **errp)
4264 ChardevInfoList *chr_list = NULL;
4265 CharDriverState *chr;
4267 QTAILQ_FOREACH(chr, &chardevs, next) {
4268 ChardevInfoList *info = g_malloc0(sizeof(*info));
4269 info->value = g_malloc0(sizeof(*info->value));
4270 info->value->label = g_strdup(chr->label);
4271 info->value->filename = g_strdup(chr->filename);
4272 info->value->frontend_open = chr->fe_open;
4274 info->next = chr_list;
4281 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4283 ChardevBackendInfoList *backend_list = NULL;
4284 CharDriver *c = NULL;
4287 for (i = backends; i; i = i->next) {
4288 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4290 info->value = g_malloc0(sizeof(*info->value));
4291 info->value->name = g_strdup(c->name);
4293 info->next = backend_list;
4294 backend_list = info;
4297 return backend_list;
4300 CharDriverState *qemu_chr_find(const char *name)
4302 CharDriverState *chr;
4304 QTAILQ_FOREACH(chr, &chardevs, next) {
4305 if (strcmp(chr->label, name) != 0)
4312 QemuOptsList qemu_chardev_opts = {
4314 .implied_opt_name = "backend",
4315 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4319 .type = QEMU_OPT_STRING,
4322 .type = QEMU_OPT_STRING,
4325 .type = QEMU_OPT_STRING,
4328 .type = QEMU_OPT_STRING,
4330 .name = "localaddr",
4331 .type = QEMU_OPT_STRING,
4333 .name = "localport",
4334 .type = QEMU_OPT_STRING,
4337 .type = QEMU_OPT_NUMBER,
4340 .type = QEMU_OPT_BOOL,
4343 .type = QEMU_OPT_BOOL,
4346 .type = QEMU_OPT_BOOL,
4349 .type = QEMU_OPT_BOOL,
4352 .type = QEMU_OPT_BOOL,
4354 .name = "reconnect",
4355 .type = QEMU_OPT_NUMBER,
4358 .type = QEMU_OPT_BOOL,
4360 .name = "tls-creds",
4361 .type = QEMU_OPT_STRING,
4364 .type = QEMU_OPT_NUMBER,
4367 .type = QEMU_OPT_NUMBER,
4370 .type = QEMU_OPT_NUMBER,
4373 .type = QEMU_OPT_NUMBER,
4376 .type = QEMU_OPT_BOOL,
4379 .type = QEMU_OPT_BOOL,
4382 .type = QEMU_OPT_STRING,
4385 .type = QEMU_OPT_NUMBER,
4388 .type = QEMU_OPT_SIZE,
4391 .type = QEMU_OPT_STRING,
4394 .type = QEMU_OPT_BOOL,
4397 .type = QEMU_OPT_STRING,
4399 .name = "logappend",
4400 .type = QEMU_OPT_BOOL,
4402 { /* end of list */ }
4408 static CharDriverState *qmp_chardev_open_file(const char *id,
4409 ChardevBackend *backend,
4413 ChardevFile *file = backend->u.file.data;
4414 ChardevCommon *common = qapi_ChardevFile_base(file);
4420 error_setg(errp, "input file not supported");
4424 if (file->has_append && file->append) {
4425 /* Append to file if it already exists. */
4426 accessmode = FILE_GENERIC_WRITE & ~FILE_WRITE_DATA;
4427 flags = OPEN_ALWAYS;
4429 /* Truncate file if it already exists. */
4430 accessmode = GENERIC_WRITE;
4431 flags = CREATE_ALWAYS;
4434 out = CreateFile(file->out, accessmode, FILE_SHARE_READ, NULL, flags,
4435 FILE_ATTRIBUTE_NORMAL, NULL);
4436 if (out == INVALID_HANDLE_VALUE) {
4437 error_setg(errp, "open %s failed", file->out);
4440 return qemu_chr_open_win_file(out, common, errp);
4443 static CharDriverState *qmp_chardev_open_serial(const char *id,
4444 ChardevBackend *backend,
4448 ChardevHostdev *serial = backend->u.serial.data;
4449 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4450 return qemu_chr_open_win_path(serial->device, common, errp);
4455 static int qmp_chardev_open_file_source(char *src, int flags,
4460 TFR(fd = qemu_open(src, flags, 0666));
4462 error_setg_file_open(errp, errno, src);
4467 static CharDriverState *qmp_chardev_open_file(const char *id,
4468 ChardevBackend *backend,
4472 ChardevFile *file = backend->u.file.data;
4473 ChardevCommon *common = qapi_ChardevFile_base(file);
4474 int flags, in = -1, out;
4476 flags = O_WRONLY | O_CREAT | O_BINARY;
4477 if (file->has_append && file->append) {
4483 out = qmp_chardev_open_file_source(file->out, flags, errp);
4490 in = qmp_chardev_open_file_source(file->in, flags, errp);
4497 return qemu_chr_open_fd(in, out, common, errp);
4500 #ifdef HAVE_CHARDEV_SERIAL
4501 static CharDriverState *qmp_chardev_open_serial(const char *id,
4502 ChardevBackend *backend,
4506 ChardevHostdev *serial = backend->u.serial.data;
4507 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4510 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4514 qemu_set_nonblock(fd);
4515 return qemu_chr_open_tty_fd(fd, common, errp);
4519 #ifdef HAVE_CHARDEV_PARPORT
4520 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4521 ChardevBackend *backend,
4525 ChardevHostdev *parallel = backend->u.parallel.data;
4526 ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
4529 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4533 return qemu_chr_open_pp_fd(fd, common, errp);
4539 static gboolean socket_reconnect_timeout(gpointer opaque)
4541 CharDriverState *chr = opaque;
4542 TCPCharDriver *s = chr->opaque;
4543 QIOChannelSocket *sioc;
4545 s->reconnect_timer = 0;
4551 sioc = qio_channel_socket_new();
4552 qio_channel_socket_connect_async(sioc, s->addr,
4553 qemu_chr_socket_connected,
4559 static CharDriverState *qmp_chardev_open_socket(const char *id,
4560 ChardevBackend *backend,
4564 CharDriverState *chr;
4566 ChardevSocket *sock = backend->u.socket.data;
4567 SocketAddress *addr = sock->addr;
4568 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4569 bool is_listen = sock->has_server ? sock->server : true;
4570 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4571 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4572 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4573 ChardevCommon *common = qapi_ChardevSocket_base(sock);
4574 QIOChannelSocket *sioc = NULL;
4576 chr = qemu_chr_alloc(common, errp);
4580 s = g_new0(TCPCharDriver, 1);
4582 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4583 s->is_listen = is_listen;
4584 s->is_telnet = is_telnet;
4585 s->do_nodelay = do_nodelay;
4586 if (sock->tls_creds) {
4588 creds = object_resolve_path_component(
4589 object_get_objects_root(), sock->tls_creds);
4591 error_setg(errp, "No TLS credentials with id '%s'",
4595 s->tls_creds = (QCryptoTLSCreds *)
4596 object_dynamic_cast(creds,
4597 TYPE_QCRYPTO_TLS_CREDS);
4598 if (!s->tls_creds) {
4599 error_setg(errp, "Object with id '%s' is not TLS credentials",
4603 object_ref(OBJECT(s->tls_creds));
4605 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4606 error_setg(errp, "%s",
4607 "Expected TLS credentials for server endpoint");
4611 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4612 error_setg(errp, "%s",
4613 "Expected TLS credentials for client endpoint");
4619 s->addr = QAPI_CLONE(SocketAddress, sock->addr);
4621 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_RECONNECTABLE);
4623 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_FD_PASS);
4627 chr->chr_wait_connected = tcp_chr_wait_connected;
4628 chr->chr_write = tcp_chr_write;
4629 chr->chr_sync_read = tcp_chr_sync_read;
4630 chr->chr_close = tcp_chr_close;
4631 chr->chr_disconnect = tcp_chr_disconnect;
4632 chr->get_msgfds = tcp_get_msgfds;
4633 chr->set_msgfds = tcp_set_msgfds;
4634 chr->chr_add_client = tcp_chr_add_client;
4635 chr->chr_add_watch = tcp_chr_add_watch;
4636 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4637 /* be isn't opened until we get a connection */
4638 chr->explicit_be_open = true;
4640 chr->filename = SocketAddress_to_str("disconnected:",
4641 addr, is_listen, is_telnet);
4645 s->do_telnetopt = 1;
4647 } else if (reconnect > 0) {
4648 s->reconnect_time = reconnect;
4651 if (s->reconnect_time) {
4652 sioc = qio_channel_socket_new();
4653 qio_channel_socket_connect_async(sioc, s->addr,
4654 qemu_chr_socket_connected,
4658 sioc = qio_channel_socket_new();
4659 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4662 s->listen_ioc = sioc;
4663 if (is_waitconnect &&
4664 qemu_chr_wait_connected(chr, errp) < 0) {
4668 s->listen_tag = qio_channel_add_watch(
4669 QIO_CHANNEL(s->listen_ioc), G_IO_IN,
4670 tcp_chr_accept, chr, NULL);
4672 } else if (qemu_chr_wait_connected(chr, errp) < 0) {
4681 object_unref(OBJECT(sioc));
4684 object_unref(OBJECT(s->tls_creds));
4687 qemu_chr_free_common(chr);
4691 static CharDriverState *qmp_chardev_open_udp(const char *id,
4692 ChardevBackend *backend,
4696 ChardevUdp *udp = backend->u.udp.data;
4697 ChardevCommon *common = qapi_ChardevUdp_base(udp);
4698 QIOChannelSocket *sioc = qio_channel_socket_new();
4700 if (qio_channel_socket_dgram_sync(sioc,
4701 udp->local, udp->remote,
4703 object_unref(OBJECT(sioc));
4706 return qemu_chr_open_udp(sioc, common, errp);
4710 bool qemu_chr_has_feature(CharDriverState *chr,
4711 CharDriverFeature feature)
4713 return test_bit(feature, chr->features);
4716 void qemu_chr_set_feature(CharDriverState *chr,
4717 CharDriverFeature feature)
4719 return set_bit(feature, chr->features);
4722 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4725 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4726 CharDriverState *chr = NULL;
4727 Error *local_err = NULL;
4731 chr = qemu_chr_find(id);
4733 error_setg(errp, "Chardev '%s' already exists", id);
4738 for (i = backends; i; i = i->next) {
4741 if (cd->kind == backend->type) {
4742 chr = cd->create(id, backend, ret, &local_err);
4744 error_propagate(errp, local_err);
4753 error_setg(errp, "chardev backend not available");
4757 chr->label = g_strdup(id);
4758 chr->avail_connections =
4759 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4760 if (!chr->filename) {
4761 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4763 if (!chr->explicit_be_open) {
4764 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4766 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4774 void qmp_chardev_remove(const char *id, Error **errp)
4776 CharDriverState *chr;
4778 chr = qemu_chr_find(id);
4780 error_setg(errp, "Chardev '%s' not found", id);
4783 if (chr->chr_can_read || chr->chr_read ||
4784 chr->chr_event || chr->handler_opaque) {
4785 error_setg(errp, "Chardev '%s' is busy", id);
4790 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4793 qemu_chr_delete(chr);
4796 void qemu_chr_cleanup(void)
4798 CharDriverState *chr, *tmp;
4800 QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
4801 qemu_chr_delete(chr);
4805 static void register_types(void)
4807 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4808 qemu_chr_open_null);
4809 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4810 qemu_chr_parse_socket, qmp_chardev_open_socket);
4811 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4812 qmp_chardev_open_udp);
4813 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4814 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4815 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4816 qemu_chr_parse_file_out, qmp_chardev_open_file);
4817 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4818 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4819 #if defined HAVE_CHARDEV_SERIAL
4820 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4821 qemu_chr_parse_serial, qmp_chardev_open_serial);
4822 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4823 qemu_chr_parse_serial, qmp_chardev_open_serial);
4825 #ifdef HAVE_CHARDEV_PARPORT
4826 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4827 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4828 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4829 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4831 #ifdef HAVE_CHARDEV_PTY
4832 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4836 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4837 qemu_chr_open_win_con);
4839 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4840 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4841 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4843 /* Bug-compatibility: */
4844 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4845 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4846 /* this must be done after machine init, since we register FEs with muxes
4847 * as part of realize functions like serial_isa_realizefn when -nographic
4850 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4853 type_init(register_types);