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_write(CharDriverState *s, const uint8_t *buf, int len)
144 return s->chr_write(s, buf, len);
147 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
151 return s->chr_ioctl(s, cmd, arg);
154 int qemu_chr_can_read(CharDriverState *s)
156 if (!s->chr_can_read)
158 return s->chr_can_read(s->handler_opaque);
161 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
163 s->chr_read(s->handler_opaque, buf, len);
166 int qemu_chr_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_printf(CharDriverState *s, const char *fmt, ...)
184 char buf[READ_BUF_LEN];
187 vsnprintf(buf, sizeof(buf), fmt, ap);
188 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
192 void qemu_chr_send_event(CharDriverState *s, int event)
194 if (s->chr_send_event)
195 s->chr_send_event(s, event);
198 void qemu_chr_add_handlers(CharDriverState *s,
199 IOCanReadHandler *fd_can_read,
200 IOReadHandler *fd_read,
201 IOEventHandler *fd_event,
204 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
205 /* chr driver being released. */
206 ++s->avail_connections;
208 s->chr_can_read = fd_can_read;
209 s->chr_read = fd_read;
210 s->chr_event = fd_event;
211 s->handler_opaque = opaque;
212 if (s->chr_update_read_handler)
213 s->chr_update_read_handler(s);
215 /* We're connecting to an already opened device, so let's make sure we
216 also get the open event */
218 qemu_chr_generic_open(s);
222 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
227 static int qemu_chr_open_null(QemuOpts *opts, CharDriverState **_chr)
229 CharDriverState *chr;
231 chr = qemu_mallocz(sizeof(CharDriverState));
232 chr->chr_write = null_chr_write;
238 /* MUX driver for serial I/O splitting */
240 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
241 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
243 IOCanReadHandler *chr_can_read[MAX_MUX];
244 IOReadHandler *chr_read[MAX_MUX];
245 IOEventHandler *chr_event[MAX_MUX];
246 void *ext_opaque[MAX_MUX];
247 CharDriverState *drv;
252 /* Intermediate input buffer allows to catch escape sequences even if the
253 currently active device is not accepting any input - but only until it
255 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
260 int64_t timestamps_start;
264 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
266 MuxDriver *d = chr->opaque;
268 if (!d->timestamps) {
269 ret = d->drv->chr_write(d->drv, buf, len);
274 for (i = 0; i < len; i++) {
280 ti = qemu_get_clock_ms(rt_clock);
281 if (d->timestamps_start == -1)
282 d->timestamps_start = ti;
283 ti -= d->timestamps_start;
285 snprintf(buf1, sizeof(buf1),
286 "[%02d:%02d:%02d.%03d] ",
291 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
294 ret += d->drv->chr_write(d->drv, buf+i, 1);
295 if (buf[i] == '\n') {
303 static const char * const mux_help[] = {
304 "% h print this help\n\r",
305 "% x exit emulator\n\r",
306 "% s save disk data back to file (if -snapshot)\n\r",
307 "% t toggle console timestamps\n\r"
308 "% b send break (magic sysrq)\n\r",
309 "% c switch between console and monitor\n\r",
314 int term_escape_char = 0x01; /* ctrl-a is used for escape */
315 static void mux_print_help(CharDriverState *chr)
318 char ebuf[15] = "Escape-Char";
319 char cbuf[50] = "\n\r";
321 if (term_escape_char > 0 && term_escape_char < 26) {
322 snprintf(cbuf, sizeof(cbuf), "\n\r");
323 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
325 snprintf(cbuf, sizeof(cbuf),
326 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
329 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
330 for (i = 0; mux_help[i] != NULL; i++) {
331 for (j=0; mux_help[i][j] != '\0'; j++) {
332 if (mux_help[i][j] == '%')
333 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
335 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
340 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
342 if (d->chr_event[mux_nr])
343 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
346 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
348 if (d->term_got_escape) {
349 d->term_got_escape = 0;
350 if (ch == term_escape_char)
359 const char *term = "QEMU: Terminated\n\r";
360 chr->chr_write(chr,(uint8_t *)term,strlen(term));
368 qemu_chr_event(chr, CHR_EVENT_BREAK);
371 /* Switch to the next registered device */
372 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
374 if (d->focus >= d->mux_cnt)
376 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
379 d->timestamps = !d->timestamps;
380 d->timestamps_start = -1;
384 } else if (ch == term_escape_char) {
385 d->term_got_escape = 1;
393 static void mux_chr_accept_input(CharDriverState *chr)
395 MuxDriver *d = chr->opaque;
398 while (d->prod[m] != d->cons[m] &&
399 d->chr_can_read[m] &&
400 d->chr_can_read[m](d->ext_opaque[m])) {
401 d->chr_read[m](d->ext_opaque[m],
402 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
406 static int mux_chr_can_read(void *opaque)
408 CharDriverState *chr = opaque;
409 MuxDriver *d = chr->opaque;
412 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
414 if (d->chr_can_read[m])
415 return d->chr_can_read[m](d->ext_opaque[m]);
419 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
421 CharDriverState *chr = opaque;
422 MuxDriver *d = chr->opaque;
426 mux_chr_accept_input (opaque);
428 for(i = 0; i < size; i++)
429 if (mux_proc_byte(chr, d, buf[i])) {
430 if (d->prod[m] == d->cons[m] &&
431 d->chr_can_read[m] &&
432 d->chr_can_read[m](d->ext_opaque[m]))
433 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
435 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
439 static void mux_chr_event(void *opaque, int event)
441 CharDriverState *chr = opaque;
442 MuxDriver *d = chr->opaque;
445 /* Send the event to all registered listeners */
446 for (i = 0; i < d->mux_cnt; i++)
447 mux_chr_send_event(d, i, event);
450 static void mux_chr_update_read_handler(CharDriverState *chr)
452 MuxDriver *d = chr->opaque;
454 if (d->mux_cnt >= MAX_MUX) {
455 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
458 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
459 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
460 d->chr_read[d->mux_cnt] = chr->chr_read;
461 d->chr_event[d->mux_cnt] = chr->chr_event;
462 /* Fix up the real driver with mux routines */
463 if (d->mux_cnt == 0) {
464 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
467 if (d->focus != -1) {
468 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
470 d->focus = d->mux_cnt;
472 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
475 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
477 CharDriverState *chr;
480 chr = qemu_mallocz(sizeof(CharDriverState));
481 d = qemu_mallocz(sizeof(MuxDriver));
486 chr->chr_write = mux_chr_write;
487 chr->chr_update_read_handler = mux_chr_update_read_handler;
488 chr->chr_accept_input = mux_chr_accept_input;
489 /* Frontend guest-open / -close notification is not support with muxes */
490 chr->chr_guest_open = NULL;
491 chr->chr_guest_close = NULL;
493 /* Muxes are always open on creation */
494 qemu_chr_generic_open(chr);
501 int send_all(int fd, const void *buf, int len1)
507 ret = send(fd, buf, len, 0);
509 errno = WSAGetLastError();
510 if (errno != WSAEWOULDBLOCK) {
513 } else if (ret == 0) {
525 int send_all(int fd, const void *_buf, int len1)
528 const uint8_t *buf = _buf;
532 ret = write(fd, buf, len);
534 if (errno != EINTR && errno != EAGAIN)
536 } else if (ret == 0) {
554 #define STDIO_MAX_CLIENTS 1
555 static int stdio_nb_clients = 0;
557 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
559 FDCharDriver *s = chr->opaque;
560 return send_all(s->fd_out, buf, len);
563 static int fd_chr_read_poll(void *opaque)
565 CharDriverState *chr = opaque;
566 FDCharDriver *s = chr->opaque;
568 s->max_size = qemu_chr_can_read(chr);
572 static void fd_chr_read(void *opaque)
574 CharDriverState *chr = opaque;
575 FDCharDriver *s = chr->opaque;
577 uint8_t buf[READ_BUF_LEN];
580 if (len > s->max_size)
584 size = read(s->fd_in, buf, len);
586 /* FD has been closed. Remove it from the active list. */
587 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
588 qemu_chr_event(chr, CHR_EVENT_CLOSED);
592 qemu_chr_read(chr, buf, size);
596 static void fd_chr_update_read_handler(CharDriverState *chr)
598 FDCharDriver *s = chr->opaque;
601 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
603 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
604 fd_chr_read, NULL, chr);
609 static void fd_chr_close(struct CharDriverState *chr)
611 FDCharDriver *s = chr->opaque;
614 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
616 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
621 qemu_chr_event(chr, CHR_EVENT_CLOSED);
624 /* open a character device to a unix fd */
625 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
627 CharDriverState *chr;
630 chr = qemu_mallocz(sizeof(CharDriverState));
631 s = qemu_mallocz(sizeof(FDCharDriver));
635 chr->chr_write = fd_chr_write;
636 chr->chr_update_read_handler = fd_chr_update_read_handler;
637 chr->chr_close = fd_chr_close;
639 qemu_chr_generic_open(chr);
644 static int qemu_chr_open_file_out(QemuOpts *opts, CharDriverState **_chr)
648 TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
649 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
654 *_chr = qemu_chr_open_fd(-1, fd_out);
658 static int qemu_chr_open_pipe(QemuOpts *opts, CharDriverState **_chr)
661 char filename_in[256], filename_out[256];
662 const char *filename = qemu_opt_get(opts, "path");
664 if (filename == NULL) {
665 fprintf(stderr, "chardev: pipe: no filename given\n");
669 snprintf(filename_in, 256, "%s.in", filename);
670 snprintf(filename_out, 256, "%s.out", filename);
671 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
672 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
673 if (fd_in < 0 || fd_out < 0) {
678 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
684 *_chr = qemu_chr_open_fd(fd_in, fd_out);
689 /* for STDIO, we handle the case where several clients use it
692 #define TERM_FIFO_MAX_SIZE 1
694 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
695 static int term_fifo_size;
697 static int stdio_read_poll(void *opaque)
699 CharDriverState *chr = opaque;
701 /* try to flush the queue if needed */
702 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
703 qemu_chr_read(chr, term_fifo, 1);
706 /* see if we can absorb more chars */
707 if (term_fifo_size == 0)
713 static void stdio_read(void *opaque)
717 CharDriverState *chr = opaque;
719 size = read(0, buf, 1);
721 /* stdin has been closed. Remove it from the active list. */
722 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
723 qemu_chr_event(chr, CHR_EVENT_CLOSED);
727 if (qemu_chr_can_read(chr) > 0) {
728 qemu_chr_read(chr, buf, 1);
729 } else if (term_fifo_size == 0) {
730 term_fifo[term_fifo_size++] = buf[0];
735 /* init terminal so that we can grab keys */
736 static struct termios oldtty;
737 static int old_fd0_flags;
738 static bool stdio_allow_signal;
740 static void term_exit(void)
742 tcsetattr (0, TCSANOW, &oldtty);
743 fcntl(0, F_SETFL, old_fd0_flags);
746 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
752 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
753 |INLCR|IGNCR|ICRNL|IXON);
754 tty.c_oflag |= OPOST;
755 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
756 tty.c_cflag &= ~(CSIZE|PARENB);
761 /* if graphical mode, we allow Ctrl-C handling */
762 if (!stdio_allow_signal)
763 tty.c_lflag &= ~ISIG;
765 tcsetattr (0, TCSANOW, &tty);
768 static void qemu_chr_close_stdio(struct CharDriverState *chr)
772 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
776 static int qemu_chr_open_stdio(QemuOpts *opts, CharDriverState **_chr)
778 CharDriverState *chr;
780 if (stdio_nb_clients >= STDIO_MAX_CLIENTS) {
784 if (stdio_nb_clients == 0) {
785 old_fd0_flags = fcntl(0, F_GETFL);
786 tcgetattr (0, &oldtty);
787 fcntl(0, F_SETFL, O_NONBLOCK);
791 chr = qemu_chr_open_fd(0, 1);
792 chr->chr_close = qemu_chr_close_stdio;
793 chr->chr_set_echo = qemu_chr_set_echo_stdio;
794 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
796 stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
797 display_type != DT_NOGRAPHIC);
798 qemu_chr_set_echo(chr, false);
805 /* Once Solaris has openpty(), this is going to be removed. */
806 static int openpty(int *amaster, int *aslave, char *name,
807 struct termios *termp, struct winsize *winp)
810 int mfd = -1, sfd = -1;
812 *amaster = *aslave = -1;
814 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
818 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
821 if ((slave = ptsname(mfd)) == NULL)
824 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
827 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
828 (termp != NULL && tcgetattr(sfd, termp) < 0))
836 ioctl(sfd, TIOCSWINSZ, winp);
847 static void cfmakeraw (struct termios *termios_p)
849 termios_p->c_iflag &=
850 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
851 termios_p->c_oflag &= ~OPOST;
852 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
853 termios_p->c_cflag &= ~(CSIZE|PARENB);
854 termios_p->c_cflag |= CS8;
856 termios_p->c_cc[VMIN] = 0;
857 termios_p->c_cc[VTIME] = 0;
861 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
862 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
863 || defined(__GLIBC__)
873 static void pty_chr_update_read_handler(CharDriverState *chr);
874 static void pty_chr_state(CharDriverState *chr, int connected);
876 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
878 PtyCharDriver *s = chr->opaque;
881 /* guest sends data, check for (re-)connect */
882 pty_chr_update_read_handler(chr);
885 return send_all(s->fd, buf, len);
888 static int pty_chr_read_poll(void *opaque)
890 CharDriverState *chr = opaque;
891 PtyCharDriver *s = chr->opaque;
893 s->read_bytes = qemu_chr_can_read(chr);
894 return s->read_bytes;
897 static void pty_chr_read(void *opaque)
899 CharDriverState *chr = opaque;
900 PtyCharDriver *s = chr->opaque;
902 uint8_t buf[READ_BUF_LEN];
905 if (len > s->read_bytes)
909 size = read(s->fd, buf, len);
910 if ((size == -1 && errno == EIO) ||
912 pty_chr_state(chr, 0);
916 pty_chr_state(chr, 1);
917 qemu_chr_read(chr, buf, size);
921 static void pty_chr_update_read_handler(CharDriverState *chr)
923 PtyCharDriver *s = chr->opaque;
925 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
926 pty_chr_read, NULL, chr);
929 * Short timeout here: just need wait long enougth that qemu makes
930 * it through the poll loop once. When reconnected we want a
931 * short timeout so we notice it almost instantly. Otherwise
932 * read() gives us -EIO instantly, making pty_chr_state() reset the
933 * timeout to the normal (much longer) poll interval before the
936 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 10);
939 static void pty_chr_state(CharDriverState *chr, int connected)
941 PtyCharDriver *s = chr->opaque;
944 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
947 /* (re-)connect poll interval for idle guests: once per second.
948 * We check more frequently in case the guests sends data to
949 * the virtual device linked to our pty. */
950 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 1000);
953 qemu_chr_generic_open(chr);
958 static void pty_chr_timer(void *opaque)
960 struct CharDriverState *chr = opaque;
961 PtyCharDriver *s = chr->opaque;
966 /* If we arrive here without polling being cleared due
967 * read returning -EIO, then we are (re-)connected */
968 pty_chr_state(chr, 1);
973 pty_chr_update_read_handler(chr);
976 static void pty_chr_close(struct CharDriverState *chr)
978 PtyCharDriver *s = chr->opaque;
980 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
982 qemu_del_timer(s->timer);
983 qemu_free_timer(s->timer);
985 qemu_chr_event(chr, CHR_EVENT_CLOSED);
988 static int qemu_chr_open_pty(QemuOpts *opts, CharDriverState **_chr)
990 CharDriverState *chr;
994 #if defined(__OpenBSD__) || defined(__DragonFly__)
995 char pty_name[PATH_MAX];
996 #define q_ptsname(x) pty_name
998 char *pty_name = NULL;
999 #define q_ptsname(x) ptsname(x)
1002 chr = qemu_mallocz(sizeof(CharDriverState));
1003 s = qemu_mallocz(sizeof(PtyCharDriver));
1005 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1009 /* Set raw attributes on the pty. */
1010 tcgetattr(slave_fd, &tty);
1012 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1015 len = strlen(q_ptsname(s->fd)) + 5;
1016 chr->filename = qemu_malloc(len);
1017 snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
1018 qemu_opt_set(opts, "path", q_ptsname(s->fd));
1019 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
1022 chr->chr_write = pty_chr_write;
1023 chr->chr_update_read_handler = pty_chr_update_read_handler;
1024 chr->chr_close = pty_chr_close;
1026 s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr);
1032 static void tty_serial_init(int fd, int speed,
1033 int parity, int data_bits, int stop_bits)
1039 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1040 speed, parity, data_bits, stop_bits);
1042 tcgetattr (fd, &tty);
1044 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1045 speed = speed * 10 / 11;
1062 /* Non-Posix values follow. They may be unsupported on some systems. */
1064 check_speed(115200);
1066 check_speed(230400);
1069 check_speed(460800);
1072 check_speed(500000);
1075 check_speed(576000);
1078 check_speed(921600);
1081 check_speed(1000000);
1084 check_speed(1152000);
1087 check_speed(1500000);
1090 check_speed(2000000);
1093 check_speed(2500000);
1096 check_speed(3000000);
1099 check_speed(3500000);
1102 check_speed(4000000);
1107 cfsetispeed(&tty, spd);
1108 cfsetospeed(&tty, spd);
1110 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1111 |INLCR|IGNCR|ICRNL|IXON);
1112 tty.c_oflag |= OPOST;
1113 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1114 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1135 tty.c_cflag |= PARENB;
1138 tty.c_cflag |= PARENB | PARODD;
1142 tty.c_cflag |= CSTOPB;
1144 tcsetattr (fd, TCSANOW, &tty);
1147 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1149 FDCharDriver *s = chr->opaque;
1152 case CHR_IOCTL_SERIAL_SET_PARAMS:
1154 QEMUSerialSetParams *ssp = arg;
1155 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1156 ssp->data_bits, ssp->stop_bits);
1159 case CHR_IOCTL_SERIAL_SET_BREAK:
1161 int enable = *(int *)arg;
1163 tcsendbreak(s->fd_in, 1);
1166 case CHR_IOCTL_SERIAL_GET_TIOCM:
1169 int *targ = (int *)arg;
1170 ioctl(s->fd_in, TIOCMGET, &sarg);
1172 if (sarg & TIOCM_CTS)
1173 *targ |= CHR_TIOCM_CTS;
1174 if (sarg & TIOCM_CAR)
1175 *targ |= CHR_TIOCM_CAR;
1176 if (sarg & TIOCM_DSR)
1177 *targ |= CHR_TIOCM_DSR;
1178 if (sarg & TIOCM_RI)
1179 *targ |= CHR_TIOCM_RI;
1180 if (sarg & TIOCM_DTR)
1181 *targ |= CHR_TIOCM_DTR;
1182 if (sarg & TIOCM_RTS)
1183 *targ |= CHR_TIOCM_RTS;
1186 case CHR_IOCTL_SERIAL_SET_TIOCM:
1188 int sarg = *(int *)arg;
1190 ioctl(s->fd_in, TIOCMGET, &targ);
1191 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1192 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1193 if (sarg & CHR_TIOCM_CTS)
1195 if (sarg & CHR_TIOCM_CAR)
1197 if (sarg & CHR_TIOCM_DSR)
1199 if (sarg & CHR_TIOCM_RI)
1201 if (sarg & CHR_TIOCM_DTR)
1203 if (sarg & CHR_TIOCM_RTS)
1205 ioctl(s->fd_in, TIOCMSET, &targ);
1214 static void qemu_chr_close_tty(CharDriverState *chr)
1216 FDCharDriver *s = chr->opaque;
1230 static int qemu_chr_open_tty(QemuOpts *opts, CharDriverState **_chr)
1232 const char *filename = qemu_opt_get(opts, "path");
1233 CharDriverState *chr;
1236 TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
1240 tty_serial_init(fd, 115200, 'N', 8, 1);
1241 chr = qemu_chr_open_fd(fd, fd);
1242 chr->chr_ioctl = tty_serial_ioctl;
1243 chr->chr_close = qemu_chr_close_tty;
1248 #else /* ! __linux__ && ! __sun__ */
1249 static int qemu_chr_open_pty(QemuOpts *opts, CharDriverState **_chr)
1253 #endif /* __linux__ || __sun__ */
1255 #if defined(__linux__)
1259 } ParallelCharDriver;
1261 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1263 if (s->mode != mode) {
1265 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1272 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1274 ParallelCharDriver *drv = chr->opaque;
1279 case CHR_IOCTL_PP_READ_DATA:
1280 if (ioctl(fd, PPRDATA, &b) < 0)
1282 *(uint8_t *)arg = b;
1284 case CHR_IOCTL_PP_WRITE_DATA:
1285 b = *(uint8_t *)arg;
1286 if (ioctl(fd, PPWDATA, &b) < 0)
1289 case CHR_IOCTL_PP_READ_CONTROL:
1290 if (ioctl(fd, PPRCONTROL, &b) < 0)
1292 /* Linux gives only the lowest bits, and no way to know data
1293 direction! For better compatibility set the fixed upper
1295 *(uint8_t *)arg = b | 0xc0;
1297 case CHR_IOCTL_PP_WRITE_CONTROL:
1298 b = *(uint8_t *)arg;
1299 if (ioctl(fd, PPWCONTROL, &b) < 0)
1302 case CHR_IOCTL_PP_READ_STATUS:
1303 if (ioctl(fd, PPRSTATUS, &b) < 0)
1305 *(uint8_t *)arg = b;
1307 case CHR_IOCTL_PP_DATA_DIR:
1308 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1311 case CHR_IOCTL_PP_EPP_READ_ADDR:
1312 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1313 struct ParallelIOArg *parg = arg;
1314 int n = read(fd, parg->buffer, parg->count);
1315 if (n != parg->count) {
1320 case CHR_IOCTL_PP_EPP_READ:
1321 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1322 struct ParallelIOArg *parg = arg;
1323 int n = read(fd, parg->buffer, parg->count);
1324 if (n != parg->count) {
1329 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1330 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1331 struct ParallelIOArg *parg = arg;
1332 int n = write(fd, parg->buffer, parg->count);
1333 if (n != parg->count) {
1338 case CHR_IOCTL_PP_EPP_WRITE:
1339 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1340 struct ParallelIOArg *parg = arg;
1341 int n = write(fd, parg->buffer, parg->count);
1342 if (n != parg->count) {
1353 static void pp_close(CharDriverState *chr)
1355 ParallelCharDriver *drv = chr->opaque;
1358 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1359 ioctl(fd, PPRELEASE);
1362 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1365 static int qemu_chr_open_pp(QemuOpts *opts, CharDriverState **_chr)
1367 const char *filename = qemu_opt_get(opts, "path");
1368 CharDriverState *chr;
1369 ParallelCharDriver *drv;
1372 TFR(fd = open(filename, O_RDWR));
1377 if (ioctl(fd, PPCLAIM) < 0) {
1382 drv = qemu_mallocz(sizeof(ParallelCharDriver));
1384 drv->mode = IEEE1284_MODE_COMPAT;
1386 chr = qemu_mallocz(sizeof(CharDriverState));
1387 chr->chr_write = null_chr_write;
1388 chr->chr_ioctl = pp_ioctl;
1389 chr->chr_close = pp_close;
1392 qemu_chr_generic_open(chr);
1397 #endif /* __linux__ */
1399 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1400 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1402 int fd = (int)(intptr_t)chr->opaque;
1406 case CHR_IOCTL_PP_READ_DATA:
1407 if (ioctl(fd, PPIGDATA, &b) < 0)
1409 *(uint8_t *)arg = b;
1411 case CHR_IOCTL_PP_WRITE_DATA:
1412 b = *(uint8_t *)arg;
1413 if (ioctl(fd, PPISDATA, &b) < 0)
1416 case CHR_IOCTL_PP_READ_CONTROL:
1417 if (ioctl(fd, PPIGCTRL, &b) < 0)
1419 *(uint8_t *)arg = b;
1421 case CHR_IOCTL_PP_WRITE_CONTROL:
1422 b = *(uint8_t *)arg;
1423 if (ioctl(fd, PPISCTRL, &b) < 0)
1426 case CHR_IOCTL_PP_READ_STATUS:
1427 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1429 *(uint8_t *)arg = b;
1437 static int qemu_chr_open_pp(QemuOpts *opts, CharDriverState **_chr)
1439 const char *filename = qemu_opt_get(opts, "path");
1440 CharDriverState *chr;
1443 fd = qemu_open(filename, O_RDWR);
1448 chr = qemu_mallocz(sizeof(CharDriverState));
1449 chr->opaque = (void *)(intptr_t)fd;
1450 chr->chr_write = null_chr_write;
1451 chr->chr_ioctl = pp_ioctl;
1462 HANDLE hcom, hrecv, hsend;
1463 OVERLAPPED orecv, osend;
1468 #define NSENDBUF 2048
1469 #define NRECVBUF 2048
1470 #define MAXCONNECT 1
1471 #define NTIMEOUT 5000
1473 static int win_chr_poll(void *opaque);
1474 static int win_chr_pipe_poll(void *opaque);
1476 static void win_chr_close(CharDriverState *chr)
1478 WinCharState *s = chr->opaque;
1481 CloseHandle(s->hsend);
1485 CloseHandle(s->hrecv);
1489 CloseHandle(s->hcom);
1493 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1495 qemu_del_polling_cb(win_chr_poll, chr);
1497 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1500 static int win_chr_init(CharDriverState *chr, const char *filename)
1502 WinCharState *s = chr->opaque;
1504 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1509 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1511 fprintf(stderr, "Failed CreateEvent\n");
1514 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1516 fprintf(stderr, "Failed CreateEvent\n");
1520 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1521 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1522 if (s->hcom == INVALID_HANDLE_VALUE) {
1523 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1528 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1529 fprintf(stderr, "Failed SetupComm\n");
1533 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1534 size = sizeof(COMMCONFIG);
1535 GetDefaultCommConfig(filename, &comcfg, &size);
1536 comcfg.dcb.DCBlength = sizeof(DCB);
1537 CommConfigDialog(filename, NULL, &comcfg);
1539 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1540 fprintf(stderr, "Failed SetCommState\n");
1544 if (!SetCommMask(s->hcom, EV_ERR)) {
1545 fprintf(stderr, "Failed SetCommMask\n");
1549 cto.ReadIntervalTimeout = MAXDWORD;
1550 if (!SetCommTimeouts(s->hcom, &cto)) {
1551 fprintf(stderr, "Failed SetCommTimeouts\n");
1555 if (!ClearCommError(s->hcom, &err, &comstat)) {
1556 fprintf(stderr, "Failed ClearCommError\n");
1559 qemu_add_polling_cb(win_chr_poll, chr);
1567 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1569 WinCharState *s = chr->opaque;
1570 DWORD len, ret, size, err;
1573 ZeroMemory(&s->osend, sizeof(s->osend));
1574 s->osend.hEvent = s->hsend;
1577 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1579 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1581 err = GetLastError();
1582 if (err == ERROR_IO_PENDING) {
1583 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1601 static int win_chr_read_poll(CharDriverState *chr)
1603 WinCharState *s = chr->opaque;
1605 s->max_size = qemu_chr_can_read(chr);
1609 static void win_chr_readfile(CharDriverState *chr)
1611 WinCharState *s = chr->opaque;
1613 uint8_t buf[READ_BUF_LEN];
1616 ZeroMemory(&s->orecv, sizeof(s->orecv));
1617 s->orecv.hEvent = s->hrecv;
1618 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1620 err = GetLastError();
1621 if (err == ERROR_IO_PENDING) {
1622 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1627 qemu_chr_read(chr, buf, size);
1631 static void win_chr_read(CharDriverState *chr)
1633 WinCharState *s = chr->opaque;
1635 if (s->len > s->max_size)
1636 s->len = s->max_size;
1640 win_chr_readfile(chr);
1643 static int win_chr_poll(void *opaque)
1645 CharDriverState *chr = opaque;
1646 WinCharState *s = chr->opaque;
1650 ClearCommError(s->hcom, &comerr, &status);
1651 if (status.cbInQue > 0) {
1652 s->len = status.cbInQue;
1653 win_chr_read_poll(chr);
1660 static int qemu_chr_open_win(QemuOpts *opts, CharDriverState **_chr)
1662 const char *filename = qemu_opt_get(opts, "path");
1663 CharDriverState *chr;
1666 chr = qemu_mallocz(sizeof(CharDriverState));
1667 s = qemu_mallocz(sizeof(WinCharState));
1669 chr->chr_write = win_chr_write;
1670 chr->chr_close = win_chr_close;
1672 if (win_chr_init(chr, filename) < 0) {
1677 qemu_chr_generic_open(chr);
1683 static int win_chr_pipe_poll(void *opaque)
1685 CharDriverState *chr = opaque;
1686 WinCharState *s = chr->opaque;
1689 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1692 win_chr_read_poll(chr);
1699 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1701 WinCharState *s = chr->opaque;
1709 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1711 fprintf(stderr, "Failed CreateEvent\n");
1714 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1716 fprintf(stderr, "Failed CreateEvent\n");
1720 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1721 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1722 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1724 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1725 if (s->hcom == INVALID_HANDLE_VALUE) {
1726 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1731 ZeroMemory(&ov, sizeof(ov));
1732 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1733 ret = ConnectNamedPipe(s->hcom, &ov);
1735 fprintf(stderr, "Failed ConnectNamedPipe\n");
1739 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1741 fprintf(stderr, "Failed GetOverlappedResult\n");
1743 CloseHandle(ov.hEvent);
1750 CloseHandle(ov.hEvent);
1753 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1762 static int qemu_chr_open_win_pipe(QemuOpts *opts, CharDriverState **_chr)
1764 const char *filename = qemu_opt_get(opts, "path");
1765 CharDriverState *chr;
1768 chr = qemu_mallocz(sizeof(CharDriverState));
1769 s = qemu_mallocz(sizeof(WinCharState));
1771 chr->chr_write = win_chr_write;
1772 chr->chr_close = win_chr_close;
1774 if (win_chr_pipe_init(chr, filename) < 0) {
1779 qemu_chr_generic_open(chr);
1785 static int qemu_chr_open_win_file(HANDLE fd_out, CharDriverState **pchr)
1787 CharDriverState *chr;
1790 chr = qemu_mallocz(sizeof(CharDriverState));
1791 s = qemu_mallocz(sizeof(WinCharState));
1794 chr->chr_write = win_chr_write;
1795 qemu_chr_generic_open(chr);
1800 static int qemu_chr_open_win_con(QemuOpts *opts, CharDriverState **chr)
1802 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE), chr);
1805 static int qemu_chr_open_win_file_out(QemuOpts *opts, CharDriverState **_chr)
1807 const char *file_out = qemu_opt_get(opts, "path");
1810 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1811 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1812 if (fd_out == INVALID_HANDLE_VALUE) {
1816 return qemu_chr_open_win_file(fd_out, _chr);
1818 #endif /* !_WIN32 */
1820 /***********************************************************/
1821 /* UDP Net console */
1825 uint8_t buf[READ_BUF_LEN];
1831 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1833 NetCharDriver *s = chr->opaque;
1835 return send(s->fd, (const void *)buf, len, 0);
1838 static int udp_chr_read_poll(void *opaque)
1840 CharDriverState *chr = opaque;
1841 NetCharDriver *s = chr->opaque;
1843 s->max_size = qemu_chr_can_read(chr);
1845 /* If there were any stray characters in the queue process them
1848 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1849 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1851 s->max_size = qemu_chr_can_read(chr);
1856 static void udp_chr_read(void *opaque)
1858 CharDriverState *chr = opaque;
1859 NetCharDriver *s = chr->opaque;
1861 if (s->max_size == 0)
1863 s->bufcnt = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
1864 s->bufptr = s->bufcnt;
1869 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1870 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1872 s->max_size = qemu_chr_can_read(chr);
1876 static void udp_chr_update_read_handler(CharDriverState *chr)
1878 NetCharDriver *s = chr->opaque;
1881 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
1882 udp_chr_read, NULL, chr);
1886 static void udp_chr_close(CharDriverState *chr)
1888 NetCharDriver *s = chr->opaque;
1890 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1894 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1897 static int qemu_chr_open_udp(QemuOpts *opts, CharDriverState **_chr)
1899 CharDriverState *chr = NULL;
1900 NetCharDriver *s = NULL;
1904 chr = qemu_mallocz(sizeof(CharDriverState));
1905 s = qemu_mallocz(sizeof(NetCharDriver));
1907 fd = inet_dgram_opts(opts);
1909 fprintf(stderr, "inet_dgram_opts failed\n");
1918 chr->chr_write = udp_chr_write;
1919 chr->chr_update_read_handler = udp_chr_update_read_handler;
1920 chr->chr_close = udp_chr_close;
1934 /***********************************************************/
1935 /* TCP Net console */
1947 static void tcp_chr_accept(void *opaque);
1949 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1951 TCPCharDriver *s = chr->opaque;
1953 return send_all(s->fd, buf, len);
1955 /* XXX: indicate an error ? */
1960 static int tcp_chr_read_poll(void *opaque)
1962 CharDriverState *chr = opaque;
1963 TCPCharDriver *s = chr->opaque;
1966 s->max_size = qemu_chr_can_read(chr);
1971 #define IAC_BREAK 243
1972 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
1974 uint8_t *buf, int *size)
1976 /* Handle any telnet client's basic IAC options to satisfy char by
1977 * char mode with no echo. All IAC options will be removed from
1978 * the buf and the do_telnetopt variable will be used to track the
1979 * state of the width of the IAC information.
1981 * IAC commands come in sets of 3 bytes with the exception of the
1982 * "IAC BREAK" command and the double IAC.
1988 for (i = 0; i < *size; i++) {
1989 if (s->do_telnetopt > 1) {
1990 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
1991 /* Double IAC means send an IAC */
1995 s->do_telnetopt = 1;
1997 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
1998 /* Handle IAC break commands by sending a serial break */
1999 qemu_chr_event(chr, CHR_EVENT_BREAK);
2004 if (s->do_telnetopt >= 4) {
2005 s->do_telnetopt = 1;
2008 if ((unsigned char)buf[i] == IAC) {
2009 s->do_telnetopt = 2;
2020 static int tcp_get_msgfd(CharDriverState *chr)
2022 TCPCharDriver *s = chr->opaque;
2029 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2031 TCPCharDriver *s = chr->opaque;
2032 struct cmsghdr *cmsg;
2034 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2037 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2038 cmsg->cmsg_level != SOL_SOCKET ||
2039 cmsg->cmsg_type != SCM_RIGHTS)
2042 fd = *((int *)CMSG_DATA(cmsg));
2052 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2054 TCPCharDriver *s = chr->opaque;
2055 struct msghdr msg = { NULL, };
2056 struct iovec iov[1];
2058 struct cmsghdr cmsg;
2059 char control[CMSG_SPACE(sizeof(int))];
2063 iov[0].iov_base = buf;
2064 iov[0].iov_len = len;
2068 msg.msg_control = &msg_control;
2069 msg.msg_controllen = sizeof(msg_control);
2071 ret = recvmsg(s->fd, &msg, 0);
2072 if (ret > 0 && s->is_unix)
2073 unix_process_msgfd(chr, &msg);
2078 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2080 TCPCharDriver *s = chr->opaque;
2081 return qemu_recv(s->fd, buf, len, 0);
2085 static void tcp_chr_read(void *opaque)
2087 CharDriverState *chr = opaque;
2088 TCPCharDriver *s = chr->opaque;
2089 uint8_t buf[READ_BUF_LEN];
2092 if (!s->connected || s->max_size <= 0)
2095 if (len > s->max_size)
2097 size = tcp_chr_recv(chr, (void *)buf, len);
2099 /* connection closed */
2101 if (s->listen_fd >= 0) {
2102 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2104 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2107 qemu_chr_event(chr, CHR_EVENT_CLOSED);
2108 } else if (size > 0) {
2109 if (s->do_telnetopt)
2110 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2112 qemu_chr_read(chr, buf, size);
2117 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2119 return qemu_chr_open_fd(eventfd, eventfd);
2123 static void tcp_chr_connect(void *opaque)
2125 CharDriverState *chr = opaque;
2126 TCPCharDriver *s = chr->opaque;
2129 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2130 tcp_chr_read, NULL, chr);
2131 qemu_chr_generic_open(chr);
2134 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2135 static void tcp_chr_telnet_init(int fd)
2138 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2139 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2140 send(fd, (char *)buf, 3, 0);
2141 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2142 send(fd, (char *)buf, 3, 0);
2143 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2144 send(fd, (char *)buf, 3, 0);
2145 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2146 send(fd, (char *)buf, 3, 0);
2149 static void socket_set_nodelay(int fd)
2152 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2155 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2157 TCPCharDriver *s = chr->opaque;
2161 socket_set_nonblock(fd);
2163 socket_set_nodelay(fd);
2165 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2166 tcp_chr_connect(chr);
2171 static void tcp_chr_accept(void *opaque)
2173 CharDriverState *chr = opaque;
2174 TCPCharDriver *s = chr->opaque;
2175 struct sockaddr_in saddr;
2177 struct sockaddr_un uaddr;
2179 struct sockaddr *addr;
2186 len = sizeof(uaddr);
2187 addr = (struct sockaddr *)&uaddr;
2191 len = sizeof(saddr);
2192 addr = (struct sockaddr *)&saddr;
2194 fd = qemu_accept(s->listen_fd, addr, &len);
2195 if (fd < 0 && errno != EINTR) {
2197 } else if (fd >= 0) {
2198 if (s->do_telnetopt)
2199 tcp_chr_telnet_init(fd);
2203 if (tcp_chr_add_client(chr, fd) < 0)
2207 static void tcp_chr_close(CharDriverState *chr)
2209 TCPCharDriver *s = chr->opaque;
2211 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2214 if (s->listen_fd >= 0) {
2215 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2216 closesocket(s->listen_fd);
2219 qemu_chr_event(chr, CHR_EVENT_CLOSED);
2222 static int qemu_chr_open_socket(QemuOpts *opts, CharDriverState **_chr)
2224 CharDriverState *chr = NULL;
2225 TCPCharDriver *s = NULL;
2234 is_listen = qemu_opt_get_bool(opts, "server", 0);
2235 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2236 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2237 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2238 is_unix = qemu_opt_get(opts, "path") != NULL;
2242 chr = qemu_mallocz(sizeof(CharDriverState));
2243 s = qemu_mallocz(sizeof(TCPCharDriver));
2247 fd = unix_listen_opts(opts);
2249 fd = unix_connect_opts(opts);
2253 fd = inet_listen_opts(opts, 0);
2255 fd = inet_connect_opts(opts);
2263 if (!is_waitconnect)
2264 socket_set_nonblock(fd);
2270 s->is_unix = is_unix;
2271 s->do_nodelay = do_nodelay && !is_unix;
2274 chr->chr_write = tcp_chr_write;
2275 chr->chr_close = tcp_chr_close;
2276 chr->get_msgfd = tcp_get_msgfd;
2277 chr->chr_add_client = tcp_chr_add_client;
2281 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2283 s->do_telnetopt = 1;
2288 socket_set_nodelay(fd);
2289 tcp_chr_connect(chr);
2292 /* for "info chardev" monitor command */
2293 chr->filename = qemu_malloc(256);
2295 snprintf(chr->filename, 256, "unix:%s%s",
2296 qemu_opt_get(opts, "path"),
2297 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2298 } else if (is_telnet) {
2299 snprintf(chr->filename, 256, "telnet:%s:%s%s",
2300 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2301 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2303 snprintf(chr->filename, 256, "tcp:%s:%s%s",
2304 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2305 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2308 if (is_listen && is_waitconnect) {
2309 printf("QEMU waiting for connection on: %s\n",
2311 tcp_chr_accept(chr);
2312 socket_set_nonblock(s->listen_fd);
2326 /***********************************************************/
2327 /* Memory chardev */
2330 size_t outbuf_capacity;
2334 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2336 MemoryDriver *d = chr->opaque;
2338 /* TODO: the QString implementation has the same code, we should
2339 * introduce a generic way to do this in cutils.c */
2340 if (d->outbuf_capacity < d->outbuf_size + len) {
2342 d->outbuf_capacity += len;
2343 d->outbuf_capacity *= 2;
2344 d->outbuf = qemu_realloc(d->outbuf, d->outbuf_capacity);
2347 memcpy(d->outbuf + d->outbuf_size, buf, len);
2348 d->outbuf_size += len;
2353 void qemu_chr_init_mem(CharDriverState *chr)
2357 d = qemu_malloc(sizeof(*d));
2359 d->outbuf_capacity = 4096;
2360 d->outbuf = qemu_mallocz(d->outbuf_capacity);
2362 memset(chr, 0, sizeof(*chr));
2364 chr->chr_write = mem_chr_write;
2367 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2369 MemoryDriver *d = chr->opaque;
2370 return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2373 /* NOTE: this driver can not be closed with qemu_chr_close()! */
2374 void qemu_chr_close_mem(CharDriverState *chr)
2376 MemoryDriver *d = chr->opaque;
2378 qemu_free(d->outbuf);
2379 qemu_free(chr->opaque);
2381 chr->chr_write = NULL;
2384 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2386 const MemoryDriver *d = chr->opaque;
2387 return d->outbuf_size;
2390 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2392 char host[65], port[33], width[8], height[8];
2397 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1);
2401 if (strstart(filename, "mon:", &p)) {
2403 qemu_opt_set(opts, "mux", "on");
2406 if (strcmp(filename, "null") == 0 ||
2407 strcmp(filename, "pty") == 0 ||
2408 strcmp(filename, "msmouse") == 0 ||
2409 strcmp(filename, "braille") == 0 ||
2410 strcmp(filename, "stdio") == 0) {
2411 qemu_opt_set(opts, "backend", filename);
2414 if (strstart(filename, "vc", &p)) {
2415 qemu_opt_set(opts, "backend", "vc");
2417 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2419 qemu_opt_set(opts, "width", width);
2420 qemu_opt_set(opts, "height", height);
2421 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2423 qemu_opt_set(opts, "cols", width);
2424 qemu_opt_set(opts, "rows", height);
2431 if (strcmp(filename, "con:") == 0) {
2432 qemu_opt_set(opts, "backend", "console");
2435 if (strstart(filename, "COM", NULL)) {
2436 qemu_opt_set(opts, "backend", "serial");
2437 qemu_opt_set(opts, "path", filename);
2440 if (strstart(filename, "file:", &p)) {
2441 qemu_opt_set(opts, "backend", "file");
2442 qemu_opt_set(opts, "path", p);
2445 if (strstart(filename, "pipe:", &p)) {
2446 qemu_opt_set(opts, "backend", "pipe");
2447 qemu_opt_set(opts, "path", p);
2450 if (strstart(filename, "tcp:", &p) ||
2451 strstart(filename, "telnet:", &p)) {
2452 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2454 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2457 qemu_opt_set(opts, "backend", "socket");
2458 qemu_opt_set(opts, "host", host);
2459 qemu_opt_set(opts, "port", port);
2460 if (p[pos] == ',') {
2461 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2464 if (strstart(filename, "telnet:", &p))
2465 qemu_opt_set(opts, "telnet", "on");
2468 if (strstart(filename, "udp:", &p)) {
2469 qemu_opt_set(opts, "backend", "udp");
2470 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2472 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
2476 qemu_opt_set(opts, "host", host);
2477 qemu_opt_set(opts, "port", port);
2478 if (p[pos] == '@') {
2480 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2482 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2486 qemu_opt_set(opts, "localaddr", host);
2487 qemu_opt_set(opts, "localport", port);
2491 if (strstart(filename, "unix:", &p)) {
2492 qemu_opt_set(opts, "backend", "socket");
2493 if (qemu_opts_do_parse(opts, p, "path") != 0)
2497 if (strstart(filename, "/dev/parport", NULL) ||
2498 strstart(filename, "/dev/ppi", NULL)) {
2499 qemu_opt_set(opts, "backend", "parport");
2500 qemu_opt_set(opts, "path", filename);
2503 if (strstart(filename, "/dev/", NULL)) {
2504 qemu_opt_set(opts, "backend", "tty");
2505 qemu_opt_set(opts, "path", filename);
2510 qemu_opts_del(opts);
2514 static const struct {
2516 int (*open)(QemuOpts *opts, CharDriverState **chr);
2517 } backend_table[] = {
2518 { .name = "null", .open = qemu_chr_open_null },
2519 { .name = "socket", .open = qemu_chr_open_socket },
2520 { .name = "udp", .open = qemu_chr_open_udp },
2521 { .name = "msmouse", .open = qemu_chr_open_msmouse },
2522 { .name = "vc", .open = text_console_init },
2524 { .name = "file", .open = qemu_chr_open_win_file_out },
2525 { .name = "pipe", .open = qemu_chr_open_win_pipe },
2526 { .name = "console", .open = qemu_chr_open_win_con },
2527 { .name = "serial", .open = qemu_chr_open_win },
2529 { .name = "file", .open = qemu_chr_open_file_out },
2530 { .name = "pipe", .open = qemu_chr_open_pipe },
2531 { .name = "pty", .open = qemu_chr_open_pty },
2532 { .name = "stdio", .open = qemu_chr_open_stdio },
2534 #ifdef CONFIG_BRLAPI
2535 { .name = "braille", .open = chr_baum_init },
2537 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2538 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
2539 || defined(__FreeBSD_kernel__)
2540 { .name = "tty", .open = qemu_chr_open_tty },
2542 #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) \
2543 || defined(__FreeBSD_kernel__)
2544 { .name = "parport", .open = qemu_chr_open_pp },
2547 { .name = "spicevmc", .open = qemu_chr_open_spice },
2551 CharDriverState *qemu_chr_open_opts(QemuOpts *opts,
2552 void (*init)(struct CharDriverState *s))
2554 CharDriverState *chr;
2558 if (qemu_opts_id(opts) == NULL) {
2559 fprintf(stderr, "chardev: no id specified\n");
2563 if (qemu_opt_get(opts, "backend") == NULL) {
2564 fprintf(stderr, "chardev: \"%s\" missing backend\n",
2565 qemu_opts_id(opts));
2568 for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
2569 if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
2572 if (i == ARRAY_SIZE(backend_table)) {
2573 fprintf(stderr, "chardev: backend \"%s\" not found\n",
2574 qemu_opt_get(opts, "backend"));
2578 ret = backend_table[i].open(opts, &chr);
2580 fprintf(stderr, "chardev: opening backend \"%s\" failed: %s\n",
2581 qemu_opt_get(opts, "backend"), strerror(-ret));
2586 chr->filename = qemu_strdup(qemu_opt_get(opts, "backend"));
2588 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2590 if (qemu_opt_get_bool(opts, "mux", 0)) {
2591 CharDriverState *base = chr;
2592 int len = strlen(qemu_opts_id(opts)) + 6;
2593 base->label = qemu_malloc(len);
2594 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
2595 chr = qemu_chr_open_mux(base);
2596 chr->filename = base->filename;
2597 chr->avail_connections = MAX_MUX;
2598 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2600 chr->avail_connections = 1;
2602 chr->label = qemu_strdup(qemu_opts_id(opts));
2606 CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2609 CharDriverState *chr;
2612 if (strstart(filename, "chardev:", &p)) {
2613 return qemu_chr_find(p);
2616 opts = qemu_chr_parse_compat(label, filename);
2620 chr = qemu_chr_open_opts(opts, init);
2621 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
2622 monitor_init(chr, MONITOR_USE_READLINE);
2624 qemu_opts_del(opts);
2628 void qemu_chr_set_echo(struct CharDriverState *chr, bool echo)
2630 if (chr->chr_set_echo) {
2631 chr->chr_set_echo(chr, echo);
2635 void qemu_chr_guest_open(struct CharDriverState *chr)
2637 if (chr->chr_guest_open) {
2638 chr->chr_guest_open(chr);
2642 void qemu_chr_guest_close(struct CharDriverState *chr)
2644 if (chr->chr_guest_close) {
2645 chr->chr_guest_close(chr);
2649 void qemu_chr_close(CharDriverState *chr)
2651 QTAILQ_REMOVE(&chardevs, chr, next);
2653 chr->chr_close(chr);
2654 qemu_free(chr->filename);
2655 qemu_free(chr->label);
2659 static void qemu_chr_qlist_iter(QObject *obj, void *opaque)
2662 Monitor *mon = opaque;
2664 chr_dict = qobject_to_qdict(obj);
2665 monitor_printf(mon, "%s: filename=%s\n", qdict_get_str(chr_dict, "label"),
2666 qdict_get_str(chr_dict, "filename"));
2669 void qemu_chr_info_print(Monitor *mon, const QObject *ret_data)
2671 qlist_iter(qobject_to_qlist(ret_data), qemu_chr_qlist_iter, mon);
2674 void qemu_chr_info(Monitor *mon, QObject **ret_data)
2677 CharDriverState *chr;
2679 chr_list = qlist_new();
2681 QTAILQ_FOREACH(chr, &chardevs, next) {
2682 QObject *obj = qobject_from_jsonf("{ 'label': %s, 'filename': %s }",
2683 chr->label, chr->filename);
2684 qlist_append_obj(chr_list, obj);
2687 *ret_data = QOBJECT(chr_list);
2690 CharDriverState *qemu_chr_find(const char *name)
2692 CharDriverState *chr;
2694 QTAILQ_FOREACH(chr, &chardevs, next) {
2695 if (strcmp(chr->label, name) != 0)