net: make tap_receive() re-use tap_receive_iov() code
[qemu.git] / qemu-char.c
blob6f05f8a747ce85f242f21d0aec733e9a7c4a9cbd
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 "block.h"
32 #include "hw/usb.h"
33 #include "hw/baum.h"
34 #include "hw/msmouse.h"
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <signal.h>
39 #include <time.h>
40 #include <errno.h>
41 #include <sys/time.h>
42 #include <zlib.h>
44 #ifndef _WIN32
45 #include <sys/times.h>
46 #include <sys/wait.h>
47 #include <termios.h>
48 #include <sys/mman.h>
49 #include <sys/ioctl.h>
50 #include <sys/resource.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <net/if.h>
54 #include <arpa/inet.h>
55 #include <dirent.h>
56 #include <netdb.h>
57 #include <sys/select.h>
58 #ifdef CONFIG_BSD
59 #include <sys/stat.h>
60 #ifdef __FreeBSD__
61 #include <libutil.h>
62 #include <dev/ppbus/ppi.h>
63 #include <dev/ppbus/ppbconf.h>
64 #elif defined(__DragonFly__)
65 #include <libutil.h>
66 #include <dev/misc/ppi/ppi.h>
67 #include <bus/ppbus/ppbconf.h>
68 #else
69 #include <util.h>
70 #endif
71 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
72 #include <freebsd/stdlib.h>
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"
100 /***********************************************************/
101 /* character device */
103 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
104 QTAILQ_HEAD_INITIALIZER(chardevs);
106 static void qemu_chr_event(CharDriverState *s, int event)
108 if (!s->chr_event)
109 return;
110 s->chr_event(s->handler_opaque, event);
113 static void qemu_chr_reset_bh(void *opaque)
115 CharDriverState *s = opaque;
117 if (s->initial_reset_issued) {
118 qemu_chr_event(s, CHR_EVENT_OPENED);
119 } else {
120 s->initial_reset_issued = true;
122 qemu_bh_delete(s->bh);
123 s->bh = NULL;
126 void qemu_chr_reset(CharDriverState *s)
128 if (s->bh == NULL) {
129 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
130 qemu_bh_schedule(s->bh);
134 void qemu_chr_initial_reset(void)
136 CharDriverState *chr;
138 QTAILQ_FOREACH(chr, &chardevs, next) {
139 qemu_chr_reset(chr);
143 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
145 return s->chr_write(s, buf, len);
148 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
150 if (!s->chr_ioctl)
151 return -ENOTSUP;
152 return s->chr_ioctl(s, cmd, arg);
155 int qemu_chr_can_read(CharDriverState *s)
157 if (!s->chr_can_read)
158 return 0;
159 return s->chr_can_read(s->handler_opaque);
162 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
164 s->chr_read(s->handler_opaque, buf, len);
167 int qemu_chr_get_msgfd(CharDriverState *s)
169 return s->get_msgfd ? s->get_msgfd(s) : -1;
172 void qemu_chr_accept_input(CharDriverState *s)
174 if (s->chr_accept_input)
175 s->chr_accept_input(s);
178 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
180 char buf[4096];
181 va_list ap;
182 va_start(ap, fmt);
183 vsnprintf(buf, sizeof(buf), fmt, ap);
184 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
185 va_end(ap);
188 void qemu_chr_send_event(CharDriverState *s, int event)
190 if (s->chr_send_event)
191 s->chr_send_event(s, event);
194 void qemu_chr_add_handlers(CharDriverState *s,
195 IOCanRWHandler *fd_can_read,
196 IOReadHandler *fd_read,
197 IOEventHandler *fd_event,
198 void *opaque)
200 s->chr_can_read = fd_can_read;
201 s->chr_read = fd_read;
202 s->chr_event = fd_event;
203 s->handler_opaque = opaque;
204 if (s->chr_update_read_handler)
205 s->chr_update_read_handler(s);
208 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
210 return len;
213 static CharDriverState *qemu_chr_open_null(QemuOpts *opts)
215 CharDriverState *chr;
217 chr = qemu_mallocz(sizeof(CharDriverState));
218 chr->chr_write = null_chr_write;
219 return chr;
222 /* MUX driver for serial I/O splitting */
223 #define MAX_MUX 4
224 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
225 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
226 typedef struct {
227 IOCanRWHandler *chr_can_read[MAX_MUX];
228 IOReadHandler *chr_read[MAX_MUX];
229 IOEventHandler *chr_event[MAX_MUX];
230 void *ext_opaque[MAX_MUX];
231 CharDriverState *drv;
232 int focus;
233 int mux_cnt;
234 int term_got_escape;
235 int max_size;
236 /* Intermediate input buffer allows to catch escape sequences even if the
237 currently active device is not accepting any input - but only until it
238 is full as well. */
239 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
240 int prod[MAX_MUX];
241 int cons[MAX_MUX];
242 int timestamps;
243 int linestart;
244 int64_t timestamps_start;
245 } MuxDriver;
248 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
250 MuxDriver *d = chr->opaque;
251 int ret;
252 if (!d->timestamps) {
253 ret = d->drv->chr_write(d->drv, buf, len);
254 } else {
255 int i;
257 ret = 0;
258 for (i = 0; i < len; i++) {
259 if (d->linestart) {
260 char buf1[64];
261 int64_t ti;
262 int secs;
264 ti = qemu_get_clock(rt_clock);
265 if (d->timestamps_start == -1)
266 d->timestamps_start = ti;
267 ti -= d->timestamps_start;
268 secs = ti / 1000;
269 snprintf(buf1, sizeof(buf1),
270 "[%02d:%02d:%02d.%03d] ",
271 secs / 3600,
272 (secs / 60) % 60,
273 secs % 60,
274 (int)(ti % 1000));
275 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
276 d->linestart = 0;
278 ret += d->drv->chr_write(d->drv, buf+i, 1);
279 if (buf[i] == '\n') {
280 d->linestart = 1;
284 return ret;
287 static const char * const mux_help[] = {
288 "% h print this help\n\r",
289 "% x exit emulator\n\r",
290 "% s save disk data back to file (if -snapshot)\n\r",
291 "% t toggle console timestamps\n\r"
292 "% b send break (magic sysrq)\n\r",
293 "% c switch between console and monitor\n\r",
294 "% % sends %\n\r",
295 NULL
298 int term_escape_char = 0x01; /* ctrl-a is used for escape */
299 static void mux_print_help(CharDriverState *chr)
301 int i, j;
302 char ebuf[15] = "Escape-Char";
303 char cbuf[50] = "\n\r";
305 if (term_escape_char > 0 && term_escape_char < 26) {
306 snprintf(cbuf, sizeof(cbuf), "\n\r");
307 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
308 } else {
309 snprintf(cbuf, sizeof(cbuf),
310 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
311 term_escape_char);
313 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
314 for (i = 0; mux_help[i] != NULL; i++) {
315 for (j=0; mux_help[i][j] != '\0'; j++) {
316 if (mux_help[i][j] == '%')
317 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
318 else
319 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
324 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
326 if (d->chr_event[mux_nr])
327 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
330 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
332 if (d->term_got_escape) {
333 d->term_got_escape = 0;
334 if (ch == term_escape_char)
335 goto send_char;
336 switch(ch) {
337 case '?':
338 case 'h':
339 mux_print_help(chr);
340 break;
341 case 'x':
343 const char *term = "QEMU: Terminated\n\r";
344 chr->chr_write(chr,(uint8_t *)term,strlen(term));
345 exit(0);
346 break;
348 case 's':
350 DriveInfo *dinfo;
351 QTAILQ_FOREACH(dinfo, &drives, next) {
352 bdrv_commit(dinfo->bdrv);
355 break;
356 case 'b':
357 qemu_chr_event(chr, CHR_EVENT_BREAK);
358 break;
359 case 'c':
360 /* Switch to the next registered device */
361 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
362 d->focus++;
363 if (d->focus >= d->mux_cnt)
364 d->focus = 0;
365 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
366 break;
367 case 't':
368 d->timestamps = !d->timestamps;
369 d->timestamps_start = -1;
370 d->linestart = 0;
371 break;
373 } else if (ch == term_escape_char) {
374 d->term_got_escape = 1;
375 } else {
376 send_char:
377 return 1;
379 return 0;
382 static void mux_chr_accept_input(CharDriverState *chr)
384 MuxDriver *d = chr->opaque;
385 int m = d->focus;
387 while (d->prod[m] != d->cons[m] &&
388 d->chr_can_read[m] &&
389 d->chr_can_read[m](d->ext_opaque[m])) {
390 d->chr_read[m](d->ext_opaque[m],
391 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
395 static int mux_chr_can_read(void *opaque)
397 CharDriverState *chr = opaque;
398 MuxDriver *d = chr->opaque;
399 int m = d->focus;
401 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
402 return 1;
403 if (d->chr_can_read[m])
404 return d->chr_can_read[m](d->ext_opaque[m]);
405 return 0;
408 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
410 CharDriverState *chr = opaque;
411 MuxDriver *d = chr->opaque;
412 int m = d->focus;
413 int i;
415 mux_chr_accept_input (opaque);
417 for(i = 0; i < size; i++)
418 if (mux_proc_byte(chr, d, buf[i])) {
419 if (d->prod[m] == d->cons[m] &&
420 d->chr_can_read[m] &&
421 d->chr_can_read[m](d->ext_opaque[m]))
422 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
423 else
424 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
428 static void mux_chr_event(void *opaque, int event)
430 CharDriverState *chr = opaque;
431 MuxDriver *d = chr->opaque;
432 int i;
434 /* Send the event to all registered listeners */
435 for (i = 0; i < d->mux_cnt; i++)
436 mux_chr_send_event(d, i, event);
439 static void mux_chr_update_read_handler(CharDriverState *chr)
441 MuxDriver *d = chr->opaque;
443 if (d->mux_cnt >= MAX_MUX) {
444 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
445 return;
447 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
448 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
449 d->chr_read[d->mux_cnt] = chr->chr_read;
450 d->chr_event[d->mux_cnt] = chr->chr_event;
451 /* Fix up the real driver with mux routines */
452 if (d->mux_cnt == 0) {
453 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
454 mux_chr_event, chr);
456 if (d->focus != -1) {
457 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
459 d->focus = d->mux_cnt;
460 d->mux_cnt++;
461 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
464 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
466 CharDriverState *chr;
467 MuxDriver *d;
469 chr = qemu_mallocz(sizeof(CharDriverState));
470 d = qemu_mallocz(sizeof(MuxDriver));
472 chr->opaque = d;
473 d->drv = drv;
474 d->focus = -1;
475 chr->chr_write = mux_chr_write;
476 chr->chr_update_read_handler = mux_chr_update_read_handler;
477 chr->chr_accept_input = mux_chr_accept_input;
478 return chr;
482 #ifdef _WIN32
483 int send_all(int fd, const void *buf, int len1)
485 int ret, len;
487 len = len1;
488 while (len > 0) {
489 ret = send(fd, buf, len, 0);
490 if (ret < 0) {
491 errno = WSAGetLastError();
492 if (errno != WSAEWOULDBLOCK) {
493 return -1;
495 } else if (ret == 0) {
496 break;
497 } else {
498 buf += ret;
499 len -= ret;
502 return len1 - len;
505 #else
507 static int unix_write(int fd, const uint8_t *buf, int len1)
509 int ret, len;
511 len = len1;
512 while (len > 0) {
513 ret = write(fd, buf, len);
514 if (ret < 0) {
515 if (errno != EINTR && errno != EAGAIN)
516 return -1;
517 } else if (ret == 0) {
518 break;
519 } else {
520 buf += ret;
521 len -= ret;
524 return len1 - len;
527 int send_all(int fd, const void *buf, int len1)
529 return unix_write(fd, buf, len1);
531 #endif /* !_WIN32 */
533 #ifndef _WIN32
535 typedef struct {
536 int fd_in, fd_out;
537 int max_size;
538 } FDCharDriver;
540 #define STDIO_MAX_CLIENTS 1
541 static int stdio_nb_clients = 0;
543 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
545 FDCharDriver *s = chr->opaque;
546 return send_all(s->fd_out, buf, len);
549 static int fd_chr_read_poll(void *opaque)
551 CharDriverState *chr = opaque;
552 FDCharDriver *s = chr->opaque;
554 s->max_size = qemu_chr_can_read(chr);
555 return s->max_size;
558 static void fd_chr_read(void *opaque)
560 CharDriverState *chr = opaque;
561 FDCharDriver *s = chr->opaque;
562 int size, len;
563 uint8_t buf[1024];
565 len = sizeof(buf);
566 if (len > s->max_size)
567 len = s->max_size;
568 if (len == 0)
569 return;
570 size = read(s->fd_in, buf, len);
571 if (size == 0) {
572 /* FD has been closed. Remove it from the active list. */
573 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
574 qemu_chr_event(chr, CHR_EVENT_CLOSED);
575 return;
577 if (size > 0) {
578 qemu_chr_read(chr, buf, size);
582 static void fd_chr_update_read_handler(CharDriverState *chr)
584 FDCharDriver *s = chr->opaque;
586 if (s->fd_in >= 0) {
587 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
588 } else {
589 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
590 fd_chr_read, NULL, chr);
595 static void fd_chr_close(struct CharDriverState *chr)
597 FDCharDriver *s = chr->opaque;
599 if (s->fd_in >= 0) {
600 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
601 } else {
602 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
606 qemu_free(s);
607 qemu_chr_event(chr, CHR_EVENT_CLOSED);
610 /* open a character device to a unix fd */
611 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
613 CharDriverState *chr;
614 FDCharDriver *s;
616 chr = qemu_mallocz(sizeof(CharDriverState));
617 s = qemu_mallocz(sizeof(FDCharDriver));
618 s->fd_in = fd_in;
619 s->fd_out = fd_out;
620 chr->opaque = s;
621 chr->chr_write = fd_chr_write;
622 chr->chr_update_read_handler = fd_chr_update_read_handler;
623 chr->chr_close = fd_chr_close;
625 qemu_chr_reset(chr);
627 return chr;
630 static CharDriverState *qemu_chr_open_file_out(QemuOpts *opts)
632 int fd_out;
634 TFR(fd_out = open(qemu_opt_get(opts, "path"),
635 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
636 if (fd_out < 0)
637 return NULL;
638 return qemu_chr_open_fd(-1, fd_out);
641 static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)
643 int fd_in, fd_out;
644 char filename_in[256], filename_out[256];
645 const char *filename = qemu_opt_get(opts, "path");
647 if (filename == NULL) {
648 fprintf(stderr, "chardev: pipe: no filename given\n");
649 return NULL;
652 snprintf(filename_in, 256, "%s.in", filename);
653 snprintf(filename_out, 256, "%s.out", filename);
654 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
655 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
656 if (fd_in < 0 || fd_out < 0) {
657 if (fd_in >= 0)
658 close(fd_in);
659 if (fd_out >= 0)
660 close(fd_out);
661 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
662 if (fd_in < 0)
663 return NULL;
665 return qemu_chr_open_fd(fd_in, fd_out);
669 /* for STDIO, we handle the case where several clients use it
670 (nographic mode) */
672 #define TERM_FIFO_MAX_SIZE 1
674 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
675 static int term_fifo_size;
677 static int stdio_read_poll(void *opaque)
679 CharDriverState *chr = opaque;
681 /* try to flush the queue if needed */
682 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
683 qemu_chr_read(chr, term_fifo, 1);
684 term_fifo_size = 0;
686 /* see if we can absorb more chars */
687 if (term_fifo_size == 0)
688 return 1;
689 else
690 return 0;
693 static void stdio_read(void *opaque)
695 int size;
696 uint8_t buf[1];
697 CharDriverState *chr = opaque;
699 size = read(0, buf, 1);
700 if (size == 0) {
701 /* stdin has been closed. Remove it from the active list. */
702 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
703 qemu_chr_event(chr, CHR_EVENT_CLOSED);
704 return;
706 if (size > 0) {
707 if (qemu_chr_can_read(chr) > 0) {
708 qemu_chr_read(chr, buf, 1);
709 } else if (term_fifo_size == 0) {
710 term_fifo[term_fifo_size++] = buf[0];
715 /* init terminal so that we can grab keys */
716 static struct termios oldtty;
717 static int old_fd0_flags;
718 static int term_atexit_done;
720 static void term_exit(void)
722 tcsetattr (0, TCSANOW, &oldtty);
723 fcntl(0, F_SETFL, old_fd0_flags);
726 static void term_init(QemuOpts *opts)
728 struct termios tty;
730 tcgetattr (0, &tty);
731 oldtty = tty;
732 old_fd0_flags = fcntl(0, F_GETFL);
734 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
735 |INLCR|IGNCR|ICRNL|IXON);
736 tty.c_oflag |= OPOST;
737 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
738 /* if graphical mode, we allow Ctrl-C handling */
739 if (!qemu_opt_get_bool(opts, "signal", display_type != DT_NOGRAPHIC))
740 tty.c_lflag &= ~ISIG;
741 tty.c_cflag &= ~(CSIZE|PARENB);
742 tty.c_cflag |= CS8;
743 tty.c_cc[VMIN] = 1;
744 tty.c_cc[VTIME] = 0;
746 tcsetattr (0, TCSANOW, &tty);
748 if (!term_atexit_done++)
749 atexit(term_exit);
751 fcntl(0, F_SETFL, O_NONBLOCK);
754 static void qemu_chr_close_stdio(struct CharDriverState *chr)
756 term_exit();
757 stdio_nb_clients--;
758 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
759 fd_chr_close(chr);
762 static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)
764 CharDriverState *chr;
766 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
767 return NULL;
768 chr = qemu_chr_open_fd(0, 1);
769 chr->chr_close = qemu_chr_close_stdio;
770 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
771 stdio_nb_clients++;
772 term_init(opts);
774 return chr;
777 #ifdef __sun__
778 /* Once Solaris has openpty(), this is going to be removed. */
779 static int openpty(int *amaster, int *aslave, char *name,
780 struct termios *termp, struct winsize *winp)
782 const char *slave;
783 int mfd = -1, sfd = -1;
785 *amaster = *aslave = -1;
787 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
788 if (mfd < 0)
789 goto err;
791 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
792 goto err;
794 if ((slave = ptsname(mfd)) == NULL)
795 goto err;
797 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
798 goto err;
800 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
801 (termp != NULL && tcgetattr(sfd, termp) < 0))
802 goto err;
804 if (amaster)
805 *amaster = mfd;
806 if (aslave)
807 *aslave = sfd;
808 if (winp)
809 ioctl(sfd, TIOCSWINSZ, winp);
811 return 0;
813 err:
814 if (sfd != -1)
815 close(sfd);
816 close(mfd);
817 return -1;
820 static void cfmakeraw (struct termios *termios_p)
822 termios_p->c_iflag &=
823 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
824 termios_p->c_oflag &= ~OPOST;
825 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
826 termios_p->c_cflag &= ~(CSIZE|PARENB);
827 termios_p->c_cflag |= CS8;
829 termios_p->c_cc[VMIN] = 0;
830 termios_p->c_cc[VTIME] = 0;
832 #endif
834 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
835 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
837 typedef struct {
838 int fd;
839 int connected;
840 int polling;
841 int read_bytes;
842 QEMUTimer *timer;
843 } PtyCharDriver;
845 static void pty_chr_update_read_handler(CharDriverState *chr);
846 static void pty_chr_state(CharDriverState *chr, int connected);
848 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
850 PtyCharDriver *s = chr->opaque;
852 if (!s->connected) {
853 /* guest sends data, check for (re-)connect */
854 pty_chr_update_read_handler(chr);
855 return 0;
857 return send_all(s->fd, buf, len);
860 static int pty_chr_read_poll(void *opaque)
862 CharDriverState *chr = opaque;
863 PtyCharDriver *s = chr->opaque;
865 s->read_bytes = qemu_chr_can_read(chr);
866 return s->read_bytes;
869 static void pty_chr_read(void *opaque)
871 CharDriverState *chr = opaque;
872 PtyCharDriver *s = chr->opaque;
873 int size, len;
874 uint8_t buf[1024];
876 len = sizeof(buf);
877 if (len > s->read_bytes)
878 len = s->read_bytes;
879 if (len == 0)
880 return;
881 size = read(s->fd, buf, len);
882 if ((size == -1 && errno == EIO) ||
883 (size == 0)) {
884 pty_chr_state(chr, 0);
885 return;
887 if (size > 0) {
888 pty_chr_state(chr, 1);
889 qemu_chr_read(chr, buf, size);
893 static void pty_chr_update_read_handler(CharDriverState *chr)
895 PtyCharDriver *s = chr->opaque;
897 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
898 pty_chr_read, NULL, chr);
899 s->polling = 1;
901 * Short timeout here: just need wait long enougth that qemu makes
902 * it through the poll loop once. When reconnected we want a
903 * short timeout so we notice it almost instantly. Otherwise
904 * read() gives us -EIO instantly, making pty_chr_state() reset the
905 * timeout to the normal (much longer) poll interval before the
906 * timer triggers.
908 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
911 static void pty_chr_state(CharDriverState *chr, int connected)
913 PtyCharDriver *s = chr->opaque;
915 if (!connected) {
916 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
917 s->connected = 0;
918 s->polling = 0;
919 /* (re-)connect poll interval for idle guests: once per second.
920 * We check more frequently in case the guests sends data to
921 * the virtual device linked to our pty. */
922 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
923 } else {
924 if (!s->connected)
925 qemu_chr_reset(chr);
926 s->connected = 1;
930 static void pty_chr_timer(void *opaque)
932 struct CharDriverState *chr = opaque;
933 PtyCharDriver *s = chr->opaque;
935 if (s->connected)
936 return;
937 if (s->polling) {
938 /* If we arrive here without polling being cleared due
939 * read returning -EIO, then we are (re-)connected */
940 pty_chr_state(chr, 1);
941 return;
944 /* Next poll ... */
945 pty_chr_update_read_handler(chr);
948 static void pty_chr_close(struct CharDriverState *chr)
950 PtyCharDriver *s = chr->opaque;
952 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
953 close(s->fd);
954 qemu_del_timer(s->timer);
955 qemu_free_timer(s->timer);
956 qemu_free(s);
957 qemu_chr_event(chr, CHR_EVENT_CLOSED);
960 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
962 CharDriverState *chr;
963 PtyCharDriver *s;
964 struct termios tty;
965 int slave_fd, len;
966 #if defined(__OpenBSD__) || defined(__DragonFly__)
967 char pty_name[PATH_MAX];
968 #define q_ptsname(x) pty_name
969 #else
970 char *pty_name = NULL;
971 #define q_ptsname(x) ptsname(x)
972 #endif
974 chr = qemu_mallocz(sizeof(CharDriverState));
975 s = qemu_mallocz(sizeof(PtyCharDriver));
977 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
978 return NULL;
981 /* Set raw attributes on the pty. */
982 tcgetattr(slave_fd, &tty);
983 cfmakeraw(&tty);
984 tcsetattr(slave_fd, TCSAFLUSH, &tty);
985 close(slave_fd);
987 len = strlen(q_ptsname(s->fd)) + 5;
988 chr->filename = qemu_malloc(len);
989 snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
990 qemu_opt_set(opts, "path", q_ptsname(s->fd));
991 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
993 chr->opaque = s;
994 chr->chr_write = pty_chr_write;
995 chr->chr_update_read_handler = pty_chr_update_read_handler;
996 chr->chr_close = pty_chr_close;
998 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
1000 return chr;
1003 static void tty_serial_init(int fd, int speed,
1004 int parity, int data_bits, int stop_bits)
1006 struct termios tty;
1007 speed_t spd;
1009 #if 0
1010 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1011 speed, parity, data_bits, stop_bits);
1012 #endif
1013 tcgetattr (fd, &tty);
1015 #define MARGIN 1.1
1016 if (speed <= 50 * MARGIN)
1017 spd = B50;
1018 else if (speed <= 75 * MARGIN)
1019 spd = B75;
1020 else if (speed <= 300 * MARGIN)
1021 spd = B300;
1022 else if (speed <= 600 * MARGIN)
1023 spd = B600;
1024 else if (speed <= 1200 * MARGIN)
1025 spd = B1200;
1026 else if (speed <= 2400 * MARGIN)
1027 spd = B2400;
1028 else if (speed <= 4800 * MARGIN)
1029 spd = B4800;
1030 else if (speed <= 9600 * MARGIN)
1031 spd = B9600;
1032 else if (speed <= 19200 * MARGIN)
1033 spd = B19200;
1034 else if (speed <= 38400 * MARGIN)
1035 spd = B38400;
1036 else if (speed <= 57600 * MARGIN)
1037 spd = B57600;
1038 else if (speed <= 115200 * MARGIN)
1039 spd = B115200;
1040 else
1041 spd = B115200;
1043 cfsetispeed(&tty, spd);
1044 cfsetospeed(&tty, spd);
1046 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1047 |INLCR|IGNCR|ICRNL|IXON);
1048 tty.c_oflag |= OPOST;
1049 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1050 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1051 switch(data_bits) {
1052 default:
1053 case 8:
1054 tty.c_cflag |= CS8;
1055 break;
1056 case 7:
1057 tty.c_cflag |= CS7;
1058 break;
1059 case 6:
1060 tty.c_cflag |= CS6;
1061 break;
1062 case 5:
1063 tty.c_cflag |= CS5;
1064 break;
1066 switch(parity) {
1067 default:
1068 case 'N':
1069 break;
1070 case 'E':
1071 tty.c_cflag |= PARENB;
1072 break;
1073 case 'O':
1074 tty.c_cflag |= PARENB | PARODD;
1075 break;
1077 if (stop_bits == 2)
1078 tty.c_cflag |= CSTOPB;
1080 tcsetattr (fd, TCSANOW, &tty);
1083 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1085 FDCharDriver *s = chr->opaque;
1087 switch(cmd) {
1088 case CHR_IOCTL_SERIAL_SET_PARAMS:
1090 QEMUSerialSetParams *ssp = arg;
1091 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1092 ssp->data_bits, ssp->stop_bits);
1094 break;
1095 case CHR_IOCTL_SERIAL_SET_BREAK:
1097 int enable = *(int *)arg;
1098 if (enable)
1099 tcsendbreak(s->fd_in, 1);
1101 break;
1102 case CHR_IOCTL_SERIAL_GET_TIOCM:
1104 int sarg = 0;
1105 int *targ = (int *)arg;
1106 ioctl(s->fd_in, TIOCMGET, &sarg);
1107 *targ = 0;
1108 if (sarg & TIOCM_CTS)
1109 *targ |= CHR_TIOCM_CTS;
1110 if (sarg & TIOCM_CAR)
1111 *targ |= CHR_TIOCM_CAR;
1112 if (sarg & TIOCM_DSR)
1113 *targ |= CHR_TIOCM_DSR;
1114 if (sarg & TIOCM_RI)
1115 *targ |= CHR_TIOCM_RI;
1116 if (sarg & TIOCM_DTR)
1117 *targ |= CHR_TIOCM_DTR;
1118 if (sarg & TIOCM_RTS)
1119 *targ |= CHR_TIOCM_RTS;
1121 break;
1122 case CHR_IOCTL_SERIAL_SET_TIOCM:
1124 int sarg = *(int *)arg;
1125 int targ = 0;
1126 ioctl(s->fd_in, TIOCMGET, &targ);
1127 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1128 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1129 if (sarg & CHR_TIOCM_CTS)
1130 targ |= TIOCM_CTS;
1131 if (sarg & CHR_TIOCM_CAR)
1132 targ |= TIOCM_CAR;
1133 if (sarg & CHR_TIOCM_DSR)
1134 targ |= TIOCM_DSR;
1135 if (sarg & CHR_TIOCM_RI)
1136 targ |= TIOCM_RI;
1137 if (sarg & CHR_TIOCM_DTR)
1138 targ |= TIOCM_DTR;
1139 if (sarg & CHR_TIOCM_RTS)
1140 targ |= TIOCM_RTS;
1141 ioctl(s->fd_in, TIOCMSET, &targ);
1143 break;
1144 default:
1145 return -ENOTSUP;
1147 return 0;
1150 static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
1152 const char *filename = qemu_opt_get(opts, "path");
1153 CharDriverState *chr;
1154 int fd;
1156 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
1157 tty_serial_init(fd, 115200, 'N', 8, 1);
1158 chr = qemu_chr_open_fd(fd, fd);
1159 if (!chr) {
1160 close(fd);
1161 return NULL;
1163 chr->chr_ioctl = tty_serial_ioctl;
1164 qemu_chr_reset(chr);
1165 return chr;
1167 #else /* ! __linux__ && ! __sun__ */
1168 static CharDriverState *qemu_chr_open_pty(void)
1170 return NULL;
1172 #endif /* __linux__ || __sun__ */
1174 #if defined(__linux__)
1175 typedef struct {
1176 int fd;
1177 int mode;
1178 } ParallelCharDriver;
1180 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1182 if (s->mode != mode) {
1183 int m = mode;
1184 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1185 return 0;
1186 s->mode = mode;
1188 return 1;
1191 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1193 ParallelCharDriver *drv = chr->opaque;
1194 int fd = drv->fd;
1195 uint8_t b;
1197 switch(cmd) {
1198 case CHR_IOCTL_PP_READ_DATA:
1199 if (ioctl(fd, PPRDATA, &b) < 0)
1200 return -ENOTSUP;
1201 *(uint8_t *)arg = b;
1202 break;
1203 case CHR_IOCTL_PP_WRITE_DATA:
1204 b = *(uint8_t *)arg;
1205 if (ioctl(fd, PPWDATA, &b) < 0)
1206 return -ENOTSUP;
1207 break;
1208 case CHR_IOCTL_PP_READ_CONTROL:
1209 if (ioctl(fd, PPRCONTROL, &b) < 0)
1210 return -ENOTSUP;
1211 /* Linux gives only the lowest bits, and no way to know data
1212 direction! For better compatibility set the fixed upper
1213 bits. */
1214 *(uint8_t *)arg = b | 0xc0;
1215 break;
1216 case CHR_IOCTL_PP_WRITE_CONTROL:
1217 b = *(uint8_t *)arg;
1218 if (ioctl(fd, PPWCONTROL, &b) < 0)
1219 return -ENOTSUP;
1220 break;
1221 case CHR_IOCTL_PP_READ_STATUS:
1222 if (ioctl(fd, PPRSTATUS, &b) < 0)
1223 return -ENOTSUP;
1224 *(uint8_t *)arg = b;
1225 break;
1226 case CHR_IOCTL_PP_DATA_DIR:
1227 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1228 return -ENOTSUP;
1229 break;
1230 case CHR_IOCTL_PP_EPP_READ_ADDR:
1231 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1232 struct ParallelIOArg *parg = arg;
1233 int n = read(fd, parg->buffer, parg->count);
1234 if (n != parg->count) {
1235 return -EIO;
1238 break;
1239 case CHR_IOCTL_PP_EPP_READ:
1240 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1241 struct ParallelIOArg *parg = arg;
1242 int n = read(fd, parg->buffer, parg->count);
1243 if (n != parg->count) {
1244 return -EIO;
1247 break;
1248 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1249 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1250 struct ParallelIOArg *parg = arg;
1251 int n = write(fd, parg->buffer, parg->count);
1252 if (n != parg->count) {
1253 return -EIO;
1256 break;
1257 case CHR_IOCTL_PP_EPP_WRITE:
1258 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1259 struct ParallelIOArg *parg = arg;
1260 int n = write(fd, parg->buffer, parg->count);
1261 if (n != parg->count) {
1262 return -EIO;
1265 break;
1266 default:
1267 return -ENOTSUP;
1269 return 0;
1272 static void pp_close(CharDriverState *chr)
1274 ParallelCharDriver *drv = chr->opaque;
1275 int fd = drv->fd;
1277 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1278 ioctl(fd, PPRELEASE);
1279 close(fd);
1280 qemu_free(drv);
1281 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1284 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1286 const char *filename = qemu_opt_get(opts, "path");
1287 CharDriverState *chr;
1288 ParallelCharDriver *drv;
1289 int fd;
1291 TFR(fd = open(filename, O_RDWR));
1292 if (fd < 0)
1293 return NULL;
1295 if (ioctl(fd, PPCLAIM) < 0) {
1296 close(fd);
1297 return NULL;
1300 drv = qemu_mallocz(sizeof(ParallelCharDriver));
1301 drv->fd = fd;
1302 drv->mode = IEEE1284_MODE_COMPAT;
1304 chr = qemu_mallocz(sizeof(CharDriverState));
1305 chr->chr_write = null_chr_write;
1306 chr->chr_ioctl = pp_ioctl;
1307 chr->chr_close = pp_close;
1308 chr->opaque = drv;
1310 qemu_chr_reset(chr);
1312 return chr;
1314 #endif /* __linux__ */
1316 #if defined(__FreeBSD__) || defined(__DragonFly__)
1317 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1319 int fd = (int)chr->opaque;
1320 uint8_t b;
1322 switch(cmd) {
1323 case CHR_IOCTL_PP_READ_DATA:
1324 if (ioctl(fd, PPIGDATA, &b) < 0)
1325 return -ENOTSUP;
1326 *(uint8_t *)arg = b;
1327 break;
1328 case CHR_IOCTL_PP_WRITE_DATA:
1329 b = *(uint8_t *)arg;
1330 if (ioctl(fd, PPISDATA, &b) < 0)
1331 return -ENOTSUP;
1332 break;
1333 case CHR_IOCTL_PP_READ_CONTROL:
1334 if (ioctl(fd, PPIGCTRL, &b) < 0)
1335 return -ENOTSUP;
1336 *(uint8_t *)arg = b;
1337 break;
1338 case CHR_IOCTL_PP_WRITE_CONTROL:
1339 b = *(uint8_t *)arg;
1340 if (ioctl(fd, PPISCTRL, &b) < 0)
1341 return -ENOTSUP;
1342 break;
1343 case CHR_IOCTL_PP_READ_STATUS:
1344 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1345 return -ENOTSUP;
1346 *(uint8_t *)arg = b;
1347 break;
1348 default:
1349 return -ENOTSUP;
1351 return 0;
1354 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1356 const char *filename = qemu_opt_get(opts, "path");
1357 CharDriverState *chr;
1358 int fd;
1360 fd = open(filename, O_RDWR);
1361 if (fd < 0)
1362 return NULL;
1364 chr = qemu_mallocz(sizeof(CharDriverState));
1365 chr->opaque = (void *)fd;
1366 chr->chr_write = null_chr_write;
1367 chr->chr_ioctl = pp_ioctl;
1368 return chr;
1370 #endif
1372 #else /* _WIN32 */
1374 typedef struct {
1375 int max_size;
1376 HANDLE hcom, hrecv, hsend;
1377 OVERLAPPED orecv, osend;
1378 BOOL fpipe;
1379 DWORD len;
1380 } WinCharState;
1382 #define NSENDBUF 2048
1383 #define NRECVBUF 2048
1384 #define MAXCONNECT 1
1385 #define NTIMEOUT 5000
1387 static int win_chr_poll(void *opaque);
1388 static int win_chr_pipe_poll(void *opaque);
1390 static void win_chr_close(CharDriverState *chr)
1392 WinCharState *s = chr->opaque;
1394 if (s->hsend) {
1395 CloseHandle(s->hsend);
1396 s->hsend = NULL;
1398 if (s->hrecv) {
1399 CloseHandle(s->hrecv);
1400 s->hrecv = NULL;
1402 if (s->hcom) {
1403 CloseHandle(s->hcom);
1404 s->hcom = NULL;
1406 if (s->fpipe)
1407 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1408 else
1409 qemu_del_polling_cb(win_chr_poll, chr);
1411 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1414 static int win_chr_init(CharDriverState *chr, const char *filename)
1416 WinCharState *s = chr->opaque;
1417 COMMCONFIG comcfg;
1418 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1419 COMSTAT comstat;
1420 DWORD size;
1421 DWORD err;
1423 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1424 if (!s->hsend) {
1425 fprintf(stderr, "Failed CreateEvent\n");
1426 goto fail;
1428 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1429 if (!s->hrecv) {
1430 fprintf(stderr, "Failed CreateEvent\n");
1431 goto fail;
1434 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1435 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1436 if (s->hcom == INVALID_HANDLE_VALUE) {
1437 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1438 s->hcom = NULL;
1439 goto fail;
1442 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1443 fprintf(stderr, "Failed SetupComm\n");
1444 goto fail;
1447 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1448 size = sizeof(COMMCONFIG);
1449 GetDefaultCommConfig(filename, &comcfg, &size);
1450 comcfg.dcb.DCBlength = sizeof(DCB);
1451 CommConfigDialog(filename, NULL, &comcfg);
1453 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1454 fprintf(stderr, "Failed SetCommState\n");
1455 goto fail;
1458 if (!SetCommMask(s->hcom, EV_ERR)) {
1459 fprintf(stderr, "Failed SetCommMask\n");
1460 goto fail;
1463 cto.ReadIntervalTimeout = MAXDWORD;
1464 if (!SetCommTimeouts(s->hcom, &cto)) {
1465 fprintf(stderr, "Failed SetCommTimeouts\n");
1466 goto fail;
1469 if (!ClearCommError(s->hcom, &err, &comstat)) {
1470 fprintf(stderr, "Failed ClearCommError\n");
1471 goto fail;
1473 qemu_add_polling_cb(win_chr_poll, chr);
1474 return 0;
1476 fail:
1477 win_chr_close(chr);
1478 return -1;
1481 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1483 WinCharState *s = chr->opaque;
1484 DWORD len, ret, size, err;
1486 len = len1;
1487 ZeroMemory(&s->osend, sizeof(s->osend));
1488 s->osend.hEvent = s->hsend;
1489 while (len > 0) {
1490 if (s->hsend)
1491 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1492 else
1493 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1494 if (!ret) {
1495 err = GetLastError();
1496 if (err == ERROR_IO_PENDING) {
1497 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1498 if (ret) {
1499 buf += size;
1500 len -= size;
1501 } else {
1502 break;
1504 } else {
1505 break;
1507 } else {
1508 buf += size;
1509 len -= size;
1512 return len1 - len;
1515 static int win_chr_read_poll(CharDriverState *chr)
1517 WinCharState *s = chr->opaque;
1519 s->max_size = qemu_chr_can_read(chr);
1520 return s->max_size;
1523 static void win_chr_readfile(CharDriverState *chr)
1525 WinCharState *s = chr->opaque;
1526 int ret, err;
1527 uint8_t buf[1024];
1528 DWORD size;
1530 ZeroMemory(&s->orecv, sizeof(s->orecv));
1531 s->orecv.hEvent = s->hrecv;
1532 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1533 if (!ret) {
1534 err = GetLastError();
1535 if (err == ERROR_IO_PENDING) {
1536 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1540 if (size > 0) {
1541 qemu_chr_read(chr, buf, size);
1545 static void win_chr_read(CharDriverState *chr)
1547 WinCharState *s = chr->opaque;
1549 if (s->len > s->max_size)
1550 s->len = s->max_size;
1551 if (s->len == 0)
1552 return;
1554 win_chr_readfile(chr);
1557 static int win_chr_poll(void *opaque)
1559 CharDriverState *chr = opaque;
1560 WinCharState *s = chr->opaque;
1561 COMSTAT status;
1562 DWORD comerr;
1564 ClearCommError(s->hcom, &comerr, &status);
1565 if (status.cbInQue > 0) {
1566 s->len = status.cbInQue;
1567 win_chr_read_poll(chr);
1568 win_chr_read(chr);
1569 return 1;
1571 return 0;
1574 static CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1576 const char *filename = qemu_opt_get(opts, "path");
1577 CharDriverState *chr;
1578 WinCharState *s;
1580 chr = qemu_mallocz(sizeof(CharDriverState));
1581 s = qemu_mallocz(sizeof(WinCharState));
1582 chr->opaque = s;
1583 chr->chr_write = win_chr_write;
1584 chr->chr_close = win_chr_close;
1586 if (win_chr_init(chr, filename) < 0) {
1587 free(s);
1588 free(chr);
1589 return NULL;
1591 qemu_chr_reset(chr);
1592 return chr;
1595 static int win_chr_pipe_poll(void *opaque)
1597 CharDriverState *chr = opaque;
1598 WinCharState *s = chr->opaque;
1599 DWORD size;
1601 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1602 if (size > 0) {
1603 s->len = size;
1604 win_chr_read_poll(chr);
1605 win_chr_read(chr);
1606 return 1;
1608 return 0;
1611 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1613 WinCharState *s = chr->opaque;
1614 OVERLAPPED ov;
1615 int ret;
1616 DWORD size;
1617 char openname[256];
1619 s->fpipe = TRUE;
1621 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1622 if (!s->hsend) {
1623 fprintf(stderr, "Failed CreateEvent\n");
1624 goto fail;
1626 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1627 if (!s->hrecv) {
1628 fprintf(stderr, "Failed CreateEvent\n");
1629 goto fail;
1632 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1633 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1634 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1635 PIPE_WAIT,
1636 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1637 if (s->hcom == INVALID_HANDLE_VALUE) {
1638 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1639 s->hcom = NULL;
1640 goto fail;
1643 ZeroMemory(&ov, sizeof(ov));
1644 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1645 ret = ConnectNamedPipe(s->hcom, &ov);
1646 if (ret) {
1647 fprintf(stderr, "Failed ConnectNamedPipe\n");
1648 goto fail;
1651 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1652 if (!ret) {
1653 fprintf(stderr, "Failed GetOverlappedResult\n");
1654 if (ov.hEvent) {
1655 CloseHandle(ov.hEvent);
1656 ov.hEvent = NULL;
1658 goto fail;
1661 if (ov.hEvent) {
1662 CloseHandle(ov.hEvent);
1663 ov.hEvent = NULL;
1665 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1666 return 0;
1668 fail:
1669 win_chr_close(chr);
1670 return -1;
1674 static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
1676 const char *filename = qemu_opt_get(opts, "path");
1677 CharDriverState *chr;
1678 WinCharState *s;
1680 chr = qemu_mallocz(sizeof(CharDriverState));
1681 s = qemu_mallocz(sizeof(WinCharState));
1682 chr->opaque = s;
1683 chr->chr_write = win_chr_write;
1684 chr->chr_close = win_chr_close;
1686 if (win_chr_pipe_init(chr, filename) < 0) {
1687 free(s);
1688 free(chr);
1689 return NULL;
1691 qemu_chr_reset(chr);
1692 return chr;
1695 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1697 CharDriverState *chr;
1698 WinCharState *s;
1700 chr = qemu_mallocz(sizeof(CharDriverState));
1701 s = qemu_mallocz(sizeof(WinCharState));
1702 s->hcom = fd_out;
1703 chr->opaque = s;
1704 chr->chr_write = win_chr_write;
1705 qemu_chr_reset(chr);
1706 return chr;
1709 static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
1711 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1714 static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
1716 const char *file_out = qemu_opt_get(opts, "path");
1717 HANDLE fd_out;
1719 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1720 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1721 if (fd_out == INVALID_HANDLE_VALUE)
1722 return NULL;
1724 return qemu_chr_open_win_file(fd_out);
1726 #endif /* !_WIN32 */
1728 /***********************************************************/
1729 /* UDP Net console */
1731 typedef struct {
1732 int fd;
1733 uint8_t buf[1024];
1734 int bufcnt;
1735 int bufptr;
1736 int max_size;
1737 } NetCharDriver;
1739 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1741 NetCharDriver *s = chr->opaque;
1743 return send(s->fd, (const void *)buf, len, 0);
1746 static int udp_chr_read_poll(void *opaque)
1748 CharDriverState *chr = opaque;
1749 NetCharDriver *s = chr->opaque;
1751 s->max_size = qemu_chr_can_read(chr);
1753 /* If there were any stray characters in the queue process them
1754 * first
1756 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1757 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1758 s->bufptr++;
1759 s->max_size = qemu_chr_can_read(chr);
1761 return s->max_size;
1764 static void udp_chr_read(void *opaque)
1766 CharDriverState *chr = opaque;
1767 NetCharDriver *s = chr->opaque;
1769 if (s->max_size == 0)
1770 return;
1771 s->bufcnt = recv(s->fd, (void *)s->buf, sizeof(s->buf), 0);
1772 s->bufptr = s->bufcnt;
1773 if (s->bufcnt <= 0)
1774 return;
1776 s->bufptr = 0;
1777 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1778 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1779 s->bufptr++;
1780 s->max_size = qemu_chr_can_read(chr);
1784 static void udp_chr_update_read_handler(CharDriverState *chr)
1786 NetCharDriver *s = chr->opaque;
1788 if (s->fd >= 0) {
1789 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
1790 udp_chr_read, NULL, chr);
1794 static void udp_chr_close(CharDriverState *chr)
1796 NetCharDriver *s = chr->opaque;
1797 if (s->fd >= 0) {
1798 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1799 closesocket(s->fd);
1801 qemu_free(s);
1802 qemu_chr_event(chr, CHR_EVENT_CLOSED);
1805 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
1807 CharDriverState *chr = NULL;
1808 NetCharDriver *s = NULL;
1809 int fd = -1;
1811 chr = qemu_mallocz(sizeof(CharDriverState));
1812 s = qemu_mallocz(sizeof(NetCharDriver));
1814 fd = inet_dgram_opts(opts);
1815 if (fd < 0) {
1816 fprintf(stderr, "inet_dgram_opts failed\n");
1817 goto return_err;
1820 s->fd = fd;
1821 s->bufcnt = 0;
1822 s->bufptr = 0;
1823 chr->opaque = s;
1824 chr->chr_write = udp_chr_write;
1825 chr->chr_update_read_handler = udp_chr_update_read_handler;
1826 chr->chr_close = udp_chr_close;
1827 return chr;
1829 return_err:
1830 if (chr)
1831 free(chr);
1832 if (s)
1833 free(s);
1834 if (fd >= 0)
1835 closesocket(fd);
1836 return NULL;
1839 /***********************************************************/
1840 /* TCP Net console */
1842 typedef struct {
1843 int fd, listen_fd;
1844 int connected;
1845 int max_size;
1846 int do_telnetopt;
1847 int do_nodelay;
1848 int is_unix;
1849 int msgfd;
1850 } TCPCharDriver;
1852 static void tcp_chr_accept(void *opaque);
1854 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1856 TCPCharDriver *s = chr->opaque;
1857 if (s->connected) {
1858 return send_all(s->fd, buf, len);
1859 } else {
1860 /* XXX: indicate an error ? */
1861 return len;
1865 static int tcp_chr_read_poll(void *opaque)
1867 CharDriverState *chr = opaque;
1868 TCPCharDriver *s = chr->opaque;
1869 if (!s->connected)
1870 return 0;
1871 s->max_size = qemu_chr_can_read(chr);
1872 return s->max_size;
1875 #define IAC 255
1876 #define IAC_BREAK 243
1877 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
1878 TCPCharDriver *s,
1879 uint8_t *buf, int *size)
1881 /* Handle any telnet client's basic IAC options to satisfy char by
1882 * char mode with no echo. All IAC options will be removed from
1883 * the buf and the do_telnetopt variable will be used to track the
1884 * state of the width of the IAC information.
1886 * IAC commands come in sets of 3 bytes with the exception of the
1887 * "IAC BREAK" command and the double IAC.
1890 int i;
1891 int j = 0;
1893 for (i = 0; i < *size; i++) {
1894 if (s->do_telnetopt > 1) {
1895 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
1896 /* Double IAC means send an IAC */
1897 if (j != i)
1898 buf[j] = buf[i];
1899 j++;
1900 s->do_telnetopt = 1;
1901 } else {
1902 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
1903 /* Handle IAC break commands by sending a serial break */
1904 qemu_chr_event(chr, CHR_EVENT_BREAK);
1905 s->do_telnetopt++;
1907 s->do_telnetopt++;
1909 if (s->do_telnetopt >= 4) {
1910 s->do_telnetopt = 1;
1912 } else {
1913 if ((unsigned char)buf[i] == IAC) {
1914 s->do_telnetopt = 2;
1915 } else {
1916 if (j != i)
1917 buf[j] = buf[i];
1918 j++;
1922 *size = j;
1925 static int tcp_get_msgfd(CharDriverState *chr)
1927 TCPCharDriver *s = chr->opaque;
1929 return s->msgfd;
1932 #ifndef _WIN32
1933 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
1935 TCPCharDriver *s = chr->opaque;
1936 struct cmsghdr *cmsg;
1938 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
1939 int fd;
1941 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
1942 cmsg->cmsg_level != SOL_SOCKET ||
1943 cmsg->cmsg_type != SCM_RIGHTS)
1944 continue;
1946 fd = *((int *)CMSG_DATA(cmsg));
1947 if (fd < 0)
1948 continue;
1950 if (s->msgfd != -1)
1951 close(s->msgfd);
1952 s->msgfd = fd;
1956 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
1958 TCPCharDriver *s = chr->opaque;
1959 struct msghdr msg = { NULL, };
1960 struct iovec iov[1];
1961 union {
1962 struct cmsghdr cmsg;
1963 char control[CMSG_SPACE(sizeof(int))];
1964 } msg_control;
1965 ssize_t ret;
1967 iov[0].iov_base = buf;
1968 iov[0].iov_len = len;
1970 msg.msg_iov = iov;
1971 msg.msg_iovlen = 1;
1972 msg.msg_control = &msg_control;
1973 msg.msg_controllen = sizeof(msg_control);
1975 ret = recvmsg(s->fd, &msg, 0);
1976 if (ret > 0 && s->is_unix)
1977 unix_process_msgfd(chr, &msg);
1979 return ret;
1981 #else
1982 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
1984 TCPCharDriver *s = chr->opaque;
1985 return recv(s->fd, buf, len, 0);
1987 #endif
1989 static void tcp_chr_read(void *opaque)
1991 CharDriverState *chr = opaque;
1992 TCPCharDriver *s = chr->opaque;
1993 uint8_t buf[1024];
1994 int len, size;
1996 if (!s->connected || s->max_size <= 0)
1997 return;
1998 len = sizeof(buf);
1999 if (len > s->max_size)
2000 len = s->max_size;
2001 size = tcp_chr_recv(chr, (void *)buf, len);
2002 if (size == 0) {
2003 /* connection closed */
2004 s->connected = 0;
2005 if (s->listen_fd >= 0) {
2006 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2008 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2009 closesocket(s->fd);
2010 s->fd = -1;
2011 qemu_chr_event(chr, CHR_EVENT_CLOSED);
2012 } else if (size > 0) {
2013 if (s->do_telnetopt)
2014 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2015 if (size > 0)
2016 qemu_chr_read(chr, buf, size);
2017 if (s->msgfd != -1) {
2018 close(s->msgfd);
2019 s->msgfd = -1;
2024 static void tcp_chr_connect(void *opaque)
2026 CharDriverState *chr = opaque;
2027 TCPCharDriver *s = chr->opaque;
2029 s->connected = 1;
2030 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2031 tcp_chr_read, NULL, chr);
2032 qemu_chr_reset(chr);
2035 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2036 static void tcp_chr_telnet_init(int fd)
2038 char buf[3];
2039 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2040 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2041 send(fd, (char *)buf, 3, 0);
2042 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2043 send(fd, (char *)buf, 3, 0);
2044 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2045 send(fd, (char *)buf, 3, 0);
2046 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2047 send(fd, (char *)buf, 3, 0);
2050 static void socket_set_nodelay(int fd)
2052 int val = 1;
2053 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2056 static void tcp_chr_accept(void *opaque)
2058 CharDriverState *chr = opaque;
2059 TCPCharDriver *s = chr->opaque;
2060 struct sockaddr_in saddr;
2061 #ifndef _WIN32
2062 struct sockaddr_un uaddr;
2063 #endif
2064 struct sockaddr *addr;
2065 socklen_t len;
2066 int fd;
2068 for(;;) {
2069 #ifndef _WIN32
2070 if (s->is_unix) {
2071 len = sizeof(uaddr);
2072 addr = (struct sockaddr *)&uaddr;
2073 } else
2074 #endif
2076 len = sizeof(saddr);
2077 addr = (struct sockaddr *)&saddr;
2079 fd = accept(s->listen_fd, addr, &len);
2080 if (fd < 0 && errno != EINTR) {
2081 return;
2082 } else if (fd >= 0) {
2083 if (s->do_telnetopt)
2084 tcp_chr_telnet_init(fd);
2085 break;
2088 socket_set_nonblock(fd);
2089 if (s->do_nodelay)
2090 socket_set_nodelay(fd);
2091 s->fd = fd;
2092 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2093 tcp_chr_connect(chr);
2096 static void tcp_chr_close(CharDriverState *chr)
2098 TCPCharDriver *s = chr->opaque;
2099 if (s->fd >= 0) {
2100 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2101 closesocket(s->fd);
2103 if (s->listen_fd >= 0) {
2104 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2105 closesocket(s->listen_fd);
2107 qemu_free(s);
2108 qemu_chr_event(chr, CHR_EVENT_CLOSED);
2111 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2113 CharDriverState *chr = NULL;
2114 TCPCharDriver *s = NULL;
2115 int fd = -1;
2116 int is_listen;
2117 int is_waitconnect;
2118 int do_nodelay;
2119 int is_unix;
2120 int is_telnet;
2122 is_listen = qemu_opt_get_bool(opts, "server", 0);
2123 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2124 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2125 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2126 is_unix = qemu_opt_get(opts, "path") != NULL;
2127 if (!is_listen)
2128 is_waitconnect = 0;
2130 chr = qemu_mallocz(sizeof(CharDriverState));
2131 s = qemu_mallocz(sizeof(TCPCharDriver));
2133 if (is_unix) {
2134 if (is_listen) {
2135 fd = unix_listen_opts(opts);
2136 } else {
2137 fd = unix_connect_opts(opts);
2139 } else {
2140 if (is_listen) {
2141 fd = inet_listen_opts(opts, 0);
2142 } else {
2143 fd = inet_connect_opts(opts);
2146 if (fd < 0)
2147 goto fail;
2149 if (!is_waitconnect)
2150 socket_set_nonblock(fd);
2152 s->connected = 0;
2153 s->fd = -1;
2154 s->listen_fd = -1;
2155 s->msgfd = -1;
2156 s->is_unix = is_unix;
2157 s->do_nodelay = do_nodelay && !is_unix;
2159 chr->opaque = s;
2160 chr->chr_write = tcp_chr_write;
2161 chr->chr_close = tcp_chr_close;
2162 chr->get_msgfd = tcp_get_msgfd;
2164 if (is_listen) {
2165 s->listen_fd = fd;
2166 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2167 if (is_telnet)
2168 s->do_telnetopt = 1;
2170 } else {
2171 s->connected = 1;
2172 s->fd = fd;
2173 socket_set_nodelay(fd);
2174 tcp_chr_connect(chr);
2177 /* for "info chardev" monitor command */
2178 chr->filename = qemu_malloc(256);
2179 if (is_unix) {
2180 snprintf(chr->filename, 256, "unix:%s%s",
2181 qemu_opt_get(opts, "path"),
2182 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2183 } else if (is_telnet) {
2184 snprintf(chr->filename, 256, "telnet:%s:%s%s",
2185 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2186 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2187 } else {
2188 snprintf(chr->filename, 256, "tcp:%s:%s%s",
2189 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2190 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2193 if (is_listen && is_waitconnect) {
2194 printf("QEMU waiting for connection on: %s\n",
2195 chr->filename);
2196 tcp_chr_accept(chr);
2197 socket_set_nonblock(s->listen_fd);
2199 return chr;
2201 fail:
2202 if (fd >= 0)
2203 closesocket(fd);
2204 qemu_free(s);
2205 qemu_free(chr);
2206 return NULL;
2209 static QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2211 char host[65], port[33], width[8], height[8];
2212 int pos;
2213 const char *p;
2214 QemuOpts *opts;
2216 opts = qemu_opts_create(&qemu_chardev_opts, label, 1);
2217 if (NULL == opts)
2218 return NULL;
2220 if (strstart(filename, "mon:", &p)) {
2221 filename = p;
2222 qemu_opt_set(opts, "mux", "on");
2225 if (strcmp(filename, "null") == 0 ||
2226 strcmp(filename, "pty") == 0 ||
2227 strcmp(filename, "msmouse") == 0 ||
2228 strcmp(filename, "braille") == 0 ||
2229 strcmp(filename, "stdio") == 0) {
2230 qemu_opt_set(opts, "backend", filename);
2231 return opts;
2233 if (strstart(filename, "vc", &p)) {
2234 qemu_opt_set(opts, "backend", "vc");
2235 if (*p == ':') {
2236 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2237 /* pixels */
2238 qemu_opt_set(opts, "width", width);
2239 qemu_opt_set(opts, "height", height);
2240 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2241 /* chars */
2242 qemu_opt_set(opts, "cols", width);
2243 qemu_opt_set(opts, "rows", height);
2244 } else {
2245 goto fail;
2248 return opts;
2250 if (strcmp(filename, "con:") == 0) {
2251 qemu_opt_set(opts, "backend", "console");
2252 return opts;
2254 if (strstart(filename, "COM", NULL)) {
2255 qemu_opt_set(opts, "backend", "serial");
2256 qemu_opt_set(opts, "path", filename);
2257 return opts;
2259 if (strstart(filename, "file:", &p)) {
2260 qemu_opt_set(opts, "backend", "file");
2261 qemu_opt_set(opts, "path", p);
2262 return opts;
2264 if (strstart(filename, "pipe:", &p)) {
2265 qemu_opt_set(opts, "backend", "pipe");
2266 qemu_opt_set(opts, "path", p);
2267 return opts;
2269 if (strstart(filename, "tcp:", &p) ||
2270 strstart(filename, "telnet:", &p)) {
2271 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2272 host[0] = 0;
2273 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2274 goto fail;
2276 qemu_opt_set(opts, "backend", "socket");
2277 qemu_opt_set(opts, "host", host);
2278 qemu_opt_set(opts, "port", port);
2279 if (p[pos] == ',') {
2280 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2281 goto fail;
2283 if (strstart(filename, "telnet:", &p))
2284 qemu_opt_set(opts, "telnet", "on");
2285 return opts;
2287 if (strstart(filename, "udp:", &p)) {
2288 qemu_opt_set(opts, "backend", "udp");
2289 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2290 host[0] = 0;
2291 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2292 fprintf(stderr, "udp #1\n");
2293 goto fail;
2296 qemu_opt_set(opts, "host", host);
2297 qemu_opt_set(opts, "port", port);
2298 if (p[pos] == '@') {
2299 p += pos + 1;
2300 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2301 host[0] = 0;
2302 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2303 fprintf(stderr, "udp #2\n");
2304 goto fail;
2307 qemu_opt_set(opts, "localaddr", host);
2308 qemu_opt_set(opts, "localport", port);
2310 return opts;
2312 if (strstart(filename, "unix:", &p)) {
2313 qemu_opt_set(opts, "backend", "socket");
2314 if (qemu_opts_do_parse(opts, p, "path") != 0)
2315 goto fail;
2316 return opts;
2318 if (strstart(filename, "/dev/parport", NULL) ||
2319 strstart(filename, "/dev/ppi", NULL)) {
2320 qemu_opt_set(opts, "backend", "parport");
2321 qemu_opt_set(opts, "path", filename);
2322 return opts;
2324 if (strstart(filename, "/dev/", NULL)) {
2325 qemu_opt_set(opts, "backend", "tty");
2326 qemu_opt_set(opts, "path", filename);
2327 return opts;
2330 fail:
2331 fprintf(stderr, "%s: fail on \"%s\"\n", __FUNCTION__, filename);
2332 qemu_opts_del(opts);
2333 return NULL;
2336 static const struct {
2337 const char *name;
2338 CharDriverState *(*open)(QemuOpts *opts);
2339 } backend_table[] = {
2340 { .name = "null", .open = qemu_chr_open_null },
2341 { .name = "socket", .open = qemu_chr_open_socket },
2342 { .name = "udp", .open = qemu_chr_open_udp },
2343 { .name = "msmouse", .open = qemu_chr_open_msmouse },
2344 { .name = "vc", .open = text_console_init },
2345 #ifdef _WIN32
2346 { .name = "file", .open = qemu_chr_open_win_file_out },
2347 { .name = "pipe", .open = qemu_chr_open_win_pipe },
2348 { .name = "console", .open = qemu_chr_open_win_con },
2349 { .name = "serial", .open = qemu_chr_open_win },
2350 #else
2351 { .name = "file", .open = qemu_chr_open_file_out },
2352 { .name = "pipe", .open = qemu_chr_open_pipe },
2353 { .name = "pty", .open = qemu_chr_open_pty },
2354 { .name = "stdio", .open = qemu_chr_open_stdio },
2355 #endif
2356 #ifdef CONFIG_BRLAPI
2357 { .name = "braille", .open = chr_baum_init },
2358 #endif
2359 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2360 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
2361 { .name = "tty", .open = qemu_chr_open_tty },
2362 #endif
2363 #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__)
2364 { .name = "parport", .open = qemu_chr_open_pp },
2365 #endif
2368 CharDriverState *qemu_chr_open_opts(QemuOpts *opts,
2369 void (*init)(struct CharDriverState *s))
2371 CharDriverState *chr;
2372 int i;
2374 if (qemu_opts_id(opts) == NULL) {
2375 fprintf(stderr, "chardev: no id specified\n");
2376 return NULL;
2379 for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
2380 if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
2381 break;
2383 if (i == ARRAY_SIZE(backend_table)) {
2384 fprintf(stderr, "chardev: backend \"%s\" not found\n",
2385 qemu_opt_get(opts, "backend"));
2386 return NULL;
2389 chr = backend_table[i].open(opts);
2390 if (!chr) {
2391 fprintf(stderr, "chardev: opening backend \"%s\" failed\n",
2392 qemu_opt_get(opts, "backend"));
2393 return NULL;
2396 if (!chr->filename)
2397 chr->filename = qemu_strdup(qemu_opt_get(opts, "backend"));
2398 chr->init = init;
2399 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2401 if (qemu_opt_get_bool(opts, "mux", 0)) {
2402 CharDriverState *base = chr;
2403 int len = strlen(qemu_opts_id(opts)) + 6;
2404 base->label = qemu_malloc(len);
2405 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
2406 chr = qemu_chr_open_mux(base);
2407 chr->filename = base->filename;
2408 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2410 chr->label = qemu_strdup(qemu_opts_id(opts));
2411 return chr;
2414 CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2416 const char *p;
2417 CharDriverState *chr;
2418 QemuOpts *opts;
2420 if (strstart(filename, "chardev:", &p)) {
2421 return qemu_chr_find(p);
2424 opts = qemu_chr_parse_compat(label, filename);
2425 if (!opts)
2426 return NULL;
2428 chr = qemu_chr_open_opts(opts, init);
2429 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
2430 monitor_init(chr, MONITOR_USE_READLINE);
2432 return chr;
2435 void qemu_chr_close(CharDriverState *chr)
2437 QTAILQ_REMOVE(&chardevs, chr, next);
2438 if (chr->chr_close)
2439 chr->chr_close(chr);
2440 qemu_free(chr->filename);
2441 qemu_free(chr->label);
2442 qemu_free(chr);
2445 void qemu_chr_info(Monitor *mon)
2447 CharDriverState *chr;
2449 QTAILQ_FOREACH(chr, &chardevs, next) {
2450 monitor_printf(mon, "%s: filename=%s\n", chr->label, chr->filename);
2454 CharDriverState *qemu_chr_find(const char *name)
2456 CharDriverState *chr;
2458 QTAILQ_FOREACH(chr, &chardevs, next) {
2459 if (strcmp(chr->label, name) != 0)
2460 continue;
2461 return chr;
2463 return NULL;