char: implement get_msgfd in terms of an ioctl
[qemu/aliguori.git] / qemu-char.c
blobd2469e6eb6b21daf3d9c7e3e57040bf252d6f19c
1 /*
2 * QEMU System Emulator
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
22 * THE SOFTWARE.
24 #include "qemu-common.h"
25 #include "net.h"
26 #include "monitor.h"
27 #include "console.h"
28 #include "sysemu.h"
29 #include "qemu-timer.h"
30 #include "qemu-char.h"
31 #include "hw/usb.h"
32 #include "hw/baum.h"
33 #include "hw/msmouse.h"
34 #include "qemu-objects.h"
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <time.h>
39 #include <errno.h>
40 #include <sys/time.h>
41 #include <zlib.h>
43 #ifndef _WIN32
44 #include <sys/times.h>
45 #include <sys/wait.h>
46 #include <termios.h>
47 #include <sys/mman.h>
48 #include <sys/ioctl.h>
49 #include <sys/resource.h>
50 #include <sys/socket.h>
51 #include <netinet/in.h>
52 #include <net/if.h>
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef CONFIG_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
60 #include <libutil.h>
61 #include <dev/ppbus/ppi.h>
62 #include <dev/ppbus/ppbconf.h>
63 #if defined(__GLIBC__)
64 #include <pty.h>
65 #endif
66 #elif defined(__DragonFly__)
67 #include <libutil.h>
68 #include <dev/misc/ppi/ppi.h>
69 #include <bus/ppbus/ppbconf.h>
70 #else
71 #include <util.h>
72 #endif
73 #else
74 #ifdef __linux__
75 #include <pty.h>
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
79 #endif
80 #ifdef __sun__
81 #include <sys/stat.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>
91 #include <net/if.h>
92 #include <syslog.h>
93 #include <stropts.h>
94 #endif
95 #endif
96 #endif
98 #include "qemu_socket.h"
99 #include "ui/qemu-spice.h"
101 #define READ_BUF_LEN 4096
103 int term_escape_char = 0x01; /* ctrl-a is used for escape */
105 /***********************************************************/
106 /* character device */
108 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
109 QTAILQ_HEAD_INITIALIZER(chardevs);
111 static void qemu_chr_event(CharDriverState *s, int event)
113 /* Keep track if the char device is open */
114 switch (event) {
115 case CHR_EVENT_OPENED:
116 s->opened = 1;
117 break;
118 case CHR_EVENT_CLOSED:
119 s->opened = 0;
120 break;
123 if (!s->chr_event)
124 return;
125 s->chr_event(s->handler_opaque, event, NULL);
128 static void qemu_chr_generic_open_bh(void *opaque)
130 CharDriverState *s = opaque;
131 qemu_chr_event(s, CHR_EVENT_OPENED);
132 qemu_bh_delete(s->bh);
133 s->bh = NULL;
136 void qemu_chr_generic_open(CharDriverState *s)
138 if (s->bh == NULL) {
139 s->bh = qemu_bh_new(qemu_chr_generic_open_bh, s);
140 qemu_bh_schedule(s->bh);
144 static uint32_t char_queue_get_avail(CharQueue *q)
146 return sizeof(q->ring) - (q->prod - q->cons);
149 static bool char_queue_get_empty(CharQueue *q)
151 return (q->cons == q->prod);
154 static size_t char_queue_write(CharQueue *q, const void *data, size_t size)
156 const uint8_t *ptr = data;
157 size_t i;
159 for (i = 0; i < size; i++) {
160 if (char_queue_get_avail(q) == 0) {
161 break;
164 q->ring[q->prod % sizeof(q->ring)] = ptr[i];
165 q->prod++;
168 return i;
171 static size_t char_queue_read(CharQueue *q, void *data, size_t size)
173 uint8_t *ptr = data;
174 size_t i;
176 for (i = 0; i < size; i++) {
177 if (char_queue_get_empty(q)) {
178 break;
181 ptr[i] = q->ring[q->cons % sizeof(q->ring)];
182 q->cons++;
185 return i;
188 static void qemu_chr_flush_fe_tx(CharDriverState *s)
190 uint8_t buf[MAX_CHAR_QUEUE_RING];
191 int len;
193 /* Don't use polling queue if new style handlers are registered */
194 if (s->be_read || s->be_write) {
195 return;
198 /* Drain the queue into a flat buffer */
199 len = char_queue_read(&s->fe_tx, buf, sizeof(buf));
201 s->chr_write(s, buf, len);
203 /* We drop unwritten data until we have backend flow control */
206 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
208 int ret;
209 bool is_empty;
211 assert(s->fe_opened > 0);
213 is_empty = char_queue_get_empty(&s->fe_tx);
215 ret = char_queue_write(&s->fe_tx, buf, len);
217 /* If the queue was empty, and now it's not, generate a read edge
218 * event for the backend. */
219 if (is_empty && !char_queue_get_empty(&s->fe_tx)) {
220 if (s->be_read) {
221 s->be_read(s->opaque);
225 qemu_chr_flush_fe_tx(s);
227 return ret;
230 int qemu_chr_fe_read(CharDriverState *s, uint8_t *buf, int len)
232 bool is_full;
233 int ret;
235 assert(s->fe_opened > 0);
237 is_full = (char_queue_get_avail(&s->be_tx) == 0);
239 ret = char_queue_read(&s->be_tx, buf, len);
241 /* If the queue was empty, and now its not, generate a write edge
242 * event for the backend. */
243 if (is_full && char_queue_get_avail(&s->be_tx)) {
244 if (s->be_write) {
245 s->be_write(s->opaque);
249 return ret;
252 void qemu_chr_fe_set_handlers(CharDriverState *s,
253 IOHandler *chr_read,
254 IOHandler *chr_write,
255 IOEventHandler *chr_event,
256 void *opaque)
258 assert(s->fe_opened > 0);
260 if (!opaque && !chr_read && !chr_write && !chr_event) {
261 /* chr driver being released. */
262 ++s->avail_connections;
264 s->fe_read = chr_read;
265 s->fe_write = chr_write;
266 s->chr_event = chr_event;
267 s->handler_opaque = opaque;
269 /* We're connecting to an already opened device, so let's make sure we
270 also get the open event */
271 if (s->opened) {
272 qemu_chr_generic_open(s);
276 int qemu_chr_be_can_write(CharDriverState *s)
278 /* Try to flush any queued data before returning how much data we can
279 * accept. */
280 return char_queue_get_avail(&s->be_tx);
283 int qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
285 int ret;
286 bool is_empty;
288 is_empty = char_queue_get_empty(&s->be_tx);
290 ret = char_queue_write(&s->be_tx, buf, len);
292 /* If the queue was empty, and now it's not, trigger a read edge
293 * event. */
294 if (is_empty && !char_queue_get_empty(&s->be_tx)) {
295 if (s->fe_read) {
296 s->fe_read(s->handler_opaque);
300 return ret;
303 int qemu_chr_be_read(CharDriverState *s, uint8_t *buf, int len)
305 bool is_full;
306 int ret;
308 is_full = (char_queue_get_avail(&s->fe_tx) == 0);
310 ret = char_queue_read(&s->fe_tx, buf, len);
312 /* If the queue was full, and now it's not, trigger an write edge
313 * event. */
314 if (is_full && char_queue_get_avail(&s->fe_tx)) {
315 if (s->fe_write) {
316 s->fe_write(s->handler_opaque);
320 return ret;
323 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
325 if (!s->chr_ioctl)
326 return -ENOTSUP;
327 return s->chr_ioctl(s->opaque, cmd, arg);
330 int qemu_chr_add_client(CharDriverState *s, int fd)
332 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
335 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
337 char buf[READ_BUF_LEN];
338 va_list ap;
339 va_start(ap, fmt);
340 vsnprintf(buf, sizeof(buf), fmt, ap);
341 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
342 va_end(ap);
345 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
347 return len;
350 static int qemu_chr_open_null(QemuOpts *opts, CharDriverState **_chr)
352 CharDriverState *chr;
354 chr = qemu_mallocz(sizeof(CharDriverState));
355 chr->chr_write = null_chr_write;
357 *_chr= chr;
358 return 0;
361 #ifdef _WIN32
362 int send_all(int fd, const void *buf, int len1)
364 int ret, len;
366 len = len1;
367 while (len > 0) {
368 ret = send(fd, buf, len, 0);
369 if (ret < 0) {
370 errno = WSAGetLastError();
371 if (errno != WSAEWOULDBLOCK) {
372 return -1;
374 } else if (ret == 0) {
375 break;
376 } else {
377 buf += ret;
378 len -= ret;
381 return len1 - len;
384 #else
386 int send_all(int fd, const void *_buf, int len1)
388 int ret, len;
389 const uint8_t *buf = _buf;
391 len = len1;
392 while (len > 0) {
393 ret = write(fd, buf, len);
394 if (ret < 0) {
395 if (errno != EINTR && errno != EAGAIN)
396 return -1;
397 } else if (ret == 0) {
398 break;
399 } else {
400 buf += ret;
401 len -= ret;
404 return len1 - len;
406 #endif /* !_WIN32 */
408 #ifndef _WIN32
410 typedef struct {
411 int fd_in, fd_out;
412 int max_size;
413 } FDCharDriver;
415 #define STDIO_MAX_CLIENTS 1
416 static int stdio_nb_clients = 0;
418 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
420 FDCharDriver *s = chr->opaque;
421 return send_all(s->fd_out, buf, len);
424 static int fd_chr_read_poll(void *opaque)
426 CharDriverState *chr = opaque;
427 FDCharDriver *s = chr->opaque;
429 s->max_size = qemu_chr_be_can_write(chr);
430 return s->max_size;
433 static void fd_chr_read(void *opaque)
435 CharDriverState *chr = opaque;
436 FDCharDriver *s = chr->opaque;
437 int size, len;
438 uint8_t buf[READ_BUF_LEN];
440 len = sizeof(buf);
441 if (len > s->max_size)
442 len = s->max_size;
443 if (len == 0)
444 return;
445 size = read(s->fd_in, buf, len);
446 if (size == 0) {
447 /* FD has been closed. Remove it from the active list. */
448 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
449 qemu_chr_event(chr, CHR_EVENT_CLOSED);
450 return;
452 if (size > 0) {
453 qemu_chr_be_write(chr, buf, size);
457 static void fd_chr_update_read_handler(CharDriverState *chr)
459 FDCharDriver *s = chr->opaque;
461 if (s->fd_in >= 0) {
462 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
463 } else {
464 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
465 fd_chr_read, NULL, chr);
470 static void fd_chr_close(struct CharDriverState *chr)
472 FDCharDriver *s = chr->opaque;
474 if (s->fd_in >= 0) {
475 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
476 } else {
477 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
481 qemu_free(s);
482 qemu_chr_event(chr, CHR_EVENT_CLOSED);
485 /* open a character device to a unix fd */
486 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
488 CharDriverState *chr;
489 FDCharDriver *s;
491 chr = qemu_mallocz(sizeof(CharDriverState));
492 s = qemu_mallocz(sizeof(FDCharDriver));
493 s->fd_in = fd_in;
494 s->fd_out = fd_out;
495 chr->opaque = s;
496 chr->chr_write = fd_chr_write;
497 chr->chr_update_read_handler = fd_chr_update_read_handler;
498 chr->chr_close = fd_chr_close;
500 qemu_chr_generic_open(chr);
502 return chr;
505 static int qemu_chr_open_file_out(QemuOpts *opts, CharDriverState **_chr)
507 int fd_out;
509 TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
510 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
511 if (fd_out < 0) {
512 return -errno;
515 *_chr = qemu_chr_open_fd(-1, fd_out);
516 return 0;
519 static int qemu_chr_open_pipe(QemuOpts *opts, CharDriverState **_chr)
521 int fd_in, fd_out;
522 char filename_in[256], filename_out[256];
523 const char *filename = qemu_opt_get(opts, "path");
525 if (filename == NULL) {
526 fprintf(stderr, "chardev: pipe: no filename given\n");
527 return -EINVAL;
530 snprintf(filename_in, 256, "%s.in", filename);
531 snprintf(filename_out, 256, "%s.out", filename);
532 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
533 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
534 if (fd_in < 0 || fd_out < 0) {
535 if (fd_in >= 0)
536 close(fd_in);
537 if (fd_out >= 0)
538 close(fd_out);
539 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
540 if (fd_in < 0) {
541 return -errno;
545 *_chr = qemu_chr_open_fd(fd_in, fd_out);
546 return 0;
550 /* for STDIO, we handle the case where several clients use it
551 (nographic mode) */
553 #define TERM_FIFO_MAX_SIZE 1
555 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
556 static int term_fifo_size;
558 static int stdio_read_poll(void *opaque)
560 CharDriverState *chr = opaque;
562 /* try to flush the queue if needed */
563 if (term_fifo_size != 0 && qemu_chr_be_can_write(chr) > 0) {
564 qemu_chr_be_write(chr, term_fifo, 1);
565 term_fifo_size = 0;
567 /* see if we can absorb more chars */
568 if (term_fifo_size == 0)
569 return 1;
570 else
571 return 0;
574 static void stdio_read(void *opaque)
576 int size;
577 uint8_t buf[1];
578 CharDriverState *chr = opaque;
580 size = read(0, buf, 1);
581 if (size == 0) {
582 /* stdin has been closed. Remove it from the active list. */
583 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
584 qemu_chr_event(chr, CHR_EVENT_CLOSED);
585 return;
587 if (size > 0) {
588 if (qemu_chr_be_can_write(chr) > 0) {
589 qemu_chr_be_write(chr, buf, 1);
590 } else if (term_fifo_size == 0) {
591 term_fifo[term_fifo_size++] = buf[0];
596 /* init terminal so that we can grab keys */
597 static struct termios oldtty;
598 static int old_fd0_flags;
599 static bool stdio_allow_signal;
601 static void term_exit(void)
603 tcsetattr (0, TCSANOW, &oldtty);
604 fcntl(0, F_SETFL, old_fd0_flags);
607 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
609 struct termios tty;
611 tty = oldtty;
612 if (!echo) {
613 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
614 |INLCR|IGNCR|ICRNL|IXON);
615 tty.c_oflag |= OPOST;
616 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
617 tty.c_cflag &= ~(CSIZE|PARENB);
618 tty.c_cflag |= CS8;
619 tty.c_cc[VMIN] = 1;
620 tty.c_cc[VTIME] = 0;
622 /* if graphical mode, we allow Ctrl-C handling */
623 if (!stdio_allow_signal)
624 tty.c_lflag &= ~ISIG;
626 tcsetattr (0, TCSANOW, &tty);
629 static void qemu_chr_close_stdio(struct CharDriverState *chr)
631 term_exit();
632 stdio_nb_clients--;
633 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
634 fd_chr_close(chr);
637 static int qemu_chr_open_stdio(QemuOpts *opts, CharDriverState **_chr)
639 CharDriverState *chr;
641 if (stdio_nb_clients >= STDIO_MAX_CLIENTS) {
642 return -EBUSY;
645 if (stdio_nb_clients == 0) {
646 old_fd0_flags = fcntl(0, F_GETFL);
647 tcgetattr (0, &oldtty);
648 fcntl(0, F_SETFL, O_NONBLOCK);
649 atexit(term_exit);
652 chr = qemu_chr_open_fd(0, 1);
653 chr->chr_close = qemu_chr_close_stdio;
654 chr->chr_set_echo = qemu_chr_set_echo_stdio;
655 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
656 stdio_nb_clients++;
657 stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
658 display_type != DT_NOGRAPHIC);
659 qemu_chr_set_echo(chr, false);
661 *_chr = chr;
662 return 0;
665 #ifdef __sun__
666 /* Once Solaris has openpty(), this is going to be removed. */
667 static int openpty(int *amaster, int *aslave, char *name,
668 struct termios *termp, struct winsize *winp)
670 const char *slave;
671 int mfd = -1, sfd = -1;
673 *amaster = *aslave = -1;
675 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
676 if (mfd < 0)
677 goto err;
679 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
680 goto err;
682 if ((slave = ptsname(mfd)) == NULL)
683 goto err;
685 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
686 goto err;
688 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
689 (termp != NULL && tcgetattr(sfd, termp) < 0))
690 goto err;
692 if (amaster)
693 *amaster = mfd;
694 if (aslave)
695 *aslave = sfd;
696 if (winp)
697 ioctl(sfd, TIOCSWINSZ, winp);
699 return 0;
701 err:
702 if (sfd != -1)
703 close(sfd);
704 close(mfd);
705 return -1;
708 static void cfmakeraw (struct termios *termios_p)
710 termios_p->c_iflag &=
711 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
712 termios_p->c_oflag &= ~OPOST;
713 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
714 termios_p->c_cflag &= ~(CSIZE|PARENB);
715 termios_p->c_cflag |= CS8;
717 termios_p->c_cc[VMIN] = 0;
718 termios_p->c_cc[VTIME] = 0;
720 #endif
722 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
723 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
724 || defined(__GLIBC__)
726 typedef struct {
727 int fd;
728 int connected;
729 int polling;
730 int read_bytes;
731 QEMUTimer *timer;
732 } PtyCharDriver;
734 static void pty_chr_update_read_handler(CharDriverState *chr);
735 static void pty_chr_state(CharDriverState *chr, int connected);
737 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
739 PtyCharDriver *s = chr->opaque;
741 if (!s->connected) {
742 /* guest sends data, check for (re-)connect */
743 pty_chr_update_read_handler(chr);
744 return 0;
746 return send_all(s->fd, buf, len);
749 static int pty_chr_read_poll(void *opaque)
751 CharDriverState *chr = opaque;
752 PtyCharDriver *s = chr->opaque;
754 s->read_bytes = qemu_chr_be_can_write(chr);
755 return s->read_bytes;
758 static void pty_chr_read(void *opaque)
760 CharDriverState *chr = opaque;
761 PtyCharDriver *s = chr->opaque;
762 int size, len;
763 uint8_t buf[READ_BUF_LEN];
765 len = sizeof(buf);
766 if (len > s->read_bytes)
767 len = s->read_bytes;
768 if (len == 0)
769 return;
770 size = read(s->fd, buf, len);
771 if ((size == -1 && errno == EIO) ||
772 (size == 0)) {
773 pty_chr_state(chr, 0);
774 return;
776 if (size > 0) {
777 pty_chr_state(chr, 1);
778 qemu_chr_be_write(chr, buf, size);
782 static void pty_chr_update_read_handler(CharDriverState *chr)
784 PtyCharDriver *s = chr->opaque;
786 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
787 pty_chr_read, NULL, chr);
788 s->polling = 1;
790 * Short timeout here: just need wait long enougth that qemu makes
791 * it through the poll loop once. When reconnected we want a
792 * short timeout so we notice it almost instantly. Otherwise
793 * read() gives us -EIO instantly, making pty_chr_state() reset the
794 * timeout to the normal (much longer) poll interval before the
795 * timer triggers.
797 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 10);
800 static void pty_chr_state(CharDriverState *chr, int connected)
802 PtyCharDriver *s = chr->opaque;
804 if (!connected) {
805 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
806 s->connected = 0;
807 s->polling = 0;
808 /* (re-)connect poll interval for idle guests: once per second.
809 * We check more frequently in case the guests sends data to
810 * the virtual device linked to our pty. */
811 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 1000);
812 } else {
813 if (!s->connected)
814 qemu_chr_generic_open(chr);
815 s->connected = 1;
819 static void pty_chr_timer(void *opaque)
821 struct CharDriverState *chr = opaque;
822 PtyCharDriver *s = chr->opaque;
824 if (s->connected)
825 return;
826 if (s->polling) {
827 /* If we arrive here without polling being cleared due
828 * read returning -EIO, then we are (re-)connected */
829 pty_chr_state(chr, 1);
830 return;
833 /* Next poll ... */
834 pty_chr_update_read_handler(chr);
837 static void pty_chr_close(struct CharDriverState *chr)
839 PtyCharDriver *s = chr->opaque;
841 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
842 close(s->fd);
843 qemu_del_timer(s->timer);
844 qemu_free_timer(s->timer);
845 qemu_free(s);
846 qemu_chr_event(chr, CHR_EVENT_CLOSED);
849 static int qemu_chr_open_pty(QemuOpts *opts, CharDriverState **_chr)
851 CharDriverState *chr;
852 PtyCharDriver *s;
853 struct termios tty;
854 int slave_fd, len;
855 #if defined(__OpenBSD__) || defined(__DragonFly__)
856 char pty_name[PATH_MAX];
857 #define q_ptsname(x) pty_name
858 #else
859 char *pty_name = NULL;
860 #define q_ptsname(x) ptsname(x)
861 #endif
863 chr = qemu_mallocz(sizeof(CharDriverState));
864 s = qemu_mallocz(sizeof(PtyCharDriver));
866 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
867 return -errno;
870 /* Set raw attributes on the pty. */
871 tcgetattr(slave_fd, &tty);
872 cfmakeraw(&tty);
873 tcsetattr(slave_fd, TCSAFLUSH, &tty);
874 close(slave_fd);
876 len = strlen(q_ptsname(s->fd)) + 5;
877 chr->filename = qemu_malloc(len);
878 snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
879 qemu_opt_set(opts, "path", q_ptsname(s->fd));
880 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
882 chr->opaque = s;
883 chr->chr_write = pty_chr_write;
884 chr->chr_update_read_handler = pty_chr_update_read_handler;
885 chr->chr_close = pty_chr_close;
887 s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr);
889 *_chr = chr;
890 return 0;
893 static void tty_serial_init(int fd, int speed,
894 int parity, int data_bits, int stop_bits)
896 struct termios tty;
897 speed_t spd;
899 #if 0
900 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
901 speed, parity, data_bits, stop_bits);
902 #endif
903 tcgetattr (fd, &tty);
905 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
906 speed = speed * 10 / 11;
907 do {
908 check_speed(50);
909 check_speed(75);
910 check_speed(110);
911 check_speed(134);
912 check_speed(150);
913 check_speed(200);
914 check_speed(300);
915 check_speed(600);
916 check_speed(1200);
917 check_speed(1800);
918 check_speed(2400);
919 check_speed(4800);
920 check_speed(9600);
921 check_speed(19200);
922 check_speed(38400);
923 /* Non-Posix values follow. They may be unsupported on some systems. */
924 check_speed(57600);
925 check_speed(115200);
926 #ifdef B230400
927 check_speed(230400);
928 #endif
929 #ifdef B460800
930 check_speed(460800);
931 #endif
932 #ifdef B500000
933 check_speed(500000);
934 #endif
935 #ifdef B576000
936 check_speed(576000);
937 #endif
938 #ifdef B921600
939 check_speed(921600);
940 #endif
941 #ifdef B1000000
942 check_speed(1000000);
943 #endif
944 #ifdef B1152000
945 check_speed(1152000);
946 #endif
947 #ifdef B1500000
948 check_speed(1500000);
949 #endif
950 #ifdef B2000000
951 check_speed(2000000);
952 #endif
953 #ifdef B2500000
954 check_speed(2500000);
955 #endif
956 #ifdef B3000000
957 check_speed(3000000);
958 #endif
959 #ifdef B3500000
960 check_speed(3500000);
961 #endif
962 #ifdef B4000000
963 check_speed(4000000);
964 #endif
965 spd = B115200;
966 } while (0);
968 cfsetispeed(&tty, spd);
969 cfsetospeed(&tty, spd);
971 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
972 |INLCR|IGNCR|ICRNL|IXON);
973 tty.c_oflag |= OPOST;
974 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
975 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
976 switch(data_bits) {
977 default:
978 case 8:
979 tty.c_cflag |= CS8;
980 break;
981 case 7:
982 tty.c_cflag |= CS7;
983 break;
984 case 6:
985 tty.c_cflag |= CS6;
986 break;
987 case 5:
988 tty.c_cflag |= CS5;
989 break;
991 switch(parity) {
992 default:
993 case 'N':
994 break;
995 case 'E':
996 tty.c_cflag |= PARENB;
997 break;
998 case 'O':
999 tty.c_cflag |= PARENB | PARODD;
1000 break;
1002 if (stop_bits == 2)
1003 tty.c_cflag |= CSTOPB;
1005 tcsetattr (fd, TCSANOW, &tty);
1008 static int tty_serial_ioctl(void *opaque, int cmd, void *arg)
1010 FDCharDriver *s = opaque;
1012 switch(cmd) {
1013 case CHR_IOCTL_SERIAL_SET_PARAMS:
1015 QEMUSerialSetParams *ssp = arg;
1016 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1017 ssp->data_bits, ssp->stop_bits);
1019 break;
1020 case CHR_IOCTL_SERIAL_SET_BREAK:
1022 int enable = *(int *)arg;
1023 if (enable)
1024 tcsendbreak(s->fd_in, 1);
1026 break;
1027 case CHR_IOCTL_SERIAL_GET_TIOCM:
1029 int sarg = 0;
1030 int *targ = (int *)arg;
1031 ioctl(s->fd_in, TIOCMGET, &sarg);
1032 *targ = 0;
1033 if (sarg & TIOCM_CTS)
1034 *targ |= CHR_TIOCM_CTS;
1035 if (sarg & TIOCM_CAR)
1036 *targ |= CHR_TIOCM_CAR;
1037 if (sarg & TIOCM_DSR)
1038 *targ |= CHR_TIOCM_DSR;
1039 if (sarg & TIOCM_RI)
1040 *targ |= CHR_TIOCM_RI;
1041 if (sarg & TIOCM_DTR)
1042 *targ |= CHR_TIOCM_DTR;
1043 if (sarg & TIOCM_RTS)
1044 *targ |= CHR_TIOCM_RTS;
1046 break;
1047 case CHR_IOCTL_SERIAL_SET_TIOCM:
1049 int sarg = *(int *)arg;
1050 int targ = 0;
1051 ioctl(s->fd_in, TIOCMGET, &targ);
1052 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1053 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1054 if (sarg & CHR_TIOCM_CTS)
1055 targ |= TIOCM_CTS;
1056 if (sarg & CHR_TIOCM_CAR)
1057 targ |= TIOCM_CAR;
1058 if (sarg & CHR_TIOCM_DSR)
1059 targ |= TIOCM_DSR;
1060 if (sarg & CHR_TIOCM_RI)
1061 targ |= TIOCM_RI;
1062 if (sarg & CHR_TIOCM_DTR)
1063 targ |= TIOCM_DTR;
1064 if (sarg & CHR_TIOCM_RTS)
1065 targ |= TIOCM_RTS;
1066 ioctl(s->fd_in, TIOCMSET, &targ);
1068 break;
1069 default:
1070 return -ENOTSUP;
1072 return 0;
1075 static void qemu_chr_close_tty(CharDriverState *chr)
1077 FDCharDriver *s = chr->opaque;
1078 int fd = -1;
1080 if (s) {
1081 fd = s->fd_in;
1084 fd_chr_close(chr);
1086 if (fd >= 0) {
1087 close(fd);
1091 static int qemu_chr_open_tty(QemuOpts *opts, CharDriverState **_chr)
1093 const char *filename = qemu_opt_get(opts, "path");
1094 CharDriverState *chr;
1095 int fd;
1097 TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
1098 if (fd < 0) {
1099 return -errno;
1101 tty_serial_init(fd, 115200, 'N', 8, 1);
1102 chr = qemu_chr_open_fd(fd, fd);
1103 chr->chr_ioctl = tty_serial_ioctl;
1104 chr->chr_close = qemu_chr_close_tty;
1106 *_chr = chr;
1107 return 0;
1109 #else /* ! __linux__ && ! __sun__ */
1110 static int qemu_chr_open_pty(QemuOpts *opts, CharDriverState **_chr)
1112 return -ENOTSUP;
1114 #endif /* __linux__ || __sun__ */
1116 #if defined(__linux__)
1117 typedef struct {
1118 int fd;
1119 int mode;
1120 } ParallelCharDriver;
1122 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1124 if (s->mode != mode) {
1125 int m = mode;
1126 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1127 return 0;
1128 s->mode = mode;
1130 return 1;
1133 static int pp_ioctl(void *opaque, int cmd, void *arg)
1135 ParallelCharDriver *drv = opaque;
1136 int fd = drv->fd;
1137 uint8_t b;
1139 switch(cmd) {
1140 case CHR_IOCTL_PP_READ_DATA:
1141 if (ioctl(fd, PPRDATA, &b) < 0)
1142 return -ENOTSUP;
1143 *(uint8_t *)arg = b;
1144 break;
1145 case CHR_IOCTL_PP_WRITE_DATA:
1146 b = *(uint8_t *)arg;
1147 if (ioctl(fd, PPWDATA, &b) < 0)
1148 return -ENOTSUP;
1149 break;
1150 case CHR_IOCTL_PP_READ_CONTROL:
1151 if (ioctl(fd, PPRCONTROL, &b) < 0)
1152 return -ENOTSUP;
1153 /* Linux gives only the lowest bits, and no way to know data
1154 direction! For better compatibility set the fixed upper
1155 bits. */
1156 *(uint8_t *)arg = b | 0xc0;
1157 break;
1158 case CHR_IOCTL_PP_WRITE_CONTROL:
1159 b = *(uint8_t *)arg;
1160 if (ioctl(fd, PPWCONTROL, &b) < 0)
1161 return -ENOTSUP;
1162 break;
1163 case CHR_IOCTL_PP_READ_STATUS:
1164 if (ioctl(fd, PPRSTATUS, &b) < 0)
1165 return -ENOTSUP;
1166 *(uint8_t *)arg = b;
1167 break;
1168 case CHR_IOCTL_PP_DATA_DIR:
1169 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1170 return -ENOTSUP;
1171 break;
1172 case CHR_IOCTL_PP_EPP_READ_ADDR:
1173 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1174 struct ParallelIOArg *parg = arg;
1175 int n = read(fd, parg->buffer, parg->count);
1176 if (n != parg->count) {
1177 return -EIO;
1180 break;
1181 case CHR_IOCTL_PP_EPP_READ:
1182 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1183 struct ParallelIOArg *parg = arg;
1184 int n = read(fd, parg->buffer, parg->count);
1185 if (n != parg->count) {
1186 return -EIO;
1189 break;
1190 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1191 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1192 struct ParallelIOArg *parg = arg;
1193 int n = write(fd, parg->buffer, parg->count);
1194 if (n != parg->count) {
1195 return -EIO;
1198 break;
1199 case CHR_IOCTL_PP_EPP_WRITE:
1200 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1201 struct ParallelIOArg *parg = arg;
1202 int n = write(fd, parg->buffer, parg->count);
1203 if (n != parg->count) {
1204 return -EIO;
1207 break;
1208 default:
1209 return -ENOTSUP;
1211 return 0;
1214 static void pp_close(CharDriverState *chr)
1216 ParallelCharDriver *drv = chr->opaque;
1217 int fd = drv->fd;
1219 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1220 ioctl(fd, PPRELEASE);
1221 close(fd);
1222 qemu_free(drv);
1223 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1226 static int qemu_chr_open_pp(QemuOpts *opts, CharDriverState **_chr)
1228 const char *filename = qemu_opt_get(opts, "path");
1229 CharDriverState *chr;
1230 ParallelCharDriver *drv;
1231 int fd;
1233 TFR(fd = open(filename, O_RDWR));
1234 if (fd < 0) {
1235 return -errno;
1238 if (ioctl(fd, PPCLAIM) < 0) {
1239 close(fd);
1240 return -errno;
1243 drv = qemu_mallocz(sizeof(ParallelCharDriver));
1244 drv->fd = fd;
1245 drv->mode = IEEE1284_MODE_COMPAT;
1247 chr = qemu_mallocz(sizeof(CharDriverState));
1248 chr->chr_write = null_chr_write;
1249 chr->chr_ioctl = pp_ioctl;
1250 chr->chr_close = pp_close;
1251 chr->opaque = drv;
1253 qemu_chr_generic_open(chr);
1255 *_chr = chr;
1256 return 0;
1258 #endif /* __linux__ */
1260 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1261 static int pp_ioctl(void *opaque, int cmd, void *arg)
1263 int fd = (int)(intptr_t)opaque;
1264 uint8_t b;
1266 switch(cmd) {
1267 case CHR_IOCTL_PP_READ_DATA:
1268 if (ioctl(fd, PPIGDATA, &b) < 0)
1269 return -ENOTSUP;
1270 *(uint8_t *)arg = b;
1271 break;
1272 case CHR_IOCTL_PP_WRITE_DATA:
1273 b = *(uint8_t *)arg;
1274 if (ioctl(fd, PPISDATA, &b) < 0)
1275 return -ENOTSUP;
1276 break;
1277 case CHR_IOCTL_PP_READ_CONTROL:
1278 if (ioctl(fd, PPIGCTRL, &b) < 0)
1279 return -ENOTSUP;
1280 *(uint8_t *)arg = b;
1281 break;
1282 case CHR_IOCTL_PP_WRITE_CONTROL:
1283 b = *(uint8_t *)arg;
1284 if (ioctl(fd, PPISCTRL, &b) < 0)
1285 return -ENOTSUP;
1286 break;
1287 case CHR_IOCTL_PP_READ_STATUS:
1288 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1289 return -ENOTSUP;
1290 *(uint8_t *)arg = b;
1291 break;
1292 default:
1293 return -ENOTSUP;
1295 return 0;
1298 static int qemu_chr_open_pp(QemuOpts *opts, CharDriverState **_chr)
1300 const char *filename = qemu_opt_get(opts, "path");
1301 CharDriverState *chr;
1302 int fd;
1304 fd = qemu_open(filename, O_RDWR);
1305 if (fd < 0) {
1306 return -errno;
1309 chr = qemu_mallocz(sizeof(CharDriverState));
1310 chr->opaque = (void *)(intptr_t)fd;
1311 chr->chr_write = null_chr_write;
1312 chr->chr_ioctl = pp_ioctl;
1314 *_chr = chr;
1315 return 0;
1317 #endif
1319 #else /* _WIN32 */
1321 typedef struct {
1322 int max_size;
1323 HANDLE hcom, hrecv, hsend;
1324 OVERLAPPED orecv, osend;
1325 BOOL fpipe;
1326 DWORD len;
1327 } WinCharState;
1329 #define NSENDBUF 2048
1330 #define NRECVBUF 2048
1331 #define MAXCONNECT 1
1332 #define NTIMEOUT 5000
1334 static int win_chr_poll(void *opaque);
1335 static int win_chr_pipe_poll(void *opaque);
1337 static void win_chr_close(CharDriverState *chr)
1339 WinCharState *s = chr->opaque;
1341 if (s->hsend) {
1342 CloseHandle(s->hsend);
1343 s->hsend = NULL;
1345 if (s->hrecv) {
1346 CloseHandle(s->hrecv);
1347 s->hrecv = NULL;
1349 if (s->hcom) {
1350 CloseHandle(s->hcom);
1351 s->hcom = NULL;
1353 if (s->fpipe)
1354 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1355 else
1356 qemu_del_polling_cb(win_chr_poll, chr);
1358 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1361 static int win_chr_init(CharDriverState *chr, const char *filename)
1363 WinCharState *s = chr->opaque;
1364 COMMCONFIG comcfg;
1365 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1366 COMSTAT comstat;
1367 DWORD size;
1368 DWORD err;
1370 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1371 if (!s->hsend) {
1372 fprintf(stderr, "Failed CreateEvent\n");
1373 goto fail;
1375 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1376 if (!s->hrecv) {
1377 fprintf(stderr, "Failed CreateEvent\n");
1378 goto fail;
1381 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1382 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1383 if (s->hcom == INVALID_HANDLE_VALUE) {
1384 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1385 s->hcom = NULL;
1386 goto fail;
1389 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1390 fprintf(stderr, "Failed SetupComm\n");
1391 goto fail;
1394 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1395 size = sizeof(COMMCONFIG);
1396 GetDefaultCommConfig(filename, &comcfg, &size);
1397 comcfg.dcb.DCBlength = sizeof(DCB);
1398 CommConfigDialog(filename, NULL, &comcfg);
1400 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1401 fprintf(stderr, "Failed SetCommState\n");
1402 goto fail;
1405 if (!SetCommMask(s->hcom, EV_ERR)) {
1406 fprintf(stderr, "Failed SetCommMask\n");
1407 goto fail;
1410 cto.ReadIntervalTimeout = MAXDWORD;
1411 if (!SetCommTimeouts(s->hcom, &cto)) {
1412 fprintf(stderr, "Failed SetCommTimeouts\n");
1413 goto fail;
1416 if (!ClearCommError(s->hcom, &err, &comstat)) {
1417 fprintf(stderr, "Failed ClearCommError\n");
1418 goto fail;
1420 qemu_add_polling_cb(win_chr_poll, chr);
1421 return 0;
1423 fail:
1424 win_chr_close(chr);
1425 return -1;
1428 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1430 WinCharState *s = chr->opaque;
1431 DWORD len, ret, size, err;
1433 len = len1;
1434 ZeroMemory(&s->osend, sizeof(s->osend));
1435 s->osend.hEvent = s->hsend;
1436 while (len > 0) {
1437 if (s->hsend)
1438 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1439 else
1440 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1441 if (!ret) {
1442 err = GetLastError();
1443 if (err == ERROR_IO_PENDING) {
1444 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1445 if (ret) {
1446 buf += size;
1447 len -= size;
1448 } else {
1449 break;
1451 } else {
1452 break;
1454 } else {
1455 buf += size;
1456 len -= size;
1459 return len1 - len;
1462 static int win_chr_read_poll(CharDriverState *chr)
1464 WinCharState *s = chr->opaque;
1466 s->max_size = qemu_chr_be_can_write(chr);
1467 return s->max_size;
1470 static void win_chr_readfile(CharDriverState *chr)
1472 WinCharState *s = chr->opaque;
1473 int ret, err;
1474 uint8_t buf[READ_BUF_LEN];
1475 DWORD size;
1477 ZeroMemory(&s->orecv, sizeof(s->orecv));
1478 s->orecv.hEvent = s->hrecv;
1479 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1480 if (!ret) {
1481 err = GetLastError();
1482 if (err == ERROR_IO_PENDING) {
1483 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1487 if (size > 0) {
1488 qemu_chr_be_write(chr, buf, size);
1492 static void win_chr_read(CharDriverState *chr)
1494 WinCharState *s = chr->opaque;
1496 if (s->len > s->max_size)
1497 s->len = s->max_size;
1498 if (s->len == 0)
1499 return;
1501 win_chr_readfile(chr);
1504 static int win_chr_poll(void *opaque)
1506 CharDriverState *chr = opaque;
1507 WinCharState *s = chr->opaque;
1508 COMSTAT status;
1509 DWORD comerr;
1511 ClearCommError(s->hcom, &comerr, &status);
1512 if (status.cbInQue > 0) {
1513 s->len = status.cbInQue;
1514 win_chr_read_poll(chr);
1515 win_chr_read(chr);
1516 return 1;
1518 return 0;
1521 static int qemu_chr_open_win(QemuOpts *opts, CharDriverState **_chr)
1523 const char *filename = qemu_opt_get(opts, "path");
1524 CharDriverState *chr;
1525 WinCharState *s;
1527 chr = qemu_mallocz(sizeof(CharDriverState));
1528 s = qemu_mallocz(sizeof(WinCharState));
1529 chr->opaque = s;
1530 chr->chr_write = win_chr_write;
1531 chr->chr_close = win_chr_close;
1533 if (win_chr_init(chr, filename) < 0) {
1534 free(s);
1535 free(chr);
1536 return -EIO;
1538 qemu_chr_generic_open(chr);
1540 *_chr = chr;
1541 return 0;
1544 static int win_chr_pipe_poll(void *opaque)
1546 CharDriverState *chr = opaque;
1547 WinCharState *s = chr->opaque;
1548 DWORD size;
1550 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1551 if (size > 0) {
1552 s->len = size;
1553 win_chr_read_poll(chr);
1554 win_chr_read(chr);
1555 return 1;
1557 return 0;
1560 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1562 WinCharState *s = chr->opaque;
1563 OVERLAPPED ov;
1564 int ret;
1565 DWORD size;
1566 char openname[256];
1568 s->fpipe = TRUE;
1570 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1571 if (!s->hsend) {
1572 fprintf(stderr, "Failed CreateEvent\n");
1573 goto fail;
1575 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1576 if (!s->hrecv) {
1577 fprintf(stderr, "Failed CreateEvent\n");
1578 goto fail;
1581 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1582 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1583 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1584 PIPE_WAIT,
1585 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1586 if (s->hcom == INVALID_HANDLE_VALUE) {
1587 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1588 s->hcom = NULL;
1589 goto fail;
1592 ZeroMemory(&ov, sizeof(ov));
1593 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1594 ret = ConnectNamedPipe(s->hcom, &ov);
1595 if (ret) {
1596 fprintf(stderr, "Failed ConnectNamedPipe\n");
1597 goto fail;
1600 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1601 if (!ret) {
1602 fprintf(stderr, "Failed GetOverlappedResult\n");
1603 if (ov.hEvent) {
1604 CloseHandle(ov.hEvent);
1605 ov.hEvent = NULL;
1607 goto fail;
1610 if (ov.hEvent) {
1611 CloseHandle(ov.hEvent);
1612 ov.hEvent = NULL;
1614 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1615 return 0;
1617 fail:
1618 win_chr_close(chr);
1619 return -1;
1623 static int qemu_chr_open_win_pipe(QemuOpts *opts, CharDriverState **_chr)
1625 const char *filename = qemu_opt_get(opts, "path");
1626 CharDriverState *chr;
1627 WinCharState *s;
1629 chr = qemu_mallocz(sizeof(CharDriverState));
1630 s = qemu_mallocz(sizeof(WinCharState));
1631 chr->opaque = s;
1632 chr->chr_write = win_chr_write;
1633 chr->chr_close = win_chr_close;
1635 if (win_chr_pipe_init(chr, filename) < 0) {
1636 free(s);
1637 free(chr);
1638 return -EIO;
1640 qemu_chr_generic_open(chr);
1642 *_chr = chr;
1643 return 0;
1646 static int qemu_chr_open_win_file(HANDLE fd_out, CharDriverState **pchr)
1648 CharDriverState *chr;
1649 WinCharState *s;
1651 chr = qemu_mallocz(sizeof(CharDriverState));
1652 s = qemu_mallocz(sizeof(WinCharState));
1653 s->hcom = fd_out;
1654 chr->opaque = s;
1655 chr->chr_write = win_chr_write;
1656 qemu_chr_generic_open(chr);
1657 *pchr = chr;
1658 return 0;
1661 static int qemu_chr_open_win_con(QemuOpts *opts, CharDriverState **chr)
1663 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE), chr);
1666 static int qemu_chr_open_win_file_out(QemuOpts *opts, CharDriverState **_chr)
1668 const char *file_out = qemu_opt_get(opts, "path");
1669 HANDLE fd_out;
1671 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1672 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1673 if (fd_out == INVALID_HANDLE_VALUE) {
1674 return -EIO;
1677 return qemu_chr_open_win_file(fd_out, _chr);
1679 #endif /* !_WIN32 */
1681 /***********************************************************/
1682 /* UDP Net console */
1684 typedef struct {
1685 int fd;
1686 uint8_t buf[READ_BUF_LEN];
1687 int bufcnt;
1688 int bufptr;
1689 int max_size;
1690 } NetCharDriver;
1692 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1694 NetCharDriver *s = chr->opaque;
1696 return send(s->fd, (const void *)buf, len, 0);
1699 static int udp_chr_read_poll(void *opaque)
1701 CharDriverState *chr = opaque;
1702 NetCharDriver *s = chr->opaque;
1704 s->max_size = qemu_chr_be_can_write(chr);
1706 /* If there were any stray characters in the queue process them
1707 * first
1709 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1710 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
1711 s->bufptr++;
1712 s->max_size = qemu_chr_be_can_write(chr);
1714 return s->max_size;
1717 static void udp_chr_read(void *opaque)
1719 CharDriverState *chr = opaque;
1720 NetCharDriver *s = chr->opaque;
1722 if (s->max_size == 0)
1723 return;
1724 s->bufcnt = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
1725 s->bufptr = s->bufcnt;
1726 if (s->bufcnt <= 0)
1727 return;
1729 s->bufptr = 0;
1730 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1731 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
1732 s->bufptr++;
1733 s->max_size = qemu_chr_be_can_write(chr);
1737 static void udp_chr_update_read_handler(CharDriverState *chr)
1739 NetCharDriver *s = chr->opaque;
1741 if (s->fd >= 0) {
1742 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
1743 udp_chr_read, NULL, chr);
1747 static void udp_chr_close(CharDriverState *chr)
1749 NetCharDriver *s = chr->opaque;
1750 if (s->fd >= 0) {
1751 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1752 closesocket(s->fd);
1754 qemu_free(s);
1755 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1758 static int qemu_chr_open_udp(QemuOpts *opts, CharDriverState **_chr)
1760 CharDriverState *chr = NULL;
1761 NetCharDriver *s = NULL;
1762 int fd = -1;
1763 int ret;
1765 chr = qemu_mallocz(sizeof(CharDriverState));
1766 s = qemu_mallocz(sizeof(NetCharDriver));
1768 fd = inet_dgram_opts(opts);
1769 if (fd < 0) {
1770 fprintf(stderr, "inet_dgram_opts failed\n");
1771 ret = -errno;
1772 goto return_err;
1775 s->fd = fd;
1776 s->bufcnt = 0;
1777 s->bufptr = 0;
1778 chr->opaque = s;
1779 chr->chr_write = udp_chr_write;
1780 chr->chr_update_read_handler = udp_chr_update_read_handler;
1781 chr->chr_close = udp_chr_close;
1783 *_chr = chr;
1784 return 0;
1786 return_err:
1787 qemu_free(chr);
1788 qemu_free(s);
1789 if (fd >= 0) {
1790 closesocket(fd);
1792 return ret;
1795 /***********************************************************/
1796 /* TCP Net console */
1798 typedef struct {
1799 int fd, listen_fd;
1800 int connected;
1801 int max_size;
1802 int do_telnetopt;
1803 int do_nodelay;
1804 int is_unix;
1805 int msgfd;
1806 } TCPCharDriver;
1808 static void tcp_chr_accept(void *opaque);
1810 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1812 TCPCharDriver *s = chr->opaque;
1813 if (s->connected) {
1814 return send_all(s->fd, buf, len);
1815 } else {
1816 /* XXX: indicate an error ? */
1817 return len;
1821 static int tcp_chr_read_poll(void *opaque)
1823 CharDriverState *chr = opaque;
1824 TCPCharDriver *s = chr->opaque;
1825 if (!s->connected)
1826 return 0;
1827 s->max_size = qemu_chr_be_can_write(chr);
1828 return s->max_size;
1831 #define IAC 255
1832 #define IAC_BREAK 243
1833 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
1834 TCPCharDriver *s,
1835 uint8_t *buf, int *size)
1837 /* Handle any telnet client's basic IAC options to satisfy char by
1838 * char mode with no echo. All IAC options will be removed from
1839 * the buf and the do_telnetopt variable will be used to track the
1840 * state of the width of the IAC information.
1842 * IAC commands come in sets of 3 bytes with the exception of the
1843 * "IAC BREAK" command and the double IAC.
1846 int i;
1847 int j = 0;
1849 for (i = 0; i < *size; i++) {
1850 if (s->do_telnetopt > 1) {
1851 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
1852 /* Double IAC means send an IAC */
1853 if (j != i)
1854 buf[j] = buf[i];
1855 j++;
1856 s->do_telnetopt = 1;
1857 } else {
1858 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
1859 /* Handle IAC break commands by sending a serial break */
1860 qemu_chr_event(chr, CHR_EVENT_BREAK);
1861 s->do_telnetopt++;
1863 s->do_telnetopt++;
1865 if (s->do_telnetopt >= 4) {
1866 s->do_telnetopt = 1;
1868 } else {
1869 if ((unsigned char)buf[i] == IAC) {
1870 s->do_telnetopt = 2;
1871 } else {
1872 if (j != i)
1873 buf[j] = buf[i];
1874 j++;
1878 *size = j;
1881 static int tcp_chr_ioctl(void *opaque, int cmd, void *data)
1883 TCPCharDriver *s = opaque;
1884 int ret;
1886 switch (cmd) {
1887 case CHR_GET_MSGFD: {
1888 int *pfd = data;
1889 *pfd = s->msgfd;
1890 s->msgfd = -1;
1891 ret = 0;
1892 break;
1894 default:
1895 ret = -ENOTSUP;
1896 break;
1899 return ret;
1902 #ifndef _WIN32
1903 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
1905 TCPCharDriver *s = chr->opaque;
1906 struct cmsghdr *cmsg;
1908 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
1909 int fd;
1911 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
1912 cmsg->cmsg_level != SOL_SOCKET ||
1913 cmsg->cmsg_type != SCM_RIGHTS)
1914 continue;
1916 fd = *((int *)CMSG_DATA(cmsg));
1917 if (fd < 0)
1918 continue;
1920 if (s->msgfd != -1)
1921 close(s->msgfd);
1922 s->msgfd = fd;
1926 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
1928 TCPCharDriver *s = chr->opaque;
1929 struct msghdr msg = { NULL, };
1930 struct iovec iov[1];
1931 union {
1932 struct cmsghdr cmsg;
1933 char control[CMSG_SPACE(sizeof(int))];
1934 } msg_control;
1935 ssize_t ret;
1937 iov[0].iov_base = buf;
1938 iov[0].iov_len = len;
1940 msg.msg_iov = iov;
1941 msg.msg_iovlen = 1;
1942 msg.msg_control = &msg_control;
1943 msg.msg_controllen = sizeof(msg_control);
1945 ret = recvmsg(s->fd, &msg, 0);
1946 if (ret > 0 && s->is_unix)
1947 unix_process_msgfd(chr, &msg);
1949 return ret;
1951 #else
1952 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
1954 TCPCharDriver *s = chr->opaque;
1955 return qemu_recv(s->fd, buf, len, 0);
1957 #endif
1959 static void tcp_chr_read(void *opaque)
1961 CharDriverState *chr = opaque;
1962 TCPCharDriver *s = chr->opaque;
1963 uint8_t buf[READ_BUF_LEN];
1964 int len, size;
1966 if (!s->connected || s->max_size <= 0)
1967 return;
1968 len = sizeof(buf);
1969 if (len > s->max_size)
1970 len = s->max_size;
1971 size = tcp_chr_recv(chr, (void *)buf, len);
1972 if (size == 0) {
1973 /* connection closed */
1974 s->connected = 0;
1975 if (s->listen_fd >= 0) {
1976 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
1978 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1979 closesocket(s->fd);
1980 s->fd = -1;
1981 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1982 } else if (size > 0) {
1983 if (s->do_telnetopt)
1984 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
1985 if (size > 0)
1986 qemu_chr_be_write(chr, buf, size);
1990 #ifndef _WIN32
1991 CharDriverState *qemu_chr_open_eventfd(int eventfd)
1993 return qemu_chr_open_fd(eventfd, eventfd);
1995 #endif
1997 static void tcp_chr_connect(void *opaque)
1999 CharDriverState *chr = opaque;
2000 TCPCharDriver *s = chr->opaque;
2002 s->connected = 1;
2003 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2004 tcp_chr_read, NULL, chr);
2005 qemu_chr_generic_open(chr);
2008 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2009 static void tcp_chr_telnet_init(int fd)
2011 char buf[3];
2012 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2013 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2014 send(fd, (char *)buf, 3, 0);
2015 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2016 send(fd, (char *)buf, 3, 0);
2017 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2018 send(fd, (char *)buf, 3, 0);
2019 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2020 send(fd, (char *)buf, 3, 0);
2023 static void socket_set_nodelay(int fd)
2025 int val = 1;
2026 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2029 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2031 TCPCharDriver *s = chr->opaque;
2032 if (s->fd != -1)
2033 return -1;
2035 socket_set_nonblock(fd);
2036 if (s->do_nodelay)
2037 socket_set_nodelay(fd);
2038 s->fd = fd;
2039 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2040 tcp_chr_connect(chr);
2042 return 0;
2045 static void tcp_chr_accept(void *opaque)
2047 CharDriverState *chr = opaque;
2048 TCPCharDriver *s = chr->opaque;
2049 struct sockaddr_in saddr;
2050 #ifndef _WIN32
2051 struct sockaddr_un uaddr;
2052 #endif
2053 struct sockaddr *addr;
2054 socklen_t len;
2055 int fd;
2057 for(;;) {
2058 #ifndef _WIN32
2059 if (s->is_unix) {
2060 len = sizeof(uaddr);
2061 addr = (struct sockaddr *)&uaddr;
2062 } else
2063 #endif
2065 len = sizeof(saddr);
2066 addr = (struct sockaddr *)&saddr;
2068 fd = qemu_accept(s->listen_fd, addr, &len);
2069 if (fd < 0 && errno != EINTR) {
2070 return;
2071 } else if (fd >= 0) {
2072 if (s->do_telnetopt)
2073 tcp_chr_telnet_init(fd);
2074 break;
2077 if (tcp_chr_add_client(chr, fd) < 0)
2078 close(fd);
2081 static void tcp_chr_close(CharDriverState *chr)
2083 TCPCharDriver *s = chr->opaque;
2084 if (s->fd >= 0) {
2085 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2086 closesocket(s->fd);
2088 if (s->listen_fd >= 0) {
2089 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2090 closesocket(s->listen_fd);
2092 qemu_free(s);
2093 qemu_chr_event(chr, CHR_EVENT_CLOSED);
2096 static int qemu_chr_open_socket(QemuOpts *opts, CharDriverState **_chr)
2098 CharDriverState *chr = NULL;
2099 TCPCharDriver *s = NULL;
2100 int fd = -1;
2101 int is_listen;
2102 int is_waitconnect;
2103 int do_nodelay;
2104 int is_unix;
2105 int is_telnet;
2106 int ret;
2108 is_listen = qemu_opt_get_bool(opts, "server", 0);
2109 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2110 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2111 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2112 is_unix = qemu_opt_get(opts, "path") != NULL;
2113 if (!is_listen)
2114 is_waitconnect = 0;
2116 chr = qemu_mallocz(sizeof(CharDriverState));
2117 s = qemu_mallocz(sizeof(TCPCharDriver));
2119 if (is_unix) {
2120 if (is_listen) {
2121 fd = unix_listen_opts(opts);
2122 } else {
2123 fd = unix_connect_opts(opts);
2125 } else {
2126 if (is_listen) {
2127 fd = inet_listen_opts(opts, 0);
2128 } else {
2129 fd = inet_connect_opts(opts);
2132 if (fd < 0) {
2133 ret = -errno;
2134 goto fail;
2137 if (!is_waitconnect)
2138 socket_set_nonblock(fd);
2140 s->connected = 0;
2141 s->fd = -1;
2142 s->listen_fd = -1;
2143 s->msgfd = -1;
2144 s->is_unix = is_unix;
2145 s->do_nodelay = do_nodelay && !is_unix;
2147 chr->opaque = s;
2148 chr->chr_write = tcp_chr_write;
2149 chr->chr_close = tcp_chr_close;
2150 chr->chr_add_client = tcp_chr_add_client;
2151 chr->chr_ioctl = tcp_chr_ioctl;
2153 if (is_listen) {
2154 s->listen_fd = fd;
2155 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2156 if (is_telnet)
2157 s->do_telnetopt = 1;
2159 } else {
2160 s->connected = 1;
2161 s->fd = fd;
2162 socket_set_nodelay(fd);
2163 tcp_chr_connect(chr);
2166 /* for "info chardev" monitor command */
2167 chr->filename = qemu_malloc(256);
2168 if (is_unix) {
2169 snprintf(chr->filename, 256, "unix:%s%s",
2170 qemu_opt_get(opts, "path"),
2171 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2172 } else if (is_telnet) {
2173 snprintf(chr->filename, 256, "telnet:%s:%s%s",
2174 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2175 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2176 } else {
2177 snprintf(chr->filename, 256, "tcp:%s:%s%s",
2178 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2179 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2182 if (is_listen && is_waitconnect) {
2183 printf("QEMU waiting for connection on: %s\n",
2184 chr->filename);
2185 tcp_chr_accept(chr);
2186 socket_set_nonblock(s->listen_fd);
2189 *_chr = chr;
2190 return 0;
2192 fail:
2193 if (fd >= 0)
2194 closesocket(fd);
2195 qemu_free(s);
2196 qemu_free(chr);
2197 return ret;
2200 /***********************************************************/
2201 /* Memory chardev */
2202 typedef struct {
2203 size_t outbuf_size;
2204 size_t outbuf_capacity;
2205 uint8_t *outbuf;
2206 } MemoryDriver;
2208 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2210 MemoryDriver *d = chr->opaque;
2212 /* TODO: the QString implementation has the same code, we should
2213 * introduce a generic way to do this in cutils.c */
2214 if (d->outbuf_capacity < d->outbuf_size + len) {
2215 /* grow outbuf */
2216 d->outbuf_capacity += len;
2217 d->outbuf_capacity *= 2;
2218 d->outbuf = qemu_realloc(d->outbuf, d->outbuf_capacity);
2221 memcpy(d->outbuf + d->outbuf_size, buf, len);
2222 d->outbuf_size += len;
2224 return len;
2227 void qemu_chr_init_mem(CharDriverState *chr)
2229 MemoryDriver *d;
2231 d = qemu_malloc(sizeof(*d));
2232 d->outbuf_size = 0;
2233 d->outbuf_capacity = 4096;
2234 d->outbuf = qemu_mallocz(d->outbuf_capacity);
2236 memset(chr, 0, sizeof(*chr));
2237 chr->opaque = d;
2238 chr->chr_write = mem_chr_write;
2241 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2243 MemoryDriver *d = chr->opaque;
2244 return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2247 /* NOTE: this driver can not be closed with qemu_chr_close()! */
2248 void qemu_chr_close_mem(CharDriverState *chr)
2250 MemoryDriver *d = chr->opaque;
2252 qemu_free(d->outbuf);
2253 qemu_free(chr->opaque);
2254 chr->opaque = NULL;
2255 chr->chr_write = NULL;
2258 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2260 const MemoryDriver *d = chr->opaque;
2261 return d->outbuf_size;
2264 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2266 char host[65], port[33], width[8], height[8];
2267 int pos;
2268 const char *p;
2269 QemuOpts *opts;
2271 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1);
2272 if (NULL == opts)
2273 return NULL;
2275 if (strcmp(filename, "null") == 0 ||
2276 strcmp(filename, "pty") == 0 ||
2277 strcmp(filename, "msmouse") == 0 ||
2278 strcmp(filename, "braille") == 0 ||
2279 strcmp(filename, "stdio") == 0) {
2280 qemu_opt_set(opts, "backend", filename);
2281 return opts;
2283 if (strstart(filename, "vc", &p)) {
2284 qemu_opt_set(opts, "backend", "vc");
2285 if (*p == ':') {
2286 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2287 /* pixels */
2288 qemu_opt_set(opts, "width", width);
2289 qemu_opt_set(opts, "height", height);
2290 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2291 /* chars */
2292 qemu_opt_set(opts, "cols", width);
2293 qemu_opt_set(opts, "rows", height);
2294 } else {
2295 goto fail;
2298 return opts;
2300 if (strcmp(filename, "con:") == 0) {
2301 qemu_opt_set(opts, "backend", "console");
2302 return opts;
2304 if (strstart(filename, "COM", NULL)) {
2305 qemu_opt_set(opts, "backend", "serial");
2306 qemu_opt_set(opts, "path", filename);
2307 return opts;
2309 if (strstart(filename, "file:", &p)) {
2310 qemu_opt_set(opts, "backend", "file");
2311 qemu_opt_set(opts, "path", p);
2312 return opts;
2314 if (strstart(filename, "pipe:", &p)) {
2315 qemu_opt_set(opts, "backend", "pipe");
2316 qemu_opt_set(opts, "path", p);
2317 return opts;
2319 if (strstart(filename, "tcp:", &p) ||
2320 strstart(filename, "telnet:", &p)) {
2321 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2322 host[0] = 0;
2323 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2324 goto fail;
2326 qemu_opt_set(opts, "backend", "socket");
2327 qemu_opt_set(opts, "host", host);
2328 qemu_opt_set(opts, "port", port);
2329 if (p[pos] == ',') {
2330 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2331 goto fail;
2333 if (strstart(filename, "telnet:", &p))
2334 qemu_opt_set(opts, "telnet", "on");
2335 return opts;
2337 if (strstart(filename, "udp:", &p)) {
2338 qemu_opt_set(opts, "backend", "udp");
2339 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2340 host[0] = 0;
2341 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
2342 goto fail;
2345 qemu_opt_set(opts, "host", host);
2346 qemu_opt_set(opts, "port", port);
2347 if (p[pos] == '@') {
2348 p += pos + 1;
2349 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2350 host[0] = 0;
2351 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2352 goto fail;
2355 qemu_opt_set(opts, "localaddr", host);
2356 qemu_opt_set(opts, "localport", port);
2358 return opts;
2360 if (strstart(filename, "unix:", &p)) {
2361 qemu_opt_set(opts, "backend", "socket");
2362 if (qemu_opts_do_parse(opts, p, "path") != 0)
2363 goto fail;
2364 return opts;
2366 if (strstart(filename, "/dev/parport", NULL) ||
2367 strstart(filename, "/dev/ppi", NULL)) {
2368 qemu_opt_set(opts, "backend", "parport");
2369 qemu_opt_set(opts, "path", filename);
2370 return opts;
2372 if (strstart(filename, "/dev/", NULL)) {
2373 qemu_opt_set(opts, "backend", "tty");
2374 qemu_opt_set(opts, "path", filename);
2375 return opts;
2378 fail:
2379 qemu_opts_del(opts);
2380 return NULL;
2383 static const struct {
2384 const char *name;
2385 int (*open)(QemuOpts *opts, CharDriverState **chr);
2386 } backend_table[] = {
2387 { .name = "null", .open = qemu_chr_open_null },
2388 { .name = "socket", .open = qemu_chr_open_socket },
2389 { .name = "udp", .open = qemu_chr_open_udp },
2390 { .name = "msmouse", .open = qemu_chr_open_msmouse },
2391 { .name = "vc", .open = text_console_init },
2392 #ifdef _WIN32
2393 { .name = "file", .open = qemu_chr_open_win_file_out },
2394 { .name = "pipe", .open = qemu_chr_open_win_pipe },
2395 { .name = "console", .open = qemu_chr_open_win_con },
2396 { .name = "serial", .open = qemu_chr_open_win },
2397 #else
2398 { .name = "file", .open = qemu_chr_open_file_out },
2399 { .name = "pipe", .open = qemu_chr_open_pipe },
2400 { .name = "pty", .open = qemu_chr_open_pty },
2401 { .name = "stdio", .open = qemu_chr_open_stdio },
2402 #endif
2403 #ifdef CONFIG_BRLAPI
2404 { .name = "braille", .open = chr_baum_init },
2405 #endif
2406 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2407 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
2408 || defined(__FreeBSD_kernel__)
2409 { .name = "tty", .open = qemu_chr_open_tty },
2410 #endif
2411 #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) \
2412 || defined(__FreeBSD_kernel__)
2413 { .name = "parport", .open = qemu_chr_open_pp },
2414 #endif
2415 #ifdef CONFIG_SPICE
2416 { .name = "spicevmc", .open = qemu_chr_open_spice },
2417 #endif
2420 CharDriverState *qemu_chr_open_opts(QemuOpts *opts,
2421 void (*init)(struct CharDriverState *s))
2423 CharDriverState *chr;
2424 int i;
2425 int ret;
2427 if (qemu_opts_id(opts) == NULL) {
2428 fprintf(stderr, "chardev: no id specified\n");
2429 return NULL;
2432 if (qemu_opt_get(opts, "backend") == NULL) {
2433 fprintf(stderr, "chardev: \"%s\" missing backend\n",
2434 qemu_opts_id(opts));
2435 return NULL;
2437 for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
2438 if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
2439 break;
2441 if (i == ARRAY_SIZE(backend_table)) {
2442 fprintf(stderr, "chardev: backend \"%s\" not found\n",
2443 qemu_opt_get(opts, "backend"));
2444 return NULL;
2447 ret = backend_table[i].open(opts, &chr);
2448 if (ret < 0) {
2449 fprintf(stderr, "chardev: opening backend \"%s\" failed: %s\n",
2450 qemu_opt_get(opts, "backend"), strerror(-ret));
2451 return NULL;
2454 if (!chr->filename)
2455 chr->filename = qemu_strdup(qemu_opt_get(opts, "backend"));
2456 chr->init = init;
2457 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2459 chr->avail_connections = 1;
2460 chr->label = qemu_strdup(qemu_opts_id(opts));
2461 return chr;
2464 CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2466 const char *p;
2467 CharDriverState *chr;
2468 QemuOpts *opts;
2470 if (strstart(filename, "chardev:", &p)) {
2471 return qemu_chr_find(p);
2474 opts = qemu_chr_parse_compat(label, filename);
2475 if (!opts)
2476 return NULL;
2478 chr = qemu_chr_open_opts(opts, init);
2479 qemu_opts_del(opts);
2480 return chr;
2483 void qemu_chr_set_echo(struct CharDriverState *chr, bool echo)
2485 if (chr->chr_set_echo) {
2486 chr->chr_set_echo(chr, echo);
2490 void qemu_chr_fe_open(struct CharDriverState *chr)
2492 chr->fe_opened++;
2494 if (chr->chr_guest_open) {
2495 chr->chr_guest_open(chr);
2499 void qemu_chr_fe_close(struct CharDriverState *chr)
2501 if (chr->chr_guest_close) {
2502 chr->chr_guest_close(chr);
2505 chr->fe_opened--;
2508 void qemu_chr_close(CharDriverState *chr)
2510 QTAILQ_REMOVE(&chardevs, chr, next);
2511 if (chr->chr_close)
2512 chr->chr_close(chr);
2513 qemu_free(chr->filename);
2514 qemu_free(chr->label);
2515 qemu_free(chr);
2518 static void qemu_chr_qlist_iter(QObject *obj, void *opaque)
2520 QDict *chr_dict;
2521 Monitor *mon = opaque;
2523 chr_dict = qobject_to_qdict(obj);
2524 monitor_printf(mon, "%s: filename=%s\n", qdict_get_str(chr_dict, "label"),
2525 qdict_get_str(chr_dict, "filename"));
2528 void qemu_chr_info_print(Monitor *mon, const QObject *ret_data)
2530 qlist_iter(qobject_to_qlist(ret_data), qemu_chr_qlist_iter, mon);
2533 void qemu_chr_info(Monitor *mon, QObject **ret_data)
2535 QList *chr_list;
2536 CharDriverState *chr;
2538 chr_list = qlist_new();
2540 QTAILQ_FOREACH(chr, &chardevs, next) {
2541 QObject *obj = qobject_from_jsonf("{ 'label': %s, 'filename': %s }",
2542 chr->label, chr->filename);
2543 qlist_append_obj(chr_list, obj);
2546 *ret_data = QOBJECT(chr_list);
2549 CharDriverState *qemu_chr_find(const char *name)
2551 CharDriverState *chr;
2553 QTAILQ_FOREACH(chr, &chardevs, next) {
2554 if (strcmp(chr->label, name) != 0)
2555 continue;
2556 return chr;
2558 return NULL;