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"
44 #include <sys/times.h>
48 #include <sys/ioctl.h>
49 #include <sys/resource.h>
50 #include <sys/socket.h>
51 #include <netinet/in.h>
53 #include <arpa/inet.h>
56 #include <sys/select.h>
59 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
61 #include <dev/ppbus/ppi.h>
62 #include <dev/ppbus/ppbconf.h>
63 #if defined(__GLIBC__)
66 #elif defined(__DragonFly__)
68 #include <dev/misc/ppi/ppi.h>
69 #include <bus/ppbus/ppbconf.h>
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
98 #include "qemu_socket.h"
99 #include "ui/qemu-spice.h"
101 #define READ_BUF_LEN 4096
103 /***********************************************************/
104 /* character device */
106 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
107 QTAILQ_HEAD_INITIALIZER(chardevs);
109 static void qemu_chr_event(CharDriverState *s, int event)
111 /* Keep track if the char device is open */
113 case CHR_EVENT_OPENED:
116 case CHR_EVENT_CLOSED:
123 s->chr_event(s->handler_opaque, event);
126 static void qemu_chr_generic_open_bh(void *opaque)
128 CharDriverState *s = opaque;
129 qemu_chr_event(s, CHR_EVENT_OPENED);
130 qemu_bh_delete(s->bh);
134 void qemu_chr_generic_open(CharDriverState *s)
137 s->bh = qemu_bh_new(qemu_chr_generic_open_bh, s);
138 qemu_bh_schedule(s->bh);
142 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
144 return s->chr_write(s, buf, len);
147 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
151 return s->chr_ioctl(s, cmd, arg);
154 int qemu_chr_be_can_write(CharDriverState *s)
156 if (!s->chr_can_read)
158 return s->chr_can_read(s->handler_opaque);
161 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
163 s->chr_read(s->handler_opaque, buf, len);
166 int qemu_chr_fe_get_msgfd(CharDriverState *s)
168 return s->get_msgfd ? s->get_msgfd(s) : -1;
171 int qemu_chr_add_client(CharDriverState *s, int fd)
173 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
176 void qemu_chr_accept_input(CharDriverState *s)
178 if (s->chr_accept_input)
179 s->chr_accept_input(s);
182 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
184 char buf[READ_BUF_LEN];
187 vsnprintf(buf, sizeof(buf), fmt, ap);
188 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
192 void qemu_chr_add_handlers(CharDriverState *s,
193 IOCanReadHandler *fd_can_read,
194 IOReadHandler *fd_read,
195 IOEventHandler *fd_event,
198 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
199 /* chr driver being released. */
200 ++s->avail_connections;
202 s->chr_can_read = fd_can_read;
203 s->chr_read = fd_read;
204 s->chr_event = fd_event;
205 s->handler_opaque = opaque;
206 if (s->chr_update_read_handler)
207 s->chr_update_read_handler(s);
209 /* We're connecting to an already opened device, so let's make sure we
210 also get the open event */
212 qemu_chr_generic_open(s);
216 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
221 static int qemu_chr_open_null(QemuOpts *opts, CharDriverState **_chr)
223 CharDriverState *chr;
225 chr = g_malloc0(sizeof(CharDriverState));
226 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_ms(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 = g_malloc0(sizeof(CharDriverState));
475 d = g_malloc0(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;
483 /* Frontend guest-open / -close notification is not support with muxes */
484 chr->chr_guest_open = NULL;
485 chr->chr_guest_close = NULL;
487 /* Muxes are always open on creation */
488 qemu_chr_generic_open(chr);
495 int send_all(int fd, const void *buf, int len1)
501 ret = send(fd, buf, len, 0);
503 errno = WSAGetLastError();
504 if (errno != WSAEWOULDBLOCK) {
507 } else if (ret == 0) {
519 int send_all(int fd, const void *_buf, int len1)
522 const uint8_t *buf = _buf;
526 ret = write(fd, buf, len);
528 if (errno != EINTR && errno != EAGAIN)
530 } else if (ret == 0) {
548 #define STDIO_MAX_CLIENTS 1
549 static int stdio_nb_clients = 0;
551 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
553 FDCharDriver *s = chr->opaque;
554 return send_all(s->fd_out, buf, len);
557 static int fd_chr_read_poll(void *opaque)
559 CharDriverState *chr = opaque;
560 FDCharDriver *s = chr->opaque;
562 s->max_size = qemu_chr_be_can_write(chr);
566 static void fd_chr_read(void *opaque)
568 CharDriverState *chr = opaque;
569 FDCharDriver *s = chr->opaque;
571 uint8_t buf[READ_BUF_LEN];
574 if (len > s->max_size)
578 size = read(s->fd_in, buf, len);
580 /* FD has been closed. Remove it from the active list. */
581 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
582 qemu_chr_event(chr, CHR_EVENT_CLOSED);
586 qemu_chr_be_write(chr, buf, size);
590 static void fd_chr_update_read_handler(CharDriverState *chr)
592 FDCharDriver *s = chr->opaque;
595 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
597 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
598 fd_chr_read, NULL, chr);
603 static void fd_chr_close(struct CharDriverState *chr)
605 FDCharDriver *s = chr->opaque;
608 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
610 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
615 qemu_chr_event(chr, CHR_EVENT_CLOSED);
618 /* open a character device to a unix fd */
619 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
621 CharDriverState *chr;
624 chr = g_malloc0(sizeof(CharDriverState));
625 s = g_malloc0(sizeof(FDCharDriver));
629 chr->chr_write = fd_chr_write;
630 chr->chr_update_read_handler = fd_chr_update_read_handler;
631 chr->chr_close = fd_chr_close;
633 qemu_chr_generic_open(chr);
638 static int qemu_chr_open_file_out(QemuOpts *opts, CharDriverState **_chr)
642 TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
643 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
648 *_chr = qemu_chr_open_fd(-1, fd_out);
652 static int qemu_chr_open_pipe(QemuOpts *opts, CharDriverState **_chr)
655 char filename_in[256], filename_out[256];
656 const char *filename = qemu_opt_get(opts, "path");
658 if (filename == NULL) {
659 fprintf(stderr, "chardev: pipe: no filename given\n");
663 snprintf(filename_in, 256, "%s.in", filename);
664 snprintf(filename_out, 256, "%s.out", filename);
665 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
666 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
667 if (fd_in < 0 || fd_out < 0) {
672 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
678 *_chr = qemu_chr_open_fd(fd_in, fd_out);
683 /* for STDIO, we handle the case where several clients use it
686 #define TERM_FIFO_MAX_SIZE 1
688 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
689 static int term_fifo_size;
691 static int stdio_read_poll(void *opaque)
693 CharDriverState *chr = opaque;
695 /* try to flush the queue if needed */
696 if (term_fifo_size != 0 && qemu_chr_be_can_write(chr) > 0) {
697 qemu_chr_be_write(chr, term_fifo, 1);
700 /* see if we can absorb more chars */
701 if (term_fifo_size == 0)
707 static void stdio_read(void *opaque)
711 CharDriverState *chr = opaque;
713 size = read(0, buf, 1);
715 /* stdin has been closed. Remove it from the active list. */
716 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
717 qemu_chr_event(chr, CHR_EVENT_CLOSED);
721 if (qemu_chr_be_can_write(chr) > 0) {
722 qemu_chr_be_write(chr, buf, 1);
723 } else if (term_fifo_size == 0) {
724 term_fifo[term_fifo_size++] = buf[0];
729 /* init terminal so that we can grab keys */
730 static struct termios oldtty;
731 static int old_fd0_flags;
732 static bool stdio_allow_signal;
734 static void term_exit(void)
736 tcsetattr (0, TCSANOW, &oldtty);
737 fcntl(0, F_SETFL, old_fd0_flags);
740 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
746 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
747 |INLCR|IGNCR|ICRNL|IXON);
748 tty.c_oflag |= OPOST;
749 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
750 tty.c_cflag &= ~(CSIZE|PARENB);
755 /* if graphical mode, we allow Ctrl-C handling */
756 if (!stdio_allow_signal)
757 tty.c_lflag &= ~ISIG;
759 tcsetattr (0, TCSANOW, &tty);
762 static void qemu_chr_close_stdio(struct CharDriverState *chr)
766 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
770 static int qemu_chr_open_stdio(QemuOpts *opts, CharDriverState **_chr)
772 CharDriverState *chr;
774 if (stdio_nb_clients >= STDIO_MAX_CLIENTS) {
778 if (stdio_nb_clients == 0) {
779 old_fd0_flags = fcntl(0, F_GETFL);
780 tcgetattr (0, &oldtty);
781 fcntl(0, F_SETFL, O_NONBLOCK);
785 chr = qemu_chr_open_fd(0, 1);
786 chr->chr_close = qemu_chr_close_stdio;
787 chr->chr_set_echo = qemu_chr_set_echo_stdio;
788 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
790 stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
791 display_type != DT_NOGRAPHIC);
792 qemu_chr_fe_set_echo(chr, false);
799 /* Once Solaris has openpty(), this is going to be removed. */
800 static int openpty(int *amaster, int *aslave, char *name,
801 struct termios *termp, struct winsize *winp)
804 int mfd = -1, sfd = -1;
806 *amaster = *aslave = -1;
808 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
812 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
815 if ((slave = ptsname(mfd)) == NULL)
818 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
821 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
822 (termp != NULL && tcgetattr(sfd, termp) < 0))
830 ioctl(sfd, TIOCSWINSZ, winp);
841 static void cfmakeraw (struct termios *termios_p)
843 termios_p->c_iflag &=
844 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
845 termios_p->c_oflag &= ~OPOST;
846 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
847 termios_p->c_cflag &= ~(CSIZE|PARENB);
848 termios_p->c_cflag |= CS8;
850 termios_p->c_cc[VMIN] = 0;
851 termios_p->c_cc[VTIME] = 0;
855 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
856 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
857 || defined(__GLIBC__)
867 static void pty_chr_update_read_handler(CharDriverState *chr);
868 static void pty_chr_state(CharDriverState *chr, int connected);
870 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
872 PtyCharDriver *s = chr->opaque;
875 /* guest sends data, check for (re-)connect */
876 pty_chr_update_read_handler(chr);
879 return send_all(s->fd, buf, len);
882 static int pty_chr_read_poll(void *opaque)
884 CharDriverState *chr = opaque;
885 PtyCharDriver *s = chr->opaque;
887 s->read_bytes = qemu_chr_be_can_write(chr);
888 return s->read_bytes;
891 static void pty_chr_read(void *opaque)
893 CharDriverState *chr = opaque;
894 PtyCharDriver *s = chr->opaque;
896 uint8_t buf[READ_BUF_LEN];
899 if (len > s->read_bytes)
903 size = read(s->fd, buf, len);
904 if ((size == -1 && errno == EIO) ||
906 pty_chr_state(chr, 0);
910 pty_chr_state(chr, 1);
911 qemu_chr_be_write(chr, buf, size);
915 static void pty_chr_update_read_handler(CharDriverState *chr)
917 PtyCharDriver *s = chr->opaque;
919 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
920 pty_chr_read, NULL, chr);
923 * Short timeout here: just need wait long enougth that qemu makes
924 * it through the poll loop once. When reconnected we want a
925 * short timeout so we notice it almost instantly. Otherwise
926 * read() gives us -EIO instantly, making pty_chr_state() reset the
927 * timeout to the normal (much longer) poll interval before the
930 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 10);
933 static void pty_chr_state(CharDriverState *chr, int connected)
935 PtyCharDriver *s = chr->opaque;
938 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
941 /* (re-)connect poll interval for idle guests: once per second.
942 * We check more frequently in case the guests sends data to
943 * the virtual device linked to our pty. */
944 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 1000);
947 qemu_chr_generic_open(chr);
952 static void pty_chr_timer(void *opaque)
954 struct CharDriverState *chr = opaque;
955 PtyCharDriver *s = chr->opaque;
960 /* If we arrive here without polling being cleared due
961 * read returning -EIO, then we are (re-)connected */
962 pty_chr_state(chr, 1);
967 pty_chr_update_read_handler(chr);
970 static void pty_chr_close(struct CharDriverState *chr)
972 PtyCharDriver *s = chr->opaque;
974 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
976 qemu_del_timer(s->timer);
977 qemu_free_timer(s->timer);
979 qemu_chr_event(chr, CHR_EVENT_CLOSED);
982 static int qemu_chr_open_pty(QemuOpts *opts, CharDriverState **_chr)
984 CharDriverState *chr;
988 #if defined(__OpenBSD__) || defined(__DragonFly__)
989 char pty_name[PATH_MAX];
990 #define q_ptsname(x) pty_name
992 char *pty_name = NULL;
993 #define q_ptsname(x) ptsname(x)
996 chr = g_malloc0(sizeof(CharDriverState));
997 s = g_malloc0(sizeof(PtyCharDriver));
999 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1003 /* Set raw attributes on the pty. */
1004 tcgetattr(slave_fd, &tty);
1006 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1009 len = strlen(q_ptsname(s->fd)) + 5;
1010 chr->filename = g_malloc(len);
1011 snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
1012 qemu_opt_set(opts, "path", q_ptsname(s->fd));
1013 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
1016 chr->chr_write = pty_chr_write;
1017 chr->chr_update_read_handler = pty_chr_update_read_handler;
1018 chr->chr_close = pty_chr_close;
1020 s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr);
1026 static void tty_serial_init(int fd, int speed,
1027 int parity, int data_bits, int stop_bits)
1033 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1034 speed, parity, data_bits, stop_bits);
1036 tcgetattr (fd, &tty);
1038 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1039 speed = speed * 10 / 11;
1056 /* Non-Posix values follow. They may be unsupported on some systems. */
1058 check_speed(115200);
1060 check_speed(230400);
1063 check_speed(460800);
1066 check_speed(500000);
1069 check_speed(576000);
1072 check_speed(921600);
1075 check_speed(1000000);
1078 check_speed(1152000);
1081 check_speed(1500000);
1084 check_speed(2000000);
1087 check_speed(2500000);
1090 check_speed(3000000);
1093 check_speed(3500000);
1096 check_speed(4000000);
1101 cfsetispeed(&tty, spd);
1102 cfsetospeed(&tty, spd);
1104 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1105 |INLCR|IGNCR|ICRNL|IXON);
1106 tty.c_oflag |= OPOST;
1107 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1108 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1129 tty.c_cflag |= PARENB;
1132 tty.c_cflag |= PARENB | PARODD;
1136 tty.c_cflag |= CSTOPB;
1138 tcsetattr (fd, TCSANOW, &tty);
1141 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1143 FDCharDriver *s = chr->opaque;
1146 case CHR_IOCTL_SERIAL_SET_PARAMS:
1148 QEMUSerialSetParams *ssp = arg;
1149 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1150 ssp->data_bits, ssp->stop_bits);
1153 case CHR_IOCTL_SERIAL_SET_BREAK:
1155 int enable = *(int *)arg;
1157 tcsendbreak(s->fd_in, 1);
1160 case CHR_IOCTL_SERIAL_GET_TIOCM:
1163 int *targ = (int *)arg;
1164 ioctl(s->fd_in, TIOCMGET, &sarg);
1166 if (sarg & TIOCM_CTS)
1167 *targ |= CHR_TIOCM_CTS;
1168 if (sarg & TIOCM_CAR)
1169 *targ |= CHR_TIOCM_CAR;
1170 if (sarg & TIOCM_DSR)
1171 *targ |= CHR_TIOCM_DSR;
1172 if (sarg & TIOCM_RI)
1173 *targ |= CHR_TIOCM_RI;
1174 if (sarg & TIOCM_DTR)
1175 *targ |= CHR_TIOCM_DTR;
1176 if (sarg & TIOCM_RTS)
1177 *targ |= CHR_TIOCM_RTS;
1180 case CHR_IOCTL_SERIAL_SET_TIOCM:
1182 int sarg = *(int *)arg;
1184 ioctl(s->fd_in, TIOCMGET, &targ);
1185 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1186 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1187 if (sarg & CHR_TIOCM_CTS)
1189 if (sarg & CHR_TIOCM_CAR)
1191 if (sarg & CHR_TIOCM_DSR)
1193 if (sarg & CHR_TIOCM_RI)
1195 if (sarg & CHR_TIOCM_DTR)
1197 if (sarg & CHR_TIOCM_RTS)
1199 ioctl(s->fd_in, TIOCMSET, &targ);
1208 static void qemu_chr_close_tty(CharDriverState *chr)
1210 FDCharDriver *s = chr->opaque;
1224 static int qemu_chr_open_tty(QemuOpts *opts, CharDriverState **_chr)
1226 const char *filename = qemu_opt_get(opts, "path");
1227 CharDriverState *chr;
1230 TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
1234 tty_serial_init(fd, 115200, 'N', 8, 1);
1235 chr = qemu_chr_open_fd(fd, fd);
1236 chr->chr_ioctl = tty_serial_ioctl;
1237 chr->chr_close = qemu_chr_close_tty;
1242 #else /* ! __linux__ && ! __sun__ */
1243 static int qemu_chr_open_pty(QemuOpts *opts, CharDriverState **_chr)
1247 #endif /* __linux__ || __sun__ */
1249 #if defined(__linux__)
1253 } ParallelCharDriver;
1255 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1257 if (s->mode != mode) {
1259 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1266 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1268 ParallelCharDriver *drv = chr->opaque;
1273 case CHR_IOCTL_PP_READ_DATA:
1274 if (ioctl(fd, PPRDATA, &b) < 0)
1276 *(uint8_t *)arg = b;
1278 case CHR_IOCTL_PP_WRITE_DATA:
1279 b = *(uint8_t *)arg;
1280 if (ioctl(fd, PPWDATA, &b) < 0)
1283 case CHR_IOCTL_PP_READ_CONTROL:
1284 if (ioctl(fd, PPRCONTROL, &b) < 0)
1286 /* Linux gives only the lowest bits, and no way to know data
1287 direction! For better compatibility set the fixed upper
1289 *(uint8_t *)arg = b | 0xc0;
1291 case CHR_IOCTL_PP_WRITE_CONTROL:
1292 b = *(uint8_t *)arg;
1293 if (ioctl(fd, PPWCONTROL, &b) < 0)
1296 case CHR_IOCTL_PP_READ_STATUS:
1297 if (ioctl(fd, PPRSTATUS, &b) < 0)
1299 *(uint8_t *)arg = b;
1301 case CHR_IOCTL_PP_DATA_DIR:
1302 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1305 case CHR_IOCTL_PP_EPP_READ_ADDR:
1306 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1307 struct ParallelIOArg *parg = arg;
1308 int n = read(fd, parg->buffer, parg->count);
1309 if (n != parg->count) {
1314 case CHR_IOCTL_PP_EPP_READ:
1315 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1316 struct ParallelIOArg *parg = arg;
1317 int n = read(fd, parg->buffer, parg->count);
1318 if (n != parg->count) {
1323 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1324 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1325 struct ParallelIOArg *parg = arg;
1326 int n = write(fd, parg->buffer, parg->count);
1327 if (n != parg->count) {
1332 case CHR_IOCTL_PP_EPP_WRITE:
1333 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1334 struct ParallelIOArg *parg = arg;
1335 int n = write(fd, parg->buffer, parg->count);
1336 if (n != parg->count) {
1347 static void pp_close(CharDriverState *chr)
1349 ParallelCharDriver *drv = chr->opaque;
1352 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1353 ioctl(fd, PPRELEASE);
1356 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1359 static int qemu_chr_open_pp(QemuOpts *opts, CharDriverState **_chr)
1361 const char *filename = qemu_opt_get(opts, "path");
1362 CharDriverState *chr;
1363 ParallelCharDriver *drv;
1366 TFR(fd = open(filename, O_RDWR));
1371 if (ioctl(fd, PPCLAIM) < 0) {
1376 drv = g_malloc0(sizeof(ParallelCharDriver));
1378 drv->mode = IEEE1284_MODE_COMPAT;
1380 chr = g_malloc0(sizeof(CharDriverState));
1381 chr->chr_write = null_chr_write;
1382 chr->chr_ioctl = pp_ioctl;
1383 chr->chr_close = pp_close;
1386 qemu_chr_generic_open(chr);
1391 #endif /* __linux__ */
1393 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1394 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1396 int fd = (int)(intptr_t)chr->opaque;
1400 case CHR_IOCTL_PP_READ_DATA:
1401 if (ioctl(fd, PPIGDATA, &b) < 0)
1403 *(uint8_t *)arg = b;
1405 case CHR_IOCTL_PP_WRITE_DATA:
1406 b = *(uint8_t *)arg;
1407 if (ioctl(fd, PPISDATA, &b) < 0)
1410 case CHR_IOCTL_PP_READ_CONTROL:
1411 if (ioctl(fd, PPIGCTRL, &b) < 0)
1413 *(uint8_t *)arg = b;
1415 case CHR_IOCTL_PP_WRITE_CONTROL:
1416 b = *(uint8_t *)arg;
1417 if (ioctl(fd, PPISCTRL, &b) < 0)
1420 case CHR_IOCTL_PP_READ_STATUS:
1421 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1423 *(uint8_t *)arg = b;
1431 static int qemu_chr_open_pp(QemuOpts *opts, CharDriverState **_chr)
1433 const char *filename = qemu_opt_get(opts, "path");
1434 CharDriverState *chr;
1437 fd = qemu_open(filename, O_RDWR);
1442 chr = g_malloc0(sizeof(CharDriverState));
1443 chr->opaque = (void *)(intptr_t)fd;
1444 chr->chr_write = null_chr_write;
1445 chr->chr_ioctl = pp_ioctl;
1456 HANDLE hcom, hrecv, hsend;
1457 OVERLAPPED orecv, osend;
1462 #define NSENDBUF 2048
1463 #define NRECVBUF 2048
1464 #define MAXCONNECT 1
1465 #define NTIMEOUT 5000
1467 static int win_chr_poll(void *opaque);
1468 static int win_chr_pipe_poll(void *opaque);
1470 static void win_chr_close(CharDriverState *chr)
1472 WinCharState *s = chr->opaque;
1475 CloseHandle(s->hsend);
1479 CloseHandle(s->hrecv);
1483 CloseHandle(s->hcom);
1487 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1489 qemu_del_polling_cb(win_chr_poll, chr);
1491 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1494 static int win_chr_init(CharDriverState *chr, const char *filename)
1496 WinCharState *s = chr->opaque;
1498 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1503 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1505 fprintf(stderr, "Failed CreateEvent\n");
1508 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1510 fprintf(stderr, "Failed CreateEvent\n");
1514 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1515 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1516 if (s->hcom == INVALID_HANDLE_VALUE) {
1517 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1522 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1523 fprintf(stderr, "Failed SetupComm\n");
1527 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1528 size = sizeof(COMMCONFIG);
1529 GetDefaultCommConfig(filename, &comcfg, &size);
1530 comcfg.dcb.DCBlength = sizeof(DCB);
1531 CommConfigDialog(filename, NULL, &comcfg);
1533 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1534 fprintf(stderr, "Failed SetCommState\n");
1538 if (!SetCommMask(s->hcom, EV_ERR)) {
1539 fprintf(stderr, "Failed SetCommMask\n");
1543 cto.ReadIntervalTimeout = MAXDWORD;
1544 if (!SetCommTimeouts(s->hcom, &cto)) {
1545 fprintf(stderr, "Failed SetCommTimeouts\n");
1549 if (!ClearCommError(s->hcom, &err, &comstat)) {
1550 fprintf(stderr, "Failed ClearCommError\n");
1553 qemu_add_polling_cb(win_chr_poll, chr);
1561 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1563 WinCharState *s = chr->opaque;
1564 DWORD len, ret, size, err;
1567 ZeroMemory(&s->osend, sizeof(s->osend));
1568 s->osend.hEvent = s->hsend;
1571 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1573 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1575 err = GetLastError();
1576 if (err == ERROR_IO_PENDING) {
1577 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1595 static int win_chr_read_poll(CharDriverState *chr)
1597 WinCharState *s = chr->opaque;
1599 s->max_size = qemu_chr_be_can_write(chr);
1603 static void win_chr_readfile(CharDriverState *chr)
1605 WinCharState *s = chr->opaque;
1607 uint8_t buf[READ_BUF_LEN];
1610 ZeroMemory(&s->orecv, sizeof(s->orecv));
1611 s->orecv.hEvent = s->hrecv;
1612 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1614 err = GetLastError();
1615 if (err == ERROR_IO_PENDING) {
1616 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1621 qemu_chr_be_write(chr, buf, size);
1625 static void win_chr_read(CharDriverState *chr)
1627 WinCharState *s = chr->opaque;
1629 if (s->len > s->max_size)
1630 s->len = s->max_size;
1634 win_chr_readfile(chr);
1637 static int win_chr_poll(void *opaque)
1639 CharDriverState *chr = opaque;
1640 WinCharState *s = chr->opaque;
1644 ClearCommError(s->hcom, &comerr, &status);
1645 if (status.cbInQue > 0) {
1646 s->len = status.cbInQue;
1647 win_chr_read_poll(chr);
1654 static int qemu_chr_open_win(QemuOpts *opts, CharDriverState **_chr)
1656 const char *filename = qemu_opt_get(opts, "path");
1657 CharDriverState *chr;
1660 chr = g_malloc0(sizeof(CharDriverState));
1661 s = g_malloc0(sizeof(WinCharState));
1663 chr->chr_write = win_chr_write;
1664 chr->chr_close = win_chr_close;
1666 if (win_chr_init(chr, filename) < 0) {
1671 qemu_chr_generic_open(chr);
1677 static int win_chr_pipe_poll(void *opaque)
1679 CharDriverState *chr = opaque;
1680 WinCharState *s = chr->opaque;
1683 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1686 win_chr_read_poll(chr);
1693 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1695 WinCharState *s = chr->opaque;
1703 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1705 fprintf(stderr, "Failed CreateEvent\n");
1708 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1710 fprintf(stderr, "Failed CreateEvent\n");
1714 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1715 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1716 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1718 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1719 if (s->hcom == INVALID_HANDLE_VALUE) {
1720 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1725 ZeroMemory(&ov, sizeof(ov));
1726 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1727 ret = ConnectNamedPipe(s->hcom, &ov);
1729 fprintf(stderr, "Failed ConnectNamedPipe\n");
1733 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1735 fprintf(stderr, "Failed GetOverlappedResult\n");
1737 CloseHandle(ov.hEvent);
1744 CloseHandle(ov.hEvent);
1747 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1756 static int qemu_chr_open_win_pipe(QemuOpts *opts, CharDriverState **_chr)
1758 const char *filename = qemu_opt_get(opts, "path");
1759 CharDriverState *chr;
1762 chr = g_malloc0(sizeof(CharDriverState));
1763 s = g_malloc0(sizeof(WinCharState));
1765 chr->chr_write = win_chr_write;
1766 chr->chr_close = win_chr_close;
1768 if (win_chr_pipe_init(chr, filename) < 0) {
1773 qemu_chr_generic_open(chr);
1779 static int qemu_chr_open_win_file(HANDLE fd_out, CharDriverState **pchr)
1781 CharDriverState *chr;
1784 chr = g_malloc0(sizeof(CharDriverState));
1785 s = g_malloc0(sizeof(WinCharState));
1788 chr->chr_write = win_chr_write;
1789 qemu_chr_generic_open(chr);
1794 static int qemu_chr_open_win_con(QemuOpts *opts, CharDriverState **chr)
1796 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE), chr);
1799 static int qemu_chr_open_win_file_out(QemuOpts *opts, CharDriverState **_chr)
1801 const char *file_out = qemu_opt_get(opts, "path");
1804 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1805 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1806 if (fd_out == INVALID_HANDLE_VALUE) {
1810 return qemu_chr_open_win_file(fd_out, _chr);
1812 #endif /* !_WIN32 */
1814 /***********************************************************/
1815 /* UDP Net console */
1819 uint8_t buf[READ_BUF_LEN];
1825 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1827 NetCharDriver *s = chr->opaque;
1829 return send(s->fd, (const void *)buf, len, 0);
1832 static int udp_chr_read_poll(void *opaque)
1834 CharDriverState *chr = opaque;
1835 NetCharDriver *s = chr->opaque;
1837 s->max_size = qemu_chr_be_can_write(chr);
1839 /* If there were any stray characters in the queue process them
1842 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1843 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
1845 s->max_size = qemu_chr_be_can_write(chr);
1850 static void udp_chr_read(void *opaque)
1852 CharDriverState *chr = opaque;
1853 NetCharDriver *s = chr->opaque;
1855 if (s->max_size == 0)
1857 s->bufcnt = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
1858 s->bufptr = s->bufcnt;
1863 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1864 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
1866 s->max_size = qemu_chr_be_can_write(chr);
1870 static void udp_chr_update_read_handler(CharDriverState *chr)
1872 NetCharDriver *s = chr->opaque;
1875 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
1876 udp_chr_read, NULL, chr);
1880 static void udp_chr_close(CharDriverState *chr)
1882 NetCharDriver *s = chr->opaque;
1884 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
1888 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1891 static int qemu_chr_open_udp(QemuOpts *opts, CharDriverState **_chr)
1893 CharDriverState *chr = NULL;
1894 NetCharDriver *s = NULL;
1898 chr = g_malloc0(sizeof(CharDriverState));
1899 s = g_malloc0(sizeof(NetCharDriver));
1901 fd = inet_dgram_opts(opts);
1903 fprintf(stderr, "inet_dgram_opts failed\n");
1912 chr->chr_write = udp_chr_write;
1913 chr->chr_update_read_handler = udp_chr_update_read_handler;
1914 chr->chr_close = udp_chr_close;
1928 /***********************************************************/
1929 /* TCP Net console */
1941 static void tcp_chr_accept(void *opaque);
1943 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1945 TCPCharDriver *s = chr->opaque;
1947 return send_all(s->fd, buf, len);
1949 /* XXX: indicate an error ? */
1954 static int tcp_chr_read_poll(void *opaque)
1956 CharDriverState *chr = opaque;
1957 TCPCharDriver *s = chr->opaque;
1960 s->max_size = qemu_chr_be_can_write(chr);
1965 #define IAC_BREAK 243
1966 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
1968 uint8_t *buf, int *size)
1970 /* Handle any telnet client's basic IAC options to satisfy char by
1971 * char mode with no echo. All IAC options will be removed from
1972 * the buf and the do_telnetopt variable will be used to track the
1973 * state of the width of the IAC information.
1975 * IAC commands come in sets of 3 bytes with the exception of the
1976 * "IAC BREAK" command and the double IAC.
1982 for (i = 0; i < *size; i++) {
1983 if (s->do_telnetopt > 1) {
1984 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
1985 /* Double IAC means send an IAC */
1989 s->do_telnetopt = 1;
1991 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
1992 /* Handle IAC break commands by sending a serial break */
1993 qemu_chr_event(chr, CHR_EVENT_BREAK);
1998 if (s->do_telnetopt >= 4) {
1999 s->do_telnetopt = 1;
2002 if ((unsigned char)buf[i] == IAC) {
2003 s->do_telnetopt = 2;
2014 static int tcp_get_msgfd(CharDriverState *chr)
2016 TCPCharDriver *s = chr->opaque;
2023 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2025 TCPCharDriver *s = chr->opaque;
2026 struct cmsghdr *cmsg;
2028 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2031 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2032 cmsg->cmsg_level != SOL_SOCKET ||
2033 cmsg->cmsg_type != SCM_RIGHTS)
2036 fd = *((int *)CMSG_DATA(cmsg));
2046 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2048 TCPCharDriver *s = chr->opaque;
2049 struct msghdr msg = { NULL, };
2050 struct iovec iov[1];
2052 struct cmsghdr cmsg;
2053 char control[CMSG_SPACE(sizeof(int))];
2057 iov[0].iov_base = buf;
2058 iov[0].iov_len = len;
2062 msg.msg_control = &msg_control;
2063 msg.msg_controllen = sizeof(msg_control);
2065 ret = recvmsg(s->fd, &msg, 0);
2066 if (ret > 0 && s->is_unix)
2067 unix_process_msgfd(chr, &msg);
2072 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2074 TCPCharDriver *s = chr->opaque;
2075 return qemu_recv(s->fd, buf, len, 0);
2079 static void tcp_chr_read(void *opaque)
2081 CharDriverState *chr = opaque;
2082 TCPCharDriver *s = chr->opaque;
2083 uint8_t buf[READ_BUF_LEN];
2086 if (!s->connected || s->max_size <= 0)
2089 if (len > s->max_size)
2091 size = tcp_chr_recv(chr, (void *)buf, len);
2093 /* connection closed */
2095 if (s->listen_fd >= 0) {
2096 qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2098 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2101 qemu_chr_event(chr, CHR_EVENT_CLOSED);
2102 } else if (size > 0) {
2103 if (s->do_telnetopt)
2104 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2106 qemu_chr_be_write(chr, buf, size);
2111 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2113 return qemu_chr_open_fd(eventfd, eventfd);
2117 static void tcp_chr_connect(void *opaque)
2119 CharDriverState *chr = opaque;
2120 TCPCharDriver *s = chr->opaque;
2123 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2124 tcp_chr_read, NULL, chr);
2125 qemu_chr_generic_open(chr);
2128 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2129 static void tcp_chr_telnet_init(int fd)
2132 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2133 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2134 send(fd, (char *)buf, 3, 0);
2135 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2136 send(fd, (char *)buf, 3, 0);
2137 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2138 send(fd, (char *)buf, 3, 0);
2139 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2140 send(fd, (char *)buf, 3, 0);
2143 static void socket_set_nodelay(int fd)
2146 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2149 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2151 TCPCharDriver *s = chr->opaque;
2155 socket_set_nonblock(fd);
2157 socket_set_nodelay(fd);
2159 qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2160 tcp_chr_connect(chr);
2165 static void tcp_chr_accept(void *opaque)
2167 CharDriverState *chr = opaque;
2168 TCPCharDriver *s = chr->opaque;
2169 struct sockaddr_in saddr;
2171 struct sockaddr_un uaddr;
2173 struct sockaddr *addr;
2180 len = sizeof(uaddr);
2181 addr = (struct sockaddr *)&uaddr;
2185 len = sizeof(saddr);
2186 addr = (struct sockaddr *)&saddr;
2188 fd = qemu_accept(s->listen_fd, addr, &len);
2189 if (fd < 0 && errno != EINTR) {
2191 } else if (fd >= 0) {
2192 if (s->do_telnetopt)
2193 tcp_chr_telnet_init(fd);
2197 if (tcp_chr_add_client(chr, fd) < 0)
2201 static void tcp_chr_close(CharDriverState *chr)
2203 TCPCharDriver *s = chr->opaque;
2205 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2208 if (s->listen_fd >= 0) {
2209 qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2210 closesocket(s->listen_fd);
2213 qemu_chr_event(chr, CHR_EVENT_CLOSED);
2216 static int qemu_chr_open_socket(QemuOpts *opts, CharDriverState **_chr)
2218 CharDriverState *chr = NULL;
2219 TCPCharDriver *s = NULL;
2228 is_listen = qemu_opt_get_bool(opts, "server", 0);
2229 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2230 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2231 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2232 is_unix = qemu_opt_get(opts, "path") != NULL;
2236 chr = g_malloc0(sizeof(CharDriverState));
2237 s = g_malloc0(sizeof(TCPCharDriver));
2241 fd = unix_listen_opts(opts);
2243 fd = unix_connect_opts(opts);
2247 fd = inet_listen_opts(opts, 0);
2249 fd = inet_connect_opts(opts);
2257 if (!is_waitconnect)
2258 socket_set_nonblock(fd);
2264 s->is_unix = is_unix;
2265 s->do_nodelay = do_nodelay && !is_unix;
2268 chr->chr_write = tcp_chr_write;
2269 chr->chr_close = tcp_chr_close;
2270 chr->get_msgfd = tcp_get_msgfd;
2271 chr->chr_add_client = tcp_chr_add_client;
2275 qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2277 s->do_telnetopt = 1;
2282 socket_set_nodelay(fd);
2283 tcp_chr_connect(chr);
2286 /* for "info chardev" monitor command */
2287 chr->filename = g_malloc(256);
2289 snprintf(chr->filename, 256, "unix:%s%s",
2290 qemu_opt_get(opts, "path"),
2291 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2292 } else if (is_telnet) {
2293 snprintf(chr->filename, 256, "telnet:%s:%s%s",
2294 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2295 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2297 snprintf(chr->filename, 256, "tcp:%s:%s%s",
2298 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2299 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2302 if (is_listen && is_waitconnect) {
2303 printf("QEMU waiting for connection on: %s\n",
2305 tcp_chr_accept(chr);
2306 socket_set_nonblock(s->listen_fd);
2320 /***********************************************************/
2321 /* Memory chardev */
2324 size_t outbuf_capacity;
2328 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2330 MemoryDriver *d = chr->opaque;
2332 /* TODO: the QString implementation has the same code, we should
2333 * introduce a generic way to do this in cutils.c */
2334 if (d->outbuf_capacity < d->outbuf_size + len) {
2336 d->outbuf_capacity += len;
2337 d->outbuf_capacity *= 2;
2338 d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
2341 memcpy(d->outbuf + d->outbuf_size, buf, len);
2342 d->outbuf_size += len;
2347 void qemu_chr_init_mem(CharDriverState *chr)
2351 d = g_malloc(sizeof(*d));
2353 d->outbuf_capacity = 4096;
2354 d->outbuf = g_malloc0(d->outbuf_capacity);
2356 memset(chr, 0, sizeof(*chr));
2358 chr->chr_write = mem_chr_write;
2361 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2363 MemoryDriver *d = chr->opaque;
2364 return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2367 /* NOTE: this driver can not be closed with qemu_chr_delete()! */
2368 void qemu_chr_close_mem(CharDriverState *chr)
2370 MemoryDriver *d = chr->opaque;
2373 g_free(chr->opaque);
2375 chr->chr_write = NULL;
2378 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2380 const MemoryDriver *d = chr->opaque;
2381 return d->outbuf_size;
2384 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2386 char host[65], port[33], width[8], height[8];
2391 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1);
2395 if (strstart(filename, "mon:", &p)) {
2397 qemu_opt_set(opts, "mux", "on");
2400 if (strcmp(filename, "null") == 0 ||
2401 strcmp(filename, "pty") == 0 ||
2402 strcmp(filename, "msmouse") == 0 ||
2403 strcmp(filename, "braille") == 0 ||
2404 strcmp(filename, "stdio") == 0) {
2405 qemu_opt_set(opts, "backend", filename);
2408 if (strstart(filename, "vc", &p)) {
2409 qemu_opt_set(opts, "backend", "vc");
2411 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2413 qemu_opt_set(opts, "width", width);
2414 qemu_opt_set(opts, "height", height);
2415 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2417 qemu_opt_set(opts, "cols", width);
2418 qemu_opt_set(opts, "rows", height);
2425 if (strcmp(filename, "con:") == 0) {
2426 qemu_opt_set(opts, "backend", "console");
2429 if (strstart(filename, "COM", NULL)) {
2430 qemu_opt_set(opts, "backend", "serial");
2431 qemu_opt_set(opts, "path", filename);
2434 if (strstart(filename, "file:", &p)) {
2435 qemu_opt_set(opts, "backend", "file");
2436 qemu_opt_set(opts, "path", p);
2439 if (strstart(filename, "pipe:", &p)) {
2440 qemu_opt_set(opts, "backend", "pipe");
2441 qemu_opt_set(opts, "path", p);
2444 if (strstart(filename, "tcp:", &p) ||
2445 strstart(filename, "telnet:", &p)) {
2446 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2448 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2451 qemu_opt_set(opts, "backend", "socket");
2452 qemu_opt_set(opts, "host", host);
2453 qemu_opt_set(opts, "port", port);
2454 if (p[pos] == ',') {
2455 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2458 if (strstart(filename, "telnet:", &p))
2459 qemu_opt_set(opts, "telnet", "on");
2462 if (strstart(filename, "udp:", &p)) {
2463 qemu_opt_set(opts, "backend", "udp");
2464 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2466 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
2470 qemu_opt_set(opts, "host", host);
2471 qemu_opt_set(opts, "port", port);
2472 if (p[pos] == '@') {
2474 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2476 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2480 qemu_opt_set(opts, "localaddr", host);
2481 qemu_opt_set(opts, "localport", port);
2485 if (strstart(filename, "unix:", &p)) {
2486 qemu_opt_set(opts, "backend", "socket");
2487 if (qemu_opts_do_parse(opts, p, "path") != 0)
2491 if (strstart(filename, "/dev/parport", NULL) ||
2492 strstart(filename, "/dev/ppi", NULL)) {
2493 qemu_opt_set(opts, "backend", "parport");
2494 qemu_opt_set(opts, "path", filename);
2497 if (strstart(filename, "/dev/", NULL)) {
2498 qemu_opt_set(opts, "backend", "tty");
2499 qemu_opt_set(opts, "path", filename);
2504 qemu_opts_del(opts);
2508 static const struct {
2510 int (*open)(QemuOpts *opts, CharDriverState **chr);
2511 } backend_table[] = {
2512 { .name = "null", .open = qemu_chr_open_null },
2513 { .name = "socket", .open = qemu_chr_open_socket },
2514 { .name = "udp", .open = qemu_chr_open_udp },
2515 { .name = "msmouse", .open = qemu_chr_open_msmouse },
2516 { .name = "vc", .open = text_console_init },
2518 { .name = "file", .open = qemu_chr_open_win_file_out },
2519 { .name = "pipe", .open = qemu_chr_open_win_pipe },
2520 { .name = "console", .open = qemu_chr_open_win_con },
2521 { .name = "serial", .open = qemu_chr_open_win },
2523 { .name = "file", .open = qemu_chr_open_file_out },
2524 { .name = "pipe", .open = qemu_chr_open_pipe },
2525 { .name = "pty", .open = qemu_chr_open_pty },
2526 { .name = "stdio", .open = qemu_chr_open_stdio },
2528 #ifdef CONFIG_BRLAPI
2529 { .name = "braille", .open = chr_baum_init },
2531 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2532 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
2533 || defined(__FreeBSD_kernel__)
2534 { .name = "tty", .open = qemu_chr_open_tty },
2536 #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) \
2537 || defined(__FreeBSD_kernel__)
2538 { .name = "parport", .open = qemu_chr_open_pp },
2541 { .name = "spicevmc", .open = qemu_chr_open_spice },
2545 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
2546 void (*init)(struct CharDriverState *s))
2548 CharDriverState *chr;
2552 if (qemu_opts_id(opts) == NULL) {
2553 fprintf(stderr, "chardev: no id specified\n");
2557 if (qemu_opt_get(opts, "backend") == NULL) {
2558 fprintf(stderr, "chardev: \"%s\" missing backend\n",
2559 qemu_opts_id(opts));
2562 for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
2563 if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
2566 if (i == ARRAY_SIZE(backend_table)) {
2567 fprintf(stderr, "chardev: backend \"%s\" not found\n",
2568 qemu_opt_get(opts, "backend"));
2572 ret = backend_table[i].open(opts, &chr);
2574 fprintf(stderr, "chardev: opening backend \"%s\" failed: %s\n",
2575 qemu_opt_get(opts, "backend"), strerror(-ret));
2580 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
2582 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2584 if (qemu_opt_get_bool(opts, "mux", 0)) {
2585 CharDriverState *base = chr;
2586 int len = strlen(qemu_opts_id(opts)) + 6;
2587 base->label = g_malloc(len);
2588 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
2589 chr = qemu_chr_open_mux(base);
2590 chr->filename = base->filename;
2591 chr->avail_connections = MAX_MUX;
2592 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2594 chr->avail_connections = 1;
2596 chr->label = g_strdup(qemu_opts_id(opts));
2600 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2603 CharDriverState *chr;
2606 if (strstart(filename, "chardev:", &p)) {
2607 return qemu_chr_find(p);
2610 opts = qemu_chr_parse_compat(label, filename);
2614 chr = qemu_chr_new_from_opts(opts, init);
2615 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
2616 monitor_init(chr, MONITOR_USE_READLINE);
2618 qemu_opts_del(opts);
2622 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
2624 if (chr->chr_set_echo) {
2625 chr->chr_set_echo(chr, echo);
2629 void qemu_chr_fe_open(struct CharDriverState *chr)
2631 if (chr->chr_guest_open) {
2632 chr->chr_guest_open(chr);
2636 void qemu_chr_fe_close(struct CharDriverState *chr)
2638 if (chr->chr_guest_close) {
2639 chr->chr_guest_close(chr);
2643 void qemu_chr_delete(CharDriverState *chr)
2645 QTAILQ_REMOVE(&chardevs, chr, next);
2647 chr->chr_close(chr);
2648 g_free(chr->filename);
2653 static void qemu_chr_qlist_iter(QObject *obj, void *opaque)
2656 Monitor *mon = opaque;
2658 chr_dict = qobject_to_qdict(obj);
2659 monitor_printf(mon, "%s: filename=%s\n", qdict_get_str(chr_dict, "label"),
2660 qdict_get_str(chr_dict, "filename"));
2663 void qemu_chr_info_print(Monitor *mon, const QObject *ret_data)
2665 qlist_iter(qobject_to_qlist(ret_data), qemu_chr_qlist_iter, mon);
2668 void qemu_chr_info(Monitor *mon, QObject **ret_data)
2671 CharDriverState *chr;
2673 chr_list = qlist_new();
2675 QTAILQ_FOREACH(chr, &chardevs, next) {
2676 QObject *obj = qobject_from_jsonf("{ 'label': %s, 'filename': %s }",
2677 chr->label, chr->filename);
2678 qlist_append_obj(chr_list, obj);
2681 *ret_data = QOBJECT(chr_list);
2684 CharDriverState *qemu_chr_find(const char *name)
2686 CharDriverState *chr;
2688 QTAILQ_FOREACH(chr, &chardevs, next) {
2689 if (strcmp(chr->label, name) != 0)