4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 #include "qemu-common.h"
25 #include "monitor/monitor.h"
26 #include "ui/console.h"
27 #include "sysemu/sysemu.h"
28 #include "qemu/timer.h"
29 #include "char/char.h"
32 #include "hw/msmouse.h"
33 #include "qmp-commands.h"
43 #include <sys/times.h>
47 #include <sys/ioctl.h>
48 #include <sys/resource.h>
49 #include <sys/socket.h>
50 #include <netinet/in.h>
52 #include <arpa/inet.h>
55 #include <sys/select.h>
58 #if defined(__GLIBC__)
60 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
65 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
66 #include <dev/ppbus/ppi.h>
67 #include <dev/ppbus/ppbconf.h>
68 #elif defined(__DragonFly__)
69 #include <dev/misc/ppi/ppi.h>
70 #include <bus/ppbus/ppbconf.h>
76 #include <linux/ppdev.h>
77 #include <linux/parport.h>
81 #include <sys/ethernet.h>
82 #include <sys/sockio.h>
83 #include <netinet/arp.h>
84 #include <netinet/in.h>
85 #include <netinet/in_systm.h>
86 #include <netinet/ip.h>
87 #include <netinet/ip_icmp.h> // must come after ip.h
88 #include <netinet/udp.h>
89 #include <netinet/tcp.h>
97 #include "qemu/sockets.h"
98 #include "ui/qemu-spice.h"
100 #define READ_BUF_LEN 4096
102 /***********************************************************/
103 /* character device */
105 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
106 QTAILQ_HEAD_INITIALIZER(chardevs);
108 void qemu_chr_be_event(CharDriverState *s, int event)
110 /* Keep track if the char device is open */
112 case CHR_EVENT_OPENED:
115 case CHR_EVENT_CLOSED:
122 s->chr_event(s->handler_opaque, event);
125 static void qemu_chr_fire_open_event(void *opaque)
127 CharDriverState *s = opaque;
128 qemu_chr_be_event(s, CHR_EVENT_OPENED);
129 qemu_free_timer(s->open_timer);
130 s->open_timer = NULL;
133 void qemu_chr_generic_open(CharDriverState *s)
135 if (s->open_timer == NULL) {
136 s->open_timer = qemu_new_timer_ms(rt_clock,
137 qemu_chr_fire_open_event, s);
138 qemu_mod_timer(s->open_timer, qemu_get_clock_ms(rt_clock) - 1);
142 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
144 return s->chr_write(s, buf, len);
147 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
151 return s->chr_ioctl(s, cmd, arg);
154 int qemu_chr_be_can_write(CharDriverState *s)
156 if (!s->chr_can_read)
158 return s->chr_can_read(s->handler_opaque);
161 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
164 s->chr_read(s->handler_opaque, buf, len);
168 int qemu_chr_fe_get_msgfd(CharDriverState *s)
170 return s->get_msgfd ? s->get_msgfd(s) : -1;
173 int qemu_chr_add_client(CharDriverState *s, int fd)
175 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
178 void qemu_chr_accept_input(CharDriverState *s)
180 if (s->chr_accept_input)
181 s->chr_accept_input(s);
185 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
187 char buf[READ_BUF_LEN];
190 vsnprintf(buf, sizeof(buf), fmt, ap);
191 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
195 void qemu_chr_add_handlers(CharDriverState *s,
196 IOCanReadHandler *fd_can_read,
197 IOReadHandler *fd_read,
198 IOEventHandler *fd_event,
201 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
202 /* chr driver being released. */
203 ++s->avail_connections;
205 s->chr_can_read = fd_can_read;
206 s->chr_read = fd_read;
207 s->chr_event = fd_event;
208 s->handler_opaque = opaque;
209 if (s->chr_update_read_handler)
210 s->chr_update_read_handler(s);
212 /* We're connecting to an already opened device, so let's make sure we
213 also get the open event */
215 qemu_chr_generic_open(s);
219 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
224 static CharDriverState *qemu_chr_open_null(QemuOpts *opts)
226 CharDriverState *chr;
228 chr = g_malloc0(sizeof(CharDriverState));
229 chr->chr_write = null_chr_write;
233 /* MUX driver for serial I/O splitting */
235 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
236 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
238 IOCanReadHandler *chr_can_read[MAX_MUX];
239 IOReadHandler *chr_read[MAX_MUX];
240 IOEventHandler *chr_event[MAX_MUX];
241 void *ext_opaque[MAX_MUX];
242 CharDriverState *drv;
247 /* Intermediate input buffer allows to catch escape sequences even if the
248 currently active device is not accepting any input - but only until it
250 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
255 int64_t timestamps_start;
259 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
261 MuxDriver *d = chr->opaque;
263 if (!d->timestamps) {
264 ret = d->drv->chr_write(d->drv, buf, len);
269 for (i = 0; i < len; i++) {
275 ti = qemu_get_clock_ms(rt_clock);
276 if (d->timestamps_start == -1)
277 d->timestamps_start = ti;
278 ti -= d->timestamps_start;
280 snprintf(buf1, sizeof(buf1),
281 "[%02d:%02d:%02d.%03d] ",
286 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
289 ret += d->drv->chr_write(d->drv, buf+i, 1);
290 if (buf[i] == '\n') {
298 static const char * const mux_help[] = {
299 "% h print this help\n\r",
300 "% x exit emulator\n\r",
301 "% s save disk data back to file (if -snapshot)\n\r",
302 "% t toggle console timestamps\n\r"
303 "% b send break (magic sysrq)\n\r",
304 "% c switch between console and monitor\n\r",
309 int term_escape_char = 0x01; /* ctrl-a is used for escape */
310 static void mux_print_help(CharDriverState *chr)
313 char ebuf[15] = "Escape-Char";
314 char cbuf[50] = "\n\r";
316 if (term_escape_char > 0 && term_escape_char < 26) {
317 snprintf(cbuf, sizeof(cbuf), "\n\r");
318 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
320 snprintf(cbuf, sizeof(cbuf),
321 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
324 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
325 for (i = 0; mux_help[i] != NULL; i++) {
326 for (j=0; mux_help[i][j] != '\0'; j++) {
327 if (mux_help[i][j] == '%')
328 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
330 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
335 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
337 if (d->chr_event[mux_nr])
338 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
341 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
343 if (d->term_got_escape) {
344 d->term_got_escape = 0;
345 if (ch == term_escape_char)
354 const char *term = "QEMU: Terminated\n\r";
355 chr->chr_write(chr,(uint8_t *)term,strlen(term));
363 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
366 /* Switch to the next registered device */
367 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
369 if (d->focus >= d->mux_cnt)
371 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
374 d->timestamps = !d->timestamps;
375 d->timestamps_start = -1;
379 } else if (ch == term_escape_char) {
380 d->term_got_escape = 1;
388 static void mux_chr_accept_input(CharDriverState *chr)
390 MuxDriver *d = chr->opaque;
393 while (d->prod[m] != d->cons[m] &&
394 d->chr_can_read[m] &&
395 d->chr_can_read[m](d->ext_opaque[m])) {
396 d->chr_read[m](d->ext_opaque[m],
397 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
401 static int mux_chr_can_read(void *opaque)
403 CharDriverState *chr = opaque;
404 MuxDriver *d = chr->opaque;
407 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
409 if (d->chr_can_read[m])
410 return d->chr_can_read[m](d->ext_opaque[m]);
414 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
416 CharDriverState *chr = opaque;
417 MuxDriver *d = chr->opaque;
421 mux_chr_accept_input (opaque);
423 for(i = 0; i < size; i++)
424 if (mux_proc_byte(chr, d, buf[i])) {
425 if (d->prod[m] == d->cons[m] &&
426 d->chr_can_read[m] &&
427 d->chr_can_read[m](d->ext_opaque[m]))
428 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
430 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
434 static void mux_chr_event(void *opaque, int event)
436 CharDriverState *chr = opaque;
437 MuxDriver *d = chr->opaque;
440 /* Send the event to all registered listeners */
441 for (i = 0; i < d->mux_cnt; i++)
442 mux_chr_send_event(d, i, event);
445 static void mux_chr_update_read_handler(CharDriverState *chr)
447 MuxDriver *d = chr->opaque;
449 if (d->mux_cnt >= MAX_MUX) {
450 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
453 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
454 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
455 d->chr_read[d->mux_cnt] = chr->chr_read;
456 d->chr_event[d->mux_cnt] = chr->chr_event;
457 /* Fix up the real driver with mux routines */
458 if (d->mux_cnt == 0) {
459 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
462 if (d->focus != -1) {
463 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
465 d->focus = d->mux_cnt;
467 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
470 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
472 CharDriverState *chr;
475 chr = g_malloc0(sizeof(CharDriverState));
476 d = g_malloc0(sizeof(MuxDriver));
481 chr->chr_write = mux_chr_write;
482 chr->chr_update_read_handler = mux_chr_update_read_handler;
483 chr->chr_accept_input = mux_chr_accept_input;
484 /* Frontend guest-open / -close notification is not support with muxes */
485 chr->chr_guest_open = NULL;
486 chr->chr_guest_close = NULL;
488 /* Muxes are always open on creation */
489 qemu_chr_generic_open(chr);
496 int send_all(int fd, const void *buf, int len1)
502 ret = send(fd, buf, len, 0);
504 errno = WSAGetLastError();
505 if (errno != WSAEWOULDBLOCK) {
508 } else if (ret == 0) {
520 int send_all(int fd, const void *_buf, int len1)
523 const uint8_t *buf = _buf;
527 ret = write(fd, buf, len);
529 if (errno != EINTR && errno != EAGAIN)
531 } else if (ret == 0) {
544 typedef struct IOWatchPoll
549 IOCanReadHandler *fd_can_read;
552 QTAILQ_ENTRY(IOWatchPoll) node;
555 static QTAILQ_HEAD(, IOWatchPoll) io_watch_poll_list =
556 QTAILQ_HEAD_INITIALIZER(io_watch_poll_list);
558 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
562 QTAILQ_FOREACH(i, &io_watch_poll_list, node) {
563 if (i->src == source) {
571 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
573 IOWatchPoll *iwp = io_watch_poll_from_source(source);
575 iwp->max_size = iwp->fd_can_read(iwp->opaque);
576 if (iwp->max_size == 0) {
580 return g_io_watch_funcs.prepare(source, timeout_);
583 static gboolean io_watch_poll_check(GSource *source)
585 IOWatchPoll *iwp = io_watch_poll_from_source(source);
587 if (iwp->max_size == 0) {
591 return g_io_watch_funcs.check(source);
594 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
597 return g_io_watch_funcs.dispatch(source, callback, user_data);
600 static void io_watch_poll_finalize(GSource *source)
602 IOWatchPoll *iwp = io_watch_poll_from_source(source);
603 QTAILQ_REMOVE(&io_watch_poll_list, iwp, node);
604 g_io_watch_funcs.finalize(source);
607 static GSourceFuncs io_watch_poll_funcs = {
608 .prepare = io_watch_poll_prepare,
609 .check = io_watch_poll_check,
610 .dispatch = io_watch_poll_dispatch,
611 .finalize = io_watch_poll_finalize,
614 /* Can only be used for read */
615 static guint io_add_watch_poll(GIOChannel *channel,
616 IOCanReadHandler *fd_can_read,
624 src = g_io_create_watch(channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
625 g_source_set_funcs(src, &io_watch_poll_funcs);
626 g_source_set_callback(src, (GSourceFunc)fd_read, user_data, NULL);
627 tag = g_source_attach(src, NULL);
630 iwp = g_malloc0(sizeof(*iwp));
633 iwp->fd_can_read = fd_can_read;
634 iwp->opaque = user_data;
636 QTAILQ_INSERT_HEAD(&io_watch_poll_list, iwp, node);
641 static GIOChannel *io_channel_from_fd(int fd)
649 chan = g_io_channel_unix_new(fd);
651 g_io_channel_set_encoding(chan, NULL, NULL);
652 g_io_channel_set_buffered(chan, FALSE);
657 static GIOChannel *io_channel_from_socket(int fd)
666 chan = g_io_channel_win32_new_socket(fd);
668 chan = g_io_channel_unix_new(fd);
671 g_io_channel_set_encoding(chan, NULL, NULL);
672 g_io_channel_set_buffered(chan, FALSE);
677 static int io_channel_send_all(GIOChannel *fd, const void *_buf, int len1)
682 const uint8_t *buf = _buf;
686 status = g_io_channel_write_chars(fd, (const gchar *)buf, len,
687 &bytes_written, NULL);
688 if (status != G_IO_STATUS_NORMAL) {
689 if (status == G_IO_STATUS_AGAIN) {
696 } else if (status == G_IO_STATUS_EOF) {
699 buf += bytes_written;
700 len -= bytes_written;
706 typedef struct FDCharDriver {
707 CharDriverState *chr;
708 GIOChannel *fd_in, *fd_out;
711 QTAILQ_ENTRY(FDCharDriver) node;
714 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
716 FDCharDriver *s = chr->opaque;
718 return io_channel_send_all(s->fd_out, buf, len);
721 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
723 CharDriverState *chr = opaque;
724 FDCharDriver *s = chr->opaque;
726 uint8_t buf[READ_BUF_LEN];
731 if (len > s->max_size) {
738 status = g_io_channel_read_chars(chan, (gchar *)buf,
739 len, &bytes_read, NULL);
740 if (status == G_IO_STATUS_EOF) {
741 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
744 if (status == G_IO_STATUS_NORMAL) {
745 qemu_chr_be_write(chr, buf, bytes_read);
751 static int fd_chr_read_poll(void *opaque)
753 CharDriverState *chr = opaque;
754 FDCharDriver *s = chr->opaque;
756 s->max_size = qemu_chr_be_can_write(chr);
760 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
762 FDCharDriver *s = chr->opaque;
763 return g_io_create_watch(s->fd_out, cond);
766 static void fd_chr_update_read_handler(CharDriverState *chr)
768 FDCharDriver *s = chr->opaque;
771 g_source_remove(s->fd_in_tag);
775 s->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll, fd_chr_read, chr);
779 static void fd_chr_close(struct CharDriverState *chr)
781 FDCharDriver *s = chr->opaque;
784 g_source_remove(s->fd_in_tag);
789 g_io_channel_unref(s->fd_in);
792 g_io_channel_unref(s->fd_out);
796 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
799 /* open a character device to a unix fd */
800 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
802 CharDriverState *chr;
805 chr = g_malloc0(sizeof(CharDriverState));
806 s = g_malloc0(sizeof(FDCharDriver));
807 s->fd_in = io_channel_from_fd(fd_in);
808 s->fd_out = io_channel_from_fd(fd_out);
809 fcntl(fd_out, F_SETFL, O_NONBLOCK);
812 chr->chr_add_watch = fd_chr_add_watch;
813 chr->chr_write = fd_chr_write;
814 chr->chr_update_read_handler = fd_chr_update_read_handler;
815 chr->chr_close = fd_chr_close;
817 qemu_chr_generic_open(chr);
822 static CharDriverState *qemu_chr_open_file_out(QemuOpts *opts)
826 TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
827 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
831 return qemu_chr_open_fd(-1, fd_out);
834 static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)
837 char filename_in[256], filename_out[256];
838 const char *filename = qemu_opt_get(opts, "path");
840 if (filename == NULL) {
841 fprintf(stderr, "chardev: pipe: no filename given\n");
845 snprintf(filename_in, 256, "%s.in", filename);
846 snprintf(filename_out, 256, "%s.out", filename);
847 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
848 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
849 if (fd_in < 0 || fd_out < 0) {
854 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
859 return qemu_chr_open_fd(fd_in, fd_out);
862 /* init terminal so that we can grab keys */
863 static struct termios oldtty;
864 static int old_fd0_flags;
865 static bool stdio_allow_signal;
867 static void term_exit(void)
869 tcsetattr (0, TCSANOW, &oldtty);
870 fcntl(0, F_SETFL, old_fd0_flags);
873 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
879 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
880 |INLCR|IGNCR|ICRNL|IXON);
881 tty.c_oflag |= OPOST;
882 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
883 tty.c_cflag &= ~(CSIZE|PARENB);
888 /* if graphical mode, we allow Ctrl-C handling */
889 if (!stdio_allow_signal)
890 tty.c_lflag &= ~ISIG;
892 tcsetattr (0, TCSANOW, &tty);
895 static void qemu_chr_close_stdio(struct CharDriverState *chr)
901 static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)
903 CharDriverState *chr;
905 if (is_daemonized()) {
906 error_report("cannot use stdio with -daemonize");
909 old_fd0_flags = fcntl(0, F_GETFL);
910 tcgetattr (0, &oldtty);
911 fcntl(0, F_SETFL, O_NONBLOCK);
914 chr = qemu_chr_open_fd(0, 1);
915 chr->chr_close = qemu_chr_close_stdio;
916 chr->chr_set_echo = qemu_chr_set_echo_stdio;
917 stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
918 display_type != DT_NOGRAPHIC);
919 qemu_chr_fe_set_echo(chr, false);
925 /* Once Solaris has openpty(), this is going to be removed. */
926 static int openpty(int *amaster, int *aslave, char *name,
927 struct termios *termp, struct winsize *winp)
930 int mfd = -1, sfd = -1;
932 *amaster = *aslave = -1;
934 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
938 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
941 if ((slave = ptsname(mfd)) == NULL)
944 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
947 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
948 (termp != NULL && tcgetattr(sfd, termp) < 0))
956 ioctl(sfd, TIOCSWINSZ, winp);
967 static void cfmakeraw (struct termios *termios_p)
969 termios_p->c_iflag &=
970 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
971 termios_p->c_oflag &= ~OPOST;
972 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
973 termios_p->c_cflag &= ~(CSIZE|PARENB);
974 termios_p->c_cflag |= CS8;
976 termios_p->c_cc[VMIN] = 0;
977 termios_p->c_cc[VTIME] = 0;
981 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
982 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
983 || defined(__GLIBC__)
985 #define HAVE_CHARDEV_TTY 1
996 static void pty_chr_update_read_handler(CharDriverState *chr);
997 static void pty_chr_state(CharDriverState *chr, int connected);
999 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1001 PtyCharDriver *s = chr->opaque;
1003 if (!s->connected) {
1004 /* guest sends data, check for (re-)connect */
1005 pty_chr_update_read_handler(chr);
1008 return io_channel_send_all(s->fd, buf, len);
1011 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1013 PtyCharDriver *s = chr->opaque;
1014 return g_io_create_watch(s->fd, cond);
1017 static int pty_chr_read_poll(void *opaque)
1019 CharDriverState *chr = opaque;
1020 PtyCharDriver *s = chr->opaque;
1022 s->read_bytes = qemu_chr_be_can_write(chr);
1023 return s->read_bytes;
1026 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1028 CharDriverState *chr = opaque;
1029 PtyCharDriver *s = chr->opaque;
1031 uint8_t buf[READ_BUF_LEN];
1035 if (len > s->read_bytes)
1036 len = s->read_bytes;
1039 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1040 if (status != G_IO_STATUS_NORMAL) {
1041 pty_chr_state(chr, 0);
1044 pty_chr_state(chr, 1);
1045 qemu_chr_be_write(chr, buf, size);
1050 static void pty_chr_update_read_handler(CharDriverState *chr)
1052 PtyCharDriver *s = chr->opaque;
1055 g_source_remove(s->fd_tag);
1058 s->fd_tag = io_add_watch_poll(s->fd, pty_chr_read_poll, pty_chr_read, chr);
1061 * Short timeout here: just need wait long enougth that qemu makes
1062 * it through the poll loop once. When reconnected we want a
1063 * short timeout so we notice it almost instantly. Otherwise
1064 * read() gives us -EIO instantly, making pty_chr_state() reset the
1065 * timeout to the normal (much longer) poll interval before the
1068 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 10);
1071 static void pty_chr_state(CharDriverState *chr, int connected)
1073 PtyCharDriver *s = chr->opaque;
1076 g_source_remove(s->fd_tag);
1080 /* (re-)connect poll interval for idle guests: once per second.
1081 * We check more frequently in case the guests sends data to
1082 * the virtual device linked to our pty. */
1083 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 1000);
1086 qemu_chr_generic_open(chr);
1091 static void pty_chr_timer(void *opaque)
1093 struct CharDriverState *chr = opaque;
1094 PtyCharDriver *s = chr->opaque;
1099 /* If we arrive here without polling being cleared due
1100 * read returning -EIO, then we are (re-)connected */
1101 pty_chr_state(chr, 1);
1106 pty_chr_update_read_handler(chr);
1109 static void pty_chr_close(struct CharDriverState *chr)
1111 PtyCharDriver *s = chr->opaque;
1115 g_source_remove(s->fd_tag);
1117 fd = g_io_channel_unix_get_fd(s->fd);
1118 g_io_channel_unref(s->fd);
1120 qemu_del_timer(s->timer);
1121 qemu_free_timer(s->timer);
1123 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1126 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
1128 CharDriverState *chr;
1132 int master_fd, slave_fd, len;
1133 #if defined(__OpenBSD__) || defined(__DragonFly__)
1134 char pty_name[PATH_MAX];
1135 #define q_ptsname(x) pty_name
1137 char *pty_name = NULL;
1138 #define q_ptsname(x) ptsname(x)
1141 if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1145 /* Set raw attributes on the pty. */
1146 tcgetattr(slave_fd, &tty);
1148 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1151 chr = g_malloc0(sizeof(CharDriverState));
1153 len = strlen(q_ptsname(master_fd)) + 5;
1154 chr->filename = g_malloc(len);
1155 snprintf(chr->filename, len, "pty:%s", q_ptsname(master_fd));
1156 qemu_opt_set(opts, "path", q_ptsname(master_fd));
1158 label = qemu_opts_id(opts);
1159 fprintf(stderr, "char device redirected to %s%s%s%s\n",
1160 q_ptsname(master_fd),
1161 label ? " (label " : "",
1165 s = g_malloc0(sizeof(PtyCharDriver));
1167 chr->chr_write = pty_chr_write;
1168 chr->chr_update_read_handler = pty_chr_update_read_handler;
1169 chr->chr_close = pty_chr_close;
1170 chr->chr_add_watch = pty_chr_add_watch;
1172 s->fd = io_channel_from_fd(master_fd);
1173 s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr);
1178 static void tty_serial_init(int fd, int speed,
1179 int parity, int data_bits, int stop_bits)
1185 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1186 speed, parity, data_bits, stop_bits);
1188 tcgetattr (fd, &tty);
1190 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1191 speed = speed * 10 / 11;
1208 /* Non-Posix values follow. They may be unsupported on some systems. */
1210 check_speed(115200);
1212 check_speed(230400);
1215 check_speed(460800);
1218 check_speed(500000);
1221 check_speed(576000);
1224 check_speed(921600);
1227 check_speed(1000000);
1230 check_speed(1152000);
1233 check_speed(1500000);
1236 check_speed(2000000);
1239 check_speed(2500000);
1242 check_speed(3000000);
1245 check_speed(3500000);
1248 check_speed(4000000);
1253 cfsetispeed(&tty, spd);
1254 cfsetospeed(&tty, spd);
1256 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1257 |INLCR|IGNCR|ICRNL|IXON);
1258 tty.c_oflag |= OPOST;
1259 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1260 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1281 tty.c_cflag |= PARENB;
1284 tty.c_cflag |= PARENB | PARODD;
1288 tty.c_cflag |= CSTOPB;
1290 tcsetattr (fd, TCSANOW, &tty);
1293 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1295 FDCharDriver *s = chr->opaque;
1298 case CHR_IOCTL_SERIAL_SET_PARAMS:
1300 QEMUSerialSetParams *ssp = arg;
1301 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1302 ssp->speed, ssp->parity,
1303 ssp->data_bits, ssp->stop_bits);
1306 case CHR_IOCTL_SERIAL_SET_BREAK:
1308 int enable = *(int *)arg;
1310 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1314 case CHR_IOCTL_SERIAL_GET_TIOCM:
1317 int *targ = (int *)arg;
1318 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1320 if (sarg & TIOCM_CTS)
1321 *targ |= CHR_TIOCM_CTS;
1322 if (sarg & TIOCM_CAR)
1323 *targ |= CHR_TIOCM_CAR;
1324 if (sarg & TIOCM_DSR)
1325 *targ |= CHR_TIOCM_DSR;
1326 if (sarg & TIOCM_RI)
1327 *targ |= CHR_TIOCM_RI;
1328 if (sarg & TIOCM_DTR)
1329 *targ |= CHR_TIOCM_DTR;
1330 if (sarg & TIOCM_RTS)
1331 *targ |= CHR_TIOCM_RTS;
1334 case CHR_IOCTL_SERIAL_SET_TIOCM:
1336 int sarg = *(int *)arg;
1338 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1339 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1340 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1341 if (sarg & CHR_TIOCM_CTS)
1343 if (sarg & CHR_TIOCM_CAR)
1345 if (sarg & CHR_TIOCM_DSR)
1347 if (sarg & CHR_TIOCM_RI)
1349 if (sarg & CHR_TIOCM_DTR)
1351 if (sarg & CHR_TIOCM_RTS)
1353 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1362 static void qemu_chr_close_tty(CharDriverState *chr)
1364 FDCharDriver *s = chr->opaque;
1368 fd = g_io_channel_unix_get_fd(s->fd_in);
1378 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1380 CharDriverState *chr;
1382 tty_serial_init(fd, 115200, 'N', 8, 1);
1383 chr = qemu_chr_open_fd(fd, fd);
1384 chr->chr_ioctl = tty_serial_ioctl;
1385 chr->chr_close = qemu_chr_close_tty;
1389 static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
1391 const char *filename = qemu_opt_get(opts, "path");
1394 TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
1398 return qemu_chr_open_tty_fd(fd);
1400 #endif /* __linux__ || __sun__ */
1402 #if defined(__linux__)
1404 #define HAVE_CHARDEV_PARPORT 1
1409 } ParallelCharDriver;
1411 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1413 if (s->mode != mode) {
1415 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1422 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1424 ParallelCharDriver *drv = chr->opaque;
1429 case CHR_IOCTL_PP_READ_DATA:
1430 if (ioctl(fd, PPRDATA, &b) < 0)
1432 *(uint8_t *)arg = b;
1434 case CHR_IOCTL_PP_WRITE_DATA:
1435 b = *(uint8_t *)arg;
1436 if (ioctl(fd, PPWDATA, &b) < 0)
1439 case CHR_IOCTL_PP_READ_CONTROL:
1440 if (ioctl(fd, PPRCONTROL, &b) < 0)
1442 /* Linux gives only the lowest bits, and no way to know data
1443 direction! For better compatibility set the fixed upper
1445 *(uint8_t *)arg = b | 0xc0;
1447 case CHR_IOCTL_PP_WRITE_CONTROL:
1448 b = *(uint8_t *)arg;
1449 if (ioctl(fd, PPWCONTROL, &b) < 0)
1452 case CHR_IOCTL_PP_READ_STATUS:
1453 if (ioctl(fd, PPRSTATUS, &b) < 0)
1455 *(uint8_t *)arg = b;
1457 case CHR_IOCTL_PP_DATA_DIR:
1458 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1461 case CHR_IOCTL_PP_EPP_READ_ADDR:
1462 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1463 struct ParallelIOArg *parg = arg;
1464 int n = read(fd, parg->buffer, parg->count);
1465 if (n != parg->count) {
1470 case CHR_IOCTL_PP_EPP_READ:
1471 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1472 struct ParallelIOArg *parg = arg;
1473 int n = read(fd, parg->buffer, parg->count);
1474 if (n != parg->count) {
1479 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1480 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1481 struct ParallelIOArg *parg = arg;
1482 int n = write(fd, parg->buffer, parg->count);
1483 if (n != parg->count) {
1488 case CHR_IOCTL_PP_EPP_WRITE:
1489 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1490 struct ParallelIOArg *parg = arg;
1491 int n = write(fd, parg->buffer, parg->count);
1492 if (n != parg->count) {
1503 static void pp_close(CharDriverState *chr)
1505 ParallelCharDriver *drv = chr->opaque;
1508 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1509 ioctl(fd, PPRELEASE);
1512 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1515 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1517 CharDriverState *chr;
1518 ParallelCharDriver *drv;
1520 if (ioctl(fd, PPCLAIM) < 0) {
1525 drv = g_malloc0(sizeof(ParallelCharDriver));
1527 drv->mode = IEEE1284_MODE_COMPAT;
1529 chr = g_malloc0(sizeof(CharDriverState));
1530 chr->chr_write = null_chr_write;
1531 chr->chr_ioctl = pp_ioctl;
1532 chr->chr_close = pp_close;
1535 qemu_chr_generic_open(chr);
1539 #endif /* __linux__ */
1541 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1543 #define HAVE_CHARDEV_PARPORT 1
1545 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1547 int fd = (int)(intptr_t)chr->opaque;
1551 case CHR_IOCTL_PP_READ_DATA:
1552 if (ioctl(fd, PPIGDATA, &b) < 0)
1554 *(uint8_t *)arg = b;
1556 case CHR_IOCTL_PP_WRITE_DATA:
1557 b = *(uint8_t *)arg;
1558 if (ioctl(fd, PPISDATA, &b) < 0)
1561 case CHR_IOCTL_PP_READ_CONTROL:
1562 if (ioctl(fd, PPIGCTRL, &b) < 0)
1564 *(uint8_t *)arg = b;
1566 case CHR_IOCTL_PP_WRITE_CONTROL:
1567 b = *(uint8_t *)arg;
1568 if (ioctl(fd, PPISCTRL, &b) < 0)
1571 case CHR_IOCTL_PP_READ_STATUS:
1572 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1574 *(uint8_t *)arg = b;
1582 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1584 CharDriverState *chr;
1586 chr = g_malloc0(sizeof(CharDriverState));
1587 chr->opaque = (void *)(intptr_t)fd;
1588 chr->chr_write = null_chr_write;
1589 chr->chr_ioctl = pp_ioctl;
1598 HANDLE hcom, hrecv, hsend;
1599 OVERLAPPED orecv, osend;
1606 HANDLE hInputReadyEvent;
1607 HANDLE hInputDoneEvent;
1608 HANDLE hInputThread;
1609 uint8_t win_stdio_buf;
1610 } WinStdioCharState;
1612 #define NSENDBUF 2048
1613 #define NRECVBUF 2048
1614 #define MAXCONNECT 1
1615 #define NTIMEOUT 5000
1617 static int win_chr_poll(void *opaque);
1618 static int win_chr_pipe_poll(void *opaque);
1620 static void win_chr_close(CharDriverState *chr)
1622 WinCharState *s = chr->opaque;
1625 CloseHandle(s->hsend);
1629 CloseHandle(s->hrecv);
1633 CloseHandle(s->hcom);
1637 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1639 qemu_del_polling_cb(win_chr_poll, chr);
1641 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1644 static int win_chr_init(CharDriverState *chr, const char *filename)
1646 WinCharState *s = chr->opaque;
1648 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1653 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1655 fprintf(stderr, "Failed CreateEvent\n");
1658 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1660 fprintf(stderr, "Failed CreateEvent\n");
1664 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1665 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1666 if (s->hcom == INVALID_HANDLE_VALUE) {
1667 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1672 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1673 fprintf(stderr, "Failed SetupComm\n");
1677 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1678 size = sizeof(COMMCONFIG);
1679 GetDefaultCommConfig(filename, &comcfg, &size);
1680 comcfg.dcb.DCBlength = sizeof(DCB);
1681 CommConfigDialog(filename, NULL, &comcfg);
1683 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1684 fprintf(stderr, "Failed SetCommState\n");
1688 if (!SetCommMask(s->hcom, EV_ERR)) {
1689 fprintf(stderr, "Failed SetCommMask\n");
1693 cto.ReadIntervalTimeout = MAXDWORD;
1694 if (!SetCommTimeouts(s->hcom, &cto)) {
1695 fprintf(stderr, "Failed SetCommTimeouts\n");
1699 if (!ClearCommError(s->hcom, &err, &comstat)) {
1700 fprintf(stderr, "Failed ClearCommError\n");
1703 qemu_add_polling_cb(win_chr_poll, chr);
1711 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1713 WinCharState *s = chr->opaque;
1714 DWORD len, ret, size, err;
1717 ZeroMemory(&s->osend, sizeof(s->osend));
1718 s->osend.hEvent = s->hsend;
1721 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1723 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1725 err = GetLastError();
1726 if (err == ERROR_IO_PENDING) {
1727 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1745 static int win_chr_read_poll(CharDriverState *chr)
1747 WinCharState *s = chr->opaque;
1749 s->max_size = qemu_chr_be_can_write(chr);
1753 static void win_chr_readfile(CharDriverState *chr)
1755 WinCharState *s = chr->opaque;
1757 uint8_t buf[READ_BUF_LEN];
1760 ZeroMemory(&s->orecv, sizeof(s->orecv));
1761 s->orecv.hEvent = s->hrecv;
1762 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1764 err = GetLastError();
1765 if (err == ERROR_IO_PENDING) {
1766 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1771 qemu_chr_be_write(chr, buf, size);
1775 static void win_chr_read(CharDriverState *chr)
1777 WinCharState *s = chr->opaque;
1779 if (s->len > s->max_size)
1780 s->len = s->max_size;
1784 win_chr_readfile(chr);
1787 static int win_chr_poll(void *opaque)
1789 CharDriverState *chr = opaque;
1790 WinCharState *s = chr->opaque;
1794 ClearCommError(s->hcom, &comerr, &status);
1795 if (status.cbInQue > 0) {
1796 s->len = status.cbInQue;
1797 win_chr_read_poll(chr);
1804 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1806 CharDriverState *chr;
1809 chr = g_malloc0(sizeof(CharDriverState));
1810 s = g_malloc0(sizeof(WinCharState));
1812 chr->chr_write = win_chr_write;
1813 chr->chr_close = win_chr_close;
1815 if (win_chr_init(chr, filename) < 0) {
1820 qemu_chr_generic_open(chr);
1824 static CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1826 return qemu_chr_open_win_path(qemu_opt_get(opts, "path"));
1829 static int win_chr_pipe_poll(void *opaque)
1831 CharDriverState *chr = opaque;
1832 WinCharState *s = chr->opaque;
1835 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1838 win_chr_read_poll(chr);
1845 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1847 WinCharState *s = chr->opaque;
1855 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1857 fprintf(stderr, "Failed CreateEvent\n");
1860 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1862 fprintf(stderr, "Failed CreateEvent\n");
1866 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1867 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1868 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1870 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1871 if (s->hcom == INVALID_HANDLE_VALUE) {
1872 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1877 ZeroMemory(&ov, sizeof(ov));
1878 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1879 ret = ConnectNamedPipe(s->hcom, &ov);
1881 fprintf(stderr, "Failed ConnectNamedPipe\n");
1885 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1887 fprintf(stderr, "Failed GetOverlappedResult\n");
1889 CloseHandle(ov.hEvent);
1896 CloseHandle(ov.hEvent);
1899 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1908 static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
1910 const char *filename = qemu_opt_get(opts, "path");
1911 CharDriverState *chr;
1914 chr = g_malloc0(sizeof(CharDriverState));
1915 s = g_malloc0(sizeof(WinCharState));
1917 chr->chr_write = win_chr_write;
1918 chr->chr_close = win_chr_close;
1920 if (win_chr_pipe_init(chr, filename) < 0) {
1925 qemu_chr_generic_open(chr);
1929 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1931 CharDriverState *chr;
1934 chr = g_malloc0(sizeof(CharDriverState));
1935 s = g_malloc0(sizeof(WinCharState));
1938 chr->chr_write = win_chr_write;
1939 qemu_chr_generic_open(chr);
1943 static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
1945 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1948 static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
1950 const char *file_out = qemu_opt_get(opts, "path");
1953 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1954 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1955 if (fd_out == INVALID_HANDLE_VALUE) {
1959 return qemu_chr_open_win_file(fd_out);
1962 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1964 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1971 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
1981 static void win_stdio_wait_func(void *opaque)
1983 CharDriverState *chr = opaque;
1984 WinStdioCharState *stdio = chr->opaque;
1985 INPUT_RECORD buf[4];
1990 ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
1994 /* Avoid error storm */
1995 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
1999 for (i = 0; i < dwSize; i++) {
2000 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2002 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2004 if (kev->uChar.AsciiChar != 0) {
2005 for (j = 0; j < kev->wRepeatCount; j++) {
2006 if (qemu_chr_be_can_write(chr)) {
2007 uint8_t c = kev->uChar.AsciiChar;
2008 qemu_chr_be_write(chr, &c, 1);
2016 static DWORD WINAPI win_stdio_thread(LPVOID param)
2018 CharDriverState *chr = param;
2019 WinStdioCharState *stdio = chr->opaque;
2025 /* Wait for one byte */
2026 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2028 /* Exit in case of error, continue if nothing read */
2036 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2037 if (stdio->win_stdio_buf == '\r') {
2041 /* Signal the main thread and wait until the byte was eaten */
2042 if (!SetEvent(stdio->hInputReadyEvent)) {
2045 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2051 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2055 static void win_stdio_thread_wait_func(void *opaque)
2057 CharDriverState *chr = opaque;
2058 WinStdioCharState *stdio = chr->opaque;
2060 if (qemu_chr_be_can_write(chr)) {
2061 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2064 SetEvent(stdio->hInputDoneEvent);
2067 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2069 WinStdioCharState *stdio = chr->opaque;
2072 GetConsoleMode(stdio->hStdIn, &dwMode);
2075 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2077 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2081 static void win_stdio_close(CharDriverState *chr)
2083 WinStdioCharState *stdio = chr->opaque;
2085 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2086 CloseHandle(stdio->hInputReadyEvent);
2088 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2089 CloseHandle(stdio->hInputDoneEvent);
2091 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2092 TerminateThread(stdio->hInputThread, 0);
2095 g_free(chr->opaque);
2099 static CharDriverState *qemu_chr_open_win_stdio(QemuOpts *opts)
2101 CharDriverState *chr;
2102 WinStdioCharState *stdio;
2106 chr = g_malloc0(sizeof(CharDriverState));
2107 stdio = g_malloc0(sizeof(WinStdioCharState));
2109 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2110 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2111 fprintf(stderr, "cannot open stdio: invalid handle\n");
2115 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2117 chr->opaque = stdio;
2118 chr->chr_write = win_stdio_write;
2119 chr->chr_close = win_stdio_close;
2122 if (qemu_add_wait_object(stdio->hStdIn,
2123 win_stdio_wait_func, chr)) {
2124 fprintf(stderr, "qemu_add_wait_object: failed\n");
2129 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2130 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2131 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2134 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2135 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2136 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2137 fprintf(stderr, "cannot create stdio thread or event\n");
2140 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2141 win_stdio_thread_wait_func, chr)) {
2142 fprintf(stderr, "qemu_add_wait_object: failed\n");
2146 dwMode |= ENABLE_LINE_INPUT;
2149 /* set the terminal in raw mode */
2150 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2151 dwMode |= ENABLE_PROCESSED_INPUT;
2154 SetConsoleMode(stdio->hStdIn, dwMode);
2156 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2157 qemu_chr_fe_set_echo(chr, false);
2161 #endif /* !_WIN32 */
2163 /***********************************************************/
2164 /* UDP Net console */
2170 uint8_t buf[READ_BUF_LEN];
2176 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2178 NetCharDriver *s = chr->opaque;
2179 gsize bytes_written;
2182 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2183 if (status == G_IO_STATUS_EOF) {
2185 } else if (status != G_IO_STATUS_NORMAL) {
2189 return bytes_written;
2192 static int udp_chr_read_poll(void *opaque)
2194 CharDriverState *chr = opaque;
2195 NetCharDriver *s = chr->opaque;
2197 s->max_size = qemu_chr_be_can_write(chr);
2199 /* If there were any stray characters in the queue process them
2202 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2203 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2205 s->max_size = qemu_chr_be_can_write(chr);
2210 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2212 CharDriverState *chr = opaque;
2213 NetCharDriver *s = chr->opaque;
2214 gsize bytes_read = 0;
2217 if (s->max_size == 0)
2219 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2221 s->bufcnt = bytes_read;
2222 s->bufptr = s->bufcnt;
2223 if (status != G_IO_STATUS_NORMAL) {
2228 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2229 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2231 s->max_size = qemu_chr_be_can_write(chr);
2237 static void udp_chr_update_read_handler(CharDriverState *chr)
2239 NetCharDriver *s = chr->opaque;
2242 g_source_remove(s->tag);
2247 s->tag = io_add_watch_poll(s->chan, udp_chr_read_poll, udp_chr_read, chr);
2251 static void udp_chr_close(CharDriverState *chr)
2253 NetCharDriver *s = chr->opaque;
2255 g_source_remove(s->tag);
2258 g_io_channel_unref(s->chan);
2262 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2265 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2267 CharDriverState *chr = NULL;
2268 NetCharDriver *s = NULL;
2269 Error *local_err = NULL;
2272 chr = g_malloc0(sizeof(CharDriverState));
2273 s = g_malloc0(sizeof(NetCharDriver));
2275 fd = inet_dgram_opts(opts, &local_err);
2281 s->chan = io_channel_from_socket(s->fd);
2285 chr->chr_write = udp_chr_write;
2286 chr->chr_update_read_handler = udp_chr_update_read_handler;
2287 chr->chr_close = udp_chr_close;
2292 qerror_report_err(local_err);
2293 error_free(local_err);
2303 /***********************************************************/
2304 /* TCP Net console */
2308 GIOChannel *chan, *listen_chan;
2309 guint tag, listen_tag;
2319 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2321 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2323 TCPCharDriver *s = chr->opaque;
2325 return io_channel_send_all(s->chan, buf, len);
2327 /* XXX: indicate an error ? */
2332 static int tcp_chr_read_poll(void *opaque)
2334 CharDriverState *chr = opaque;
2335 TCPCharDriver *s = chr->opaque;
2338 s->max_size = qemu_chr_be_can_write(chr);
2343 #define IAC_BREAK 243
2344 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2346 uint8_t *buf, int *size)
2348 /* Handle any telnet client's basic IAC options to satisfy char by
2349 * char mode with no echo. All IAC options will be removed from
2350 * the buf and the do_telnetopt variable will be used to track the
2351 * state of the width of the IAC information.
2353 * IAC commands come in sets of 3 bytes with the exception of the
2354 * "IAC BREAK" command and the double IAC.
2360 for (i = 0; i < *size; i++) {
2361 if (s->do_telnetopt > 1) {
2362 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2363 /* Double IAC means send an IAC */
2367 s->do_telnetopt = 1;
2369 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2370 /* Handle IAC break commands by sending a serial break */
2371 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2376 if (s->do_telnetopt >= 4) {
2377 s->do_telnetopt = 1;
2380 if ((unsigned char)buf[i] == IAC) {
2381 s->do_telnetopt = 2;
2392 static int tcp_get_msgfd(CharDriverState *chr)
2394 TCPCharDriver *s = chr->opaque;
2401 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2403 TCPCharDriver *s = chr->opaque;
2404 struct cmsghdr *cmsg;
2406 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2409 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2410 cmsg->cmsg_level != SOL_SOCKET ||
2411 cmsg->cmsg_type != SCM_RIGHTS)
2414 fd = *((int *)CMSG_DATA(cmsg));
2418 #ifndef MSG_CMSG_CLOEXEC
2419 qemu_set_cloexec(fd);
2427 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2429 TCPCharDriver *s = chr->opaque;
2430 struct msghdr msg = { NULL, };
2431 struct iovec iov[1];
2433 struct cmsghdr cmsg;
2434 char control[CMSG_SPACE(sizeof(int))];
2439 iov[0].iov_base = buf;
2440 iov[0].iov_len = len;
2444 msg.msg_control = &msg_control;
2445 msg.msg_controllen = sizeof(msg_control);
2447 #ifdef MSG_CMSG_CLOEXEC
2448 flags |= MSG_CMSG_CLOEXEC;
2450 ret = recvmsg(s->fd, &msg, flags);
2451 if (ret > 0 && s->is_unix) {
2452 unix_process_msgfd(chr, &msg);
2458 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2460 TCPCharDriver *s = chr->opaque;
2461 return qemu_recv(s->fd, buf, len, 0);
2465 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2467 CharDriverState *chr = opaque;
2468 TCPCharDriver *s = chr->opaque;
2469 uint8_t buf[READ_BUF_LEN];
2472 if (!s->connected || s->max_size <= 0) {
2476 if (len > s->max_size)
2478 size = tcp_chr_recv(chr, (void *)buf, len);
2480 /* connection closed */
2482 if (s->listen_chan) {
2483 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2485 g_source_remove(s->tag);
2487 g_io_channel_unref(s->chan);
2491 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2492 } else if (size > 0) {
2493 if (s->do_telnetopt)
2494 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2496 qemu_chr_be_write(chr, buf, size);
2503 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2505 return qemu_chr_open_fd(eventfd, eventfd);
2509 static void tcp_chr_connect(void *opaque)
2511 CharDriverState *chr = opaque;
2512 TCPCharDriver *s = chr->opaque;
2516 s->tag = io_add_watch_poll(s->chan, tcp_chr_read_poll, tcp_chr_read, chr);
2518 qemu_chr_generic_open(chr);
2521 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2522 static void tcp_chr_telnet_init(int fd)
2525 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2526 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2527 send(fd, (char *)buf, 3, 0);
2528 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2529 send(fd, (char *)buf, 3, 0);
2530 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2531 send(fd, (char *)buf, 3, 0);
2532 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2533 send(fd, (char *)buf, 3, 0);
2536 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2538 TCPCharDriver *s = chr->opaque;
2542 socket_set_nonblock(fd);
2544 socket_set_nodelay(fd);
2546 s->chan = io_channel_from_socket(fd);
2547 g_source_remove(s->listen_tag);
2549 tcp_chr_connect(chr);
2554 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2556 CharDriverState *chr = opaque;
2557 TCPCharDriver *s = chr->opaque;
2558 struct sockaddr_in saddr;
2560 struct sockaddr_un uaddr;
2562 struct sockaddr *addr;
2569 len = sizeof(uaddr);
2570 addr = (struct sockaddr *)&uaddr;
2574 len = sizeof(saddr);
2575 addr = (struct sockaddr *)&saddr;
2577 fd = qemu_accept(s->listen_fd, addr, &len);
2578 if (fd < 0 && errno != EINTR) {
2580 } else if (fd >= 0) {
2581 if (s->do_telnetopt)
2582 tcp_chr_telnet_init(fd);
2586 if (tcp_chr_add_client(chr, fd) < 0)
2592 static void tcp_chr_close(CharDriverState *chr)
2594 TCPCharDriver *s = chr->opaque;
2597 g_source_remove(s->tag);
2600 g_io_channel_unref(s->chan);
2604 if (s->listen_fd >= 0) {
2605 if (s->listen_tag) {
2606 g_source_remove(s->listen_tag);
2608 if (s->listen_chan) {
2609 g_io_channel_unref(s->listen_chan);
2611 closesocket(s->listen_fd);
2614 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2617 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2618 bool is_listen, bool is_telnet,
2619 bool is_waitconnect,
2622 CharDriverState *chr = NULL;
2623 TCPCharDriver *s = NULL;
2624 char host[NI_MAXHOST], serv[NI_MAXSERV];
2625 const char *left = "", *right = "";
2626 struct sockaddr_storage ss;
2627 socklen_t ss_len = sizeof(ss);
2629 memset(&ss, 0, ss_len);
2630 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2631 error_setg(errp, "getsockname: %s", strerror(errno));
2635 chr = g_malloc0(sizeof(CharDriverState));
2636 s = g_malloc0(sizeof(TCPCharDriver));
2643 chr->filename = g_malloc(256);
2644 switch (ss.ss_family) {
2648 snprintf(chr->filename, 256, "unix:%s%s",
2649 ((struct sockaddr_un *)(&ss))->sun_path,
2650 is_listen ? ",server" : "");
2658 s->do_nodelay = do_nodelay;
2659 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2660 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2661 snprintf(chr->filename, 256, "%s:%s:%s%s%s%s",
2662 is_telnet ? "telnet" : "tcp",
2663 left, host, right, serv,
2664 is_listen ? ",server" : "");
2669 chr->chr_write = tcp_chr_write;
2670 chr->chr_close = tcp_chr_close;
2671 chr->get_msgfd = tcp_get_msgfd;
2672 chr->chr_add_client = tcp_chr_add_client;
2676 s->listen_chan = io_channel_from_socket(s->listen_fd);
2677 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2679 s->do_telnetopt = 1;
2684 socket_set_nodelay(fd);
2685 s->chan = io_channel_from_socket(s->fd);
2686 tcp_chr_connect(chr);
2689 if (is_listen && is_waitconnect) {
2690 printf("QEMU waiting for connection on: %s\n",
2692 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2693 socket_set_nonblock(s->listen_fd);
2698 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2700 CharDriverState *chr = NULL;
2701 Error *local_err = NULL;
2709 is_listen = qemu_opt_get_bool(opts, "server", 0);
2710 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2711 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2712 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2713 is_unix = qemu_opt_get(opts, "path") != NULL;
2719 fd = unix_listen_opts(opts, &local_err);
2721 fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2725 fd = inet_listen_opts(opts, 0, &local_err);
2727 fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2734 if (!is_waitconnect)
2735 socket_set_nonblock(fd);
2737 chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2738 is_waitconnect, &local_err);
2739 if (error_is_set(&local_err)) {
2747 qerror_report_err(local_err);
2748 error_free(local_err);
2754 g_free(chr->opaque);
2760 /***********************************************************/
2761 /* Memory chardev */
2764 size_t outbuf_capacity;
2768 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2770 MemoryDriver *d = chr->opaque;
2772 /* TODO: the QString implementation has the same code, we should
2773 * introduce a generic way to do this in cutils.c */
2774 if (d->outbuf_capacity < d->outbuf_size + len) {
2776 d->outbuf_capacity += len;
2777 d->outbuf_capacity *= 2;
2778 d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
2781 memcpy(d->outbuf + d->outbuf_size, buf, len);
2782 d->outbuf_size += len;
2787 void qemu_chr_init_mem(CharDriverState *chr)
2791 d = g_malloc(sizeof(*d));
2793 d->outbuf_capacity = 4096;
2794 d->outbuf = g_malloc0(d->outbuf_capacity);
2796 memset(chr, 0, sizeof(*chr));
2798 chr->chr_write = mem_chr_write;
2801 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2803 MemoryDriver *d = chr->opaque;
2804 return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2807 /* NOTE: this driver can not be closed with qemu_chr_delete()! */
2808 void qemu_chr_close_mem(CharDriverState *chr)
2810 MemoryDriver *d = chr->opaque;
2813 g_free(chr->opaque);
2815 chr->chr_write = NULL;
2818 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2820 const MemoryDriver *d = chr->opaque;
2821 return d->outbuf_size;
2824 /*********************************************************/
2825 /* Ring buffer chardev */
2832 } RingBufCharDriver;
2834 static size_t ringbuf_count(const CharDriverState *chr)
2836 const RingBufCharDriver *d = chr->opaque;
2838 return d->prod - d->cons;
2841 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2843 RingBufCharDriver *d = chr->opaque;
2846 if (!buf || (len < 0)) {
2850 for (i = 0; i < len; i++ ) {
2851 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2852 if (d->prod - d->cons > d->size) {
2853 d->cons = d->prod - d->size;
2860 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2862 RingBufCharDriver *d = chr->opaque;
2865 for (i = 0; i < len && d->cons != d->prod; i++) {
2866 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2872 static void ringbuf_chr_close(struct CharDriverState *chr)
2874 RingBufCharDriver *d = chr->opaque;
2881 static CharDriverState *qemu_chr_open_ringbuf(QemuOpts *opts)
2883 CharDriverState *chr;
2884 RingBufCharDriver *d;
2886 chr = g_malloc0(sizeof(CharDriverState));
2887 d = g_malloc(sizeof(*d));
2889 d->size = qemu_opt_get_size(opts, "size", 0);
2894 /* The size must be power of 2 */
2895 if (d->size & (d->size - 1)) {
2896 error_report("size of ringbuf device must be power of two");
2902 d->cbuf = g_malloc0(d->size);
2905 chr->chr_write = ringbuf_chr_write;
2906 chr->chr_close = ringbuf_chr_close;
2916 static bool chr_is_ringbuf(const CharDriverState *chr)
2918 return chr->chr_write == ringbuf_chr_write;
2921 void qmp_ringbuf_write(const char *device, const char *data,
2922 bool has_format, enum DataFormat format,
2925 CharDriverState *chr;
2926 const uint8_t *write_data;
2930 chr = qemu_chr_find(device);
2932 error_setg(errp, "Device '%s' not found", device);
2936 if (!chr_is_ringbuf(chr)) {
2937 error_setg(errp,"%s is not a ringbuf device", device);
2941 if (has_format && (format == DATA_FORMAT_BASE64)) {
2942 write_data = g_base64_decode(data, &write_count);
2944 write_data = (uint8_t *)data;
2945 write_count = strlen(data);
2948 ret = ringbuf_chr_write(chr, write_data, write_count);
2950 if (write_data != (uint8_t *)data) {
2951 g_free((void *)write_data);
2955 error_setg(errp, "Failed to write to device %s", device);
2960 char *qmp_ringbuf_read(const char *device, int64_t size,
2961 bool has_format, enum DataFormat format,
2964 CharDriverState *chr;
2969 chr = qemu_chr_find(device);
2971 error_setg(errp, "Device '%s' not found", device);
2975 if (!chr_is_ringbuf(chr)) {
2976 error_setg(errp,"%s is not a ringbuf device", device);
2981 error_setg(errp, "size must be greater than zero");
2985 count = ringbuf_count(chr);
2986 size = size > count ? count : size;
2987 read_data = g_malloc(size + 1);
2989 ringbuf_chr_read(chr, read_data, size);
2991 if (has_format && (format == DATA_FORMAT_BASE64)) {
2992 data = g_base64_encode(read_data, size);
2996 * FIXME should read only complete, valid UTF-8 characters up
2997 * to @size bytes. Invalid sequences should be replaced by a
2998 * suitable replacement character. Except when (and only
2999 * when) ring buffer lost characters since last read, initial
3000 * continuation characters should be dropped.
3002 read_data[size] = 0;
3003 data = (char *)read_data;
3009 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3011 char host[65], port[33], width[8], height[8];
3015 Error *local_err = NULL;
3017 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3018 if (error_is_set(&local_err)) {
3019 qerror_report_err(local_err);
3020 error_free(local_err);
3024 if (strstart(filename, "mon:", &p)) {
3026 qemu_opt_set(opts, "mux", "on");
3029 if (strcmp(filename, "null") == 0 ||
3030 strcmp(filename, "pty") == 0 ||
3031 strcmp(filename, "msmouse") == 0 ||
3032 strcmp(filename, "braille") == 0 ||
3033 strcmp(filename, "stdio") == 0) {
3034 qemu_opt_set(opts, "backend", filename);
3037 if (strstart(filename, "vc", &p)) {
3038 qemu_opt_set(opts, "backend", "vc");
3040 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
3042 qemu_opt_set(opts, "width", width);
3043 qemu_opt_set(opts, "height", height);
3044 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
3046 qemu_opt_set(opts, "cols", width);
3047 qemu_opt_set(opts, "rows", height);
3054 if (strcmp(filename, "con:") == 0) {
3055 qemu_opt_set(opts, "backend", "console");
3058 if (strstart(filename, "COM", NULL)) {
3059 qemu_opt_set(opts, "backend", "serial");
3060 qemu_opt_set(opts, "path", filename);
3063 if (strstart(filename, "file:", &p)) {
3064 qemu_opt_set(opts, "backend", "file");
3065 qemu_opt_set(opts, "path", p);
3068 if (strstart(filename, "pipe:", &p)) {
3069 qemu_opt_set(opts, "backend", "pipe");
3070 qemu_opt_set(opts, "path", p);
3073 if (strstart(filename, "tcp:", &p) ||
3074 strstart(filename, "telnet:", &p)) {
3075 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3077 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3080 qemu_opt_set(opts, "backend", "socket");
3081 qemu_opt_set(opts, "host", host);
3082 qemu_opt_set(opts, "port", port);
3083 if (p[pos] == ',') {
3084 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3087 if (strstart(filename, "telnet:", &p))
3088 qemu_opt_set(opts, "telnet", "on");
3091 if (strstart(filename, "udp:", &p)) {
3092 qemu_opt_set(opts, "backend", "udp");
3093 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3095 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3099 qemu_opt_set(opts, "host", host);
3100 qemu_opt_set(opts, "port", port);
3101 if (p[pos] == '@') {
3103 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3105 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3109 qemu_opt_set(opts, "localaddr", host);
3110 qemu_opt_set(opts, "localport", port);
3114 if (strstart(filename, "unix:", &p)) {
3115 qemu_opt_set(opts, "backend", "socket");
3116 if (qemu_opts_do_parse(opts, p, "path") != 0)
3120 if (strstart(filename, "/dev/parport", NULL) ||
3121 strstart(filename, "/dev/ppi", NULL)) {
3122 qemu_opt_set(opts, "backend", "parport");
3123 qemu_opt_set(opts, "path", filename);
3126 if (strstart(filename, "/dev/", NULL)) {
3127 qemu_opt_set(opts, "backend", "tty");
3128 qemu_opt_set(opts, "path", filename);
3133 qemu_opts_del(opts);
3137 #ifdef HAVE_CHARDEV_PARPORT
3139 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
3141 const char *filename = qemu_opt_get(opts, "path");
3144 fd = qemu_open(filename, O_RDWR);
3148 return qemu_chr_open_pp_fd(fd);
3153 static const struct {
3155 CharDriverState *(*open)(QemuOpts *opts);
3156 } backend_table[] = {
3157 { .name = "null", .open = qemu_chr_open_null },
3158 { .name = "socket", .open = qemu_chr_open_socket },
3159 { .name = "udp", .open = qemu_chr_open_udp },
3160 { .name = "msmouse", .open = qemu_chr_open_msmouse },
3161 { .name = "vc", .open = vc_init },
3162 { .name = "memory", .open = qemu_chr_open_ringbuf },
3164 { .name = "file", .open = qemu_chr_open_win_file_out },
3165 { .name = "pipe", .open = qemu_chr_open_win_pipe },
3166 { .name = "console", .open = qemu_chr_open_win_con },
3167 { .name = "serial", .open = qemu_chr_open_win },
3168 { .name = "stdio", .open = qemu_chr_open_win_stdio },
3170 { .name = "file", .open = qemu_chr_open_file_out },
3171 { .name = "pipe", .open = qemu_chr_open_pipe },
3172 { .name = "stdio", .open = qemu_chr_open_stdio },
3174 #ifdef CONFIG_BRLAPI
3175 { .name = "braille", .open = chr_baum_init },
3177 #ifdef HAVE_CHARDEV_TTY
3178 { .name = "tty", .open = qemu_chr_open_tty },
3179 { .name = "serial", .open = qemu_chr_open_tty },
3180 { .name = "pty", .open = qemu_chr_open_pty },
3182 #ifdef HAVE_CHARDEV_PARPORT
3183 { .name = "parallel", .open = qemu_chr_open_pp },
3184 { .name = "parport", .open = qemu_chr_open_pp },
3187 { .name = "spicevmc", .open = qemu_chr_open_spice },
3188 #if SPICE_SERVER_VERSION >= 0x000c02
3189 { .name = "spiceport", .open = qemu_chr_open_spice_port },
3194 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3195 void (*init)(struct CharDriverState *s),
3198 CharDriverState *chr;
3201 if (qemu_opts_id(opts) == NULL) {
3202 error_setg(errp, "chardev: no id specified");
3206 if (qemu_opt_get(opts, "backend") == NULL) {
3207 error_setg(errp, "chardev: \"%s\" missing backend",
3208 qemu_opts_id(opts));
3211 for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
3212 if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
3215 if (i == ARRAY_SIZE(backend_table)) {
3216 error_setg(errp, "chardev: backend \"%s\" not found",
3217 qemu_opt_get(opts, "backend"));
3221 chr = backend_table[i].open(opts);
3223 error_setg(errp, "chardev: opening backend \"%s\" failed",
3224 qemu_opt_get(opts, "backend"));
3229 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3231 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3233 if (qemu_opt_get_bool(opts, "mux", 0)) {
3234 CharDriverState *base = chr;
3235 int len = strlen(qemu_opts_id(opts)) + 6;
3236 base->label = g_malloc(len);
3237 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3238 chr = qemu_chr_open_mux(base);
3239 chr->filename = base->filename;
3240 chr->avail_connections = MAX_MUX;
3241 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3243 chr->avail_connections = 1;
3245 chr->label = g_strdup(qemu_opts_id(opts));
3250 qemu_opts_del(opts);
3254 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3257 CharDriverState *chr;
3261 if (strstart(filename, "chardev:", &p)) {
3262 return qemu_chr_find(p);
3265 opts = qemu_chr_parse_compat(label, filename);
3269 chr = qemu_chr_new_from_opts(opts, init, &err);
3270 if (error_is_set(&err)) {
3271 fprintf(stderr, "%s\n", error_get_pretty(err));
3274 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3275 monitor_init(chr, MONITOR_USE_READLINE);
3280 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3282 if (chr->chr_set_echo) {
3283 chr->chr_set_echo(chr, echo);
3287 void qemu_chr_fe_open(struct CharDriverState *chr)
3289 if (chr->chr_guest_open) {
3290 chr->chr_guest_open(chr);
3294 void qemu_chr_fe_close(struct CharDriverState *chr)
3296 if (chr->chr_guest_close) {
3297 chr->chr_guest_close(chr);
3301 guint qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3302 GIOFunc func, void *user_data)
3307 if (s->chr_add_watch == NULL) {
3311 src = s->chr_add_watch(s, cond);
3312 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3313 tag = g_source_attach(src, NULL);
3314 g_source_unref(src);
3319 void qemu_chr_delete(CharDriverState *chr)
3321 QTAILQ_REMOVE(&chardevs, chr, next);
3322 if (chr->chr_close) {
3323 chr->chr_close(chr);
3325 g_free(chr->filename);
3328 qemu_opts_del(chr->opts);
3333 ChardevInfoList *qmp_query_chardev(Error **errp)
3335 ChardevInfoList *chr_list = NULL;
3336 CharDriverState *chr;
3338 QTAILQ_FOREACH(chr, &chardevs, next) {
3339 ChardevInfoList *info = g_malloc0(sizeof(*info));
3340 info->value = g_malloc0(sizeof(*info->value));
3341 info->value->label = g_strdup(chr->label);
3342 info->value->filename = g_strdup(chr->filename);
3344 info->next = chr_list;
3351 CharDriverState *qemu_chr_find(const char *name)
3353 CharDriverState *chr;
3355 QTAILQ_FOREACH(chr, &chardevs, next) {
3356 if (strcmp(chr->label, name) != 0)
3363 /* Get a character (serial) device interface. */
3364 CharDriverState *qemu_char_get_next_serial(void)
3366 static int next_serial;
3368 /* FIXME: This function needs to go away: use chardev properties! */
3369 return serial_hds[next_serial++];
3372 QemuOptsList qemu_chardev_opts = {
3374 .implied_opt_name = "backend",
3375 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3379 .type = QEMU_OPT_STRING,
3382 .type = QEMU_OPT_STRING,
3385 .type = QEMU_OPT_STRING,
3388 .type = QEMU_OPT_STRING,
3390 .name = "localaddr",
3391 .type = QEMU_OPT_STRING,
3393 .name = "localport",
3394 .type = QEMU_OPT_STRING,
3397 .type = QEMU_OPT_NUMBER,
3400 .type = QEMU_OPT_BOOL,
3403 .type = QEMU_OPT_BOOL,
3406 .type = QEMU_OPT_BOOL,
3409 .type = QEMU_OPT_BOOL,
3412 .type = QEMU_OPT_BOOL,
3415 .type = QEMU_OPT_BOOL,
3418 .type = QEMU_OPT_NUMBER,
3421 .type = QEMU_OPT_NUMBER,
3424 .type = QEMU_OPT_NUMBER,
3427 .type = QEMU_OPT_NUMBER,
3430 .type = QEMU_OPT_BOOL,
3433 .type = QEMU_OPT_BOOL,
3436 .type = QEMU_OPT_STRING,
3439 .type = QEMU_OPT_NUMBER,
3442 .type = QEMU_OPT_SIZE,
3444 { /* end of list */ }
3450 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3455 error_setg(errp, "input file not supported");
3459 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3460 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3461 if (out == INVALID_HANDLE_VALUE) {
3462 error_setg(errp, "open %s failed", file->out);
3465 return qemu_chr_open_win_file(out);
3468 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3471 return qemu_chr_open_win_path(serial->device);
3474 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3477 error_setg(errp, "character device backend type 'parallel' not supported");
3483 static int qmp_chardev_open_file_source(char *src, int flags,
3488 TFR(fd = qemu_open(src, flags, 0666));
3490 error_setg(errp, "open %s: %s", src, strerror(errno));
3495 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3497 int flags, in = -1, out = -1;
3499 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3500 out = qmp_chardev_open_file_source(file->out, flags, errp);
3501 if (error_is_set(errp)) {
3507 in = qmp_chardev_open_file_source(file->in, flags, errp);
3508 if (error_is_set(errp)) {
3514 return qemu_chr_open_fd(in, out);
3517 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3520 #ifdef HAVE_CHARDEV_TTY
3523 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3524 if (error_is_set(errp)) {
3527 socket_set_nonblock(fd);
3528 return qemu_chr_open_tty_fd(fd);
3530 error_setg(errp, "character device backend type 'serial' not supported");
3535 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3538 #ifdef HAVE_CHARDEV_PARPORT
3541 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3542 if (error_is_set(errp)) {
3545 return qemu_chr_open_pp_fd(fd);
3547 error_setg(errp, "character device backend type 'parallel' not supported");
3554 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3557 SocketAddress *addr = sock->addr;
3558 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3559 bool is_listen = sock->has_server ? sock->server : true;
3560 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3561 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3565 fd = socket_listen(addr, errp);
3567 fd = socket_connect(addr, errp, NULL, NULL);
3569 if (error_is_set(errp)) {
3572 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3573 is_telnet, is_waitconnect, errp);
3576 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3579 ChardevReturn *ret = g_new0(ChardevReturn, 1);
3580 CharDriverState *chr = NULL;
3582 chr = qemu_chr_find(id);
3584 error_setg(errp, "Chardev '%s' already exists", id);
3589 switch (backend->kind) {
3590 case CHARDEV_BACKEND_KIND_FILE:
3591 chr = qmp_chardev_open_file(backend->file, errp);
3593 case CHARDEV_BACKEND_KIND_SERIAL:
3594 chr = qmp_chardev_open_serial(backend->serial, errp);
3596 case CHARDEV_BACKEND_KIND_PARALLEL:
3597 chr = qmp_chardev_open_parallel(backend->parallel, errp);
3599 case CHARDEV_BACKEND_KIND_SOCKET:
3600 chr = qmp_chardev_open_socket(backend->socket, errp);
3602 #ifdef HAVE_CHARDEV_TTY
3603 case CHARDEV_BACKEND_KIND_PTY:
3605 /* qemu_chr_open_pty sets "path" in opts */
3607 opts = qemu_opts_create_nofail(qemu_find_opts("chardev"));
3608 chr = qemu_chr_open_pty(opts);
3609 ret->pty = g_strdup(qemu_opt_get(opts, "path"));
3610 ret->has_pty = true;
3611 qemu_opts_del(opts);
3615 case CHARDEV_BACKEND_KIND_NULL:
3616 chr = qemu_chr_open_null(NULL);
3619 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3623 if (chr == NULL && !error_is_set(errp)) {
3624 error_setg(errp, "Failed to create chardev");
3627 chr->label = g_strdup(id);
3628 chr->avail_connections = 1;
3629 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3637 void qmp_chardev_remove(const char *id, Error **errp)
3639 CharDriverState *chr;
3641 chr = qemu_chr_find(id);
3643 error_setg(errp, "Chardev '%s' not found", id);
3646 if (chr->chr_can_read || chr->chr_read ||
3647 chr->chr_event || chr->handler_opaque) {
3648 error_setg(errp, "Chardev '%s' is busy", id);
3651 qemu_chr_delete(chr);