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 "sysemu/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(__FreeBSD__) || defined(__FreeBSD_kernel__)
57 #include <dev/ppbus/ppi.h>
58 #include <dev/ppbus/ppbconf.h>
59 #elif defined(__DragonFly__)
60 #include <dev/misc/ppi/ppi.h>
61 #include <bus/ppbus/ppbconf.h>
65 #include <linux/ppdev.h>
66 #include <linux/parport.h>
70 #include <sys/ethernet.h>
71 #include <sys/sockio.h>
72 #include <netinet/arp.h>
73 #include <netinet/in.h>
74 #include <netinet/in_systm.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_icmp.h> // must come after ip.h
77 #include <netinet/udp.h>
78 #include <netinet/tcp.h>
85 #include "qemu/sockets.h"
86 #include "ui/qemu-spice.h"
88 #define READ_BUF_LEN 4096
90 /***********************************************************/
91 /* character device */
93 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
94 QTAILQ_HEAD_INITIALIZER(chardevs);
96 void qemu_chr_be_event(CharDriverState *s, int event)
98 /* Keep track if the char device is open */
100 case CHR_EVENT_OPENED:
103 case CHR_EVENT_CLOSED:
110 s->chr_event(s->handler_opaque, event);
113 static gboolean qemu_chr_be_generic_open_bh(gpointer opaque)
115 CharDriverState *s = opaque;
116 qemu_chr_be_event(s, CHR_EVENT_OPENED);
121 void qemu_chr_be_generic_open(CharDriverState *s)
123 if (s->idle_tag == 0) {
124 s->idle_tag = g_idle_add(qemu_chr_be_generic_open_bh, s);
128 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
130 return s->chr_write(s, buf, len);
133 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
138 while (offset < len) {
140 res = s->chr_write(s, buf + offset, len - offset);
141 if (res == -1 && errno == EAGAIN) {
144 } while (res == -1 && errno == EAGAIN);
160 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
164 return s->chr_ioctl(s, cmd, arg);
167 int qemu_chr_be_can_write(CharDriverState *s)
169 if (!s->chr_can_read)
171 return s->chr_can_read(s->handler_opaque);
174 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
177 s->chr_read(s->handler_opaque, buf, len);
181 int qemu_chr_fe_get_msgfd(CharDriverState *s)
183 return s->get_msgfd ? s->get_msgfd(s) : -1;
186 int qemu_chr_add_client(CharDriverState *s, int fd)
188 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
191 void qemu_chr_accept_input(CharDriverState *s)
193 if (s->chr_accept_input)
194 s->chr_accept_input(s);
198 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
200 char buf[READ_BUF_LEN];
203 vsnprintf(buf, sizeof(buf), fmt, ap);
204 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
208 void qemu_chr_add_handlers(CharDriverState *s,
209 IOCanReadHandler *fd_can_read,
210 IOReadHandler *fd_read,
211 IOEventHandler *fd_event,
216 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
221 s->chr_can_read = fd_can_read;
222 s->chr_read = fd_read;
223 s->chr_event = fd_event;
224 s->handler_opaque = opaque;
225 if (s->chr_update_read_handler)
226 s->chr_update_read_handler(s);
228 if (!s->explicit_fe_open) {
229 qemu_chr_fe_set_open(s, fe_open);
232 /* We're connecting to an already opened device, so let's make sure we
233 also get the open event */
234 if (fe_open && s->be_open) {
235 qemu_chr_be_generic_open(s);
239 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
244 static CharDriverState *qemu_chr_open_null(void)
246 CharDriverState *chr;
248 chr = g_malloc0(sizeof(CharDriverState));
249 chr->chr_write = null_chr_write;
253 /* MUX driver for serial I/O splitting */
255 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
256 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
258 IOCanReadHandler *chr_can_read[MAX_MUX];
259 IOReadHandler *chr_read[MAX_MUX];
260 IOEventHandler *chr_event[MAX_MUX];
261 void *ext_opaque[MAX_MUX];
262 CharDriverState *drv;
267 /* Intermediate input buffer allows to catch escape sequences even if the
268 currently active device is not accepting any input - but only until it
270 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
275 int64_t timestamps_start;
279 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
281 MuxDriver *d = chr->opaque;
283 if (!d->timestamps) {
284 ret = d->drv->chr_write(d->drv, buf, len);
289 for (i = 0; i < len; i++) {
295 ti = qemu_get_clock_ms(rt_clock);
296 if (d->timestamps_start == -1)
297 d->timestamps_start = ti;
298 ti -= d->timestamps_start;
300 snprintf(buf1, sizeof(buf1),
301 "[%02d:%02d:%02d.%03d] ",
306 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
309 ret += d->drv->chr_write(d->drv, buf+i, 1);
310 if (buf[i] == '\n') {
318 static const char * const mux_help[] = {
319 "% h print this help\n\r",
320 "% x exit emulator\n\r",
321 "% s save disk data back to file (if -snapshot)\n\r",
322 "% t toggle console timestamps\n\r"
323 "% b send break (magic sysrq)\n\r",
324 "% c switch between console and monitor\n\r",
329 int term_escape_char = 0x01; /* ctrl-a is used for escape */
330 static void mux_print_help(CharDriverState *chr)
333 char ebuf[15] = "Escape-Char";
334 char cbuf[50] = "\n\r";
336 if (term_escape_char > 0 && term_escape_char < 26) {
337 snprintf(cbuf, sizeof(cbuf), "\n\r");
338 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
340 snprintf(cbuf, sizeof(cbuf),
341 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
344 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
345 for (i = 0; mux_help[i] != NULL; i++) {
346 for (j=0; mux_help[i][j] != '\0'; j++) {
347 if (mux_help[i][j] == '%')
348 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
350 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
355 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
357 if (d->chr_event[mux_nr])
358 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
361 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
363 if (d->term_got_escape) {
364 d->term_got_escape = 0;
365 if (ch == term_escape_char)
374 const char *term = "QEMU: Terminated\n\r";
375 chr->chr_write(chr,(uint8_t *)term,strlen(term));
383 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
386 /* Switch to the next registered device */
387 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
389 if (d->focus >= d->mux_cnt)
391 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
394 d->timestamps = !d->timestamps;
395 d->timestamps_start = -1;
399 } else if (ch == term_escape_char) {
400 d->term_got_escape = 1;
408 static void mux_chr_accept_input(CharDriverState *chr)
410 MuxDriver *d = chr->opaque;
413 while (d->prod[m] != d->cons[m] &&
414 d->chr_can_read[m] &&
415 d->chr_can_read[m](d->ext_opaque[m])) {
416 d->chr_read[m](d->ext_opaque[m],
417 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
421 static int mux_chr_can_read(void *opaque)
423 CharDriverState *chr = opaque;
424 MuxDriver *d = chr->opaque;
427 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
429 if (d->chr_can_read[m])
430 return d->chr_can_read[m](d->ext_opaque[m]);
434 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
436 CharDriverState *chr = opaque;
437 MuxDriver *d = chr->opaque;
441 mux_chr_accept_input (opaque);
443 for(i = 0; i < size; i++)
444 if (mux_proc_byte(chr, d, buf[i])) {
445 if (d->prod[m] == d->cons[m] &&
446 d->chr_can_read[m] &&
447 d->chr_can_read[m](d->ext_opaque[m]))
448 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
450 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
454 static void mux_chr_event(void *opaque, int event)
456 CharDriverState *chr = opaque;
457 MuxDriver *d = chr->opaque;
460 /* Send the event to all registered listeners */
461 for (i = 0; i < d->mux_cnt; i++)
462 mux_chr_send_event(d, i, event);
465 static void mux_chr_update_read_handler(CharDriverState *chr)
467 MuxDriver *d = chr->opaque;
469 if (d->mux_cnt >= MAX_MUX) {
470 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
473 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
474 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
475 d->chr_read[d->mux_cnt] = chr->chr_read;
476 d->chr_event[d->mux_cnt] = chr->chr_event;
477 /* Fix up the real driver with mux routines */
478 if (d->mux_cnt == 0) {
479 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
482 if (d->focus != -1) {
483 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
485 d->focus = d->mux_cnt;
487 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
490 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
492 CharDriverState *chr;
495 chr = g_malloc0(sizeof(CharDriverState));
496 d = g_malloc0(sizeof(MuxDriver));
501 chr->chr_write = mux_chr_write;
502 chr->chr_update_read_handler = mux_chr_update_read_handler;
503 chr->chr_accept_input = mux_chr_accept_input;
504 /* Frontend guest-open / -close notification is not support with muxes */
505 chr->chr_set_fe_open = NULL;
507 /* Muxes are always open on creation */
508 qemu_chr_be_generic_open(chr);
515 int send_all(int fd, const void *buf, int len1)
521 ret = send(fd, buf, len, 0);
523 errno = WSAGetLastError();
524 if (errno != WSAEWOULDBLOCK) {
527 } else if (ret == 0) {
539 int send_all(int fd, const void *_buf, int len1)
542 const uint8_t *buf = _buf;
546 ret = write(fd, buf, len);
548 if (errno != EINTR && errno != EAGAIN)
550 } else if (ret == 0) {
560 int recv_all(int fd, void *_buf, int len1, bool single_read)
566 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
568 if (errno != EINTR && errno != EAGAIN) {
585 typedef struct IOWatchPoll
592 IOCanReadHandler *fd_can_read;
597 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
599 return container_of(source, IOWatchPoll, parent);
602 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
604 IOWatchPoll *iwp = io_watch_poll_from_source(source);
605 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
606 bool was_active = iwp->src != NULL;
607 if (was_active == now_active) {
612 iwp->src = g_io_create_watch(iwp->channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
613 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
614 g_source_attach(iwp->src, NULL);
616 g_source_destroy(iwp->src);
617 g_source_unref(iwp->src);
623 static gboolean io_watch_poll_check(GSource *source)
628 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
634 static void io_watch_poll_finalize(GSource *source)
636 /* Due to a glib bug, removing the last reference to a source
637 * inside a finalize callback causes recursive locking (and a
638 * deadlock). This is not a problem inside other callbacks,
639 * including dispatch callbacks, so we call io_remove_watch_poll
640 * to remove this source. At this point, iwp->src must
641 * be NULL, or we would leak it.
643 * This would be solved much more elegantly by child sources,
644 * but we support older glib versions that do not have them.
646 IOWatchPoll *iwp = io_watch_poll_from_source(source);
647 assert(iwp->src == NULL);
650 static GSourceFuncs io_watch_poll_funcs = {
651 .prepare = io_watch_poll_prepare,
652 .check = io_watch_poll_check,
653 .dispatch = io_watch_poll_dispatch,
654 .finalize = io_watch_poll_finalize,
657 /* Can only be used for read */
658 static guint io_add_watch_poll(GIOChannel *channel,
659 IOCanReadHandler *fd_can_read,
666 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
667 iwp->fd_can_read = fd_can_read;
668 iwp->opaque = user_data;
669 iwp->channel = channel;
670 iwp->fd_read = (GSourceFunc) fd_read;
673 tag = g_source_attach(&iwp->parent, NULL);
674 g_source_unref(&iwp->parent);
678 static void io_remove_watch_poll(guint tag)
683 g_return_if_fail (tag > 0);
685 source = g_main_context_find_source_by_id(NULL, tag);
686 g_return_if_fail (source != NULL);
688 iwp = io_watch_poll_from_source(source);
690 g_source_destroy(iwp->src);
691 g_source_unref(iwp->src);
694 g_source_destroy(&iwp->parent);
698 static GIOChannel *io_channel_from_fd(int fd)
706 chan = g_io_channel_unix_new(fd);
708 g_io_channel_set_encoding(chan, NULL, NULL);
709 g_io_channel_set_buffered(chan, FALSE);
715 static GIOChannel *io_channel_from_socket(int fd)
724 chan = g_io_channel_win32_new_socket(fd);
726 chan = g_io_channel_unix_new(fd);
729 g_io_channel_set_encoding(chan, NULL, NULL);
730 g_io_channel_set_buffered(chan, FALSE);
735 static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
741 while (offset < len) {
744 status = g_io_channel_write_chars(fd, buf + offset, len - offset,
745 &bytes_written, NULL);
746 if (status != G_IO_STATUS_NORMAL) {
747 if (status == G_IO_STATUS_AGAIN) {
748 /* If we've written any data, return a partial write. */
758 } else if (status == G_IO_STATUS_EOF) {
762 offset += bytes_written;
770 typedef struct FDCharDriver {
771 CharDriverState *chr;
772 GIOChannel *fd_in, *fd_out;
775 QTAILQ_ENTRY(FDCharDriver) node;
778 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
780 FDCharDriver *s = chr->opaque;
782 return io_channel_send(s->fd_out, buf, len);
785 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
787 CharDriverState *chr = opaque;
788 FDCharDriver *s = chr->opaque;
790 uint8_t buf[READ_BUF_LEN];
795 if (len > s->max_size) {
802 status = g_io_channel_read_chars(chan, (gchar *)buf,
803 len, &bytes_read, NULL);
804 if (status == G_IO_STATUS_EOF) {
806 io_remove_watch_poll(s->fd_in_tag);
809 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
812 if (status == G_IO_STATUS_NORMAL) {
813 qemu_chr_be_write(chr, buf, bytes_read);
819 static int fd_chr_read_poll(void *opaque)
821 CharDriverState *chr = opaque;
822 FDCharDriver *s = chr->opaque;
824 s->max_size = qemu_chr_be_can_write(chr);
828 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
830 FDCharDriver *s = chr->opaque;
831 return g_io_create_watch(s->fd_out, cond);
834 static void fd_chr_update_read_handler(CharDriverState *chr)
836 FDCharDriver *s = chr->opaque;
839 io_remove_watch_poll(s->fd_in_tag);
844 s->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll, fd_chr_read, chr);
848 static void fd_chr_close(struct CharDriverState *chr)
850 FDCharDriver *s = chr->opaque;
853 io_remove_watch_poll(s->fd_in_tag);
858 g_io_channel_unref(s->fd_in);
861 g_io_channel_unref(s->fd_out);
865 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
868 /* open a character device to a unix fd */
869 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
871 CharDriverState *chr;
874 chr = g_malloc0(sizeof(CharDriverState));
875 s = g_malloc0(sizeof(FDCharDriver));
876 s->fd_in = io_channel_from_fd(fd_in);
877 s->fd_out = io_channel_from_fd(fd_out);
878 fcntl(fd_out, F_SETFL, O_NONBLOCK);
881 chr->chr_add_watch = fd_chr_add_watch;
882 chr->chr_write = fd_chr_write;
883 chr->chr_update_read_handler = fd_chr_update_read_handler;
884 chr->chr_close = fd_chr_close;
886 qemu_chr_be_generic_open(chr);
891 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
894 char filename_in[256], filename_out[256];
895 const char *filename = opts->device;
897 if (filename == NULL) {
898 fprintf(stderr, "chardev: pipe: no filename given\n");
902 snprintf(filename_in, 256, "%s.in", filename);
903 snprintf(filename_out, 256, "%s.out", filename);
904 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
905 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
906 if (fd_in < 0 || fd_out < 0) {
911 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
916 return qemu_chr_open_fd(fd_in, fd_out);
919 /* init terminal so that we can grab keys */
920 static struct termios oldtty;
921 static int old_fd0_flags;
922 static bool stdio_allow_signal;
924 static void term_exit(void)
926 tcsetattr (0, TCSANOW, &oldtty);
927 fcntl(0, F_SETFL, old_fd0_flags);
930 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
936 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
937 |INLCR|IGNCR|ICRNL|IXON);
938 tty.c_oflag |= OPOST;
939 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
940 tty.c_cflag &= ~(CSIZE|PARENB);
945 /* if graphical mode, we allow Ctrl-C handling */
946 if (!stdio_allow_signal)
947 tty.c_lflag &= ~ISIG;
949 tcsetattr (0, TCSANOW, &tty);
952 static void qemu_chr_close_stdio(struct CharDriverState *chr)
958 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
960 CharDriverState *chr;
962 if (is_daemonized()) {
963 error_report("cannot use stdio with -daemonize");
966 old_fd0_flags = fcntl(0, F_GETFL);
967 tcgetattr (0, &oldtty);
968 fcntl(0, F_SETFL, O_NONBLOCK);
971 chr = qemu_chr_open_fd(0, 1);
972 chr->chr_close = qemu_chr_close_stdio;
973 chr->chr_set_echo = qemu_chr_set_echo_stdio;
974 stdio_allow_signal = display_type != DT_NOGRAPHIC;
975 if (opts->has_signal) {
976 stdio_allow_signal = opts->signal;
978 qemu_chr_fe_set_echo(chr, false);
984 /* Once Solaris has openpty(), this is going to be removed. */
985 static int openpty(int *amaster, int *aslave, char *name,
986 struct termios *termp, struct winsize *winp)
989 int mfd = -1, sfd = -1;
991 *amaster = *aslave = -1;
993 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
997 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
1000 if ((slave = ptsname(mfd)) == NULL)
1003 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
1006 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
1007 (termp != NULL && tcgetattr(sfd, termp) < 0))
1015 ioctl(sfd, TIOCSWINSZ, winp);
1026 static void cfmakeraw (struct termios *termios_p)
1028 termios_p->c_iflag &=
1029 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
1030 termios_p->c_oflag &= ~OPOST;
1031 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
1032 termios_p->c_cflag &= ~(CSIZE|PARENB);
1033 termios_p->c_cflag |= CS8;
1035 termios_p->c_cc[VMIN] = 0;
1036 termios_p->c_cc[VTIME] = 0;
1040 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1041 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1042 || defined(__GLIBC__)
1044 #define HAVE_CHARDEV_TTY 1
1054 static void pty_chr_update_read_handler(CharDriverState *chr);
1055 static void pty_chr_state(CharDriverState *chr, int connected);
1057 static gboolean pty_chr_timer(gpointer opaque)
1059 struct CharDriverState *chr = opaque;
1060 PtyCharDriver *s = chr->opaque;
1067 pty_chr_update_read_handler(chr);
1074 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1076 PtyCharDriver *s = chr->opaque;
1079 g_source_remove(s->timer_tag);
1084 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1086 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1090 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1092 PtyCharDriver *s = chr->opaque;
1094 if (!s->connected) {
1095 /* guest sends data, check for (re-)connect */
1096 pty_chr_update_read_handler(chr);
1099 return io_channel_send(s->fd, buf, len);
1102 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1104 PtyCharDriver *s = chr->opaque;
1105 return g_io_create_watch(s->fd, cond);
1108 static int pty_chr_read_poll(void *opaque)
1110 CharDriverState *chr = opaque;
1111 PtyCharDriver *s = chr->opaque;
1113 s->read_bytes = qemu_chr_be_can_write(chr);
1114 return s->read_bytes;
1117 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1119 CharDriverState *chr = opaque;
1120 PtyCharDriver *s = chr->opaque;
1122 uint8_t buf[READ_BUF_LEN];
1126 if (len > s->read_bytes)
1127 len = s->read_bytes;
1131 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1132 if (status != G_IO_STATUS_NORMAL) {
1133 pty_chr_state(chr, 0);
1136 pty_chr_state(chr, 1);
1137 qemu_chr_be_write(chr, buf, size);
1142 static void pty_chr_update_read_handler(CharDriverState *chr)
1144 PtyCharDriver *s = chr->opaque;
1147 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1148 pfd.events = G_IO_OUT;
1151 if (pfd.revents & G_IO_HUP) {
1152 pty_chr_state(chr, 0);
1154 pty_chr_state(chr, 1);
1158 static void pty_chr_state(CharDriverState *chr, int connected)
1160 PtyCharDriver *s = chr->opaque;
1164 io_remove_watch_poll(s->fd_tag);
1168 /* (re-)connect poll interval for idle guests: once per second.
1169 * We check more frequently in case the guests sends data to
1170 * the virtual device linked to our pty. */
1171 pty_chr_rearm_timer(chr, 1000);
1174 g_source_remove(s->timer_tag);
1177 if (!s->connected) {
1178 qemu_chr_be_generic_open(chr);
1180 s->fd_tag = io_add_watch_poll(s->fd, pty_chr_read_poll, pty_chr_read, chr);
1186 static void pty_chr_close(struct CharDriverState *chr)
1188 PtyCharDriver *s = chr->opaque;
1192 io_remove_watch_poll(s->fd_tag);
1195 fd = g_io_channel_unix_get_fd(s->fd);
1196 g_io_channel_unref(s->fd);
1199 g_source_remove(s->timer_tag);
1203 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1206 static CharDriverState *qemu_chr_open_pty(const char *id,
1209 CharDriverState *chr;
1212 int master_fd, slave_fd;
1213 #if defined(__OpenBSD__) || defined(__DragonFly__)
1214 char pty_name[PATH_MAX];
1215 #define q_ptsname(x) pty_name
1217 char *pty_name = NULL;
1218 #define q_ptsname(x) ptsname(x)
1221 if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1225 /* Set raw attributes on the pty. */
1226 tcgetattr(slave_fd, &tty);
1228 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1231 chr = g_malloc0(sizeof(CharDriverState));
1233 chr->filename = g_strdup_printf("pty:%s", q_ptsname(master_fd));
1234 ret->pty = g_strdup(q_ptsname(master_fd));
1235 ret->has_pty = true;
1237 fprintf(stderr, "char device redirected to %s (label %s)\n",
1238 q_ptsname(master_fd), id);
1240 s = g_malloc0(sizeof(PtyCharDriver));
1242 chr->chr_write = pty_chr_write;
1243 chr->chr_update_read_handler = pty_chr_update_read_handler;
1244 chr->chr_close = pty_chr_close;
1245 chr->chr_add_watch = pty_chr_add_watch;
1247 s->fd = io_channel_from_fd(master_fd);
1253 static void tty_serial_init(int fd, int speed,
1254 int parity, int data_bits, int stop_bits)
1260 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1261 speed, parity, data_bits, stop_bits);
1263 tcgetattr (fd, &tty);
1265 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1266 speed = speed * 10 / 11;
1283 /* Non-Posix values follow. They may be unsupported on some systems. */
1285 check_speed(115200);
1287 check_speed(230400);
1290 check_speed(460800);
1293 check_speed(500000);
1296 check_speed(576000);
1299 check_speed(921600);
1302 check_speed(1000000);
1305 check_speed(1152000);
1308 check_speed(1500000);
1311 check_speed(2000000);
1314 check_speed(2500000);
1317 check_speed(3000000);
1320 check_speed(3500000);
1323 check_speed(4000000);
1328 cfsetispeed(&tty, spd);
1329 cfsetospeed(&tty, spd);
1331 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1332 |INLCR|IGNCR|ICRNL|IXON);
1333 tty.c_oflag |= OPOST;
1334 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1335 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1356 tty.c_cflag |= PARENB;
1359 tty.c_cflag |= PARENB | PARODD;
1363 tty.c_cflag |= CSTOPB;
1365 tcsetattr (fd, TCSANOW, &tty);
1368 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1370 FDCharDriver *s = chr->opaque;
1373 case CHR_IOCTL_SERIAL_SET_PARAMS:
1375 QEMUSerialSetParams *ssp = arg;
1376 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1377 ssp->speed, ssp->parity,
1378 ssp->data_bits, ssp->stop_bits);
1381 case CHR_IOCTL_SERIAL_SET_BREAK:
1383 int enable = *(int *)arg;
1385 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1389 case CHR_IOCTL_SERIAL_GET_TIOCM:
1392 int *targ = (int *)arg;
1393 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1395 if (sarg & TIOCM_CTS)
1396 *targ |= CHR_TIOCM_CTS;
1397 if (sarg & TIOCM_CAR)
1398 *targ |= CHR_TIOCM_CAR;
1399 if (sarg & TIOCM_DSR)
1400 *targ |= CHR_TIOCM_DSR;
1401 if (sarg & TIOCM_RI)
1402 *targ |= CHR_TIOCM_RI;
1403 if (sarg & TIOCM_DTR)
1404 *targ |= CHR_TIOCM_DTR;
1405 if (sarg & TIOCM_RTS)
1406 *targ |= CHR_TIOCM_RTS;
1409 case CHR_IOCTL_SERIAL_SET_TIOCM:
1411 int sarg = *(int *)arg;
1413 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1414 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1415 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1416 if (sarg & CHR_TIOCM_CTS)
1418 if (sarg & CHR_TIOCM_CAR)
1420 if (sarg & CHR_TIOCM_DSR)
1422 if (sarg & CHR_TIOCM_RI)
1424 if (sarg & CHR_TIOCM_DTR)
1426 if (sarg & CHR_TIOCM_RTS)
1428 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1437 static void qemu_chr_close_tty(CharDriverState *chr)
1439 FDCharDriver *s = chr->opaque;
1443 fd = g_io_channel_unix_get_fd(s->fd_in);
1453 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1455 CharDriverState *chr;
1457 tty_serial_init(fd, 115200, 'N', 8, 1);
1458 chr = qemu_chr_open_fd(fd, fd);
1459 chr->chr_ioctl = tty_serial_ioctl;
1460 chr->chr_close = qemu_chr_close_tty;
1463 #endif /* __linux__ || __sun__ */
1465 #if defined(__linux__)
1467 #define HAVE_CHARDEV_PARPORT 1
1472 } ParallelCharDriver;
1474 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1476 if (s->mode != mode) {
1478 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1485 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1487 ParallelCharDriver *drv = chr->opaque;
1492 case CHR_IOCTL_PP_READ_DATA:
1493 if (ioctl(fd, PPRDATA, &b) < 0)
1495 *(uint8_t *)arg = b;
1497 case CHR_IOCTL_PP_WRITE_DATA:
1498 b = *(uint8_t *)arg;
1499 if (ioctl(fd, PPWDATA, &b) < 0)
1502 case CHR_IOCTL_PP_READ_CONTROL:
1503 if (ioctl(fd, PPRCONTROL, &b) < 0)
1505 /* Linux gives only the lowest bits, and no way to know data
1506 direction! For better compatibility set the fixed upper
1508 *(uint8_t *)arg = b | 0xc0;
1510 case CHR_IOCTL_PP_WRITE_CONTROL:
1511 b = *(uint8_t *)arg;
1512 if (ioctl(fd, PPWCONTROL, &b) < 0)
1515 case CHR_IOCTL_PP_READ_STATUS:
1516 if (ioctl(fd, PPRSTATUS, &b) < 0)
1518 *(uint8_t *)arg = b;
1520 case CHR_IOCTL_PP_DATA_DIR:
1521 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1524 case CHR_IOCTL_PP_EPP_READ_ADDR:
1525 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1526 struct ParallelIOArg *parg = arg;
1527 int n = read(fd, parg->buffer, parg->count);
1528 if (n != parg->count) {
1533 case CHR_IOCTL_PP_EPP_READ:
1534 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1535 struct ParallelIOArg *parg = arg;
1536 int n = read(fd, parg->buffer, parg->count);
1537 if (n != parg->count) {
1542 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1543 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1544 struct ParallelIOArg *parg = arg;
1545 int n = write(fd, parg->buffer, parg->count);
1546 if (n != parg->count) {
1551 case CHR_IOCTL_PP_EPP_WRITE:
1552 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1553 struct ParallelIOArg *parg = arg;
1554 int n = write(fd, parg->buffer, parg->count);
1555 if (n != parg->count) {
1566 static void pp_close(CharDriverState *chr)
1568 ParallelCharDriver *drv = chr->opaque;
1571 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1572 ioctl(fd, PPRELEASE);
1575 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1578 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1580 CharDriverState *chr;
1581 ParallelCharDriver *drv;
1583 if (ioctl(fd, PPCLAIM) < 0) {
1588 drv = g_malloc0(sizeof(ParallelCharDriver));
1590 drv->mode = IEEE1284_MODE_COMPAT;
1592 chr = g_malloc0(sizeof(CharDriverState));
1593 chr->chr_write = null_chr_write;
1594 chr->chr_ioctl = pp_ioctl;
1595 chr->chr_close = pp_close;
1598 qemu_chr_be_generic_open(chr);
1602 #endif /* __linux__ */
1604 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1606 #define HAVE_CHARDEV_PARPORT 1
1608 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1610 int fd = (int)(intptr_t)chr->opaque;
1614 case CHR_IOCTL_PP_READ_DATA:
1615 if (ioctl(fd, PPIGDATA, &b) < 0)
1617 *(uint8_t *)arg = b;
1619 case CHR_IOCTL_PP_WRITE_DATA:
1620 b = *(uint8_t *)arg;
1621 if (ioctl(fd, PPISDATA, &b) < 0)
1624 case CHR_IOCTL_PP_READ_CONTROL:
1625 if (ioctl(fd, PPIGCTRL, &b) < 0)
1627 *(uint8_t *)arg = b;
1629 case CHR_IOCTL_PP_WRITE_CONTROL:
1630 b = *(uint8_t *)arg;
1631 if (ioctl(fd, PPISCTRL, &b) < 0)
1634 case CHR_IOCTL_PP_READ_STATUS:
1635 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1637 *(uint8_t *)arg = b;
1645 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1647 CharDriverState *chr;
1649 chr = g_malloc0(sizeof(CharDriverState));
1650 chr->opaque = (void *)(intptr_t)fd;
1651 chr->chr_write = null_chr_write;
1652 chr->chr_ioctl = pp_ioctl;
1661 HANDLE hcom, hrecv, hsend;
1662 OVERLAPPED orecv, osend;
1669 HANDLE hInputReadyEvent;
1670 HANDLE hInputDoneEvent;
1671 HANDLE hInputThread;
1672 uint8_t win_stdio_buf;
1673 } WinStdioCharState;
1675 #define NSENDBUF 2048
1676 #define NRECVBUF 2048
1677 #define MAXCONNECT 1
1678 #define NTIMEOUT 5000
1680 static int win_chr_poll(void *opaque);
1681 static int win_chr_pipe_poll(void *opaque);
1683 static void win_chr_close(CharDriverState *chr)
1685 WinCharState *s = chr->opaque;
1688 CloseHandle(s->hsend);
1692 CloseHandle(s->hrecv);
1696 CloseHandle(s->hcom);
1700 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1702 qemu_del_polling_cb(win_chr_poll, chr);
1704 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1707 static int win_chr_init(CharDriverState *chr, const char *filename)
1709 WinCharState *s = chr->opaque;
1711 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1716 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1718 fprintf(stderr, "Failed CreateEvent\n");
1721 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1723 fprintf(stderr, "Failed CreateEvent\n");
1727 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1728 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1729 if (s->hcom == INVALID_HANDLE_VALUE) {
1730 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1735 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1736 fprintf(stderr, "Failed SetupComm\n");
1740 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1741 size = sizeof(COMMCONFIG);
1742 GetDefaultCommConfig(filename, &comcfg, &size);
1743 comcfg.dcb.DCBlength = sizeof(DCB);
1744 CommConfigDialog(filename, NULL, &comcfg);
1746 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1747 fprintf(stderr, "Failed SetCommState\n");
1751 if (!SetCommMask(s->hcom, EV_ERR)) {
1752 fprintf(stderr, "Failed SetCommMask\n");
1756 cto.ReadIntervalTimeout = MAXDWORD;
1757 if (!SetCommTimeouts(s->hcom, &cto)) {
1758 fprintf(stderr, "Failed SetCommTimeouts\n");
1762 if (!ClearCommError(s->hcom, &err, &comstat)) {
1763 fprintf(stderr, "Failed ClearCommError\n");
1766 qemu_add_polling_cb(win_chr_poll, chr);
1774 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1776 WinCharState *s = chr->opaque;
1777 DWORD len, ret, size, err;
1780 ZeroMemory(&s->osend, sizeof(s->osend));
1781 s->osend.hEvent = s->hsend;
1784 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1786 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1788 err = GetLastError();
1789 if (err == ERROR_IO_PENDING) {
1790 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1808 static int win_chr_read_poll(CharDriverState *chr)
1810 WinCharState *s = chr->opaque;
1812 s->max_size = qemu_chr_be_can_write(chr);
1816 static void win_chr_readfile(CharDriverState *chr)
1818 WinCharState *s = chr->opaque;
1820 uint8_t buf[READ_BUF_LEN];
1823 ZeroMemory(&s->orecv, sizeof(s->orecv));
1824 s->orecv.hEvent = s->hrecv;
1825 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1827 err = GetLastError();
1828 if (err == ERROR_IO_PENDING) {
1829 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1834 qemu_chr_be_write(chr, buf, size);
1838 static void win_chr_read(CharDriverState *chr)
1840 WinCharState *s = chr->opaque;
1842 if (s->len > s->max_size)
1843 s->len = s->max_size;
1847 win_chr_readfile(chr);
1850 static int win_chr_poll(void *opaque)
1852 CharDriverState *chr = opaque;
1853 WinCharState *s = chr->opaque;
1857 ClearCommError(s->hcom, &comerr, &status);
1858 if (status.cbInQue > 0) {
1859 s->len = status.cbInQue;
1860 win_chr_read_poll(chr);
1867 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1869 CharDriverState *chr;
1872 chr = g_malloc0(sizeof(CharDriverState));
1873 s = g_malloc0(sizeof(WinCharState));
1875 chr->chr_write = win_chr_write;
1876 chr->chr_close = win_chr_close;
1878 if (win_chr_init(chr, filename) < 0) {
1883 qemu_chr_be_generic_open(chr);
1887 static int win_chr_pipe_poll(void *opaque)
1889 CharDriverState *chr = opaque;
1890 WinCharState *s = chr->opaque;
1893 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1896 win_chr_read_poll(chr);
1903 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1905 WinCharState *s = chr->opaque;
1913 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1915 fprintf(stderr, "Failed CreateEvent\n");
1918 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1920 fprintf(stderr, "Failed CreateEvent\n");
1924 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1925 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1926 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1928 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1929 if (s->hcom == INVALID_HANDLE_VALUE) {
1930 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1935 ZeroMemory(&ov, sizeof(ov));
1936 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1937 ret = ConnectNamedPipe(s->hcom, &ov);
1939 fprintf(stderr, "Failed ConnectNamedPipe\n");
1943 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1945 fprintf(stderr, "Failed GetOverlappedResult\n");
1947 CloseHandle(ov.hEvent);
1954 CloseHandle(ov.hEvent);
1957 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1966 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
1968 const char *filename = opts->device;
1969 CharDriverState *chr;
1972 chr = g_malloc0(sizeof(CharDriverState));
1973 s = g_malloc0(sizeof(WinCharState));
1975 chr->chr_write = win_chr_write;
1976 chr->chr_close = win_chr_close;
1978 if (win_chr_pipe_init(chr, filename) < 0) {
1983 qemu_chr_be_generic_open(chr);
1987 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1989 CharDriverState *chr;
1992 chr = g_malloc0(sizeof(CharDriverState));
1993 s = g_malloc0(sizeof(WinCharState));
1996 chr->chr_write = win_chr_write;
1997 qemu_chr_be_generic_open(chr);
2001 static CharDriverState *qemu_chr_open_win_con(void)
2003 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2006 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2008 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2015 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2025 static void win_stdio_wait_func(void *opaque)
2027 CharDriverState *chr = opaque;
2028 WinStdioCharState *stdio = chr->opaque;
2029 INPUT_RECORD buf[4];
2034 ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
2038 /* Avoid error storm */
2039 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2043 for (i = 0; i < dwSize; i++) {
2044 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2046 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2048 if (kev->uChar.AsciiChar != 0) {
2049 for (j = 0; j < kev->wRepeatCount; j++) {
2050 if (qemu_chr_be_can_write(chr)) {
2051 uint8_t c = kev->uChar.AsciiChar;
2052 qemu_chr_be_write(chr, &c, 1);
2060 static DWORD WINAPI win_stdio_thread(LPVOID param)
2062 CharDriverState *chr = param;
2063 WinStdioCharState *stdio = chr->opaque;
2069 /* Wait for one byte */
2070 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2072 /* Exit in case of error, continue if nothing read */
2080 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2081 if (stdio->win_stdio_buf == '\r') {
2085 /* Signal the main thread and wait until the byte was eaten */
2086 if (!SetEvent(stdio->hInputReadyEvent)) {
2089 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2095 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2099 static void win_stdio_thread_wait_func(void *opaque)
2101 CharDriverState *chr = opaque;
2102 WinStdioCharState *stdio = chr->opaque;
2104 if (qemu_chr_be_can_write(chr)) {
2105 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2108 SetEvent(stdio->hInputDoneEvent);
2111 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2113 WinStdioCharState *stdio = chr->opaque;
2116 GetConsoleMode(stdio->hStdIn, &dwMode);
2119 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2121 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2125 static void win_stdio_close(CharDriverState *chr)
2127 WinStdioCharState *stdio = chr->opaque;
2129 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2130 CloseHandle(stdio->hInputReadyEvent);
2132 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2133 CloseHandle(stdio->hInputDoneEvent);
2135 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2136 TerminateThread(stdio->hInputThread, 0);
2139 g_free(chr->opaque);
2143 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2145 CharDriverState *chr;
2146 WinStdioCharState *stdio;
2150 chr = g_malloc0(sizeof(CharDriverState));
2151 stdio = g_malloc0(sizeof(WinStdioCharState));
2153 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2154 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2155 fprintf(stderr, "cannot open stdio: invalid handle\n");
2159 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2161 chr->opaque = stdio;
2162 chr->chr_write = win_stdio_write;
2163 chr->chr_close = win_stdio_close;
2166 if (qemu_add_wait_object(stdio->hStdIn,
2167 win_stdio_wait_func, chr)) {
2168 fprintf(stderr, "qemu_add_wait_object: failed\n");
2173 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2174 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2175 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2178 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2179 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2180 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2181 fprintf(stderr, "cannot create stdio thread or event\n");
2184 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2185 win_stdio_thread_wait_func, chr)) {
2186 fprintf(stderr, "qemu_add_wait_object: failed\n");
2190 dwMode |= ENABLE_LINE_INPUT;
2193 /* set the terminal in raw mode */
2194 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2195 dwMode |= ENABLE_PROCESSED_INPUT;
2198 SetConsoleMode(stdio->hStdIn, dwMode);
2200 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2201 qemu_chr_fe_set_echo(chr, false);
2205 #endif /* !_WIN32 */
2208 /***********************************************************/
2209 /* UDP Net console */
2215 uint8_t buf[READ_BUF_LEN];
2221 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2223 NetCharDriver *s = chr->opaque;
2224 gsize bytes_written;
2227 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2228 if (status == G_IO_STATUS_EOF) {
2230 } else if (status != G_IO_STATUS_NORMAL) {
2234 return bytes_written;
2237 static int udp_chr_read_poll(void *opaque)
2239 CharDriverState *chr = opaque;
2240 NetCharDriver *s = chr->opaque;
2242 s->max_size = qemu_chr_be_can_write(chr);
2244 /* If there were any stray characters in the queue process them
2247 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2248 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2250 s->max_size = qemu_chr_be_can_write(chr);
2255 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2257 CharDriverState *chr = opaque;
2258 NetCharDriver *s = chr->opaque;
2259 gsize bytes_read = 0;
2262 if (s->max_size == 0) {
2265 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2267 s->bufcnt = bytes_read;
2268 s->bufptr = s->bufcnt;
2269 if (status != G_IO_STATUS_NORMAL) {
2271 io_remove_watch_poll(s->tag);
2278 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2279 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2281 s->max_size = qemu_chr_be_can_write(chr);
2287 static void udp_chr_update_read_handler(CharDriverState *chr)
2289 NetCharDriver *s = chr->opaque;
2292 io_remove_watch_poll(s->tag);
2297 s->tag = io_add_watch_poll(s->chan, udp_chr_read_poll, udp_chr_read, chr);
2301 static void udp_chr_close(CharDriverState *chr)
2303 NetCharDriver *s = chr->opaque;
2305 io_remove_watch_poll(s->tag);
2309 g_io_channel_unref(s->chan);
2313 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2316 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2318 CharDriverState *chr = NULL;
2319 NetCharDriver *s = NULL;
2321 chr = g_malloc0(sizeof(CharDriverState));
2322 s = g_malloc0(sizeof(NetCharDriver));
2325 s->chan = io_channel_from_socket(s->fd);
2329 chr->chr_write = udp_chr_write;
2330 chr->chr_update_read_handler = udp_chr_update_read_handler;
2331 chr->chr_close = udp_chr_close;
2335 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2337 Error *local_err = NULL;
2340 fd = inet_dgram_opts(opts, &local_err);
2344 return qemu_chr_open_udp_fd(fd);
2347 /***********************************************************/
2348 /* TCP Net console */
2352 GIOChannel *chan, *listen_chan;
2353 guint tag, listen_tag;
2363 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2365 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2367 TCPCharDriver *s = chr->opaque;
2369 return io_channel_send(s->chan, buf, len);
2371 /* XXX: indicate an error ? */
2376 static int tcp_chr_read_poll(void *opaque)
2378 CharDriverState *chr = opaque;
2379 TCPCharDriver *s = chr->opaque;
2382 s->max_size = qemu_chr_be_can_write(chr);
2387 #define IAC_BREAK 243
2388 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2390 uint8_t *buf, int *size)
2392 /* Handle any telnet client's basic IAC options to satisfy char by
2393 * char mode with no echo. All IAC options will be removed from
2394 * the buf and the do_telnetopt variable will be used to track the
2395 * state of the width of the IAC information.
2397 * IAC commands come in sets of 3 bytes with the exception of the
2398 * "IAC BREAK" command and the double IAC.
2404 for (i = 0; i < *size; i++) {
2405 if (s->do_telnetopt > 1) {
2406 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2407 /* Double IAC means send an IAC */
2411 s->do_telnetopt = 1;
2413 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2414 /* Handle IAC break commands by sending a serial break */
2415 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2420 if (s->do_telnetopt >= 4) {
2421 s->do_telnetopt = 1;
2424 if ((unsigned char)buf[i] == IAC) {
2425 s->do_telnetopt = 2;
2436 static int tcp_get_msgfd(CharDriverState *chr)
2438 TCPCharDriver *s = chr->opaque;
2445 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2447 TCPCharDriver *s = chr->opaque;
2448 struct cmsghdr *cmsg;
2450 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2453 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2454 cmsg->cmsg_level != SOL_SOCKET ||
2455 cmsg->cmsg_type != SCM_RIGHTS)
2458 fd = *((int *)CMSG_DATA(cmsg));
2462 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2465 #ifndef MSG_CMSG_CLOEXEC
2466 qemu_set_cloexec(fd);
2474 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2476 TCPCharDriver *s = chr->opaque;
2477 struct msghdr msg = { NULL, };
2478 struct iovec iov[1];
2480 struct cmsghdr cmsg;
2481 char control[CMSG_SPACE(sizeof(int))];
2486 iov[0].iov_base = buf;
2487 iov[0].iov_len = len;
2491 msg.msg_control = &msg_control;
2492 msg.msg_controllen = sizeof(msg_control);
2494 #ifdef MSG_CMSG_CLOEXEC
2495 flags |= MSG_CMSG_CLOEXEC;
2497 ret = recvmsg(s->fd, &msg, flags);
2498 if (ret > 0 && s->is_unix) {
2499 unix_process_msgfd(chr, &msg);
2505 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2507 TCPCharDriver *s = chr->opaque;
2508 return qemu_recv(s->fd, buf, len, 0);
2512 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2514 TCPCharDriver *s = chr->opaque;
2515 return g_io_create_watch(s->chan, cond);
2518 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2520 CharDriverState *chr = opaque;
2521 TCPCharDriver *s = chr->opaque;
2522 uint8_t buf[READ_BUF_LEN];
2525 if (!s->connected || s->max_size <= 0) {
2529 if (len > s->max_size)
2531 size = tcp_chr_recv(chr, (void *)buf, len);
2533 /* connection closed */
2535 if (s->listen_chan) {
2536 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2539 io_remove_watch_poll(s->tag);
2542 g_io_channel_unref(s->chan);
2546 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2547 } else if (size > 0) {
2548 if (s->do_telnetopt)
2549 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2551 qemu_chr_be_write(chr, buf, size);
2558 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2560 return qemu_chr_open_fd(eventfd, eventfd);
2564 static void tcp_chr_connect(void *opaque)
2566 CharDriverState *chr = opaque;
2567 TCPCharDriver *s = chr->opaque;
2571 s->tag = io_add_watch_poll(s->chan, tcp_chr_read_poll, tcp_chr_read, chr);
2573 qemu_chr_be_generic_open(chr);
2576 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2577 static void tcp_chr_telnet_init(int fd)
2580 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2581 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2582 send(fd, (char *)buf, 3, 0);
2583 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2584 send(fd, (char *)buf, 3, 0);
2585 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2586 send(fd, (char *)buf, 3, 0);
2587 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2588 send(fd, (char *)buf, 3, 0);
2591 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2593 TCPCharDriver *s = chr->opaque;
2597 qemu_set_nonblock(fd);
2599 socket_set_nodelay(fd);
2601 s->chan = io_channel_from_socket(fd);
2602 if (s->listen_tag) {
2603 g_source_remove(s->listen_tag);
2606 tcp_chr_connect(chr);
2611 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2613 CharDriverState *chr = opaque;
2614 TCPCharDriver *s = chr->opaque;
2615 struct sockaddr_in saddr;
2617 struct sockaddr_un uaddr;
2619 struct sockaddr *addr;
2626 len = sizeof(uaddr);
2627 addr = (struct sockaddr *)&uaddr;
2631 len = sizeof(saddr);
2632 addr = (struct sockaddr *)&saddr;
2634 fd = qemu_accept(s->listen_fd, addr, &len);
2635 if (fd < 0 && errno != EINTR) {
2638 } else if (fd >= 0) {
2639 if (s->do_telnetopt)
2640 tcp_chr_telnet_init(fd);
2644 if (tcp_chr_add_client(chr, fd) < 0)
2650 static void tcp_chr_close(CharDriverState *chr)
2652 TCPCharDriver *s = chr->opaque;
2655 io_remove_watch_poll(s->tag);
2659 g_io_channel_unref(s->chan);
2663 if (s->listen_fd >= 0) {
2664 if (s->listen_tag) {
2665 g_source_remove(s->listen_tag);
2668 if (s->listen_chan) {
2669 g_io_channel_unref(s->listen_chan);
2671 closesocket(s->listen_fd);
2674 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2677 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2678 bool is_listen, bool is_telnet,
2679 bool is_waitconnect,
2682 CharDriverState *chr = NULL;
2683 TCPCharDriver *s = NULL;
2684 char host[NI_MAXHOST], serv[NI_MAXSERV];
2685 const char *left = "", *right = "";
2686 struct sockaddr_storage ss;
2687 socklen_t ss_len = sizeof(ss);
2689 memset(&ss, 0, ss_len);
2690 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2691 error_setg(errp, "getsockname: %s", strerror(errno));
2695 chr = g_malloc0(sizeof(CharDriverState));
2696 s = g_malloc0(sizeof(TCPCharDriver));
2703 chr->filename = g_malloc(256);
2704 switch (ss.ss_family) {
2708 snprintf(chr->filename, 256, "unix:%s%s",
2709 ((struct sockaddr_un *)(&ss))->sun_path,
2710 is_listen ? ",server" : "");
2718 s->do_nodelay = do_nodelay;
2719 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2720 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2721 snprintf(chr->filename, 256, "%s:%s%s%s:%s%s",
2722 is_telnet ? "telnet" : "tcp",
2723 left, host, right, serv,
2724 is_listen ? ",server" : "");
2729 chr->chr_write = tcp_chr_write;
2730 chr->chr_close = tcp_chr_close;
2731 chr->get_msgfd = tcp_get_msgfd;
2732 chr->chr_add_client = tcp_chr_add_client;
2733 chr->chr_add_watch = tcp_chr_add_watch;
2737 s->listen_chan = io_channel_from_socket(s->listen_fd);
2738 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2740 s->do_telnetopt = 1;
2745 socket_set_nodelay(fd);
2746 s->chan = io_channel_from_socket(s->fd);
2747 tcp_chr_connect(chr);
2750 if (is_listen && is_waitconnect) {
2751 printf("QEMU waiting for connection on: %s\n",
2753 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2754 qemu_set_nonblock(s->listen_fd);
2759 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2761 CharDriverState *chr = NULL;
2762 Error *local_err = NULL;
2770 is_listen = qemu_opt_get_bool(opts, "server", 0);
2771 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2772 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2773 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2774 is_unix = qemu_opt_get(opts, "path") != NULL;
2780 fd = unix_listen_opts(opts, &local_err);
2782 fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2786 fd = inet_listen_opts(opts, 0, &local_err);
2788 fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2795 if (!is_waitconnect)
2796 qemu_set_nonblock(fd);
2798 chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2799 is_waitconnect, &local_err);
2800 if (error_is_set(&local_err)) {
2808 qerror_report_err(local_err);
2809 error_free(local_err);
2815 g_free(chr->opaque);
2821 /*********************************************************/
2822 /* Ring buffer chardev */
2829 } RingBufCharDriver;
2831 static size_t ringbuf_count(const CharDriverState *chr)
2833 const RingBufCharDriver *d = chr->opaque;
2835 return d->prod - d->cons;
2838 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2840 RingBufCharDriver *d = chr->opaque;
2843 if (!buf || (len < 0)) {
2847 for (i = 0; i < len; i++ ) {
2848 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2849 if (d->prod - d->cons > d->size) {
2850 d->cons = d->prod - d->size;
2857 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2859 RingBufCharDriver *d = chr->opaque;
2862 for (i = 0; i < len && d->cons != d->prod; i++) {
2863 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2869 static void ringbuf_chr_close(struct CharDriverState *chr)
2871 RingBufCharDriver *d = chr->opaque;
2878 static CharDriverState *qemu_chr_open_memory(ChardevMemory *opts,
2881 CharDriverState *chr;
2882 RingBufCharDriver *d;
2884 chr = g_malloc0(sizeof(CharDriverState));
2885 d = g_malloc(sizeof(*d));
2887 d->size = opts->has_size ? opts->size : 65536;
2889 /* The size must be power of 2 */
2890 if (d->size & (d->size - 1)) {
2891 error_setg(errp, "size of memory chardev must be power of two");
2897 d->cbuf = g_malloc0(d->size);
2900 chr->chr_write = ringbuf_chr_write;
2901 chr->chr_close = ringbuf_chr_close;
2911 static bool chr_is_ringbuf(const CharDriverState *chr)
2913 return chr->chr_write == ringbuf_chr_write;
2916 void qmp_ringbuf_write(const char *device, const char *data,
2917 bool has_format, enum DataFormat format,
2920 CharDriverState *chr;
2921 const uint8_t *write_data;
2925 chr = qemu_chr_find(device);
2927 error_setg(errp, "Device '%s' not found", device);
2931 if (!chr_is_ringbuf(chr)) {
2932 error_setg(errp,"%s is not a ringbuf device", device);
2936 if (has_format && (format == DATA_FORMAT_BASE64)) {
2937 write_data = g_base64_decode(data, &write_count);
2939 write_data = (uint8_t *)data;
2940 write_count = strlen(data);
2943 ret = ringbuf_chr_write(chr, write_data, write_count);
2945 if (write_data != (uint8_t *)data) {
2946 g_free((void *)write_data);
2950 error_setg(errp, "Failed to write to device %s", device);
2955 char *qmp_ringbuf_read(const char *device, int64_t size,
2956 bool has_format, enum DataFormat format,
2959 CharDriverState *chr;
2964 chr = qemu_chr_find(device);
2966 error_setg(errp, "Device '%s' not found", device);
2970 if (!chr_is_ringbuf(chr)) {
2971 error_setg(errp,"%s is not a ringbuf device", device);
2976 error_setg(errp, "size must be greater than zero");
2980 count = ringbuf_count(chr);
2981 size = size > count ? count : size;
2982 read_data = g_malloc(size + 1);
2984 ringbuf_chr_read(chr, read_data, size);
2986 if (has_format && (format == DATA_FORMAT_BASE64)) {
2987 data = g_base64_encode(read_data, size);
2991 * FIXME should read only complete, valid UTF-8 characters up
2992 * to @size bytes. Invalid sequences should be replaced by a
2993 * suitable replacement character. Except when (and only
2994 * when) ring buffer lost characters since last read, initial
2995 * continuation characters should be dropped.
2997 read_data[size] = 0;
2998 data = (char *)read_data;
3004 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3006 char host[65], port[33], width[8], height[8];
3010 Error *local_err = NULL;
3012 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3013 if (error_is_set(&local_err)) {
3014 qerror_report_err(local_err);
3015 error_free(local_err);
3019 if (strstart(filename, "mon:", &p)) {
3021 qemu_opt_set(opts, "mux", "on");
3024 if (strcmp(filename, "null") == 0 ||
3025 strcmp(filename, "pty") == 0 ||
3026 strcmp(filename, "msmouse") == 0 ||
3027 strcmp(filename, "braille") == 0 ||
3028 strcmp(filename, "stdio") == 0) {
3029 qemu_opt_set(opts, "backend", filename);
3032 if (strstart(filename, "vc", &p)) {
3033 qemu_opt_set(opts, "backend", "vc");
3035 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
3037 qemu_opt_set(opts, "width", width);
3038 qemu_opt_set(opts, "height", height);
3039 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
3041 qemu_opt_set(opts, "cols", width);
3042 qemu_opt_set(opts, "rows", height);
3049 if (strcmp(filename, "con:") == 0) {
3050 qemu_opt_set(opts, "backend", "console");
3053 if (strstart(filename, "COM", NULL)) {
3054 qemu_opt_set(opts, "backend", "serial");
3055 qemu_opt_set(opts, "path", filename);
3058 if (strstart(filename, "file:", &p)) {
3059 qemu_opt_set(opts, "backend", "file");
3060 qemu_opt_set(opts, "path", p);
3063 if (strstart(filename, "pipe:", &p)) {
3064 qemu_opt_set(opts, "backend", "pipe");
3065 qemu_opt_set(opts, "path", p);
3068 if (strstart(filename, "tcp:", &p) ||
3069 strstart(filename, "telnet:", &p)) {
3070 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3072 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3075 qemu_opt_set(opts, "backend", "socket");
3076 qemu_opt_set(opts, "host", host);
3077 qemu_opt_set(opts, "port", port);
3078 if (p[pos] == ',') {
3079 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3082 if (strstart(filename, "telnet:", &p))
3083 qemu_opt_set(opts, "telnet", "on");
3086 if (strstart(filename, "udp:", &p)) {
3087 qemu_opt_set(opts, "backend", "udp");
3088 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3090 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3094 qemu_opt_set(opts, "host", host);
3095 qemu_opt_set(opts, "port", port);
3096 if (p[pos] == '@') {
3098 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3100 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3104 qemu_opt_set(opts, "localaddr", host);
3105 qemu_opt_set(opts, "localport", port);
3109 if (strstart(filename, "unix:", &p)) {
3110 qemu_opt_set(opts, "backend", "socket");
3111 if (qemu_opts_do_parse(opts, p, "path") != 0)
3115 if (strstart(filename, "/dev/parport", NULL) ||
3116 strstart(filename, "/dev/ppi", NULL)) {
3117 qemu_opt_set(opts, "backend", "parport");
3118 qemu_opt_set(opts, "path", filename);
3121 if (strstart(filename, "/dev/", NULL)) {
3122 qemu_opt_set(opts, "backend", "tty");
3123 qemu_opt_set(opts, "path", filename);
3128 qemu_opts_del(opts);
3132 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3135 const char *path = qemu_opt_get(opts, "path");
3138 error_setg(errp, "chardev: file: no filename given");
3141 backend->file = g_new0(ChardevFile, 1);
3142 backend->file->out = g_strdup(path);
3145 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3148 backend->stdio = g_new0(ChardevStdio, 1);
3149 backend->stdio->has_signal = true;
3150 backend->stdio->signal =
3151 qemu_opt_get_bool(opts, "signal", display_type != DT_NOGRAPHIC);
3154 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3157 const char *device = qemu_opt_get(opts, "path");
3159 if (device == NULL) {
3160 error_setg(errp, "chardev: serial/tty: no device path given");
3163 backend->serial = g_new0(ChardevHostdev, 1);
3164 backend->serial->device = g_strdup(device);
3167 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3170 const char *device = qemu_opt_get(opts, "path");
3172 if (device == NULL) {
3173 error_setg(errp, "chardev: parallel: no device path given");
3176 backend->parallel = g_new0(ChardevHostdev, 1);
3177 backend->parallel->device = g_strdup(device);
3180 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3183 const char *device = qemu_opt_get(opts, "path");
3185 if (device == NULL) {
3186 error_setg(errp, "chardev: pipe: no device path given");
3189 backend->pipe = g_new0(ChardevHostdev, 1);
3190 backend->pipe->device = g_strdup(device);
3193 static void qemu_chr_parse_memory(QemuOpts *opts, ChardevBackend *backend,
3198 backend->memory = g_new0(ChardevMemory, 1);
3200 val = qemu_opt_get_number(opts, "size", 0);
3202 backend->memory->has_size = true;
3203 backend->memory->size = val;
3207 typedef struct CharDriver {
3210 CharDriverState *(*open)(QemuOpts *opts);
3211 /* new, qapi-based */
3213 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3216 static GSList *backends;
3218 void register_char_driver(const char *name, CharDriverState *(*open)(QemuOpts *))
3222 s = g_malloc0(sizeof(*s));
3223 s->name = g_strdup(name);
3226 backends = g_slist_append(backends, s);
3229 void register_char_driver_qapi(const char *name, int kind,
3230 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3234 s = g_malloc0(sizeof(*s));
3235 s->name = g_strdup(name);
3239 backends = g_slist_append(backends, s);
3242 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3243 void (*init)(struct CharDriverState *s),
3247 CharDriverState *chr;
3250 if (qemu_opts_id(opts) == NULL) {
3251 error_setg(errp, "chardev: no id specified");
3255 if (qemu_opt_get(opts, "backend") == NULL) {
3256 error_setg(errp, "chardev: \"%s\" missing backend",
3257 qemu_opts_id(opts));
3260 for (i = backends; i; i = i->next) {
3263 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3268 error_setg(errp, "chardev: backend \"%s\" not found",
3269 qemu_opt_get(opts, "backend"));
3274 /* using new, qapi init */
3275 ChardevBackend *backend = g_new0(ChardevBackend, 1);
3276 ChardevReturn *ret = NULL;
3277 const char *id = qemu_opts_id(opts);
3278 const char *bid = NULL;
3280 if (qemu_opt_get_bool(opts, "mux", 0)) {
3281 bid = g_strdup_printf("%s-base", id);
3285 backend->kind = cd->kind;
3287 cd->parse(opts, backend, errp);
3288 if (error_is_set(errp)) {
3292 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3293 if (error_is_set(errp)) {
3298 qapi_free_ChardevBackend(backend);
3299 qapi_free_ChardevReturn(ret);
3300 backend = g_new0(ChardevBackend, 1);
3301 backend->mux = g_new0(ChardevMux, 1);
3302 backend->kind = CHARDEV_BACKEND_KIND_MUX;
3303 backend->mux->chardev = g_strdup(bid);
3304 ret = qmp_chardev_add(id, backend, errp);
3305 if (error_is_set(errp)) {
3310 chr = qemu_chr_find(id);
3313 qapi_free_ChardevBackend(backend);
3314 qapi_free_ChardevReturn(ret);
3318 chr = cd->open(opts);
3320 error_setg(errp, "chardev: opening backend \"%s\" failed",
3321 qemu_opt_get(opts, "backend"));
3326 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3328 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3330 if (qemu_opt_get_bool(opts, "mux", 0)) {
3331 CharDriverState *base = chr;
3332 int len = strlen(qemu_opts_id(opts)) + 6;
3333 base->label = g_malloc(len);
3334 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3335 chr = qemu_chr_open_mux(base);
3336 chr->filename = base->filename;
3337 chr->avail_connections = MAX_MUX;
3338 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3340 chr->avail_connections = 1;
3342 chr->label = g_strdup(qemu_opts_id(opts));
3347 qemu_opts_del(opts);
3351 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3354 CharDriverState *chr;
3358 if (strstart(filename, "chardev:", &p)) {
3359 return qemu_chr_find(p);
3362 opts = qemu_chr_parse_compat(label, filename);
3366 chr = qemu_chr_new_from_opts(opts, init, &err);
3367 if (error_is_set(&err)) {
3368 fprintf(stderr, "%s\n", error_get_pretty(err));
3371 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3372 qemu_chr_fe_claim_no_fail(chr);
3373 monitor_init(chr, MONITOR_USE_READLINE);
3378 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3380 if (chr->chr_set_echo) {
3381 chr->chr_set_echo(chr, echo);
3385 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3387 if (chr->fe_open == fe_open) {
3390 chr->fe_open = fe_open;
3391 if (chr->chr_set_fe_open) {
3392 chr->chr_set_fe_open(chr, fe_open);
3396 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3397 GIOFunc func, void *user_data)
3402 if (s->chr_add_watch == NULL) {
3406 src = s->chr_add_watch(s, cond);
3407 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3408 tag = g_source_attach(src, NULL);
3409 g_source_unref(src);
3414 int qemu_chr_fe_claim(CharDriverState *s)
3416 if (s->avail_connections < 1) {
3419 s->avail_connections--;
3423 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3425 if (qemu_chr_fe_claim(s) != 0) {
3426 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3427 __func__, s->label);
3432 void qemu_chr_fe_release(CharDriverState *s)
3434 s->avail_connections++;
3437 void qemu_chr_delete(CharDriverState *chr)
3439 QTAILQ_REMOVE(&chardevs, chr, next);
3440 if (chr->chr_close) {
3441 chr->chr_close(chr);
3443 g_free(chr->filename);
3446 qemu_opts_del(chr->opts);
3451 ChardevInfoList *qmp_query_chardev(Error **errp)
3453 ChardevInfoList *chr_list = NULL;
3454 CharDriverState *chr;
3456 QTAILQ_FOREACH(chr, &chardevs, next) {
3457 ChardevInfoList *info = g_malloc0(sizeof(*info));
3458 info->value = g_malloc0(sizeof(*info->value));
3459 info->value->label = g_strdup(chr->label);
3460 info->value->filename = g_strdup(chr->filename);
3462 info->next = chr_list;
3469 CharDriverState *qemu_chr_find(const char *name)
3471 CharDriverState *chr;
3473 QTAILQ_FOREACH(chr, &chardevs, next) {
3474 if (strcmp(chr->label, name) != 0)
3481 /* Get a character (serial) device interface. */
3482 CharDriverState *qemu_char_get_next_serial(void)
3484 static int next_serial;
3485 CharDriverState *chr;
3487 /* FIXME: This function needs to go away: use chardev properties! */
3489 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3490 chr = serial_hds[next_serial++];
3491 qemu_chr_fe_claim_no_fail(chr);
3497 QemuOptsList qemu_chardev_opts = {
3499 .implied_opt_name = "backend",
3500 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3504 .type = QEMU_OPT_STRING,
3507 .type = QEMU_OPT_STRING,
3510 .type = QEMU_OPT_STRING,
3513 .type = QEMU_OPT_STRING,
3515 .name = "localaddr",
3516 .type = QEMU_OPT_STRING,
3518 .name = "localport",
3519 .type = QEMU_OPT_STRING,
3522 .type = QEMU_OPT_NUMBER,
3525 .type = QEMU_OPT_BOOL,
3528 .type = QEMU_OPT_BOOL,
3531 .type = QEMU_OPT_BOOL,
3534 .type = QEMU_OPT_BOOL,
3537 .type = QEMU_OPT_BOOL,
3540 .type = QEMU_OPT_BOOL,
3543 .type = QEMU_OPT_NUMBER,
3546 .type = QEMU_OPT_NUMBER,
3549 .type = QEMU_OPT_NUMBER,
3552 .type = QEMU_OPT_NUMBER,
3555 .type = QEMU_OPT_BOOL,
3558 .type = QEMU_OPT_BOOL,
3561 .type = QEMU_OPT_STRING,
3564 .type = QEMU_OPT_NUMBER,
3567 .type = QEMU_OPT_SIZE,
3569 { /* end of list */ }
3575 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3580 error_setg(errp, "input file not supported");
3584 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3585 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3586 if (out == INVALID_HANDLE_VALUE) {
3587 error_setg(errp, "open %s failed", file->out);
3590 return qemu_chr_open_win_file(out);
3593 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3596 return qemu_chr_open_win_path(serial->device);
3599 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3602 error_setg(errp, "character device backend type 'parallel' not supported");
3608 static int qmp_chardev_open_file_source(char *src, int flags,
3613 TFR(fd = qemu_open(src, flags, 0666));
3615 error_setg(errp, "open %s: %s", src, strerror(errno));
3620 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3622 int flags, in = -1, out = -1;
3624 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3625 out = qmp_chardev_open_file_source(file->out, flags, errp);
3626 if (error_is_set(errp)) {
3632 in = qmp_chardev_open_file_source(file->in, flags, errp);
3633 if (error_is_set(errp)) {
3639 return qemu_chr_open_fd(in, out);
3642 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3645 #ifdef HAVE_CHARDEV_TTY
3648 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3649 if (error_is_set(errp)) {
3652 qemu_set_nonblock(fd);
3653 return qemu_chr_open_tty_fd(fd);
3655 error_setg(errp, "character device backend type 'serial' not supported");
3660 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3663 #ifdef HAVE_CHARDEV_PARPORT
3666 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3667 if (error_is_set(errp)) {
3670 return qemu_chr_open_pp_fd(fd);
3672 error_setg(errp, "character device backend type 'parallel' not supported");
3679 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3682 SocketAddress *addr = sock->addr;
3683 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3684 bool is_listen = sock->has_server ? sock->server : true;
3685 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3686 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3690 fd = socket_listen(addr, errp);
3692 fd = socket_connect(addr, errp, NULL, NULL);
3694 if (error_is_set(errp)) {
3697 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3698 is_telnet, is_waitconnect, errp);
3701 static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
3706 fd = socket_dgram(udp->remote, udp->local, errp);
3707 if (error_is_set(errp)) {
3710 return qemu_chr_open_udp_fd(fd);
3713 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3716 ChardevReturn *ret = g_new0(ChardevReturn, 1);
3717 CharDriverState *base, *chr = NULL;
3719 chr = qemu_chr_find(id);
3721 error_setg(errp, "Chardev '%s' already exists", id);
3726 switch (backend->kind) {
3727 case CHARDEV_BACKEND_KIND_FILE:
3728 chr = qmp_chardev_open_file(backend->file, errp);
3730 case CHARDEV_BACKEND_KIND_SERIAL:
3731 chr = qmp_chardev_open_serial(backend->serial, errp);
3733 case CHARDEV_BACKEND_KIND_PARALLEL:
3734 chr = qmp_chardev_open_parallel(backend->parallel, errp);
3736 case CHARDEV_BACKEND_KIND_PIPE:
3737 chr = qemu_chr_open_pipe(backend->pipe);
3739 case CHARDEV_BACKEND_KIND_SOCKET:
3740 chr = qmp_chardev_open_socket(backend->socket, errp);
3742 case CHARDEV_BACKEND_KIND_UDP:
3743 chr = qmp_chardev_open_udp(backend->udp, errp);
3745 #ifdef HAVE_CHARDEV_TTY
3746 case CHARDEV_BACKEND_KIND_PTY:
3747 chr = qemu_chr_open_pty(id, ret);
3750 case CHARDEV_BACKEND_KIND_NULL:
3751 chr = qemu_chr_open_null();
3753 case CHARDEV_BACKEND_KIND_MUX:
3754 base = qemu_chr_find(backend->mux->chardev);
3756 error_setg(errp, "mux: base chardev %s not found",
3757 backend->mux->chardev);
3760 chr = qemu_chr_open_mux(base);
3762 case CHARDEV_BACKEND_KIND_MSMOUSE:
3763 chr = qemu_chr_open_msmouse();
3765 #ifdef CONFIG_BRLAPI
3766 case CHARDEV_BACKEND_KIND_BRAILLE:
3767 chr = chr_baum_init();
3770 case CHARDEV_BACKEND_KIND_STDIO:
3771 chr = qemu_chr_open_stdio(backend->stdio);
3774 case CHARDEV_BACKEND_KIND_CONSOLE:
3775 chr = qemu_chr_open_win_con();
3779 case CHARDEV_BACKEND_KIND_SPICEVMC:
3780 chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
3782 case CHARDEV_BACKEND_KIND_SPICEPORT:
3783 chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
3786 case CHARDEV_BACKEND_KIND_VC:
3787 chr = vc_init(backend->vc);
3789 case CHARDEV_BACKEND_KIND_MEMORY:
3790 chr = qemu_chr_open_memory(backend->memory, errp);
3793 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3797 if (chr == NULL && !error_is_set(errp)) {
3798 error_setg(errp, "Failed to create chardev");
3801 chr->label = g_strdup(id);
3802 chr->avail_connections =
3803 (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
3804 if (!chr->filename) {
3805 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
3807 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3815 void qmp_chardev_remove(const char *id, Error **errp)
3817 CharDriverState *chr;
3819 chr = qemu_chr_find(id);
3821 error_setg(errp, "Chardev '%s' not found", id);
3824 if (chr->chr_can_read || chr->chr_read ||
3825 chr->chr_event || chr->handler_opaque) {
3826 error_setg(errp, "Chardev '%s' is busy", id);
3829 qemu_chr_delete(chr);
3832 static void register_types(void)
3834 register_char_driver_qapi("null", CHARDEV_BACKEND_KIND_NULL, NULL);
3835 register_char_driver("socket", qemu_chr_open_socket);
3836 register_char_driver("udp", qemu_chr_open_udp);
3837 register_char_driver_qapi("memory", CHARDEV_BACKEND_KIND_MEMORY,
3838 qemu_chr_parse_memory);
3839 register_char_driver_qapi("file", CHARDEV_BACKEND_KIND_FILE,
3840 qemu_chr_parse_file_out);
3841 register_char_driver_qapi("stdio", CHARDEV_BACKEND_KIND_STDIO,
3842 qemu_chr_parse_stdio);
3843 register_char_driver_qapi("serial", CHARDEV_BACKEND_KIND_SERIAL,
3844 qemu_chr_parse_serial);
3845 register_char_driver_qapi("tty", CHARDEV_BACKEND_KIND_SERIAL,
3846 qemu_chr_parse_serial);
3847 register_char_driver_qapi("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
3848 qemu_chr_parse_parallel);
3849 register_char_driver_qapi("parport", CHARDEV_BACKEND_KIND_PARALLEL,
3850 qemu_chr_parse_parallel);
3851 register_char_driver_qapi("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
3852 register_char_driver_qapi("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
3853 register_char_driver_qapi("pipe", CHARDEV_BACKEND_KIND_PIPE,
3854 qemu_chr_parse_pipe);
3857 type_init(register_types);