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_ioctl(CharDriverState *s, int cmd, void *arg)
147 return s->chr_ioctl(s, cmd, arg);
150 int qemu_chr_be_can_write(CharDriverState *s)
152 if (!s->chr_can_read)
154 return s->chr_can_read(s->handler_opaque);
157 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
160 s->chr_read(s->handler_opaque, buf, len);
164 int qemu_chr_fe_get_msgfd(CharDriverState *s)
166 return s->get_msgfd ? s->get_msgfd(s) : -1;
169 int qemu_chr_add_client(CharDriverState *s, int fd)
171 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
174 void qemu_chr_accept_input(CharDriverState *s)
176 if (s->chr_accept_input)
177 s->chr_accept_input(s);
181 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
183 char buf[READ_BUF_LEN];
186 vsnprintf(buf, sizeof(buf), fmt, ap);
187 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
191 void qemu_chr_add_handlers(CharDriverState *s,
192 IOCanReadHandler *fd_can_read,
193 IOReadHandler *fd_read,
194 IOEventHandler *fd_event,
197 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
198 /* chr driver being released. */
199 ++s->avail_connections;
201 s->chr_can_read = fd_can_read;
202 s->chr_read = fd_read;
203 s->chr_event = fd_event;
204 s->handler_opaque = opaque;
205 if (s->chr_update_read_handler)
206 s->chr_update_read_handler(s);
208 /* We're connecting to an already opened device, so let's make sure we
209 also get the open event */
211 qemu_chr_generic_open(s);
215 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
220 static CharDriverState *qemu_chr_open_null(QemuOpts *opts)
222 CharDriverState *chr;
224 chr = g_malloc0(sizeof(CharDriverState));
225 chr->chr_write = null_chr_write;
229 /* MUX driver for serial I/O splitting */
231 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
232 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
234 IOCanReadHandler *chr_can_read[MAX_MUX];
235 IOReadHandler *chr_read[MAX_MUX];
236 IOEventHandler *chr_event[MAX_MUX];
237 void *ext_opaque[MAX_MUX];
238 CharDriverState *drv;
243 /* Intermediate input buffer allows to catch escape sequences even if the
244 currently active device is not accepting any input - but only until it
246 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
251 int64_t timestamps_start;
255 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
257 MuxDriver *d = chr->opaque;
259 if (!d->timestamps) {
260 ret = d->drv->chr_write(d->drv, buf, len);
265 for (i = 0; i < len; i++) {
271 ti = qemu_get_clock_ms(rt_clock);
272 if (d->timestamps_start == -1)
273 d->timestamps_start = ti;
274 ti -= d->timestamps_start;
276 snprintf(buf1, sizeof(buf1),
277 "[%02d:%02d:%02d.%03d] ",
282 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
285 ret += d->drv->chr_write(d->drv, buf+i, 1);
286 if (buf[i] == '\n') {
294 static const char * const mux_help[] = {
295 "% h print this help\n\r",
296 "% x exit emulator\n\r",
297 "% s save disk data back to file (if -snapshot)\n\r",
298 "% t toggle console timestamps\n\r"
299 "% b send break (magic sysrq)\n\r",
300 "% c switch between console and monitor\n\r",
305 int term_escape_char = 0x01; /* ctrl-a is used for escape */
306 static void mux_print_help(CharDriverState *chr)
309 char ebuf[15] = "Escape-Char";
310 char cbuf[50] = "\n\r";
312 if (term_escape_char > 0 && term_escape_char < 26) {
313 snprintf(cbuf, sizeof(cbuf), "\n\r");
314 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
316 snprintf(cbuf, sizeof(cbuf),
317 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
320 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
321 for (i = 0; mux_help[i] != NULL; i++) {
322 for (j=0; mux_help[i][j] != '\0'; j++) {
323 if (mux_help[i][j] == '%')
324 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
326 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
331 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
333 if (d->chr_event[mux_nr])
334 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
337 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
339 if (d->term_got_escape) {
340 d->term_got_escape = 0;
341 if (ch == term_escape_char)
350 const char *term = "QEMU: Terminated\n\r";
351 chr->chr_write(chr,(uint8_t *)term,strlen(term));
359 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
362 /* Switch to the next registered device */
363 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
365 if (d->focus >= d->mux_cnt)
367 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
370 d->timestamps = !d->timestamps;
371 d->timestamps_start = -1;
375 } else if (ch == term_escape_char) {
376 d->term_got_escape = 1;
384 static void mux_chr_accept_input(CharDriverState *chr)
386 MuxDriver *d = chr->opaque;
389 while (d->prod[m] != d->cons[m] &&
390 d->chr_can_read[m] &&
391 d->chr_can_read[m](d->ext_opaque[m])) {
392 d->chr_read[m](d->ext_opaque[m],
393 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
397 static int mux_chr_can_read(void *opaque)
399 CharDriverState *chr = opaque;
400 MuxDriver *d = chr->opaque;
403 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
405 if (d->chr_can_read[m])
406 return d->chr_can_read[m](d->ext_opaque[m]);
410 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
412 CharDriverState *chr = opaque;
413 MuxDriver *d = chr->opaque;
417 mux_chr_accept_input (opaque);
419 for(i = 0; i < size; i++)
420 if (mux_proc_byte(chr, d, buf[i])) {
421 if (d->prod[m] == d->cons[m] &&
422 d->chr_can_read[m] &&
423 d->chr_can_read[m](d->ext_opaque[m]))
424 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
426 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
430 static void mux_chr_event(void *opaque, int event)
432 CharDriverState *chr = opaque;
433 MuxDriver *d = chr->opaque;
436 /* Send the event to all registered listeners */
437 for (i = 0; i < d->mux_cnt; i++)
438 mux_chr_send_event(d, i, event);
441 static void mux_chr_update_read_handler(CharDriverState *chr)
443 MuxDriver *d = chr->opaque;
445 if (d->mux_cnt >= MAX_MUX) {
446 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
449 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
450 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
451 d->chr_read[d->mux_cnt] = chr->chr_read;
452 d->chr_event[d->mux_cnt] = chr->chr_event;
453 /* Fix up the real driver with mux routines */
454 if (d->mux_cnt == 0) {
455 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
458 if (d->focus != -1) {
459 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
461 d->focus = d->mux_cnt;
463 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
466 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
468 CharDriverState *chr;
471 chr = g_malloc0(sizeof(CharDriverState));
472 d = g_malloc0(sizeof(MuxDriver));
477 chr->chr_write = mux_chr_write;
478 chr->chr_update_read_handler = mux_chr_update_read_handler;
479 chr->chr_accept_input = mux_chr_accept_input;
480 /* Frontend guest-open / -close notification is not support with muxes */
481 chr->chr_guest_open = NULL;
482 chr->chr_guest_close = NULL;
484 /* Muxes are always open on creation */
485 qemu_chr_generic_open(chr);
492 int send_all(int fd, const void *buf, int len1)
498 ret = send(fd, buf, len, 0);
500 errno = WSAGetLastError();
501 if (errno != WSAEWOULDBLOCK) {
504 } else if (ret == 0) {
516 int send_all(int fd, const void *_buf, int len1)
519 const uint8_t *buf = _buf;
523 ret = write(fd, buf, len);
525 if (errno != EINTR && errno != EAGAIN)
527 } else if (ret == 0) {
537 int recv_all(int fd, void *_buf, int len1, bool single_read)
543 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
545 if (errno != EINTR && errno != EAGAIN) {
562 typedef struct IOWatchPoll
567 IOCanReadHandler *fd_can_read;
570 QTAILQ_ENTRY(IOWatchPoll) node;
573 static QTAILQ_HEAD(, IOWatchPoll) io_watch_poll_list =
574 QTAILQ_HEAD_INITIALIZER(io_watch_poll_list);
576 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
580 QTAILQ_FOREACH(i, &io_watch_poll_list, node) {
581 if (i->src == source) {
589 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
591 IOWatchPoll *iwp = io_watch_poll_from_source(source);
593 iwp->max_size = iwp->fd_can_read(iwp->opaque);
594 if (iwp->max_size == 0) {
598 return g_io_watch_funcs.prepare(source, timeout_);
601 static gboolean io_watch_poll_check(GSource *source)
603 IOWatchPoll *iwp = io_watch_poll_from_source(source);
605 if (iwp->max_size == 0) {
609 return g_io_watch_funcs.check(source);
612 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
615 return g_io_watch_funcs.dispatch(source, callback, user_data);
618 static void io_watch_poll_finalize(GSource *source)
620 IOWatchPoll *iwp = io_watch_poll_from_source(source);
621 QTAILQ_REMOVE(&io_watch_poll_list, iwp, node);
622 g_io_watch_funcs.finalize(source);
625 static GSourceFuncs io_watch_poll_funcs = {
626 .prepare = io_watch_poll_prepare,
627 .check = io_watch_poll_check,
628 .dispatch = io_watch_poll_dispatch,
629 .finalize = io_watch_poll_finalize,
632 /* Can only be used for read */
633 static guint io_add_watch_poll(GIOChannel *channel,
634 IOCanReadHandler *fd_can_read,
642 src = g_io_create_watch(channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
643 g_source_set_funcs(src, &io_watch_poll_funcs);
644 g_source_set_callback(src, (GSourceFunc)fd_read, user_data, NULL);
645 tag = g_source_attach(src, NULL);
648 iwp = g_malloc0(sizeof(*iwp));
651 iwp->fd_can_read = fd_can_read;
652 iwp->opaque = user_data;
654 QTAILQ_INSERT_HEAD(&io_watch_poll_list, iwp, node);
660 static GIOChannel *io_channel_from_fd(int fd)
668 chan = g_io_channel_unix_new(fd);
670 g_io_channel_set_encoding(chan, NULL, NULL);
671 g_io_channel_set_buffered(chan, FALSE);
677 static GIOChannel *io_channel_from_socket(int fd)
686 chan = g_io_channel_win32_new_socket(fd);
688 chan = g_io_channel_unix_new(fd);
691 g_io_channel_set_encoding(chan, NULL, NULL);
692 g_io_channel_set_buffered(chan, FALSE);
697 static int io_channel_send_all(GIOChannel *fd, const void *_buf, int len1)
702 const uint8_t *buf = _buf;
706 status = g_io_channel_write_chars(fd, (const gchar *)buf, len,
707 &bytes_written, NULL);
708 if (status != G_IO_STATUS_NORMAL) {
709 if (status == G_IO_STATUS_AGAIN) {
716 } else if (status == G_IO_STATUS_EOF) {
719 buf += bytes_written;
720 len -= bytes_written;
728 typedef struct FDCharDriver {
729 CharDriverState *chr;
730 GIOChannel *fd_in, *fd_out;
733 QTAILQ_ENTRY(FDCharDriver) node;
736 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
738 FDCharDriver *s = chr->opaque;
740 return io_channel_send_all(s->fd_out, buf, len);
743 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
745 CharDriverState *chr = opaque;
746 FDCharDriver *s = chr->opaque;
748 uint8_t buf[READ_BUF_LEN];
753 if (len > s->max_size) {
760 status = g_io_channel_read_chars(chan, (gchar *)buf,
761 len, &bytes_read, NULL);
762 if (status == G_IO_STATUS_EOF) {
763 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
766 if (status == G_IO_STATUS_NORMAL) {
767 qemu_chr_be_write(chr, buf, bytes_read);
773 static int fd_chr_read_poll(void *opaque)
775 CharDriverState *chr = opaque;
776 FDCharDriver *s = chr->opaque;
778 s->max_size = qemu_chr_be_can_write(chr);
782 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
784 FDCharDriver *s = chr->opaque;
785 return g_io_create_watch(s->fd_out, cond);
788 static void fd_chr_update_read_handler(CharDriverState *chr)
790 FDCharDriver *s = chr->opaque;
793 g_source_remove(s->fd_in_tag);
797 s->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll, fd_chr_read, chr);
801 static void fd_chr_close(struct CharDriverState *chr)
803 FDCharDriver *s = chr->opaque;
806 g_source_remove(s->fd_in_tag);
811 g_io_channel_unref(s->fd_in);
814 g_io_channel_unref(s->fd_out);
818 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
821 /* open a character device to a unix fd */
822 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
824 CharDriverState *chr;
827 chr = g_malloc0(sizeof(CharDriverState));
828 s = g_malloc0(sizeof(FDCharDriver));
829 s->fd_in = io_channel_from_fd(fd_in);
830 s->fd_out = io_channel_from_fd(fd_out);
831 fcntl(fd_out, F_SETFL, O_NONBLOCK);
834 chr->chr_add_watch = fd_chr_add_watch;
835 chr->chr_write = fd_chr_write;
836 chr->chr_update_read_handler = fd_chr_update_read_handler;
837 chr->chr_close = fd_chr_close;
839 qemu_chr_generic_open(chr);
844 static CharDriverState *qemu_chr_open_file_out(QemuOpts *opts)
848 TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
849 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
853 return qemu_chr_open_fd(-1, fd_out);
856 static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)
859 char filename_in[256], filename_out[256];
860 const char *filename = qemu_opt_get(opts, "path");
862 if (filename == NULL) {
863 fprintf(stderr, "chardev: pipe: no filename given\n");
867 snprintf(filename_in, 256, "%s.in", filename);
868 snprintf(filename_out, 256, "%s.out", filename);
869 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
870 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
871 if (fd_in < 0 || fd_out < 0) {
876 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
881 return qemu_chr_open_fd(fd_in, fd_out);
884 /* init terminal so that we can grab keys */
885 static struct termios oldtty;
886 static int old_fd0_flags;
887 static bool stdio_allow_signal;
889 static void term_exit(void)
891 tcsetattr (0, TCSANOW, &oldtty);
892 fcntl(0, F_SETFL, old_fd0_flags);
895 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
901 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
902 |INLCR|IGNCR|ICRNL|IXON);
903 tty.c_oflag |= OPOST;
904 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
905 tty.c_cflag &= ~(CSIZE|PARENB);
910 /* if graphical mode, we allow Ctrl-C handling */
911 if (!stdio_allow_signal)
912 tty.c_lflag &= ~ISIG;
914 tcsetattr (0, TCSANOW, &tty);
917 static void qemu_chr_close_stdio(struct CharDriverState *chr)
923 static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)
925 CharDriverState *chr;
927 if (is_daemonized()) {
928 error_report("cannot use stdio with -daemonize");
931 old_fd0_flags = fcntl(0, F_GETFL);
932 tcgetattr (0, &oldtty);
933 fcntl(0, F_SETFL, O_NONBLOCK);
936 chr = qemu_chr_open_fd(0, 1);
937 chr->chr_close = qemu_chr_close_stdio;
938 chr->chr_set_echo = qemu_chr_set_echo_stdio;
939 stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
940 display_type != DT_NOGRAPHIC);
941 qemu_chr_fe_set_echo(chr, false);
947 /* Once Solaris has openpty(), this is going to be removed. */
948 static int openpty(int *amaster, int *aslave, char *name,
949 struct termios *termp, struct winsize *winp)
952 int mfd = -1, sfd = -1;
954 *amaster = *aslave = -1;
956 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
960 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
963 if ((slave = ptsname(mfd)) == NULL)
966 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
969 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
970 (termp != NULL && tcgetattr(sfd, termp) < 0))
978 ioctl(sfd, TIOCSWINSZ, winp);
989 static void cfmakeraw (struct termios *termios_p)
991 termios_p->c_iflag &=
992 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
993 termios_p->c_oflag &= ~OPOST;
994 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
995 termios_p->c_cflag &= ~(CSIZE|PARENB);
996 termios_p->c_cflag |= CS8;
998 termios_p->c_cc[VMIN] = 0;
999 termios_p->c_cc[VTIME] = 0;
1003 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1004 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1005 || defined(__GLIBC__)
1007 #define HAVE_CHARDEV_TTY 1
1018 static void pty_chr_update_read_handler(CharDriverState *chr);
1019 static void pty_chr_state(CharDriverState *chr, int connected);
1021 static gboolean pty_chr_timer(gpointer opaque)
1023 struct CharDriverState *chr = opaque;
1024 PtyCharDriver *s = chr->opaque;
1030 /* If we arrive here without polling being cleared due
1031 * read returning -EIO, then we are (re-)connected */
1032 pty_chr_state(chr, 1);
1037 pty_chr_update_read_handler(chr);
1043 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1045 PtyCharDriver *s = chr->opaque;
1048 g_source_remove(s->timer_tag);
1053 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1055 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1059 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1061 PtyCharDriver *s = chr->opaque;
1063 if (!s->connected) {
1064 /* guest sends data, check for (re-)connect */
1065 pty_chr_update_read_handler(chr);
1068 return io_channel_send_all(s->fd, buf, len);
1071 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1073 PtyCharDriver *s = chr->opaque;
1074 return g_io_create_watch(s->fd, cond);
1077 static int pty_chr_read_poll(void *opaque)
1079 CharDriverState *chr = opaque;
1080 PtyCharDriver *s = chr->opaque;
1082 s->read_bytes = qemu_chr_be_can_write(chr);
1083 return s->read_bytes;
1086 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1088 CharDriverState *chr = opaque;
1089 PtyCharDriver *s = chr->opaque;
1091 uint8_t buf[READ_BUF_LEN];
1095 if (len > s->read_bytes)
1096 len = s->read_bytes;
1099 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1100 if (status != G_IO_STATUS_NORMAL) {
1101 pty_chr_state(chr, 0);
1104 pty_chr_state(chr, 1);
1105 qemu_chr_be_write(chr, buf, size);
1110 static void pty_chr_update_read_handler(CharDriverState *chr)
1112 PtyCharDriver *s = chr->opaque;
1115 g_source_remove(s->fd_tag);
1118 s->fd_tag = io_add_watch_poll(s->fd, pty_chr_read_poll, pty_chr_read, chr);
1121 * Short timeout here: just need wait long enougth that qemu makes
1122 * it through the poll loop once. When reconnected we want a
1123 * short timeout so we notice it almost instantly. Otherwise
1124 * read() gives us -EIO instantly, making pty_chr_state() reset the
1125 * timeout to the normal (much longer) poll interval before the
1128 pty_chr_rearm_timer(chr, 10);
1131 static void pty_chr_state(CharDriverState *chr, int connected)
1133 PtyCharDriver *s = chr->opaque;
1136 g_source_remove(s->fd_tag);
1140 /* (re-)connect poll interval for idle guests: once per second.
1141 * We check more frequently in case the guests sends data to
1142 * the virtual device linked to our pty. */
1143 pty_chr_rearm_timer(chr, 1000);
1146 qemu_chr_generic_open(chr);
1152 static void pty_chr_close(struct CharDriverState *chr)
1154 PtyCharDriver *s = chr->opaque;
1158 g_source_remove(s->fd_tag);
1160 fd = g_io_channel_unix_get_fd(s->fd);
1161 g_io_channel_unref(s->fd);
1164 g_source_remove(s->timer_tag);
1167 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1170 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
1172 CharDriverState *chr;
1176 int master_fd, slave_fd, len;
1177 #if defined(__OpenBSD__) || defined(__DragonFly__)
1178 char pty_name[PATH_MAX];
1179 #define q_ptsname(x) pty_name
1181 char *pty_name = NULL;
1182 #define q_ptsname(x) ptsname(x)
1185 if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1189 /* Set raw attributes on the pty. */
1190 tcgetattr(slave_fd, &tty);
1192 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1195 chr = g_malloc0(sizeof(CharDriverState));
1197 len = strlen(q_ptsname(master_fd)) + 5;
1198 chr->filename = g_malloc(len);
1199 snprintf(chr->filename, len, "pty:%s", q_ptsname(master_fd));
1200 qemu_opt_set(opts, "path", q_ptsname(master_fd));
1202 label = qemu_opts_id(opts);
1203 fprintf(stderr, "char device redirected to %s%s%s%s\n",
1204 q_ptsname(master_fd),
1205 label ? " (label " : "",
1209 s = g_malloc0(sizeof(PtyCharDriver));
1211 chr->chr_write = pty_chr_write;
1212 chr->chr_update_read_handler = pty_chr_update_read_handler;
1213 chr->chr_close = pty_chr_close;
1214 chr->chr_add_watch = pty_chr_add_watch;
1216 s->fd = io_channel_from_fd(master_fd);
1222 static void tty_serial_init(int fd, int speed,
1223 int parity, int data_bits, int stop_bits)
1229 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1230 speed, parity, data_bits, stop_bits);
1232 tcgetattr (fd, &tty);
1234 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1235 speed = speed * 10 / 11;
1252 /* Non-Posix values follow. They may be unsupported on some systems. */
1254 check_speed(115200);
1256 check_speed(230400);
1259 check_speed(460800);
1262 check_speed(500000);
1265 check_speed(576000);
1268 check_speed(921600);
1271 check_speed(1000000);
1274 check_speed(1152000);
1277 check_speed(1500000);
1280 check_speed(2000000);
1283 check_speed(2500000);
1286 check_speed(3000000);
1289 check_speed(3500000);
1292 check_speed(4000000);
1297 cfsetispeed(&tty, spd);
1298 cfsetospeed(&tty, spd);
1300 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1301 |INLCR|IGNCR|ICRNL|IXON);
1302 tty.c_oflag |= OPOST;
1303 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1304 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1325 tty.c_cflag |= PARENB;
1328 tty.c_cflag |= PARENB | PARODD;
1332 tty.c_cflag |= CSTOPB;
1334 tcsetattr (fd, TCSANOW, &tty);
1337 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1339 FDCharDriver *s = chr->opaque;
1342 case CHR_IOCTL_SERIAL_SET_PARAMS:
1344 QEMUSerialSetParams *ssp = arg;
1345 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1346 ssp->speed, ssp->parity,
1347 ssp->data_bits, ssp->stop_bits);
1350 case CHR_IOCTL_SERIAL_SET_BREAK:
1352 int enable = *(int *)arg;
1354 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1358 case CHR_IOCTL_SERIAL_GET_TIOCM:
1361 int *targ = (int *)arg;
1362 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1364 if (sarg & TIOCM_CTS)
1365 *targ |= CHR_TIOCM_CTS;
1366 if (sarg & TIOCM_CAR)
1367 *targ |= CHR_TIOCM_CAR;
1368 if (sarg & TIOCM_DSR)
1369 *targ |= CHR_TIOCM_DSR;
1370 if (sarg & TIOCM_RI)
1371 *targ |= CHR_TIOCM_RI;
1372 if (sarg & TIOCM_DTR)
1373 *targ |= CHR_TIOCM_DTR;
1374 if (sarg & TIOCM_RTS)
1375 *targ |= CHR_TIOCM_RTS;
1378 case CHR_IOCTL_SERIAL_SET_TIOCM:
1380 int sarg = *(int *)arg;
1382 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1383 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1384 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1385 if (sarg & CHR_TIOCM_CTS)
1387 if (sarg & CHR_TIOCM_CAR)
1389 if (sarg & CHR_TIOCM_DSR)
1391 if (sarg & CHR_TIOCM_RI)
1393 if (sarg & CHR_TIOCM_DTR)
1395 if (sarg & CHR_TIOCM_RTS)
1397 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1406 static void qemu_chr_close_tty(CharDriverState *chr)
1408 FDCharDriver *s = chr->opaque;
1412 fd = g_io_channel_unix_get_fd(s->fd_in);
1422 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1424 CharDriverState *chr;
1426 tty_serial_init(fd, 115200, 'N', 8, 1);
1427 chr = qemu_chr_open_fd(fd, fd);
1428 chr->chr_ioctl = tty_serial_ioctl;
1429 chr->chr_close = qemu_chr_close_tty;
1433 static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
1435 const char *filename = qemu_opt_get(opts, "path");
1438 TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
1442 return qemu_chr_open_tty_fd(fd);
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 CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1870 return qemu_chr_open_win_path(qemu_opt_get(opts, "path"));
1873 static int win_chr_pipe_poll(void *opaque)
1875 CharDriverState *chr = opaque;
1876 WinCharState *s = chr->opaque;
1879 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1882 win_chr_read_poll(chr);
1889 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1891 WinCharState *s = chr->opaque;
1899 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1901 fprintf(stderr, "Failed CreateEvent\n");
1904 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1906 fprintf(stderr, "Failed CreateEvent\n");
1910 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1911 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1912 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1914 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1915 if (s->hcom == INVALID_HANDLE_VALUE) {
1916 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1921 ZeroMemory(&ov, sizeof(ov));
1922 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1923 ret = ConnectNamedPipe(s->hcom, &ov);
1925 fprintf(stderr, "Failed ConnectNamedPipe\n");
1929 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1931 fprintf(stderr, "Failed GetOverlappedResult\n");
1933 CloseHandle(ov.hEvent);
1940 CloseHandle(ov.hEvent);
1943 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1952 static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
1954 const char *filename = qemu_opt_get(opts, "path");
1955 CharDriverState *chr;
1958 chr = g_malloc0(sizeof(CharDriverState));
1959 s = g_malloc0(sizeof(WinCharState));
1961 chr->chr_write = win_chr_write;
1962 chr->chr_close = win_chr_close;
1964 if (win_chr_pipe_init(chr, filename) < 0) {
1969 qemu_chr_generic_open(chr);
1973 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1975 CharDriverState *chr;
1978 chr = g_malloc0(sizeof(CharDriverState));
1979 s = g_malloc0(sizeof(WinCharState));
1982 chr->chr_write = win_chr_write;
1983 qemu_chr_generic_open(chr);
1987 static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
1989 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1992 static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
1994 const char *file_out = qemu_opt_get(opts, "path");
1997 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1998 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1999 if (fd_out == INVALID_HANDLE_VALUE) {
2003 return qemu_chr_open_win_file(fd_out);
2006 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2008 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2015 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2025 static void win_stdio_wait_func(void *opaque)
2027 CharDriverState *chr = opaque;
2028 WinStdioCharState *stdio = chr->opaque;
2029 INPUT_RECORD buf[4];
2034 ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
2038 /* Avoid error storm */
2039 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2043 for (i = 0; i < dwSize; i++) {
2044 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2046 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2048 if (kev->uChar.AsciiChar != 0) {
2049 for (j = 0; j < kev->wRepeatCount; j++) {
2050 if (qemu_chr_be_can_write(chr)) {
2051 uint8_t c = kev->uChar.AsciiChar;
2052 qemu_chr_be_write(chr, &c, 1);
2060 static DWORD WINAPI win_stdio_thread(LPVOID param)
2062 CharDriverState *chr = param;
2063 WinStdioCharState *stdio = chr->opaque;
2069 /* Wait for one byte */
2070 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2072 /* Exit in case of error, continue if nothing read */
2080 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2081 if (stdio->win_stdio_buf == '\r') {
2085 /* Signal the main thread and wait until the byte was eaten */
2086 if (!SetEvent(stdio->hInputReadyEvent)) {
2089 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2095 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2099 static void win_stdio_thread_wait_func(void *opaque)
2101 CharDriverState *chr = opaque;
2102 WinStdioCharState *stdio = chr->opaque;
2104 if (qemu_chr_be_can_write(chr)) {
2105 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2108 SetEvent(stdio->hInputDoneEvent);
2111 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2113 WinStdioCharState *stdio = chr->opaque;
2116 GetConsoleMode(stdio->hStdIn, &dwMode);
2119 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2121 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2125 static void win_stdio_close(CharDriverState *chr)
2127 WinStdioCharState *stdio = chr->opaque;
2129 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2130 CloseHandle(stdio->hInputReadyEvent);
2132 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2133 CloseHandle(stdio->hInputDoneEvent);
2135 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2136 TerminateThread(stdio->hInputThread, 0);
2139 g_free(chr->opaque);
2143 static CharDriverState *qemu_chr_open_win_stdio(QemuOpts *opts)
2145 CharDriverState *chr;
2146 WinStdioCharState *stdio;
2150 chr = g_malloc0(sizeof(CharDriverState));
2151 stdio = g_malloc0(sizeof(WinStdioCharState));
2153 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2154 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2155 fprintf(stderr, "cannot open stdio: invalid handle\n");
2159 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2161 chr->opaque = stdio;
2162 chr->chr_write = win_stdio_write;
2163 chr->chr_close = win_stdio_close;
2166 if (qemu_add_wait_object(stdio->hStdIn,
2167 win_stdio_wait_func, chr)) {
2168 fprintf(stderr, "qemu_add_wait_object: failed\n");
2173 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2174 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2175 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2178 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2179 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2180 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2181 fprintf(stderr, "cannot create stdio thread or event\n");
2184 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2185 win_stdio_thread_wait_func, chr)) {
2186 fprintf(stderr, "qemu_add_wait_object: failed\n");
2190 dwMode |= ENABLE_LINE_INPUT;
2193 /* set the terminal in raw mode */
2194 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2195 dwMode |= ENABLE_PROCESSED_INPUT;
2198 SetConsoleMode(stdio->hStdIn, dwMode);
2200 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2201 qemu_chr_fe_set_echo(chr, false);
2205 #endif /* !_WIN32 */
2208 /***********************************************************/
2209 /* UDP Net console */
2215 uint8_t buf[READ_BUF_LEN];
2221 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2223 NetCharDriver *s = chr->opaque;
2224 gsize bytes_written;
2227 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2228 if (status == G_IO_STATUS_EOF) {
2230 } else if (status != G_IO_STATUS_NORMAL) {
2234 return bytes_written;
2237 static int udp_chr_read_poll(void *opaque)
2239 CharDriverState *chr = opaque;
2240 NetCharDriver *s = chr->opaque;
2242 s->max_size = qemu_chr_be_can_write(chr);
2244 /* If there were any stray characters in the queue process them
2247 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2248 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2250 s->max_size = qemu_chr_be_can_write(chr);
2255 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2257 CharDriverState *chr = opaque;
2258 NetCharDriver *s = chr->opaque;
2259 gsize bytes_read = 0;
2262 if (s->max_size == 0)
2264 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2266 s->bufcnt = bytes_read;
2267 s->bufptr = s->bufcnt;
2268 if (status != G_IO_STATUS_NORMAL) {
2273 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2274 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2276 s->max_size = qemu_chr_be_can_write(chr);
2282 static void udp_chr_update_read_handler(CharDriverState *chr)
2284 NetCharDriver *s = chr->opaque;
2287 g_source_remove(s->tag);
2292 s->tag = io_add_watch_poll(s->chan, udp_chr_read_poll, udp_chr_read, chr);
2296 static void udp_chr_close(CharDriverState *chr)
2298 NetCharDriver *s = chr->opaque;
2300 g_source_remove(s->tag);
2303 g_io_channel_unref(s->chan);
2307 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2310 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2312 CharDriverState *chr = NULL;
2313 NetCharDriver *s = NULL;
2314 Error *local_err = NULL;
2317 chr = g_malloc0(sizeof(CharDriverState));
2318 s = g_malloc0(sizeof(NetCharDriver));
2320 fd = inet_dgram_opts(opts, &local_err);
2326 s->chan = io_channel_from_socket(s->fd);
2330 chr->chr_write = udp_chr_write;
2331 chr->chr_update_read_handler = udp_chr_update_read_handler;
2332 chr->chr_close = udp_chr_close;
2337 qerror_report_err(local_err);
2338 error_free(local_err);
2348 /***********************************************************/
2349 /* TCP Net console */
2353 GIOChannel *chan, *listen_chan;
2354 guint tag, listen_tag;
2364 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2366 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2368 TCPCharDriver *s = chr->opaque;
2370 return io_channel_send_all(s->chan, buf, len);
2372 /* XXX: indicate an error ? */
2377 static int tcp_chr_read_poll(void *opaque)
2379 CharDriverState *chr = opaque;
2380 TCPCharDriver *s = chr->opaque;
2383 s->max_size = qemu_chr_be_can_write(chr);
2388 #define IAC_BREAK 243
2389 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2391 uint8_t *buf, int *size)
2393 /* Handle any telnet client's basic IAC options to satisfy char by
2394 * char mode with no echo. All IAC options will be removed from
2395 * the buf and the do_telnetopt variable will be used to track the
2396 * state of the width of the IAC information.
2398 * IAC commands come in sets of 3 bytes with the exception of the
2399 * "IAC BREAK" command and the double IAC.
2405 for (i = 0; i < *size; i++) {
2406 if (s->do_telnetopt > 1) {
2407 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2408 /* Double IAC means send an IAC */
2412 s->do_telnetopt = 1;
2414 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2415 /* Handle IAC break commands by sending a serial break */
2416 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2421 if (s->do_telnetopt >= 4) {
2422 s->do_telnetopt = 1;
2425 if ((unsigned char)buf[i] == IAC) {
2426 s->do_telnetopt = 2;
2437 static int tcp_get_msgfd(CharDriverState *chr)
2439 TCPCharDriver *s = chr->opaque;
2446 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2448 TCPCharDriver *s = chr->opaque;
2449 struct cmsghdr *cmsg;
2451 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2454 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2455 cmsg->cmsg_level != SOL_SOCKET ||
2456 cmsg->cmsg_type != SCM_RIGHTS)
2459 fd = *((int *)CMSG_DATA(cmsg));
2463 #ifndef MSG_CMSG_CLOEXEC
2464 qemu_set_cloexec(fd);
2472 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2474 TCPCharDriver *s = chr->opaque;
2475 struct msghdr msg = { NULL, };
2476 struct iovec iov[1];
2478 struct cmsghdr cmsg;
2479 char control[CMSG_SPACE(sizeof(int))];
2484 iov[0].iov_base = buf;
2485 iov[0].iov_len = len;
2489 msg.msg_control = &msg_control;
2490 msg.msg_controllen = sizeof(msg_control);
2492 #ifdef MSG_CMSG_CLOEXEC
2493 flags |= MSG_CMSG_CLOEXEC;
2495 ret = recvmsg(s->fd, &msg, flags);
2496 if (ret > 0 && s->is_unix) {
2497 unix_process_msgfd(chr, &msg);
2503 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2505 TCPCharDriver *s = chr->opaque;
2506 return qemu_recv(s->fd, buf, len, 0);
2510 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2512 TCPCharDriver *s = chr->opaque;
2513 return g_io_create_watch(s->chan, cond);
2516 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2518 CharDriverState *chr = opaque;
2519 TCPCharDriver *s = chr->opaque;
2520 uint8_t buf[READ_BUF_LEN];
2523 if (!s->connected || s->max_size <= 0) {
2527 if (len > s->max_size)
2529 size = tcp_chr_recv(chr, (void *)buf, len);
2531 /* connection closed */
2533 if (s->listen_chan) {
2534 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2536 g_source_remove(s->tag);
2538 g_io_channel_unref(s->chan);
2542 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2543 } else if (size > 0) {
2544 if (s->do_telnetopt)
2545 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2547 qemu_chr_be_write(chr, buf, size);
2554 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2556 return qemu_chr_open_fd(eventfd, eventfd);
2560 static void tcp_chr_connect(void *opaque)
2562 CharDriverState *chr = opaque;
2563 TCPCharDriver *s = chr->opaque;
2567 s->tag = io_add_watch_poll(s->chan, tcp_chr_read_poll, tcp_chr_read, chr);
2569 qemu_chr_generic_open(chr);
2572 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2573 static void tcp_chr_telnet_init(int fd)
2576 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2577 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2578 send(fd, (char *)buf, 3, 0);
2579 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2580 send(fd, (char *)buf, 3, 0);
2581 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2582 send(fd, (char *)buf, 3, 0);
2583 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2584 send(fd, (char *)buf, 3, 0);
2587 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2589 TCPCharDriver *s = chr->opaque;
2593 socket_set_nonblock(fd);
2595 socket_set_nodelay(fd);
2597 s->chan = io_channel_from_socket(fd);
2598 g_source_remove(s->listen_tag);
2600 tcp_chr_connect(chr);
2605 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2607 CharDriverState *chr = opaque;
2608 TCPCharDriver *s = chr->opaque;
2609 struct sockaddr_in saddr;
2611 struct sockaddr_un uaddr;
2613 struct sockaddr *addr;
2620 len = sizeof(uaddr);
2621 addr = (struct sockaddr *)&uaddr;
2625 len = sizeof(saddr);
2626 addr = (struct sockaddr *)&saddr;
2628 fd = qemu_accept(s->listen_fd, addr, &len);
2629 if (fd < 0 && errno != EINTR) {
2631 } else if (fd >= 0) {
2632 if (s->do_telnetopt)
2633 tcp_chr_telnet_init(fd);
2637 if (tcp_chr_add_client(chr, fd) < 0)
2643 static void tcp_chr_close(CharDriverState *chr)
2645 TCPCharDriver *s = chr->opaque;
2648 g_source_remove(s->tag);
2651 g_io_channel_unref(s->chan);
2655 if (s->listen_fd >= 0) {
2656 if (s->listen_tag) {
2657 g_source_remove(s->listen_tag);
2659 if (s->listen_chan) {
2660 g_io_channel_unref(s->listen_chan);
2662 closesocket(s->listen_fd);
2665 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2668 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2669 bool is_listen, bool is_telnet,
2670 bool is_waitconnect,
2673 CharDriverState *chr = NULL;
2674 TCPCharDriver *s = NULL;
2675 char host[NI_MAXHOST], serv[NI_MAXSERV];
2676 const char *left = "", *right = "";
2677 struct sockaddr_storage ss;
2678 socklen_t ss_len = sizeof(ss);
2680 memset(&ss, 0, ss_len);
2681 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2682 error_setg(errp, "getsockname: %s", strerror(errno));
2686 chr = g_malloc0(sizeof(CharDriverState));
2687 s = g_malloc0(sizeof(TCPCharDriver));
2694 chr->filename = g_malloc(256);
2695 switch (ss.ss_family) {
2699 snprintf(chr->filename, 256, "unix:%s%s",
2700 ((struct sockaddr_un *)(&ss))->sun_path,
2701 is_listen ? ",server" : "");
2709 s->do_nodelay = do_nodelay;
2710 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2711 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2712 snprintf(chr->filename, 256, "%s:%s:%s%s%s%s",
2713 is_telnet ? "telnet" : "tcp",
2714 left, host, right, serv,
2715 is_listen ? ",server" : "");
2720 chr->chr_write = tcp_chr_write;
2721 chr->chr_close = tcp_chr_close;
2722 chr->get_msgfd = tcp_get_msgfd;
2723 chr->chr_add_client = tcp_chr_add_client;
2724 chr->chr_add_watch = tcp_chr_add_watch;
2728 s->listen_chan = io_channel_from_socket(s->listen_fd);
2729 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2731 s->do_telnetopt = 1;
2736 socket_set_nodelay(fd);
2737 s->chan = io_channel_from_socket(s->fd);
2738 tcp_chr_connect(chr);
2741 if (is_listen && is_waitconnect) {
2742 printf("QEMU waiting for connection on: %s\n",
2744 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2745 socket_set_nonblock(s->listen_fd);
2750 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2752 CharDriverState *chr = NULL;
2753 Error *local_err = NULL;
2761 is_listen = qemu_opt_get_bool(opts, "server", 0);
2762 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2763 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2764 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2765 is_unix = qemu_opt_get(opts, "path") != NULL;
2771 fd = unix_listen_opts(opts, &local_err);
2773 fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2777 fd = inet_listen_opts(opts, 0, &local_err);
2779 fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2786 if (!is_waitconnect)
2787 socket_set_nonblock(fd);
2789 chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2790 is_waitconnect, &local_err);
2791 if (error_is_set(&local_err)) {
2799 qerror_report_err(local_err);
2800 error_free(local_err);
2806 g_free(chr->opaque);
2812 /***********************************************************/
2813 /* Memory chardev */
2816 size_t outbuf_capacity;
2820 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2822 MemoryDriver *d = chr->opaque;
2824 /* TODO: the QString implementation has the same code, we should
2825 * introduce a generic way to do this in cutils.c */
2826 if (d->outbuf_capacity < d->outbuf_size + len) {
2828 d->outbuf_capacity += len;
2829 d->outbuf_capacity *= 2;
2830 d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
2833 memcpy(d->outbuf + d->outbuf_size, buf, len);
2834 d->outbuf_size += len;
2839 void qemu_chr_init_mem(CharDriverState *chr)
2843 d = g_malloc(sizeof(*d));
2845 d->outbuf_capacity = 4096;
2846 d->outbuf = g_malloc0(d->outbuf_capacity);
2848 memset(chr, 0, sizeof(*chr));
2850 chr->chr_write = mem_chr_write;
2853 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2855 MemoryDriver *d = chr->opaque;
2856 return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2859 /* NOTE: this driver can not be closed with qemu_chr_delete()! */
2860 void qemu_chr_close_mem(CharDriverState *chr)
2862 MemoryDriver *d = chr->opaque;
2865 g_free(chr->opaque);
2867 chr->chr_write = NULL;
2870 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2872 const MemoryDriver *d = chr->opaque;
2873 return d->outbuf_size;
2876 /*********************************************************/
2877 /* Ring buffer chardev */
2884 } RingBufCharDriver;
2886 static size_t ringbuf_count(const CharDriverState *chr)
2888 const RingBufCharDriver *d = chr->opaque;
2890 return d->prod - d->cons;
2893 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2895 RingBufCharDriver *d = chr->opaque;
2898 if (!buf || (len < 0)) {
2902 for (i = 0; i < len; i++ ) {
2903 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2904 if (d->prod - d->cons > d->size) {
2905 d->cons = d->prod - d->size;
2912 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2914 RingBufCharDriver *d = chr->opaque;
2917 for (i = 0; i < len && d->cons != d->prod; i++) {
2918 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2924 static void ringbuf_chr_close(struct CharDriverState *chr)
2926 RingBufCharDriver *d = chr->opaque;
2933 static CharDriverState *qemu_chr_open_ringbuf(QemuOpts *opts)
2935 CharDriverState *chr;
2936 RingBufCharDriver *d;
2938 chr = g_malloc0(sizeof(CharDriverState));
2939 d = g_malloc(sizeof(*d));
2941 d->size = qemu_opt_get_size(opts, "size", 0);
2946 /* The size must be power of 2 */
2947 if (d->size & (d->size - 1)) {
2948 error_report("size of ringbuf device must be power of two");
2954 d->cbuf = g_malloc0(d->size);
2957 chr->chr_write = ringbuf_chr_write;
2958 chr->chr_close = ringbuf_chr_close;
2968 static bool chr_is_ringbuf(const CharDriverState *chr)
2970 return chr->chr_write == ringbuf_chr_write;
2973 void qmp_ringbuf_write(const char *device, const char *data,
2974 bool has_format, enum DataFormat format,
2977 CharDriverState *chr;
2978 const uint8_t *write_data;
2982 chr = qemu_chr_find(device);
2984 error_setg(errp, "Device '%s' not found", device);
2988 if (!chr_is_ringbuf(chr)) {
2989 error_setg(errp,"%s is not a ringbuf device", device);
2993 if (has_format && (format == DATA_FORMAT_BASE64)) {
2994 write_data = g_base64_decode(data, &write_count);
2996 write_data = (uint8_t *)data;
2997 write_count = strlen(data);
3000 ret = ringbuf_chr_write(chr, write_data, write_count);
3002 if (write_data != (uint8_t *)data) {
3003 g_free((void *)write_data);
3007 error_setg(errp, "Failed to write to device %s", device);
3012 char *qmp_ringbuf_read(const char *device, int64_t size,
3013 bool has_format, enum DataFormat format,
3016 CharDriverState *chr;
3021 chr = qemu_chr_find(device);
3023 error_setg(errp, "Device '%s' not found", device);
3027 if (!chr_is_ringbuf(chr)) {
3028 error_setg(errp,"%s is not a ringbuf device", device);
3033 error_setg(errp, "size must be greater than zero");
3037 count = ringbuf_count(chr);
3038 size = size > count ? count : size;
3039 read_data = g_malloc(size + 1);
3041 ringbuf_chr_read(chr, read_data, size);
3043 if (has_format && (format == DATA_FORMAT_BASE64)) {
3044 data = g_base64_encode(read_data, size);
3048 * FIXME should read only complete, valid UTF-8 characters up
3049 * to @size bytes. Invalid sequences should be replaced by a
3050 * suitable replacement character. Except when (and only
3051 * when) ring buffer lost characters since last read, initial
3052 * continuation characters should be dropped.
3054 read_data[size] = 0;
3055 data = (char *)read_data;
3061 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3063 char host[65], port[33], width[8], height[8];
3067 Error *local_err = NULL;
3069 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3070 if (error_is_set(&local_err)) {
3071 qerror_report_err(local_err);
3072 error_free(local_err);
3076 if (strstart(filename, "mon:", &p)) {
3078 qemu_opt_set(opts, "mux", "on");
3081 if (strcmp(filename, "null") == 0 ||
3082 strcmp(filename, "pty") == 0 ||
3083 strcmp(filename, "msmouse") == 0 ||
3084 strcmp(filename, "braille") == 0 ||
3085 strcmp(filename, "stdio") == 0) {
3086 qemu_opt_set(opts, "backend", filename);
3089 if (strstart(filename, "vc", &p)) {
3090 qemu_opt_set(opts, "backend", "vc");
3092 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
3094 qemu_opt_set(opts, "width", width);
3095 qemu_opt_set(opts, "height", height);
3096 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
3098 qemu_opt_set(opts, "cols", width);
3099 qemu_opt_set(opts, "rows", height);
3106 if (strcmp(filename, "con:") == 0) {
3107 qemu_opt_set(opts, "backend", "console");
3110 if (strstart(filename, "COM", NULL)) {
3111 qemu_opt_set(opts, "backend", "serial");
3112 qemu_opt_set(opts, "path", filename);
3115 if (strstart(filename, "file:", &p)) {
3116 qemu_opt_set(opts, "backend", "file");
3117 qemu_opt_set(opts, "path", p);
3120 if (strstart(filename, "pipe:", &p)) {
3121 qemu_opt_set(opts, "backend", "pipe");
3122 qemu_opt_set(opts, "path", p);
3125 if (strstart(filename, "tcp:", &p) ||
3126 strstart(filename, "telnet:", &p)) {
3127 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3129 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3132 qemu_opt_set(opts, "backend", "socket");
3133 qemu_opt_set(opts, "host", host);
3134 qemu_opt_set(opts, "port", port);
3135 if (p[pos] == ',') {
3136 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3139 if (strstart(filename, "telnet:", &p))
3140 qemu_opt_set(opts, "telnet", "on");
3143 if (strstart(filename, "udp:", &p)) {
3144 qemu_opt_set(opts, "backend", "udp");
3145 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3147 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3151 qemu_opt_set(opts, "host", host);
3152 qemu_opt_set(opts, "port", port);
3153 if (p[pos] == '@') {
3155 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3157 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3161 qemu_opt_set(opts, "localaddr", host);
3162 qemu_opt_set(opts, "localport", port);
3166 if (strstart(filename, "unix:", &p)) {
3167 qemu_opt_set(opts, "backend", "socket");
3168 if (qemu_opts_do_parse(opts, p, "path") != 0)
3172 if (strstart(filename, "/dev/parport", NULL) ||
3173 strstart(filename, "/dev/ppi", NULL)) {
3174 qemu_opt_set(opts, "backend", "parport");
3175 qemu_opt_set(opts, "path", filename);
3178 if (strstart(filename, "/dev/", NULL)) {
3179 qemu_opt_set(opts, "backend", "tty");
3180 qemu_opt_set(opts, "path", filename);
3185 qemu_opts_del(opts);
3189 #ifdef HAVE_CHARDEV_PARPORT
3191 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
3193 const char *filename = qemu_opt_get(opts, "path");
3196 fd = qemu_open(filename, O_RDWR);
3200 return qemu_chr_open_pp_fd(fd);
3205 typedef struct CharDriver {
3208 CharDriverState *(*open)(QemuOpts *opts);
3209 /* new, qapi-based */
3211 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3214 static GSList *backends;
3216 void register_char_driver(const char *name, CharDriverState *(*open)(QemuOpts *))
3220 s = g_malloc0(sizeof(*s));
3221 s->name = g_strdup(name);
3224 backends = g_slist_append(backends, s);
3227 void register_char_driver_qapi(const char *name, int kind,
3228 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3232 s = g_malloc0(sizeof(*s));
3233 s->name = g_strdup(name);
3237 backends = g_slist_append(backends, s);
3240 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3241 void (*init)(struct CharDriverState *s),
3245 CharDriverState *chr;
3248 if (qemu_opts_id(opts) == NULL) {
3249 error_setg(errp, "chardev: no id specified");
3253 if (qemu_opt_get(opts, "backend") == NULL) {
3254 error_setg(errp, "chardev: \"%s\" missing backend",
3255 qemu_opts_id(opts));
3258 for (i = backends; i; i = i->next) {
3261 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3266 error_setg(errp, "chardev: backend \"%s\" not found",
3267 qemu_opt_get(opts, "backend"));
3272 /* using new, qapi init */
3273 ChardevBackend *backend = g_new0(ChardevBackend, 1);
3274 ChardevReturn *ret = NULL;
3275 const char *id = qemu_opts_id(opts);
3278 backend->kind = cd->kind;
3280 cd->parse(opts, backend, errp);
3281 if (error_is_set(errp)) {
3285 ret = qmp_chardev_add(qemu_opts_id(opts), backend, errp);
3286 if (error_is_set(errp)) {
3289 chr = qemu_chr_find(id);
3292 qapi_free_ChardevBackend(backend);
3293 qapi_free_ChardevReturn(ret);
3297 chr = cd->open(opts);
3299 error_setg(errp, "chardev: opening backend \"%s\" failed",
3300 qemu_opt_get(opts, "backend"));
3305 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3307 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3309 if (qemu_opt_get_bool(opts, "mux", 0)) {
3310 CharDriverState *base = chr;
3311 int len = strlen(qemu_opts_id(opts)) + 6;
3312 base->label = g_malloc(len);
3313 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3314 chr = qemu_chr_open_mux(base);
3315 chr->filename = base->filename;
3316 chr->avail_connections = MAX_MUX;
3317 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3319 chr->avail_connections = 1;
3321 chr->label = g_strdup(qemu_opts_id(opts));
3326 qemu_opts_del(opts);
3330 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3333 CharDriverState *chr;
3337 if (strstart(filename, "chardev:", &p)) {
3338 return qemu_chr_find(p);
3341 opts = qemu_chr_parse_compat(label, filename);
3345 chr = qemu_chr_new_from_opts(opts, init, &err);
3346 if (error_is_set(&err)) {
3347 fprintf(stderr, "%s\n", error_get_pretty(err));
3350 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3351 monitor_init(chr, MONITOR_USE_READLINE);
3356 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3358 if (chr->chr_set_echo) {
3359 chr->chr_set_echo(chr, echo);
3363 void qemu_chr_fe_open(struct CharDriverState *chr)
3365 if (chr->chr_guest_open) {
3366 chr->chr_guest_open(chr);
3370 void qemu_chr_fe_close(struct CharDriverState *chr)
3372 if (chr->chr_guest_close) {
3373 chr->chr_guest_close(chr);
3377 guint qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3378 GIOFunc func, void *user_data)
3383 if (s->chr_add_watch == NULL) {
3387 src = s->chr_add_watch(s, cond);
3388 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3389 tag = g_source_attach(src, NULL);
3390 g_source_unref(src);
3395 void qemu_chr_delete(CharDriverState *chr)
3397 QTAILQ_REMOVE(&chardevs, chr, next);
3398 if (chr->chr_close) {
3399 chr->chr_close(chr);
3401 g_free(chr->filename);
3404 qemu_opts_del(chr->opts);
3409 ChardevInfoList *qmp_query_chardev(Error **errp)
3411 ChardevInfoList *chr_list = NULL;
3412 CharDriverState *chr;
3414 QTAILQ_FOREACH(chr, &chardevs, next) {
3415 ChardevInfoList *info = g_malloc0(sizeof(*info));
3416 info->value = g_malloc0(sizeof(*info->value));
3417 info->value->label = g_strdup(chr->label);
3418 info->value->filename = g_strdup(chr->filename);
3420 info->next = chr_list;
3427 CharDriverState *qemu_chr_find(const char *name)
3429 CharDriverState *chr;
3431 QTAILQ_FOREACH(chr, &chardevs, next) {
3432 if (strcmp(chr->label, name) != 0)
3439 /* Get a character (serial) device interface. */
3440 CharDriverState *qemu_char_get_next_serial(void)
3442 static int next_serial;
3444 /* FIXME: This function needs to go away: use chardev properties! */
3445 return serial_hds[next_serial++];
3448 QemuOptsList qemu_chardev_opts = {
3450 .implied_opt_name = "backend",
3451 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3455 .type = QEMU_OPT_STRING,
3458 .type = QEMU_OPT_STRING,
3461 .type = QEMU_OPT_STRING,
3464 .type = QEMU_OPT_STRING,
3466 .name = "localaddr",
3467 .type = QEMU_OPT_STRING,
3469 .name = "localport",
3470 .type = QEMU_OPT_STRING,
3473 .type = QEMU_OPT_NUMBER,
3476 .type = QEMU_OPT_BOOL,
3479 .type = QEMU_OPT_BOOL,
3482 .type = QEMU_OPT_BOOL,
3485 .type = QEMU_OPT_BOOL,
3488 .type = QEMU_OPT_BOOL,
3491 .type = QEMU_OPT_BOOL,
3494 .type = QEMU_OPT_NUMBER,
3497 .type = QEMU_OPT_NUMBER,
3500 .type = QEMU_OPT_NUMBER,
3503 .type = QEMU_OPT_NUMBER,
3506 .type = QEMU_OPT_BOOL,
3509 .type = QEMU_OPT_BOOL,
3512 .type = QEMU_OPT_STRING,
3515 .type = QEMU_OPT_NUMBER,
3518 .type = QEMU_OPT_SIZE,
3520 { /* end of list */ }
3526 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3531 error_setg(errp, "input file not supported");
3535 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3536 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3537 if (out == INVALID_HANDLE_VALUE) {
3538 error_setg(errp, "open %s failed", file->out);
3541 return qemu_chr_open_win_file(out);
3544 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3547 return qemu_chr_open_win_path(serial->device);
3550 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3553 error_setg(errp, "character device backend type 'parallel' not supported");
3559 static int qmp_chardev_open_file_source(char *src, int flags,
3564 TFR(fd = qemu_open(src, flags, 0666));
3566 error_setg(errp, "open %s: %s", src, strerror(errno));
3571 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3573 int flags, in = -1, out = -1;
3575 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3576 out = qmp_chardev_open_file_source(file->out, flags, errp);
3577 if (error_is_set(errp)) {
3583 in = qmp_chardev_open_file_source(file->in, flags, errp);
3584 if (error_is_set(errp)) {
3590 return qemu_chr_open_fd(in, out);
3593 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3596 #ifdef HAVE_CHARDEV_TTY
3599 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3600 if (error_is_set(errp)) {
3603 socket_set_nonblock(fd);
3604 return qemu_chr_open_tty_fd(fd);
3606 error_setg(errp, "character device backend type 'serial' not supported");
3611 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3614 #ifdef HAVE_CHARDEV_PARPORT
3617 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3618 if (error_is_set(errp)) {
3621 return qemu_chr_open_pp_fd(fd);
3623 error_setg(errp, "character device backend type 'parallel' not supported");
3630 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3633 SocketAddress *addr = sock->addr;
3634 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3635 bool is_listen = sock->has_server ? sock->server : true;
3636 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3637 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3641 fd = socket_listen(addr, errp);
3643 fd = socket_connect(addr, errp, NULL, NULL);
3645 if (error_is_set(errp)) {
3648 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3649 is_telnet, is_waitconnect, errp);
3652 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3655 ChardevReturn *ret = g_new0(ChardevReturn, 1);
3656 CharDriverState *chr = NULL;
3658 chr = qemu_chr_find(id);
3660 error_setg(errp, "Chardev '%s' already exists", id);
3665 switch (backend->kind) {
3666 case CHARDEV_BACKEND_KIND_FILE:
3667 chr = qmp_chardev_open_file(backend->file, errp);
3669 case CHARDEV_BACKEND_KIND_SERIAL:
3670 chr = qmp_chardev_open_serial(backend->serial, errp);
3672 case CHARDEV_BACKEND_KIND_PARALLEL:
3673 chr = qmp_chardev_open_parallel(backend->parallel, errp);
3675 case CHARDEV_BACKEND_KIND_SOCKET:
3676 chr = qmp_chardev_open_socket(backend->socket, errp);
3678 #ifdef HAVE_CHARDEV_TTY
3679 case CHARDEV_BACKEND_KIND_PTY:
3681 /* qemu_chr_open_pty sets "path" in opts */
3683 opts = qemu_opts_create_nofail(qemu_find_opts("chardev"));
3684 chr = qemu_chr_open_pty(opts);
3685 ret->pty = g_strdup(qemu_opt_get(opts, "path"));
3686 ret->has_pty = true;
3687 qemu_opts_del(opts);
3691 case CHARDEV_BACKEND_KIND_NULL:
3692 chr = qemu_chr_open_null(NULL);
3695 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3699 if (chr == NULL && !error_is_set(errp)) {
3700 error_setg(errp, "Failed to create chardev");
3703 chr->label = g_strdup(id);
3704 chr->avail_connections = 1;
3705 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3713 void qmp_chardev_remove(const char *id, Error **errp)
3715 CharDriverState *chr;
3717 chr = qemu_chr_find(id);
3719 error_setg(errp, "Chardev '%s' not found", id);
3722 if (chr->chr_can_read || chr->chr_read ||
3723 chr->chr_event || chr->handler_opaque) {
3724 error_setg(errp, "Chardev '%s' is busy", id);
3727 qemu_chr_delete(chr);
3730 static void register_types(void)
3732 register_char_driver("null", qemu_chr_open_null);
3733 register_char_driver("socket", qemu_chr_open_socket);
3734 register_char_driver("udp", qemu_chr_open_udp);
3735 register_char_driver("memory", qemu_chr_open_ringbuf);
3737 register_char_driver("file", qemu_chr_open_win_file_out);
3738 register_char_driver("pipe", qemu_chr_open_win_pipe);
3739 register_char_driver("console", qemu_chr_open_win_con);
3740 register_char_driver("serial", qemu_chr_open_win);
3741 register_char_driver("stdio", qemu_chr_open_win_stdio);
3743 register_char_driver("file", qemu_chr_open_file_out);
3744 register_char_driver("pipe", qemu_chr_open_pipe);
3745 register_char_driver("stdio", qemu_chr_open_stdio);
3747 #ifdef HAVE_CHARDEV_TTY
3748 register_char_driver("tty", qemu_chr_open_tty);
3749 register_char_driver("serial", qemu_chr_open_tty);
3750 register_char_driver("pty", qemu_chr_open_pty);
3752 #ifdef HAVE_CHARDEV_PARPORT
3753 register_char_driver("parallel", qemu_chr_open_pp);
3754 register_char_driver("parport", qemu_chr_open_pp);
3758 type_init(register_types);