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-common.h"
25 #include "monitor/monitor.h"
26 #include "sysemu/sysemu.h"
27 #include "qemu/error-report.h"
28 #include "qemu/timer.h"
29 #include "sysemu/char.h"
31 #include "qmp-commands.h"
32 #include "qapi/qmp-input-visitor.h"
33 #include "qapi/qmp-output-visitor.h"
34 #include "qapi-visit.h"
44 #include <sys/times.h>
48 #include <sys/ioctl.h>
49 #include <sys/resource.h>
50 #include <sys/socket.h>
51 #include <netinet/in.h>
53 #include <arpa/inet.h>
56 #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>
73 #include <sys/ethernet.h>
74 #include <sys/sockio.h>
75 #include <netinet/arp.h>
76 #include <netinet/in.h>
77 #include <netinet/in_systm.h>
78 #include <netinet/ip.h>
79 #include <netinet/ip_icmp.h> // must come after ip.h
80 #include <netinet/udp.h>
81 #include <netinet/tcp.h>
86 #include "qemu/sockets.h"
87 #include "ui/qemu-spice.h"
89 #define READ_BUF_LEN 4096
90 #define READ_RETRIES 10
91 #define CHR_MAX_FILENAME_SIZE 256
92 #define TCP_MAX_FDS 16
94 /***********************************************************/
95 /* Socket address helpers */
96 static void qapi_copy_SocketAddress(SocketAddress **p_dest,
99 QmpOutputVisitor *qov;
100 QmpInputVisitor *qiv;
106 qov = qmp_output_visitor_new();
107 ov = qmp_output_get_visitor(qov);
108 visit_type_SocketAddress(ov, &src, NULL, &error_abort);
109 obj = qmp_output_get_qobject(qov);
110 qmp_output_visitor_cleanup(qov);
115 qiv = qmp_input_visitor_new(obj);
116 iv = qmp_input_get_visitor(qiv);
117 visit_type_SocketAddress(iv, p_dest, NULL, &error_abort);
118 qmp_input_visitor_cleanup(qiv);
122 static int SocketAddress_to_str(char *dest, int max_len,
123 const char *prefix, SocketAddress *addr,
124 bool is_listen, bool is_telnet)
126 switch (addr->kind) {
127 case SOCKET_ADDRESS_KIND_INET:
128 return snprintf(dest, max_len, "%s%s:%s:%s%s", prefix,
129 is_telnet ? "telnet" : "tcp", addr->inet->host,
130 addr->inet->port, is_listen ? ",server" : "");
132 case SOCKET_ADDRESS_KIND_UNIX:
133 return snprintf(dest, max_len, "%sunix:%s%s", prefix,
134 addr->q_unix->path, is_listen ? ",server" : "");
136 case SOCKET_ADDRESS_KIND_FD:
137 return snprintf(dest, max_len, "%sfd:%s%s", prefix, addr->fd->str,
138 is_listen ? ",server" : "");
145 static int sockaddr_to_str(char *dest, int max_len,
146 struct sockaddr_storage *ss, socklen_t ss_len,
147 struct sockaddr_storage *ps, socklen_t ps_len,
148 bool is_listen, bool is_telnet)
150 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
151 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
152 const char *left = "", *right = "";
154 switch (ss->ss_family) {
157 return snprintf(dest, max_len, "unix:%s%s",
158 ((struct sockaddr_un *)(ss))->sun_path,
159 is_listen ? ",server" : "");
166 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
167 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
168 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
169 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
170 return snprintf(dest, max_len, "%s:%s%s%s:%s%s <-> %s%s%s:%s",
171 is_telnet ? "telnet" : "tcp",
172 left, shost, right, sserv,
173 is_listen ? ",server" : "",
174 left, phost, right, pserv);
177 return snprintf(dest, max_len, "unknown");
181 /***********************************************************/
182 /* character device */
184 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
185 QTAILQ_HEAD_INITIALIZER(chardevs);
187 CharDriverState *qemu_chr_alloc(void)
189 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
190 qemu_mutex_init(&chr->chr_write_lock);
194 void qemu_chr_be_event(CharDriverState *s, int event)
196 /* Keep track if the char device is open */
198 case CHR_EVENT_OPENED:
201 case CHR_EVENT_CLOSED:
208 s->chr_event(s->handler_opaque, event);
211 void qemu_chr_be_generic_open(CharDriverState *s)
213 qemu_chr_be_event(s, CHR_EVENT_OPENED);
216 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
220 qemu_mutex_lock(&s->chr_write_lock);
221 ret = s->chr_write(s, buf, len);
222 qemu_mutex_unlock(&s->chr_write_lock);
226 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
231 qemu_mutex_lock(&s->chr_write_lock);
232 while (offset < len) {
234 res = s->chr_write(s, buf + offset, len - offset);
235 if (res == -1 && errno == EAGAIN) {
238 } while (res == -1 && errno == EAGAIN);
246 qemu_mutex_unlock(&s->chr_write_lock);
254 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
256 int offset = 0, counter = 10;
259 if (!s->chr_sync_read) {
263 while (offset < len) {
265 res = s->chr_sync_read(s, buf + offset, len - offset);
266 if (res == -1 && errno == EAGAIN) {
269 } while (res == -1 && errno == EAGAIN);
289 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
293 return s->chr_ioctl(s, cmd, arg);
296 int qemu_chr_be_can_write(CharDriverState *s)
298 if (!s->chr_can_read)
300 return s->chr_can_read(s->handler_opaque);
303 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
306 s->chr_read(s->handler_opaque, buf, len);
310 int qemu_chr_fe_get_msgfd(CharDriverState *s)
313 return (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
316 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
318 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
321 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
323 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
326 int qemu_chr_add_client(CharDriverState *s, int fd)
328 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
331 void qemu_chr_accept_input(CharDriverState *s)
333 if (s->chr_accept_input)
334 s->chr_accept_input(s);
338 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
340 char buf[READ_BUF_LEN];
343 vsnprintf(buf, sizeof(buf), fmt, ap);
344 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
348 static void remove_fd_in_watch(CharDriverState *chr);
350 void qemu_chr_add_handlers(CharDriverState *s,
351 IOCanReadHandler *fd_can_read,
352 IOReadHandler *fd_read,
353 IOEventHandler *fd_event,
358 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
360 remove_fd_in_watch(s);
364 s->chr_can_read = fd_can_read;
365 s->chr_read = fd_read;
366 s->chr_event = fd_event;
367 s->handler_opaque = opaque;
368 if (fe_open && s->chr_update_read_handler)
369 s->chr_update_read_handler(s);
371 if (!s->explicit_fe_open) {
372 qemu_chr_fe_set_open(s, fe_open);
375 /* We're connecting to an already opened device, so let's make sure we
376 also get the open event */
377 if (fe_open && s->be_open) {
378 qemu_chr_be_generic_open(s);
382 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
387 static CharDriverState *qemu_chr_open_null(void)
389 CharDriverState *chr;
391 chr = qemu_chr_alloc();
392 chr->chr_write = null_chr_write;
393 chr->explicit_be_open = true;
397 /* MUX driver for serial I/O splitting */
399 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
400 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
402 IOCanReadHandler *chr_can_read[MAX_MUX];
403 IOReadHandler *chr_read[MAX_MUX];
404 IOEventHandler *chr_event[MAX_MUX];
405 void *ext_opaque[MAX_MUX];
406 CharDriverState *drv;
411 /* Intermediate input buffer allows to catch escape sequences even if the
412 currently active device is not accepting any input - but only until it
414 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
419 /* Protected by the CharDriverState chr_write_lock. */
421 int64_t timestamps_start;
425 /* Called with chr_write_lock held. */
426 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
428 MuxDriver *d = chr->opaque;
430 if (!d->timestamps) {
431 ret = qemu_chr_fe_write(d->drv, buf, len);
436 for (i = 0; i < len; i++) {
442 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
443 if (d->timestamps_start == -1)
444 d->timestamps_start = ti;
445 ti -= d->timestamps_start;
447 snprintf(buf1, sizeof(buf1),
448 "[%02d:%02d:%02d.%03d] ",
453 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
456 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
457 if (buf[i] == '\n') {
465 static const char * const mux_help[] = {
466 "% h print this help\n\r",
467 "% x exit emulator\n\r",
468 "% s save disk data back to file (if -snapshot)\n\r",
469 "% t toggle console timestamps\n\r",
470 "% b send break (magic sysrq)\n\r",
471 "% c switch between console and monitor\n\r",
476 int term_escape_char = 0x01; /* ctrl-a is used for escape */
477 static void mux_print_help(CharDriverState *chr)
480 char ebuf[15] = "Escape-Char";
481 char cbuf[50] = "\n\r";
483 if (term_escape_char > 0 && term_escape_char < 26) {
484 snprintf(cbuf, sizeof(cbuf), "\n\r");
485 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
487 snprintf(cbuf, sizeof(cbuf),
488 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
491 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
492 for (i = 0; mux_help[i] != NULL; i++) {
493 for (j=0; mux_help[i][j] != '\0'; j++) {
494 if (mux_help[i][j] == '%')
495 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
497 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
502 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
504 if (d->chr_event[mux_nr])
505 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
508 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
510 if (d->term_got_escape) {
511 d->term_got_escape = 0;
512 if (ch == term_escape_char)
521 const char *term = "QEMU: Terminated\n\r";
522 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
530 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
533 /* Switch to the next registered device */
534 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
536 if (d->focus >= d->mux_cnt)
538 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
541 d->timestamps = !d->timestamps;
542 d->timestamps_start = -1;
546 } else if (ch == term_escape_char) {
547 d->term_got_escape = 1;
555 static void mux_chr_accept_input(CharDriverState *chr)
557 MuxDriver *d = chr->opaque;
560 while (d->prod[m] != d->cons[m] &&
561 d->chr_can_read[m] &&
562 d->chr_can_read[m](d->ext_opaque[m])) {
563 d->chr_read[m](d->ext_opaque[m],
564 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
568 static int mux_chr_can_read(void *opaque)
570 CharDriverState *chr = opaque;
571 MuxDriver *d = chr->opaque;
574 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
576 if (d->chr_can_read[m])
577 return d->chr_can_read[m](d->ext_opaque[m]);
581 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
583 CharDriverState *chr = opaque;
584 MuxDriver *d = chr->opaque;
588 mux_chr_accept_input (opaque);
590 for(i = 0; i < size; i++)
591 if (mux_proc_byte(chr, d, buf[i])) {
592 if (d->prod[m] == d->cons[m] &&
593 d->chr_can_read[m] &&
594 d->chr_can_read[m](d->ext_opaque[m]))
595 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
597 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
601 static void mux_chr_event(void *opaque, int event)
603 CharDriverState *chr = opaque;
604 MuxDriver *d = chr->opaque;
607 /* Send the event to all registered listeners */
608 for (i = 0; i < d->mux_cnt; i++)
609 mux_chr_send_event(d, i, event);
612 static void mux_chr_update_read_handler(CharDriverState *chr)
614 MuxDriver *d = chr->opaque;
616 if (d->mux_cnt >= MAX_MUX) {
617 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
620 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
621 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
622 d->chr_read[d->mux_cnt] = chr->chr_read;
623 d->chr_event[d->mux_cnt] = chr->chr_event;
624 /* Fix up the real driver with mux routines */
625 if (d->mux_cnt == 0) {
626 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
629 if (d->focus != -1) {
630 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
632 d->focus = d->mux_cnt;
634 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
637 static bool muxes_realized;
640 * Called after processing of default and command-line-specified
641 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
642 * to a mux chardev. This is done here to ensure that
643 * output/prompts/banners are only displayed for the FE that has
644 * focus when initial command-line processing/machine init is
647 * After this point, any new FE attached to any new or existing
648 * mux will receive CHR_EVENT_OPENED notifications for the BE
651 static void muxes_realize_done(Notifier *notifier, void *unused)
653 CharDriverState *chr;
655 QTAILQ_FOREACH(chr, &chardevs, next) {
657 MuxDriver *d = chr->opaque;
660 /* send OPENED to all already-attached FEs */
661 for (i = 0; i < d->mux_cnt; i++) {
662 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
664 /* mark mux as OPENED so any new FEs will immediately receive
667 qemu_chr_be_generic_open(chr);
670 muxes_realized = true;
673 static Notifier muxes_realize_notify = {
674 .notify = muxes_realize_done,
677 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
679 MuxDriver *d = s->opaque;
680 return d->drv->chr_add_watch(d->drv, cond);
683 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
685 CharDriverState *chr;
688 chr = qemu_chr_alloc();
689 d = g_malloc0(sizeof(MuxDriver));
694 chr->chr_write = mux_chr_write;
695 chr->chr_update_read_handler = mux_chr_update_read_handler;
696 chr->chr_accept_input = mux_chr_accept_input;
697 /* Frontend guest-open / -close notification is not support with muxes */
698 chr->chr_set_fe_open = NULL;
699 if (drv->chr_add_watch) {
700 chr->chr_add_watch = mux_chr_add_watch;
702 /* only default to opened state if we've realized the initial
705 chr->explicit_be_open = muxes_realized ? 0 : 1;
713 int send_all(int fd, const void *buf, int len1)
719 ret = send(fd, buf, len, 0);
721 errno = WSAGetLastError();
722 if (errno != WSAEWOULDBLOCK) {
725 } else if (ret == 0) {
737 int send_all(int fd, const void *_buf, int len1)
740 const uint8_t *buf = _buf;
744 ret = write(fd, buf, len);
746 if (errno != EINTR && errno != EAGAIN)
748 } else if (ret == 0) {
758 int recv_all(int fd, void *_buf, int len1, bool single_read)
764 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
766 if (errno != EINTR && errno != EAGAIN) {
783 typedef struct IOWatchPoll
790 IOCanReadHandler *fd_can_read;
795 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
797 return container_of(source, IOWatchPoll, parent);
800 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
802 IOWatchPoll *iwp = io_watch_poll_from_source(source);
803 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
804 bool was_active = iwp->src != NULL;
805 if (was_active == now_active) {
810 iwp->src = g_io_create_watch(iwp->channel,
811 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
812 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
813 g_source_attach(iwp->src, NULL);
815 g_source_destroy(iwp->src);
816 g_source_unref(iwp->src);
822 static gboolean io_watch_poll_check(GSource *source)
827 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
833 static void io_watch_poll_finalize(GSource *source)
835 /* Due to a glib bug, removing the last reference to a source
836 * inside a finalize callback causes recursive locking (and a
837 * deadlock). This is not a problem inside other callbacks,
838 * including dispatch callbacks, so we call io_remove_watch_poll
839 * to remove this source. At this point, iwp->src must
840 * be NULL, or we would leak it.
842 * This would be solved much more elegantly by child sources,
843 * but we support older glib versions that do not have them.
845 IOWatchPoll *iwp = io_watch_poll_from_source(source);
846 assert(iwp->src == NULL);
849 static GSourceFuncs io_watch_poll_funcs = {
850 .prepare = io_watch_poll_prepare,
851 .check = io_watch_poll_check,
852 .dispatch = io_watch_poll_dispatch,
853 .finalize = io_watch_poll_finalize,
856 /* Can only be used for read */
857 static guint io_add_watch_poll(GIOChannel *channel,
858 IOCanReadHandler *fd_can_read,
865 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
866 iwp->fd_can_read = fd_can_read;
867 iwp->opaque = user_data;
868 iwp->channel = channel;
869 iwp->fd_read = (GSourceFunc) fd_read;
872 tag = g_source_attach(&iwp->parent, NULL);
873 g_source_unref(&iwp->parent);
877 static void io_remove_watch_poll(guint tag)
882 g_return_if_fail (tag > 0);
884 source = g_main_context_find_source_by_id(NULL, tag);
885 g_return_if_fail (source != NULL);
887 iwp = io_watch_poll_from_source(source);
889 g_source_destroy(iwp->src);
890 g_source_unref(iwp->src);
893 g_source_destroy(&iwp->parent);
896 static void remove_fd_in_watch(CharDriverState *chr)
898 if (chr->fd_in_tag) {
899 io_remove_watch_poll(chr->fd_in_tag);
905 static GIOChannel *io_channel_from_fd(int fd)
913 chan = g_io_channel_unix_new(fd);
915 g_io_channel_set_encoding(chan, NULL, NULL);
916 g_io_channel_set_buffered(chan, FALSE);
922 static GIOChannel *io_channel_from_socket(int fd)
931 chan = g_io_channel_win32_new_socket(fd);
933 chan = g_io_channel_unix_new(fd);
936 g_io_channel_set_encoding(chan, NULL, NULL);
937 g_io_channel_set_buffered(chan, FALSE);
942 static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
945 GIOStatus status = G_IO_STATUS_NORMAL;
947 while (offset < len && status == G_IO_STATUS_NORMAL) {
948 gsize bytes_written = 0;
950 status = g_io_channel_write_chars(fd, buf + offset, len - offset,
951 &bytes_written, NULL);
952 offset += bytes_written;
959 case G_IO_STATUS_NORMAL:
962 case G_IO_STATUS_AGAIN:
974 typedef struct FDCharDriver {
975 CharDriverState *chr;
976 GIOChannel *fd_in, *fd_out;
980 /* Called with chr_write_lock held. */
981 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
983 FDCharDriver *s = chr->opaque;
985 return io_channel_send(s->fd_out, buf, len);
988 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
990 CharDriverState *chr = opaque;
991 FDCharDriver *s = chr->opaque;
993 uint8_t buf[READ_BUF_LEN];
998 if (len > s->max_size) {
1005 status = g_io_channel_read_chars(chan, (gchar *)buf,
1006 len, &bytes_read, NULL);
1007 if (status == G_IO_STATUS_EOF) {
1008 remove_fd_in_watch(chr);
1009 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1012 if (status == G_IO_STATUS_NORMAL) {
1013 qemu_chr_be_write(chr, buf, bytes_read);
1019 static int fd_chr_read_poll(void *opaque)
1021 CharDriverState *chr = opaque;
1022 FDCharDriver *s = chr->opaque;
1024 s->max_size = qemu_chr_be_can_write(chr);
1028 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1030 FDCharDriver *s = chr->opaque;
1031 return g_io_create_watch(s->fd_out, cond);
1034 static void fd_chr_update_read_handler(CharDriverState *chr)
1036 FDCharDriver *s = chr->opaque;
1038 remove_fd_in_watch(chr);
1040 chr->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll,
1045 static void fd_chr_close(struct CharDriverState *chr)
1047 FDCharDriver *s = chr->opaque;
1049 remove_fd_in_watch(chr);
1051 g_io_channel_unref(s->fd_in);
1054 g_io_channel_unref(s->fd_out);
1058 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1061 /* open a character device to a unix fd */
1062 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1064 CharDriverState *chr;
1067 chr = qemu_chr_alloc();
1068 s = g_malloc0(sizeof(FDCharDriver));
1069 s->fd_in = io_channel_from_fd(fd_in);
1070 s->fd_out = io_channel_from_fd(fd_out);
1071 qemu_set_nonblock(fd_out);
1074 chr->chr_add_watch = fd_chr_add_watch;
1075 chr->chr_write = fd_chr_write;
1076 chr->chr_update_read_handler = fd_chr_update_read_handler;
1077 chr->chr_close = fd_chr_close;
1082 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
1085 char filename_in[CHR_MAX_FILENAME_SIZE];
1086 char filename_out[CHR_MAX_FILENAME_SIZE];
1087 const char *filename = opts->device;
1089 if (filename == NULL) {
1090 fprintf(stderr, "chardev: pipe: no filename given\n");
1094 snprintf(filename_in, CHR_MAX_FILENAME_SIZE, "%s.in", filename);
1095 snprintf(filename_out, CHR_MAX_FILENAME_SIZE, "%s.out", filename);
1096 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1097 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1098 if (fd_in < 0 || fd_out < 0) {
1103 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1108 return qemu_chr_open_fd(fd_in, fd_out);
1111 /* init terminal so that we can grab keys */
1112 static struct termios oldtty;
1113 static int old_fd0_flags;
1114 static bool stdio_in_use;
1115 static bool stdio_allow_signal;
1116 static bool stdio_echo_state;
1118 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1120 static void term_exit(void)
1122 tcsetattr (0, TCSANOW, &oldtty);
1123 fcntl(0, F_SETFL, old_fd0_flags);
1126 static void term_stdio_handler(int sig)
1128 /* restore echo after resume from suspend. */
1129 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1132 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1136 stdio_echo_state = echo;
1139 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1140 |INLCR|IGNCR|ICRNL|IXON);
1141 tty.c_oflag |= OPOST;
1142 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1143 tty.c_cflag &= ~(CSIZE|PARENB);
1146 tty.c_cc[VTIME] = 0;
1148 if (!stdio_allow_signal)
1149 tty.c_lflag &= ~ISIG;
1151 tcsetattr (0, TCSANOW, &tty);
1154 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1160 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
1162 CharDriverState *chr;
1163 struct sigaction act;
1165 if (is_daemonized()) {
1166 error_report("cannot use stdio with -daemonize");
1171 error_report("cannot use stdio by multiple character devices");
1175 stdio_in_use = true;
1176 old_fd0_flags = fcntl(0, F_GETFL);
1177 tcgetattr(0, &oldtty);
1178 qemu_set_nonblock(0);
1181 memset(&act, 0, sizeof(act));
1182 act.sa_handler = term_stdio_handler;
1183 sigaction(SIGCONT, &act, NULL);
1185 chr = qemu_chr_open_fd(0, 1);
1186 chr->chr_close = qemu_chr_close_stdio;
1187 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1188 if (opts->has_signal) {
1189 stdio_allow_signal = opts->signal;
1191 qemu_chr_fe_set_echo(chr, false);
1196 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1197 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1198 || defined(__GLIBC__)
1200 #define HAVE_CHARDEV_TTY 1
1206 /* Protected by the CharDriverState chr_write_lock. */
1212 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1213 static void pty_chr_state(CharDriverState *chr, int connected);
1215 static gboolean pty_chr_timer(gpointer opaque)
1217 struct CharDriverState *chr = opaque;
1218 PtyCharDriver *s = chr->opaque;
1220 qemu_mutex_lock(&chr->chr_write_lock);
1223 if (!s->connected) {
1225 pty_chr_update_read_handler_locked(chr);
1227 qemu_mutex_unlock(&chr->chr_write_lock);
1231 /* Called with chr_write_lock held. */
1232 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1234 PtyCharDriver *s = chr->opaque;
1237 g_source_remove(s->timer_tag);
1242 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1244 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1248 /* Called with chr_write_lock held. */
1249 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1251 PtyCharDriver *s = chr->opaque;
1254 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1255 pfd.events = G_IO_OUT;
1258 if (pfd.revents & G_IO_HUP) {
1259 pty_chr_state(chr, 0);
1261 pty_chr_state(chr, 1);
1265 static void pty_chr_update_read_handler(CharDriverState *chr)
1267 qemu_mutex_lock(&chr->chr_write_lock);
1268 pty_chr_update_read_handler_locked(chr);
1269 qemu_mutex_unlock(&chr->chr_write_lock);
1272 /* Called with chr_write_lock held. */
1273 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1275 PtyCharDriver *s = chr->opaque;
1277 if (!s->connected) {
1278 /* guest sends data, check for (re-)connect */
1279 pty_chr_update_read_handler_locked(chr);
1280 if (!s->connected) {
1284 return io_channel_send(s->fd, buf, len);
1287 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1289 PtyCharDriver *s = chr->opaque;
1290 if (!s->connected) {
1293 return g_io_create_watch(s->fd, cond);
1296 static int pty_chr_read_poll(void *opaque)
1298 CharDriverState *chr = opaque;
1299 PtyCharDriver *s = chr->opaque;
1301 s->read_bytes = qemu_chr_be_can_write(chr);
1302 return s->read_bytes;
1305 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1307 CharDriverState *chr = opaque;
1308 PtyCharDriver *s = chr->opaque;
1310 uint8_t buf[READ_BUF_LEN];
1314 if (len > s->read_bytes)
1315 len = s->read_bytes;
1319 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1320 if (status != G_IO_STATUS_NORMAL) {
1321 pty_chr_state(chr, 0);
1324 pty_chr_state(chr, 1);
1325 qemu_chr_be_write(chr, buf, size);
1330 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1332 CharDriverState *chr = opaque;
1333 PtyCharDriver *s = chr->opaque;
1336 qemu_chr_be_generic_open(chr);
1340 /* Called with chr_write_lock held. */
1341 static void pty_chr_state(CharDriverState *chr, int connected)
1343 PtyCharDriver *s = chr->opaque;
1347 g_source_remove(s->open_tag);
1350 remove_fd_in_watch(chr);
1352 /* (re-)connect poll interval for idle guests: once per second.
1353 * We check more frequently in case the guests sends data to
1354 * the virtual device linked to our pty. */
1355 pty_chr_rearm_timer(chr, 1000);
1358 g_source_remove(s->timer_tag);
1361 if (!s->connected) {
1362 g_assert(s->open_tag == 0);
1364 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1366 if (!chr->fd_in_tag) {
1367 chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
1373 static void pty_chr_close(struct CharDriverState *chr)
1375 PtyCharDriver *s = chr->opaque;
1378 qemu_mutex_lock(&chr->chr_write_lock);
1379 pty_chr_state(chr, 0);
1380 fd = g_io_channel_unix_get_fd(s->fd);
1381 g_io_channel_unref(s->fd);
1384 g_source_remove(s->timer_tag);
1387 qemu_mutex_unlock(&chr->chr_write_lock);
1389 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1392 static CharDriverState *qemu_chr_open_pty(const char *id,
1395 CharDriverState *chr;
1397 int master_fd, slave_fd;
1398 char pty_name[PATH_MAX];
1400 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1401 if (master_fd < 0) {
1406 qemu_set_nonblock(master_fd);
1408 chr = qemu_chr_alloc();
1410 chr->filename = g_strdup_printf("pty:%s", pty_name);
1411 ret->pty = g_strdup(pty_name);
1412 ret->has_pty = true;
1414 fprintf(stderr, "char device redirected to %s (label %s)\n",
1417 s = g_malloc0(sizeof(PtyCharDriver));
1419 chr->chr_write = pty_chr_write;
1420 chr->chr_update_read_handler = pty_chr_update_read_handler;
1421 chr->chr_close = pty_chr_close;
1422 chr->chr_add_watch = pty_chr_add_watch;
1423 chr->explicit_be_open = true;
1425 s->fd = io_channel_from_fd(master_fd);
1431 static void tty_serial_init(int fd, int speed,
1432 int parity, int data_bits, int stop_bits)
1438 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1439 speed, parity, data_bits, stop_bits);
1441 tcgetattr (fd, &tty);
1443 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1444 speed = speed * 10 / 11;
1461 /* Non-Posix values follow. They may be unsupported on some systems. */
1463 check_speed(115200);
1465 check_speed(230400);
1468 check_speed(460800);
1471 check_speed(500000);
1474 check_speed(576000);
1477 check_speed(921600);
1480 check_speed(1000000);
1483 check_speed(1152000);
1486 check_speed(1500000);
1489 check_speed(2000000);
1492 check_speed(2500000);
1495 check_speed(3000000);
1498 check_speed(3500000);
1501 check_speed(4000000);
1506 cfsetispeed(&tty, spd);
1507 cfsetospeed(&tty, spd);
1509 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1510 |INLCR|IGNCR|ICRNL|IXON);
1511 tty.c_oflag |= OPOST;
1512 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1513 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1534 tty.c_cflag |= PARENB;
1537 tty.c_cflag |= PARENB | PARODD;
1541 tty.c_cflag |= CSTOPB;
1543 tcsetattr (fd, TCSANOW, &tty);
1546 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1548 FDCharDriver *s = chr->opaque;
1551 case CHR_IOCTL_SERIAL_SET_PARAMS:
1553 QEMUSerialSetParams *ssp = arg;
1554 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1555 ssp->speed, ssp->parity,
1556 ssp->data_bits, ssp->stop_bits);
1559 case CHR_IOCTL_SERIAL_SET_BREAK:
1561 int enable = *(int *)arg;
1563 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1567 case CHR_IOCTL_SERIAL_GET_TIOCM:
1570 int *targ = (int *)arg;
1571 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1573 if (sarg & TIOCM_CTS)
1574 *targ |= CHR_TIOCM_CTS;
1575 if (sarg & TIOCM_CAR)
1576 *targ |= CHR_TIOCM_CAR;
1577 if (sarg & TIOCM_DSR)
1578 *targ |= CHR_TIOCM_DSR;
1579 if (sarg & TIOCM_RI)
1580 *targ |= CHR_TIOCM_RI;
1581 if (sarg & TIOCM_DTR)
1582 *targ |= CHR_TIOCM_DTR;
1583 if (sarg & TIOCM_RTS)
1584 *targ |= CHR_TIOCM_RTS;
1587 case CHR_IOCTL_SERIAL_SET_TIOCM:
1589 int sarg = *(int *)arg;
1591 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1592 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1593 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1594 if (sarg & CHR_TIOCM_CTS)
1596 if (sarg & CHR_TIOCM_CAR)
1598 if (sarg & CHR_TIOCM_DSR)
1600 if (sarg & CHR_TIOCM_RI)
1602 if (sarg & CHR_TIOCM_DTR)
1604 if (sarg & CHR_TIOCM_RTS)
1606 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1615 static void qemu_chr_close_tty(CharDriverState *chr)
1617 FDCharDriver *s = chr->opaque;
1621 fd = g_io_channel_unix_get_fd(s->fd_in);
1631 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1633 CharDriverState *chr;
1635 tty_serial_init(fd, 115200, 'N', 8, 1);
1636 chr = qemu_chr_open_fd(fd, fd);
1637 chr->chr_ioctl = tty_serial_ioctl;
1638 chr->chr_close = qemu_chr_close_tty;
1641 #endif /* __linux__ || __sun__ */
1643 #if defined(__linux__)
1645 #define HAVE_CHARDEV_PARPORT 1
1650 } ParallelCharDriver;
1652 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1654 if (s->mode != mode) {
1656 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1663 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1665 ParallelCharDriver *drv = chr->opaque;
1670 case CHR_IOCTL_PP_READ_DATA:
1671 if (ioctl(fd, PPRDATA, &b) < 0)
1673 *(uint8_t *)arg = b;
1675 case CHR_IOCTL_PP_WRITE_DATA:
1676 b = *(uint8_t *)arg;
1677 if (ioctl(fd, PPWDATA, &b) < 0)
1680 case CHR_IOCTL_PP_READ_CONTROL:
1681 if (ioctl(fd, PPRCONTROL, &b) < 0)
1683 /* Linux gives only the lowest bits, and no way to know data
1684 direction! For better compatibility set the fixed upper
1686 *(uint8_t *)arg = b | 0xc0;
1688 case CHR_IOCTL_PP_WRITE_CONTROL:
1689 b = *(uint8_t *)arg;
1690 if (ioctl(fd, PPWCONTROL, &b) < 0)
1693 case CHR_IOCTL_PP_READ_STATUS:
1694 if (ioctl(fd, PPRSTATUS, &b) < 0)
1696 *(uint8_t *)arg = b;
1698 case CHR_IOCTL_PP_DATA_DIR:
1699 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1702 case CHR_IOCTL_PP_EPP_READ_ADDR:
1703 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1704 struct ParallelIOArg *parg = arg;
1705 int n = read(fd, parg->buffer, parg->count);
1706 if (n != parg->count) {
1711 case CHR_IOCTL_PP_EPP_READ:
1712 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1713 struct ParallelIOArg *parg = arg;
1714 int n = read(fd, parg->buffer, parg->count);
1715 if (n != parg->count) {
1720 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1721 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1722 struct ParallelIOArg *parg = arg;
1723 int n = write(fd, parg->buffer, parg->count);
1724 if (n != parg->count) {
1729 case CHR_IOCTL_PP_EPP_WRITE:
1730 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1731 struct ParallelIOArg *parg = arg;
1732 int n = write(fd, parg->buffer, parg->count);
1733 if (n != parg->count) {
1744 static void pp_close(CharDriverState *chr)
1746 ParallelCharDriver *drv = chr->opaque;
1749 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1750 ioctl(fd, PPRELEASE);
1753 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1756 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1758 CharDriverState *chr;
1759 ParallelCharDriver *drv;
1761 if (ioctl(fd, PPCLAIM) < 0) {
1766 drv = g_malloc0(sizeof(ParallelCharDriver));
1768 drv->mode = IEEE1284_MODE_COMPAT;
1770 chr = qemu_chr_alloc();
1771 chr->chr_write = null_chr_write;
1772 chr->chr_ioctl = pp_ioctl;
1773 chr->chr_close = pp_close;
1778 #endif /* __linux__ */
1780 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1782 #define HAVE_CHARDEV_PARPORT 1
1784 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1786 int fd = (int)(intptr_t)chr->opaque;
1790 case CHR_IOCTL_PP_READ_DATA:
1791 if (ioctl(fd, PPIGDATA, &b) < 0)
1793 *(uint8_t *)arg = b;
1795 case CHR_IOCTL_PP_WRITE_DATA:
1796 b = *(uint8_t *)arg;
1797 if (ioctl(fd, PPISDATA, &b) < 0)
1800 case CHR_IOCTL_PP_READ_CONTROL:
1801 if (ioctl(fd, PPIGCTRL, &b) < 0)
1803 *(uint8_t *)arg = b;
1805 case CHR_IOCTL_PP_WRITE_CONTROL:
1806 b = *(uint8_t *)arg;
1807 if (ioctl(fd, PPISCTRL, &b) < 0)
1810 case CHR_IOCTL_PP_READ_STATUS:
1811 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1813 *(uint8_t *)arg = b;
1821 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1823 CharDriverState *chr;
1825 chr = qemu_chr_alloc();
1826 chr->opaque = (void *)(intptr_t)fd;
1827 chr->chr_write = null_chr_write;
1828 chr->chr_ioctl = pp_ioctl;
1829 chr->explicit_be_open = true;
1838 HANDLE hcom, hrecv, hsend;
1843 /* Protected by the CharDriverState chr_write_lock. */
1849 HANDLE hInputReadyEvent;
1850 HANDLE hInputDoneEvent;
1851 HANDLE hInputThread;
1852 uint8_t win_stdio_buf;
1853 } WinStdioCharState;
1855 #define NSENDBUF 2048
1856 #define NRECVBUF 2048
1857 #define MAXCONNECT 1
1858 #define NTIMEOUT 5000
1860 static int win_chr_poll(void *opaque);
1861 static int win_chr_pipe_poll(void *opaque);
1863 static void win_chr_close(CharDriverState *chr)
1865 WinCharState *s = chr->opaque;
1868 CloseHandle(s->hsend);
1872 CloseHandle(s->hrecv);
1876 CloseHandle(s->hcom);
1880 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1882 qemu_del_polling_cb(win_chr_poll, chr);
1884 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1887 static int win_chr_init(CharDriverState *chr, const char *filename)
1889 WinCharState *s = chr->opaque;
1891 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1896 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1898 fprintf(stderr, "Failed CreateEvent\n");
1901 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1903 fprintf(stderr, "Failed CreateEvent\n");
1907 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1908 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1909 if (s->hcom == INVALID_HANDLE_VALUE) {
1910 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1915 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1916 fprintf(stderr, "Failed SetupComm\n");
1920 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1921 size = sizeof(COMMCONFIG);
1922 GetDefaultCommConfig(filename, &comcfg, &size);
1923 comcfg.dcb.DCBlength = sizeof(DCB);
1924 CommConfigDialog(filename, NULL, &comcfg);
1926 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1927 fprintf(stderr, "Failed SetCommState\n");
1931 if (!SetCommMask(s->hcom, EV_ERR)) {
1932 fprintf(stderr, "Failed SetCommMask\n");
1936 cto.ReadIntervalTimeout = MAXDWORD;
1937 if (!SetCommTimeouts(s->hcom, &cto)) {
1938 fprintf(stderr, "Failed SetCommTimeouts\n");
1942 if (!ClearCommError(s->hcom, &err, &comstat)) {
1943 fprintf(stderr, "Failed ClearCommError\n");
1946 qemu_add_polling_cb(win_chr_poll, chr);
1954 /* Called with chr_write_lock held. */
1955 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1957 WinCharState *s = chr->opaque;
1958 DWORD len, ret, size, err;
1961 ZeroMemory(&s->osend, sizeof(s->osend));
1962 s->osend.hEvent = s->hsend;
1965 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1967 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1969 err = GetLastError();
1970 if (err == ERROR_IO_PENDING) {
1971 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1989 static int win_chr_read_poll(CharDriverState *chr)
1991 WinCharState *s = chr->opaque;
1993 s->max_size = qemu_chr_be_can_write(chr);
1997 static void win_chr_readfile(CharDriverState *chr)
1999 WinCharState *s = chr->opaque;
2001 uint8_t buf[READ_BUF_LEN];
2004 ZeroMemory(&s->orecv, sizeof(s->orecv));
2005 s->orecv.hEvent = s->hrecv;
2006 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2008 err = GetLastError();
2009 if (err == ERROR_IO_PENDING) {
2010 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2015 qemu_chr_be_write(chr, buf, size);
2019 static void win_chr_read(CharDriverState *chr)
2021 WinCharState *s = chr->opaque;
2023 if (s->len > s->max_size)
2024 s->len = s->max_size;
2028 win_chr_readfile(chr);
2031 static int win_chr_poll(void *opaque)
2033 CharDriverState *chr = opaque;
2034 WinCharState *s = chr->opaque;
2038 ClearCommError(s->hcom, &comerr, &status);
2039 if (status.cbInQue > 0) {
2040 s->len = status.cbInQue;
2041 win_chr_read_poll(chr);
2048 static CharDriverState *qemu_chr_open_win_path(const char *filename)
2050 CharDriverState *chr;
2053 chr = qemu_chr_alloc();
2054 s = g_malloc0(sizeof(WinCharState));
2056 chr->chr_write = win_chr_write;
2057 chr->chr_close = win_chr_close;
2059 if (win_chr_init(chr, filename) < 0) {
2067 static int win_chr_pipe_poll(void *opaque)
2069 CharDriverState *chr = opaque;
2070 WinCharState *s = chr->opaque;
2073 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2076 win_chr_read_poll(chr);
2083 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2085 WinCharState *s = chr->opaque;
2089 char openname[CHR_MAX_FILENAME_SIZE];
2093 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2095 fprintf(stderr, "Failed CreateEvent\n");
2098 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2100 fprintf(stderr, "Failed CreateEvent\n");
2104 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2105 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2106 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2108 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2109 if (s->hcom == INVALID_HANDLE_VALUE) {
2110 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2115 ZeroMemory(&ov, sizeof(ov));
2116 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2117 ret = ConnectNamedPipe(s->hcom, &ov);
2119 fprintf(stderr, "Failed ConnectNamedPipe\n");
2123 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2125 fprintf(stderr, "Failed GetOverlappedResult\n");
2127 CloseHandle(ov.hEvent);
2134 CloseHandle(ov.hEvent);
2137 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2146 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
2148 const char *filename = opts->device;
2149 CharDriverState *chr;
2152 chr = qemu_chr_alloc();
2153 s = g_malloc0(sizeof(WinCharState));
2155 chr->chr_write = win_chr_write;
2156 chr->chr_close = win_chr_close;
2158 if (win_chr_pipe_init(chr, filename) < 0) {
2166 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2168 CharDriverState *chr;
2171 chr = qemu_chr_alloc();
2172 s = g_malloc0(sizeof(WinCharState));
2175 chr->chr_write = win_chr_write;
2179 static CharDriverState *qemu_chr_open_win_con(void)
2181 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2184 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2186 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2193 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2203 static void win_stdio_wait_func(void *opaque)
2205 CharDriverState *chr = opaque;
2206 WinStdioCharState *stdio = chr->opaque;
2207 INPUT_RECORD buf[4];
2212 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2215 /* Avoid error storm */
2216 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2220 for (i = 0; i < dwSize; i++) {
2221 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2223 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2225 if (kev->uChar.AsciiChar != 0) {
2226 for (j = 0; j < kev->wRepeatCount; j++) {
2227 if (qemu_chr_be_can_write(chr)) {
2228 uint8_t c = kev->uChar.AsciiChar;
2229 qemu_chr_be_write(chr, &c, 1);
2237 static DWORD WINAPI win_stdio_thread(LPVOID param)
2239 CharDriverState *chr = param;
2240 WinStdioCharState *stdio = chr->opaque;
2246 /* Wait for one byte */
2247 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2249 /* Exit in case of error, continue if nothing read */
2257 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2258 if (stdio->win_stdio_buf == '\r') {
2262 /* Signal the main thread and wait until the byte was eaten */
2263 if (!SetEvent(stdio->hInputReadyEvent)) {
2266 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2272 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2276 static void win_stdio_thread_wait_func(void *opaque)
2278 CharDriverState *chr = opaque;
2279 WinStdioCharState *stdio = chr->opaque;
2281 if (qemu_chr_be_can_write(chr)) {
2282 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2285 SetEvent(stdio->hInputDoneEvent);
2288 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2290 WinStdioCharState *stdio = chr->opaque;
2293 GetConsoleMode(stdio->hStdIn, &dwMode);
2296 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2298 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2302 static void win_stdio_close(CharDriverState *chr)
2304 WinStdioCharState *stdio = chr->opaque;
2306 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2307 CloseHandle(stdio->hInputReadyEvent);
2309 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2310 CloseHandle(stdio->hInputDoneEvent);
2312 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2313 TerminateThread(stdio->hInputThread, 0);
2316 g_free(chr->opaque);
2320 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2322 CharDriverState *chr;
2323 WinStdioCharState *stdio;
2327 chr = qemu_chr_alloc();
2328 stdio = g_malloc0(sizeof(WinStdioCharState));
2330 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2331 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2332 fprintf(stderr, "cannot open stdio: invalid handle\n");
2336 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2338 chr->opaque = stdio;
2339 chr->chr_write = win_stdio_write;
2340 chr->chr_close = win_stdio_close;
2343 if (qemu_add_wait_object(stdio->hStdIn,
2344 win_stdio_wait_func, chr)) {
2345 fprintf(stderr, "qemu_add_wait_object: failed\n");
2350 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2351 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2352 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2355 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2356 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2357 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2358 fprintf(stderr, "cannot create stdio thread or event\n");
2361 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2362 win_stdio_thread_wait_func, chr)) {
2363 fprintf(stderr, "qemu_add_wait_object: failed\n");
2367 dwMode |= ENABLE_LINE_INPUT;
2370 /* set the terminal in raw mode */
2371 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2372 dwMode |= ENABLE_PROCESSED_INPUT;
2375 SetConsoleMode(stdio->hStdIn, dwMode);
2377 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2378 qemu_chr_fe_set_echo(chr, false);
2382 #endif /* !_WIN32 */
2385 /***********************************************************/
2386 /* UDP Net console */
2391 uint8_t buf[READ_BUF_LEN];
2397 /* Called with chr_write_lock held. */
2398 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2400 NetCharDriver *s = chr->opaque;
2401 gsize bytes_written;
2404 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2405 if (status == G_IO_STATUS_EOF) {
2407 } else if (status != G_IO_STATUS_NORMAL) {
2411 return bytes_written;
2414 static int udp_chr_read_poll(void *opaque)
2416 CharDriverState *chr = opaque;
2417 NetCharDriver *s = chr->opaque;
2419 s->max_size = qemu_chr_be_can_write(chr);
2421 /* If there were any stray characters in the queue process them
2424 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2425 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2427 s->max_size = qemu_chr_be_can_write(chr);
2432 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2434 CharDriverState *chr = opaque;
2435 NetCharDriver *s = chr->opaque;
2436 gsize bytes_read = 0;
2439 if (s->max_size == 0) {
2442 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2444 s->bufcnt = bytes_read;
2445 s->bufptr = s->bufcnt;
2446 if (status != G_IO_STATUS_NORMAL) {
2447 remove_fd_in_watch(chr);
2452 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2453 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2455 s->max_size = qemu_chr_be_can_write(chr);
2461 static void udp_chr_update_read_handler(CharDriverState *chr)
2463 NetCharDriver *s = chr->opaque;
2465 remove_fd_in_watch(chr);
2467 chr->fd_in_tag = io_add_watch_poll(s->chan, udp_chr_read_poll,
2472 static void udp_chr_close(CharDriverState *chr)
2474 NetCharDriver *s = chr->opaque;
2476 remove_fd_in_watch(chr);
2478 g_io_channel_unref(s->chan);
2482 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2485 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2487 CharDriverState *chr = NULL;
2488 NetCharDriver *s = NULL;
2490 chr = qemu_chr_alloc();
2491 s = g_malloc0(sizeof(NetCharDriver));
2494 s->chan = io_channel_from_socket(s->fd);
2498 chr->chr_write = udp_chr_write;
2499 chr->chr_update_read_handler = udp_chr_update_read_handler;
2500 chr->chr_close = udp_chr_close;
2501 /* be isn't opened until we get a connection */
2502 chr->explicit_be_open = true;
2506 /***********************************************************/
2507 /* TCP Net console */
2511 GIOChannel *chan, *listen_chan;
2520 int read_msgfds_num;
2522 int write_msgfds_num;
2524 SocketAddress *addr;
2528 guint reconnect_timer;
2529 int64_t reconnect_time;
2530 bool connect_err_reported;
2533 static gboolean socket_reconnect_timeout(gpointer opaque);
2535 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2537 TCPCharDriver *s = chr->opaque;
2538 assert(s->connected == 0);
2539 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2540 socket_reconnect_timeout, chr);
2543 static void check_report_connect_error(CharDriverState *chr,
2546 TCPCharDriver *s = chr->opaque;
2548 if (!s->connect_err_reported) {
2549 error_report("Unable to connect character device %s: %s",
2550 chr->label, error_get_pretty(err));
2551 s->connect_err_reported = true;
2553 qemu_chr_socket_restart_timer(chr);
2556 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2559 static int unix_send_msgfds(CharDriverState *chr, const uint8_t *buf, int len)
2561 TCPCharDriver *s = chr->opaque;
2566 size_t fd_size = s->write_msgfds_num * sizeof(int);
2567 char control[CMSG_SPACE(fd_size)];
2568 struct cmsghdr *cmsg;
2570 memset(&msgh, 0, sizeof(msgh));
2571 memset(control, 0, sizeof(control));
2573 /* set the payload */
2574 iov.iov_base = (uint8_t *) buf;
2577 msgh.msg_iov = &iov;
2578 msgh.msg_iovlen = 1;
2580 msgh.msg_control = control;
2581 msgh.msg_controllen = sizeof(control);
2583 cmsg = CMSG_FIRSTHDR(&msgh);
2585 cmsg->cmsg_len = CMSG_LEN(fd_size);
2586 cmsg->cmsg_level = SOL_SOCKET;
2587 cmsg->cmsg_type = SCM_RIGHTS;
2588 memcpy(CMSG_DATA(cmsg), s->write_msgfds, fd_size);
2591 r = sendmsg(s->fd, &msgh, 0);
2592 } while (r < 0 && errno == EINTR);
2594 /* free the written msgfds, no matter what */
2595 if (s->write_msgfds_num) {
2596 g_free(s->write_msgfds);
2597 s->write_msgfds = 0;
2598 s->write_msgfds_num = 0;
2605 /* Called with chr_write_lock held. */
2606 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2608 TCPCharDriver *s = chr->opaque;
2611 if (s->is_unix && s->write_msgfds_num) {
2612 return unix_send_msgfds(chr, buf, len);
2616 return io_channel_send(s->chan, buf, len);
2619 /* XXX: indicate an error ? */
2624 static int tcp_chr_read_poll(void *opaque)
2626 CharDriverState *chr = opaque;
2627 TCPCharDriver *s = chr->opaque;
2630 s->max_size = qemu_chr_be_can_write(chr);
2635 #define IAC_BREAK 243
2636 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2638 uint8_t *buf, int *size)
2640 /* Handle any telnet client's basic IAC options to satisfy char by
2641 * char mode with no echo. All IAC options will be removed from
2642 * the buf and the do_telnetopt variable will be used to track the
2643 * state of the width of the IAC information.
2645 * IAC commands come in sets of 3 bytes with the exception of the
2646 * "IAC BREAK" command and the double IAC.
2652 for (i = 0; i < *size; i++) {
2653 if (s->do_telnetopt > 1) {
2654 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2655 /* Double IAC means send an IAC */
2659 s->do_telnetopt = 1;
2661 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2662 /* Handle IAC break commands by sending a serial break */
2663 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2668 if (s->do_telnetopt >= 4) {
2669 s->do_telnetopt = 1;
2672 if ((unsigned char)buf[i] == IAC) {
2673 s->do_telnetopt = 2;
2684 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2686 TCPCharDriver *s = chr->opaque;
2687 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2689 assert(num <= TCP_MAX_FDS);
2694 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2696 /* Close unused fds */
2697 for (i = to_copy; i < s->read_msgfds_num; i++) {
2698 close(s->read_msgfds[i]);
2701 g_free(s->read_msgfds);
2703 s->read_msgfds_num = 0;
2709 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2711 TCPCharDriver *s = chr->opaque;
2713 /* clear old pending fd array */
2714 if (s->write_msgfds) {
2715 g_free(s->write_msgfds);
2719 s->write_msgfds = g_malloc(num * sizeof(int));
2720 memcpy(s->write_msgfds, fds, num * sizeof(int));
2723 s->write_msgfds_num = num;
2729 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2731 TCPCharDriver *s = chr->opaque;
2732 struct cmsghdr *cmsg;
2734 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2737 if (cmsg->cmsg_len < CMSG_LEN(sizeof(int)) ||
2738 cmsg->cmsg_level != SOL_SOCKET ||
2739 cmsg->cmsg_type != SCM_RIGHTS) {
2743 fd_size = cmsg->cmsg_len - CMSG_LEN(0);
2749 /* close and clean read_msgfds */
2750 for (i = 0; i < s->read_msgfds_num; i++) {
2751 close(s->read_msgfds[i]);
2754 if (s->read_msgfds_num) {
2755 g_free(s->read_msgfds);
2758 s->read_msgfds_num = fd_size / sizeof(int);
2759 s->read_msgfds = g_malloc(fd_size);
2760 memcpy(s->read_msgfds, CMSG_DATA(cmsg), fd_size);
2762 for (i = 0; i < s->read_msgfds_num; i++) {
2763 int fd = s->read_msgfds[i];
2768 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2771 #ifndef MSG_CMSG_CLOEXEC
2772 qemu_set_cloexec(fd);
2778 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2780 TCPCharDriver *s = chr->opaque;
2781 struct msghdr msg = { NULL, };
2782 struct iovec iov[1];
2784 struct cmsghdr cmsg;
2785 char control[CMSG_SPACE(sizeof(int) * TCP_MAX_FDS)];
2790 iov[0].iov_base = buf;
2791 iov[0].iov_len = len;
2795 msg.msg_control = &msg_control;
2796 msg.msg_controllen = sizeof(msg_control);
2798 #ifdef MSG_CMSG_CLOEXEC
2799 flags |= MSG_CMSG_CLOEXEC;
2802 ret = recvmsg(s->fd, &msg, flags);
2803 } while (ret == -1 && errno == EINTR);
2805 if (ret > 0 && s->is_unix) {
2806 unix_process_msgfd(chr, &msg);
2812 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2814 TCPCharDriver *s = chr->opaque;
2818 ret = qemu_recv(s->fd, buf, len, 0);
2819 } while (ret == -1 && socket_error() == EINTR);
2825 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2827 TCPCharDriver *s = chr->opaque;
2828 return g_io_create_watch(s->chan, cond);
2831 static void tcp_chr_disconnect(CharDriverState *chr)
2833 TCPCharDriver *s = chr->opaque;
2836 if (s->listen_chan) {
2837 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
2838 tcp_chr_accept, chr);
2840 remove_fd_in_watch(chr);
2841 g_io_channel_unref(s->chan);
2845 SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
2846 "disconnected:", s->addr, s->is_listen, s->is_telnet);
2847 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2848 if (s->reconnect_time) {
2849 qemu_chr_socket_restart_timer(chr);
2853 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2855 CharDriverState *chr = opaque;
2856 TCPCharDriver *s = chr->opaque;
2857 uint8_t buf[READ_BUF_LEN];
2860 if (!s->connected || s->max_size <= 0) {
2864 if (len > s->max_size)
2866 size = tcp_chr_recv(chr, (void *)buf, len);
2869 socket_error() != EAGAIN && socket_error() != EWOULDBLOCK)) {
2870 /* connection closed */
2871 tcp_chr_disconnect(chr);
2872 } else if (size > 0) {
2873 if (s->do_telnetopt)
2874 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2876 qemu_chr_be_write(chr, buf, size);
2882 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2884 TCPCharDriver *s = chr->opaque;
2887 if (!s->connected) {
2891 size = tcp_chr_recv(chr, (void *) buf, len);
2893 /* connection closed */
2894 tcp_chr_disconnect(chr);
2901 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2903 CharDriverState *chr = qemu_chr_open_fd(eventfd, eventfd);
2906 chr->avail_connections = 1;
2913 static void tcp_chr_connect(void *opaque)
2915 CharDriverState *chr = opaque;
2916 TCPCharDriver *s = chr->opaque;
2917 struct sockaddr_storage ss, ps;
2918 socklen_t ss_len = sizeof(ss), ps_len = sizeof(ps);
2920 memset(&ss, 0, ss_len);
2921 if (getsockname(s->fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2922 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
2923 "Error in getsockname: %s\n", strerror(errno));
2924 } else if (getpeername(s->fd, (struct sockaddr *) &ps, &ps_len) != 0) {
2925 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
2926 "Error in getpeername: %s\n", strerror(errno));
2928 sockaddr_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
2929 &ss, ss_len, &ps, ps_len,
2930 s->is_listen, s->is_telnet);
2935 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2938 qemu_chr_be_generic_open(chr);
2941 static void tcp_chr_update_read_handler(CharDriverState *chr)
2943 TCPCharDriver *s = chr->opaque;
2945 remove_fd_in_watch(chr);
2947 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2952 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2953 static void tcp_chr_telnet_init(int fd)
2956 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2957 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2958 send(fd, (char *)buf, 3, 0);
2959 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2960 send(fd, (char *)buf, 3, 0);
2961 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2962 send(fd, (char *)buf, 3, 0);
2963 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2964 send(fd, (char *)buf, 3, 0);
2967 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2969 TCPCharDriver *s = chr->opaque;
2973 qemu_set_nonblock(fd);
2975 socket_set_nodelay(fd);
2977 s->chan = io_channel_from_socket(fd);
2978 if (s->listen_tag) {
2979 g_source_remove(s->listen_tag);
2982 tcp_chr_connect(chr);
2987 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2989 CharDriverState *chr = opaque;
2990 TCPCharDriver *s = chr->opaque;
2991 struct sockaddr_in saddr;
2993 struct sockaddr_un uaddr;
2995 struct sockaddr *addr;
3002 len = sizeof(uaddr);
3003 addr = (struct sockaddr *)&uaddr;
3007 len = sizeof(saddr);
3008 addr = (struct sockaddr *)&saddr;
3010 fd = qemu_accept(s->listen_fd, addr, &len);
3011 if (fd < 0 && errno != EINTR) {
3014 } else if (fd >= 0) {
3015 if (s->do_telnetopt)
3016 tcp_chr_telnet_init(fd);
3020 if (tcp_chr_add_client(chr, fd) < 0)
3026 static void tcp_chr_close(CharDriverState *chr)
3028 TCPCharDriver *s = chr->opaque;
3031 if (s->reconnect_timer) {
3032 g_source_remove(s->reconnect_timer);
3033 s->reconnect_timer = 0;
3035 qapi_free_SocketAddress(s->addr);
3037 remove_fd_in_watch(chr);
3039 g_io_channel_unref(s->chan);
3043 if (s->listen_fd >= 0) {
3044 if (s->listen_tag) {
3045 g_source_remove(s->listen_tag);
3048 if (s->listen_chan) {
3049 g_io_channel_unref(s->listen_chan);
3051 closesocket(s->listen_fd);
3053 if (s->read_msgfds_num) {
3054 for (i = 0; i < s->read_msgfds_num; i++) {
3055 close(s->read_msgfds[i]);
3057 g_free(s->read_msgfds);
3059 if (s->write_msgfds_num) {
3060 g_free(s->write_msgfds);
3063 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3066 static void qemu_chr_finish_socket_connection(CharDriverState *chr, int fd)
3068 TCPCharDriver *s = chr->opaque;
3072 s->listen_chan = io_channel_from_socket(s->listen_fd);
3073 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
3074 tcp_chr_accept, chr);
3078 socket_set_nodelay(fd);
3079 s->chan = io_channel_from_socket(s->fd);
3080 tcp_chr_connect(chr);
3084 static void qemu_chr_socket_connected(int fd, Error *err, void *opaque)
3086 CharDriverState *chr = opaque;
3087 TCPCharDriver *s = chr->opaque;
3090 check_report_connect_error(chr, err);
3094 s->connect_err_reported = false;
3095 qemu_chr_finish_socket_connection(chr, fd);
3098 static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp)
3100 TCPCharDriver *s = chr->opaque;
3104 fd = socket_listen(s->addr, errp);
3105 } else if (s->reconnect_time) {
3106 fd = socket_connect(s->addr, errp, qemu_chr_socket_connected, chr);
3109 fd = socket_connect(s->addr, errp, NULL, NULL);
3115 qemu_chr_finish_socket_connection(chr, fd);
3119 /*********************************************************/
3120 /* Ring buffer chardev */
3127 } RingBufCharDriver;
3129 static size_t ringbuf_count(const CharDriverState *chr)
3131 const RingBufCharDriver *d = chr->opaque;
3133 return d->prod - d->cons;
3136 /* Called with chr_write_lock held. */
3137 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3139 RingBufCharDriver *d = chr->opaque;
3142 if (!buf || (len < 0)) {
3146 for (i = 0; i < len; i++ ) {
3147 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3148 if (d->prod - d->cons > d->size) {
3149 d->cons = d->prod - d->size;
3156 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3158 RingBufCharDriver *d = chr->opaque;
3161 qemu_mutex_lock(&chr->chr_write_lock);
3162 for (i = 0; i < len && d->cons != d->prod; i++) {
3163 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3165 qemu_mutex_unlock(&chr->chr_write_lock);
3170 static void ringbuf_chr_close(struct CharDriverState *chr)
3172 RingBufCharDriver *d = chr->opaque;
3179 static CharDriverState *qemu_chr_open_ringbuf(ChardevRingbuf *opts,
3182 CharDriverState *chr;
3183 RingBufCharDriver *d;
3185 chr = qemu_chr_alloc();
3186 d = g_malloc(sizeof(*d));
3188 d->size = opts->has_size ? opts->size : 65536;
3190 /* The size must be power of 2 */
3191 if (d->size & (d->size - 1)) {
3192 error_setg(errp, "size of ringbuf chardev must be power of two");
3198 d->cbuf = g_malloc0(d->size);
3201 chr->chr_write = ringbuf_chr_write;
3202 chr->chr_close = ringbuf_chr_close;
3212 bool chr_is_ringbuf(const CharDriverState *chr)
3214 return chr->chr_write == ringbuf_chr_write;
3217 void qmp_ringbuf_write(const char *device, const char *data,
3218 bool has_format, enum DataFormat format,
3221 CharDriverState *chr;
3222 const uint8_t *write_data;
3226 chr = qemu_chr_find(device);
3228 error_setg(errp, "Device '%s' not found", device);
3232 if (!chr_is_ringbuf(chr)) {
3233 error_setg(errp,"%s is not a ringbuf device", device);
3237 if (has_format && (format == DATA_FORMAT_BASE64)) {
3238 write_data = g_base64_decode(data, &write_count);
3240 write_data = (uint8_t *)data;
3241 write_count = strlen(data);
3244 ret = ringbuf_chr_write(chr, write_data, write_count);
3246 if (write_data != (uint8_t *)data) {
3247 g_free((void *)write_data);
3251 error_setg(errp, "Failed to write to device %s", device);
3256 char *qmp_ringbuf_read(const char *device, int64_t size,
3257 bool has_format, enum DataFormat format,
3260 CharDriverState *chr;
3265 chr = qemu_chr_find(device);
3267 error_setg(errp, "Device '%s' not found", device);
3271 if (!chr_is_ringbuf(chr)) {
3272 error_setg(errp,"%s is not a ringbuf device", device);
3277 error_setg(errp, "size must be greater than zero");
3281 count = ringbuf_count(chr);
3282 size = size > count ? count : size;
3283 read_data = g_malloc(size + 1);
3285 ringbuf_chr_read(chr, read_data, size);
3287 if (has_format && (format == DATA_FORMAT_BASE64)) {
3288 data = g_base64_encode(read_data, size);
3292 * FIXME should read only complete, valid UTF-8 characters up
3293 * to @size bytes. Invalid sequences should be replaced by a
3294 * suitable replacement character. Except when (and only
3295 * when) ring buffer lost characters since last read, initial
3296 * continuation characters should be dropped.
3298 read_data[size] = 0;
3299 data = (char *)read_data;
3305 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3307 char host[65], port[33], width[8], height[8];
3311 Error *local_err = NULL;
3313 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3315 error_report_err(local_err);
3319 if (strstart(filename, "mon:", &p)) {
3321 qemu_opt_set(opts, "mux", "on", &error_abort);
3322 if (strcmp(filename, "stdio") == 0) {
3323 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3324 * but pass it to the guest. Handle this only for compat syntax,
3325 * for -chardev syntax we have special option for this.
3326 * This is what -nographic did, redirecting+muxing serial+monitor
3327 * to stdio causing Ctrl+C to be passed to guest. */
3328 qemu_opt_set(opts, "signal", "off", &error_abort);
3332 if (strcmp(filename, "null") == 0 ||
3333 strcmp(filename, "pty") == 0 ||
3334 strcmp(filename, "msmouse") == 0 ||
3335 strcmp(filename, "braille") == 0 ||
3336 strcmp(filename, "testdev") == 0 ||
3337 strcmp(filename, "stdio") == 0) {
3338 qemu_opt_set(opts, "backend", filename, &error_abort);
3341 if (strstart(filename, "vc", &p)) {
3342 qemu_opt_set(opts, "backend", "vc", &error_abort);
3344 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3346 qemu_opt_set(opts, "width", width, &error_abort);
3347 qemu_opt_set(opts, "height", height, &error_abort);
3348 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3350 qemu_opt_set(opts, "cols", width, &error_abort);
3351 qemu_opt_set(opts, "rows", height, &error_abort);
3358 if (strcmp(filename, "con:") == 0) {
3359 qemu_opt_set(opts, "backend", "console", &error_abort);
3362 if (strstart(filename, "COM", NULL)) {
3363 qemu_opt_set(opts, "backend", "serial", &error_abort);
3364 qemu_opt_set(opts, "path", filename, &error_abort);
3367 if (strstart(filename, "file:", &p)) {
3368 qemu_opt_set(opts, "backend", "file", &error_abort);
3369 qemu_opt_set(opts, "path", p, &error_abort);
3372 if (strstart(filename, "pipe:", &p)) {
3373 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3374 qemu_opt_set(opts, "path", p, &error_abort);
3377 if (strstart(filename, "tcp:", &p) ||
3378 strstart(filename, "telnet:", &p)) {
3379 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3381 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3384 qemu_opt_set(opts, "backend", "socket", &error_abort);
3385 qemu_opt_set(opts, "host", host, &error_abort);
3386 qemu_opt_set(opts, "port", port, &error_abort);
3387 if (p[pos] == ',') {
3388 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3390 error_report_err(local_err);
3394 if (strstart(filename, "telnet:", &p))
3395 qemu_opt_set(opts, "telnet", "on", &error_abort);
3398 if (strstart(filename, "udp:", &p)) {
3399 qemu_opt_set(opts, "backend", "udp", &error_abort);
3400 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3402 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3406 qemu_opt_set(opts, "host", host, &error_abort);
3407 qemu_opt_set(opts, "port", port, &error_abort);
3408 if (p[pos] == '@') {
3410 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3412 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3416 qemu_opt_set(opts, "localaddr", host, &error_abort);
3417 qemu_opt_set(opts, "localport", port, &error_abort);
3421 if (strstart(filename, "unix:", &p)) {
3422 qemu_opt_set(opts, "backend", "socket", &error_abort);
3423 qemu_opts_do_parse(opts, p, "path", &local_err);
3425 error_report_err(local_err);
3430 if (strstart(filename, "/dev/parport", NULL) ||
3431 strstart(filename, "/dev/ppi", NULL)) {
3432 qemu_opt_set(opts, "backend", "parport", &error_abort);
3433 qemu_opt_set(opts, "path", filename, &error_abort);
3436 if (strstart(filename, "/dev/", NULL)) {
3437 qemu_opt_set(opts, "backend", "tty", &error_abort);
3438 qemu_opt_set(opts, "path", filename, &error_abort);
3443 qemu_opts_del(opts);
3447 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3450 const char *path = qemu_opt_get(opts, "path");
3453 error_setg(errp, "chardev: file: no filename given");
3456 backend->file = g_new0(ChardevFile, 1);
3457 backend->file->out = g_strdup(path);
3460 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3463 backend->stdio = g_new0(ChardevStdio, 1);
3464 backend->stdio->has_signal = true;
3465 backend->stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3468 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3471 const char *device = qemu_opt_get(opts, "path");
3473 if (device == NULL) {
3474 error_setg(errp, "chardev: serial/tty: no device path given");
3477 backend->serial = g_new0(ChardevHostdev, 1);
3478 backend->serial->device = g_strdup(device);
3481 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3484 const char *device = qemu_opt_get(opts, "path");
3486 if (device == NULL) {
3487 error_setg(errp, "chardev: parallel: no device path given");
3490 backend->parallel = g_new0(ChardevHostdev, 1);
3491 backend->parallel->device = g_strdup(device);
3494 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3497 const char *device = qemu_opt_get(opts, "path");
3499 if (device == NULL) {
3500 error_setg(errp, "chardev: pipe: no device path given");
3503 backend->pipe = g_new0(ChardevHostdev, 1);
3504 backend->pipe->device = g_strdup(device);
3507 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3512 backend->ringbuf = g_new0(ChardevRingbuf, 1);
3514 val = qemu_opt_get_size(opts, "size", 0);
3516 backend->ringbuf->has_size = true;
3517 backend->ringbuf->size = val;
3521 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3524 const char *chardev = qemu_opt_get(opts, "chardev");
3526 if (chardev == NULL) {
3527 error_setg(errp, "chardev: mux: no chardev given");
3530 backend->mux = g_new0(ChardevMux, 1);
3531 backend->mux->chardev = g_strdup(chardev);
3534 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3537 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3538 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3539 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3540 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3541 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3542 const char *path = qemu_opt_get(opts, "path");
3543 const char *host = qemu_opt_get(opts, "host");
3544 const char *port = qemu_opt_get(opts, "port");
3545 SocketAddress *addr;
3549 error_setg(errp, "chardev: socket: no host given");
3553 error_setg(errp, "chardev: socket: no port given");
3558 backend->socket = g_new0(ChardevSocket, 1);
3560 backend->socket->has_nodelay = true;
3561 backend->socket->nodelay = do_nodelay;
3562 backend->socket->has_server = true;
3563 backend->socket->server = is_listen;
3564 backend->socket->has_telnet = true;
3565 backend->socket->telnet = is_telnet;
3566 backend->socket->has_wait = true;
3567 backend->socket->wait = is_waitconnect;
3568 backend->socket->has_reconnect = true;
3569 backend->socket->reconnect = reconnect;
3571 addr = g_new0(SocketAddress, 1);
3573 addr->kind = SOCKET_ADDRESS_KIND_UNIX;
3574 addr->q_unix = g_new0(UnixSocketAddress, 1);
3575 addr->q_unix->path = g_strdup(path);
3577 addr->kind = SOCKET_ADDRESS_KIND_INET;
3578 addr->inet = g_new0(InetSocketAddress, 1);
3579 addr->inet->host = g_strdup(host);
3580 addr->inet->port = g_strdup(port);
3581 addr->inet->has_to = qemu_opt_get(opts, "to");
3582 addr->inet->to = qemu_opt_get_number(opts, "to", 0);
3583 addr->inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3584 addr->inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3585 addr->inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3586 addr->inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3588 backend->socket->addr = addr;
3591 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3594 const char *host = qemu_opt_get(opts, "host");
3595 const char *port = qemu_opt_get(opts, "port");
3596 const char *localaddr = qemu_opt_get(opts, "localaddr");
3597 const char *localport = qemu_opt_get(opts, "localport");
3598 bool has_local = false;
3599 SocketAddress *addr;
3601 if (host == NULL || strlen(host) == 0) {
3604 if (port == NULL || strlen(port) == 0) {
3605 error_setg(errp, "chardev: udp: remote port not specified");
3608 if (localport == NULL || strlen(localport) == 0) {
3613 if (localaddr == NULL || strlen(localaddr) == 0) {
3619 backend->udp = g_new0(ChardevUdp, 1);
3621 addr = g_new0(SocketAddress, 1);
3622 addr->kind = SOCKET_ADDRESS_KIND_INET;
3623 addr->inet = g_new0(InetSocketAddress, 1);
3624 addr->inet->host = g_strdup(host);
3625 addr->inet->port = g_strdup(port);
3626 addr->inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3627 addr->inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3628 addr->inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3629 addr->inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3630 backend->udp->remote = addr;
3633 backend->udp->has_local = true;
3634 addr = g_new0(SocketAddress, 1);
3635 addr->kind = SOCKET_ADDRESS_KIND_INET;
3636 addr->inet = g_new0(InetSocketAddress, 1);
3637 addr->inet->host = g_strdup(localaddr);
3638 addr->inet->port = g_strdup(localport);
3639 backend->udp->local = addr;
3643 typedef struct CharDriver {
3645 ChardevBackendKind kind;
3646 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3649 static GSList *backends;
3651 void register_char_driver(const char *name, ChardevBackendKind kind,
3652 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3656 s = g_malloc0(sizeof(*s));
3657 s->name = g_strdup(name);
3661 backends = g_slist_append(backends, s);
3664 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3665 void (*init)(struct CharDriverState *s),
3668 Error *local_err = NULL;
3670 CharDriverState *chr;
3672 ChardevReturn *ret = NULL;
3673 ChardevBackend *backend;
3674 const char *id = qemu_opts_id(opts);
3678 error_setg(errp, "chardev: no id specified");
3682 if (qemu_opt_get(opts, "backend") == NULL) {
3683 error_setg(errp, "chardev: \"%s\" missing backend",
3684 qemu_opts_id(opts));
3687 for (i = backends; i; i = i->next) {
3690 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3695 error_setg(errp, "chardev: backend \"%s\" not found",
3696 qemu_opt_get(opts, "backend"));
3700 backend = g_new0(ChardevBackend, 1);
3702 if (qemu_opt_get_bool(opts, "mux", 0)) {
3703 bid = g_strdup_printf("%s-base", id);
3707 backend->kind = cd->kind;
3709 cd->parse(opts, backend, &local_err);
3711 error_propagate(errp, local_err);
3715 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3721 qapi_free_ChardevBackend(backend);
3722 qapi_free_ChardevReturn(ret);
3723 backend = g_new0(ChardevBackend, 1);
3724 backend->mux = g_new0(ChardevMux, 1);
3725 backend->kind = CHARDEV_BACKEND_KIND_MUX;
3726 backend->mux->chardev = g_strdup(bid);
3727 ret = qmp_chardev_add(id, backend, errp);
3729 chr = qemu_chr_find(bid);
3730 qemu_chr_delete(chr);
3736 chr = qemu_chr_find(id);
3740 qapi_free_ChardevBackend(backend);
3741 qapi_free_ChardevReturn(ret);
3746 qemu_opts_del(opts);
3750 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3753 CharDriverState *chr;
3757 if (strstart(filename, "chardev:", &p)) {
3758 return qemu_chr_find(p);
3761 opts = qemu_chr_parse_compat(label, filename);
3765 chr = qemu_chr_new_from_opts(opts, init, &err);
3767 error_report_err(err);
3769 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3770 qemu_chr_fe_claim_no_fail(chr);
3771 monitor_init(chr, MONITOR_USE_READLINE);
3776 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3778 if (chr->chr_set_echo) {
3779 chr->chr_set_echo(chr, echo);
3783 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3785 if (chr->fe_open == fe_open) {
3788 chr->fe_open = fe_open;
3789 if (chr->chr_set_fe_open) {
3790 chr->chr_set_fe_open(chr, fe_open);
3794 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3796 if (chr->chr_fe_event) {
3797 chr->chr_fe_event(chr, event);
3801 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3802 GIOFunc func, void *user_data)
3807 if (s->chr_add_watch == NULL) {
3811 src = s->chr_add_watch(s, cond);
3816 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3817 tag = g_source_attach(src, NULL);
3818 g_source_unref(src);
3823 int qemu_chr_fe_claim(CharDriverState *s)
3825 if (s->avail_connections < 1) {
3828 s->avail_connections--;
3832 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3834 if (qemu_chr_fe_claim(s) != 0) {
3835 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3836 __func__, s->label);
3841 void qemu_chr_fe_release(CharDriverState *s)
3843 s->avail_connections++;
3846 void qemu_chr_delete(CharDriverState *chr)
3848 QTAILQ_REMOVE(&chardevs, chr, next);
3849 if (chr->chr_close) {
3850 chr->chr_close(chr);
3852 g_free(chr->filename);
3854 qemu_opts_del(chr->opts);
3858 ChardevInfoList *qmp_query_chardev(Error **errp)
3860 ChardevInfoList *chr_list = NULL;
3861 CharDriverState *chr;
3863 QTAILQ_FOREACH(chr, &chardevs, next) {
3864 ChardevInfoList *info = g_malloc0(sizeof(*info));
3865 info->value = g_malloc0(sizeof(*info->value));
3866 info->value->label = g_strdup(chr->label);
3867 info->value->filename = g_strdup(chr->filename);
3868 info->value->frontend_open = chr->fe_open;
3870 info->next = chr_list;
3877 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
3879 ChardevBackendInfoList *backend_list = NULL;
3880 CharDriver *c = NULL;
3883 for (i = backends; i; i = i->next) {
3884 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
3886 info->value = g_malloc0(sizeof(*info->value));
3887 info->value->name = g_strdup(c->name);
3889 info->next = backend_list;
3890 backend_list = info;
3893 return backend_list;
3896 CharDriverState *qemu_chr_find(const char *name)
3898 CharDriverState *chr;
3900 QTAILQ_FOREACH(chr, &chardevs, next) {
3901 if (strcmp(chr->label, name) != 0)
3908 /* Get a character (serial) device interface. */
3909 CharDriverState *qemu_char_get_next_serial(void)
3911 static int next_serial;
3912 CharDriverState *chr;
3914 /* FIXME: This function needs to go away: use chardev properties! */
3916 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3917 chr = serial_hds[next_serial++];
3918 qemu_chr_fe_claim_no_fail(chr);
3924 QemuOptsList qemu_chardev_opts = {
3926 .implied_opt_name = "backend",
3927 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3931 .type = QEMU_OPT_STRING,
3934 .type = QEMU_OPT_STRING,
3937 .type = QEMU_OPT_STRING,
3940 .type = QEMU_OPT_STRING,
3942 .name = "localaddr",
3943 .type = QEMU_OPT_STRING,
3945 .name = "localport",
3946 .type = QEMU_OPT_STRING,
3949 .type = QEMU_OPT_NUMBER,
3952 .type = QEMU_OPT_BOOL,
3955 .type = QEMU_OPT_BOOL,
3958 .type = QEMU_OPT_BOOL,
3961 .type = QEMU_OPT_BOOL,
3964 .type = QEMU_OPT_BOOL,
3966 .name = "reconnect",
3967 .type = QEMU_OPT_NUMBER,
3970 .type = QEMU_OPT_BOOL,
3973 .type = QEMU_OPT_NUMBER,
3976 .type = QEMU_OPT_NUMBER,
3979 .type = QEMU_OPT_NUMBER,
3982 .type = QEMU_OPT_NUMBER,
3985 .type = QEMU_OPT_BOOL,
3988 .type = QEMU_OPT_BOOL,
3991 .type = QEMU_OPT_STRING,
3994 .type = QEMU_OPT_NUMBER,
3997 .type = QEMU_OPT_SIZE,
4000 .type = QEMU_OPT_STRING,
4002 { /* end of list */ }
4008 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
4013 error_setg(errp, "input file not supported");
4017 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
4018 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
4019 if (out == INVALID_HANDLE_VALUE) {
4020 error_setg(errp, "open %s failed", file->out);
4023 return qemu_chr_open_win_file(out);
4026 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
4029 return qemu_chr_open_win_path(serial->device);
4032 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
4035 error_setg(errp, "character device backend type 'parallel' not supported");
4041 static int qmp_chardev_open_file_source(char *src, int flags,
4046 TFR(fd = qemu_open(src, flags, 0666));
4048 error_setg_file_open(errp, errno, src);
4053 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
4055 int flags, in = -1, out;
4057 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
4058 out = qmp_chardev_open_file_source(file->out, flags, errp);
4065 in = qmp_chardev_open_file_source(file->in, flags, errp);
4072 return qemu_chr_open_fd(in, out);
4075 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
4078 #ifdef HAVE_CHARDEV_TTY
4081 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4085 qemu_set_nonblock(fd);
4086 return qemu_chr_open_tty_fd(fd);
4088 error_setg(errp, "character device backend type 'serial' not supported");
4093 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
4096 #ifdef HAVE_CHARDEV_PARPORT
4099 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4103 return qemu_chr_open_pp_fd(fd);
4105 error_setg(errp, "character device backend type 'parallel' not supported");
4112 static void socket_try_connect(CharDriverState *chr)
4116 if (!qemu_chr_open_socket_fd(chr, &err)) {
4117 check_report_connect_error(chr, err);
4121 static gboolean socket_reconnect_timeout(gpointer opaque)
4123 CharDriverState *chr = opaque;
4124 TCPCharDriver *s = chr->opaque;
4126 s->reconnect_timer = 0;
4132 socket_try_connect(chr);
4137 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
4140 CharDriverState *chr;
4142 SocketAddress *addr = sock->addr;
4143 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4144 bool is_listen = sock->has_server ? sock->server : true;
4145 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4146 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4147 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4149 chr = qemu_chr_alloc();
4150 s = g_malloc0(sizeof(TCPCharDriver));
4154 s->is_unix = addr->kind == SOCKET_ADDRESS_KIND_UNIX;
4155 s->is_listen = is_listen;
4156 s->is_telnet = is_telnet;
4157 s->do_nodelay = do_nodelay;
4158 qapi_copy_SocketAddress(&s->addr, sock->addr);
4161 chr->chr_write = tcp_chr_write;
4162 chr->chr_sync_read = tcp_chr_sync_read;
4163 chr->chr_close = tcp_chr_close;
4164 chr->get_msgfds = tcp_get_msgfds;
4165 chr->set_msgfds = tcp_set_msgfds;
4166 chr->chr_add_client = tcp_chr_add_client;
4167 chr->chr_add_watch = tcp_chr_add_watch;
4168 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4169 /* be isn't opened until we get a connection */
4170 chr->explicit_be_open = true;
4172 chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
4173 SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, "disconnected:",
4174 addr, is_listen, is_telnet);
4178 s->do_telnetopt = 1;
4180 } else if (reconnect > 0) {
4181 s->reconnect_time = reconnect;
4184 if (s->reconnect_time) {
4185 socket_try_connect(chr);
4186 } else if (!qemu_chr_open_socket_fd(chr, errp)) {
4188 g_free(chr->filename);
4193 if (is_listen && is_waitconnect) {
4194 fprintf(stderr, "QEMU waiting for connection on: %s\n",
4196 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
4197 qemu_set_nonblock(s->listen_fd);
4203 static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
4208 fd = socket_dgram(udp->remote, udp->local, errp);
4212 return qemu_chr_open_udp_fd(fd);
4215 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4218 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4219 CharDriverState *base, *chr = NULL;
4221 chr = qemu_chr_find(id);
4223 error_setg(errp, "Chardev '%s' already exists", id);
4228 switch (backend->kind) {
4229 case CHARDEV_BACKEND_KIND_FILE:
4230 chr = qmp_chardev_open_file(backend->file, errp);
4232 case CHARDEV_BACKEND_KIND_SERIAL:
4233 chr = qmp_chardev_open_serial(backend->serial, errp);
4235 case CHARDEV_BACKEND_KIND_PARALLEL:
4236 chr = qmp_chardev_open_parallel(backend->parallel, errp);
4238 case CHARDEV_BACKEND_KIND_PIPE:
4239 chr = qemu_chr_open_pipe(backend->pipe);
4241 case CHARDEV_BACKEND_KIND_SOCKET:
4242 chr = qmp_chardev_open_socket(backend->socket, errp);
4244 case CHARDEV_BACKEND_KIND_UDP:
4245 chr = qmp_chardev_open_udp(backend->udp, errp);
4247 #ifdef HAVE_CHARDEV_TTY
4248 case CHARDEV_BACKEND_KIND_PTY:
4249 chr = qemu_chr_open_pty(id, ret);
4252 case CHARDEV_BACKEND_KIND_NULL:
4253 chr = qemu_chr_open_null();
4255 case CHARDEV_BACKEND_KIND_MUX:
4256 base = qemu_chr_find(backend->mux->chardev);
4258 error_setg(errp, "mux: base chardev %s not found",
4259 backend->mux->chardev);
4262 chr = qemu_chr_open_mux(base);
4264 case CHARDEV_BACKEND_KIND_MSMOUSE:
4265 chr = qemu_chr_open_msmouse();
4267 #ifdef CONFIG_BRLAPI
4268 case CHARDEV_BACKEND_KIND_BRAILLE:
4269 chr = chr_baum_init();
4272 case CHARDEV_BACKEND_KIND_TESTDEV:
4273 chr = chr_testdev_init();
4275 case CHARDEV_BACKEND_KIND_STDIO:
4276 chr = qemu_chr_open_stdio(backend->stdio);
4279 case CHARDEV_BACKEND_KIND_CONSOLE:
4280 chr = qemu_chr_open_win_con();
4284 case CHARDEV_BACKEND_KIND_SPICEVMC:
4285 chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
4287 case CHARDEV_BACKEND_KIND_SPICEPORT:
4288 chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
4291 case CHARDEV_BACKEND_KIND_VC:
4292 chr = vc_init(backend->vc);
4294 case CHARDEV_BACKEND_KIND_RINGBUF:
4295 case CHARDEV_BACKEND_KIND_MEMORY:
4296 chr = qemu_chr_open_ringbuf(backend->ringbuf, errp);
4299 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
4304 * Character backend open hasn't been fully converted to the Error
4305 * API. Some opens fail without setting an error. Set a generic
4307 * TODO full conversion to Error API
4309 if (chr == NULL && errp && !*errp) {
4310 error_setg(errp, "Failed to create chardev");
4313 chr->label = g_strdup(id);
4314 chr->avail_connections =
4315 (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4316 if (!chr->filename) {
4317 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
4319 if (!chr->explicit_be_open) {
4320 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4322 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4330 void qmp_chardev_remove(const char *id, Error **errp)
4332 CharDriverState *chr;
4334 chr = qemu_chr_find(id);
4336 error_setg(errp, "Chardev '%s' not found", id);
4339 if (chr->chr_can_read || chr->chr_read ||
4340 chr->chr_event || chr->handler_opaque) {
4341 error_setg(errp, "Chardev '%s' is busy", id);
4344 qemu_chr_delete(chr);
4347 static void register_types(void)
4349 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL);
4350 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4351 qemu_chr_parse_socket);
4352 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp);
4353 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4354 qemu_chr_parse_ringbuf);
4355 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4356 qemu_chr_parse_file_out);
4357 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4358 qemu_chr_parse_stdio);
4359 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4360 qemu_chr_parse_serial);
4361 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4362 qemu_chr_parse_serial);
4363 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4364 qemu_chr_parse_parallel);
4365 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4366 qemu_chr_parse_parallel);
4367 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
4368 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
4369 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4370 qemu_chr_parse_pipe);
4371 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux);
4372 /* Bug-compatibility: */
4373 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4374 qemu_chr_parse_ringbuf);
4375 /* this must be done after machine init, since we register FEs with muxes
4376 * as part of realize functions like serial_isa_realizefn when -nographic
4379 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4382 type_init(register_types);