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 "ui/console.h"
27 #include "sysemu/sysemu.h"
28 #include "qemu/timer.h"
29 #include "char/char.h"
31 #include "qmp-commands.h"
41 #include <sys/times.h>
45 #include <sys/ioctl.h>
46 #include <sys/resource.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
50 #include <arpa/inet.h>
53 #include <sys/select.h>
56 #if defined(__GLIBC__)
58 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
63 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
64 #include <dev/ppbus/ppi.h>
65 #include <dev/ppbus/ppbconf.h>
66 #elif defined(__DragonFly__)
67 #include <dev/misc/ppi/ppi.h>
68 #include <bus/ppbus/ppbconf.h>
74 #include <linux/ppdev.h>
75 #include <linux/parport.h>
79 #include <sys/ethernet.h>
80 #include <sys/sockio.h>
81 #include <netinet/arp.h>
82 #include <netinet/in.h>
83 #include <netinet/in_systm.h>
84 #include <netinet/ip.h>
85 #include <netinet/ip_icmp.h> // must come after ip.h
86 #include <netinet/udp.h>
87 #include <netinet/tcp.h>
95 #include "qemu/sockets.h"
96 #include "ui/qemu-spice.h"
98 #define READ_BUF_LEN 4096
100 /***********************************************************/
101 /* character device */
103 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
104 QTAILQ_HEAD_INITIALIZER(chardevs);
106 void qemu_chr_be_event(CharDriverState *s, int event)
108 /* Keep track if the char device is open */
110 case CHR_EVENT_OPENED:
113 case CHR_EVENT_CLOSED:
120 s->chr_event(s->handler_opaque, event);
123 static gboolean qemu_chr_generic_open_bh(gpointer opaque)
125 CharDriverState *s = opaque;
126 qemu_chr_be_event(s, CHR_EVENT_OPENED);
131 void qemu_chr_generic_open(CharDriverState *s)
133 if (s->idle_tag == 0) {
134 s->idle_tag = g_idle_add(qemu_chr_generic_open_bh, s);
138 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
140 return s->chr_write(s, buf, len);
143 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
148 while (offset < len) {
150 res = s->chr_write(s, buf + offset, len - offset);
151 if (res == -1 && errno == EAGAIN) {
154 } while (res == -1 && errno == EAGAIN);
170 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
174 return s->chr_ioctl(s, cmd, arg);
177 int qemu_chr_be_can_write(CharDriverState *s)
179 if (!s->chr_can_read)
181 return s->chr_can_read(s->handler_opaque);
184 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
187 s->chr_read(s->handler_opaque, buf, len);
191 int qemu_chr_fe_get_msgfd(CharDriverState *s)
193 return s->get_msgfd ? s->get_msgfd(s) : -1;
196 int qemu_chr_add_client(CharDriverState *s, int fd)
198 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
201 void qemu_chr_accept_input(CharDriverState *s)
203 if (s->chr_accept_input)
204 s->chr_accept_input(s);
208 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
210 char buf[READ_BUF_LEN];
213 vsnprintf(buf, sizeof(buf), fmt, ap);
214 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
218 void qemu_chr_add_handlers(CharDriverState *s,
219 IOCanReadHandler *fd_can_read,
220 IOReadHandler *fd_read,
221 IOEventHandler *fd_event,
224 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
225 /* chr driver being released. */
226 ++s->avail_connections;
228 s->chr_can_read = fd_can_read;
229 s->chr_read = fd_read;
230 s->chr_event = fd_event;
231 s->handler_opaque = opaque;
232 if (s->chr_update_read_handler)
233 s->chr_update_read_handler(s);
235 /* We're connecting to an already opened device, so let's make sure we
236 also get the open event */
238 qemu_chr_generic_open(s);
242 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
247 static CharDriverState *qemu_chr_open_null(void)
249 CharDriverState *chr;
251 chr = g_malloc0(sizeof(CharDriverState));
252 chr->chr_write = null_chr_write;
256 /* MUX driver for serial I/O splitting */
258 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
259 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
261 IOCanReadHandler *chr_can_read[MAX_MUX];
262 IOReadHandler *chr_read[MAX_MUX];
263 IOEventHandler *chr_event[MAX_MUX];
264 void *ext_opaque[MAX_MUX];
265 CharDriverState *drv;
270 /* Intermediate input buffer allows to catch escape sequences even if the
271 currently active device is not accepting any input - but only until it
273 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
278 int64_t timestamps_start;
282 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
284 MuxDriver *d = chr->opaque;
286 if (!d->timestamps) {
287 ret = d->drv->chr_write(d->drv, buf, len);
292 for (i = 0; i < len; i++) {
298 ti = qemu_get_clock_ms(rt_clock);
299 if (d->timestamps_start == -1)
300 d->timestamps_start = ti;
301 ti -= d->timestamps_start;
303 snprintf(buf1, sizeof(buf1),
304 "[%02d:%02d:%02d.%03d] ",
309 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
312 ret += d->drv->chr_write(d->drv, buf+i, 1);
313 if (buf[i] == '\n') {
321 static const char * const mux_help[] = {
322 "% h print this help\n\r",
323 "% x exit emulator\n\r",
324 "% s save disk data back to file (if -snapshot)\n\r",
325 "% t toggle console timestamps\n\r"
326 "% b send break (magic sysrq)\n\r",
327 "% c switch between console and monitor\n\r",
332 int term_escape_char = 0x01; /* ctrl-a is used for escape */
333 static void mux_print_help(CharDriverState *chr)
336 char ebuf[15] = "Escape-Char";
337 char cbuf[50] = "\n\r";
339 if (term_escape_char > 0 && term_escape_char < 26) {
340 snprintf(cbuf, sizeof(cbuf), "\n\r");
341 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
343 snprintf(cbuf, sizeof(cbuf),
344 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
347 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
348 for (i = 0; mux_help[i] != NULL; i++) {
349 for (j=0; mux_help[i][j] != '\0'; j++) {
350 if (mux_help[i][j] == '%')
351 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
353 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
358 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
360 if (d->chr_event[mux_nr])
361 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
364 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
366 if (d->term_got_escape) {
367 d->term_got_escape = 0;
368 if (ch == term_escape_char)
377 const char *term = "QEMU: Terminated\n\r";
378 chr->chr_write(chr,(uint8_t *)term,strlen(term));
386 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
389 /* Switch to the next registered device */
390 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
392 if (d->focus >= d->mux_cnt)
394 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
397 d->timestamps = !d->timestamps;
398 d->timestamps_start = -1;
402 } else if (ch == term_escape_char) {
403 d->term_got_escape = 1;
411 static void mux_chr_accept_input(CharDriverState *chr)
413 MuxDriver *d = chr->opaque;
416 while (d->prod[m] != d->cons[m] &&
417 d->chr_can_read[m] &&
418 d->chr_can_read[m](d->ext_opaque[m])) {
419 d->chr_read[m](d->ext_opaque[m],
420 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
424 static int mux_chr_can_read(void *opaque)
426 CharDriverState *chr = opaque;
427 MuxDriver *d = chr->opaque;
430 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
432 if (d->chr_can_read[m])
433 return d->chr_can_read[m](d->ext_opaque[m]);
437 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
439 CharDriverState *chr = opaque;
440 MuxDriver *d = chr->opaque;
444 mux_chr_accept_input (opaque);
446 for(i = 0; i < size; i++)
447 if (mux_proc_byte(chr, d, buf[i])) {
448 if (d->prod[m] == d->cons[m] &&
449 d->chr_can_read[m] &&
450 d->chr_can_read[m](d->ext_opaque[m]))
451 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
453 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
457 static void mux_chr_event(void *opaque, int event)
459 CharDriverState *chr = opaque;
460 MuxDriver *d = chr->opaque;
463 /* Send the event to all registered listeners */
464 for (i = 0; i < d->mux_cnt; i++)
465 mux_chr_send_event(d, i, event);
468 static void mux_chr_update_read_handler(CharDriverState *chr)
470 MuxDriver *d = chr->opaque;
472 if (d->mux_cnt >= MAX_MUX) {
473 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
476 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
477 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
478 d->chr_read[d->mux_cnt] = chr->chr_read;
479 d->chr_event[d->mux_cnt] = chr->chr_event;
480 /* Fix up the real driver with mux routines */
481 if (d->mux_cnt == 0) {
482 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
485 if (d->focus != -1) {
486 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
488 d->focus = d->mux_cnt;
490 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
493 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
495 CharDriverState *chr;
498 chr = g_malloc0(sizeof(CharDriverState));
499 d = g_malloc0(sizeof(MuxDriver));
504 chr->chr_write = mux_chr_write;
505 chr->chr_update_read_handler = mux_chr_update_read_handler;
506 chr->chr_accept_input = mux_chr_accept_input;
507 /* Frontend guest-open / -close notification is not support with muxes */
508 chr->chr_guest_open = NULL;
509 chr->chr_guest_close = NULL;
511 /* Muxes are always open on creation */
512 qemu_chr_generic_open(chr);
519 int send_all(int fd, const void *buf, int len1)
525 ret = send(fd, buf, len, 0);
527 errno = WSAGetLastError();
528 if (errno != WSAEWOULDBLOCK) {
531 } else if (ret == 0) {
543 int send_all(int fd, const void *_buf, int len1)
546 const uint8_t *buf = _buf;
550 ret = write(fd, buf, len);
552 if (errno != EINTR && errno != EAGAIN)
554 } else if (ret == 0) {
564 int recv_all(int fd, void *_buf, int len1, bool single_read)
570 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
572 if (errno != EINTR && errno != EAGAIN) {
589 typedef struct IOWatchPoll
594 IOCanReadHandler *fd_can_read;
597 QTAILQ_ENTRY(IOWatchPoll) node;
600 static QTAILQ_HEAD(, IOWatchPoll) io_watch_poll_list =
601 QTAILQ_HEAD_INITIALIZER(io_watch_poll_list);
603 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
607 QTAILQ_FOREACH(i, &io_watch_poll_list, node) {
608 if (i->src == source) {
616 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
618 IOWatchPoll *iwp = io_watch_poll_from_source(source);
620 iwp->max_size = iwp->fd_can_read(iwp->opaque);
621 if (iwp->max_size == 0) {
625 return g_io_watch_funcs.prepare(source, timeout_);
628 static gboolean io_watch_poll_check(GSource *source)
630 IOWatchPoll *iwp = io_watch_poll_from_source(source);
632 if (iwp->max_size == 0) {
636 return g_io_watch_funcs.check(source);
639 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
642 return g_io_watch_funcs.dispatch(source, callback, user_data);
645 static void io_watch_poll_finalize(GSource *source)
647 IOWatchPoll *iwp = io_watch_poll_from_source(source);
648 QTAILQ_REMOVE(&io_watch_poll_list, iwp, node);
649 g_io_watch_funcs.finalize(source);
652 static GSourceFuncs io_watch_poll_funcs = {
653 .prepare = io_watch_poll_prepare,
654 .check = io_watch_poll_check,
655 .dispatch = io_watch_poll_dispatch,
656 .finalize = io_watch_poll_finalize,
659 /* Can only be used for read */
660 static guint io_add_watch_poll(GIOChannel *channel,
661 IOCanReadHandler *fd_can_read,
669 src = g_io_create_watch(channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
670 g_source_set_funcs(src, &io_watch_poll_funcs);
671 g_source_set_callback(src, (GSourceFunc)fd_read, user_data, NULL);
672 tag = g_source_attach(src, NULL);
675 iwp = g_malloc0(sizeof(*iwp));
678 iwp->fd_can_read = fd_can_read;
679 iwp->opaque = user_data;
681 QTAILQ_INSERT_HEAD(&io_watch_poll_list, iwp, node);
687 static GIOChannel *io_channel_from_fd(int fd)
695 chan = g_io_channel_unix_new(fd);
697 g_io_channel_set_encoding(chan, NULL, NULL);
698 g_io_channel_set_buffered(chan, FALSE);
704 static GIOChannel *io_channel_from_socket(int fd)
713 chan = g_io_channel_win32_new_socket(fd);
715 chan = g_io_channel_unix_new(fd);
718 g_io_channel_set_encoding(chan, NULL, NULL);
719 g_io_channel_set_buffered(chan, FALSE);
724 static int io_channel_send_all(GIOChannel *fd, const void *_buf, int len1)
729 const uint8_t *buf = _buf;
733 status = g_io_channel_write_chars(fd, (const gchar *)buf, len,
734 &bytes_written, NULL);
735 if (status != G_IO_STATUS_NORMAL) {
736 if (status == G_IO_STATUS_AGAIN) {
743 } else if (status == G_IO_STATUS_EOF) {
746 buf += bytes_written;
747 len -= bytes_written;
755 typedef struct FDCharDriver {
756 CharDriverState *chr;
757 GIOChannel *fd_in, *fd_out;
760 QTAILQ_ENTRY(FDCharDriver) node;
763 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
765 FDCharDriver *s = chr->opaque;
767 return io_channel_send_all(s->fd_out, buf, len);
770 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
772 CharDriverState *chr = opaque;
773 FDCharDriver *s = chr->opaque;
775 uint8_t buf[READ_BUF_LEN];
780 if (len > s->max_size) {
787 status = g_io_channel_read_chars(chan, (gchar *)buf,
788 len, &bytes_read, NULL);
789 if (status == G_IO_STATUS_EOF) {
790 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
793 if (status == G_IO_STATUS_NORMAL) {
794 qemu_chr_be_write(chr, buf, bytes_read);
800 static int fd_chr_read_poll(void *opaque)
802 CharDriverState *chr = opaque;
803 FDCharDriver *s = chr->opaque;
805 s->max_size = qemu_chr_be_can_write(chr);
809 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
811 FDCharDriver *s = chr->opaque;
812 return g_io_create_watch(s->fd_out, cond);
815 static void fd_chr_update_read_handler(CharDriverState *chr)
817 FDCharDriver *s = chr->opaque;
820 g_source_remove(s->fd_in_tag);
824 s->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll, fd_chr_read, chr);
828 static void fd_chr_close(struct CharDriverState *chr)
830 FDCharDriver *s = chr->opaque;
833 g_source_remove(s->fd_in_tag);
838 g_io_channel_unref(s->fd_in);
841 g_io_channel_unref(s->fd_out);
845 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
848 /* open a character device to a unix fd */
849 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
851 CharDriverState *chr;
854 chr = g_malloc0(sizeof(CharDriverState));
855 s = g_malloc0(sizeof(FDCharDriver));
856 s->fd_in = io_channel_from_fd(fd_in);
857 s->fd_out = io_channel_from_fd(fd_out);
858 fcntl(fd_out, F_SETFL, O_NONBLOCK);
861 chr->chr_add_watch = fd_chr_add_watch;
862 chr->chr_write = fd_chr_write;
863 chr->chr_update_read_handler = fd_chr_update_read_handler;
864 chr->chr_close = fd_chr_close;
866 qemu_chr_generic_open(chr);
871 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
874 char filename_in[256], filename_out[256];
875 const char *filename = opts->device;
877 if (filename == NULL) {
878 fprintf(stderr, "chardev: pipe: no filename given\n");
882 snprintf(filename_in, 256, "%s.in", filename);
883 snprintf(filename_out, 256, "%s.out", filename);
884 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
885 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
886 if (fd_in < 0 || fd_out < 0) {
891 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
896 return qemu_chr_open_fd(fd_in, fd_out);
899 /* init terminal so that we can grab keys */
900 static struct termios oldtty;
901 static int old_fd0_flags;
902 static bool stdio_allow_signal;
904 static void term_exit(void)
906 tcsetattr (0, TCSANOW, &oldtty);
907 fcntl(0, F_SETFL, old_fd0_flags);
910 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
916 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
917 |INLCR|IGNCR|ICRNL|IXON);
918 tty.c_oflag |= OPOST;
919 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
920 tty.c_cflag &= ~(CSIZE|PARENB);
925 /* if graphical mode, we allow Ctrl-C handling */
926 if (!stdio_allow_signal)
927 tty.c_lflag &= ~ISIG;
929 tcsetattr (0, TCSANOW, &tty);
932 static void qemu_chr_close_stdio(struct CharDriverState *chr)
938 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
940 CharDriverState *chr;
942 if (is_daemonized()) {
943 error_report("cannot use stdio with -daemonize");
946 old_fd0_flags = fcntl(0, F_GETFL);
947 tcgetattr (0, &oldtty);
948 fcntl(0, F_SETFL, O_NONBLOCK);
951 chr = qemu_chr_open_fd(0, 1);
952 chr->chr_close = qemu_chr_close_stdio;
953 chr->chr_set_echo = qemu_chr_set_echo_stdio;
954 stdio_allow_signal = display_type != DT_NOGRAPHIC;
955 if (opts->has_signal) {
956 stdio_allow_signal = opts->signal;
958 qemu_chr_fe_set_echo(chr, false);
964 /* Once Solaris has openpty(), this is going to be removed. */
965 static int openpty(int *amaster, int *aslave, char *name,
966 struct termios *termp, struct winsize *winp)
969 int mfd = -1, sfd = -1;
971 *amaster = *aslave = -1;
973 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
977 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
980 if ((slave = ptsname(mfd)) == NULL)
983 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
986 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
987 (termp != NULL && tcgetattr(sfd, termp) < 0))
995 ioctl(sfd, TIOCSWINSZ, winp);
1006 static void cfmakeraw (struct termios *termios_p)
1008 termios_p->c_iflag &=
1009 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
1010 termios_p->c_oflag &= ~OPOST;
1011 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
1012 termios_p->c_cflag &= ~(CSIZE|PARENB);
1013 termios_p->c_cflag |= CS8;
1015 termios_p->c_cc[VMIN] = 0;
1016 termios_p->c_cc[VTIME] = 0;
1020 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1021 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1022 || defined(__GLIBC__)
1024 #define HAVE_CHARDEV_TTY 1
1035 static void pty_chr_update_read_handler(CharDriverState *chr);
1036 static void pty_chr_state(CharDriverState *chr, int connected);
1038 static gboolean pty_chr_timer(gpointer opaque)
1040 struct CharDriverState *chr = opaque;
1041 PtyCharDriver *s = chr->opaque;
1047 /* If we arrive here without polling being cleared due
1048 * read returning -EIO, then we are (re-)connected */
1049 pty_chr_state(chr, 1);
1054 pty_chr_update_read_handler(chr);
1060 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1062 PtyCharDriver *s = chr->opaque;
1065 g_source_remove(s->timer_tag);
1070 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1072 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1076 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1078 PtyCharDriver *s = chr->opaque;
1080 if (!s->connected) {
1081 /* guest sends data, check for (re-)connect */
1082 pty_chr_update_read_handler(chr);
1085 return io_channel_send_all(s->fd, buf, len);
1088 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1090 PtyCharDriver *s = chr->opaque;
1091 return g_io_create_watch(s->fd, cond);
1094 static int pty_chr_read_poll(void *opaque)
1096 CharDriverState *chr = opaque;
1097 PtyCharDriver *s = chr->opaque;
1099 s->read_bytes = qemu_chr_be_can_write(chr);
1100 return s->read_bytes;
1103 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1105 CharDriverState *chr = opaque;
1106 PtyCharDriver *s = chr->opaque;
1108 uint8_t buf[READ_BUF_LEN];
1112 if (len > s->read_bytes)
1113 len = s->read_bytes;
1116 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1117 if (status != G_IO_STATUS_NORMAL) {
1118 pty_chr_state(chr, 0);
1121 pty_chr_state(chr, 1);
1122 qemu_chr_be_write(chr, buf, size);
1127 static void pty_chr_update_read_handler(CharDriverState *chr)
1129 PtyCharDriver *s = chr->opaque;
1132 g_source_remove(s->fd_tag);
1135 s->fd_tag = io_add_watch_poll(s->fd, pty_chr_read_poll, pty_chr_read, chr);
1138 * Short timeout here: just need wait long enougth that qemu makes
1139 * it through the poll loop once. When reconnected we want a
1140 * short timeout so we notice it almost instantly. Otherwise
1141 * read() gives us -EIO instantly, making pty_chr_state() reset the
1142 * timeout to the normal (much longer) poll interval before the
1145 pty_chr_rearm_timer(chr, 10);
1148 static void pty_chr_state(CharDriverState *chr, int connected)
1150 PtyCharDriver *s = chr->opaque;
1153 g_source_remove(s->fd_tag);
1157 /* (re-)connect poll interval for idle guests: once per second.
1158 * We check more frequently in case the guests sends data to
1159 * the virtual device linked to our pty. */
1160 pty_chr_rearm_timer(chr, 1000);
1163 qemu_chr_generic_open(chr);
1169 static void pty_chr_close(struct CharDriverState *chr)
1171 PtyCharDriver *s = chr->opaque;
1175 g_source_remove(s->fd_tag);
1177 fd = g_io_channel_unix_get_fd(s->fd);
1178 g_io_channel_unref(s->fd);
1181 g_source_remove(s->timer_tag);
1184 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1187 static CharDriverState *qemu_chr_open_pty(const char *id,
1190 CharDriverState *chr;
1193 int master_fd, slave_fd;
1194 #if defined(__OpenBSD__) || defined(__DragonFly__)
1195 char pty_name[PATH_MAX];
1196 #define q_ptsname(x) pty_name
1198 char *pty_name = NULL;
1199 #define q_ptsname(x) ptsname(x)
1202 if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1206 /* Set raw attributes on the pty. */
1207 tcgetattr(slave_fd, &tty);
1209 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1212 chr = g_malloc0(sizeof(CharDriverState));
1214 chr->filename = g_strdup_printf("pty:%s", q_ptsname(master_fd));
1215 ret->pty = g_strdup(q_ptsname(master_fd));
1216 ret->has_pty = true;
1218 fprintf(stderr, "char device redirected to %s (label %s)\n",
1219 q_ptsname(master_fd), id);
1221 s = g_malloc0(sizeof(PtyCharDriver));
1223 chr->chr_write = pty_chr_write;
1224 chr->chr_update_read_handler = pty_chr_update_read_handler;
1225 chr->chr_close = pty_chr_close;
1226 chr->chr_add_watch = pty_chr_add_watch;
1228 s->fd = io_channel_from_fd(master_fd);
1234 static void tty_serial_init(int fd, int speed,
1235 int parity, int data_bits, int stop_bits)
1241 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1242 speed, parity, data_bits, stop_bits);
1244 tcgetattr (fd, &tty);
1246 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1247 speed = speed * 10 / 11;
1264 /* Non-Posix values follow. They may be unsupported on some systems. */
1266 check_speed(115200);
1268 check_speed(230400);
1271 check_speed(460800);
1274 check_speed(500000);
1277 check_speed(576000);
1280 check_speed(921600);
1283 check_speed(1000000);
1286 check_speed(1152000);
1289 check_speed(1500000);
1292 check_speed(2000000);
1295 check_speed(2500000);
1298 check_speed(3000000);
1301 check_speed(3500000);
1304 check_speed(4000000);
1309 cfsetispeed(&tty, spd);
1310 cfsetospeed(&tty, spd);
1312 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1313 |INLCR|IGNCR|ICRNL|IXON);
1314 tty.c_oflag |= OPOST;
1315 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1316 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1337 tty.c_cflag |= PARENB;
1340 tty.c_cflag |= PARENB | PARODD;
1344 tty.c_cflag |= CSTOPB;
1346 tcsetattr (fd, TCSANOW, &tty);
1349 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1351 FDCharDriver *s = chr->opaque;
1354 case CHR_IOCTL_SERIAL_SET_PARAMS:
1356 QEMUSerialSetParams *ssp = arg;
1357 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1358 ssp->speed, ssp->parity,
1359 ssp->data_bits, ssp->stop_bits);
1362 case CHR_IOCTL_SERIAL_SET_BREAK:
1364 int enable = *(int *)arg;
1366 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1370 case CHR_IOCTL_SERIAL_GET_TIOCM:
1373 int *targ = (int *)arg;
1374 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1376 if (sarg & TIOCM_CTS)
1377 *targ |= CHR_TIOCM_CTS;
1378 if (sarg & TIOCM_CAR)
1379 *targ |= CHR_TIOCM_CAR;
1380 if (sarg & TIOCM_DSR)
1381 *targ |= CHR_TIOCM_DSR;
1382 if (sarg & TIOCM_RI)
1383 *targ |= CHR_TIOCM_RI;
1384 if (sarg & TIOCM_DTR)
1385 *targ |= CHR_TIOCM_DTR;
1386 if (sarg & TIOCM_RTS)
1387 *targ |= CHR_TIOCM_RTS;
1390 case CHR_IOCTL_SERIAL_SET_TIOCM:
1392 int sarg = *(int *)arg;
1394 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1395 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1396 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1397 if (sarg & CHR_TIOCM_CTS)
1399 if (sarg & CHR_TIOCM_CAR)
1401 if (sarg & CHR_TIOCM_DSR)
1403 if (sarg & CHR_TIOCM_RI)
1405 if (sarg & CHR_TIOCM_DTR)
1407 if (sarg & CHR_TIOCM_RTS)
1409 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1418 static void qemu_chr_close_tty(CharDriverState *chr)
1420 FDCharDriver *s = chr->opaque;
1424 fd = g_io_channel_unix_get_fd(s->fd_in);
1434 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1436 CharDriverState *chr;
1438 tty_serial_init(fd, 115200, 'N', 8, 1);
1439 chr = qemu_chr_open_fd(fd, fd);
1440 chr->chr_ioctl = tty_serial_ioctl;
1441 chr->chr_close = qemu_chr_close_tty;
1444 #endif /* __linux__ || __sun__ */
1446 #if defined(__linux__)
1448 #define HAVE_CHARDEV_PARPORT 1
1453 } ParallelCharDriver;
1455 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1457 if (s->mode != mode) {
1459 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1466 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1468 ParallelCharDriver *drv = chr->opaque;
1473 case CHR_IOCTL_PP_READ_DATA:
1474 if (ioctl(fd, PPRDATA, &b) < 0)
1476 *(uint8_t *)arg = b;
1478 case CHR_IOCTL_PP_WRITE_DATA:
1479 b = *(uint8_t *)arg;
1480 if (ioctl(fd, PPWDATA, &b) < 0)
1483 case CHR_IOCTL_PP_READ_CONTROL:
1484 if (ioctl(fd, PPRCONTROL, &b) < 0)
1486 /* Linux gives only the lowest bits, and no way to know data
1487 direction! For better compatibility set the fixed upper
1489 *(uint8_t *)arg = b | 0xc0;
1491 case CHR_IOCTL_PP_WRITE_CONTROL:
1492 b = *(uint8_t *)arg;
1493 if (ioctl(fd, PPWCONTROL, &b) < 0)
1496 case CHR_IOCTL_PP_READ_STATUS:
1497 if (ioctl(fd, PPRSTATUS, &b) < 0)
1499 *(uint8_t *)arg = b;
1501 case CHR_IOCTL_PP_DATA_DIR:
1502 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1505 case CHR_IOCTL_PP_EPP_READ_ADDR:
1506 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1507 struct ParallelIOArg *parg = arg;
1508 int n = read(fd, parg->buffer, parg->count);
1509 if (n != parg->count) {
1514 case CHR_IOCTL_PP_EPP_READ:
1515 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1516 struct ParallelIOArg *parg = arg;
1517 int n = read(fd, parg->buffer, parg->count);
1518 if (n != parg->count) {
1523 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1524 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1525 struct ParallelIOArg *parg = arg;
1526 int n = write(fd, parg->buffer, parg->count);
1527 if (n != parg->count) {
1532 case CHR_IOCTL_PP_EPP_WRITE:
1533 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1534 struct ParallelIOArg *parg = arg;
1535 int n = write(fd, parg->buffer, parg->count);
1536 if (n != parg->count) {
1547 static void pp_close(CharDriverState *chr)
1549 ParallelCharDriver *drv = chr->opaque;
1552 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1553 ioctl(fd, PPRELEASE);
1556 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1559 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1561 CharDriverState *chr;
1562 ParallelCharDriver *drv;
1564 if (ioctl(fd, PPCLAIM) < 0) {
1569 drv = g_malloc0(sizeof(ParallelCharDriver));
1571 drv->mode = IEEE1284_MODE_COMPAT;
1573 chr = g_malloc0(sizeof(CharDriverState));
1574 chr->chr_write = null_chr_write;
1575 chr->chr_ioctl = pp_ioctl;
1576 chr->chr_close = pp_close;
1579 qemu_chr_generic_open(chr);
1583 #endif /* __linux__ */
1585 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1587 #define HAVE_CHARDEV_PARPORT 1
1589 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1591 int fd = (int)(intptr_t)chr->opaque;
1595 case CHR_IOCTL_PP_READ_DATA:
1596 if (ioctl(fd, PPIGDATA, &b) < 0)
1598 *(uint8_t *)arg = b;
1600 case CHR_IOCTL_PP_WRITE_DATA:
1601 b = *(uint8_t *)arg;
1602 if (ioctl(fd, PPISDATA, &b) < 0)
1605 case CHR_IOCTL_PP_READ_CONTROL:
1606 if (ioctl(fd, PPIGCTRL, &b) < 0)
1608 *(uint8_t *)arg = b;
1610 case CHR_IOCTL_PP_WRITE_CONTROL:
1611 b = *(uint8_t *)arg;
1612 if (ioctl(fd, PPISCTRL, &b) < 0)
1615 case CHR_IOCTL_PP_READ_STATUS:
1616 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1618 *(uint8_t *)arg = b;
1626 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1628 CharDriverState *chr;
1630 chr = g_malloc0(sizeof(CharDriverState));
1631 chr->opaque = (void *)(intptr_t)fd;
1632 chr->chr_write = null_chr_write;
1633 chr->chr_ioctl = pp_ioctl;
1642 HANDLE hcom, hrecv, hsend;
1643 OVERLAPPED orecv, osend;
1650 HANDLE hInputReadyEvent;
1651 HANDLE hInputDoneEvent;
1652 HANDLE hInputThread;
1653 uint8_t win_stdio_buf;
1654 } WinStdioCharState;
1656 #define NSENDBUF 2048
1657 #define NRECVBUF 2048
1658 #define MAXCONNECT 1
1659 #define NTIMEOUT 5000
1661 static int win_chr_poll(void *opaque);
1662 static int win_chr_pipe_poll(void *opaque);
1664 static void win_chr_close(CharDriverState *chr)
1666 WinCharState *s = chr->opaque;
1669 CloseHandle(s->hsend);
1673 CloseHandle(s->hrecv);
1677 CloseHandle(s->hcom);
1681 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1683 qemu_del_polling_cb(win_chr_poll, chr);
1685 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1688 static int win_chr_init(CharDriverState *chr, const char *filename)
1690 WinCharState *s = chr->opaque;
1692 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1697 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1699 fprintf(stderr, "Failed CreateEvent\n");
1702 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1704 fprintf(stderr, "Failed CreateEvent\n");
1708 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1709 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1710 if (s->hcom == INVALID_HANDLE_VALUE) {
1711 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1716 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1717 fprintf(stderr, "Failed SetupComm\n");
1721 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1722 size = sizeof(COMMCONFIG);
1723 GetDefaultCommConfig(filename, &comcfg, &size);
1724 comcfg.dcb.DCBlength = sizeof(DCB);
1725 CommConfigDialog(filename, NULL, &comcfg);
1727 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1728 fprintf(stderr, "Failed SetCommState\n");
1732 if (!SetCommMask(s->hcom, EV_ERR)) {
1733 fprintf(stderr, "Failed SetCommMask\n");
1737 cto.ReadIntervalTimeout = MAXDWORD;
1738 if (!SetCommTimeouts(s->hcom, &cto)) {
1739 fprintf(stderr, "Failed SetCommTimeouts\n");
1743 if (!ClearCommError(s->hcom, &err, &comstat)) {
1744 fprintf(stderr, "Failed ClearCommError\n");
1747 qemu_add_polling_cb(win_chr_poll, chr);
1755 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1757 WinCharState *s = chr->opaque;
1758 DWORD len, ret, size, err;
1761 ZeroMemory(&s->osend, sizeof(s->osend));
1762 s->osend.hEvent = s->hsend;
1765 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1767 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1769 err = GetLastError();
1770 if (err == ERROR_IO_PENDING) {
1771 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1789 static int win_chr_read_poll(CharDriverState *chr)
1791 WinCharState *s = chr->opaque;
1793 s->max_size = qemu_chr_be_can_write(chr);
1797 static void win_chr_readfile(CharDriverState *chr)
1799 WinCharState *s = chr->opaque;
1801 uint8_t buf[READ_BUF_LEN];
1804 ZeroMemory(&s->orecv, sizeof(s->orecv));
1805 s->orecv.hEvent = s->hrecv;
1806 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1808 err = GetLastError();
1809 if (err == ERROR_IO_PENDING) {
1810 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1815 qemu_chr_be_write(chr, buf, size);
1819 static void win_chr_read(CharDriverState *chr)
1821 WinCharState *s = chr->opaque;
1823 if (s->len > s->max_size)
1824 s->len = s->max_size;
1828 win_chr_readfile(chr);
1831 static int win_chr_poll(void *opaque)
1833 CharDriverState *chr = opaque;
1834 WinCharState *s = chr->opaque;
1838 ClearCommError(s->hcom, &comerr, &status);
1839 if (status.cbInQue > 0) {
1840 s->len = status.cbInQue;
1841 win_chr_read_poll(chr);
1848 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1850 CharDriverState *chr;
1853 chr = g_malloc0(sizeof(CharDriverState));
1854 s = g_malloc0(sizeof(WinCharState));
1856 chr->chr_write = win_chr_write;
1857 chr->chr_close = win_chr_close;
1859 if (win_chr_init(chr, filename) < 0) {
1864 qemu_chr_generic_open(chr);
1868 static int win_chr_pipe_poll(void *opaque)
1870 CharDriverState *chr = opaque;
1871 WinCharState *s = chr->opaque;
1874 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1877 win_chr_read_poll(chr);
1884 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1886 WinCharState *s = chr->opaque;
1894 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1896 fprintf(stderr, "Failed CreateEvent\n");
1899 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1901 fprintf(stderr, "Failed CreateEvent\n");
1905 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1906 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1907 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1909 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1910 if (s->hcom == INVALID_HANDLE_VALUE) {
1911 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1916 ZeroMemory(&ov, sizeof(ov));
1917 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1918 ret = ConnectNamedPipe(s->hcom, &ov);
1920 fprintf(stderr, "Failed ConnectNamedPipe\n");
1924 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1926 fprintf(stderr, "Failed GetOverlappedResult\n");
1928 CloseHandle(ov.hEvent);
1935 CloseHandle(ov.hEvent);
1938 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1947 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
1949 const char *filename = opts->device;
1950 CharDriverState *chr;
1953 chr = g_malloc0(sizeof(CharDriverState));
1954 s = g_malloc0(sizeof(WinCharState));
1956 chr->chr_write = win_chr_write;
1957 chr->chr_close = win_chr_close;
1959 if (win_chr_pipe_init(chr, filename) < 0) {
1964 qemu_chr_generic_open(chr);
1968 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1970 CharDriverState *chr;
1973 chr = g_malloc0(sizeof(CharDriverState));
1974 s = g_malloc0(sizeof(WinCharState));
1977 chr->chr_write = win_chr_write;
1978 qemu_chr_generic_open(chr);
1982 static CharDriverState *qemu_chr_open_win_con(void)
1984 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1987 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1989 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1996 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2006 static void win_stdio_wait_func(void *opaque)
2008 CharDriverState *chr = opaque;
2009 WinStdioCharState *stdio = chr->opaque;
2010 INPUT_RECORD buf[4];
2015 ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
2019 /* Avoid error storm */
2020 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2024 for (i = 0; i < dwSize; i++) {
2025 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2027 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2029 if (kev->uChar.AsciiChar != 0) {
2030 for (j = 0; j < kev->wRepeatCount; j++) {
2031 if (qemu_chr_be_can_write(chr)) {
2032 uint8_t c = kev->uChar.AsciiChar;
2033 qemu_chr_be_write(chr, &c, 1);
2041 static DWORD WINAPI win_stdio_thread(LPVOID param)
2043 CharDriverState *chr = param;
2044 WinStdioCharState *stdio = chr->opaque;
2050 /* Wait for one byte */
2051 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2053 /* Exit in case of error, continue if nothing read */
2061 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2062 if (stdio->win_stdio_buf == '\r') {
2066 /* Signal the main thread and wait until the byte was eaten */
2067 if (!SetEvent(stdio->hInputReadyEvent)) {
2070 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2076 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2080 static void win_stdio_thread_wait_func(void *opaque)
2082 CharDriverState *chr = opaque;
2083 WinStdioCharState *stdio = chr->opaque;
2085 if (qemu_chr_be_can_write(chr)) {
2086 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2089 SetEvent(stdio->hInputDoneEvent);
2092 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2094 WinStdioCharState *stdio = chr->opaque;
2097 GetConsoleMode(stdio->hStdIn, &dwMode);
2100 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2102 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2106 static void win_stdio_close(CharDriverState *chr)
2108 WinStdioCharState *stdio = chr->opaque;
2110 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2111 CloseHandle(stdio->hInputReadyEvent);
2113 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2114 CloseHandle(stdio->hInputDoneEvent);
2116 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2117 TerminateThread(stdio->hInputThread, 0);
2120 g_free(chr->opaque);
2124 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2126 CharDriverState *chr;
2127 WinStdioCharState *stdio;
2131 chr = g_malloc0(sizeof(CharDriverState));
2132 stdio = g_malloc0(sizeof(WinStdioCharState));
2134 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2135 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2136 fprintf(stderr, "cannot open stdio: invalid handle\n");
2140 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2142 chr->opaque = stdio;
2143 chr->chr_write = win_stdio_write;
2144 chr->chr_close = win_stdio_close;
2147 if (qemu_add_wait_object(stdio->hStdIn,
2148 win_stdio_wait_func, chr)) {
2149 fprintf(stderr, "qemu_add_wait_object: failed\n");
2154 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2155 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2156 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2159 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2160 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2161 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2162 fprintf(stderr, "cannot create stdio thread or event\n");
2165 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2166 win_stdio_thread_wait_func, chr)) {
2167 fprintf(stderr, "qemu_add_wait_object: failed\n");
2171 dwMode |= ENABLE_LINE_INPUT;
2174 /* set the terminal in raw mode */
2175 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2176 dwMode |= ENABLE_PROCESSED_INPUT;
2179 SetConsoleMode(stdio->hStdIn, dwMode);
2181 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2182 qemu_chr_fe_set_echo(chr, false);
2186 #endif /* !_WIN32 */
2189 /***********************************************************/
2190 /* UDP Net console */
2196 uint8_t buf[READ_BUF_LEN];
2202 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2204 NetCharDriver *s = chr->opaque;
2205 gsize bytes_written;
2208 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2209 if (status == G_IO_STATUS_EOF) {
2211 } else if (status != G_IO_STATUS_NORMAL) {
2215 return bytes_written;
2218 static int udp_chr_read_poll(void *opaque)
2220 CharDriverState *chr = opaque;
2221 NetCharDriver *s = chr->opaque;
2223 s->max_size = qemu_chr_be_can_write(chr);
2225 /* If there were any stray characters in the queue process them
2228 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2229 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2231 s->max_size = qemu_chr_be_can_write(chr);
2236 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2238 CharDriverState *chr = opaque;
2239 NetCharDriver *s = chr->opaque;
2240 gsize bytes_read = 0;
2243 if (s->max_size == 0)
2245 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2247 s->bufcnt = bytes_read;
2248 s->bufptr = s->bufcnt;
2249 if (status != G_IO_STATUS_NORMAL) {
2254 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2255 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2257 s->max_size = qemu_chr_be_can_write(chr);
2263 static void udp_chr_update_read_handler(CharDriverState *chr)
2265 NetCharDriver *s = chr->opaque;
2268 g_source_remove(s->tag);
2273 s->tag = io_add_watch_poll(s->chan, udp_chr_read_poll, udp_chr_read, chr);
2277 static void udp_chr_close(CharDriverState *chr)
2279 NetCharDriver *s = chr->opaque;
2281 g_source_remove(s->tag);
2284 g_io_channel_unref(s->chan);
2288 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2291 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2293 CharDriverState *chr = NULL;
2294 NetCharDriver *s = NULL;
2296 chr = g_malloc0(sizeof(CharDriverState));
2297 s = g_malloc0(sizeof(NetCharDriver));
2300 s->chan = io_channel_from_socket(s->fd);
2304 chr->chr_write = udp_chr_write;
2305 chr->chr_update_read_handler = udp_chr_update_read_handler;
2306 chr->chr_close = udp_chr_close;
2310 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2312 Error *local_err = NULL;
2315 fd = inet_dgram_opts(opts, &local_err);
2319 return qemu_chr_open_udp_fd(fd);
2322 /***********************************************************/
2323 /* TCP Net console */
2327 GIOChannel *chan, *listen_chan;
2328 guint tag, listen_tag;
2338 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2340 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2342 TCPCharDriver *s = chr->opaque;
2344 return io_channel_send_all(s->chan, buf, len);
2346 /* XXX: indicate an error ? */
2351 static int tcp_chr_read_poll(void *opaque)
2353 CharDriverState *chr = opaque;
2354 TCPCharDriver *s = chr->opaque;
2357 s->max_size = qemu_chr_be_can_write(chr);
2362 #define IAC_BREAK 243
2363 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2365 uint8_t *buf, int *size)
2367 /* Handle any telnet client's basic IAC options to satisfy char by
2368 * char mode with no echo. All IAC options will be removed from
2369 * the buf and the do_telnetopt variable will be used to track the
2370 * state of the width of the IAC information.
2372 * IAC commands come in sets of 3 bytes with the exception of the
2373 * "IAC BREAK" command and the double IAC.
2379 for (i = 0; i < *size; i++) {
2380 if (s->do_telnetopt > 1) {
2381 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2382 /* Double IAC means send an IAC */
2386 s->do_telnetopt = 1;
2388 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2389 /* Handle IAC break commands by sending a serial break */
2390 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2395 if (s->do_telnetopt >= 4) {
2396 s->do_telnetopt = 1;
2399 if ((unsigned char)buf[i] == IAC) {
2400 s->do_telnetopt = 2;
2411 static int tcp_get_msgfd(CharDriverState *chr)
2413 TCPCharDriver *s = chr->opaque;
2420 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2422 TCPCharDriver *s = chr->opaque;
2423 struct cmsghdr *cmsg;
2425 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2428 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2429 cmsg->cmsg_level != SOL_SOCKET ||
2430 cmsg->cmsg_type != SCM_RIGHTS)
2433 fd = *((int *)CMSG_DATA(cmsg));
2437 #ifndef MSG_CMSG_CLOEXEC
2438 qemu_set_cloexec(fd);
2446 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2448 TCPCharDriver *s = chr->opaque;
2449 struct msghdr msg = { NULL, };
2450 struct iovec iov[1];
2452 struct cmsghdr cmsg;
2453 char control[CMSG_SPACE(sizeof(int))];
2458 iov[0].iov_base = buf;
2459 iov[0].iov_len = len;
2463 msg.msg_control = &msg_control;
2464 msg.msg_controllen = sizeof(msg_control);
2466 #ifdef MSG_CMSG_CLOEXEC
2467 flags |= MSG_CMSG_CLOEXEC;
2469 ret = recvmsg(s->fd, &msg, flags);
2470 if (ret > 0 && s->is_unix) {
2471 unix_process_msgfd(chr, &msg);
2477 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2479 TCPCharDriver *s = chr->opaque;
2480 return qemu_recv(s->fd, buf, len, 0);
2484 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2486 TCPCharDriver *s = chr->opaque;
2487 return g_io_create_watch(s->chan, cond);
2490 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2492 CharDriverState *chr = opaque;
2493 TCPCharDriver *s = chr->opaque;
2494 uint8_t buf[READ_BUF_LEN];
2497 if (!s->connected || s->max_size <= 0) {
2501 if (len > s->max_size)
2503 size = tcp_chr_recv(chr, (void *)buf, len);
2505 /* connection closed */
2507 if (s->listen_chan) {
2508 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2510 g_source_remove(s->tag);
2512 g_io_channel_unref(s->chan);
2516 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2517 } else if (size > 0) {
2518 if (s->do_telnetopt)
2519 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2521 qemu_chr_be_write(chr, buf, size);
2528 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2530 return qemu_chr_open_fd(eventfd, eventfd);
2534 static void tcp_chr_connect(void *opaque)
2536 CharDriverState *chr = opaque;
2537 TCPCharDriver *s = chr->opaque;
2541 s->tag = io_add_watch_poll(s->chan, tcp_chr_read_poll, tcp_chr_read, chr);
2543 qemu_chr_generic_open(chr);
2546 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2547 static void tcp_chr_telnet_init(int fd)
2550 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2551 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2552 send(fd, (char *)buf, 3, 0);
2553 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2554 send(fd, (char *)buf, 3, 0);
2555 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2556 send(fd, (char *)buf, 3, 0);
2557 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2558 send(fd, (char *)buf, 3, 0);
2561 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2563 TCPCharDriver *s = chr->opaque;
2567 socket_set_nonblock(fd);
2569 socket_set_nodelay(fd);
2571 s->chan = io_channel_from_socket(fd);
2572 g_source_remove(s->listen_tag);
2574 tcp_chr_connect(chr);
2579 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2581 CharDriverState *chr = opaque;
2582 TCPCharDriver *s = chr->opaque;
2583 struct sockaddr_in saddr;
2585 struct sockaddr_un uaddr;
2587 struct sockaddr *addr;
2594 len = sizeof(uaddr);
2595 addr = (struct sockaddr *)&uaddr;
2599 len = sizeof(saddr);
2600 addr = (struct sockaddr *)&saddr;
2602 fd = qemu_accept(s->listen_fd, addr, &len);
2603 if (fd < 0 && errno != EINTR) {
2605 } else if (fd >= 0) {
2606 if (s->do_telnetopt)
2607 tcp_chr_telnet_init(fd);
2611 if (tcp_chr_add_client(chr, fd) < 0)
2617 static void tcp_chr_close(CharDriverState *chr)
2619 TCPCharDriver *s = chr->opaque;
2622 g_source_remove(s->tag);
2625 g_io_channel_unref(s->chan);
2629 if (s->listen_fd >= 0) {
2630 if (s->listen_tag) {
2631 g_source_remove(s->listen_tag);
2633 if (s->listen_chan) {
2634 g_io_channel_unref(s->listen_chan);
2636 closesocket(s->listen_fd);
2639 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2642 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2643 bool is_listen, bool is_telnet,
2644 bool is_waitconnect,
2647 CharDriverState *chr = NULL;
2648 TCPCharDriver *s = NULL;
2649 char host[NI_MAXHOST], serv[NI_MAXSERV];
2650 const char *left = "", *right = "";
2651 struct sockaddr_storage ss;
2652 socklen_t ss_len = sizeof(ss);
2654 memset(&ss, 0, ss_len);
2655 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2656 error_setg(errp, "getsockname: %s", strerror(errno));
2660 chr = g_malloc0(sizeof(CharDriverState));
2661 s = g_malloc0(sizeof(TCPCharDriver));
2668 chr->filename = g_malloc(256);
2669 switch (ss.ss_family) {
2673 snprintf(chr->filename, 256, "unix:%s%s",
2674 ((struct sockaddr_un *)(&ss))->sun_path,
2675 is_listen ? ",server" : "");
2683 s->do_nodelay = do_nodelay;
2684 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2685 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2686 snprintf(chr->filename, 256, "%s:%s%s%s:%s%s",
2687 is_telnet ? "telnet" : "tcp",
2688 left, host, right, serv,
2689 is_listen ? ",server" : "");
2694 chr->chr_write = tcp_chr_write;
2695 chr->chr_close = tcp_chr_close;
2696 chr->get_msgfd = tcp_get_msgfd;
2697 chr->chr_add_client = tcp_chr_add_client;
2698 chr->chr_add_watch = tcp_chr_add_watch;
2702 s->listen_chan = io_channel_from_socket(s->listen_fd);
2703 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2705 s->do_telnetopt = 1;
2710 socket_set_nodelay(fd);
2711 s->chan = io_channel_from_socket(s->fd);
2712 tcp_chr_connect(chr);
2715 if (is_listen && is_waitconnect) {
2716 printf("QEMU waiting for connection on: %s\n",
2718 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2719 socket_set_nonblock(s->listen_fd);
2724 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2726 CharDriverState *chr = NULL;
2727 Error *local_err = NULL;
2735 is_listen = qemu_opt_get_bool(opts, "server", 0);
2736 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2737 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2738 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2739 is_unix = qemu_opt_get(opts, "path") != NULL;
2745 fd = unix_listen_opts(opts, &local_err);
2747 fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2751 fd = inet_listen_opts(opts, 0, &local_err);
2753 fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2760 if (!is_waitconnect)
2761 socket_set_nonblock(fd);
2763 chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2764 is_waitconnect, &local_err);
2765 if (error_is_set(&local_err)) {
2773 qerror_report_err(local_err);
2774 error_free(local_err);
2780 g_free(chr->opaque);
2786 /***********************************************************/
2787 /* Memory chardev */
2790 size_t outbuf_capacity;
2794 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2796 MemoryDriver *d = chr->opaque;
2798 /* TODO: the QString implementation has the same code, we should
2799 * introduce a generic way to do this in cutils.c */
2800 if (d->outbuf_capacity < d->outbuf_size + len) {
2802 d->outbuf_capacity += len;
2803 d->outbuf_capacity *= 2;
2804 d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
2807 memcpy(d->outbuf + d->outbuf_size, buf, len);
2808 d->outbuf_size += len;
2813 void qemu_chr_init_mem(CharDriverState *chr)
2817 d = g_malloc(sizeof(*d));
2819 d->outbuf_capacity = 4096;
2820 d->outbuf = g_malloc0(d->outbuf_capacity);
2822 memset(chr, 0, sizeof(*chr));
2824 chr->chr_write = mem_chr_write;
2827 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2829 MemoryDriver *d = chr->opaque;
2830 return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2833 /* NOTE: this driver can not be closed with qemu_chr_delete()! */
2834 void qemu_chr_close_mem(CharDriverState *chr)
2836 MemoryDriver *d = chr->opaque;
2839 g_free(chr->opaque);
2841 chr->chr_write = NULL;
2844 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2846 const MemoryDriver *d = chr->opaque;
2847 return d->outbuf_size;
2850 /*********************************************************/
2851 /* Ring buffer chardev */
2858 } RingBufCharDriver;
2860 static size_t ringbuf_count(const CharDriverState *chr)
2862 const RingBufCharDriver *d = chr->opaque;
2864 return d->prod - d->cons;
2867 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2869 RingBufCharDriver *d = chr->opaque;
2872 if (!buf || (len < 0)) {
2876 for (i = 0; i < len; i++ ) {
2877 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2878 if (d->prod - d->cons > d->size) {
2879 d->cons = d->prod - d->size;
2886 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2888 RingBufCharDriver *d = chr->opaque;
2891 for (i = 0; i < len && d->cons != d->prod; i++) {
2892 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2898 static void ringbuf_chr_close(struct CharDriverState *chr)
2900 RingBufCharDriver *d = chr->opaque;
2907 static CharDriverState *qemu_chr_open_ringbuf(ChardevRingbuf *opts,
2910 CharDriverState *chr;
2911 RingBufCharDriver *d;
2913 chr = g_malloc0(sizeof(CharDriverState));
2914 d = g_malloc(sizeof(*d));
2916 d->size = opts->has_size ? opts->size : 65536;
2918 /* The size must be power of 2 */
2919 if (d->size & (d->size - 1)) {
2920 error_setg(errp, "size of ringbuf chardev must be power of two");
2926 d->cbuf = g_malloc0(d->size);
2929 chr->chr_write = ringbuf_chr_write;
2930 chr->chr_close = ringbuf_chr_close;
2940 static bool chr_is_ringbuf(const CharDriverState *chr)
2942 return chr->chr_write == ringbuf_chr_write;
2945 void qmp_ringbuf_write(const char *device, const char *data,
2946 bool has_format, enum DataFormat format,
2949 CharDriverState *chr;
2950 const uint8_t *write_data;
2954 chr = qemu_chr_find(device);
2956 error_setg(errp, "Device '%s' not found", device);
2960 if (!chr_is_ringbuf(chr)) {
2961 error_setg(errp,"%s is not a ringbuf device", device);
2965 if (has_format && (format == DATA_FORMAT_BASE64)) {
2966 write_data = g_base64_decode(data, &write_count);
2968 write_data = (uint8_t *)data;
2969 write_count = strlen(data);
2972 ret = ringbuf_chr_write(chr, write_data, write_count);
2974 if (write_data != (uint8_t *)data) {
2975 g_free((void *)write_data);
2979 error_setg(errp, "Failed to write to device %s", device);
2984 char *qmp_ringbuf_read(const char *device, int64_t size,
2985 bool has_format, enum DataFormat format,
2988 CharDriverState *chr;
2993 chr = qemu_chr_find(device);
2995 error_setg(errp, "Device '%s' not found", device);
2999 if (!chr_is_ringbuf(chr)) {
3000 error_setg(errp,"%s is not a ringbuf device", device);
3005 error_setg(errp, "size must be greater than zero");
3009 count = ringbuf_count(chr);
3010 size = size > count ? count : size;
3011 read_data = g_malloc(size + 1);
3013 ringbuf_chr_read(chr, read_data, size);
3015 if (has_format && (format == DATA_FORMAT_BASE64)) {
3016 data = g_base64_encode(read_data, size);
3020 * FIXME should read only complete, valid UTF-8 characters up
3021 * to @size bytes. Invalid sequences should be replaced by a
3022 * suitable replacement character. Except when (and only
3023 * when) ring buffer lost characters since last read, initial
3024 * continuation characters should be dropped.
3026 read_data[size] = 0;
3027 data = (char *)read_data;
3033 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3035 char host[65], port[33], width[8], height[8];
3039 Error *local_err = NULL;
3041 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3042 if (error_is_set(&local_err)) {
3043 qerror_report_err(local_err);
3044 error_free(local_err);
3048 if (strstart(filename, "mon:", &p)) {
3050 qemu_opt_set(opts, "mux", "on");
3053 if (strcmp(filename, "null") == 0 ||
3054 strcmp(filename, "pty") == 0 ||
3055 strcmp(filename, "msmouse") == 0 ||
3056 strcmp(filename, "braille") == 0 ||
3057 strcmp(filename, "stdio") == 0) {
3058 qemu_opt_set(opts, "backend", filename);
3061 if (strstart(filename, "vc", &p)) {
3062 qemu_opt_set(opts, "backend", "vc");
3064 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
3066 qemu_opt_set(opts, "width", width);
3067 qemu_opt_set(opts, "height", height);
3068 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
3070 qemu_opt_set(opts, "cols", width);
3071 qemu_opt_set(opts, "rows", height);
3078 if (strcmp(filename, "con:") == 0) {
3079 qemu_opt_set(opts, "backend", "console");
3082 if (strstart(filename, "COM", NULL)) {
3083 qemu_opt_set(opts, "backend", "serial");
3084 qemu_opt_set(opts, "path", filename);
3087 if (strstart(filename, "file:", &p)) {
3088 qemu_opt_set(opts, "backend", "file");
3089 qemu_opt_set(opts, "path", p);
3092 if (strstart(filename, "pipe:", &p)) {
3093 qemu_opt_set(opts, "backend", "pipe");
3094 qemu_opt_set(opts, "path", p);
3097 if (strstart(filename, "tcp:", &p) ||
3098 strstart(filename, "telnet:", &p)) {
3099 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3101 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3104 qemu_opt_set(opts, "backend", "socket");
3105 qemu_opt_set(opts, "host", host);
3106 qemu_opt_set(opts, "port", port);
3107 if (p[pos] == ',') {
3108 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3111 if (strstart(filename, "telnet:", &p))
3112 qemu_opt_set(opts, "telnet", "on");
3115 if (strstart(filename, "udp:", &p)) {
3116 qemu_opt_set(opts, "backend", "udp");
3117 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3119 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3123 qemu_opt_set(opts, "host", host);
3124 qemu_opt_set(opts, "port", port);
3125 if (p[pos] == '@') {
3127 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3129 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3133 qemu_opt_set(opts, "localaddr", host);
3134 qemu_opt_set(opts, "localport", port);
3138 if (strstart(filename, "unix:", &p)) {
3139 qemu_opt_set(opts, "backend", "socket");
3140 if (qemu_opts_do_parse(opts, p, "path") != 0)
3144 if (strstart(filename, "/dev/parport", NULL) ||
3145 strstart(filename, "/dev/ppi", NULL)) {
3146 qemu_opt_set(opts, "backend", "parport");
3147 qemu_opt_set(opts, "path", filename);
3150 if (strstart(filename, "/dev/", NULL)) {
3151 qemu_opt_set(opts, "backend", "tty");
3152 qemu_opt_set(opts, "path", filename);
3157 qemu_opts_del(opts);
3161 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3164 const char *path = qemu_opt_get(opts, "path");
3167 error_setg(errp, "chardev: file: no filename given");
3170 backend->file = g_new0(ChardevFile, 1);
3171 backend->file->out = g_strdup(path);
3174 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3177 backend->stdio = g_new0(ChardevStdio, 1);
3178 backend->stdio->has_signal = true;
3179 backend->stdio->signal =
3180 qemu_opt_get_bool(opts, "signal", display_type != DT_NOGRAPHIC);
3183 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3186 const char *device = qemu_opt_get(opts, "path");
3188 if (device == NULL) {
3189 error_setg(errp, "chardev: serial/tty: no device path given");
3192 backend->serial = g_new0(ChardevHostdev, 1);
3193 backend->serial->device = g_strdup(device);
3196 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3199 const char *device = qemu_opt_get(opts, "path");
3201 if (device == NULL) {
3202 error_setg(errp, "chardev: parallel: no device path given");
3205 backend->parallel = g_new0(ChardevHostdev, 1);
3206 backend->parallel->device = g_strdup(device);
3209 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3212 const char *device = qemu_opt_get(opts, "path");
3214 if (device == NULL) {
3215 error_setg(errp, "chardev: pipe: no device path given");
3218 backend->pipe = g_new0(ChardevHostdev, 1);
3219 backend->pipe->device = g_strdup(device);
3222 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3227 backend->memory = g_new0(ChardevRingbuf, 1);
3229 val = qemu_opt_get_number(opts, "size", 0);
3231 backend->memory->has_size = true;
3232 backend->memory->size = val;
3236 typedef struct CharDriver {
3239 CharDriverState *(*open)(QemuOpts *opts);
3240 /* new, qapi-based */
3242 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3245 static GSList *backends;
3247 void register_char_driver(const char *name, CharDriverState *(*open)(QemuOpts *))
3251 s = g_malloc0(sizeof(*s));
3252 s->name = g_strdup(name);
3255 backends = g_slist_append(backends, s);
3258 void register_char_driver_qapi(const char *name, int kind,
3259 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3263 s = g_malloc0(sizeof(*s));
3264 s->name = g_strdup(name);
3268 backends = g_slist_append(backends, s);
3271 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3272 void (*init)(struct CharDriverState *s),
3276 CharDriverState *chr;
3279 if (qemu_opts_id(opts) == NULL) {
3280 error_setg(errp, "chardev: no id specified");
3284 if (qemu_opt_get(opts, "backend") == NULL) {
3285 error_setg(errp, "chardev: \"%s\" missing backend",
3286 qemu_opts_id(opts));
3289 for (i = backends; i; i = i->next) {
3292 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3297 error_setg(errp, "chardev: backend \"%s\" not found",
3298 qemu_opt_get(opts, "backend"));
3303 /* using new, qapi init */
3304 ChardevBackend *backend = g_new0(ChardevBackend, 1);
3305 ChardevReturn *ret = NULL;
3306 const char *id = qemu_opts_id(opts);
3307 const char *bid = NULL;
3309 if (qemu_opt_get_bool(opts, "mux", 0)) {
3310 bid = g_strdup_printf("%s-base", id);
3314 backend->kind = cd->kind;
3316 cd->parse(opts, backend, errp);
3317 if (error_is_set(errp)) {
3321 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3322 if (error_is_set(errp)) {
3327 qapi_free_ChardevBackend(backend);
3328 qapi_free_ChardevReturn(ret);
3329 backend = g_new0(ChardevBackend, 1);
3330 backend->mux = g_new0(ChardevMux, 1);
3331 backend->kind = CHARDEV_BACKEND_KIND_MUX;
3332 backend->mux->chardev = g_strdup(bid);
3333 ret = qmp_chardev_add(id, backend, errp);
3334 if (error_is_set(errp)) {
3339 chr = qemu_chr_find(id);
3342 qapi_free_ChardevBackend(backend);
3343 qapi_free_ChardevReturn(ret);
3347 chr = cd->open(opts);
3349 error_setg(errp, "chardev: opening backend \"%s\" failed",
3350 qemu_opt_get(opts, "backend"));
3355 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3357 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3359 if (qemu_opt_get_bool(opts, "mux", 0)) {
3360 CharDriverState *base = chr;
3361 int len = strlen(qemu_opts_id(opts)) + 6;
3362 base->label = g_malloc(len);
3363 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3364 chr = qemu_chr_open_mux(base);
3365 chr->filename = base->filename;
3366 chr->avail_connections = MAX_MUX;
3367 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3369 chr->avail_connections = 1;
3371 chr->label = g_strdup(qemu_opts_id(opts));
3376 qemu_opts_del(opts);
3380 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3383 CharDriverState *chr;
3387 if (strstart(filename, "chardev:", &p)) {
3388 return qemu_chr_find(p);
3391 opts = qemu_chr_parse_compat(label, filename);
3395 chr = qemu_chr_new_from_opts(opts, init, &err);
3396 if (error_is_set(&err)) {
3397 fprintf(stderr, "%s\n", error_get_pretty(err));
3400 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3401 monitor_init(chr, MONITOR_USE_READLINE);
3406 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3408 if (chr->chr_set_echo) {
3409 chr->chr_set_echo(chr, echo);
3413 void qemu_chr_fe_open(struct CharDriverState *chr)
3415 if (chr->chr_guest_open) {
3416 chr->chr_guest_open(chr);
3420 void qemu_chr_fe_close(struct CharDriverState *chr)
3422 if (chr->chr_guest_close) {
3423 chr->chr_guest_close(chr);
3427 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3428 GIOFunc func, void *user_data)
3433 if (s->chr_add_watch == NULL) {
3437 src = s->chr_add_watch(s, cond);
3438 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3439 tag = g_source_attach(src, NULL);
3440 g_source_unref(src);
3445 void qemu_chr_delete(CharDriverState *chr)
3447 QTAILQ_REMOVE(&chardevs, chr, next);
3448 if (chr->chr_close) {
3449 chr->chr_close(chr);
3451 g_free(chr->filename);
3454 qemu_opts_del(chr->opts);
3459 ChardevInfoList *qmp_query_chardev(Error **errp)
3461 ChardevInfoList *chr_list = NULL;
3462 CharDriverState *chr;
3464 QTAILQ_FOREACH(chr, &chardevs, next) {
3465 ChardevInfoList *info = g_malloc0(sizeof(*info));
3466 info->value = g_malloc0(sizeof(*info->value));
3467 info->value->label = g_strdup(chr->label);
3468 info->value->filename = g_strdup(chr->filename);
3470 info->next = chr_list;
3477 CharDriverState *qemu_chr_find(const char *name)
3479 CharDriverState *chr;
3481 QTAILQ_FOREACH(chr, &chardevs, next) {
3482 if (strcmp(chr->label, name) != 0)
3489 /* Get a character (serial) device interface. */
3490 CharDriverState *qemu_char_get_next_serial(void)
3492 static int next_serial;
3494 /* FIXME: This function needs to go away: use chardev properties! */
3495 return serial_hds[next_serial++];
3498 QemuOptsList qemu_chardev_opts = {
3500 .implied_opt_name = "backend",
3501 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3505 .type = QEMU_OPT_STRING,
3508 .type = QEMU_OPT_STRING,
3511 .type = QEMU_OPT_STRING,
3514 .type = QEMU_OPT_STRING,
3516 .name = "localaddr",
3517 .type = QEMU_OPT_STRING,
3519 .name = "localport",
3520 .type = QEMU_OPT_STRING,
3523 .type = QEMU_OPT_NUMBER,
3526 .type = QEMU_OPT_BOOL,
3529 .type = QEMU_OPT_BOOL,
3532 .type = QEMU_OPT_BOOL,
3535 .type = QEMU_OPT_BOOL,
3538 .type = QEMU_OPT_BOOL,
3541 .type = QEMU_OPT_BOOL,
3544 .type = QEMU_OPT_NUMBER,
3547 .type = QEMU_OPT_NUMBER,
3550 .type = QEMU_OPT_NUMBER,
3553 .type = QEMU_OPT_NUMBER,
3556 .type = QEMU_OPT_BOOL,
3559 .type = QEMU_OPT_BOOL,
3562 .type = QEMU_OPT_STRING,
3565 .type = QEMU_OPT_NUMBER,
3568 .type = QEMU_OPT_SIZE,
3570 { /* end of list */ }
3576 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3581 error_setg(errp, "input file not supported");
3585 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3586 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3587 if (out == INVALID_HANDLE_VALUE) {
3588 error_setg(errp, "open %s failed", file->out);
3591 return qemu_chr_open_win_file(out);
3594 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3597 return qemu_chr_open_win_path(serial->device);
3600 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3603 error_setg(errp, "character device backend type 'parallel' not supported");
3609 static int qmp_chardev_open_file_source(char *src, int flags,
3614 TFR(fd = qemu_open(src, flags, 0666));
3616 error_setg(errp, "open %s: %s", src, strerror(errno));
3621 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3623 int flags, in = -1, out = -1;
3625 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3626 out = qmp_chardev_open_file_source(file->out, flags, errp);
3627 if (error_is_set(errp)) {
3633 in = qmp_chardev_open_file_source(file->in, flags, errp);
3634 if (error_is_set(errp)) {
3640 return qemu_chr_open_fd(in, out);
3643 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3646 #ifdef HAVE_CHARDEV_TTY
3649 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3650 if (error_is_set(errp)) {
3653 socket_set_nonblock(fd);
3654 return qemu_chr_open_tty_fd(fd);
3656 error_setg(errp, "character device backend type 'serial' not supported");
3661 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3664 #ifdef HAVE_CHARDEV_PARPORT
3667 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3668 if (error_is_set(errp)) {
3671 return qemu_chr_open_pp_fd(fd);
3673 error_setg(errp, "character device backend type 'parallel' not supported");
3680 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3683 SocketAddress *addr = sock->addr;
3684 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3685 bool is_listen = sock->has_server ? sock->server : true;
3686 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3687 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3691 fd = socket_listen(addr, errp);
3693 fd = socket_connect(addr, errp, NULL, NULL);
3695 if (error_is_set(errp)) {
3698 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3699 is_telnet, is_waitconnect, errp);
3702 static CharDriverState *qmp_chardev_open_dgram(ChardevDgram *dgram,
3707 fd = socket_dgram(dgram->remote, dgram->local, errp);
3708 if (error_is_set(errp)) {
3711 return qemu_chr_open_udp_fd(fd);
3714 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3717 ChardevReturn *ret = g_new0(ChardevReturn, 1);
3718 CharDriverState *base, *chr = NULL;
3720 chr = qemu_chr_find(id);
3722 error_setg(errp, "Chardev '%s' already exists", id);
3727 switch (backend->kind) {
3728 case CHARDEV_BACKEND_KIND_FILE:
3729 chr = qmp_chardev_open_file(backend->file, errp);
3731 case CHARDEV_BACKEND_KIND_SERIAL:
3732 chr = qmp_chardev_open_serial(backend->serial, errp);
3734 case CHARDEV_BACKEND_KIND_PARALLEL:
3735 chr = qmp_chardev_open_parallel(backend->parallel, errp);
3737 case CHARDEV_BACKEND_KIND_PIPE:
3738 chr = qemu_chr_open_pipe(backend->pipe);
3740 case CHARDEV_BACKEND_KIND_SOCKET:
3741 chr = qmp_chardev_open_socket(backend->socket, errp);
3743 case CHARDEV_BACKEND_KIND_DGRAM:
3744 chr = qmp_chardev_open_dgram(backend->dgram, errp);
3746 #ifdef HAVE_CHARDEV_TTY
3747 case CHARDEV_BACKEND_KIND_PTY:
3748 chr = qemu_chr_open_pty(id, ret);
3751 case CHARDEV_BACKEND_KIND_NULL:
3752 chr = qemu_chr_open_null();
3754 case CHARDEV_BACKEND_KIND_MUX:
3755 base = qemu_chr_find(backend->mux->chardev);
3757 error_setg(errp, "mux: base chardev %s not found",
3758 backend->mux->chardev);
3761 chr = qemu_chr_open_mux(base);
3763 case CHARDEV_BACKEND_KIND_MSMOUSE:
3764 chr = qemu_chr_open_msmouse();
3766 #ifdef CONFIG_BRLAPI
3767 case CHARDEV_BACKEND_KIND_BRAILLE:
3768 chr = chr_baum_init();
3771 case CHARDEV_BACKEND_KIND_STDIO:
3772 chr = qemu_chr_open_stdio(backend->stdio);
3775 case CHARDEV_BACKEND_KIND_CONSOLE:
3776 chr = qemu_chr_open_win_con();
3780 case CHARDEV_BACKEND_KIND_SPICEVMC:
3781 chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
3783 case CHARDEV_BACKEND_KIND_SPICEPORT:
3784 chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
3787 case CHARDEV_BACKEND_KIND_VC:
3788 chr = vc_init(backend->vc);
3790 case CHARDEV_BACKEND_KIND_MEMORY:
3791 chr = qemu_chr_open_ringbuf(backend->memory, errp);
3794 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3798 if (chr == NULL && !error_is_set(errp)) {
3799 error_setg(errp, "Failed to create chardev");
3802 chr->label = g_strdup(id);
3803 chr->avail_connections =
3804 (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
3805 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3813 void qmp_chardev_remove(const char *id, Error **errp)
3815 CharDriverState *chr;
3817 chr = qemu_chr_find(id);
3819 error_setg(errp, "Chardev '%s' not found", id);
3822 if (chr->chr_can_read || chr->chr_read ||
3823 chr->chr_event || chr->handler_opaque) {
3824 error_setg(errp, "Chardev '%s' is busy", id);
3827 qemu_chr_delete(chr);
3830 static void register_types(void)
3832 register_char_driver_qapi("null", CHARDEV_BACKEND_KIND_NULL, NULL);
3833 register_char_driver("socket", qemu_chr_open_socket);
3834 register_char_driver("udp", qemu_chr_open_udp);
3835 register_char_driver_qapi("memory", CHARDEV_BACKEND_KIND_MEMORY,
3836 qemu_chr_parse_ringbuf);
3837 register_char_driver_qapi("file", CHARDEV_BACKEND_KIND_FILE,
3838 qemu_chr_parse_file_out);
3839 register_char_driver_qapi("stdio", CHARDEV_BACKEND_KIND_STDIO,
3840 qemu_chr_parse_stdio);
3841 register_char_driver_qapi("serial", CHARDEV_BACKEND_KIND_SERIAL,
3842 qemu_chr_parse_serial);
3843 register_char_driver_qapi("tty", CHARDEV_BACKEND_KIND_SERIAL,
3844 qemu_chr_parse_serial);
3845 register_char_driver_qapi("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
3846 qemu_chr_parse_parallel);
3847 register_char_driver_qapi("parport", CHARDEV_BACKEND_KIND_PARALLEL,
3848 qemu_chr_parse_parallel);
3849 register_char_driver_qapi("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
3850 register_char_driver_qapi("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
3851 register_char_driver_qapi("pipe", CHARDEV_BACKEND_KIND_PIPE,
3852 qemu_chr_parse_pipe);
3855 type_init(register_types);