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 void qemu_chr_accept_input(CharDriverState *s)
173 if (s->chr_accept_input)
174 s->chr_accept_input(s);
177 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
179 char buf[READ_BUF_LEN];
182 vsnprintf(buf, sizeof(buf), fmt, ap);
183 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
187 void qemu_chr_send_event(CharDriverState *s, int event)
189 if (s->chr_send_event)
190 s->chr_send_event(s, event);
193 void qemu_chr_add_handlers(CharDriverState *s,
194 IOCanReadHandler *fd_can_read,
195 IOReadHandler *fd_read,
196 IOEventHandler *fd_event,
199 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
200 /* chr driver being released. */
201 ++s->avail_connections;
203 s->chr_can_read = fd_can_read;
204 s->chr_read = fd_read;
205 s->chr_event = fd_event;
206 s->handler_opaque = opaque;
207 if (s->chr_update_read_handler)
208 s->chr_update_read_handler(s);
210 /* We're connecting to an already opened device, so let's make sure we
211 also get the open event */
213 qemu_chr_generic_open(s);
217 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
222 static int qemu_chr_open_null(QemuOpts *opts, CharDriverState **_chr)
224 CharDriverState *chr;
226 chr = qemu_mallocz(sizeof(CharDriverState));
227 chr->chr_write = null_chr_write;
233 /* MUX driver for serial I/O splitting */
235 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
236 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
238 IOCanReadHandler *chr_can_read[MAX_MUX];
239 IOReadHandler *chr_read[MAX_MUX];
240 IOEventHandler *chr_event[MAX_MUX];
241 void *ext_opaque[MAX_MUX];
242 CharDriverState *drv;
247 /* Intermediate input buffer allows to catch escape sequences even if the
248 currently active device is not accepting any input - but only until it
250 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
255 int64_t timestamps_start;
259 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
261 MuxDriver *d = chr->opaque;
263 if (!d->timestamps) {
264 ret = d->drv->chr_write(d->drv, buf, len);
269 for (i = 0; i < len; i++) {
275 ti = qemu_get_clock_ms(rt_clock);
276 if (d->timestamps_start == -1)
277 d->timestamps_start = ti;
278 ti -= d->timestamps_start;
280 snprintf(buf1, sizeof(buf1),
281 "[%02d:%02d:%02d.%03d] ",
286 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
289 ret += d->drv->chr_write(d->drv, buf+i, 1);
290 if (buf[i] == '\n') {
298 static const char * const mux_help[] = {
299 "% h print this help\n\r",
300 "% x exit emulator\n\r",
301 "% s save disk data back to file (if -snapshot)\n\r",
302 "% t toggle console timestamps\n\r"
303 "% b send break (magic sysrq)\n\r",
304 "% c switch between console and monitor\n\r",
309 int term_escape_char = 0x01; /* ctrl-a is used for escape */
310 static void mux_print_help(CharDriverState *chr)
313 char ebuf[15] = "Escape-Char";
314 char cbuf[50] = "\n\r";
316 if (term_escape_char > 0 && term_escape_char < 26) {
317 snprintf(cbuf, sizeof(cbuf), "\n\r");
318 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
320 snprintf(cbuf, sizeof(cbuf),
321 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
324 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
325 for (i = 0; mux_help[i] != NULL; i++) {
326 for (j=0; mux_help[i][j] != '\0'; j++) {
327 if (mux_help[i][j] == '%')
328 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
330 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
335 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
337 if (d->chr_event[mux_nr])
338 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
341 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
343 if (d->term_got_escape) {
344 d->term_got_escape = 0;
345 if (ch == term_escape_char)
354 const char *term = "QEMU: Terminated\n\r";
355 chr->chr_write(chr,(uint8_t *)term,strlen(term));
363 qemu_chr_event(chr, CHR_EVENT_BREAK);
366 /* Switch to the next registered device */
367 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
369 if (d->focus >= d->mux_cnt)
371 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
374 d->timestamps = !d->timestamps;
375 d->timestamps_start = -1;
379 } else if (ch == term_escape_char) {
380 d->term_got_escape = 1;
388 static void mux_chr_accept_input(CharDriverState *chr)
390 MuxDriver *d = chr->opaque;
393 while (d->prod[m] != d->cons[m] &&
394 d->chr_can_read[m] &&
395 d->chr_can_read[m](d->ext_opaque[m])) {
396 d->chr_read[m](d->ext_opaque[m],
397 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
401 static int mux_chr_can_read(void *opaque)
403 CharDriverState *chr = opaque;
404 MuxDriver *d = chr->opaque;
407 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
409 if (d->chr_can_read[m])
410 return d->chr_can_read[m](d->ext_opaque[m]);
414 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
416 CharDriverState *chr = opaque;
417 MuxDriver *d = chr->opaque;
421 mux_chr_accept_input (opaque);
423 for(i = 0; i < size; i++)
424 if (mux_proc_byte(chr, d, buf[i])) {
425 if (d->prod[m] == d->cons[m] &&
426 d->chr_can_read[m] &&
427 d->chr_can_read[m](d->ext_opaque[m]))
428 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
430 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
434 static void mux_chr_event(void *opaque, int event)
436 CharDriverState *chr = opaque;
437 MuxDriver *d = chr->opaque;
440 /* Send the event to all registered listeners */
441 for (i = 0; i < d->mux_cnt; i++)
442 mux_chr_send_event(d, i, event);
445 static void mux_chr_update_read_handler(CharDriverState *chr)
447 MuxDriver *d = chr->opaque;
449 if (d->mux_cnt >= MAX_MUX) {
450 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
453 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
454 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
455 d->chr_read[d->mux_cnt] = chr->chr_read;
456 d->chr_event[d->mux_cnt] = chr->chr_event;
457 /* Fix up the real driver with mux routines */
458 if (d->mux_cnt == 0) {
459 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
462 if (d->focus != -1) {
463 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
465 d->focus = d->mux_cnt;
467 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
470 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
472 CharDriverState *chr;
475 chr = qemu_mallocz(sizeof(CharDriverState));
476 d = qemu_mallocz(sizeof(MuxDriver));
481 chr->chr_write = mux_chr_write;
482 chr->chr_update_read_handler = mux_chr_update_read_handler;
483 chr->chr_accept_input = mux_chr_accept_input;
484 /* Frontend guest-open / -close notification is not support with muxes */
485 chr->chr_guest_open = NULL;
486 chr->chr_guest_close = NULL;
488 /* Muxes are always open on creation */
489 qemu_chr_generic_open(chr);
496 int send_all(int fd, const void *buf, int len1)
502 ret = send(fd, buf, len, 0);
504 errno = WSAGetLastError();
505 if (errno != WSAEWOULDBLOCK) {
508 } else if (ret == 0) {
520 int send_all(int fd, const void *_buf, int len1)
523 const uint8_t *buf = _buf;
527 ret = write(fd, buf, len);
529 if (errno != EINTR && errno != EAGAIN)
531 } else if (ret == 0) {
549 #define STDIO_MAX_CLIENTS 1
550 static int stdio_nb_clients = 0;
552 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
554 FDCharDriver *s = chr->opaque;
555 return send_all(s->fd_out, buf, len);
558 static int fd_chr_read_poll(void *opaque)
560 CharDriverState *chr = opaque;
561 FDCharDriver *s = chr->opaque;
563 s->max_size = qemu_chr_can_read(chr);
567 static void fd_chr_read(void *opaque)
569 CharDriverState *chr = opaque;
570 FDCharDriver *s = chr->opaque;
572 uint8_t buf[READ_BUF_LEN];
575 if (len > s->max_size)
579 size = read(s->fd_in, buf, len);
581 /* FD has been closed. Remove it from the active list. */
582 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
583 qemu_chr_event(chr, CHR_EVENT_CLOSED);
587 qemu_chr_read(chr, buf, size);
591 static void fd_chr_update_read_handler(CharDriverState *chr)
593 FDCharDriver *s = chr->opaque;
596 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
598 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
599 fd_chr_read, NULL, chr);
604 static void fd_chr_close(struct CharDriverState *chr)
606 FDCharDriver *s = chr->opaque;
609 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
611 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
616 qemu_chr_event(chr, CHR_EVENT_CLOSED);
619 /* open a character device to a unix fd */
620 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
622 CharDriverState *chr;
625 chr = qemu_mallocz(sizeof(CharDriverState));
626 s = qemu_mallocz(sizeof(FDCharDriver));
630 chr->chr_write = fd_chr_write;
631 chr->chr_update_read_handler = fd_chr_update_read_handler;
632 chr->chr_close = fd_chr_close;
634 qemu_chr_generic_open(chr);
639 static int qemu_chr_open_file_out(QemuOpts *opts, CharDriverState **_chr)
643 TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
644 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
649 *_chr = qemu_chr_open_fd(-1, fd_out);
653 static int qemu_chr_open_pipe(QemuOpts *opts, CharDriverState **_chr)
656 char filename_in[256], filename_out[256];
657 const char *filename = qemu_opt_get(opts, "path");
659 if (filename == NULL) {
660 fprintf(stderr, "chardev: pipe: no filename given\n");
664 snprintf(filename_in, 256, "%s.in", filename);
665 snprintf(filename_out, 256, "%s.out", filename);
666 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
667 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
668 if (fd_in < 0 || fd_out < 0) {
673 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
679 *_chr = qemu_chr_open_fd(fd_in, fd_out);
684 /* for STDIO, we handle the case where several clients use it
687 #define TERM_FIFO_MAX_SIZE 1
689 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
690 static int term_fifo_size;
692 static int stdio_read_poll(void *opaque)
694 CharDriverState *chr = opaque;
696 /* try to flush the queue if needed */
697 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
698 qemu_chr_read(chr, term_fifo, 1);
701 /* see if we can absorb more chars */
702 if (term_fifo_size == 0)
708 static void stdio_read(void *opaque)
712 CharDriverState *chr = opaque;
714 size = read(0, buf, 1);
716 /* stdin has been closed. Remove it from the active list. */
717 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
718 qemu_chr_event(chr, CHR_EVENT_CLOSED);
722 if (qemu_chr_can_read(chr) > 0) {
723 qemu_chr_read(chr, buf, 1);
724 } else if (term_fifo_size == 0) {
725 term_fifo[term_fifo_size++] = buf[0];
730 /* init terminal so that we can grab keys */
731 static struct termios oldtty;
732 static int old_fd0_flags;
733 static bool stdio_allow_signal;
735 static void term_exit(void)
737 tcsetattr (0, TCSANOW, &oldtty);
738 fcntl(0, F_SETFL, old_fd0_flags);
741 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
747 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
748 |INLCR|IGNCR|ICRNL|IXON);
749 tty.c_oflag |= OPOST;
750 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
751 tty.c_cflag &= ~(CSIZE|PARENB);
756 /* if graphical mode, we allow Ctrl-C handling */
757 if (!stdio_allow_signal)
758 tty.c_lflag &= ~ISIG;
760 tcsetattr (0, TCSANOW, &tty);
763 static void qemu_chr_close_stdio(struct CharDriverState *chr)
767 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
771 static int qemu_chr_open_stdio(QemuOpts *opts, CharDriverState **_chr)
773 CharDriverState *chr;
775 if (stdio_nb_clients >= STDIO_MAX_CLIENTS) {
779 if (stdio_nb_clients == 0) {
780 old_fd0_flags = fcntl(0, F_GETFL);
781 tcgetattr (0, &oldtty);
782 fcntl(0, F_SETFL, O_NONBLOCK);
786 chr = qemu_chr_open_fd(0, 1);
787 chr->chr_close = qemu_chr_close_stdio;
788 chr->chr_set_echo = qemu_chr_set_echo_stdio;
789 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
791 stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
792 display_type != DT_NOGRAPHIC);
793 qemu_chr_set_echo(chr, false);
800 /* Once Solaris has openpty(), this is going to be removed. */
801 static int openpty(int *amaster, int *aslave, char *name,
802 struct termios *termp, struct winsize *winp)
805 int mfd = -1, sfd = -1;
807 *amaster = *aslave = -1;
809 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
813 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
816 if ((slave = ptsname(mfd)) == NULL)
819 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
822 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
823 (termp != NULL && tcgetattr(sfd, termp) < 0))
831 ioctl(sfd, TIOCSWINSZ, winp);
842 static void cfmakeraw (struct termios *termios_p)
844 termios_p->c_iflag &=
845 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
846 termios_p->c_oflag &= ~OPOST;
847 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
848 termios_p->c_cflag &= ~(CSIZE|PARENB);
849 termios_p->c_cflag |= CS8;
851 termios_p->c_cc[VMIN] = 0;
852 termios_p->c_cc[VTIME] = 0;
856 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
857 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
858 || defined(__GLIBC__)
868 static void pty_chr_update_read_handler(CharDriverState *chr);
869 static void pty_chr_state(CharDriverState *chr, int connected);
871 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
873 PtyCharDriver *s = chr->opaque;
876 /* guest sends data, check for (re-)connect */
877 pty_chr_update_read_handler(chr);
880 return send_all(s->fd, buf, len);
883 static int pty_chr_read_poll(void *opaque)
885 CharDriverState *chr = opaque;
886 PtyCharDriver *s = chr->opaque;
888 s->read_bytes = qemu_chr_can_read(chr);
889 return s->read_bytes;
892 static void pty_chr_read(void *opaque)
894 CharDriverState *chr = opaque;
895 PtyCharDriver *s = chr->opaque;
897 uint8_t buf[READ_BUF_LEN];
900 if (len > s->read_bytes)
904 size = read(s->fd, buf, len);
905 if ((size == -1 && errno == EIO) ||
907 pty_chr_state(chr, 0);
911 pty_chr_state(chr, 1);
912 qemu_chr_read(chr, buf, size);
916 static void pty_chr_update_read_handler(CharDriverState *chr)
918 PtyCharDriver *s = chr->opaque;
920 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
921 pty_chr_read, NULL, chr);
924 * Short timeout here: just need wait long enougth that qemu makes
925 * it through the poll loop once. When reconnected we want a
926 * short timeout so we notice it almost instantly. Otherwise
927 * read() gives us -EIO instantly, making pty_chr_state() reset the
928 * timeout to the normal (much longer) poll interval before the
931 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 10);
934 static void pty_chr_state(CharDriverState *chr, int connected)
936 PtyCharDriver *s = chr->opaque;
939 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
942 /* (re-)connect poll interval for idle guests: once per second.
943 * We check more frequently in case the guests sends data to
944 * the virtual device linked to our pty. */
945 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 1000);
948 qemu_chr_generic_open(chr);
953 static void pty_chr_timer(void *opaque)
955 struct CharDriverState *chr = opaque;
956 PtyCharDriver *s = chr->opaque;
961 /* If we arrive here without polling being cleared due
962 * read returning -EIO, then we are (re-)connected */
963 pty_chr_state(chr, 1);
968 pty_chr_update_read_handler(chr);
971 static void pty_chr_close(struct CharDriverState *chr)
973 PtyCharDriver *s = chr->opaque;
975 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
977 qemu_del_timer(s->timer);
978 qemu_free_timer(s->timer);
980 qemu_chr_event(chr, CHR_EVENT_CLOSED);
983 static int qemu_chr_open_pty(QemuOpts *opts, CharDriverState **_chr)
985 CharDriverState *chr;
989 #if defined(__OpenBSD__) || defined(__DragonFly__)
990 char pty_name[PATH_MAX];
991 #define q_ptsname(x) pty_name
993 char *pty_name = NULL;
994 #define q_ptsname(x) ptsname(x)
997 chr = qemu_mallocz(sizeof(CharDriverState));
998 s = qemu_mallocz(sizeof(PtyCharDriver));
1000 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1004 /* Set raw attributes on the pty. */
1005 tcgetattr(slave_fd, &tty);
1007 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1010 len = strlen(q_ptsname(s->fd)) + 5;
1011 chr->filename = qemu_malloc(len);
1012 snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
1013 qemu_opt_set(opts, "path", q_ptsname(s->fd));
1014 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
1017 chr->chr_write = pty_chr_write;
1018 chr->chr_update_read_handler = pty_chr_update_read_handler;
1019 chr->chr_close = pty_chr_close;
1021 s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr);
1027 static void tty_serial_init(int fd, int speed,
1028 int parity, int data_bits, int stop_bits)
1034 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1035 speed, parity, data_bits, stop_bits);
1037 tcgetattr (fd, &tty);
1039 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1040 speed = speed * 10 / 11;
1057 /* Non-Posix values follow. They may be unsupported on some systems. */
1059 check_speed(115200);
1061 check_speed(230400);
1064 check_speed(460800);
1067 check_speed(500000);
1070 check_speed(576000);
1073 check_speed(921600);
1076 check_speed(1000000);
1079 check_speed(1152000);
1082 check_speed(1500000);
1085 check_speed(2000000);
1088 check_speed(2500000);
1091 check_speed(3000000);
1094 check_speed(3500000);
1097 check_speed(4000000);
1102 cfsetispeed(&tty, spd);
1103 cfsetospeed(&tty, spd);
1105 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1106 |INLCR|IGNCR|ICRNL|IXON);
1107 tty.c_oflag |= OPOST;
1108 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1109 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1130 tty.c_cflag |= PARENB;
1133 tty.c_cflag |= PARENB | PARODD;
1137 tty.c_cflag |= CSTOPB;
1139 tcsetattr (fd, TCSANOW, &tty);
1142 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1144 FDCharDriver *s = chr->opaque;
1147 case CHR_IOCTL_SERIAL_SET_PARAMS:
1149 QEMUSerialSetParams *ssp = arg;
1150 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1151 ssp->data_bits, ssp->stop_bits);
1154 case CHR_IOCTL_SERIAL_SET_BREAK:
1156 int enable = *(int *)arg;
1158 tcsendbreak(s->fd_in, 1);
1161 case CHR_IOCTL_SERIAL_GET_TIOCM:
1164 int *targ = (int *)arg;
1165 ioctl(s->fd_in, TIOCMGET, &sarg);
1167 if (sarg & TIOCM_CTS)
1168 *targ |= CHR_TIOCM_CTS;
1169 if (sarg & TIOCM_CAR)
1170 *targ |= CHR_TIOCM_CAR;
1171 if (sarg & TIOCM_DSR)
1172 *targ |= CHR_TIOCM_DSR;
1173 if (sarg & TIOCM_RI)
1174 *targ |= CHR_TIOCM_RI;
1175 if (sarg & TIOCM_DTR)
1176 *targ |= CHR_TIOCM_DTR;
1177 if (sarg & TIOCM_RTS)
1178 *targ |= CHR_TIOCM_RTS;
1181 case CHR_IOCTL_SERIAL_SET_TIOCM:
1183 int sarg = *(int *)arg;
1185 ioctl(s->fd_in, TIOCMGET, &targ);
1186 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1187 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1188 if (sarg & CHR_TIOCM_CTS)
1190 if (sarg & CHR_TIOCM_CAR)
1192 if (sarg & CHR_TIOCM_DSR)
1194 if (sarg & CHR_TIOCM_RI)
1196 if (sarg & CHR_TIOCM_DTR)
1198 if (sarg & CHR_TIOCM_RTS)
1200 ioctl(s->fd_in, TIOCMSET, &targ);
1209 static void qemu_chr_close_tty(CharDriverState *chr)
1211 FDCharDriver *s = chr->opaque;
1225 static int qemu_chr_open_tty(QemuOpts *opts, CharDriverState **_chr)
1227 const char *filename = qemu_opt_get(opts, "path");
1228 CharDriverState *chr;
1231 TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
1235 tty_serial_init(fd, 115200, 'N', 8, 1);
1236 chr = qemu_chr_open_fd(fd, fd);
1237 chr->chr_ioctl = tty_serial_ioctl;
1238 chr->chr_close = qemu_chr_close_tty;
1243 #else /* ! __linux__ && ! __sun__ */
1244 static int qemu_chr_open_pty(QemuOpts *opts, CharDriverState **_chr)
1248 #endif /* __linux__ || __sun__ */
1250 #if defined(__linux__)
1254 } ParallelCharDriver;
1256 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1258 if (s->mode != mode) {
1260 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1267 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1269 ParallelCharDriver *drv = chr->opaque;
1274 case CHR_IOCTL_PP_READ_DATA:
1275 if (ioctl(fd, PPRDATA, &b) < 0)
1277 *(uint8_t *)arg = b;
1279 case CHR_IOCTL_PP_WRITE_DATA:
1280 b = *(uint8_t *)arg;
1281 if (ioctl(fd, PPWDATA, &b) < 0)
1284 case CHR_IOCTL_PP_READ_CONTROL:
1285 if (ioctl(fd, PPRCONTROL, &b) < 0)
1287 /* Linux gives only the lowest bits, and no way to know data
1288 direction! For better compatibility set the fixed upper
1290 *(uint8_t *)arg = b | 0xc0;
1292 case CHR_IOCTL_PP_WRITE_CONTROL:
1293 b = *(uint8_t *)arg;
1294 if (ioctl(fd, PPWCONTROL, &b) < 0)
1297 case CHR_IOCTL_PP_READ_STATUS:
1298 if (ioctl(fd, PPRSTATUS, &b) < 0)
1300 *(uint8_t *)arg = b;
1302 case CHR_IOCTL_PP_DATA_DIR:
1303 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1306 case CHR_IOCTL_PP_EPP_READ_ADDR:
1307 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1308 struct ParallelIOArg *parg = arg;
1309 int n = read(fd, parg->buffer, parg->count);
1310 if (n != parg->count) {
1315 case CHR_IOCTL_PP_EPP_READ:
1316 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1317 struct ParallelIOArg *parg = arg;
1318 int n = read(fd, parg->buffer, parg->count);
1319 if (n != parg->count) {
1324 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1325 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1326 struct ParallelIOArg *parg = arg;
1327 int n = write(fd, parg->buffer, parg->count);
1328 if (n != parg->count) {
1333 case CHR_IOCTL_PP_EPP_WRITE:
1334 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1335 struct ParallelIOArg *parg = arg;
1336 int n = write(fd, parg->buffer, parg->count);
1337 if (n != parg->count) {
1348 static void pp_close(CharDriverState *chr)
1350 ParallelCharDriver *drv = chr->opaque;
1353 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1354 ioctl(fd, PPRELEASE);
1357 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1360 static int qemu_chr_open_pp(QemuOpts *opts, CharDriverState **_chr)
1362 const char *filename = qemu_opt_get(opts, "path");
1363 CharDriverState *chr;
1364 ParallelCharDriver *drv;
1367 TFR(fd = open(filename, O_RDWR));
1372 if (ioctl(fd, PPCLAIM) < 0) {
1377 drv = qemu_mallocz(sizeof(ParallelCharDriver));
1379 drv->mode = IEEE1284_MODE_COMPAT;
1381 chr = qemu_mallocz(sizeof(CharDriverState));
1382 chr->chr_write = null_chr_write;
1383 chr->chr_ioctl = pp_ioctl;
1384 chr->chr_close = pp_close;
1387 qemu_chr_generic_open(chr);
1392 #endif /* __linux__ */
1394 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1395 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1397 int fd = (int)(intptr_t)chr->opaque;
1401 case CHR_IOCTL_PP_READ_DATA:
1402 if (ioctl(fd, PPIGDATA, &b) < 0)
1404 *(uint8_t *)arg = b;
1406 case CHR_IOCTL_PP_WRITE_DATA:
1407 b = *(uint8_t *)arg;
1408 if (ioctl(fd, PPISDATA, &b) < 0)
1411 case CHR_IOCTL_PP_READ_CONTROL:
1412 if (ioctl(fd, PPIGCTRL, &b) < 0)
1414 *(uint8_t *)arg = b;
1416 case CHR_IOCTL_PP_WRITE_CONTROL:
1417 b = *(uint8_t *)arg;
1418 if (ioctl(fd, PPISCTRL, &b) < 0)
1421 case CHR_IOCTL_PP_READ_STATUS:
1422 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1424 *(uint8_t *)arg = b;
1432 static int qemu_chr_open_pp(QemuOpts *opts, CharDriverState **_chr)
1434 const char *filename = qemu_opt_get(opts, "path");
1435 CharDriverState *chr;
1438 fd = qemu_open(filename, O_RDWR);
1443 chr = qemu_mallocz(sizeof(CharDriverState));
1444 chr->opaque = (void *)(intptr_t)fd;
1445 chr->chr_write = null_chr_write;
1446 chr->chr_ioctl = pp_ioctl;
1457 HANDLE hcom, hrecv, hsend;
1458 OVERLAPPED orecv, osend;
1463 #define NSENDBUF 2048
1464 #define NRECVBUF 2048
1465 #define MAXCONNECT 1
1466 #define NTIMEOUT 5000
1468 static int win_chr_poll(void *opaque);
1469 static int win_chr_pipe_poll(void *opaque);
1471 static void win_chr_close(CharDriverState *chr)
1473 WinCharState *s = chr->opaque;
1476 CloseHandle(s->hsend);
1480 CloseHandle(s->hrecv);
1484 CloseHandle(s->hcom);
1488 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1490 qemu_del_polling_cb(win_chr_poll, chr);
1492 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1495 static int win_chr_init(CharDriverState *chr, const char *filename)
1497 WinCharState *s = chr->opaque;
1499 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1504 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1506 fprintf(stderr, "Failed CreateEvent\n");
1509 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1511 fprintf(stderr, "Failed CreateEvent\n");
1515 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1516 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1517 if (s->hcom == INVALID_HANDLE_VALUE) {
1518 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1523 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1524 fprintf(stderr, "Failed SetupComm\n");
1528 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1529 size = sizeof(COMMCONFIG);
1530 GetDefaultCommConfig(filename, &comcfg, &size);
1531 comcfg.dcb.DCBlength = sizeof(DCB);
1532 CommConfigDialog(filename, NULL, &comcfg);
1534 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1535 fprintf(stderr, "Failed SetCommState\n");
1539 if (!SetCommMask(s->hcom, EV_ERR)) {
1540 fprintf(stderr, "Failed SetCommMask\n");
1544 cto.ReadIntervalTimeout = MAXDWORD;
1545 if (!SetCommTimeouts(s->hcom, &cto)) {
1546 fprintf(stderr, "Failed SetCommTimeouts\n");
1550 if (!ClearCommError(s->hcom, &err, &comstat)) {
1551 fprintf(stderr, "Failed ClearCommError\n");
1554 qemu_add_polling_cb(win_chr_poll, chr);
1562 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1564 WinCharState *s = chr->opaque;
1565 DWORD len, ret, size, err;
1568 ZeroMemory(&s->osend, sizeof(s->osend));
1569 s->osend.hEvent = s->hsend;
1572 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1574 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1576 err = GetLastError();
1577 if (err == ERROR_IO_PENDING) {
1578 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1596 static int win_chr_read_poll(CharDriverState *chr)
1598 WinCharState *s = chr->opaque;
1600 s->max_size = qemu_chr_can_read(chr);
1604 static void win_chr_readfile(CharDriverState *chr)
1606 WinCharState *s = chr->opaque;
1608 uint8_t buf[READ_BUF_LEN];
1611 ZeroMemory(&s->orecv, sizeof(s->orecv));
1612 s->orecv.hEvent = s->hrecv;
1613 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1615 err = GetLastError();
1616 if (err == ERROR_IO_PENDING) {
1617 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1622 qemu_chr_read(chr, buf, size);
1626 static void win_chr_read(CharDriverState *chr)
1628 WinCharState *s = chr->opaque;
1630 if (s->len > s->max_size)
1631 s->len = s->max_size;
1635 win_chr_readfile(chr);
1638 static int win_chr_poll(void *opaque)
1640 CharDriverState *chr = opaque;
1641 WinCharState *s = chr->opaque;
1645 ClearCommError(s->hcom, &comerr, &status);
1646 if (status.cbInQue > 0) {
1647 s->len = status.cbInQue;
1648 win_chr_read_poll(chr);
1655 static int qemu_chr_open_win(QemuOpts *opts, CharDriverState **_chr)
1657 const char *filename = qemu_opt_get(opts, "path");
1658 CharDriverState *chr;
1661 chr = qemu_mallocz(sizeof(CharDriverState));
1662 s = qemu_mallocz(sizeof(WinCharState));
1664 chr->chr_write = win_chr_write;
1665 chr->chr_close = win_chr_close;
1667 if (win_chr_init(chr, filename) < 0) {
1672 qemu_chr_generic_open(chr);
1678 static int win_chr_pipe_poll(void *opaque)
1680 CharDriverState *chr = opaque;
1681 WinCharState *s = chr->opaque;
1684 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1687 win_chr_read_poll(chr);
1694 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1696 WinCharState *s = chr->opaque;
1704 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1706 fprintf(stderr, "Failed CreateEvent\n");
1709 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1711 fprintf(stderr, "Failed CreateEvent\n");
1715 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1716 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1717 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1719 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1720 if (s->hcom == INVALID_HANDLE_VALUE) {
1721 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1726 ZeroMemory(&ov, sizeof(ov));
1727 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1728 ret = ConnectNamedPipe(s->hcom, &ov);
1730 fprintf(stderr, "Failed ConnectNamedPipe\n");
1734 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1736 fprintf(stderr, "Failed GetOverlappedResult\n");
1738 CloseHandle(ov.hEvent);
1745 CloseHandle(ov.hEvent);
1748 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1757 static int qemu_chr_open_win_pipe(QemuOpts *opts, CharDriverState **_chr)
1759 const char *filename = qemu_opt_get(opts, "path");
1760 CharDriverState *chr;
1763 chr = qemu_mallocz(sizeof(CharDriverState));
1764 s = qemu_mallocz(sizeof(WinCharState));
1766 chr->chr_write = win_chr_write;
1767 chr->chr_close = win_chr_close;
1769 if (win_chr_pipe_init(chr, filename) < 0) {
1774 qemu_chr_generic_open(chr);
1780 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1782 CharDriverState *chr;
1785 chr = qemu_mallocz(sizeof(CharDriverState));
1786 s = qemu_mallocz(sizeof(WinCharState));
1789 chr->chr_write = win_chr_write;
1790 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_can_read(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_read(chr, &s->buf[s->bufptr], 1);
1845 s->max_size = qemu_chr_can_read(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 = recv(s->fd, (void *)s->buf, sizeof(s->buf), 0);
1858 s->bufptr = s->bufcnt;
1863 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1864 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1866 s->max_size = qemu_chr_can_read(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_handler(s->fd, 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 = qemu_mallocz(sizeof(CharDriverState));
1899 s = qemu_mallocz(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_can_read(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 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_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2098 qemu_set_fd_handler(s->fd, 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_read(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 void tcp_chr_accept(void *opaque)
2151 CharDriverState *chr = opaque;
2152 TCPCharDriver *s = chr->opaque;
2153 struct sockaddr_in saddr;
2155 struct sockaddr_un uaddr;
2157 struct sockaddr *addr;
2164 len = sizeof(uaddr);
2165 addr = (struct sockaddr *)&uaddr;
2169 len = sizeof(saddr);
2170 addr = (struct sockaddr *)&saddr;
2172 fd = qemu_accept(s->listen_fd, addr, &len);
2173 if (fd < 0 && errno != EINTR) {
2175 } else if (fd >= 0) {
2176 if (s->do_telnetopt)
2177 tcp_chr_telnet_init(fd);
2181 socket_set_nonblock(fd);
2183 socket_set_nodelay(fd);
2185 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2186 tcp_chr_connect(chr);
2189 static void tcp_chr_close(CharDriverState *chr)
2191 TCPCharDriver *s = chr->opaque;
2193 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2196 if (s->listen_fd >= 0) {
2197 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2198 closesocket(s->listen_fd);
2201 qemu_chr_event(chr, CHR_EVENT_CLOSED);
2204 static int qemu_chr_open_socket(QemuOpts *opts, CharDriverState **_chr)
2206 CharDriverState *chr = NULL;
2207 TCPCharDriver *s = NULL;
2216 is_listen = qemu_opt_get_bool(opts, "server", 0);
2217 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2218 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2219 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2220 is_unix = qemu_opt_get(opts, "path") != NULL;
2224 chr = qemu_mallocz(sizeof(CharDriverState));
2225 s = qemu_mallocz(sizeof(TCPCharDriver));
2229 fd = unix_listen_opts(opts);
2231 fd = unix_connect_opts(opts);
2235 fd = inet_listen_opts(opts, 0);
2237 fd = inet_connect_opts(opts);
2245 if (!is_waitconnect)
2246 socket_set_nonblock(fd);
2252 s->is_unix = is_unix;
2253 s->do_nodelay = do_nodelay && !is_unix;
2256 chr->chr_write = tcp_chr_write;
2257 chr->chr_close = tcp_chr_close;
2258 chr->get_msgfd = tcp_get_msgfd;
2262 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2264 s->do_telnetopt = 1;
2269 socket_set_nodelay(fd);
2270 tcp_chr_connect(chr);
2273 /* for "info chardev" monitor command */
2274 chr->filename = qemu_malloc(256);
2276 snprintf(chr->filename, 256, "unix:%s%s",
2277 qemu_opt_get(opts, "path"),
2278 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2279 } else if (is_telnet) {
2280 snprintf(chr->filename, 256, "telnet:%s:%s%s",
2281 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2282 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2284 snprintf(chr->filename, 256, "tcp:%s:%s%s",
2285 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2286 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2289 if (is_listen && is_waitconnect) {
2290 printf("QEMU waiting for connection on: %s\n",
2292 tcp_chr_accept(chr);
2293 socket_set_nonblock(s->listen_fd);
2307 /***********************************************************/
2308 /* Memory chardev */
2311 size_t outbuf_capacity;
2315 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2317 MemoryDriver *d = chr->opaque;
2319 /* TODO: the QString implementation has the same code, we should
2320 * introduce a generic way to do this in cutils.c */
2321 if (d->outbuf_capacity < d->outbuf_size + len) {
2323 d->outbuf_capacity += len;
2324 d->outbuf_capacity *= 2;
2325 d->outbuf = qemu_realloc(d->outbuf, d->outbuf_capacity);
2328 memcpy(d->outbuf + d->outbuf_size, buf, len);
2329 d->outbuf_size += len;
2334 void qemu_chr_init_mem(CharDriverState *chr)
2338 d = qemu_malloc(sizeof(*d));
2340 d->outbuf_capacity = 4096;
2341 d->outbuf = qemu_mallocz(d->outbuf_capacity);
2343 memset(chr, 0, sizeof(*chr));
2345 chr->chr_write = mem_chr_write;
2348 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2350 MemoryDriver *d = chr->opaque;
2351 return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2354 /* NOTE: this driver can not be closed with qemu_chr_close()! */
2355 void qemu_chr_close_mem(CharDriverState *chr)
2357 MemoryDriver *d = chr->opaque;
2359 qemu_free(d->outbuf);
2360 qemu_free(chr->opaque);
2362 chr->chr_write = NULL;
2365 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2367 const MemoryDriver *d = chr->opaque;
2368 return d->outbuf_size;
2371 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2373 char host[65], port[33], width[8], height[8];
2378 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1);
2382 if (strstart(filename, "mon:", &p)) {
2384 qemu_opt_set(opts, "mux", "on");
2387 if (strcmp(filename, "null") == 0 ||
2388 strcmp(filename, "pty") == 0 ||
2389 strcmp(filename, "msmouse") == 0 ||
2390 strcmp(filename, "braille") == 0 ||
2391 strcmp(filename, "stdio") == 0) {
2392 qemu_opt_set(opts, "backend", filename);
2395 if (strstart(filename, "vc", &p)) {
2396 qemu_opt_set(opts, "backend", "vc");
2398 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2400 qemu_opt_set(opts, "width", width);
2401 qemu_opt_set(opts, "height", height);
2402 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2404 qemu_opt_set(opts, "cols", width);
2405 qemu_opt_set(opts, "rows", height);
2412 if (strcmp(filename, "con:") == 0) {
2413 qemu_opt_set(opts, "backend", "console");
2416 if (strstart(filename, "COM", NULL)) {
2417 qemu_opt_set(opts, "backend", "serial");
2418 qemu_opt_set(opts, "path", filename);
2421 if (strstart(filename, "file:", &p)) {
2422 qemu_opt_set(opts, "backend", "file");
2423 qemu_opt_set(opts, "path", p);
2426 if (strstart(filename, "pipe:", &p)) {
2427 qemu_opt_set(opts, "backend", "pipe");
2428 qemu_opt_set(opts, "path", p);
2431 if (strstart(filename, "tcp:", &p) ||
2432 strstart(filename, "telnet:", &p)) {
2433 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2435 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2438 qemu_opt_set(opts, "backend", "socket");
2439 qemu_opt_set(opts, "host", host);
2440 qemu_opt_set(opts, "port", port);
2441 if (p[pos] == ',') {
2442 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2445 if (strstart(filename, "telnet:", &p))
2446 qemu_opt_set(opts, "telnet", "on");
2449 if (strstart(filename, "udp:", &p)) {
2450 qemu_opt_set(opts, "backend", "udp");
2451 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2453 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
2457 qemu_opt_set(opts, "host", host);
2458 qemu_opt_set(opts, "port", port);
2459 if (p[pos] == '@') {
2461 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2463 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2467 qemu_opt_set(opts, "localaddr", host);
2468 qemu_opt_set(opts, "localport", port);
2472 if (strstart(filename, "unix:", &p)) {
2473 qemu_opt_set(opts, "backend", "socket");
2474 if (qemu_opts_do_parse(opts, p, "path") != 0)
2478 if (strstart(filename, "/dev/parport", NULL) ||
2479 strstart(filename, "/dev/ppi", NULL)) {
2480 qemu_opt_set(opts, "backend", "parport");
2481 qemu_opt_set(opts, "path", filename);
2484 if (strstart(filename, "/dev/", NULL)) {
2485 qemu_opt_set(opts, "backend", "tty");
2486 qemu_opt_set(opts, "path", filename);
2491 qemu_opts_del(opts);
2495 static const struct {
2497 int (*open)(QemuOpts *opts, CharDriverState **chr);
2498 } backend_table[] = {
2499 { .name = "null", .open = qemu_chr_open_null },
2500 { .name = "socket", .open = qemu_chr_open_socket },
2501 { .name = "udp", .open = qemu_chr_open_udp },
2502 { .name = "msmouse", .open = qemu_chr_open_msmouse },
2503 { .name = "vc", .open = text_console_init },
2505 { .name = "file", .open = qemu_chr_open_win_file_out },
2506 { .name = "pipe", .open = qemu_chr_open_win_pipe },
2507 { .name = "console", .open = qemu_chr_open_win_con },
2508 { .name = "serial", .open = qemu_chr_open_win },
2510 { .name = "file", .open = qemu_chr_open_file_out },
2511 { .name = "pipe", .open = qemu_chr_open_pipe },
2512 { .name = "pty", .open = qemu_chr_open_pty },
2513 { .name = "stdio", .open = qemu_chr_open_stdio },
2515 #ifdef CONFIG_BRLAPI
2516 { .name = "braille", .open = chr_baum_init },
2518 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2519 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
2520 || defined(__FreeBSD_kernel__)
2521 { .name = "tty", .open = qemu_chr_open_tty },
2523 #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) \
2524 || defined(__FreeBSD_kernel__)
2525 { .name = "parport", .open = qemu_chr_open_pp },
2528 { .name = "spicevmc", .open = qemu_chr_open_spice },
2532 CharDriverState *qemu_chr_open_opts(QemuOpts *opts,
2533 void (*init)(struct CharDriverState *s))
2535 CharDriverState *chr;
2539 if (qemu_opts_id(opts) == NULL) {
2540 fprintf(stderr, "chardev: no id specified\n");
2544 if (qemu_opt_get(opts, "backend") == NULL) {
2545 fprintf(stderr, "chardev: \"%s\" missing backend\n",
2546 qemu_opts_id(opts));
2549 for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
2550 if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
2553 if (i == ARRAY_SIZE(backend_table)) {
2554 fprintf(stderr, "chardev: backend \"%s\" not found\n",
2555 qemu_opt_get(opts, "backend"));
2559 ret = backend_table[i].open(opts, &chr);
2561 fprintf(stderr, "chardev: opening backend \"%s\" failed: %s\n",
2562 qemu_opt_get(opts, "backend"), strerror(-ret));
2567 chr->filename = qemu_strdup(qemu_opt_get(opts, "backend"));
2569 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2571 if (qemu_opt_get_bool(opts, "mux", 0)) {
2572 CharDriverState *base = chr;
2573 int len = strlen(qemu_opts_id(opts)) + 6;
2574 base->label = qemu_malloc(len);
2575 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
2576 chr = qemu_chr_open_mux(base);
2577 chr->filename = base->filename;
2578 chr->avail_connections = MAX_MUX;
2579 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2581 chr->avail_connections = 1;
2583 chr->label = qemu_strdup(qemu_opts_id(opts));
2587 CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2590 CharDriverState *chr;
2593 if (strstart(filename, "chardev:", &p)) {
2594 return qemu_chr_find(p);
2597 opts = qemu_chr_parse_compat(label, filename);
2601 chr = qemu_chr_open_opts(opts, init);
2602 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
2603 monitor_init(chr, MONITOR_USE_READLINE);
2605 qemu_opts_del(opts);
2609 void qemu_chr_set_echo(struct CharDriverState *chr, bool echo)
2611 if (chr->chr_set_echo) {
2612 chr->chr_set_echo(chr, echo);
2616 void qemu_chr_guest_open(struct CharDriverState *chr)
2618 if (chr->chr_guest_open) {
2619 chr->chr_guest_open(chr);
2623 void qemu_chr_guest_close(struct CharDriverState *chr)
2625 if (chr->chr_guest_close) {
2626 chr->chr_guest_close(chr);
2630 void qemu_chr_close(CharDriverState *chr)
2632 QTAILQ_REMOVE(&chardevs, chr, next);
2634 chr->chr_close(chr);
2635 qemu_free(chr->filename);
2636 qemu_free(chr->label);
2640 static void qemu_chr_qlist_iter(QObject *obj, void *opaque)
2643 Monitor *mon = opaque;
2645 chr_dict = qobject_to_qdict(obj);
2646 monitor_printf(mon, "%s: filename=%s\n", qdict_get_str(chr_dict, "label"),
2647 qdict_get_str(chr_dict, "filename"));
2650 void qemu_chr_info_print(Monitor *mon, const QObject *ret_data)
2652 qlist_iter(qobject_to_qlist(ret_data), qemu_chr_qlist_iter, mon);
2655 void qemu_chr_info(Monitor *mon, QObject **ret_data)
2658 CharDriverState *chr;
2660 chr_list = qlist_new();
2662 QTAILQ_FOREACH(chr, &chardevs, next) {
2663 QObject *obj = qobject_from_jsonf("{ 'label': %s, 'filename': %s }",
2664 chr->label, chr->filename);
2665 qlist_append_obj(chr_list, obj);
2668 *ret_data = QOBJECT(chr_list);
2671 CharDriverState *qemu_chr_find(const char *name)
2673 CharDriverState *chr;
2675 QTAILQ_FOREACH(chr, &chardevs, next) {
2676 if (strcmp(chr->label, name) != 0)