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) {
538 typedef struct IOWatchPoll
543 IOCanReadHandler *fd_can_read;
546 QTAILQ_ENTRY(IOWatchPoll) node;
549 static QTAILQ_HEAD(, IOWatchPoll) io_watch_poll_list =
550 QTAILQ_HEAD_INITIALIZER(io_watch_poll_list);
552 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
556 QTAILQ_FOREACH(i, &io_watch_poll_list, node) {
557 if (i->src == source) {
565 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
567 IOWatchPoll *iwp = io_watch_poll_from_source(source);
569 iwp->max_size = iwp->fd_can_read(iwp->opaque);
570 if (iwp->max_size == 0) {
574 return g_io_watch_funcs.prepare(source, timeout_);
577 static gboolean io_watch_poll_check(GSource *source)
579 IOWatchPoll *iwp = io_watch_poll_from_source(source);
581 if (iwp->max_size == 0) {
585 return g_io_watch_funcs.check(source);
588 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
591 return g_io_watch_funcs.dispatch(source, callback, user_data);
594 static void io_watch_poll_finalize(GSource *source)
596 IOWatchPoll *iwp = io_watch_poll_from_source(source);
597 QTAILQ_REMOVE(&io_watch_poll_list, iwp, node);
598 g_io_watch_funcs.finalize(source);
601 static GSourceFuncs io_watch_poll_funcs = {
602 .prepare = io_watch_poll_prepare,
603 .check = io_watch_poll_check,
604 .dispatch = io_watch_poll_dispatch,
605 .finalize = io_watch_poll_finalize,
608 /* Can only be used for read */
609 static guint io_add_watch_poll(GIOChannel *channel,
610 IOCanReadHandler *fd_can_read,
618 src = g_io_create_watch(channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
619 g_source_set_funcs(src, &io_watch_poll_funcs);
620 g_source_set_callback(src, (GSourceFunc)fd_read, user_data, NULL);
621 tag = g_source_attach(src, NULL);
624 iwp = g_malloc0(sizeof(*iwp));
627 iwp->fd_can_read = fd_can_read;
628 iwp->opaque = user_data;
630 QTAILQ_INSERT_HEAD(&io_watch_poll_list, iwp, node);
636 static GIOChannel *io_channel_from_fd(int fd)
644 chan = g_io_channel_unix_new(fd);
646 g_io_channel_set_encoding(chan, NULL, NULL);
647 g_io_channel_set_buffered(chan, FALSE);
653 static GIOChannel *io_channel_from_socket(int fd)
662 chan = g_io_channel_win32_new_socket(fd);
664 chan = g_io_channel_unix_new(fd);
667 g_io_channel_set_encoding(chan, NULL, NULL);
668 g_io_channel_set_buffered(chan, FALSE);
673 static int io_channel_send_all(GIOChannel *fd, const void *_buf, int len1)
678 const uint8_t *buf = _buf;
682 status = g_io_channel_write_chars(fd, (const gchar *)buf, len,
683 &bytes_written, NULL);
684 if (status != G_IO_STATUS_NORMAL) {
685 if (status == G_IO_STATUS_AGAIN) {
692 } else if (status == G_IO_STATUS_EOF) {
695 buf += bytes_written;
696 len -= bytes_written;
704 typedef struct FDCharDriver {
705 CharDriverState *chr;
706 GIOChannel *fd_in, *fd_out;
709 QTAILQ_ENTRY(FDCharDriver) node;
712 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
714 FDCharDriver *s = chr->opaque;
716 return io_channel_send_all(s->fd_out, buf, len);
719 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
721 CharDriverState *chr = opaque;
722 FDCharDriver *s = chr->opaque;
724 uint8_t buf[READ_BUF_LEN];
729 if (len > s->max_size) {
736 status = g_io_channel_read_chars(chan, (gchar *)buf,
737 len, &bytes_read, NULL);
738 if (status == G_IO_STATUS_EOF) {
739 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
742 if (status == G_IO_STATUS_NORMAL) {
743 qemu_chr_be_write(chr, buf, bytes_read);
749 static int fd_chr_read_poll(void *opaque)
751 CharDriverState *chr = opaque;
752 FDCharDriver *s = chr->opaque;
754 s->max_size = qemu_chr_be_can_write(chr);
758 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
760 FDCharDriver *s = chr->opaque;
761 return g_io_create_watch(s->fd_out, cond);
764 static void fd_chr_update_read_handler(CharDriverState *chr)
766 FDCharDriver *s = chr->opaque;
769 g_source_remove(s->fd_in_tag);
773 s->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll, fd_chr_read, chr);
777 static void fd_chr_close(struct CharDriverState *chr)
779 FDCharDriver *s = chr->opaque;
782 g_source_remove(s->fd_in_tag);
787 g_io_channel_unref(s->fd_in);
790 g_io_channel_unref(s->fd_out);
794 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
797 /* open a character device to a unix fd */
798 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
800 CharDriverState *chr;
803 chr = g_malloc0(sizeof(CharDriverState));
804 s = g_malloc0(sizeof(FDCharDriver));
805 s->fd_in = io_channel_from_fd(fd_in);
806 s->fd_out = io_channel_from_fd(fd_out);
807 fcntl(fd_out, F_SETFL, O_NONBLOCK);
810 chr->chr_add_watch = fd_chr_add_watch;
811 chr->chr_write = fd_chr_write;
812 chr->chr_update_read_handler = fd_chr_update_read_handler;
813 chr->chr_close = fd_chr_close;
815 qemu_chr_generic_open(chr);
820 static CharDriverState *qemu_chr_open_file_out(QemuOpts *opts)
824 TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
825 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
829 return qemu_chr_open_fd(-1, fd_out);
832 static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)
835 char filename_in[256], filename_out[256];
836 const char *filename = qemu_opt_get(opts, "path");
838 if (filename == NULL) {
839 fprintf(stderr, "chardev: pipe: no filename given\n");
843 snprintf(filename_in, 256, "%s.in", filename);
844 snprintf(filename_out, 256, "%s.out", filename);
845 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
846 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
847 if (fd_in < 0 || fd_out < 0) {
852 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
857 return qemu_chr_open_fd(fd_in, fd_out);
860 /* init terminal so that we can grab keys */
861 static struct termios oldtty;
862 static int old_fd0_flags;
863 static bool stdio_allow_signal;
865 static void term_exit(void)
867 tcsetattr (0, TCSANOW, &oldtty);
868 fcntl(0, F_SETFL, old_fd0_flags);
871 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
877 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
878 |INLCR|IGNCR|ICRNL|IXON);
879 tty.c_oflag |= OPOST;
880 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
881 tty.c_cflag &= ~(CSIZE|PARENB);
886 /* if graphical mode, we allow Ctrl-C handling */
887 if (!stdio_allow_signal)
888 tty.c_lflag &= ~ISIG;
890 tcsetattr (0, TCSANOW, &tty);
893 static void qemu_chr_close_stdio(struct CharDriverState *chr)
899 static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)
901 CharDriverState *chr;
903 if (is_daemonized()) {
904 error_report("cannot use stdio with -daemonize");
907 old_fd0_flags = fcntl(0, F_GETFL);
908 tcgetattr (0, &oldtty);
909 fcntl(0, F_SETFL, O_NONBLOCK);
912 chr = qemu_chr_open_fd(0, 1);
913 chr->chr_close = qemu_chr_close_stdio;
914 chr->chr_set_echo = qemu_chr_set_echo_stdio;
915 stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
916 display_type != DT_NOGRAPHIC);
917 qemu_chr_fe_set_echo(chr, false);
923 /* Once Solaris has openpty(), this is going to be removed. */
924 static int openpty(int *amaster, int *aslave, char *name,
925 struct termios *termp, struct winsize *winp)
928 int mfd = -1, sfd = -1;
930 *amaster = *aslave = -1;
932 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
936 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
939 if ((slave = ptsname(mfd)) == NULL)
942 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
945 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
946 (termp != NULL && tcgetattr(sfd, termp) < 0))
954 ioctl(sfd, TIOCSWINSZ, winp);
965 static void cfmakeraw (struct termios *termios_p)
967 termios_p->c_iflag &=
968 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
969 termios_p->c_oflag &= ~OPOST;
970 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
971 termios_p->c_cflag &= ~(CSIZE|PARENB);
972 termios_p->c_cflag |= CS8;
974 termios_p->c_cc[VMIN] = 0;
975 termios_p->c_cc[VTIME] = 0;
979 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
980 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
981 || defined(__GLIBC__)
983 #define HAVE_CHARDEV_TTY 1
994 static void pty_chr_update_read_handler(CharDriverState *chr);
995 static void pty_chr_state(CharDriverState *chr, int connected);
997 static gboolean pty_chr_timer(gpointer opaque)
999 struct CharDriverState *chr = opaque;
1000 PtyCharDriver *s = chr->opaque;
1006 /* If we arrive here without polling being cleared due
1007 * read returning -EIO, then we are (re-)connected */
1008 pty_chr_state(chr, 1);
1013 pty_chr_update_read_handler(chr);
1019 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1021 PtyCharDriver *s = chr->opaque;
1024 g_source_remove(s->timer_tag);
1029 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1031 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1035 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1037 PtyCharDriver *s = chr->opaque;
1039 if (!s->connected) {
1040 /* guest sends data, check for (re-)connect */
1041 pty_chr_update_read_handler(chr);
1044 return io_channel_send_all(s->fd, buf, len);
1047 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1049 PtyCharDriver *s = chr->opaque;
1050 return g_io_create_watch(s->fd, cond);
1053 static int pty_chr_read_poll(void *opaque)
1055 CharDriverState *chr = opaque;
1056 PtyCharDriver *s = chr->opaque;
1058 s->read_bytes = qemu_chr_be_can_write(chr);
1059 return s->read_bytes;
1062 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1064 CharDriverState *chr = opaque;
1065 PtyCharDriver *s = chr->opaque;
1067 uint8_t buf[READ_BUF_LEN];
1071 if (len > s->read_bytes)
1072 len = s->read_bytes;
1075 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1076 if (status != G_IO_STATUS_NORMAL) {
1077 pty_chr_state(chr, 0);
1080 pty_chr_state(chr, 1);
1081 qemu_chr_be_write(chr, buf, size);
1086 static void pty_chr_update_read_handler(CharDriverState *chr)
1088 PtyCharDriver *s = chr->opaque;
1091 g_source_remove(s->fd_tag);
1094 s->fd_tag = io_add_watch_poll(s->fd, pty_chr_read_poll, pty_chr_read, chr);
1097 * Short timeout here: just need wait long enougth that qemu makes
1098 * it through the poll loop once. When reconnected we want a
1099 * short timeout so we notice it almost instantly. Otherwise
1100 * read() gives us -EIO instantly, making pty_chr_state() reset the
1101 * timeout to the normal (much longer) poll interval before the
1104 pty_chr_rearm_timer(chr, 10);
1107 static void pty_chr_state(CharDriverState *chr, int connected)
1109 PtyCharDriver *s = chr->opaque;
1112 g_source_remove(s->fd_tag);
1116 /* (re-)connect poll interval for idle guests: once per second.
1117 * We check more frequently in case the guests sends data to
1118 * the virtual device linked to our pty. */
1119 pty_chr_rearm_timer(chr, 1000);
1122 qemu_chr_generic_open(chr);
1128 static void pty_chr_close(struct CharDriverState *chr)
1130 PtyCharDriver *s = chr->opaque;
1134 g_source_remove(s->fd_tag);
1136 fd = g_io_channel_unix_get_fd(s->fd);
1137 g_io_channel_unref(s->fd);
1140 g_source_remove(s->timer_tag);
1143 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1146 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
1148 CharDriverState *chr;
1152 int master_fd, slave_fd, len;
1153 #if defined(__OpenBSD__) || defined(__DragonFly__)
1154 char pty_name[PATH_MAX];
1155 #define q_ptsname(x) pty_name
1157 char *pty_name = NULL;
1158 #define q_ptsname(x) ptsname(x)
1161 if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1165 /* Set raw attributes on the pty. */
1166 tcgetattr(slave_fd, &tty);
1168 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1171 chr = g_malloc0(sizeof(CharDriverState));
1173 len = strlen(q_ptsname(master_fd)) + 5;
1174 chr->filename = g_malloc(len);
1175 snprintf(chr->filename, len, "pty:%s", q_ptsname(master_fd));
1176 qemu_opt_set(opts, "path", q_ptsname(master_fd));
1178 label = qemu_opts_id(opts);
1179 fprintf(stderr, "char device redirected to %s%s%s%s\n",
1180 q_ptsname(master_fd),
1181 label ? " (label " : "",
1185 s = g_malloc0(sizeof(PtyCharDriver));
1187 chr->chr_write = pty_chr_write;
1188 chr->chr_update_read_handler = pty_chr_update_read_handler;
1189 chr->chr_close = pty_chr_close;
1190 chr->chr_add_watch = pty_chr_add_watch;
1192 s->fd = io_channel_from_fd(master_fd);
1198 static void tty_serial_init(int fd, int speed,
1199 int parity, int data_bits, int stop_bits)
1205 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1206 speed, parity, data_bits, stop_bits);
1208 tcgetattr (fd, &tty);
1210 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1211 speed = speed * 10 / 11;
1228 /* Non-Posix values follow. They may be unsupported on some systems. */
1230 check_speed(115200);
1232 check_speed(230400);
1235 check_speed(460800);
1238 check_speed(500000);
1241 check_speed(576000);
1244 check_speed(921600);
1247 check_speed(1000000);
1250 check_speed(1152000);
1253 check_speed(1500000);
1256 check_speed(2000000);
1259 check_speed(2500000);
1262 check_speed(3000000);
1265 check_speed(3500000);
1268 check_speed(4000000);
1273 cfsetispeed(&tty, spd);
1274 cfsetospeed(&tty, spd);
1276 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1277 |INLCR|IGNCR|ICRNL|IXON);
1278 tty.c_oflag |= OPOST;
1279 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1280 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1301 tty.c_cflag |= PARENB;
1304 tty.c_cflag |= PARENB | PARODD;
1308 tty.c_cflag |= CSTOPB;
1310 tcsetattr (fd, TCSANOW, &tty);
1313 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1315 FDCharDriver *s = chr->opaque;
1318 case CHR_IOCTL_SERIAL_SET_PARAMS:
1320 QEMUSerialSetParams *ssp = arg;
1321 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1322 ssp->speed, ssp->parity,
1323 ssp->data_bits, ssp->stop_bits);
1326 case CHR_IOCTL_SERIAL_SET_BREAK:
1328 int enable = *(int *)arg;
1330 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1334 case CHR_IOCTL_SERIAL_GET_TIOCM:
1337 int *targ = (int *)arg;
1338 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1340 if (sarg & TIOCM_CTS)
1341 *targ |= CHR_TIOCM_CTS;
1342 if (sarg & TIOCM_CAR)
1343 *targ |= CHR_TIOCM_CAR;
1344 if (sarg & TIOCM_DSR)
1345 *targ |= CHR_TIOCM_DSR;
1346 if (sarg & TIOCM_RI)
1347 *targ |= CHR_TIOCM_RI;
1348 if (sarg & TIOCM_DTR)
1349 *targ |= CHR_TIOCM_DTR;
1350 if (sarg & TIOCM_RTS)
1351 *targ |= CHR_TIOCM_RTS;
1354 case CHR_IOCTL_SERIAL_SET_TIOCM:
1356 int sarg = *(int *)arg;
1358 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1359 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1360 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1361 if (sarg & CHR_TIOCM_CTS)
1363 if (sarg & CHR_TIOCM_CAR)
1365 if (sarg & CHR_TIOCM_DSR)
1367 if (sarg & CHR_TIOCM_RI)
1369 if (sarg & CHR_TIOCM_DTR)
1371 if (sarg & CHR_TIOCM_RTS)
1373 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1382 static void qemu_chr_close_tty(CharDriverState *chr)
1384 FDCharDriver *s = chr->opaque;
1388 fd = g_io_channel_unix_get_fd(s->fd_in);
1398 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1400 CharDriverState *chr;
1402 tty_serial_init(fd, 115200, 'N', 8, 1);
1403 chr = qemu_chr_open_fd(fd, fd);
1404 chr->chr_ioctl = tty_serial_ioctl;
1405 chr->chr_close = qemu_chr_close_tty;
1409 static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
1411 const char *filename = qemu_opt_get(opts, "path");
1414 TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
1418 return qemu_chr_open_tty_fd(fd);
1420 #endif /* __linux__ || __sun__ */
1422 #if defined(__linux__)
1424 #define HAVE_CHARDEV_PARPORT 1
1429 } ParallelCharDriver;
1431 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1433 if (s->mode != mode) {
1435 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1442 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1444 ParallelCharDriver *drv = chr->opaque;
1449 case CHR_IOCTL_PP_READ_DATA:
1450 if (ioctl(fd, PPRDATA, &b) < 0)
1452 *(uint8_t *)arg = b;
1454 case CHR_IOCTL_PP_WRITE_DATA:
1455 b = *(uint8_t *)arg;
1456 if (ioctl(fd, PPWDATA, &b) < 0)
1459 case CHR_IOCTL_PP_READ_CONTROL:
1460 if (ioctl(fd, PPRCONTROL, &b) < 0)
1462 /* Linux gives only the lowest bits, and no way to know data
1463 direction! For better compatibility set the fixed upper
1465 *(uint8_t *)arg = b | 0xc0;
1467 case CHR_IOCTL_PP_WRITE_CONTROL:
1468 b = *(uint8_t *)arg;
1469 if (ioctl(fd, PPWCONTROL, &b) < 0)
1472 case CHR_IOCTL_PP_READ_STATUS:
1473 if (ioctl(fd, PPRSTATUS, &b) < 0)
1475 *(uint8_t *)arg = b;
1477 case CHR_IOCTL_PP_DATA_DIR:
1478 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1481 case CHR_IOCTL_PP_EPP_READ_ADDR:
1482 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1483 struct ParallelIOArg *parg = arg;
1484 int n = read(fd, parg->buffer, parg->count);
1485 if (n != parg->count) {
1490 case CHR_IOCTL_PP_EPP_READ:
1491 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1492 struct ParallelIOArg *parg = arg;
1493 int n = read(fd, parg->buffer, parg->count);
1494 if (n != parg->count) {
1499 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1500 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1501 struct ParallelIOArg *parg = arg;
1502 int n = write(fd, parg->buffer, parg->count);
1503 if (n != parg->count) {
1508 case CHR_IOCTL_PP_EPP_WRITE:
1509 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1510 struct ParallelIOArg *parg = arg;
1511 int n = write(fd, parg->buffer, parg->count);
1512 if (n != parg->count) {
1523 static void pp_close(CharDriverState *chr)
1525 ParallelCharDriver *drv = chr->opaque;
1528 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1529 ioctl(fd, PPRELEASE);
1532 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1535 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1537 CharDriverState *chr;
1538 ParallelCharDriver *drv;
1540 if (ioctl(fd, PPCLAIM) < 0) {
1545 drv = g_malloc0(sizeof(ParallelCharDriver));
1547 drv->mode = IEEE1284_MODE_COMPAT;
1549 chr = g_malloc0(sizeof(CharDriverState));
1550 chr->chr_write = null_chr_write;
1551 chr->chr_ioctl = pp_ioctl;
1552 chr->chr_close = pp_close;
1555 qemu_chr_generic_open(chr);
1559 #endif /* __linux__ */
1561 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1563 #define HAVE_CHARDEV_PARPORT 1
1565 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1567 int fd = (int)(intptr_t)chr->opaque;
1571 case CHR_IOCTL_PP_READ_DATA:
1572 if (ioctl(fd, PPIGDATA, &b) < 0)
1574 *(uint8_t *)arg = b;
1576 case CHR_IOCTL_PP_WRITE_DATA:
1577 b = *(uint8_t *)arg;
1578 if (ioctl(fd, PPISDATA, &b) < 0)
1581 case CHR_IOCTL_PP_READ_CONTROL:
1582 if (ioctl(fd, PPIGCTRL, &b) < 0)
1584 *(uint8_t *)arg = b;
1586 case CHR_IOCTL_PP_WRITE_CONTROL:
1587 b = *(uint8_t *)arg;
1588 if (ioctl(fd, PPISCTRL, &b) < 0)
1591 case CHR_IOCTL_PP_READ_STATUS:
1592 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1594 *(uint8_t *)arg = b;
1602 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1604 CharDriverState *chr;
1606 chr = g_malloc0(sizeof(CharDriverState));
1607 chr->opaque = (void *)(intptr_t)fd;
1608 chr->chr_write = null_chr_write;
1609 chr->chr_ioctl = pp_ioctl;
1618 HANDLE hcom, hrecv, hsend;
1619 OVERLAPPED orecv, osend;
1626 HANDLE hInputReadyEvent;
1627 HANDLE hInputDoneEvent;
1628 HANDLE hInputThread;
1629 uint8_t win_stdio_buf;
1630 } WinStdioCharState;
1632 #define NSENDBUF 2048
1633 #define NRECVBUF 2048
1634 #define MAXCONNECT 1
1635 #define NTIMEOUT 5000
1637 static int win_chr_poll(void *opaque);
1638 static int win_chr_pipe_poll(void *opaque);
1640 static void win_chr_close(CharDriverState *chr)
1642 WinCharState *s = chr->opaque;
1645 CloseHandle(s->hsend);
1649 CloseHandle(s->hrecv);
1653 CloseHandle(s->hcom);
1657 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1659 qemu_del_polling_cb(win_chr_poll, chr);
1661 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1664 static int win_chr_init(CharDriverState *chr, const char *filename)
1666 WinCharState *s = chr->opaque;
1668 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1673 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1675 fprintf(stderr, "Failed CreateEvent\n");
1678 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1680 fprintf(stderr, "Failed CreateEvent\n");
1684 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1685 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1686 if (s->hcom == INVALID_HANDLE_VALUE) {
1687 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1692 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1693 fprintf(stderr, "Failed SetupComm\n");
1697 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1698 size = sizeof(COMMCONFIG);
1699 GetDefaultCommConfig(filename, &comcfg, &size);
1700 comcfg.dcb.DCBlength = sizeof(DCB);
1701 CommConfigDialog(filename, NULL, &comcfg);
1703 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1704 fprintf(stderr, "Failed SetCommState\n");
1708 if (!SetCommMask(s->hcom, EV_ERR)) {
1709 fprintf(stderr, "Failed SetCommMask\n");
1713 cto.ReadIntervalTimeout = MAXDWORD;
1714 if (!SetCommTimeouts(s->hcom, &cto)) {
1715 fprintf(stderr, "Failed SetCommTimeouts\n");
1719 if (!ClearCommError(s->hcom, &err, &comstat)) {
1720 fprintf(stderr, "Failed ClearCommError\n");
1723 qemu_add_polling_cb(win_chr_poll, chr);
1731 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1733 WinCharState *s = chr->opaque;
1734 DWORD len, ret, size, err;
1737 ZeroMemory(&s->osend, sizeof(s->osend));
1738 s->osend.hEvent = s->hsend;
1741 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1743 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1745 err = GetLastError();
1746 if (err == ERROR_IO_PENDING) {
1747 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1765 static int win_chr_read_poll(CharDriverState *chr)
1767 WinCharState *s = chr->opaque;
1769 s->max_size = qemu_chr_be_can_write(chr);
1773 static void win_chr_readfile(CharDriverState *chr)
1775 WinCharState *s = chr->opaque;
1777 uint8_t buf[READ_BUF_LEN];
1780 ZeroMemory(&s->orecv, sizeof(s->orecv));
1781 s->orecv.hEvent = s->hrecv;
1782 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1784 err = GetLastError();
1785 if (err == ERROR_IO_PENDING) {
1786 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1791 qemu_chr_be_write(chr, buf, size);
1795 static void win_chr_read(CharDriverState *chr)
1797 WinCharState *s = chr->opaque;
1799 if (s->len > s->max_size)
1800 s->len = s->max_size;
1804 win_chr_readfile(chr);
1807 static int win_chr_poll(void *opaque)
1809 CharDriverState *chr = opaque;
1810 WinCharState *s = chr->opaque;
1814 ClearCommError(s->hcom, &comerr, &status);
1815 if (status.cbInQue > 0) {
1816 s->len = status.cbInQue;
1817 win_chr_read_poll(chr);
1824 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1826 CharDriverState *chr;
1829 chr = g_malloc0(sizeof(CharDriverState));
1830 s = g_malloc0(sizeof(WinCharState));
1832 chr->chr_write = win_chr_write;
1833 chr->chr_close = win_chr_close;
1835 if (win_chr_init(chr, filename) < 0) {
1840 qemu_chr_generic_open(chr);
1844 static CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1846 return qemu_chr_open_win_path(qemu_opt_get(opts, "path"));
1849 static int win_chr_pipe_poll(void *opaque)
1851 CharDriverState *chr = opaque;
1852 WinCharState *s = chr->opaque;
1855 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1858 win_chr_read_poll(chr);
1865 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1867 WinCharState *s = chr->opaque;
1875 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1877 fprintf(stderr, "Failed CreateEvent\n");
1880 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1882 fprintf(stderr, "Failed CreateEvent\n");
1886 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1887 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1888 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1890 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1891 if (s->hcom == INVALID_HANDLE_VALUE) {
1892 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1897 ZeroMemory(&ov, sizeof(ov));
1898 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1899 ret = ConnectNamedPipe(s->hcom, &ov);
1901 fprintf(stderr, "Failed ConnectNamedPipe\n");
1905 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1907 fprintf(stderr, "Failed GetOverlappedResult\n");
1909 CloseHandle(ov.hEvent);
1916 CloseHandle(ov.hEvent);
1919 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1928 static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
1930 const char *filename = qemu_opt_get(opts, "path");
1931 CharDriverState *chr;
1934 chr = g_malloc0(sizeof(CharDriverState));
1935 s = g_malloc0(sizeof(WinCharState));
1937 chr->chr_write = win_chr_write;
1938 chr->chr_close = win_chr_close;
1940 if (win_chr_pipe_init(chr, filename) < 0) {
1945 qemu_chr_generic_open(chr);
1949 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1951 CharDriverState *chr;
1954 chr = g_malloc0(sizeof(CharDriverState));
1955 s = g_malloc0(sizeof(WinCharState));
1958 chr->chr_write = win_chr_write;
1959 qemu_chr_generic_open(chr);
1963 static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
1965 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1968 static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
1970 const char *file_out = qemu_opt_get(opts, "path");
1973 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1974 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1975 if (fd_out == INVALID_HANDLE_VALUE) {
1979 return qemu_chr_open_win_file(fd_out);
1982 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1984 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1991 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2001 static void win_stdio_wait_func(void *opaque)
2003 CharDriverState *chr = opaque;
2004 WinStdioCharState *stdio = chr->opaque;
2005 INPUT_RECORD buf[4];
2010 ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
2014 /* Avoid error storm */
2015 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2019 for (i = 0; i < dwSize; i++) {
2020 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2022 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2024 if (kev->uChar.AsciiChar != 0) {
2025 for (j = 0; j < kev->wRepeatCount; j++) {
2026 if (qemu_chr_be_can_write(chr)) {
2027 uint8_t c = kev->uChar.AsciiChar;
2028 qemu_chr_be_write(chr, &c, 1);
2036 static DWORD WINAPI win_stdio_thread(LPVOID param)
2038 CharDriverState *chr = param;
2039 WinStdioCharState *stdio = chr->opaque;
2045 /* Wait for one byte */
2046 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2048 /* Exit in case of error, continue if nothing read */
2056 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2057 if (stdio->win_stdio_buf == '\r') {
2061 /* Signal the main thread and wait until the byte was eaten */
2062 if (!SetEvent(stdio->hInputReadyEvent)) {
2065 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2071 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2075 static void win_stdio_thread_wait_func(void *opaque)
2077 CharDriverState *chr = opaque;
2078 WinStdioCharState *stdio = chr->opaque;
2080 if (qemu_chr_be_can_write(chr)) {
2081 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2084 SetEvent(stdio->hInputDoneEvent);
2087 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2089 WinStdioCharState *stdio = chr->opaque;
2092 GetConsoleMode(stdio->hStdIn, &dwMode);
2095 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2097 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2101 static void win_stdio_close(CharDriverState *chr)
2103 WinStdioCharState *stdio = chr->opaque;
2105 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2106 CloseHandle(stdio->hInputReadyEvent);
2108 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2109 CloseHandle(stdio->hInputDoneEvent);
2111 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2112 TerminateThread(stdio->hInputThread, 0);
2115 g_free(chr->opaque);
2119 static CharDriverState *qemu_chr_open_win_stdio(QemuOpts *opts)
2121 CharDriverState *chr;
2122 WinStdioCharState *stdio;
2126 chr = g_malloc0(sizeof(CharDriverState));
2127 stdio = g_malloc0(sizeof(WinStdioCharState));
2129 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2130 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2131 fprintf(stderr, "cannot open stdio: invalid handle\n");
2135 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2137 chr->opaque = stdio;
2138 chr->chr_write = win_stdio_write;
2139 chr->chr_close = win_stdio_close;
2142 if (qemu_add_wait_object(stdio->hStdIn,
2143 win_stdio_wait_func, chr)) {
2144 fprintf(stderr, "qemu_add_wait_object: failed\n");
2149 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2150 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2151 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2154 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2155 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2156 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2157 fprintf(stderr, "cannot create stdio thread or event\n");
2160 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2161 win_stdio_thread_wait_func, chr)) {
2162 fprintf(stderr, "qemu_add_wait_object: failed\n");
2166 dwMode |= ENABLE_LINE_INPUT;
2169 /* set the terminal in raw mode */
2170 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2171 dwMode |= ENABLE_PROCESSED_INPUT;
2174 SetConsoleMode(stdio->hStdIn, dwMode);
2176 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2177 qemu_chr_fe_set_echo(chr, false);
2181 #endif /* !_WIN32 */
2184 /***********************************************************/
2185 /* UDP Net console */
2191 uint8_t buf[READ_BUF_LEN];
2197 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2199 NetCharDriver *s = chr->opaque;
2200 gsize bytes_written;
2203 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2204 if (status == G_IO_STATUS_EOF) {
2206 } else if (status != G_IO_STATUS_NORMAL) {
2210 return bytes_written;
2213 static int udp_chr_read_poll(void *opaque)
2215 CharDriverState *chr = opaque;
2216 NetCharDriver *s = chr->opaque;
2218 s->max_size = qemu_chr_be_can_write(chr);
2220 /* If there were any stray characters in the queue process them
2223 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2224 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2226 s->max_size = qemu_chr_be_can_write(chr);
2231 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2233 CharDriverState *chr = opaque;
2234 NetCharDriver *s = chr->opaque;
2235 gsize bytes_read = 0;
2238 if (s->max_size == 0)
2240 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2242 s->bufcnt = bytes_read;
2243 s->bufptr = s->bufcnt;
2244 if (status != G_IO_STATUS_NORMAL) {
2249 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2250 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2252 s->max_size = qemu_chr_be_can_write(chr);
2258 static void udp_chr_update_read_handler(CharDriverState *chr)
2260 NetCharDriver *s = chr->opaque;
2263 g_source_remove(s->tag);
2268 s->tag = io_add_watch_poll(s->chan, udp_chr_read_poll, udp_chr_read, chr);
2272 static void udp_chr_close(CharDriverState *chr)
2274 NetCharDriver *s = chr->opaque;
2276 g_source_remove(s->tag);
2279 g_io_channel_unref(s->chan);
2283 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2286 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2288 CharDriverState *chr = NULL;
2289 NetCharDriver *s = NULL;
2290 Error *local_err = NULL;
2293 chr = g_malloc0(sizeof(CharDriverState));
2294 s = g_malloc0(sizeof(NetCharDriver));
2296 fd = inet_dgram_opts(opts, &local_err);
2302 s->chan = io_channel_from_socket(s->fd);
2306 chr->chr_write = udp_chr_write;
2307 chr->chr_update_read_handler = udp_chr_update_read_handler;
2308 chr->chr_close = udp_chr_close;
2313 qerror_report_err(local_err);
2314 error_free(local_err);
2324 /***********************************************************/
2325 /* TCP Net console */
2329 GIOChannel *chan, *listen_chan;
2330 guint tag, listen_tag;
2340 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2342 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2344 TCPCharDriver *s = chr->opaque;
2346 return io_channel_send_all(s->chan, buf, len);
2348 /* XXX: indicate an error ? */
2353 static int tcp_chr_read_poll(void *opaque)
2355 CharDriverState *chr = opaque;
2356 TCPCharDriver *s = chr->opaque;
2359 s->max_size = qemu_chr_be_can_write(chr);
2364 #define IAC_BREAK 243
2365 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2367 uint8_t *buf, int *size)
2369 /* Handle any telnet client's basic IAC options to satisfy char by
2370 * char mode with no echo. All IAC options will be removed from
2371 * the buf and the do_telnetopt variable will be used to track the
2372 * state of the width of the IAC information.
2374 * IAC commands come in sets of 3 bytes with the exception of the
2375 * "IAC BREAK" command and the double IAC.
2381 for (i = 0; i < *size; i++) {
2382 if (s->do_telnetopt > 1) {
2383 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2384 /* Double IAC means send an IAC */
2388 s->do_telnetopt = 1;
2390 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2391 /* Handle IAC break commands by sending a serial break */
2392 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2397 if (s->do_telnetopt >= 4) {
2398 s->do_telnetopt = 1;
2401 if ((unsigned char)buf[i] == IAC) {
2402 s->do_telnetopt = 2;
2413 static int tcp_get_msgfd(CharDriverState *chr)
2415 TCPCharDriver *s = chr->opaque;
2422 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2424 TCPCharDriver *s = chr->opaque;
2425 struct cmsghdr *cmsg;
2427 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2430 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2431 cmsg->cmsg_level != SOL_SOCKET ||
2432 cmsg->cmsg_type != SCM_RIGHTS)
2435 fd = *((int *)CMSG_DATA(cmsg));
2439 #ifndef MSG_CMSG_CLOEXEC
2440 qemu_set_cloexec(fd);
2448 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2450 TCPCharDriver *s = chr->opaque;
2451 struct msghdr msg = { NULL, };
2452 struct iovec iov[1];
2454 struct cmsghdr cmsg;
2455 char control[CMSG_SPACE(sizeof(int))];
2460 iov[0].iov_base = buf;
2461 iov[0].iov_len = len;
2465 msg.msg_control = &msg_control;
2466 msg.msg_controllen = sizeof(msg_control);
2468 #ifdef MSG_CMSG_CLOEXEC
2469 flags |= MSG_CMSG_CLOEXEC;
2471 ret = recvmsg(s->fd, &msg, flags);
2472 if (ret > 0 && s->is_unix) {
2473 unix_process_msgfd(chr, &msg);
2479 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2481 TCPCharDriver *s = chr->opaque;
2482 return qemu_recv(s->fd, buf, len, 0);
2486 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2488 TCPCharDriver *s = chr->opaque;
2489 return g_io_create_watch(s->chan, cond);
2492 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2494 CharDriverState *chr = opaque;
2495 TCPCharDriver *s = chr->opaque;
2496 uint8_t buf[READ_BUF_LEN];
2499 if (!s->connected || s->max_size <= 0) {
2503 if (len > s->max_size)
2505 size = tcp_chr_recv(chr, (void *)buf, len);
2507 /* connection closed */
2509 if (s->listen_chan) {
2510 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2512 g_source_remove(s->tag);
2514 g_io_channel_unref(s->chan);
2518 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2519 } else if (size > 0) {
2520 if (s->do_telnetopt)
2521 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2523 qemu_chr_be_write(chr, buf, size);
2530 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2532 return qemu_chr_open_fd(eventfd, eventfd);
2536 static void tcp_chr_connect(void *opaque)
2538 CharDriverState *chr = opaque;
2539 TCPCharDriver *s = chr->opaque;
2543 s->tag = io_add_watch_poll(s->chan, tcp_chr_read_poll, tcp_chr_read, chr);
2545 qemu_chr_generic_open(chr);
2548 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2549 static void tcp_chr_telnet_init(int fd)
2552 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2553 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2554 send(fd, (char *)buf, 3, 0);
2555 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2556 send(fd, (char *)buf, 3, 0);
2557 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2558 send(fd, (char *)buf, 3, 0);
2559 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2560 send(fd, (char *)buf, 3, 0);
2563 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2565 TCPCharDriver *s = chr->opaque;
2569 socket_set_nonblock(fd);
2571 socket_set_nodelay(fd);
2573 s->chan = io_channel_from_socket(fd);
2574 g_source_remove(s->listen_tag);
2576 tcp_chr_connect(chr);
2581 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2583 CharDriverState *chr = opaque;
2584 TCPCharDriver *s = chr->opaque;
2585 struct sockaddr_in saddr;
2587 struct sockaddr_un uaddr;
2589 struct sockaddr *addr;
2596 len = sizeof(uaddr);
2597 addr = (struct sockaddr *)&uaddr;
2601 len = sizeof(saddr);
2602 addr = (struct sockaddr *)&saddr;
2604 fd = qemu_accept(s->listen_fd, addr, &len);
2605 if (fd < 0 && errno != EINTR) {
2607 } else if (fd >= 0) {
2608 if (s->do_telnetopt)
2609 tcp_chr_telnet_init(fd);
2613 if (tcp_chr_add_client(chr, fd) < 0)
2619 static void tcp_chr_close(CharDriverState *chr)
2621 TCPCharDriver *s = chr->opaque;
2624 g_source_remove(s->tag);
2627 g_io_channel_unref(s->chan);
2631 if (s->listen_fd >= 0) {
2632 if (s->listen_tag) {
2633 g_source_remove(s->listen_tag);
2635 if (s->listen_chan) {
2636 g_io_channel_unref(s->listen_chan);
2638 closesocket(s->listen_fd);
2641 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2644 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2645 bool is_listen, bool is_telnet,
2646 bool is_waitconnect,
2649 CharDriverState *chr = NULL;
2650 TCPCharDriver *s = NULL;
2651 char host[NI_MAXHOST], serv[NI_MAXSERV];
2652 const char *left = "", *right = "";
2653 struct sockaddr_storage ss;
2654 socklen_t ss_len = sizeof(ss);
2656 memset(&ss, 0, ss_len);
2657 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2658 error_setg(errp, "getsockname: %s", strerror(errno));
2662 chr = g_malloc0(sizeof(CharDriverState));
2663 s = g_malloc0(sizeof(TCPCharDriver));
2670 chr->filename = g_malloc(256);
2671 switch (ss.ss_family) {
2675 snprintf(chr->filename, 256, "unix:%s%s",
2676 ((struct sockaddr_un *)(&ss))->sun_path,
2677 is_listen ? ",server" : "");
2685 s->do_nodelay = do_nodelay;
2686 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2687 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2688 snprintf(chr->filename, 256, "%s:%s:%s%s%s%s",
2689 is_telnet ? "telnet" : "tcp",
2690 left, host, right, serv,
2691 is_listen ? ",server" : "");
2696 chr->chr_write = tcp_chr_write;
2697 chr->chr_close = tcp_chr_close;
2698 chr->get_msgfd = tcp_get_msgfd;
2699 chr->chr_add_client = tcp_chr_add_client;
2700 chr->chr_add_watch = tcp_chr_add_watch;
2704 s->listen_chan = io_channel_from_socket(s->listen_fd);
2705 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2707 s->do_telnetopt = 1;
2712 socket_set_nodelay(fd);
2713 s->chan = io_channel_from_socket(s->fd);
2714 tcp_chr_connect(chr);
2717 if (is_listen && is_waitconnect) {
2718 printf("QEMU waiting for connection on: %s\n",
2720 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2721 socket_set_nonblock(s->listen_fd);
2726 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2728 CharDriverState *chr = NULL;
2729 Error *local_err = NULL;
2737 is_listen = qemu_opt_get_bool(opts, "server", 0);
2738 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2739 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2740 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2741 is_unix = qemu_opt_get(opts, "path") != NULL;
2747 fd = unix_listen_opts(opts, &local_err);
2749 fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2753 fd = inet_listen_opts(opts, 0, &local_err);
2755 fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2762 if (!is_waitconnect)
2763 socket_set_nonblock(fd);
2765 chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2766 is_waitconnect, &local_err);
2767 if (error_is_set(&local_err)) {
2775 qerror_report_err(local_err);
2776 error_free(local_err);
2782 g_free(chr->opaque);
2788 /***********************************************************/
2789 /* Memory chardev */
2792 size_t outbuf_capacity;
2796 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2798 MemoryDriver *d = chr->opaque;
2800 /* TODO: the QString implementation has the same code, we should
2801 * introduce a generic way to do this in cutils.c */
2802 if (d->outbuf_capacity < d->outbuf_size + len) {
2804 d->outbuf_capacity += len;
2805 d->outbuf_capacity *= 2;
2806 d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
2809 memcpy(d->outbuf + d->outbuf_size, buf, len);
2810 d->outbuf_size += len;
2815 void qemu_chr_init_mem(CharDriverState *chr)
2819 d = g_malloc(sizeof(*d));
2821 d->outbuf_capacity = 4096;
2822 d->outbuf = g_malloc0(d->outbuf_capacity);
2824 memset(chr, 0, sizeof(*chr));
2826 chr->chr_write = mem_chr_write;
2829 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2831 MemoryDriver *d = chr->opaque;
2832 return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2835 /* NOTE: this driver can not be closed with qemu_chr_delete()! */
2836 void qemu_chr_close_mem(CharDriverState *chr)
2838 MemoryDriver *d = chr->opaque;
2841 g_free(chr->opaque);
2843 chr->chr_write = NULL;
2846 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2848 const MemoryDriver *d = chr->opaque;
2849 return d->outbuf_size;
2852 /*********************************************************/
2853 /* Ring buffer chardev */
2860 } RingBufCharDriver;
2862 static size_t ringbuf_count(const CharDriverState *chr)
2864 const RingBufCharDriver *d = chr->opaque;
2866 return d->prod - d->cons;
2869 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2871 RingBufCharDriver *d = chr->opaque;
2874 if (!buf || (len < 0)) {
2878 for (i = 0; i < len; i++ ) {
2879 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2880 if (d->prod - d->cons > d->size) {
2881 d->cons = d->prod - d->size;
2888 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2890 RingBufCharDriver *d = chr->opaque;
2893 for (i = 0; i < len && d->cons != d->prod; i++) {
2894 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2900 static void ringbuf_chr_close(struct CharDriverState *chr)
2902 RingBufCharDriver *d = chr->opaque;
2909 static CharDriverState *qemu_chr_open_ringbuf(QemuOpts *opts)
2911 CharDriverState *chr;
2912 RingBufCharDriver *d;
2914 chr = g_malloc0(sizeof(CharDriverState));
2915 d = g_malloc(sizeof(*d));
2917 d->size = qemu_opt_get_size(opts, "size", 0);
2922 /* The size must be power of 2 */
2923 if (d->size & (d->size - 1)) {
2924 error_report("size of ringbuf device must be power of two");
2930 d->cbuf = g_malloc0(d->size);
2933 chr->chr_write = ringbuf_chr_write;
2934 chr->chr_close = ringbuf_chr_close;
2944 static bool chr_is_ringbuf(const CharDriverState *chr)
2946 return chr->chr_write == ringbuf_chr_write;
2949 void qmp_ringbuf_write(const char *device, const char *data,
2950 bool has_format, enum DataFormat format,
2953 CharDriverState *chr;
2954 const uint8_t *write_data;
2958 chr = qemu_chr_find(device);
2960 error_setg(errp, "Device '%s' not found", device);
2964 if (!chr_is_ringbuf(chr)) {
2965 error_setg(errp,"%s is not a ringbuf device", device);
2969 if (has_format && (format == DATA_FORMAT_BASE64)) {
2970 write_data = g_base64_decode(data, &write_count);
2972 write_data = (uint8_t *)data;
2973 write_count = strlen(data);
2976 ret = ringbuf_chr_write(chr, write_data, write_count);
2978 if (write_data != (uint8_t *)data) {
2979 g_free((void *)write_data);
2983 error_setg(errp, "Failed to write to device %s", device);
2988 char *qmp_ringbuf_read(const char *device, int64_t size,
2989 bool has_format, enum DataFormat format,
2992 CharDriverState *chr;
2997 chr = qemu_chr_find(device);
2999 error_setg(errp, "Device '%s' not found", device);
3003 if (!chr_is_ringbuf(chr)) {
3004 error_setg(errp,"%s is not a ringbuf device", device);
3009 error_setg(errp, "size must be greater than zero");
3013 count = ringbuf_count(chr);
3014 size = size > count ? count : size;
3015 read_data = g_malloc(size + 1);
3017 ringbuf_chr_read(chr, read_data, size);
3019 if (has_format && (format == DATA_FORMAT_BASE64)) {
3020 data = g_base64_encode(read_data, size);
3024 * FIXME should read only complete, valid UTF-8 characters up
3025 * to @size bytes. Invalid sequences should be replaced by a
3026 * suitable replacement character. Except when (and only
3027 * when) ring buffer lost characters since last read, initial
3028 * continuation characters should be dropped.
3030 read_data[size] = 0;
3031 data = (char *)read_data;
3037 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3039 char host[65], port[33], width[8], height[8];
3043 Error *local_err = NULL;
3045 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3046 if (error_is_set(&local_err)) {
3047 qerror_report_err(local_err);
3048 error_free(local_err);
3052 if (strstart(filename, "mon:", &p)) {
3054 qemu_opt_set(opts, "mux", "on");
3057 if (strcmp(filename, "null") == 0 ||
3058 strcmp(filename, "pty") == 0 ||
3059 strcmp(filename, "msmouse") == 0 ||
3060 strcmp(filename, "braille") == 0 ||
3061 strcmp(filename, "stdio") == 0) {
3062 qemu_opt_set(opts, "backend", filename);
3065 if (strstart(filename, "vc", &p)) {
3066 qemu_opt_set(opts, "backend", "vc");
3068 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
3070 qemu_opt_set(opts, "width", width);
3071 qemu_opt_set(opts, "height", height);
3072 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
3074 qemu_opt_set(opts, "cols", width);
3075 qemu_opt_set(opts, "rows", height);
3082 if (strcmp(filename, "con:") == 0) {
3083 qemu_opt_set(opts, "backend", "console");
3086 if (strstart(filename, "COM", NULL)) {
3087 qemu_opt_set(opts, "backend", "serial");
3088 qemu_opt_set(opts, "path", filename);
3091 if (strstart(filename, "file:", &p)) {
3092 qemu_opt_set(opts, "backend", "file");
3093 qemu_opt_set(opts, "path", p);
3096 if (strstart(filename, "pipe:", &p)) {
3097 qemu_opt_set(opts, "backend", "pipe");
3098 qemu_opt_set(opts, "path", p);
3101 if (strstart(filename, "tcp:", &p) ||
3102 strstart(filename, "telnet:", &p)) {
3103 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3105 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3108 qemu_opt_set(opts, "backend", "socket");
3109 qemu_opt_set(opts, "host", host);
3110 qemu_opt_set(opts, "port", port);
3111 if (p[pos] == ',') {
3112 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3115 if (strstart(filename, "telnet:", &p))
3116 qemu_opt_set(opts, "telnet", "on");
3119 if (strstart(filename, "udp:", &p)) {
3120 qemu_opt_set(opts, "backend", "udp");
3121 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3123 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3127 qemu_opt_set(opts, "host", host);
3128 qemu_opt_set(opts, "port", port);
3129 if (p[pos] == '@') {
3131 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3133 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3137 qemu_opt_set(opts, "localaddr", host);
3138 qemu_opt_set(opts, "localport", port);
3142 if (strstart(filename, "unix:", &p)) {
3143 qemu_opt_set(opts, "backend", "socket");
3144 if (qemu_opts_do_parse(opts, p, "path") != 0)
3148 if (strstart(filename, "/dev/parport", NULL) ||
3149 strstart(filename, "/dev/ppi", NULL)) {
3150 qemu_opt_set(opts, "backend", "parport");
3151 qemu_opt_set(opts, "path", filename);
3154 if (strstart(filename, "/dev/", NULL)) {
3155 qemu_opt_set(opts, "backend", "tty");
3156 qemu_opt_set(opts, "path", filename);
3161 qemu_opts_del(opts);
3165 #ifdef HAVE_CHARDEV_PARPORT
3167 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
3169 const char *filename = qemu_opt_get(opts, "path");
3172 fd = qemu_open(filename, O_RDWR);
3176 return qemu_chr_open_pp_fd(fd);
3181 typedef struct CharDriver {
3183 CharDriverState *(*open)(QemuOpts *opts);
3186 static GSList *backends;
3188 void register_char_driver(const char *name, CharDriverState *(*open)(QemuOpts *))
3192 s = g_malloc0(sizeof(*s));
3193 s->name = g_strdup(name);
3196 backends = g_slist_append(backends, s);
3199 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3200 void (*init)(struct CharDriverState *s),
3204 CharDriverState *chr;
3207 if (qemu_opts_id(opts) == NULL) {
3208 error_setg(errp, "chardev: no id specified");
3212 if (qemu_opt_get(opts, "backend") == NULL) {
3213 error_setg(errp, "chardev: \"%s\" missing backend",
3214 qemu_opts_id(opts));
3217 for (i = backends; i; i = i->next) {
3220 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3225 error_setg(errp, "chardev: backend \"%s\" not found",
3226 qemu_opt_get(opts, "backend"));
3230 chr = cd->open(opts);
3232 error_setg(errp, "chardev: opening backend \"%s\" failed",
3233 qemu_opt_get(opts, "backend"));
3238 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3240 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3242 if (qemu_opt_get_bool(opts, "mux", 0)) {
3243 CharDriverState *base = chr;
3244 int len = strlen(qemu_opts_id(opts)) + 6;
3245 base->label = g_malloc(len);
3246 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3247 chr = qemu_chr_open_mux(base);
3248 chr->filename = base->filename;
3249 chr->avail_connections = MAX_MUX;
3250 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3252 chr->avail_connections = 1;
3254 chr->label = g_strdup(qemu_opts_id(opts));
3259 qemu_opts_del(opts);
3263 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3266 CharDriverState *chr;
3270 if (strstart(filename, "chardev:", &p)) {
3271 return qemu_chr_find(p);
3274 opts = qemu_chr_parse_compat(label, filename);
3278 chr = qemu_chr_new_from_opts(opts, init, &err);
3279 if (error_is_set(&err)) {
3280 fprintf(stderr, "%s\n", error_get_pretty(err));
3283 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3284 monitor_init(chr, MONITOR_USE_READLINE);
3289 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3291 if (chr->chr_set_echo) {
3292 chr->chr_set_echo(chr, echo);
3296 void qemu_chr_fe_open(struct CharDriverState *chr)
3298 if (chr->chr_guest_open) {
3299 chr->chr_guest_open(chr);
3303 void qemu_chr_fe_close(struct CharDriverState *chr)
3305 if (chr->chr_guest_close) {
3306 chr->chr_guest_close(chr);
3310 guint qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3311 GIOFunc func, void *user_data)
3316 if (s->chr_add_watch == NULL) {
3320 src = s->chr_add_watch(s, cond);
3321 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3322 tag = g_source_attach(src, NULL);
3323 g_source_unref(src);
3328 void qemu_chr_delete(CharDriverState *chr)
3330 QTAILQ_REMOVE(&chardevs, chr, next);
3331 if (chr->chr_close) {
3332 chr->chr_close(chr);
3334 g_free(chr->filename);
3337 qemu_opts_del(chr->opts);
3342 ChardevInfoList *qmp_query_chardev(Error **errp)
3344 ChardevInfoList *chr_list = NULL;
3345 CharDriverState *chr;
3347 QTAILQ_FOREACH(chr, &chardevs, next) {
3348 ChardevInfoList *info = g_malloc0(sizeof(*info));
3349 info->value = g_malloc0(sizeof(*info->value));
3350 info->value->label = g_strdup(chr->label);
3351 info->value->filename = g_strdup(chr->filename);
3353 info->next = chr_list;
3360 CharDriverState *qemu_chr_find(const char *name)
3362 CharDriverState *chr;
3364 QTAILQ_FOREACH(chr, &chardevs, next) {
3365 if (strcmp(chr->label, name) != 0)
3372 /* Get a character (serial) device interface. */
3373 CharDriverState *qemu_char_get_next_serial(void)
3375 static int next_serial;
3377 /* FIXME: This function needs to go away: use chardev properties! */
3378 return serial_hds[next_serial++];
3381 QemuOptsList qemu_chardev_opts = {
3383 .implied_opt_name = "backend",
3384 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3388 .type = QEMU_OPT_STRING,
3391 .type = QEMU_OPT_STRING,
3394 .type = QEMU_OPT_STRING,
3397 .type = QEMU_OPT_STRING,
3399 .name = "localaddr",
3400 .type = QEMU_OPT_STRING,
3402 .name = "localport",
3403 .type = QEMU_OPT_STRING,
3406 .type = QEMU_OPT_NUMBER,
3409 .type = QEMU_OPT_BOOL,
3412 .type = QEMU_OPT_BOOL,
3415 .type = QEMU_OPT_BOOL,
3418 .type = QEMU_OPT_BOOL,
3421 .type = QEMU_OPT_BOOL,
3424 .type = QEMU_OPT_BOOL,
3427 .type = QEMU_OPT_NUMBER,
3430 .type = QEMU_OPT_NUMBER,
3433 .type = QEMU_OPT_NUMBER,
3436 .type = QEMU_OPT_NUMBER,
3439 .type = QEMU_OPT_BOOL,
3442 .type = QEMU_OPT_BOOL,
3445 .type = QEMU_OPT_STRING,
3448 .type = QEMU_OPT_NUMBER,
3451 .type = QEMU_OPT_SIZE,
3453 { /* end of list */ }
3459 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3464 error_setg(errp, "input file not supported");
3468 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3469 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3470 if (out == INVALID_HANDLE_VALUE) {
3471 error_setg(errp, "open %s failed", file->out);
3474 return qemu_chr_open_win_file(out);
3477 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3480 return qemu_chr_open_win_path(serial->device);
3483 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3486 error_setg(errp, "character device backend type 'parallel' not supported");
3492 static int qmp_chardev_open_file_source(char *src, int flags,
3497 TFR(fd = qemu_open(src, flags, 0666));
3499 error_setg(errp, "open %s: %s", src, strerror(errno));
3504 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3506 int flags, in = -1, out = -1;
3508 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3509 out = qmp_chardev_open_file_source(file->out, flags, errp);
3510 if (error_is_set(errp)) {
3516 in = qmp_chardev_open_file_source(file->in, flags, errp);
3517 if (error_is_set(errp)) {
3523 return qemu_chr_open_fd(in, out);
3526 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3529 #ifdef HAVE_CHARDEV_TTY
3532 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3533 if (error_is_set(errp)) {
3536 socket_set_nonblock(fd);
3537 return qemu_chr_open_tty_fd(fd);
3539 error_setg(errp, "character device backend type 'serial' not supported");
3544 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3547 #ifdef HAVE_CHARDEV_PARPORT
3550 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3551 if (error_is_set(errp)) {
3554 return qemu_chr_open_pp_fd(fd);
3556 error_setg(errp, "character device backend type 'parallel' not supported");
3563 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3566 SocketAddress *addr = sock->addr;
3567 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3568 bool is_listen = sock->has_server ? sock->server : true;
3569 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3570 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3574 fd = socket_listen(addr, errp);
3576 fd = socket_connect(addr, errp, NULL, NULL);
3578 if (error_is_set(errp)) {
3581 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3582 is_telnet, is_waitconnect, errp);
3585 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3588 ChardevReturn *ret = g_new0(ChardevReturn, 1);
3589 CharDriverState *chr = NULL;
3591 chr = qemu_chr_find(id);
3593 error_setg(errp, "Chardev '%s' already exists", id);
3598 switch (backend->kind) {
3599 case CHARDEV_BACKEND_KIND_FILE:
3600 chr = qmp_chardev_open_file(backend->file, errp);
3602 case CHARDEV_BACKEND_KIND_SERIAL:
3603 chr = qmp_chardev_open_serial(backend->serial, errp);
3605 case CHARDEV_BACKEND_KIND_PARALLEL:
3606 chr = qmp_chardev_open_parallel(backend->parallel, errp);
3608 case CHARDEV_BACKEND_KIND_SOCKET:
3609 chr = qmp_chardev_open_socket(backend->socket, errp);
3611 #ifdef HAVE_CHARDEV_TTY
3612 case CHARDEV_BACKEND_KIND_PTY:
3614 /* qemu_chr_open_pty sets "path" in opts */
3616 opts = qemu_opts_create_nofail(qemu_find_opts("chardev"));
3617 chr = qemu_chr_open_pty(opts);
3618 ret->pty = g_strdup(qemu_opt_get(opts, "path"));
3619 ret->has_pty = true;
3620 qemu_opts_del(opts);
3624 case CHARDEV_BACKEND_KIND_NULL:
3625 chr = qemu_chr_open_null(NULL);
3628 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3632 if (chr == NULL && !error_is_set(errp)) {
3633 error_setg(errp, "Failed to create chardev");
3636 chr->label = g_strdup(id);
3637 chr->avail_connections = 1;
3638 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3646 void qmp_chardev_remove(const char *id, Error **errp)
3648 CharDriverState *chr;
3650 chr = qemu_chr_find(id);
3652 error_setg(errp, "Chardev '%s' not found", id);
3655 if (chr->chr_can_read || chr->chr_read ||
3656 chr->chr_event || chr->handler_opaque) {
3657 error_setg(errp, "Chardev '%s' is busy", id);
3660 qemu_chr_delete(chr);
3663 static void register_types(void)
3665 register_char_driver("null", qemu_chr_open_null);
3666 register_char_driver("socket", qemu_chr_open_socket);
3667 register_char_driver("udp", qemu_chr_open_udp);
3668 register_char_driver("memory", qemu_chr_open_ringbuf);
3670 register_char_driver("file", qemu_chr_open_win_file_out);
3671 register_char_driver("pipe", qemu_chr_open_win_pipe);
3672 register_char_driver("console", qemu_chr_open_win_con);
3673 register_char_driver("serial", qemu_chr_open_win);
3674 register_char_driver("stdio", qemu_chr_open_win_stdio);
3676 register_char_driver("file", qemu_chr_open_file_out);
3677 register_char_driver("pipe", qemu_chr_open_pipe);
3678 register_char_driver("stdio", qemu_chr_open_stdio);
3680 #ifdef HAVE_CHARDEV_TTY
3681 register_char_driver("tty", qemu_chr_open_tty);
3682 register_char_driver("serial", qemu_chr_open_tty);
3683 register_char_driver("pty", qemu_chr_open_pty);
3685 #ifdef HAVE_CHARDEV_PARPORT
3686 register_char_driver("parallel", qemu_chr_open_pp);
3687 register_char_driver("parport", qemu_chr_open_pp);
3691 type_init(register_types);