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"
32 #include "hw/msmouse.h"
33 #include "qmp-commands.h"
43 #include <sys/times.h>
47 #include <sys/ioctl.h>
48 #include <sys/resource.h>
49 #include <sys/socket.h>
50 #include <netinet/in.h>
52 #include <arpa/inet.h>
55 #include <sys/select.h>
58 #if defined(__GLIBC__)
60 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
65 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
66 #include <dev/ppbus/ppi.h>
67 #include <dev/ppbus/ppbconf.h>
68 #elif defined(__DragonFly__)
69 #include <dev/misc/ppi/ppi.h>
70 #include <bus/ppbus/ppbconf.h>
76 #include <linux/ppdev.h>
77 #include <linux/parport.h>
81 #include <sys/ethernet.h>
82 #include <sys/sockio.h>
83 #include <netinet/arp.h>
84 #include <netinet/in.h>
85 #include <netinet/in_systm.h>
86 #include <netinet/ip.h>
87 #include <netinet/ip_icmp.h> // must come after ip.h
88 #include <netinet/udp.h>
89 #include <netinet/tcp.h>
97 #include "qemu/sockets.h"
98 #include "ui/qemu-spice.h"
100 #define READ_BUF_LEN 4096
102 /***********************************************************/
103 /* character device */
105 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
106 QTAILQ_HEAD_INITIALIZER(chardevs);
108 void qemu_chr_be_event(CharDriverState *s, int event)
110 /* Keep track if the char device is open */
112 case CHR_EVENT_OPENED:
115 case CHR_EVENT_CLOSED:
122 s->chr_event(s->handler_opaque, event);
125 static void qemu_chr_fire_open_event(void *opaque)
127 CharDriverState *s = opaque;
128 qemu_chr_be_event(s, CHR_EVENT_OPENED);
129 qemu_free_timer(s->open_timer);
130 s->open_timer = NULL;
133 void qemu_chr_generic_open(CharDriverState *s)
135 if (s->open_timer == NULL) {
136 s->open_timer = qemu_new_timer_ms(rt_clock,
137 qemu_chr_fire_open_event, s);
138 qemu_mod_timer(s->open_timer, qemu_get_clock_ms(rt_clock) - 1);
142 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
144 return s->chr_write(s, buf, len);
147 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
151 return s->chr_ioctl(s, cmd, arg);
154 int qemu_chr_be_can_write(CharDriverState *s)
156 if (!s->chr_can_read)
158 return s->chr_can_read(s->handler_opaque);
161 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
164 s->chr_read(s->handler_opaque, buf, len);
168 int qemu_chr_fe_get_msgfd(CharDriverState *s)
170 return s->get_msgfd ? s->get_msgfd(s) : -1;
173 int qemu_chr_add_client(CharDriverState *s, int fd)
175 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
178 void qemu_chr_accept_input(CharDriverState *s)
180 if (s->chr_accept_input)
181 s->chr_accept_input(s);
185 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
187 char buf[READ_BUF_LEN];
190 vsnprintf(buf, sizeof(buf), fmt, ap);
191 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
195 void qemu_chr_add_handlers(CharDriverState *s,
196 IOCanReadHandler *fd_can_read,
197 IOReadHandler *fd_read,
198 IOEventHandler *fd_event,
201 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
202 /* chr driver being released. */
203 ++s->avail_connections;
205 s->chr_can_read = fd_can_read;
206 s->chr_read = fd_read;
207 s->chr_event = fd_event;
208 s->handler_opaque = opaque;
209 if (s->chr_update_read_handler)
210 s->chr_update_read_handler(s);
212 /* We're connecting to an already opened device, so let's make sure we
213 also get the open event */
215 qemu_chr_generic_open(s);
219 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
224 static CharDriverState *qemu_chr_open_null(QemuOpts *opts)
226 CharDriverState *chr;
228 chr = g_malloc0(sizeof(CharDriverState));
229 chr->chr_write = null_chr_write;
233 /* MUX driver for serial I/O splitting */
235 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
236 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
238 IOCanReadHandler *chr_can_read[MAX_MUX];
239 IOReadHandler *chr_read[MAX_MUX];
240 IOEventHandler *chr_event[MAX_MUX];
241 void *ext_opaque[MAX_MUX];
242 CharDriverState *drv;
247 /* Intermediate input buffer allows to catch escape sequences even if the
248 currently active device is not accepting any input - but only until it
250 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
255 int64_t timestamps_start;
259 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
261 MuxDriver *d = chr->opaque;
263 if (!d->timestamps) {
264 ret = d->drv->chr_write(d->drv, buf, len);
269 for (i = 0; i < len; i++) {
275 ti = qemu_get_clock_ms(rt_clock);
276 if (d->timestamps_start == -1)
277 d->timestamps_start = ti;
278 ti -= d->timestamps_start;
280 snprintf(buf1, sizeof(buf1),
281 "[%02d:%02d:%02d.%03d] ",
286 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
289 ret += d->drv->chr_write(d->drv, buf+i, 1);
290 if (buf[i] == '\n') {
298 static const char * const mux_help[] = {
299 "% h print this help\n\r",
300 "% x exit emulator\n\r",
301 "% s save disk data back to file (if -snapshot)\n\r",
302 "% t toggle console timestamps\n\r"
303 "% b send break (magic sysrq)\n\r",
304 "% c switch between console and monitor\n\r",
309 int term_escape_char = 0x01; /* ctrl-a is used for escape */
310 static void mux_print_help(CharDriverState *chr)
313 char ebuf[15] = "Escape-Char";
314 char cbuf[50] = "\n\r";
316 if (term_escape_char > 0 && term_escape_char < 26) {
317 snprintf(cbuf, sizeof(cbuf), "\n\r");
318 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
320 snprintf(cbuf, sizeof(cbuf),
321 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
324 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
325 for (i = 0; mux_help[i] != NULL; i++) {
326 for (j=0; mux_help[i][j] != '\0'; j++) {
327 if (mux_help[i][j] == '%')
328 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
330 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
335 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
337 if (d->chr_event[mux_nr])
338 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
341 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
343 if (d->term_got_escape) {
344 d->term_got_escape = 0;
345 if (ch == term_escape_char)
354 const char *term = "QEMU: Terminated\n\r";
355 chr->chr_write(chr,(uint8_t *)term,strlen(term));
363 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
366 /* Switch to the next registered device */
367 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
369 if (d->focus >= d->mux_cnt)
371 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
374 d->timestamps = !d->timestamps;
375 d->timestamps_start = -1;
379 } else if (ch == term_escape_char) {
380 d->term_got_escape = 1;
388 static void mux_chr_accept_input(CharDriverState *chr)
390 MuxDriver *d = chr->opaque;
393 while (d->prod[m] != d->cons[m] &&
394 d->chr_can_read[m] &&
395 d->chr_can_read[m](d->ext_opaque[m])) {
396 d->chr_read[m](d->ext_opaque[m],
397 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
401 static int mux_chr_can_read(void *opaque)
403 CharDriverState *chr = opaque;
404 MuxDriver *d = chr->opaque;
407 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
409 if (d->chr_can_read[m])
410 return d->chr_can_read[m](d->ext_opaque[m]);
414 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
416 CharDriverState *chr = opaque;
417 MuxDriver *d = chr->opaque;
421 mux_chr_accept_input (opaque);
423 for(i = 0; i < size; i++)
424 if (mux_proc_byte(chr, d, buf[i])) {
425 if (d->prod[m] == d->cons[m] &&
426 d->chr_can_read[m] &&
427 d->chr_can_read[m](d->ext_opaque[m]))
428 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
430 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
434 static void mux_chr_event(void *opaque, int event)
436 CharDriverState *chr = opaque;
437 MuxDriver *d = chr->opaque;
440 /* Send the event to all registered listeners */
441 for (i = 0; i < d->mux_cnt; i++)
442 mux_chr_send_event(d, i, event);
445 static void mux_chr_update_read_handler(CharDriverState *chr)
447 MuxDriver *d = chr->opaque;
449 if (d->mux_cnt >= MAX_MUX) {
450 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
453 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
454 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
455 d->chr_read[d->mux_cnt] = chr->chr_read;
456 d->chr_event[d->mux_cnt] = chr->chr_event;
457 /* Fix up the real driver with mux routines */
458 if (d->mux_cnt == 0) {
459 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
462 if (d->focus != -1) {
463 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
465 d->focus = d->mux_cnt;
467 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
470 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
472 CharDriverState *chr;
475 chr = g_malloc0(sizeof(CharDriverState));
476 d = g_malloc0(sizeof(MuxDriver));
481 chr->chr_write = mux_chr_write;
482 chr->chr_update_read_handler = mux_chr_update_read_handler;
483 chr->chr_accept_input = mux_chr_accept_input;
484 /* Frontend guest-open / -close notification is not support with muxes */
485 chr->chr_guest_open = NULL;
486 chr->chr_guest_close = NULL;
488 /* Muxes are always open on creation */
489 qemu_chr_generic_open(chr);
496 int send_all(int fd, const void *buf, int len1)
502 ret = send(fd, buf, len, 0);
504 errno = WSAGetLastError();
505 if (errno != WSAEWOULDBLOCK) {
508 } else if (ret == 0) {
520 int send_all(int fd, const void *_buf, int len1)
523 const uint8_t *buf = _buf;
527 ret = write(fd, buf, len);
529 if (errno != EINTR && errno != EAGAIN)
531 } else if (ret == 0) {
544 typedef struct IOWatchPoll
549 IOCanReadHandler *fd_can_read;
552 QTAILQ_ENTRY(IOWatchPoll) node;
555 static QTAILQ_HEAD(, IOWatchPoll) io_watch_poll_list =
556 QTAILQ_HEAD_INITIALIZER(io_watch_poll_list);
558 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
562 QTAILQ_FOREACH(i, &io_watch_poll_list, node) {
563 if (i->src == source) {
571 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
573 IOWatchPoll *iwp = io_watch_poll_from_source(source);
575 iwp->max_size = iwp->fd_can_read(iwp->opaque);
576 if (iwp->max_size == 0) {
580 return g_io_watch_funcs.prepare(source, timeout_);
583 static gboolean io_watch_poll_check(GSource *source)
585 IOWatchPoll *iwp = io_watch_poll_from_source(source);
587 if (iwp->max_size == 0) {
591 return g_io_watch_funcs.check(source);
594 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
597 return g_io_watch_funcs.dispatch(source, callback, user_data);
600 static void io_watch_poll_finalize(GSource *source)
602 IOWatchPoll *iwp = io_watch_poll_from_source(source);
603 QTAILQ_REMOVE(&io_watch_poll_list, iwp, node);
604 g_io_watch_funcs.finalize(source);
607 static GSourceFuncs io_watch_poll_funcs = {
608 .prepare = io_watch_poll_prepare,
609 .check = io_watch_poll_check,
610 .dispatch = io_watch_poll_dispatch,
611 .finalize = io_watch_poll_finalize,
614 /* Can only be used for read */
615 static guint io_add_watch_poll(GIOChannel *channel,
616 IOCanReadHandler *fd_can_read,
624 src = g_io_create_watch(channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
625 g_source_set_funcs(src, &io_watch_poll_funcs);
626 g_source_set_callback(src, (GSourceFunc)fd_read, user_data, NULL);
627 tag = g_source_attach(src, NULL);
630 iwp = g_malloc0(sizeof(*iwp));
633 iwp->fd_can_read = fd_can_read;
634 iwp->opaque = user_data;
636 QTAILQ_INSERT_HEAD(&io_watch_poll_list, iwp, node);
641 static GIOChannel *io_channel_from_fd(int fd)
649 chan = g_io_channel_unix_new(fd);
651 g_io_channel_set_encoding(chan, NULL, NULL);
652 g_io_channel_set_buffered(chan, FALSE);
657 static int io_channel_send_all(GIOChannel *fd, const void *_buf, int len1)
662 const uint8_t *buf = _buf;
666 status = g_io_channel_write_chars(fd, (const gchar *)buf, len,
667 &bytes_written, NULL);
668 if (status != G_IO_STATUS_NORMAL) {
669 if (status != G_IO_STATUS_AGAIN) {
672 } else if (status == G_IO_STATUS_EOF) {
675 buf += bytes_written;
676 len -= bytes_written;
682 typedef struct FDCharDriver {
683 CharDriverState *chr;
684 GIOChannel *fd_in, *fd_out;
687 QTAILQ_ENTRY(FDCharDriver) node;
690 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
692 FDCharDriver *s = chr->opaque;
694 return io_channel_send_all(s->fd_out, buf, len);
697 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
699 CharDriverState *chr = opaque;
700 FDCharDriver *s = chr->opaque;
702 uint8_t buf[READ_BUF_LEN];
707 if (len > s->max_size) {
714 status = g_io_channel_read_chars(chan, (gchar *)buf,
715 len, &bytes_read, NULL);
716 if (status == G_IO_STATUS_EOF) {
717 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
720 if (status == G_IO_STATUS_NORMAL) {
721 qemu_chr_be_write(chr, buf, bytes_read);
727 static int fd_chr_read_poll(void *opaque)
729 CharDriverState *chr = opaque;
730 FDCharDriver *s = chr->opaque;
732 s->max_size = qemu_chr_be_can_write(chr);
736 static void fd_chr_update_read_handler(CharDriverState *chr)
738 FDCharDriver *s = chr->opaque;
741 g_source_remove(s->fd_in_tag);
745 s->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll, fd_chr_read, chr);
749 static void fd_chr_close(struct CharDriverState *chr)
751 FDCharDriver *s = chr->opaque;
754 g_source_remove(s->fd_in_tag);
759 g_io_channel_unref(s->fd_in);
762 g_io_channel_unref(s->fd_out);
766 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
769 /* open a character device to a unix fd */
770 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
772 CharDriverState *chr;
775 chr = g_malloc0(sizeof(CharDriverState));
776 s = g_malloc0(sizeof(FDCharDriver));
777 s->fd_in = io_channel_from_fd(fd_in);
778 s->fd_out = io_channel_from_fd(fd_out);
781 chr->chr_write = fd_chr_write;
782 chr->chr_update_read_handler = fd_chr_update_read_handler;
783 chr->chr_close = fd_chr_close;
785 qemu_chr_generic_open(chr);
790 static CharDriverState *qemu_chr_open_file_out(QemuOpts *opts)
794 TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
795 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
799 return qemu_chr_open_fd(-1, fd_out);
802 static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)
805 char filename_in[256], filename_out[256];
806 const char *filename = qemu_opt_get(opts, "path");
808 if (filename == NULL) {
809 fprintf(stderr, "chardev: pipe: no filename given\n");
813 snprintf(filename_in, 256, "%s.in", filename);
814 snprintf(filename_out, 256, "%s.out", filename);
815 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
816 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
817 if (fd_in < 0 || fd_out < 0) {
822 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
827 return qemu_chr_open_fd(fd_in, fd_out);
830 /* init terminal so that we can grab keys */
831 static struct termios oldtty;
832 static int old_fd0_flags;
833 static bool stdio_allow_signal;
835 static void term_exit(void)
837 tcsetattr (0, TCSANOW, &oldtty);
838 fcntl(0, F_SETFL, old_fd0_flags);
841 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
847 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
848 |INLCR|IGNCR|ICRNL|IXON);
849 tty.c_oflag |= OPOST;
850 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
851 tty.c_cflag &= ~(CSIZE|PARENB);
856 /* if graphical mode, we allow Ctrl-C handling */
857 if (!stdio_allow_signal)
858 tty.c_lflag &= ~ISIG;
860 tcsetattr (0, TCSANOW, &tty);
863 static void qemu_chr_close_stdio(struct CharDriverState *chr)
869 static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)
871 CharDriverState *chr;
873 if (is_daemonized()) {
874 error_report("cannot use stdio with -daemonize");
877 old_fd0_flags = fcntl(0, F_GETFL);
878 tcgetattr (0, &oldtty);
879 fcntl(0, F_SETFL, O_NONBLOCK);
882 chr = qemu_chr_open_fd(0, 1);
883 chr->chr_close = qemu_chr_close_stdio;
884 chr->chr_set_echo = qemu_chr_set_echo_stdio;
885 stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
886 display_type != DT_NOGRAPHIC);
887 qemu_chr_fe_set_echo(chr, false);
893 /* Once Solaris has openpty(), this is going to be removed. */
894 static int openpty(int *amaster, int *aslave, char *name,
895 struct termios *termp, struct winsize *winp)
898 int mfd = -1, sfd = -1;
900 *amaster = *aslave = -1;
902 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
906 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
909 if ((slave = ptsname(mfd)) == NULL)
912 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
915 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
916 (termp != NULL && tcgetattr(sfd, termp) < 0))
924 ioctl(sfd, TIOCSWINSZ, winp);
935 static void cfmakeraw (struct termios *termios_p)
937 termios_p->c_iflag &=
938 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
939 termios_p->c_oflag &= ~OPOST;
940 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
941 termios_p->c_cflag &= ~(CSIZE|PARENB);
942 termios_p->c_cflag |= CS8;
944 termios_p->c_cc[VMIN] = 0;
945 termios_p->c_cc[VTIME] = 0;
949 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
950 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
951 || defined(__GLIBC__)
953 #define HAVE_CHARDEV_TTY 1
963 static void pty_chr_update_read_handler(CharDriverState *chr);
964 static void pty_chr_state(CharDriverState *chr, int connected);
966 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
968 PtyCharDriver *s = chr->opaque;
971 /* guest sends data, check for (re-)connect */
972 pty_chr_update_read_handler(chr);
975 return send_all(s->fd, buf, len);
978 static int pty_chr_read_poll(void *opaque)
980 CharDriverState *chr = opaque;
981 PtyCharDriver *s = chr->opaque;
983 s->read_bytes = qemu_chr_be_can_write(chr);
984 return s->read_bytes;
987 static void pty_chr_read(void *opaque)
989 CharDriverState *chr = opaque;
990 PtyCharDriver *s = chr->opaque;
992 uint8_t buf[READ_BUF_LEN];
995 if (len > s->read_bytes)
999 size = read(s->fd, buf, len);
1000 if ((size == -1 && errno == EIO) ||
1002 pty_chr_state(chr, 0);
1006 pty_chr_state(chr, 1);
1007 qemu_chr_be_write(chr, buf, size);
1011 static void pty_chr_update_read_handler(CharDriverState *chr)
1013 PtyCharDriver *s = chr->opaque;
1015 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
1016 pty_chr_read, NULL, chr);
1019 * Short timeout here: just need wait long enougth that qemu makes
1020 * it through the poll loop once. When reconnected we want a
1021 * short timeout so we notice it almost instantly. Otherwise
1022 * read() gives us -EIO instantly, making pty_chr_state() reset the
1023 * timeout to the normal (much longer) poll interval before the
1026 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 10);
1029 static void pty_chr_state(CharDriverState *chr, int connected)
1031 PtyCharDriver *s = chr->opaque;
1034 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
1037 /* (re-)connect poll interval for idle guests: once per second.
1038 * We check more frequently in case the guests sends data to
1039 * the virtual device linked to our pty. */
1040 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 1000);
1043 qemu_chr_generic_open(chr);
1048 static void pty_chr_timer(void *opaque)
1050 struct CharDriverState *chr = opaque;
1051 PtyCharDriver *s = chr->opaque;
1056 /* If we arrive here without polling being cleared due
1057 * read returning -EIO, then we are (re-)connected */
1058 pty_chr_state(chr, 1);
1063 pty_chr_update_read_handler(chr);
1066 static void pty_chr_close(struct CharDriverState *chr)
1068 PtyCharDriver *s = chr->opaque;
1070 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
1072 qemu_del_timer(s->timer);
1073 qemu_free_timer(s->timer);
1075 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1078 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
1080 CharDriverState *chr;
1084 int master_fd, slave_fd, len;
1085 #if defined(__OpenBSD__) || defined(__DragonFly__)
1086 char pty_name[PATH_MAX];
1087 #define q_ptsname(x) pty_name
1089 char *pty_name = NULL;
1090 #define q_ptsname(x) ptsname(x)
1093 if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1097 /* Set raw attributes on the pty. */
1098 tcgetattr(slave_fd, &tty);
1100 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1103 chr = g_malloc0(sizeof(CharDriverState));
1105 len = strlen(q_ptsname(master_fd)) + 5;
1106 chr->filename = g_malloc(len);
1107 snprintf(chr->filename, len, "pty:%s", q_ptsname(master_fd));
1108 qemu_opt_set(opts, "path", q_ptsname(master_fd));
1110 label = qemu_opts_id(opts);
1111 fprintf(stderr, "char device redirected to %s%s%s%s\n",
1112 q_ptsname(master_fd),
1113 label ? " (label " : "",
1117 s = g_malloc0(sizeof(PtyCharDriver));
1119 chr->chr_write = pty_chr_write;
1120 chr->chr_update_read_handler = pty_chr_update_read_handler;
1121 chr->chr_close = pty_chr_close;
1124 s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr);
1129 static void tty_serial_init(int fd, int speed,
1130 int parity, int data_bits, int stop_bits)
1136 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1137 speed, parity, data_bits, stop_bits);
1139 tcgetattr (fd, &tty);
1141 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1142 speed = speed * 10 / 11;
1159 /* Non-Posix values follow. They may be unsupported on some systems. */
1161 check_speed(115200);
1163 check_speed(230400);
1166 check_speed(460800);
1169 check_speed(500000);
1172 check_speed(576000);
1175 check_speed(921600);
1178 check_speed(1000000);
1181 check_speed(1152000);
1184 check_speed(1500000);
1187 check_speed(2000000);
1190 check_speed(2500000);
1193 check_speed(3000000);
1196 check_speed(3500000);
1199 check_speed(4000000);
1204 cfsetispeed(&tty, spd);
1205 cfsetospeed(&tty, spd);
1207 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1208 |INLCR|IGNCR|ICRNL|IXON);
1209 tty.c_oflag |= OPOST;
1210 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1211 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1232 tty.c_cflag |= PARENB;
1235 tty.c_cflag |= PARENB | PARODD;
1239 tty.c_cflag |= CSTOPB;
1241 tcsetattr (fd, TCSANOW, &tty);
1244 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1246 FDCharDriver *s = chr->opaque;
1249 case CHR_IOCTL_SERIAL_SET_PARAMS:
1251 QEMUSerialSetParams *ssp = arg;
1252 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1253 ssp->speed, ssp->parity,
1254 ssp->data_bits, ssp->stop_bits);
1257 case CHR_IOCTL_SERIAL_SET_BREAK:
1259 int enable = *(int *)arg;
1261 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1265 case CHR_IOCTL_SERIAL_GET_TIOCM:
1268 int *targ = (int *)arg;
1269 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1271 if (sarg & TIOCM_CTS)
1272 *targ |= CHR_TIOCM_CTS;
1273 if (sarg & TIOCM_CAR)
1274 *targ |= CHR_TIOCM_CAR;
1275 if (sarg & TIOCM_DSR)
1276 *targ |= CHR_TIOCM_DSR;
1277 if (sarg & TIOCM_RI)
1278 *targ |= CHR_TIOCM_RI;
1279 if (sarg & TIOCM_DTR)
1280 *targ |= CHR_TIOCM_DTR;
1281 if (sarg & TIOCM_RTS)
1282 *targ |= CHR_TIOCM_RTS;
1285 case CHR_IOCTL_SERIAL_SET_TIOCM:
1287 int sarg = *(int *)arg;
1289 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1290 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1291 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1292 if (sarg & CHR_TIOCM_CTS)
1294 if (sarg & CHR_TIOCM_CAR)
1296 if (sarg & CHR_TIOCM_DSR)
1298 if (sarg & CHR_TIOCM_RI)
1300 if (sarg & CHR_TIOCM_DTR)
1302 if (sarg & CHR_TIOCM_RTS)
1304 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1313 static void qemu_chr_close_tty(CharDriverState *chr)
1315 FDCharDriver *s = chr->opaque;
1319 fd = g_io_channel_unix_get_fd(s->fd_in);
1329 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1331 CharDriverState *chr;
1333 tty_serial_init(fd, 115200, 'N', 8, 1);
1334 chr = qemu_chr_open_fd(fd, fd);
1335 chr->chr_ioctl = tty_serial_ioctl;
1336 chr->chr_close = qemu_chr_close_tty;
1340 static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
1342 const char *filename = qemu_opt_get(opts, "path");
1345 TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
1349 return qemu_chr_open_tty_fd(fd);
1351 #endif /* __linux__ || __sun__ */
1353 #if defined(__linux__)
1355 #define HAVE_CHARDEV_PARPORT 1
1360 } ParallelCharDriver;
1362 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1364 if (s->mode != mode) {
1366 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1373 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1375 ParallelCharDriver *drv = chr->opaque;
1380 case CHR_IOCTL_PP_READ_DATA:
1381 if (ioctl(fd, PPRDATA, &b) < 0)
1383 *(uint8_t *)arg = b;
1385 case CHR_IOCTL_PP_WRITE_DATA:
1386 b = *(uint8_t *)arg;
1387 if (ioctl(fd, PPWDATA, &b) < 0)
1390 case CHR_IOCTL_PP_READ_CONTROL:
1391 if (ioctl(fd, PPRCONTROL, &b) < 0)
1393 /* Linux gives only the lowest bits, and no way to know data
1394 direction! For better compatibility set the fixed upper
1396 *(uint8_t *)arg = b | 0xc0;
1398 case CHR_IOCTL_PP_WRITE_CONTROL:
1399 b = *(uint8_t *)arg;
1400 if (ioctl(fd, PPWCONTROL, &b) < 0)
1403 case CHR_IOCTL_PP_READ_STATUS:
1404 if (ioctl(fd, PPRSTATUS, &b) < 0)
1406 *(uint8_t *)arg = b;
1408 case CHR_IOCTL_PP_DATA_DIR:
1409 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1412 case CHR_IOCTL_PP_EPP_READ_ADDR:
1413 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1414 struct ParallelIOArg *parg = arg;
1415 int n = read(fd, parg->buffer, parg->count);
1416 if (n != parg->count) {
1421 case CHR_IOCTL_PP_EPP_READ:
1422 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1423 struct ParallelIOArg *parg = arg;
1424 int n = read(fd, parg->buffer, parg->count);
1425 if (n != parg->count) {
1430 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1431 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1432 struct ParallelIOArg *parg = arg;
1433 int n = write(fd, parg->buffer, parg->count);
1434 if (n != parg->count) {
1439 case CHR_IOCTL_PP_EPP_WRITE:
1440 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1441 struct ParallelIOArg *parg = arg;
1442 int n = write(fd, parg->buffer, parg->count);
1443 if (n != parg->count) {
1454 static void pp_close(CharDriverState *chr)
1456 ParallelCharDriver *drv = chr->opaque;
1459 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1460 ioctl(fd, PPRELEASE);
1463 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1466 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1468 CharDriverState *chr;
1469 ParallelCharDriver *drv;
1471 if (ioctl(fd, PPCLAIM) < 0) {
1476 drv = g_malloc0(sizeof(ParallelCharDriver));
1478 drv->mode = IEEE1284_MODE_COMPAT;
1480 chr = g_malloc0(sizeof(CharDriverState));
1481 chr->chr_write = null_chr_write;
1482 chr->chr_ioctl = pp_ioctl;
1483 chr->chr_close = pp_close;
1486 qemu_chr_generic_open(chr);
1490 #endif /* __linux__ */
1492 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1494 #define HAVE_CHARDEV_PARPORT 1
1496 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1498 int fd = (int)(intptr_t)chr->opaque;
1502 case CHR_IOCTL_PP_READ_DATA:
1503 if (ioctl(fd, PPIGDATA, &b) < 0)
1505 *(uint8_t *)arg = b;
1507 case CHR_IOCTL_PP_WRITE_DATA:
1508 b = *(uint8_t *)arg;
1509 if (ioctl(fd, PPISDATA, &b) < 0)
1512 case CHR_IOCTL_PP_READ_CONTROL:
1513 if (ioctl(fd, PPIGCTRL, &b) < 0)
1515 *(uint8_t *)arg = b;
1517 case CHR_IOCTL_PP_WRITE_CONTROL:
1518 b = *(uint8_t *)arg;
1519 if (ioctl(fd, PPISCTRL, &b) < 0)
1522 case CHR_IOCTL_PP_READ_STATUS:
1523 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1525 *(uint8_t *)arg = b;
1533 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1535 CharDriverState *chr;
1537 chr = g_malloc0(sizeof(CharDriverState));
1538 chr->opaque = (void *)(intptr_t)fd;
1539 chr->chr_write = null_chr_write;
1540 chr->chr_ioctl = pp_ioctl;
1549 HANDLE hcom, hrecv, hsend;
1550 OVERLAPPED orecv, osend;
1557 HANDLE hInputReadyEvent;
1558 HANDLE hInputDoneEvent;
1559 HANDLE hInputThread;
1560 uint8_t win_stdio_buf;
1561 } WinStdioCharState;
1563 #define NSENDBUF 2048
1564 #define NRECVBUF 2048
1565 #define MAXCONNECT 1
1566 #define NTIMEOUT 5000
1568 static int win_chr_poll(void *opaque);
1569 static int win_chr_pipe_poll(void *opaque);
1571 static void win_chr_close(CharDriverState *chr)
1573 WinCharState *s = chr->opaque;
1576 CloseHandle(s->hsend);
1580 CloseHandle(s->hrecv);
1584 CloseHandle(s->hcom);
1588 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1590 qemu_del_polling_cb(win_chr_poll, chr);
1592 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1595 static int win_chr_init(CharDriverState *chr, const char *filename)
1597 WinCharState *s = chr->opaque;
1599 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1604 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1606 fprintf(stderr, "Failed CreateEvent\n");
1609 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1611 fprintf(stderr, "Failed CreateEvent\n");
1615 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1616 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1617 if (s->hcom == INVALID_HANDLE_VALUE) {
1618 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1623 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1624 fprintf(stderr, "Failed SetupComm\n");
1628 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1629 size = sizeof(COMMCONFIG);
1630 GetDefaultCommConfig(filename, &comcfg, &size);
1631 comcfg.dcb.DCBlength = sizeof(DCB);
1632 CommConfigDialog(filename, NULL, &comcfg);
1634 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1635 fprintf(stderr, "Failed SetCommState\n");
1639 if (!SetCommMask(s->hcom, EV_ERR)) {
1640 fprintf(stderr, "Failed SetCommMask\n");
1644 cto.ReadIntervalTimeout = MAXDWORD;
1645 if (!SetCommTimeouts(s->hcom, &cto)) {
1646 fprintf(stderr, "Failed SetCommTimeouts\n");
1650 if (!ClearCommError(s->hcom, &err, &comstat)) {
1651 fprintf(stderr, "Failed ClearCommError\n");
1654 qemu_add_polling_cb(win_chr_poll, chr);
1662 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1664 WinCharState *s = chr->opaque;
1665 DWORD len, ret, size, err;
1668 ZeroMemory(&s->osend, sizeof(s->osend));
1669 s->osend.hEvent = s->hsend;
1672 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1674 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1676 err = GetLastError();
1677 if (err == ERROR_IO_PENDING) {
1678 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1696 static int win_chr_read_poll(CharDriverState *chr)
1698 WinCharState *s = chr->opaque;
1700 s->max_size = qemu_chr_be_can_write(chr);
1704 static void win_chr_readfile(CharDriverState *chr)
1706 WinCharState *s = chr->opaque;
1708 uint8_t buf[READ_BUF_LEN];
1711 ZeroMemory(&s->orecv, sizeof(s->orecv));
1712 s->orecv.hEvent = s->hrecv;
1713 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1715 err = GetLastError();
1716 if (err == ERROR_IO_PENDING) {
1717 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1722 qemu_chr_be_write(chr, buf, size);
1726 static void win_chr_read(CharDriverState *chr)
1728 WinCharState *s = chr->opaque;
1730 if (s->len > s->max_size)
1731 s->len = s->max_size;
1735 win_chr_readfile(chr);
1738 static int win_chr_poll(void *opaque)
1740 CharDriverState *chr = opaque;
1741 WinCharState *s = chr->opaque;
1745 ClearCommError(s->hcom, &comerr, &status);
1746 if (status.cbInQue > 0) {
1747 s->len = status.cbInQue;
1748 win_chr_read_poll(chr);
1755 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1757 CharDriverState *chr;
1760 chr = g_malloc0(sizeof(CharDriverState));
1761 s = g_malloc0(sizeof(WinCharState));
1763 chr->chr_write = win_chr_write;
1764 chr->chr_close = win_chr_close;
1766 if (win_chr_init(chr, filename) < 0) {
1771 qemu_chr_generic_open(chr);
1775 static CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1777 return qemu_chr_open_win_path(qemu_opt_get(opts, "path"));
1780 static int win_chr_pipe_poll(void *opaque)
1782 CharDriverState *chr = opaque;
1783 WinCharState *s = chr->opaque;
1786 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1789 win_chr_read_poll(chr);
1796 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1798 WinCharState *s = chr->opaque;
1806 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1808 fprintf(stderr, "Failed CreateEvent\n");
1811 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1813 fprintf(stderr, "Failed CreateEvent\n");
1817 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1818 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1819 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1821 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1822 if (s->hcom == INVALID_HANDLE_VALUE) {
1823 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1828 ZeroMemory(&ov, sizeof(ov));
1829 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1830 ret = ConnectNamedPipe(s->hcom, &ov);
1832 fprintf(stderr, "Failed ConnectNamedPipe\n");
1836 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1838 fprintf(stderr, "Failed GetOverlappedResult\n");
1840 CloseHandle(ov.hEvent);
1847 CloseHandle(ov.hEvent);
1850 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1859 static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
1861 const char *filename = qemu_opt_get(opts, "path");
1862 CharDriverState *chr;
1865 chr = g_malloc0(sizeof(CharDriverState));
1866 s = g_malloc0(sizeof(WinCharState));
1868 chr->chr_write = win_chr_write;
1869 chr->chr_close = win_chr_close;
1871 if (win_chr_pipe_init(chr, filename) < 0) {
1876 qemu_chr_generic_open(chr);
1880 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1882 CharDriverState *chr;
1885 chr = g_malloc0(sizeof(CharDriverState));
1886 s = g_malloc0(sizeof(WinCharState));
1889 chr->chr_write = win_chr_write;
1890 qemu_chr_generic_open(chr);
1894 static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
1896 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1899 static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
1901 const char *file_out = qemu_opt_get(opts, "path");
1904 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1905 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1906 if (fd_out == INVALID_HANDLE_VALUE) {
1910 return qemu_chr_open_win_file(fd_out);
1913 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1915 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1922 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
1932 static void win_stdio_wait_func(void *opaque)
1934 CharDriverState *chr = opaque;
1935 WinStdioCharState *stdio = chr->opaque;
1936 INPUT_RECORD buf[4];
1941 ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
1945 /* Avoid error storm */
1946 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
1950 for (i = 0; i < dwSize; i++) {
1951 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
1953 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
1955 if (kev->uChar.AsciiChar != 0) {
1956 for (j = 0; j < kev->wRepeatCount; j++) {
1957 if (qemu_chr_be_can_write(chr)) {
1958 uint8_t c = kev->uChar.AsciiChar;
1959 qemu_chr_be_write(chr, &c, 1);
1967 static DWORD WINAPI win_stdio_thread(LPVOID param)
1969 CharDriverState *chr = param;
1970 WinStdioCharState *stdio = chr->opaque;
1976 /* Wait for one byte */
1977 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
1979 /* Exit in case of error, continue if nothing read */
1987 /* Some terminal emulator returns \r\n for Enter, just pass \n */
1988 if (stdio->win_stdio_buf == '\r') {
1992 /* Signal the main thread and wait until the byte was eaten */
1993 if (!SetEvent(stdio->hInputReadyEvent)) {
1996 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2002 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2006 static void win_stdio_thread_wait_func(void *opaque)
2008 CharDriverState *chr = opaque;
2009 WinStdioCharState *stdio = chr->opaque;
2011 if (qemu_chr_be_can_write(chr)) {
2012 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2015 SetEvent(stdio->hInputDoneEvent);
2018 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2020 WinStdioCharState *stdio = chr->opaque;
2023 GetConsoleMode(stdio->hStdIn, &dwMode);
2026 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2028 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2032 static void win_stdio_close(CharDriverState *chr)
2034 WinStdioCharState *stdio = chr->opaque;
2036 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2037 CloseHandle(stdio->hInputReadyEvent);
2039 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2040 CloseHandle(stdio->hInputDoneEvent);
2042 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2043 TerminateThread(stdio->hInputThread, 0);
2046 g_free(chr->opaque);
2050 static CharDriverState *qemu_chr_open_win_stdio(QemuOpts *opts)
2052 CharDriverState *chr;
2053 WinStdioCharState *stdio;
2057 chr = g_malloc0(sizeof(CharDriverState));
2058 stdio = g_malloc0(sizeof(WinStdioCharState));
2060 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2061 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2062 fprintf(stderr, "cannot open stdio: invalid handle\n");
2066 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2068 chr->opaque = stdio;
2069 chr->chr_write = win_stdio_write;
2070 chr->chr_close = win_stdio_close;
2073 if (qemu_add_wait_object(stdio->hStdIn,
2074 win_stdio_wait_func, chr)) {
2075 fprintf(stderr, "qemu_add_wait_object: failed\n");
2080 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2081 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2082 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2085 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2086 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2087 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2088 fprintf(stderr, "cannot create stdio thread or event\n");
2091 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2092 win_stdio_thread_wait_func, chr)) {
2093 fprintf(stderr, "qemu_add_wait_object: failed\n");
2097 dwMode |= ENABLE_LINE_INPUT;
2100 /* set the terminal in raw mode */
2101 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2102 dwMode |= ENABLE_PROCESSED_INPUT;
2105 SetConsoleMode(stdio->hStdIn, dwMode);
2107 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2108 qemu_chr_fe_set_echo(chr, false);
2112 #endif /* !_WIN32 */
2114 /***********************************************************/
2115 /* UDP Net console */
2119 uint8_t buf[READ_BUF_LEN];
2125 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2127 NetCharDriver *s = chr->opaque;
2129 return send(s->fd, (const void *)buf, len, 0);
2132 static int udp_chr_read_poll(void *opaque)
2134 CharDriverState *chr = opaque;
2135 NetCharDriver *s = chr->opaque;
2137 s->max_size = qemu_chr_be_can_write(chr);
2139 /* If there were any stray characters in the queue process them
2142 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2143 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2145 s->max_size = qemu_chr_be_can_write(chr);
2150 static void udp_chr_read(void *opaque)
2152 CharDriverState *chr = opaque;
2153 NetCharDriver *s = chr->opaque;
2155 if (s->max_size == 0)
2157 s->bufcnt = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
2158 s->bufptr = s->bufcnt;
2163 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2164 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2166 s->max_size = qemu_chr_be_can_write(chr);
2170 static void udp_chr_update_read_handler(CharDriverState *chr)
2172 NetCharDriver *s = chr->opaque;
2175 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2176 udp_chr_read, NULL, chr);
2180 static void udp_chr_close(CharDriverState *chr)
2182 NetCharDriver *s = chr->opaque;
2184 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2188 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2191 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2193 CharDriverState *chr = NULL;
2194 NetCharDriver *s = NULL;
2195 Error *local_err = NULL;
2198 chr = g_malloc0(sizeof(CharDriverState));
2199 s = g_malloc0(sizeof(NetCharDriver));
2201 fd = inet_dgram_opts(opts, &local_err);
2210 chr->chr_write = udp_chr_write;
2211 chr->chr_update_read_handler = udp_chr_update_read_handler;
2212 chr->chr_close = udp_chr_close;
2217 qerror_report_err(local_err);
2218 error_free(local_err);
2228 /***********************************************************/
2229 /* TCP Net console */
2241 static void tcp_chr_accept(void *opaque);
2243 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2245 TCPCharDriver *s = chr->opaque;
2247 return send_all(s->fd, buf, len);
2249 /* XXX: indicate an error ? */
2254 static int tcp_chr_read_poll(void *opaque)
2256 CharDriverState *chr = opaque;
2257 TCPCharDriver *s = chr->opaque;
2260 s->max_size = qemu_chr_be_can_write(chr);
2265 #define IAC_BREAK 243
2266 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2268 uint8_t *buf, int *size)
2270 /* Handle any telnet client's basic IAC options to satisfy char by
2271 * char mode with no echo. All IAC options will be removed from
2272 * the buf and the do_telnetopt variable will be used to track the
2273 * state of the width of the IAC information.
2275 * IAC commands come in sets of 3 bytes with the exception of the
2276 * "IAC BREAK" command and the double IAC.
2282 for (i = 0; i < *size; i++) {
2283 if (s->do_telnetopt > 1) {
2284 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2285 /* Double IAC means send an IAC */
2289 s->do_telnetopt = 1;
2291 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2292 /* Handle IAC break commands by sending a serial break */
2293 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2298 if (s->do_telnetopt >= 4) {
2299 s->do_telnetopt = 1;
2302 if ((unsigned char)buf[i] == IAC) {
2303 s->do_telnetopt = 2;
2314 static int tcp_get_msgfd(CharDriverState *chr)
2316 TCPCharDriver *s = chr->opaque;
2323 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2325 TCPCharDriver *s = chr->opaque;
2326 struct cmsghdr *cmsg;
2328 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2331 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2332 cmsg->cmsg_level != SOL_SOCKET ||
2333 cmsg->cmsg_type != SCM_RIGHTS)
2336 fd = *((int *)CMSG_DATA(cmsg));
2340 #ifndef MSG_CMSG_CLOEXEC
2341 qemu_set_cloexec(fd);
2349 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2351 TCPCharDriver *s = chr->opaque;
2352 struct msghdr msg = { NULL, };
2353 struct iovec iov[1];
2355 struct cmsghdr cmsg;
2356 char control[CMSG_SPACE(sizeof(int))];
2361 iov[0].iov_base = buf;
2362 iov[0].iov_len = len;
2366 msg.msg_control = &msg_control;
2367 msg.msg_controllen = sizeof(msg_control);
2369 #ifdef MSG_CMSG_CLOEXEC
2370 flags |= MSG_CMSG_CLOEXEC;
2372 ret = recvmsg(s->fd, &msg, flags);
2373 if (ret > 0 && s->is_unix) {
2374 unix_process_msgfd(chr, &msg);
2380 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2382 TCPCharDriver *s = chr->opaque;
2383 return qemu_recv(s->fd, buf, len, 0);
2387 static void tcp_chr_read(void *opaque)
2389 CharDriverState *chr = opaque;
2390 TCPCharDriver *s = chr->opaque;
2391 uint8_t buf[READ_BUF_LEN];
2394 if (!s->connected || s->max_size <= 0)
2397 if (len > s->max_size)
2399 size = tcp_chr_recv(chr, (void *)buf, len);
2401 /* connection closed */
2403 if (s->listen_fd >= 0) {
2404 qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2406 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2409 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2410 } else if (size > 0) {
2411 if (s->do_telnetopt)
2412 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2414 qemu_chr_be_write(chr, buf, size);
2419 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2421 return qemu_chr_open_fd(eventfd, eventfd);
2425 static void tcp_chr_connect(void *opaque)
2427 CharDriverState *chr = opaque;
2428 TCPCharDriver *s = chr->opaque;
2432 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2433 tcp_chr_read, NULL, chr);
2435 qemu_chr_generic_open(chr);
2438 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2439 static void tcp_chr_telnet_init(int fd)
2442 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2443 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2444 send(fd, (char *)buf, 3, 0);
2445 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2446 send(fd, (char *)buf, 3, 0);
2447 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2448 send(fd, (char *)buf, 3, 0);
2449 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2450 send(fd, (char *)buf, 3, 0);
2453 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2455 TCPCharDriver *s = chr->opaque;
2459 socket_set_nonblock(fd);
2461 socket_set_nodelay(fd);
2463 qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2464 tcp_chr_connect(chr);
2469 static void tcp_chr_accept(void *opaque)
2471 CharDriverState *chr = opaque;
2472 TCPCharDriver *s = chr->opaque;
2473 struct sockaddr_in saddr;
2475 struct sockaddr_un uaddr;
2477 struct sockaddr *addr;
2484 len = sizeof(uaddr);
2485 addr = (struct sockaddr *)&uaddr;
2489 len = sizeof(saddr);
2490 addr = (struct sockaddr *)&saddr;
2492 fd = qemu_accept(s->listen_fd, addr, &len);
2493 if (fd < 0 && errno != EINTR) {
2495 } else if (fd >= 0) {
2496 if (s->do_telnetopt)
2497 tcp_chr_telnet_init(fd);
2501 if (tcp_chr_add_client(chr, fd) < 0)
2505 static void tcp_chr_close(CharDriverState *chr)
2507 TCPCharDriver *s = chr->opaque;
2509 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2512 if (s->listen_fd >= 0) {
2513 qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2514 closesocket(s->listen_fd);
2517 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2520 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2521 bool is_listen, bool is_telnet,
2522 bool is_waitconnect,
2525 CharDriverState *chr = NULL;
2526 TCPCharDriver *s = NULL;
2527 char host[NI_MAXHOST], serv[NI_MAXSERV];
2528 const char *left = "", *right = "";
2529 struct sockaddr_storage ss;
2530 socklen_t ss_len = sizeof(ss);
2532 memset(&ss, 0, ss_len);
2533 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2534 error_setg(errp, "getsockname: %s", strerror(errno));
2538 chr = g_malloc0(sizeof(CharDriverState));
2539 s = g_malloc0(sizeof(TCPCharDriver));
2546 chr->filename = g_malloc(256);
2547 switch (ss.ss_family) {
2551 snprintf(chr->filename, 256, "unix:%s%s",
2552 ((struct sockaddr_un *)(&ss))->sun_path,
2553 is_listen ? ",server" : "");
2561 s->do_nodelay = do_nodelay;
2562 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2563 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2564 snprintf(chr->filename, 256, "%s:%s:%s%s%s%s",
2565 is_telnet ? "telnet" : "tcp",
2566 left, host, right, serv,
2567 is_listen ? ",server" : "");
2572 chr->chr_write = tcp_chr_write;
2573 chr->chr_close = tcp_chr_close;
2574 chr->get_msgfd = tcp_get_msgfd;
2575 chr->chr_add_client = tcp_chr_add_client;
2579 qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2581 s->do_telnetopt = 1;
2586 socket_set_nodelay(fd);
2587 tcp_chr_connect(chr);
2590 if (is_listen && is_waitconnect) {
2591 printf("QEMU waiting for connection on: %s\n",
2593 tcp_chr_accept(chr);
2594 socket_set_nonblock(s->listen_fd);
2599 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2601 CharDriverState *chr = NULL;
2602 Error *local_err = NULL;
2610 is_listen = qemu_opt_get_bool(opts, "server", 0);
2611 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2612 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2613 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2614 is_unix = qemu_opt_get(opts, "path") != NULL;
2620 fd = unix_listen_opts(opts, &local_err);
2622 fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2626 fd = inet_listen_opts(opts, 0, &local_err);
2628 fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2635 if (!is_waitconnect)
2636 socket_set_nonblock(fd);
2638 chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2639 is_waitconnect, &local_err);
2640 if (error_is_set(&local_err)) {
2648 qerror_report_err(local_err);
2649 error_free(local_err);
2655 g_free(chr->opaque);
2661 /***********************************************************/
2662 /* Memory chardev */
2665 size_t outbuf_capacity;
2669 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2671 MemoryDriver *d = chr->opaque;
2673 /* TODO: the QString implementation has the same code, we should
2674 * introduce a generic way to do this in cutils.c */
2675 if (d->outbuf_capacity < d->outbuf_size + len) {
2677 d->outbuf_capacity += len;
2678 d->outbuf_capacity *= 2;
2679 d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
2682 memcpy(d->outbuf + d->outbuf_size, buf, len);
2683 d->outbuf_size += len;
2688 void qemu_chr_init_mem(CharDriverState *chr)
2692 d = g_malloc(sizeof(*d));
2694 d->outbuf_capacity = 4096;
2695 d->outbuf = g_malloc0(d->outbuf_capacity);
2697 memset(chr, 0, sizeof(*chr));
2699 chr->chr_write = mem_chr_write;
2702 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2704 MemoryDriver *d = chr->opaque;
2705 return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2708 /* NOTE: this driver can not be closed with qemu_chr_delete()! */
2709 void qemu_chr_close_mem(CharDriverState *chr)
2711 MemoryDriver *d = chr->opaque;
2714 g_free(chr->opaque);
2716 chr->chr_write = NULL;
2719 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2721 const MemoryDriver *d = chr->opaque;
2722 return d->outbuf_size;
2725 /*********************************************************/
2726 /* Ring buffer chardev */
2733 } RingBufCharDriver;
2735 static size_t ringbuf_count(const CharDriverState *chr)
2737 const RingBufCharDriver *d = chr->opaque;
2739 return d->prod - d->cons;
2742 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2744 RingBufCharDriver *d = chr->opaque;
2747 if (!buf || (len < 0)) {
2751 for (i = 0; i < len; i++ ) {
2752 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2753 if (d->prod - d->cons > d->size) {
2754 d->cons = d->prod - d->size;
2761 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2763 RingBufCharDriver *d = chr->opaque;
2766 for (i = 0; i < len && d->cons != d->prod; i++) {
2767 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2773 static void ringbuf_chr_close(struct CharDriverState *chr)
2775 RingBufCharDriver *d = chr->opaque;
2782 static CharDriverState *qemu_chr_open_ringbuf(QemuOpts *opts)
2784 CharDriverState *chr;
2785 RingBufCharDriver *d;
2787 chr = g_malloc0(sizeof(CharDriverState));
2788 d = g_malloc(sizeof(*d));
2790 d->size = qemu_opt_get_size(opts, "size", 0);
2795 /* The size must be power of 2 */
2796 if (d->size & (d->size - 1)) {
2797 error_report("size of ringbuf device must be power of two");
2803 d->cbuf = g_malloc0(d->size);
2806 chr->chr_write = ringbuf_chr_write;
2807 chr->chr_close = ringbuf_chr_close;
2817 static bool chr_is_ringbuf(const CharDriverState *chr)
2819 return chr->chr_write == ringbuf_chr_write;
2822 void qmp_ringbuf_write(const char *device, const char *data,
2823 bool has_format, enum DataFormat format,
2826 CharDriverState *chr;
2827 const uint8_t *write_data;
2831 chr = qemu_chr_find(device);
2833 error_setg(errp, "Device '%s' not found", device);
2837 if (!chr_is_ringbuf(chr)) {
2838 error_setg(errp,"%s is not a ringbuf device", device);
2842 if (has_format && (format == DATA_FORMAT_BASE64)) {
2843 write_data = g_base64_decode(data, &write_count);
2845 write_data = (uint8_t *)data;
2846 write_count = strlen(data);
2849 ret = ringbuf_chr_write(chr, write_data, write_count);
2851 if (write_data != (uint8_t *)data) {
2852 g_free((void *)write_data);
2856 error_setg(errp, "Failed to write to device %s", device);
2861 char *qmp_ringbuf_read(const char *device, int64_t size,
2862 bool has_format, enum DataFormat format,
2865 CharDriverState *chr;
2870 chr = qemu_chr_find(device);
2872 error_setg(errp, "Device '%s' not found", device);
2876 if (!chr_is_ringbuf(chr)) {
2877 error_setg(errp,"%s is not a ringbuf device", device);
2882 error_setg(errp, "size must be greater than zero");
2886 count = ringbuf_count(chr);
2887 size = size > count ? count : size;
2888 read_data = g_malloc(size + 1);
2890 ringbuf_chr_read(chr, read_data, size);
2892 if (has_format && (format == DATA_FORMAT_BASE64)) {
2893 data = g_base64_encode(read_data, size);
2897 * FIXME should read only complete, valid UTF-8 characters up
2898 * to @size bytes. Invalid sequences should be replaced by a
2899 * suitable replacement character. Except when (and only
2900 * when) ring buffer lost characters since last read, initial
2901 * continuation characters should be dropped.
2903 read_data[size] = 0;
2904 data = (char *)read_data;
2910 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2912 char host[65], port[33], width[8], height[8];
2916 Error *local_err = NULL;
2918 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
2919 if (error_is_set(&local_err)) {
2920 qerror_report_err(local_err);
2921 error_free(local_err);
2925 if (strstart(filename, "mon:", &p)) {
2927 qemu_opt_set(opts, "mux", "on");
2930 if (strcmp(filename, "null") == 0 ||
2931 strcmp(filename, "pty") == 0 ||
2932 strcmp(filename, "msmouse") == 0 ||
2933 strcmp(filename, "braille") == 0 ||
2934 strcmp(filename, "stdio") == 0) {
2935 qemu_opt_set(opts, "backend", filename);
2938 if (strstart(filename, "vc", &p)) {
2939 qemu_opt_set(opts, "backend", "vc");
2941 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2943 qemu_opt_set(opts, "width", width);
2944 qemu_opt_set(opts, "height", height);
2945 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2947 qemu_opt_set(opts, "cols", width);
2948 qemu_opt_set(opts, "rows", height);
2955 if (strcmp(filename, "con:") == 0) {
2956 qemu_opt_set(opts, "backend", "console");
2959 if (strstart(filename, "COM", NULL)) {
2960 qemu_opt_set(opts, "backend", "serial");
2961 qemu_opt_set(opts, "path", filename);
2964 if (strstart(filename, "file:", &p)) {
2965 qemu_opt_set(opts, "backend", "file");
2966 qemu_opt_set(opts, "path", p);
2969 if (strstart(filename, "pipe:", &p)) {
2970 qemu_opt_set(opts, "backend", "pipe");
2971 qemu_opt_set(opts, "path", p);
2974 if (strstart(filename, "tcp:", &p) ||
2975 strstart(filename, "telnet:", &p)) {
2976 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2978 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2981 qemu_opt_set(opts, "backend", "socket");
2982 qemu_opt_set(opts, "host", host);
2983 qemu_opt_set(opts, "port", port);
2984 if (p[pos] == ',') {
2985 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2988 if (strstart(filename, "telnet:", &p))
2989 qemu_opt_set(opts, "telnet", "on");
2992 if (strstart(filename, "udp:", &p)) {
2993 qemu_opt_set(opts, "backend", "udp");
2994 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2996 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3000 qemu_opt_set(opts, "host", host);
3001 qemu_opt_set(opts, "port", port);
3002 if (p[pos] == '@') {
3004 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3006 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3010 qemu_opt_set(opts, "localaddr", host);
3011 qemu_opt_set(opts, "localport", port);
3015 if (strstart(filename, "unix:", &p)) {
3016 qemu_opt_set(opts, "backend", "socket");
3017 if (qemu_opts_do_parse(opts, p, "path") != 0)
3021 if (strstart(filename, "/dev/parport", NULL) ||
3022 strstart(filename, "/dev/ppi", NULL)) {
3023 qemu_opt_set(opts, "backend", "parport");
3024 qemu_opt_set(opts, "path", filename);
3027 if (strstart(filename, "/dev/", NULL)) {
3028 qemu_opt_set(opts, "backend", "tty");
3029 qemu_opt_set(opts, "path", filename);
3034 qemu_opts_del(opts);
3038 #ifdef HAVE_CHARDEV_PARPORT
3040 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
3042 const char *filename = qemu_opt_get(opts, "path");
3045 fd = qemu_open(filename, O_RDWR);
3049 return qemu_chr_open_pp_fd(fd);
3054 static const struct {
3056 CharDriverState *(*open)(QemuOpts *opts);
3057 } backend_table[] = {
3058 { .name = "null", .open = qemu_chr_open_null },
3059 { .name = "socket", .open = qemu_chr_open_socket },
3060 { .name = "udp", .open = qemu_chr_open_udp },
3061 { .name = "msmouse", .open = qemu_chr_open_msmouse },
3062 { .name = "vc", .open = vc_init },
3063 { .name = "memory", .open = qemu_chr_open_ringbuf },
3065 { .name = "file", .open = qemu_chr_open_win_file_out },
3066 { .name = "pipe", .open = qemu_chr_open_win_pipe },
3067 { .name = "console", .open = qemu_chr_open_win_con },
3068 { .name = "serial", .open = qemu_chr_open_win },
3069 { .name = "stdio", .open = qemu_chr_open_win_stdio },
3071 { .name = "file", .open = qemu_chr_open_file_out },
3072 { .name = "pipe", .open = qemu_chr_open_pipe },
3073 { .name = "stdio", .open = qemu_chr_open_stdio },
3075 #ifdef CONFIG_BRLAPI
3076 { .name = "braille", .open = chr_baum_init },
3078 #ifdef HAVE_CHARDEV_TTY
3079 { .name = "tty", .open = qemu_chr_open_tty },
3080 { .name = "serial", .open = qemu_chr_open_tty },
3081 { .name = "pty", .open = qemu_chr_open_pty },
3083 #ifdef HAVE_CHARDEV_PARPORT
3084 { .name = "parallel", .open = qemu_chr_open_pp },
3085 { .name = "parport", .open = qemu_chr_open_pp },
3088 { .name = "spicevmc", .open = qemu_chr_open_spice },
3089 #if SPICE_SERVER_VERSION >= 0x000c02
3090 { .name = "spiceport", .open = qemu_chr_open_spice_port },
3095 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3096 void (*init)(struct CharDriverState *s),
3099 CharDriverState *chr;
3102 if (qemu_opts_id(opts) == NULL) {
3103 error_setg(errp, "chardev: no id specified");
3107 if (qemu_opt_get(opts, "backend") == NULL) {
3108 error_setg(errp, "chardev: \"%s\" missing backend",
3109 qemu_opts_id(opts));
3112 for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
3113 if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
3116 if (i == ARRAY_SIZE(backend_table)) {
3117 error_setg(errp, "chardev: backend \"%s\" not found",
3118 qemu_opt_get(opts, "backend"));
3122 chr = backend_table[i].open(opts);
3124 error_setg(errp, "chardev: opening backend \"%s\" failed",
3125 qemu_opt_get(opts, "backend"));
3130 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3132 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3134 if (qemu_opt_get_bool(opts, "mux", 0)) {
3135 CharDriverState *base = chr;
3136 int len = strlen(qemu_opts_id(opts)) + 6;
3137 base->label = g_malloc(len);
3138 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3139 chr = qemu_chr_open_mux(base);
3140 chr->filename = base->filename;
3141 chr->avail_connections = MAX_MUX;
3142 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3144 chr->avail_connections = 1;
3146 chr->label = g_strdup(qemu_opts_id(opts));
3151 qemu_opts_del(opts);
3155 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3158 CharDriverState *chr;
3162 if (strstart(filename, "chardev:", &p)) {
3163 return qemu_chr_find(p);
3166 opts = qemu_chr_parse_compat(label, filename);
3170 chr = qemu_chr_new_from_opts(opts, init, &err);
3171 if (error_is_set(&err)) {
3172 fprintf(stderr, "%s\n", error_get_pretty(err));
3175 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3176 monitor_init(chr, MONITOR_USE_READLINE);
3181 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3183 if (chr->chr_set_echo) {
3184 chr->chr_set_echo(chr, echo);
3188 void qemu_chr_fe_open(struct CharDriverState *chr)
3190 if (chr->chr_guest_open) {
3191 chr->chr_guest_open(chr);
3195 void qemu_chr_fe_close(struct CharDriverState *chr)
3197 if (chr->chr_guest_close) {
3198 chr->chr_guest_close(chr);
3202 void qemu_chr_delete(CharDriverState *chr)
3204 QTAILQ_REMOVE(&chardevs, chr, next);
3205 if (chr->chr_close) {
3206 chr->chr_close(chr);
3208 g_free(chr->filename);
3211 qemu_opts_del(chr->opts);
3216 ChardevInfoList *qmp_query_chardev(Error **errp)
3218 ChardevInfoList *chr_list = NULL;
3219 CharDriverState *chr;
3221 QTAILQ_FOREACH(chr, &chardevs, next) {
3222 ChardevInfoList *info = g_malloc0(sizeof(*info));
3223 info->value = g_malloc0(sizeof(*info->value));
3224 info->value->label = g_strdup(chr->label);
3225 info->value->filename = g_strdup(chr->filename);
3227 info->next = chr_list;
3234 CharDriverState *qemu_chr_find(const char *name)
3236 CharDriverState *chr;
3238 QTAILQ_FOREACH(chr, &chardevs, next) {
3239 if (strcmp(chr->label, name) != 0)
3246 /* Get a character (serial) device interface. */
3247 CharDriverState *qemu_char_get_next_serial(void)
3249 static int next_serial;
3251 /* FIXME: This function needs to go away: use chardev properties! */
3252 return serial_hds[next_serial++];
3255 QemuOptsList qemu_chardev_opts = {
3257 .implied_opt_name = "backend",
3258 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3262 .type = QEMU_OPT_STRING,
3265 .type = QEMU_OPT_STRING,
3268 .type = QEMU_OPT_STRING,
3271 .type = QEMU_OPT_STRING,
3273 .name = "localaddr",
3274 .type = QEMU_OPT_STRING,
3276 .name = "localport",
3277 .type = QEMU_OPT_STRING,
3280 .type = QEMU_OPT_NUMBER,
3283 .type = QEMU_OPT_BOOL,
3286 .type = QEMU_OPT_BOOL,
3289 .type = QEMU_OPT_BOOL,
3292 .type = QEMU_OPT_BOOL,
3295 .type = QEMU_OPT_BOOL,
3298 .type = QEMU_OPT_BOOL,
3301 .type = QEMU_OPT_NUMBER,
3304 .type = QEMU_OPT_NUMBER,
3307 .type = QEMU_OPT_NUMBER,
3310 .type = QEMU_OPT_NUMBER,
3313 .type = QEMU_OPT_BOOL,
3316 .type = QEMU_OPT_BOOL,
3319 .type = QEMU_OPT_STRING,
3322 .type = QEMU_OPT_NUMBER,
3325 .type = QEMU_OPT_SIZE,
3327 { /* end of list */ }
3333 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3338 error_setg(errp, "input file not supported");
3342 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3343 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3344 if (out == INVALID_HANDLE_VALUE) {
3345 error_setg(errp, "open %s failed", file->out);
3348 return qemu_chr_open_win_file(out);
3351 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3354 return qemu_chr_open_win_path(serial->device);
3357 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3360 error_setg(errp, "character device backend type 'parallel' not supported");
3366 static int qmp_chardev_open_file_source(char *src, int flags,
3371 TFR(fd = qemu_open(src, flags, 0666));
3373 error_setg(errp, "open %s: %s", src, strerror(errno));
3378 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3380 int flags, in = -1, out = -1;
3382 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3383 out = qmp_chardev_open_file_source(file->out, flags, errp);
3384 if (error_is_set(errp)) {
3390 in = qmp_chardev_open_file_source(file->in, flags, errp);
3391 if (error_is_set(errp)) {
3397 return qemu_chr_open_fd(in, out);
3400 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3403 #ifdef HAVE_CHARDEV_TTY
3406 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3407 if (error_is_set(errp)) {
3410 socket_set_nonblock(fd);
3411 return qemu_chr_open_tty_fd(fd);
3413 error_setg(errp, "character device backend type 'serial' not supported");
3418 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3421 #ifdef HAVE_CHARDEV_PARPORT
3424 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3425 if (error_is_set(errp)) {
3428 return qemu_chr_open_pp_fd(fd);
3430 error_setg(errp, "character device backend type 'parallel' not supported");
3437 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3440 SocketAddress *addr = sock->addr;
3441 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3442 bool is_listen = sock->has_server ? sock->server : true;
3443 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3444 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3448 fd = socket_listen(addr, errp);
3450 fd = socket_connect(addr, errp, NULL, NULL);
3452 if (error_is_set(errp)) {
3455 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3456 is_telnet, is_waitconnect, errp);
3459 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3462 ChardevReturn *ret = g_new0(ChardevReturn, 1);
3463 CharDriverState *chr = NULL;
3465 chr = qemu_chr_find(id);
3467 error_setg(errp, "Chardev '%s' already exists", id);
3472 switch (backend->kind) {
3473 case CHARDEV_BACKEND_KIND_FILE:
3474 chr = qmp_chardev_open_file(backend->file, errp);
3476 case CHARDEV_BACKEND_KIND_SERIAL:
3477 chr = qmp_chardev_open_serial(backend->serial, errp);
3479 case CHARDEV_BACKEND_KIND_PARALLEL:
3480 chr = qmp_chardev_open_parallel(backend->parallel, errp);
3482 case CHARDEV_BACKEND_KIND_SOCKET:
3483 chr = qmp_chardev_open_socket(backend->socket, errp);
3485 #ifdef HAVE_CHARDEV_TTY
3486 case CHARDEV_BACKEND_KIND_PTY:
3488 /* qemu_chr_open_pty sets "path" in opts */
3490 opts = qemu_opts_create_nofail(qemu_find_opts("chardev"));
3491 chr = qemu_chr_open_pty(opts);
3492 ret->pty = g_strdup(qemu_opt_get(opts, "path"));
3493 ret->has_pty = true;
3494 qemu_opts_del(opts);
3498 case CHARDEV_BACKEND_KIND_NULL:
3499 chr = qemu_chr_open_null(NULL);
3502 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3506 if (chr == NULL && !error_is_set(errp)) {
3507 error_setg(errp, "Failed to create chardev");
3510 chr->label = g_strdup(id);
3511 chr->avail_connections = 1;
3512 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3520 void qmp_chardev_remove(const char *id, Error **errp)
3522 CharDriverState *chr;
3524 chr = qemu_chr_find(id);
3526 error_setg(errp, "Chardev '%s' not found", id);
3529 if (chr->chr_can_read || chr->chr_read ||
3530 chr->chr_event || chr->handler_opaque) {
3531 error_setg(errp, "Chardev '%s' is busy", id);
3534 qemu_chr_delete(chr);