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"
29 #include "qemu-timer.h"
30 #include "qemu-char.h"
33 #include "hw/msmouse.h"
34 #include "qemu-objects.h"
45 #include <sys/times.h>
49 #include <sys/ioctl.h>
50 #include <sys/resource.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
54 #include <arpa/inet.h>
57 #include <sys/select.h>
60 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
62 #include <dev/ppbus/ppi.h>
63 #include <dev/ppbus/ppbconf.h>
64 #if defined(__GLIBC__)
67 #elif defined(__DragonFly__)
69 #include <dev/misc/ppi/ppi.h>
70 #include <bus/ppbus/ppbconf.h>
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
99 #include "qemu_socket.h"
100 #include "ui/qemu-spice.h"
102 #define READ_BUF_LEN 4096
104 /***********************************************************/
105 /* character device */
107 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
108 QTAILQ_HEAD_INITIALIZER(chardevs);
110 static void qemu_chr_event(CharDriverState *s, int event)
112 /* Keep track if the char device is open */
114 case CHR_EVENT_OPENED:
117 case CHR_EVENT_CLOSED:
124 s->chr_event(s->handler_opaque, event);
127 static void qemu_chr_generic_open_bh(void *opaque)
129 CharDriverState *s = opaque;
130 qemu_chr_event(s, CHR_EVENT_OPENED);
131 qemu_bh_delete(s->bh);
135 void qemu_chr_generic_open(CharDriverState *s)
138 s->bh = qemu_bh_new(qemu_chr_generic_open_bh, s);
139 qemu_bh_schedule(s->bh);
143 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
145 return s->chr_write(s, buf, len);
148 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
152 return s->chr_ioctl(s, cmd, arg);
155 int qemu_chr_can_read(CharDriverState *s)
157 if (!s->chr_can_read)
159 return s->chr_can_read(s->handler_opaque);
162 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
164 s->chr_read(s->handler_opaque, buf, len);
167 int qemu_chr_get_msgfd(CharDriverState *s)
169 return s->get_msgfd ? s->get_msgfd(s) : -1;
172 void qemu_chr_accept_input(CharDriverState *s)
174 if (s->chr_accept_input)
175 s->chr_accept_input(s);
178 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
180 char buf[READ_BUF_LEN];
183 vsnprintf(buf, sizeof(buf), fmt, ap);
184 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
188 void qemu_chr_send_event(CharDriverState *s, int event)
190 if (s->chr_send_event)
191 s->chr_send_event(s, event);
194 void qemu_chr_add_handlers(CharDriverState *s,
195 IOCanReadHandler *fd_can_read,
196 IOReadHandler *fd_read,
197 IOEventHandler *fd_event,
201 /* chr driver being released. */
204 s->chr_can_read = fd_can_read;
205 s->chr_read = fd_read;
206 s->chr_event = fd_event;
207 s->handler_opaque = opaque;
208 if (s->chr_update_read_handler)
209 s->chr_update_read_handler(s);
211 /* We're connecting to an already opened device, so let's make sure we
212 also get the open event */
214 qemu_chr_generic_open(s);
218 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
223 static CharDriverState *qemu_chr_open_null(QemuOpts *opts)
225 CharDriverState *chr;
227 chr = qemu_mallocz(sizeof(CharDriverState));
228 chr->chr_write = null_chr_write;
232 /* MUX driver for serial I/O splitting */
234 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
235 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
237 IOCanReadHandler *chr_can_read[MAX_MUX];
238 IOReadHandler *chr_read[MAX_MUX];
239 IOEventHandler *chr_event[MAX_MUX];
240 void *ext_opaque[MAX_MUX];
241 CharDriverState *drv;
246 /* Intermediate input buffer allows to catch escape sequences even if the
247 currently active device is not accepting any input - but only until it
249 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
254 int64_t timestamps_start;
258 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
260 MuxDriver *d = chr->opaque;
262 if (!d->timestamps) {
263 ret = d->drv->chr_write(d->drv, buf, len);
268 for (i = 0; i < len; i++) {
274 ti = qemu_get_clock(rt_clock);
275 if (d->timestamps_start == -1)
276 d->timestamps_start = ti;
277 ti -= d->timestamps_start;
279 snprintf(buf1, sizeof(buf1),
280 "[%02d:%02d:%02d.%03d] ",
285 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
288 ret += d->drv->chr_write(d->drv, buf+i, 1);
289 if (buf[i] == '\n') {
297 static const char * const mux_help[] = {
298 "% h print this help\n\r",
299 "% x exit emulator\n\r",
300 "% s save disk data back to file (if -snapshot)\n\r",
301 "% t toggle console timestamps\n\r"
302 "% b send break (magic sysrq)\n\r",
303 "% c switch between console and monitor\n\r",
308 int term_escape_char = 0x01; /* ctrl-a is used for escape */
309 static void mux_print_help(CharDriverState *chr)
312 char ebuf[15] = "Escape-Char";
313 char cbuf[50] = "\n\r";
315 if (term_escape_char > 0 && term_escape_char < 26) {
316 snprintf(cbuf, sizeof(cbuf), "\n\r");
317 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
319 snprintf(cbuf, sizeof(cbuf),
320 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
323 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
324 for (i = 0; mux_help[i] != NULL; i++) {
325 for (j=0; mux_help[i][j] != '\0'; j++) {
326 if (mux_help[i][j] == '%')
327 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
329 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
334 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
336 if (d->chr_event[mux_nr])
337 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
340 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
342 if (d->term_got_escape) {
343 d->term_got_escape = 0;
344 if (ch == term_escape_char)
353 const char *term = "QEMU: Terminated\n\r";
354 chr->chr_write(chr,(uint8_t *)term,strlen(term));
362 qemu_chr_event(chr, CHR_EVENT_BREAK);
365 /* Switch to the next registered device */
366 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
368 if (d->focus >= d->mux_cnt)
370 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
373 d->timestamps = !d->timestamps;
374 d->timestamps_start = -1;
378 } else if (ch == term_escape_char) {
379 d->term_got_escape = 1;
387 static void mux_chr_accept_input(CharDriverState *chr)
389 MuxDriver *d = chr->opaque;
392 while (d->prod[m] != d->cons[m] &&
393 d->chr_can_read[m] &&
394 d->chr_can_read[m](d->ext_opaque[m])) {
395 d->chr_read[m](d->ext_opaque[m],
396 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
400 static int mux_chr_can_read(void *opaque)
402 CharDriverState *chr = opaque;
403 MuxDriver *d = chr->opaque;
406 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
408 if (d->chr_can_read[m])
409 return d->chr_can_read[m](d->ext_opaque[m]);
413 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
415 CharDriverState *chr = opaque;
416 MuxDriver *d = chr->opaque;
420 mux_chr_accept_input (opaque);
422 for(i = 0; i < size; i++)
423 if (mux_proc_byte(chr, d, buf[i])) {
424 if (d->prod[m] == d->cons[m] &&
425 d->chr_can_read[m] &&
426 d->chr_can_read[m](d->ext_opaque[m]))
427 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
429 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
433 static void mux_chr_event(void *opaque, int event)
435 CharDriverState *chr = opaque;
436 MuxDriver *d = chr->opaque;
439 /* Send the event to all registered listeners */
440 for (i = 0; i < d->mux_cnt; i++)
441 mux_chr_send_event(d, i, event);
444 static void mux_chr_update_read_handler(CharDriverState *chr)
446 MuxDriver *d = chr->opaque;
448 if (d->mux_cnt >= MAX_MUX) {
449 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
452 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
453 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
454 d->chr_read[d->mux_cnt] = chr->chr_read;
455 d->chr_event[d->mux_cnt] = chr->chr_event;
456 /* Fix up the real driver with mux routines */
457 if (d->mux_cnt == 0) {
458 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
461 if (d->focus != -1) {
462 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
464 d->focus = d->mux_cnt;
466 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
469 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
471 CharDriverState *chr;
474 chr = qemu_mallocz(sizeof(CharDriverState));
475 d = qemu_mallocz(sizeof(MuxDriver));
480 chr->chr_write = mux_chr_write;
481 chr->chr_update_read_handler = mux_chr_update_read_handler;
482 chr->chr_accept_input = mux_chr_accept_input;
484 /* Muxes are always open on creation */
485 qemu_chr_generic_open(chr);
492 int send_all(int fd, const void *buf, int len1)
498 ret = send(fd, buf, len, 0);
500 errno = WSAGetLastError();
501 if (errno != WSAEWOULDBLOCK) {
504 } else if (ret == 0) {
516 int send_all(int fd, const void *_buf, int len1)
519 const uint8_t *buf = _buf;
523 ret = write(fd, buf, len);
525 if (errno != EINTR && errno != EAGAIN)
527 } else if (ret == 0) {
545 #define STDIO_MAX_CLIENTS 1
546 static int stdio_nb_clients = 0;
548 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
550 FDCharDriver *s = chr->opaque;
551 return send_all(s->fd_out, buf, len);
554 static int fd_chr_read_poll(void *opaque)
556 CharDriverState *chr = opaque;
557 FDCharDriver *s = chr->opaque;
559 s->max_size = qemu_chr_can_read(chr);
563 static void fd_chr_read(void *opaque)
565 CharDriverState *chr = opaque;
566 FDCharDriver *s = chr->opaque;
568 uint8_t buf[READ_BUF_LEN];
571 if (len > s->max_size)
575 size = read(s->fd_in, buf, len);
577 /* FD has been closed. Remove it from the active list. */
578 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
579 qemu_chr_event(chr, CHR_EVENT_CLOSED);
583 qemu_chr_read(chr, buf, size);
587 static void fd_chr_update_read_handler(CharDriverState *chr)
589 FDCharDriver *s = chr->opaque;
592 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
594 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
595 fd_chr_read, NULL, chr);
600 static void fd_chr_close(struct CharDriverState *chr)
602 FDCharDriver *s = chr->opaque;
605 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
607 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
612 qemu_chr_event(chr, CHR_EVENT_CLOSED);
615 /* open a character device to a unix fd */
616 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
618 CharDriverState *chr;
621 chr = qemu_mallocz(sizeof(CharDriverState));
622 s = qemu_mallocz(sizeof(FDCharDriver));
626 chr->chr_write = fd_chr_write;
627 chr->chr_update_read_handler = fd_chr_update_read_handler;
628 chr->chr_close = fd_chr_close;
630 qemu_chr_generic_open(chr);
635 static CharDriverState *qemu_chr_open_file_out(QemuOpts *opts)
639 TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
640 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
643 return qemu_chr_open_fd(-1, fd_out);
646 static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)
649 char filename_in[256], filename_out[256];
650 const char *filename = qemu_opt_get(opts, "path");
652 if (filename == NULL) {
653 fprintf(stderr, "chardev: pipe: no filename given\n");
657 snprintf(filename_in, 256, "%s.in", filename);
658 snprintf(filename_out, 256, "%s.out", filename);
659 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
660 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
661 if (fd_in < 0 || fd_out < 0) {
666 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
670 return qemu_chr_open_fd(fd_in, fd_out);
674 /* for STDIO, we handle the case where several clients use it
677 #define TERM_FIFO_MAX_SIZE 1
679 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
680 static int term_fifo_size;
682 static int stdio_read_poll(void *opaque)
684 CharDriverState *chr = opaque;
686 /* try to flush the queue if needed */
687 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
688 qemu_chr_read(chr, term_fifo, 1);
691 /* see if we can absorb more chars */
692 if (term_fifo_size == 0)
698 static void stdio_read(void *opaque)
702 CharDriverState *chr = opaque;
704 size = read(0, buf, 1);
706 /* stdin has been closed. Remove it from the active list. */
707 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
708 qemu_chr_event(chr, CHR_EVENT_CLOSED);
712 if (qemu_chr_can_read(chr) > 0) {
713 qemu_chr_read(chr, buf, 1);
714 } else if (term_fifo_size == 0) {
715 term_fifo[term_fifo_size++] = buf[0];
720 /* init terminal so that we can grab keys */
721 static struct termios oldtty;
722 static int old_fd0_flags;
723 static bool stdio_allow_signal;
725 static void term_exit(void)
727 tcsetattr (0, TCSANOW, &oldtty);
728 fcntl(0, F_SETFL, old_fd0_flags);
731 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
737 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
738 |INLCR|IGNCR|ICRNL|IXON);
739 tty.c_oflag |= OPOST;
740 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
741 tty.c_cflag &= ~(CSIZE|PARENB);
746 /* if graphical mode, we allow Ctrl-C handling */
747 if (!stdio_allow_signal)
748 tty.c_lflag &= ~ISIG;
750 tcsetattr (0, TCSANOW, &tty);
753 static void qemu_chr_close_stdio(struct CharDriverState *chr)
757 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
761 static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)
763 CharDriverState *chr;
765 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
767 if (stdio_nb_clients == 0) {
768 old_fd0_flags = fcntl(0, F_GETFL);
769 tcgetattr (0, &oldtty);
770 fcntl(0, F_SETFL, O_NONBLOCK);
774 chr = qemu_chr_open_fd(0, 1);
775 chr->chr_close = qemu_chr_close_stdio;
776 chr->chr_set_echo = qemu_chr_set_echo_stdio;
777 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
779 stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
780 display_type != DT_NOGRAPHIC);
781 qemu_chr_set_echo(chr, false);
787 /* Once Solaris has openpty(), this is going to be removed. */
788 static int openpty(int *amaster, int *aslave, char *name,
789 struct termios *termp, struct winsize *winp)
792 int mfd = -1, sfd = -1;
794 *amaster = *aslave = -1;
796 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
800 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
803 if ((slave = ptsname(mfd)) == NULL)
806 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
809 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
810 (termp != NULL && tcgetattr(sfd, termp) < 0))
818 ioctl(sfd, TIOCSWINSZ, winp);
829 static void cfmakeraw (struct termios *termios_p)
831 termios_p->c_iflag &=
832 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
833 termios_p->c_oflag &= ~OPOST;
834 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
835 termios_p->c_cflag &= ~(CSIZE|PARENB);
836 termios_p->c_cflag |= CS8;
838 termios_p->c_cc[VMIN] = 0;
839 termios_p->c_cc[VTIME] = 0;
843 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
844 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
845 || defined(__GLIBC__)
855 static void pty_chr_update_read_handler(CharDriverState *chr);
856 static void pty_chr_state(CharDriverState *chr, int connected);
858 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
860 PtyCharDriver *s = chr->opaque;
863 /* guest sends data, check for (re-)connect */
864 pty_chr_update_read_handler(chr);
867 return send_all(s->fd, buf, len);
870 static int pty_chr_read_poll(void *opaque)
872 CharDriverState *chr = opaque;
873 PtyCharDriver *s = chr->opaque;
875 s->read_bytes = qemu_chr_can_read(chr);
876 return s->read_bytes;
879 static void pty_chr_read(void *opaque)
881 CharDriverState *chr = opaque;
882 PtyCharDriver *s = chr->opaque;
884 uint8_t buf[READ_BUF_LEN];
887 if (len > s->read_bytes)
891 size = read(s->fd, buf, len);
892 if ((size == -1 && errno == EIO) ||
894 pty_chr_state(chr, 0);
898 pty_chr_state(chr, 1);
899 qemu_chr_read(chr, buf, size);
903 static void pty_chr_update_read_handler(CharDriverState *chr)
905 PtyCharDriver *s = chr->opaque;
907 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
908 pty_chr_read, NULL, chr);
911 * Short timeout here: just need wait long enougth that qemu makes
912 * it through the poll loop once. When reconnected we want a
913 * short timeout so we notice it almost instantly. Otherwise
914 * read() gives us -EIO instantly, making pty_chr_state() reset the
915 * timeout to the normal (much longer) poll interval before the
918 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
921 static void pty_chr_state(CharDriverState *chr, int connected)
923 PtyCharDriver *s = chr->opaque;
926 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
929 /* (re-)connect poll interval for idle guests: once per second.
930 * We check more frequently in case the guests sends data to
931 * the virtual device linked to our pty. */
932 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
935 qemu_chr_generic_open(chr);
940 static void pty_chr_timer(void *opaque)
942 struct CharDriverState *chr = opaque;
943 PtyCharDriver *s = chr->opaque;
948 /* If we arrive here without polling being cleared due
949 * read returning -EIO, then we are (re-)connected */
950 pty_chr_state(chr, 1);
955 pty_chr_update_read_handler(chr);
958 static void pty_chr_close(struct CharDriverState *chr)
960 PtyCharDriver *s = chr->opaque;
962 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
964 qemu_del_timer(s->timer);
965 qemu_free_timer(s->timer);
967 qemu_chr_event(chr, CHR_EVENT_CLOSED);
970 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
972 CharDriverState *chr;
976 #if defined(__OpenBSD__) || defined(__DragonFly__)
977 char pty_name[PATH_MAX];
978 #define q_ptsname(x) pty_name
980 char *pty_name = NULL;
981 #define q_ptsname(x) ptsname(x)
984 chr = qemu_mallocz(sizeof(CharDriverState));
985 s = qemu_mallocz(sizeof(PtyCharDriver));
987 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
991 /* Set raw attributes on the pty. */
992 tcgetattr(slave_fd, &tty);
994 tcsetattr(slave_fd, TCSAFLUSH, &tty);
997 len = strlen(q_ptsname(s->fd)) + 5;
998 chr->filename = qemu_malloc(len);
999 snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
1000 qemu_opt_set(opts, "path", q_ptsname(s->fd));
1001 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
1004 chr->chr_write = pty_chr_write;
1005 chr->chr_update_read_handler = pty_chr_update_read_handler;
1006 chr->chr_close = pty_chr_close;
1008 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
1013 static void tty_serial_init(int fd, int speed,
1014 int parity, int data_bits, int stop_bits)
1020 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1021 speed, parity, data_bits, stop_bits);
1023 tcgetattr (fd, &tty);
1025 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1026 speed = speed * 10 / 11;
1043 /* Non-Posix values follow. They may be unsupported on some systems. */
1045 check_speed(115200);
1047 check_speed(230400);
1050 check_speed(460800);
1053 check_speed(500000);
1056 check_speed(576000);
1059 check_speed(921600);
1062 check_speed(1000000);
1065 check_speed(1152000);
1068 check_speed(1500000);
1071 check_speed(2000000);
1074 check_speed(2500000);
1077 check_speed(3000000);
1080 check_speed(3500000);
1083 check_speed(4000000);
1088 cfsetispeed(&tty, spd);
1089 cfsetospeed(&tty, spd);
1091 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1092 |INLCR|IGNCR|ICRNL|IXON);
1093 tty.c_oflag |= OPOST;
1094 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1095 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1116 tty.c_cflag |= PARENB;
1119 tty.c_cflag |= PARENB | PARODD;
1123 tty.c_cflag |= CSTOPB;
1125 tcsetattr (fd, TCSANOW, &tty);
1128 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1130 FDCharDriver *s = chr->opaque;
1133 case CHR_IOCTL_SERIAL_SET_PARAMS:
1135 QEMUSerialSetParams *ssp = arg;
1136 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1137 ssp->data_bits, ssp->stop_bits);
1140 case CHR_IOCTL_SERIAL_SET_BREAK:
1142 int enable = *(int *)arg;
1144 tcsendbreak(s->fd_in, 1);
1147 case CHR_IOCTL_SERIAL_GET_TIOCM:
1150 int *targ = (int *)arg;
1151 ioctl(s->fd_in, TIOCMGET, &sarg);
1153 if (sarg & TIOCM_CTS)
1154 *targ |= CHR_TIOCM_CTS;
1155 if (sarg & TIOCM_CAR)
1156 *targ |= CHR_TIOCM_CAR;
1157 if (sarg & TIOCM_DSR)
1158 *targ |= CHR_TIOCM_DSR;
1159 if (sarg & TIOCM_RI)
1160 *targ |= CHR_TIOCM_RI;
1161 if (sarg & TIOCM_DTR)
1162 *targ |= CHR_TIOCM_DTR;
1163 if (sarg & TIOCM_RTS)
1164 *targ |= CHR_TIOCM_RTS;
1167 case CHR_IOCTL_SERIAL_SET_TIOCM:
1169 int sarg = *(int *)arg;
1171 ioctl(s->fd_in, TIOCMGET, &targ);
1172 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1173 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1174 if (sarg & CHR_TIOCM_CTS)
1176 if (sarg & CHR_TIOCM_CAR)
1178 if (sarg & CHR_TIOCM_DSR)
1180 if (sarg & CHR_TIOCM_RI)
1182 if (sarg & CHR_TIOCM_DTR)
1184 if (sarg & CHR_TIOCM_RTS)
1186 ioctl(s->fd_in, TIOCMSET, &targ);
1195 static void qemu_chr_close_tty(CharDriverState *chr)
1197 FDCharDriver *s = chr->opaque;
1211 static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
1213 const char *filename = qemu_opt_get(opts, "path");
1214 CharDriverState *chr;
1217 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
1221 tty_serial_init(fd, 115200, 'N', 8, 1);
1222 chr = qemu_chr_open_fd(fd, fd);
1227 chr->chr_ioctl = tty_serial_ioctl;
1228 chr->chr_close = qemu_chr_close_tty;
1231 #else /* ! __linux__ && ! __sun__ */
1232 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
1236 #endif /* __linux__ || __sun__ */
1238 #if defined(__linux__)
1242 } ParallelCharDriver;
1244 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1246 if (s->mode != mode) {
1248 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1255 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1257 ParallelCharDriver *drv = chr->opaque;
1262 case CHR_IOCTL_PP_READ_DATA:
1263 if (ioctl(fd, PPRDATA, &b) < 0)
1265 *(uint8_t *)arg = b;
1267 case CHR_IOCTL_PP_WRITE_DATA:
1268 b = *(uint8_t *)arg;
1269 if (ioctl(fd, PPWDATA, &b) < 0)
1272 case CHR_IOCTL_PP_READ_CONTROL:
1273 if (ioctl(fd, PPRCONTROL, &b) < 0)
1275 /* Linux gives only the lowest bits, and no way to know data
1276 direction! For better compatibility set the fixed upper
1278 *(uint8_t *)arg = b | 0xc0;
1280 case CHR_IOCTL_PP_WRITE_CONTROL:
1281 b = *(uint8_t *)arg;
1282 if (ioctl(fd, PPWCONTROL, &b) < 0)
1285 case CHR_IOCTL_PP_READ_STATUS:
1286 if (ioctl(fd, PPRSTATUS, &b) < 0)
1288 *(uint8_t *)arg = b;
1290 case CHR_IOCTL_PP_DATA_DIR:
1291 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1294 case CHR_IOCTL_PP_EPP_READ_ADDR:
1295 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1296 struct ParallelIOArg *parg = arg;
1297 int n = read(fd, parg->buffer, parg->count);
1298 if (n != parg->count) {
1303 case CHR_IOCTL_PP_EPP_READ:
1304 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1305 struct ParallelIOArg *parg = arg;
1306 int n = read(fd, parg->buffer, parg->count);
1307 if (n != parg->count) {
1312 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1313 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1314 struct ParallelIOArg *parg = arg;
1315 int n = write(fd, parg->buffer, parg->count);
1316 if (n != parg->count) {
1321 case CHR_IOCTL_PP_EPP_WRITE:
1322 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1323 struct ParallelIOArg *parg = arg;
1324 int n = write(fd, parg->buffer, parg->count);
1325 if (n != parg->count) {
1336 static void pp_close(CharDriverState *chr)
1338 ParallelCharDriver *drv = chr->opaque;
1341 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1342 ioctl(fd, PPRELEASE);
1345 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1348 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1350 const char *filename = qemu_opt_get(opts, "path");
1351 CharDriverState *chr;
1352 ParallelCharDriver *drv;
1355 TFR(fd = open(filename, O_RDWR));
1359 if (ioctl(fd, PPCLAIM) < 0) {
1364 drv = qemu_mallocz(sizeof(ParallelCharDriver));
1366 drv->mode = IEEE1284_MODE_COMPAT;
1368 chr = qemu_mallocz(sizeof(CharDriverState));
1369 chr->chr_write = null_chr_write;
1370 chr->chr_ioctl = pp_ioctl;
1371 chr->chr_close = pp_close;
1374 qemu_chr_generic_open(chr);
1378 #endif /* __linux__ */
1380 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1381 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1383 int fd = (int)(intptr_t)chr->opaque;
1387 case CHR_IOCTL_PP_READ_DATA:
1388 if (ioctl(fd, PPIGDATA, &b) < 0)
1390 *(uint8_t *)arg = b;
1392 case CHR_IOCTL_PP_WRITE_DATA:
1393 b = *(uint8_t *)arg;
1394 if (ioctl(fd, PPISDATA, &b) < 0)
1397 case CHR_IOCTL_PP_READ_CONTROL:
1398 if (ioctl(fd, PPIGCTRL, &b) < 0)
1400 *(uint8_t *)arg = b;
1402 case CHR_IOCTL_PP_WRITE_CONTROL:
1403 b = *(uint8_t *)arg;
1404 if (ioctl(fd, PPISCTRL, &b) < 0)
1407 case CHR_IOCTL_PP_READ_STATUS:
1408 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1410 *(uint8_t *)arg = b;
1418 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1420 const char *filename = qemu_opt_get(opts, "path");
1421 CharDriverState *chr;
1424 fd = open(filename, O_RDWR);
1428 chr = qemu_mallocz(sizeof(CharDriverState));
1429 chr->opaque = (void *)(intptr_t)fd;
1430 chr->chr_write = null_chr_write;
1431 chr->chr_ioctl = pp_ioctl;
1440 HANDLE hcom, hrecv, hsend;
1441 OVERLAPPED orecv, osend;
1446 #define NSENDBUF 2048
1447 #define NRECVBUF 2048
1448 #define MAXCONNECT 1
1449 #define NTIMEOUT 5000
1451 static int win_chr_poll(void *opaque);
1452 static int win_chr_pipe_poll(void *opaque);
1454 static void win_chr_close(CharDriverState *chr)
1456 WinCharState *s = chr->opaque;
1459 CloseHandle(s->hsend);
1463 CloseHandle(s->hrecv);
1467 CloseHandle(s->hcom);
1471 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1473 qemu_del_polling_cb(win_chr_poll, chr);
1475 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1478 static int win_chr_init(CharDriverState *chr, const char *filename)
1480 WinCharState *s = chr->opaque;
1482 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1487 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1489 fprintf(stderr, "Failed CreateEvent\n");
1492 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1494 fprintf(stderr, "Failed CreateEvent\n");
1498 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1499 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1500 if (s->hcom == INVALID_HANDLE_VALUE) {
1501 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1506 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1507 fprintf(stderr, "Failed SetupComm\n");
1511 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1512 size = sizeof(COMMCONFIG);
1513 GetDefaultCommConfig(filename, &comcfg, &size);
1514 comcfg.dcb.DCBlength = sizeof(DCB);
1515 CommConfigDialog(filename, NULL, &comcfg);
1517 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1518 fprintf(stderr, "Failed SetCommState\n");
1522 if (!SetCommMask(s->hcom, EV_ERR)) {
1523 fprintf(stderr, "Failed SetCommMask\n");
1527 cto.ReadIntervalTimeout = MAXDWORD;
1528 if (!SetCommTimeouts(s->hcom, &cto)) {
1529 fprintf(stderr, "Failed SetCommTimeouts\n");
1533 if (!ClearCommError(s->hcom, &err, &comstat)) {
1534 fprintf(stderr, "Failed ClearCommError\n");
1537 qemu_add_polling_cb(win_chr_poll, chr);
1545 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1547 WinCharState *s = chr->opaque;
1548 DWORD len, ret, size, err;
1551 ZeroMemory(&s->osend, sizeof(s->osend));
1552 s->osend.hEvent = s->hsend;
1555 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1557 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1559 err = GetLastError();
1560 if (err == ERROR_IO_PENDING) {
1561 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1579 static int win_chr_read_poll(CharDriverState *chr)
1581 WinCharState *s = chr->opaque;
1583 s->max_size = qemu_chr_can_read(chr);
1587 static void win_chr_readfile(CharDriverState *chr)
1589 WinCharState *s = chr->opaque;
1591 uint8_t buf[READ_BUF_LEN];
1594 ZeroMemory(&s->orecv, sizeof(s->orecv));
1595 s->orecv.hEvent = s->hrecv;
1596 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1598 err = GetLastError();
1599 if (err == ERROR_IO_PENDING) {
1600 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1605 qemu_chr_read(chr, buf, size);
1609 static void win_chr_read(CharDriverState *chr)
1611 WinCharState *s = chr->opaque;
1613 if (s->len > s->max_size)
1614 s->len = s->max_size;
1618 win_chr_readfile(chr);
1621 static int win_chr_poll(void *opaque)
1623 CharDriverState *chr = opaque;
1624 WinCharState *s = chr->opaque;
1628 ClearCommError(s->hcom, &comerr, &status);
1629 if (status.cbInQue > 0) {
1630 s->len = status.cbInQue;
1631 win_chr_read_poll(chr);
1638 static CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1640 const char *filename = qemu_opt_get(opts, "path");
1641 CharDriverState *chr;
1644 chr = qemu_mallocz(sizeof(CharDriverState));
1645 s = qemu_mallocz(sizeof(WinCharState));
1647 chr->chr_write = win_chr_write;
1648 chr->chr_close = win_chr_close;
1650 if (win_chr_init(chr, filename) < 0) {
1655 qemu_chr_generic_open(chr);
1659 static int win_chr_pipe_poll(void *opaque)
1661 CharDriverState *chr = opaque;
1662 WinCharState *s = chr->opaque;
1665 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1668 win_chr_read_poll(chr);
1675 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1677 WinCharState *s = chr->opaque;
1685 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1687 fprintf(stderr, "Failed CreateEvent\n");
1690 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1692 fprintf(stderr, "Failed CreateEvent\n");
1696 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1697 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1698 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1700 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1701 if (s->hcom == INVALID_HANDLE_VALUE) {
1702 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1707 ZeroMemory(&ov, sizeof(ov));
1708 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1709 ret = ConnectNamedPipe(s->hcom, &ov);
1711 fprintf(stderr, "Failed ConnectNamedPipe\n");
1715 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1717 fprintf(stderr, "Failed GetOverlappedResult\n");
1719 CloseHandle(ov.hEvent);
1726 CloseHandle(ov.hEvent);
1729 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1738 static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
1740 const char *filename = qemu_opt_get(opts, "path");
1741 CharDriverState *chr;
1744 chr = qemu_mallocz(sizeof(CharDriverState));
1745 s = qemu_mallocz(sizeof(WinCharState));
1747 chr->chr_write = win_chr_write;
1748 chr->chr_close = win_chr_close;
1750 if (win_chr_pipe_init(chr, filename) < 0) {
1755 qemu_chr_generic_open(chr);
1759 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1761 CharDriverState *chr;
1764 chr = qemu_mallocz(sizeof(CharDriverState));
1765 s = qemu_mallocz(sizeof(WinCharState));
1768 chr->chr_write = win_chr_write;
1769 qemu_chr_generic_open(chr);
1773 static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
1775 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1778 static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
1780 const char *file_out = qemu_opt_get(opts, "path");
1783 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1784 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1785 if (fd_out == INVALID_HANDLE_VALUE)
1788 return qemu_chr_open_win_file(fd_out);
1790 #endif /* !_WIN32 */
1792 /***********************************************************/
1793 /* UDP Net console */
1797 uint8_t buf[READ_BUF_LEN];
1803 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1805 NetCharDriver *s = chr->opaque;
1807 return send(s->fd, (const void *)buf, len, 0);
1810 static int udp_chr_read_poll(void *opaque)
1812 CharDriverState *chr = opaque;
1813 NetCharDriver *s = chr->opaque;
1815 s->max_size = qemu_chr_can_read(chr);
1817 /* If there were any stray characters in the queue process them
1820 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1821 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1823 s->max_size = qemu_chr_can_read(chr);
1828 static void udp_chr_read(void *opaque)
1830 CharDriverState *chr = opaque;
1831 NetCharDriver *s = chr->opaque;
1833 if (s->max_size == 0)
1835 s->bufcnt = recv(s->fd, (void *)s->buf, sizeof(s->buf), 0);
1836 s->bufptr = s->bufcnt;
1841 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1842 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1844 s->max_size = qemu_chr_can_read(chr);
1848 static void udp_chr_update_read_handler(CharDriverState *chr)
1850 NetCharDriver *s = chr->opaque;
1853 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
1854 udp_chr_read, NULL, chr);
1858 static void udp_chr_close(CharDriverState *chr)
1860 NetCharDriver *s = chr->opaque;
1862 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1866 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1869 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
1871 CharDriverState *chr = NULL;
1872 NetCharDriver *s = NULL;
1875 chr = qemu_mallocz(sizeof(CharDriverState));
1876 s = qemu_mallocz(sizeof(NetCharDriver));
1878 fd = inet_dgram_opts(opts);
1880 fprintf(stderr, "inet_dgram_opts failed\n");
1888 chr->chr_write = udp_chr_write;
1889 chr->chr_update_read_handler = udp_chr_update_read_handler;
1890 chr->chr_close = udp_chr_close;
1903 /***********************************************************/
1904 /* TCP Net console */
1916 static void tcp_chr_accept(void *opaque);
1918 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1920 TCPCharDriver *s = chr->opaque;
1922 return send_all(s->fd, buf, len);
1924 /* XXX: indicate an error ? */
1929 static int tcp_chr_read_poll(void *opaque)
1931 CharDriverState *chr = opaque;
1932 TCPCharDriver *s = chr->opaque;
1935 s->max_size = qemu_chr_can_read(chr);
1940 #define IAC_BREAK 243
1941 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
1943 uint8_t *buf, int *size)
1945 /* Handle any telnet client's basic IAC options to satisfy char by
1946 * char mode with no echo. All IAC options will be removed from
1947 * the buf and the do_telnetopt variable will be used to track the
1948 * state of the width of the IAC information.
1950 * IAC commands come in sets of 3 bytes with the exception of the
1951 * "IAC BREAK" command and the double IAC.
1957 for (i = 0; i < *size; i++) {
1958 if (s->do_telnetopt > 1) {
1959 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
1960 /* Double IAC means send an IAC */
1964 s->do_telnetopt = 1;
1966 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
1967 /* Handle IAC break commands by sending a serial break */
1968 qemu_chr_event(chr, CHR_EVENT_BREAK);
1973 if (s->do_telnetopt >= 4) {
1974 s->do_telnetopt = 1;
1977 if ((unsigned char)buf[i] == IAC) {
1978 s->do_telnetopt = 2;
1989 static int tcp_get_msgfd(CharDriverState *chr)
1991 TCPCharDriver *s = chr->opaque;
1998 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2000 TCPCharDriver *s = chr->opaque;
2001 struct cmsghdr *cmsg;
2003 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2006 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2007 cmsg->cmsg_level != SOL_SOCKET ||
2008 cmsg->cmsg_type != SCM_RIGHTS)
2011 fd = *((int *)CMSG_DATA(cmsg));
2021 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2023 TCPCharDriver *s = chr->opaque;
2024 struct msghdr msg = { NULL, };
2025 struct iovec iov[1];
2027 struct cmsghdr cmsg;
2028 char control[CMSG_SPACE(sizeof(int))];
2032 iov[0].iov_base = buf;
2033 iov[0].iov_len = len;
2037 msg.msg_control = &msg_control;
2038 msg.msg_controllen = sizeof(msg_control);
2040 ret = recvmsg(s->fd, &msg, 0);
2041 if (ret > 0 && s->is_unix)
2042 unix_process_msgfd(chr, &msg);
2047 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2049 TCPCharDriver *s = chr->opaque;
2050 return recv(s->fd, buf, len, 0);
2054 static void tcp_chr_read(void *opaque)
2056 CharDriverState *chr = opaque;
2057 TCPCharDriver *s = chr->opaque;
2058 uint8_t buf[READ_BUF_LEN];
2061 if (!s->connected || s->max_size <= 0)
2064 if (len > s->max_size)
2066 size = tcp_chr_recv(chr, (void *)buf, len);
2068 /* connection closed */
2070 if (s->listen_fd >= 0) {
2071 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2073 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2076 qemu_chr_event(chr, CHR_EVENT_CLOSED);
2077 } else if (size > 0) {
2078 if (s->do_telnetopt)
2079 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2081 qemu_chr_read(chr, buf, size);
2086 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2088 return qemu_chr_open_fd(eventfd, eventfd);
2092 static void tcp_chr_connect(void *opaque)
2094 CharDriverState *chr = opaque;
2095 TCPCharDriver *s = chr->opaque;
2098 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2099 tcp_chr_read, NULL, chr);
2100 qemu_chr_generic_open(chr);
2103 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2104 static void tcp_chr_telnet_init(int fd)
2107 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2108 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2109 send(fd, (char *)buf, 3, 0);
2110 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2111 send(fd, (char *)buf, 3, 0);
2112 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2113 send(fd, (char *)buf, 3, 0);
2114 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2115 send(fd, (char *)buf, 3, 0);
2118 static void socket_set_nodelay(int fd)
2121 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2124 static void tcp_chr_accept(void *opaque)
2126 CharDriverState *chr = opaque;
2127 TCPCharDriver *s = chr->opaque;
2128 struct sockaddr_in saddr;
2130 struct sockaddr_un uaddr;
2132 struct sockaddr *addr;
2139 len = sizeof(uaddr);
2140 addr = (struct sockaddr *)&uaddr;
2144 len = sizeof(saddr);
2145 addr = (struct sockaddr *)&saddr;
2147 fd = qemu_accept(s->listen_fd, addr, &len);
2148 if (fd < 0 && errno != EINTR) {
2150 } else if (fd >= 0) {
2151 if (s->do_telnetopt)
2152 tcp_chr_telnet_init(fd);
2156 socket_set_nonblock(fd);
2158 socket_set_nodelay(fd);
2160 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2161 tcp_chr_connect(chr);
2164 static void tcp_chr_close(CharDriverState *chr)
2166 TCPCharDriver *s = chr->opaque;
2168 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2171 if (s->listen_fd >= 0) {
2172 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2173 closesocket(s->listen_fd);
2176 qemu_chr_event(chr, CHR_EVENT_CLOSED);
2179 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2181 CharDriverState *chr = NULL;
2182 TCPCharDriver *s = NULL;
2190 is_listen = qemu_opt_get_bool(opts, "server", 0);
2191 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2192 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2193 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2194 is_unix = qemu_opt_get(opts, "path") != NULL;
2198 chr = qemu_mallocz(sizeof(CharDriverState));
2199 s = qemu_mallocz(sizeof(TCPCharDriver));
2203 fd = unix_listen_opts(opts);
2205 fd = unix_connect_opts(opts);
2209 fd = inet_listen_opts(opts, 0);
2211 fd = inet_connect_opts(opts);
2217 if (!is_waitconnect)
2218 socket_set_nonblock(fd);
2224 s->is_unix = is_unix;
2225 s->do_nodelay = do_nodelay && !is_unix;
2228 chr->chr_write = tcp_chr_write;
2229 chr->chr_close = tcp_chr_close;
2230 chr->get_msgfd = tcp_get_msgfd;
2234 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2236 s->do_telnetopt = 1;
2241 socket_set_nodelay(fd);
2242 tcp_chr_connect(chr);
2245 /* for "info chardev" monitor command */
2246 chr->filename = qemu_malloc(256);
2248 snprintf(chr->filename, 256, "unix:%s%s",
2249 qemu_opt_get(opts, "path"),
2250 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2251 } else if (is_telnet) {
2252 snprintf(chr->filename, 256, "telnet:%s:%s%s",
2253 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2254 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2256 snprintf(chr->filename, 256, "tcp:%s:%s%s",
2257 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2258 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2261 if (is_listen && is_waitconnect) {
2262 printf("QEMU waiting for connection on: %s\n",
2264 tcp_chr_accept(chr);
2265 socket_set_nonblock(s->listen_fd);
2277 /***********************************************************/
2278 /* Memory chardev */
2281 size_t outbuf_capacity;
2285 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2287 MemoryDriver *d = chr->opaque;
2289 /* TODO: the QString implementation has the same code, we should
2290 * introduce a generic way to do this in cutils.c */
2291 if (d->outbuf_capacity < d->outbuf_size + len) {
2293 d->outbuf_capacity += len;
2294 d->outbuf_capacity *= 2;
2295 d->outbuf = qemu_realloc(d->outbuf, d->outbuf_capacity);
2298 memcpy(d->outbuf + d->outbuf_size, buf, len);
2299 d->outbuf_size += len;
2304 void qemu_chr_init_mem(CharDriverState *chr)
2308 d = qemu_malloc(sizeof(*d));
2310 d->outbuf_capacity = 4096;
2311 d->outbuf = qemu_mallocz(d->outbuf_capacity);
2313 memset(chr, 0, sizeof(*chr));
2315 chr->chr_write = mem_chr_write;
2318 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2320 MemoryDriver *d = chr->opaque;
2321 return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2324 /* NOTE: this driver can not be closed with qemu_chr_close()! */
2325 void qemu_chr_close_mem(CharDriverState *chr)
2327 MemoryDriver *d = chr->opaque;
2329 qemu_free(d->outbuf);
2330 qemu_free(chr->opaque);
2332 chr->chr_write = NULL;
2335 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2337 const MemoryDriver *d = chr->opaque;
2338 return d->outbuf_size;
2341 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2343 char host[65], port[33], width[8], height[8];
2348 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1);
2352 if (strstart(filename, "mon:", &p)) {
2354 qemu_opt_set(opts, "mux", "on");
2357 if (strcmp(filename, "null") == 0 ||
2358 strcmp(filename, "pty") == 0 ||
2359 strcmp(filename, "msmouse") == 0 ||
2360 strcmp(filename, "braille") == 0 ||
2361 strcmp(filename, "stdio") == 0) {
2362 qemu_opt_set(opts, "backend", filename);
2365 if (strstart(filename, "vc", &p)) {
2366 qemu_opt_set(opts, "backend", "vc");
2368 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2370 qemu_opt_set(opts, "width", width);
2371 qemu_opt_set(opts, "height", height);
2372 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2374 qemu_opt_set(opts, "cols", width);
2375 qemu_opt_set(opts, "rows", height);
2382 if (strcmp(filename, "con:") == 0) {
2383 qemu_opt_set(opts, "backend", "console");
2386 if (strstart(filename, "COM", NULL)) {
2387 qemu_opt_set(opts, "backend", "serial");
2388 qemu_opt_set(opts, "path", filename);
2391 if (strstart(filename, "file:", &p)) {
2392 qemu_opt_set(opts, "backend", "file");
2393 qemu_opt_set(opts, "path", p);
2396 if (strstart(filename, "pipe:", &p)) {
2397 qemu_opt_set(opts, "backend", "pipe");
2398 qemu_opt_set(opts, "path", p);
2401 if (strstart(filename, "tcp:", &p) ||
2402 strstart(filename, "telnet:", &p)) {
2403 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2405 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2408 qemu_opt_set(opts, "backend", "socket");
2409 qemu_opt_set(opts, "host", host);
2410 qemu_opt_set(opts, "port", port);
2411 if (p[pos] == ',') {
2412 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2415 if (strstart(filename, "telnet:", &p))
2416 qemu_opt_set(opts, "telnet", "on");
2419 if (strstart(filename, "udp:", &p)) {
2420 qemu_opt_set(opts, "backend", "udp");
2421 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2423 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
2427 qemu_opt_set(opts, "host", host);
2428 qemu_opt_set(opts, "port", port);
2429 if (p[pos] == '@') {
2431 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2433 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2437 qemu_opt_set(opts, "localaddr", host);
2438 qemu_opt_set(opts, "localport", port);
2442 if (strstart(filename, "unix:", &p)) {
2443 qemu_opt_set(opts, "backend", "socket");
2444 if (qemu_opts_do_parse(opts, p, "path") != 0)
2448 if (strstart(filename, "/dev/parport", NULL) ||
2449 strstart(filename, "/dev/ppi", NULL)) {
2450 qemu_opt_set(opts, "backend", "parport");
2451 qemu_opt_set(opts, "path", filename);
2454 if (strstart(filename, "/dev/", NULL)) {
2455 qemu_opt_set(opts, "backend", "tty");
2456 qemu_opt_set(opts, "path", filename);
2461 qemu_opts_del(opts);
2465 static const struct {
2467 CharDriverState *(*open)(QemuOpts *opts);
2468 } backend_table[] = {
2469 { .name = "null", .open = qemu_chr_open_null },
2470 { .name = "socket", .open = qemu_chr_open_socket },
2471 { .name = "udp", .open = qemu_chr_open_udp },
2472 { .name = "msmouse", .open = qemu_chr_open_msmouse },
2473 { .name = "vc", .open = text_console_init },
2475 { .name = "file", .open = qemu_chr_open_win_file_out },
2476 { .name = "pipe", .open = qemu_chr_open_win_pipe },
2477 { .name = "console", .open = qemu_chr_open_win_con },
2478 { .name = "serial", .open = qemu_chr_open_win },
2480 { .name = "file", .open = qemu_chr_open_file_out },
2481 { .name = "pipe", .open = qemu_chr_open_pipe },
2482 { .name = "pty", .open = qemu_chr_open_pty },
2483 { .name = "stdio", .open = qemu_chr_open_stdio },
2485 #ifdef CONFIG_BRLAPI
2486 { .name = "braille", .open = chr_baum_init },
2488 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2489 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
2490 || defined(__FreeBSD_kernel__)
2491 { .name = "tty", .open = qemu_chr_open_tty },
2493 #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) \
2494 || defined(__FreeBSD_kernel__)
2495 { .name = "parport", .open = qemu_chr_open_pp },
2498 { .name = "spicevmc", .open = qemu_chr_open_spice },
2502 CharDriverState *qemu_chr_open_opts(QemuOpts *opts,
2503 void (*init)(struct CharDriverState *s))
2505 CharDriverState *chr;
2508 if (qemu_opts_id(opts) == NULL) {
2509 fprintf(stderr, "chardev: no id specified\n");
2513 if (qemu_opt_get(opts, "backend") == NULL) {
2514 fprintf(stderr, "chardev: \"%s\" missing backend\n",
2515 qemu_opts_id(opts));
2518 for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
2519 if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
2522 if (i == ARRAY_SIZE(backend_table)) {
2523 fprintf(stderr, "chardev: backend \"%s\" not found\n",
2524 qemu_opt_get(opts, "backend"));
2528 chr = backend_table[i].open(opts);
2530 fprintf(stderr, "chardev: opening backend \"%s\" failed\n",
2531 qemu_opt_get(opts, "backend"));
2536 chr->filename = qemu_strdup(qemu_opt_get(opts, "backend"));
2538 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2540 if (qemu_opt_get_bool(opts, "mux", 0)) {
2541 CharDriverState *base = chr;
2542 int len = strlen(qemu_opts_id(opts)) + 6;
2543 base->label = qemu_malloc(len);
2544 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
2545 chr = qemu_chr_open_mux(base);
2546 chr->filename = base->filename;
2547 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2549 chr->label = qemu_strdup(qemu_opts_id(opts));
2553 CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2556 CharDriverState *chr;
2559 if (strstart(filename, "chardev:", &p)) {
2560 return qemu_chr_find(p);
2563 opts = qemu_chr_parse_compat(label, filename);
2567 chr = qemu_chr_open_opts(opts, init);
2568 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
2569 monitor_init(chr, MONITOR_USE_READLINE);
2571 qemu_opts_del(opts);
2575 void qemu_chr_set_echo(struct CharDriverState *chr, bool echo)
2577 if (chr->chr_set_echo) {
2578 chr->chr_set_echo(chr, echo);
2582 void qemu_chr_close(CharDriverState *chr)
2584 QTAILQ_REMOVE(&chardevs, chr, next);
2586 chr->chr_close(chr);
2587 qemu_free(chr->filename);
2588 qemu_free(chr->label);
2592 static void qemu_chr_qlist_iter(QObject *obj, void *opaque)
2595 Monitor *mon = opaque;
2597 chr_dict = qobject_to_qdict(obj);
2598 monitor_printf(mon, "%s: filename=%s\n", qdict_get_str(chr_dict, "label"),
2599 qdict_get_str(chr_dict, "filename"));
2602 void qemu_chr_info_print(Monitor *mon, const QObject *ret_data)
2604 qlist_iter(qobject_to_qlist(ret_data), qemu_chr_qlist_iter, mon);
2607 void qemu_chr_info(Monitor *mon, QObject **ret_data)
2610 CharDriverState *chr;
2612 chr_list = qlist_new();
2614 QTAILQ_FOREACH(chr, &chardevs, next) {
2615 QObject *obj = qobject_from_jsonf("{ 'label': %s, 'filename': %s }",
2616 chr->label, chr->filename);
2617 qlist_append_obj(chr_list, obj);
2620 *ret_data = QOBJECT(chr_list);
2623 CharDriverState *qemu_chr_find(const char *name)
2625 CharDriverState *chr;
2627 QTAILQ_FOREACH(chr, &chardevs, next) {
2628 if (strcmp(chr->label, name) != 0)