tracetool: Add support for the 'stderr' backend
[qemu/opensuse.git] / qemu-char.c
blob74c60e11a03d5e124ae79fa05ab2ac69bc190936
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 "qmp-commands.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 /***********************************************************/
104 /* character device */
106 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
107 QTAILQ_HEAD_INITIALIZER(chardevs);
109 void qemu_chr_be_event(CharDriverState *s, int event)
111 /* Keep track if the char device is open */
112 switch (event) {
113 case CHR_EVENT_OPENED:
114 s->opened = 1;
115 break;
116 case CHR_EVENT_CLOSED:
117 s->opened = 0;
118 break;
121 if (!s->chr_event)
122 return;
123 s->chr_event(s->handler_opaque, event);
126 static void qemu_chr_generic_open_bh(void *opaque)
128 CharDriverState *s = opaque;
129 qemu_chr_be_event(s, CHR_EVENT_OPENED);
130 qemu_bh_delete(s->bh);
131 s->bh = NULL;
134 void qemu_chr_generic_open(CharDriverState *s)
136 if (s->bh == NULL) {
137 s->bh = qemu_bh_new(qemu_chr_generic_open_bh, s);
138 qemu_bh_schedule(s->bh);
142 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
144 return s->chr_write(s, buf, len);
147 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
149 if (!s->chr_ioctl)
150 return -ENOTSUP;
151 return s->chr_ioctl(s, cmd, arg);
154 int qemu_chr_be_can_write(CharDriverState *s)
156 if (!s->chr_can_read)
157 return 0;
158 return s->chr_can_read(s->handler_opaque);
161 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
163 s->chr_read(s->handler_opaque, buf, len);
166 int qemu_chr_fe_get_msgfd(CharDriverState *s)
168 return s->get_msgfd ? s->get_msgfd(s) : -1;
171 int qemu_chr_add_client(CharDriverState *s, int fd)
173 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
176 void qemu_chr_accept_input(CharDriverState *s)
178 if (s->chr_accept_input)
179 s->chr_accept_input(s);
180 qemu_notify_event();
183 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
185 char buf[READ_BUF_LEN];
186 va_list ap;
187 va_start(ap, fmt);
188 vsnprintf(buf, sizeof(buf), fmt, ap);
189 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
190 va_end(ap);
193 void qemu_chr_add_handlers(CharDriverState *s,
194 IOCanReadHandler *fd_can_read,
195 IOReadHandler *fd_read,
196 IOEventHandler *fd_event,
197 void *opaque)
199 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
200 /* chr driver being released. */
201 ++s->avail_connections;
203 s->chr_can_read = fd_can_read;
204 s->chr_read = fd_read;
205 s->chr_event = fd_event;
206 s->handler_opaque = opaque;
207 if (s->chr_update_read_handler)
208 s->chr_update_read_handler(s);
210 /* We're connecting to an already opened device, so let's make sure we
211 also get the open event */
212 if (s->opened) {
213 qemu_chr_generic_open(s);
217 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
219 return len;
222 static CharDriverState *qemu_chr_open_null(QemuOpts *opts)
224 CharDriverState *chr;
226 chr = g_malloc0(sizeof(CharDriverState));
227 chr->chr_write = null_chr_write;
228 return chr;
231 /* MUX driver for serial I/O splitting */
232 #define MAX_MUX 4
233 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
234 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
235 typedef struct {
236 IOCanReadHandler *chr_can_read[MAX_MUX];
237 IOReadHandler *chr_read[MAX_MUX];
238 IOEventHandler *chr_event[MAX_MUX];
239 void *ext_opaque[MAX_MUX];
240 CharDriverState *drv;
241 int focus;
242 int mux_cnt;
243 int term_got_escape;
244 int max_size;
245 /* Intermediate input buffer allows to catch escape sequences even if the
246 currently active device is not accepting any input - but only until it
247 is full as well. */
248 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
249 int prod[MAX_MUX];
250 int cons[MAX_MUX];
251 int timestamps;
252 int linestart;
253 int64_t timestamps_start;
254 } MuxDriver;
257 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
259 MuxDriver *d = chr->opaque;
260 int ret;
261 if (!d->timestamps) {
262 ret = d->drv->chr_write(d->drv, buf, len);
263 } else {
264 int i;
266 ret = 0;
267 for (i = 0; i < len; i++) {
268 if (d->linestart) {
269 char buf1[64];
270 int64_t ti;
271 int secs;
273 ti = qemu_get_clock_ms(rt_clock);
274 if (d->timestamps_start == -1)
275 d->timestamps_start = ti;
276 ti -= d->timestamps_start;
277 secs = ti / 1000;
278 snprintf(buf1, sizeof(buf1),
279 "[%02d:%02d:%02d.%03d] ",
280 secs / 3600,
281 (secs / 60) % 60,
282 secs % 60,
283 (int)(ti % 1000));
284 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
285 d->linestart = 0;
287 ret += d->drv->chr_write(d->drv, buf+i, 1);
288 if (buf[i] == '\n') {
289 d->linestart = 1;
293 return ret;
296 static const char * const mux_help[] = {
297 "% h print this help\n\r",
298 "% x exit emulator\n\r",
299 "% s save disk data back to file (if -snapshot)\n\r",
300 "% t toggle console timestamps\n\r"
301 "% b send break (magic sysrq)\n\r",
302 "% c switch between console and monitor\n\r",
303 "% % sends %\n\r",
304 NULL
307 int term_escape_char = 0x01; /* ctrl-a is used for escape */
308 static void mux_print_help(CharDriverState *chr)
310 int i, j;
311 char ebuf[15] = "Escape-Char";
312 char cbuf[50] = "\n\r";
314 if (term_escape_char > 0 && term_escape_char < 26) {
315 snprintf(cbuf, sizeof(cbuf), "\n\r");
316 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
317 } else {
318 snprintf(cbuf, sizeof(cbuf),
319 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
320 term_escape_char);
322 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
323 for (i = 0; mux_help[i] != NULL; i++) {
324 for (j=0; mux_help[i][j] != '\0'; j++) {
325 if (mux_help[i][j] == '%')
326 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
327 else
328 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
333 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
335 if (d->chr_event[mux_nr])
336 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
339 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
341 if (d->term_got_escape) {
342 d->term_got_escape = 0;
343 if (ch == term_escape_char)
344 goto send_char;
345 switch(ch) {
346 case '?':
347 case 'h':
348 mux_print_help(chr);
349 break;
350 case 'x':
352 const char *term = "QEMU: Terminated\n\r";
353 chr->chr_write(chr,(uint8_t *)term,strlen(term));
354 exit(0);
355 break;
357 case 's':
358 bdrv_commit_all();
359 break;
360 case 'b':
361 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
362 break;
363 case 'c':
364 /* Switch to the next registered device */
365 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
366 d->focus++;
367 if (d->focus >= d->mux_cnt)
368 d->focus = 0;
369 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
370 break;
371 case 't':
372 d->timestamps = !d->timestamps;
373 d->timestamps_start = -1;
374 d->linestart = 0;
375 break;
377 } else if (ch == term_escape_char) {
378 d->term_got_escape = 1;
379 } else {
380 send_char:
381 return 1;
383 return 0;
386 static void mux_chr_accept_input(CharDriverState *chr)
388 MuxDriver *d = chr->opaque;
389 int m = d->focus;
391 while (d->prod[m] != d->cons[m] &&
392 d->chr_can_read[m] &&
393 d->chr_can_read[m](d->ext_opaque[m])) {
394 d->chr_read[m](d->ext_opaque[m],
395 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
399 static int mux_chr_can_read(void *opaque)
401 CharDriverState *chr = opaque;
402 MuxDriver *d = chr->opaque;
403 int m = d->focus;
405 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
406 return 1;
407 if (d->chr_can_read[m])
408 return d->chr_can_read[m](d->ext_opaque[m]);
409 return 0;
412 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
414 CharDriverState *chr = opaque;
415 MuxDriver *d = chr->opaque;
416 int m = d->focus;
417 int i;
419 mux_chr_accept_input (opaque);
421 for(i = 0; i < size; i++)
422 if (mux_proc_byte(chr, d, buf[i])) {
423 if (d->prod[m] == d->cons[m] &&
424 d->chr_can_read[m] &&
425 d->chr_can_read[m](d->ext_opaque[m]))
426 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
427 else
428 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
432 static void mux_chr_event(void *opaque, int event)
434 CharDriverState *chr = opaque;
435 MuxDriver *d = chr->opaque;
436 int i;
438 /* Send the event to all registered listeners */
439 for (i = 0; i < d->mux_cnt; i++)
440 mux_chr_send_event(d, i, event);
443 static void mux_chr_update_read_handler(CharDriverState *chr)
445 MuxDriver *d = chr->opaque;
447 if (d->mux_cnt >= MAX_MUX) {
448 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
449 return;
451 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
452 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
453 d->chr_read[d->mux_cnt] = chr->chr_read;
454 d->chr_event[d->mux_cnt] = chr->chr_event;
455 /* Fix up the real driver with mux routines */
456 if (d->mux_cnt == 0) {
457 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
458 mux_chr_event, chr);
460 if (d->focus != -1) {
461 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
463 d->focus = d->mux_cnt;
464 d->mux_cnt++;
465 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
468 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
470 CharDriverState *chr;
471 MuxDriver *d;
473 chr = g_malloc0(sizeof(CharDriverState));
474 d = g_malloc0(sizeof(MuxDriver));
476 chr->opaque = d;
477 d->drv = drv;
478 d->focus = -1;
479 chr->chr_write = mux_chr_write;
480 chr->chr_update_read_handler = mux_chr_update_read_handler;
481 chr->chr_accept_input = mux_chr_accept_input;
482 /* Frontend guest-open / -close notification is not support with muxes */
483 chr->chr_guest_open = NULL;
484 chr->chr_guest_close = NULL;
486 /* Muxes are always open on creation */
487 qemu_chr_generic_open(chr);
489 return chr;
493 #ifdef _WIN32
494 int send_all(int fd, const void *buf, int len1)
496 int ret, len;
498 len = len1;
499 while (len > 0) {
500 ret = send(fd, buf, len, 0);
501 if (ret < 0) {
502 errno = WSAGetLastError();
503 if (errno != WSAEWOULDBLOCK) {
504 return -1;
506 } else if (ret == 0) {
507 break;
508 } else {
509 buf += ret;
510 len -= ret;
513 return len1 - len;
516 #else
518 int send_all(int fd, const void *_buf, int len1)
520 int ret, len;
521 const uint8_t *buf = _buf;
523 len = len1;
524 while (len > 0) {
525 ret = write(fd, buf, len);
526 if (ret < 0) {
527 if (errno != EINTR && errno != EAGAIN)
528 return -1;
529 } else if (ret == 0) {
530 break;
531 } else {
532 buf += ret;
533 len -= ret;
536 return len1 - len;
538 #endif /* !_WIN32 */
540 #define STDIO_MAX_CLIENTS 1
541 static int stdio_nb_clients;
543 #ifndef _WIN32
545 typedef struct {
546 int fd_in, fd_out;
547 int max_size;
548 } FDCharDriver;
551 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
553 FDCharDriver *s = chr->opaque;
554 return send_all(s->fd_out, buf, len);
557 static int fd_chr_read_poll(void *opaque)
559 CharDriverState *chr = opaque;
560 FDCharDriver *s = chr->opaque;
562 s->max_size = qemu_chr_be_can_write(chr);
563 return s->max_size;
566 static void fd_chr_read(void *opaque)
568 CharDriverState *chr = opaque;
569 FDCharDriver *s = chr->opaque;
570 int size, len;
571 uint8_t buf[READ_BUF_LEN];
573 len = sizeof(buf);
574 if (len > s->max_size)
575 len = s->max_size;
576 if (len == 0)
577 return;
578 size = read(s->fd_in, buf, len);
579 if (size == 0) {
580 /* FD has been closed. Remove it from the active list. */
581 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
582 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
583 return;
585 if (size > 0) {
586 qemu_chr_be_write(chr, buf, size);
590 static void fd_chr_update_read_handler(CharDriverState *chr)
592 FDCharDriver *s = chr->opaque;
594 if (s->fd_in >= 0) {
595 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
596 } else {
597 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
598 fd_chr_read, NULL, chr);
603 static void fd_chr_close(struct CharDriverState *chr)
605 FDCharDriver *s = chr->opaque;
607 if (s->fd_in >= 0) {
608 if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
609 } else {
610 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
614 g_free(s);
615 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
618 /* open a character device to a unix fd */
619 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
621 CharDriverState *chr;
622 FDCharDriver *s;
624 chr = g_malloc0(sizeof(CharDriverState));
625 s = g_malloc0(sizeof(FDCharDriver));
626 s->fd_in = fd_in;
627 s->fd_out = fd_out;
628 chr->opaque = s;
629 chr->chr_write = fd_chr_write;
630 chr->chr_update_read_handler = fd_chr_update_read_handler;
631 chr->chr_close = fd_chr_close;
633 qemu_chr_generic_open(chr);
635 return chr;
638 static CharDriverState *qemu_chr_open_file_out(QemuOpts *opts)
640 int fd_out;
642 TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
643 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
644 if (fd_out < 0) {
645 return NULL;
647 return qemu_chr_open_fd(-1, fd_out);
650 static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)
652 int fd_in, fd_out;
653 char filename_in[256], filename_out[256];
654 const char *filename = qemu_opt_get(opts, "path");
656 if (filename == NULL) {
657 fprintf(stderr, "chardev: pipe: no filename given\n");
658 return NULL;
661 snprintf(filename_in, 256, "%s.in", filename);
662 snprintf(filename_out, 256, "%s.out", filename);
663 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
664 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
665 if (fd_in < 0 || fd_out < 0) {
666 if (fd_in >= 0)
667 close(fd_in);
668 if (fd_out >= 0)
669 close(fd_out);
670 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
671 if (fd_in < 0) {
672 return NULL;
675 return qemu_chr_open_fd(fd_in, fd_out);
679 /* for STDIO, we handle the case where several clients use it
680 (nographic mode) */
682 #define TERM_FIFO_MAX_SIZE 1
684 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
685 static int term_fifo_size;
687 static int stdio_read_poll(void *opaque)
689 CharDriverState *chr = opaque;
691 /* try to flush the queue if needed */
692 if (term_fifo_size != 0 && qemu_chr_be_can_write(chr) > 0) {
693 qemu_chr_be_write(chr, term_fifo, 1);
694 term_fifo_size = 0;
696 /* see if we can absorb more chars */
697 if (term_fifo_size == 0)
698 return 1;
699 else
700 return 0;
703 static void stdio_read(void *opaque)
705 int size;
706 uint8_t buf[1];
707 CharDriverState *chr = opaque;
709 size = read(0, buf, 1);
710 if (size == 0) {
711 /* stdin has been closed. Remove it from the active list. */
712 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
713 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
714 return;
716 if (size > 0) {
717 if (qemu_chr_be_can_write(chr) > 0) {
718 qemu_chr_be_write(chr, buf, 1);
719 } else if (term_fifo_size == 0) {
720 term_fifo[term_fifo_size++] = buf[0];
725 /* init terminal so that we can grab keys */
726 static struct termios oldtty;
727 static int old_fd0_flags;
728 static bool stdio_allow_signal;
730 static void term_exit(void)
732 tcsetattr (0, TCSANOW, &oldtty);
733 fcntl(0, F_SETFL, old_fd0_flags);
736 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
738 struct termios tty;
740 tty = oldtty;
741 if (!echo) {
742 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
743 |INLCR|IGNCR|ICRNL|IXON);
744 tty.c_oflag |= OPOST;
745 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
746 tty.c_cflag &= ~(CSIZE|PARENB);
747 tty.c_cflag |= CS8;
748 tty.c_cc[VMIN] = 1;
749 tty.c_cc[VTIME] = 0;
751 /* if graphical mode, we allow Ctrl-C handling */
752 if (!stdio_allow_signal)
753 tty.c_lflag &= ~ISIG;
755 tcsetattr (0, TCSANOW, &tty);
758 static void qemu_chr_close_stdio(struct CharDriverState *chr)
760 term_exit();
761 stdio_nb_clients--;
762 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
763 fd_chr_close(chr);
766 static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)
768 CharDriverState *chr;
770 if (stdio_nb_clients >= STDIO_MAX_CLIENTS) {
771 return NULL;
773 if (stdio_nb_clients == 0) {
774 old_fd0_flags = fcntl(0, F_GETFL);
775 tcgetattr (0, &oldtty);
776 fcntl(0, F_SETFL, O_NONBLOCK);
777 atexit(term_exit);
780 chr = qemu_chr_open_fd(0, 1);
781 chr->chr_close = qemu_chr_close_stdio;
782 chr->chr_set_echo = qemu_chr_set_echo_stdio;
783 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
784 stdio_nb_clients++;
785 stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
786 display_type != DT_NOGRAPHIC);
787 qemu_chr_fe_set_echo(chr, false);
789 return chr;
792 #ifdef __sun__
793 /* Once Solaris has openpty(), this is going to be removed. */
794 static int openpty(int *amaster, int *aslave, char *name,
795 struct termios *termp, struct winsize *winp)
797 const char *slave;
798 int mfd = -1, sfd = -1;
800 *amaster = *aslave = -1;
802 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
803 if (mfd < 0)
804 goto err;
806 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
807 goto err;
809 if ((slave = ptsname(mfd)) == NULL)
810 goto err;
812 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
813 goto err;
815 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
816 (termp != NULL && tcgetattr(sfd, termp) < 0))
817 goto err;
819 if (amaster)
820 *amaster = mfd;
821 if (aslave)
822 *aslave = sfd;
823 if (winp)
824 ioctl(sfd, TIOCSWINSZ, winp);
826 return 0;
828 err:
829 if (sfd != -1)
830 close(sfd);
831 close(mfd);
832 return -1;
835 static void cfmakeraw (struct termios *termios_p)
837 termios_p->c_iflag &=
838 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
839 termios_p->c_oflag &= ~OPOST;
840 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
841 termios_p->c_cflag &= ~(CSIZE|PARENB);
842 termios_p->c_cflag |= CS8;
844 termios_p->c_cc[VMIN] = 0;
845 termios_p->c_cc[VTIME] = 0;
847 #endif
849 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
850 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
851 || defined(__GLIBC__)
853 typedef struct {
854 int fd;
855 int connected;
856 int polling;
857 int read_bytes;
858 QEMUTimer *timer;
859 } PtyCharDriver;
861 static void pty_chr_update_read_handler(CharDriverState *chr);
862 static void pty_chr_state(CharDriverState *chr, int connected);
864 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
866 PtyCharDriver *s = chr->opaque;
868 if (!s->connected) {
869 /* guest sends data, check for (re-)connect */
870 pty_chr_update_read_handler(chr);
871 return 0;
873 return send_all(s->fd, buf, len);
876 static int pty_chr_read_poll(void *opaque)
878 CharDriverState *chr = opaque;
879 PtyCharDriver *s = chr->opaque;
881 s->read_bytes = qemu_chr_be_can_write(chr);
882 return s->read_bytes;
885 static void pty_chr_read(void *opaque)
887 CharDriverState *chr = opaque;
888 PtyCharDriver *s = chr->opaque;
889 int size, len;
890 uint8_t buf[READ_BUF_LEN];
892 len = sizeof(buf);
893 if (len > s->read_bytes)
894 len = s->read_bytes;
895 if (len == 0)
896 return;
897 size = read(s->fd, buf, len);
898 if ((size == -1 && errno == EIO) ||
899 (size == 0)) {
900 pty_chr_state(chr, 0);
901 return;
903 if (size > 0) {
904 pty_chr_state(chr, 1);
905 qemu_chr_be_write(chr, buf, size);
909 static void pty_chr_update_read_handler(CharDriverState *chr)
911 PtyCharDriver *s = chr->opaque;
913 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
914 pty_chr_read, NULL, chr);
915 s->polling = 1;
917 * Short timeout here: just need wait long enougth that qemu makes
918 * it through the poll loop once. When reconnected we want a
919 * short timeout so we notice it almost instantly. Otherwise
920 * read() gives us -EIO instantly, making pty_chr_state() reset the
921 * timeout to the normal (much longer) poll interval before the
922 * timer triggers.
924 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 10);
927 static void pty_chr_state(CharDriverState *chr, int connected)
929 PtyCharDriver *s = chr->opaque;
931 if (!connected) {
932 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
933 s->connected = 0;
934 s->polling = 0;
935 /* (re-)connect poll interval for idle guests: once per second.
936 * We check more frequently in case the guests sends data to
937 * the virtual device linked to our pty. */
938 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 1000);
939 } else {
940 if (!s->connected)
941 qemu_chr_generic_open(chr);
942 s->connected = 1;
946 static void pty_chr_timer(void *opaque)
948 struct CharDriverState *chr = opaque;
949 PtyCharDriver *s = chr->opaque;
951 if (s->connected)
952 return;
953 if (s->polling) {
954 /* If we arrive here without polling being cleared due
955 * read returning -EIO, then we are (re-)connected */
956 pty_chr_state(chr, 1);
957 return;
960 /* Next poll ... */
961 pty_chr_update_read_handler(chr);
964 static void pty_chr_close(struct CharDriverState *chr)
966 PtyCharDriver *s = chr->opaque;
968 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
969 close(s->fd);
970 qemu_del_timer(s->timer);
971 qemu_free_timer(s->timer);
972 g_free(s);
973 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
976 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
978 CharDriverState *chr;
979 PtyCharDriver *s;
980 struct termios tty;
981 int master_fd, slave_fd, len;
982 #if defined(__OpenBSD__) || defined(__DragonFly__)
983 char pty_name[PATH_MAX];
984 #define q_ptsname(x) pty_name
985 #else
986 char *pty_name = NULL;
987 #define q_ptsname(x) ptsname(x)
988 #endif
990 if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
991 return NULL;
994 /* Set raw attributes on the pty. */
995 tcgetattr(slave_fd, &tty);
996 cfmakeraw(&tty);
997 tcsetattr(slave_fd, TCSAFLUSH, &tty);
998 close(slave_fd);
1000 chr = g_malloc0(sizeof(CharDriverState));
1002 len = strlen(q_ptsname(master_fd)) + 5;
1003 chr->filename = g_malloc(len);
1004 snprintf(chr->filename, len, "pty:%s", q_ptsname(master_fd));
1005 qemu_opt_set(opts, "path", q_ptsname(master_fd));
1006 fprintf(stderr, "char device redirected to %s\n", q_ptsname(master_fd));
1008 s = g_malloc0(sizeof(PtyCharDriver));
1009 chr->opaque = s;
1010 chr->chr_write = pty_chr_write;
1011 chr->chr_update_read_handler = pty_chr_update_read_handler;
1012 chr->chr_close = pty_chr_close;
1014 s->fd = master_fd;
1015 s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr);
1017 return chr;
1020 static void tty_serial_init(int fd, int speed,
1021 int parity, int data_bits, int stop_bits)
1023 struct termios tty;
1024 speed_t spd;
1026 #if 0
1027 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1028 speed, parity, data_bits, stop_bits);
1029 #endif
1030 tcgetattr (fd, &tty);
1032 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1033 speed = speed * 10 / 11;
1034 do {
1035 check_speed(50);
1036 check_speed(75);
1037 check_speed(110);
1038 check_speed(134);
1039 check_speed(150);
1040 check_speed(200);
1041 check_speed(300);
1042 check_speed(600);
1043 check_speed(1200);
1044 check_speed(1800);
1045 check_speed(2400);
1046 check_speed(4800);
1047 check_speed(9600);
1048 check_speed(19200);
1049 check_speed(38400);
1050 /* Non-Posix values follow. They may be unsupported on some systems. */
1051 check_speed(57600);
1052 check_speed(115200);
1053 #ifdef B230400
1054 check_speed(230400);
1055 #endif
1056 #ifdef B460800
1057 check_speed(460800);
1058 #endif
1059 #ifdef B500000
1060 check_speed(500000);
1061 #endif
1062 #ifdef B576000
1063 check_speed(576000);
1064 #endif
1065 #ifdef B921600
1066 check_speed(921600);
1067 #endif
1068 #ifdef B1000000
1069 check_speed(1000000);
1070 #endif
1071 #ifdef B1152000
1072 check_speed(1152000);
1073 #endif
1074 #ifdef B1500000
1075 check_speed(1500000);
1076 #endif
1077 #ifdef B2000000
1078 check_speed(2000000);
1079 #endif
1080 #ifdef B2500000
1081 check_speed(2500000);
1082 #endif
1083 #ifdef B3000000
1084 check_speed(3000000);
1085 #endif
1086 #ifdef B3500000
1087 check_speed(3500000);
1088 #endif
1089 #ifdef B4000000
1090 check_speed(4000000);
1091 #endif
1092 spd = B115200;
1093 } while (0);
1095 cfsetispeed(&tty, spd);
1096 cfsetospeed(&tty, spd);
1098 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1099 |INLCR|IGNCR|ICRNL|IXON);
1100 tty.c_oflag |= OPOST;
1101 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1102 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1103 switch(data_bits) {
1104 default:
1105 case 8:
1106 tty.c_cflag |= CS8;
1107 break;
1108 case 7:
1109 tty.c_cflag |= CS7;
1110 break;
1111 case 6:
1112 tty.c_cflag |= CS6;
1113 break;
1114 case 5:
1115 tty.c_cflag |= CS5;
1116 break;
1118 switch(parity) {
1119 default:
1120 case 'N':
1121 break;
1122 case 'E':
1123 tty.c_cflag |= PARENB;
1124 break;
1125 case 'O':
1126 tty.c_cflag |= PARENB | PARODD;
1127 break;
1129 if (stop_bits == 2)
1130 tty.c_cflag |= CSTOPB;
1132 tcsetattr (fd, TCSANOW, &tty);
1135 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1137 FDCharDriver *s = chr->opaque;
1139 switch(cmd) {
1140 case CHR_IOCTL_SERIAL_SET_PARAMS:
1142 QEMUSerialSetParams *ssp = arg;
1143 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1144 ssp->data_bits, ssp->stop_bits);
1146 break;
1147 case CHR_IOCTL_SERIAL_SET_BREAK:
1149 int enable = *(int *)arg;
1150 if (enable)
1151 tcsendbreak(s->fd_in, 1);
1153 break;
1154 case CHR_IOCTL_SERIAL_GET_TIOCM:
1156 int sarg = 0;
1157 int *targ = (int *)arg;
1158 ioctl(s->fd_in, TIOCMGET, &sarg);
1159 *targ = 0;
1160 if (sarg & TIOCM_CTS)
1161 *targ |= CHR_TIOCM_CTS;
1162 if (sarg & TIOCM_CAR)
1163 *targ |= CHR_TIOCM_CAR;
1164 if (sarg & TIOCM_DSR)
1165 *targ |= CHR_TIOCM_DSR;
1166 if (sarg & TIOCM_RI)
1167 *targ |= CHR_TIOCM_RI;
1168 if (sarg & TIOCM_DTR)
1169 *targ |= CHR_TIOCM_DTR;
1170 if (sarg & TIOCM_RTS)
1171 *targ |= CHR_TIOCM_RTS;
1173 break;
1174 case CHR_IOCTL_SERIAL_SET_TIOCM:
1176 int sarg = *(int *)arg;
1177 int targ = 0;
1178 ioctl(s->fd_in, TIOCMGET, &targ);
1179 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1180 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1181 if (sarg & CHR_TIOCM_CTS)
1182 targ |= TIOCM_CTS;
1183 if (sarg & CHR_TIOCM_CAR)
1184 targ |= TIOCM_CAR;
1185 if (sarg & CHR_TIOCM_DSR)
1186 targ |= TIOCM_DSR;
1187 if (sarg & CHR_TIOCM_RI)
1188 targ |= TIOCM_RI;
1189 if (sarg & CHR_TIOCM_DTR)
1190 targ |= TIOCM_DTR;
1191 if (sarg & CHR_TIOCM_RTS)
1192 targ |= TIOCM_RTS;
1193 ioctl(s->fd_in, TIOCMSET, &targ);
1195 break;
1196 default:
1197 return -ENOTSUP;
1199 return 0;
1202 static void qemu_chr_close_tty(CharDriverState *chr)
1204 FDCharDriver *s = chr->opaque;
1205 int fd = -1;
1207 if (s) {
1208 fd = s->fd_in;
1211 fd_chr_close(chr);
1213 if (fd >= 0) {
1214 close(fd);
1218 static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
1220 const char *filename = qemu_opt_get(opts, "path");
1221 CharDriverState *chr;
1222 int fd;
1224 TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
1225 if (fd < 0) {
1226 return NULL;
1228 tty_serial_init(fd, 115200, 'N', 8, 1);
1229 chr = qemu_chr_open_fd(fd, fd);
1230 chr->chr_ioctl = tty_serial_ioctl;
1231 chr->chr_close = qemu_chr_close_tty;
1232 return chr;
1234 #else /* ! __linux__ && ! __sun__ */
1235 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
1237 return NULL;
1239 #endif /* __linux__ || __sun__ */
1241 #if defined(__linux__)
1242 typedef struct {
1243 int fd;
1244 int mode;
1245 } ParallelCharDriver;
1247 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1249 if (s->mode != mode) {
1250 int m = mode;
1251 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1252 return 0;
1253 s->mode = mode;
1255 return 1;
1258 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1260 ParallelCharDriver *drv = chr->opaque;
1261 int fd = drv->fd;
1262 uint8_t b;
1264 switch(cmd) {
1265 case CHR_IOCTL_PP_READ_DATA:
1266 if (ioctl(fd, PPRDATA, &b) < 0)
1267 return -ENOTSUP;
1268 *(uint8_t *)arg = b;
1269 break;
1270 case CHR_IOCTL_PP_WRITE_DATA:
1271 b = *(uint8_t *)arg;
1272 if (ioctl(fd, PPWDATA, &b) < 0)
1273 return -ENOTSUP;
1274 break;
1275 case CHR_IOCTL_PP_READ_CONTROL:
1276 if (ioctl(fd, PPRCONTROL, &b) < 0)
1277 return -ENOTSUP;
1278 /* Linux gives only the lowest bits, and no way to know data
1279 direction! For better compatibility set the fixed upper
1280 bits. */
1281 *(uint8_t *)arg = b | 0xc0;
1282 break;
1283 case CHR_IOCTL_PP_WRITE_CONTROL:
1284 b = *(uint8_t *)arg;
1285 if (ioctl(fd, PPWCONTROL, &b) < 0)
1286 return -ENOTSUP;
1287 break;
1288 case CHR_IOCTL_PP_READ_STATUS:
1289 if (ioctl(fd, PPRSTATUS, &b) < 0)
1290 return -ENOTSUP;
1291 *(uint8_t *)arg = b;
1292 break;
1293 case CHR_IOCTL_PP_DATA_DIR:
1294 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1295 return -ENOTSUP;
1296 break;
1297 case CHR_IOCTL_PP_EPP_READ_ADDR:
1298 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1299 struct ParallelIOArg *parg = arg;
1300 int n = read(fd, parg->buffer, parg->count);
1301 if (n != parg->count) {
1302 return -EIO;
1305 break;
1306 case CHR_IOCTL_PP_EPP_READ:
1307 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1308 struct ParallelIOArg *parg = arg;
1309 int n = read(fd, parg->buffer, parg->count);
1310 if (n != parg->count) {
1311 return -EIO;
1314 break;
1315 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1316 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1317 struct ParallelIOArg *parg = arg;
1318 int n = write(fd, parg->buffer, parg->count);
1319 if (n != parg->count) {
1320 return -EIO;
1323 break;
1324 case CHR_IOCTL_PP_EPP_WRITE:
1325 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1326 struct ParallelIOArg *parg = arg;
1327 int n = write(fd, parg->buffer, parg->count);
1328 if (n != parg->count) {
1329 return -EIO;
1332 break;
1333 default:
1334 return -ENOTSUP;
1336 return 0;
1339 static void pp_close(CharDriverState *chr)
1341 ParallelCharDriver *drv = chr->opaque;
1342 int fd = drv->fd;
1344 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1345 ioctl(fd, PPRELEASE);
1346 close(fd);
1347 g_free(drv);
1348 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1351 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1353 const char *filename = qemu_opt_get(opts, "path");
1354 CharDriverState *chr;
1355 ParallelCharDriver *drv;
1356 int fd;
1358 TFR(fd = qemu_open(filename, O_RDWR));
1359 if (fd < 0) {
1360 return NULL;
1363 if (ioctl(fd, PPCLAIM) < 0) {
1364 close(fd);
1365 return NULL;
1368 drv = g_malloc0(sizeof(ParallelCharDriver));
1369 drv->fd = fd;
1370 drv->mode = IEEE1284_MODE_COMPAT;
1372 chr = g_malloc0(sizeof(CharDriverState));
1373 chr->chr_write = null_chr_write;
1374 chr->chr_ioctl = pp_ioctl;
1375 chr->chr_close = pp_close;
1376 chr->opaque = drv;
1378 qemu_chr_generic_open(chr);
1380 return chr;
1382 #endif /* __linux__ */
1384 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1385 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1387 int fd = (int)(intptr_t)chr->opaque;
1388 uint8_t b;
1390 switch(cmd) {
1391 case CHR_IOCTL_PP_READ_DATA:
1392 if (ioctl(fd, PPIGDATA, &b) < 0)
1393 return -ENOTSUP;
1394 *(uint8_t *)arg = b;
1395 break;
1396 case CHR_IOCTL_PP_WRITE_DATA:
1397 b = *(uint8_t *)arg;
1398 if (ioctl(fd, PPISDATA, &b) < 0)
1399 return -ENOTSUP;
1400 break;
1401 case CHR_IOCTL_PP_READ_CONTROL:
1402 if (ioctl(fd, PPIGCTRL, &b) < 0)
1403 return -ENOTSUP;
1404 *(uint8_t *)arg = b;
1405 break;
1406 case CHR_IOCTL_PP_WRITE_CONTROL:
1407 b = *(uint8_t *)arg;
1408 if (ioctl(fd, PPISCTRL, &b) < 0)
1409 return -ENOTSUP;
1410 break;
1411 case CHR_IOCTL_PP_READ_STATUS:
1412 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1413 return -ENOTSUP;
1414 *(uint8_t *)arg = b;
1415 break;
1416 default:
1417 return -ENOTSUP;
1419 return 0;
1422 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1424 const char *filename = qemu_opt_get(opts, "path");
1425 CharDriverState *chr;
1426 int fd;
1428 fd = qemu_open(filename, O_RDWR);
1429 if (fd < 0) {
1430 return NULL;
1433 chr = g_malloc0(sizeof(CharDriverState));
1434 chr->opaque = (void *)(intptr_t)fd;
1435 chr->chr_write = null_chr_write;
1436 chr->chr_ioctl = pp_ioctl;
1437 return chr;
1439 #endif
1441 #else /* _WIN32 */
1443 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1445 typedef struct {
1446 int max_size;
1447 HANDLE hcom, hrecv, hsend;
1448 OVERLAPPED orecv, osend;
1449 BOOL fpipe;
1450 DWORD len;
1451 } WinCharState;
1453 typedef struct {
1454 HANDLE hStdIn;
1455 HANDLE hInputReadyEvent;
1456 HANDLE hInputDoneEvent;
1457 HANDLE hInputThread;
1458 uint8_t win_stdio_buf;
1459 } WinStdioCharState;
1461 #define NSENDBUF 2048
1462 #define NRECVBUF 2048
1463 #define MAXCONNECT 1
1464 #define NTIMEOUT 5000
1466 static int win_chr_poll(void *opaque);
1467 static int win_chr_pipe_poll(void *opaque);
1469 static void win_chr_close(CharDriverState *chr)
1471 WinCharState *s = chr->opaque;
1473 if (s->hsend) {
1474 CloseHandle(s->hsend);
1475 s->hsend = NULL;
1477 if (s->hrecv) {
1478 CloseHandle(s->hrecv);
1479 s->hrecv = NULL;
1481 if (s->hcom) {
1482 CloseHandle(s->hcom);
1483 s->hcom = NULL;
1485 if (s->fpipe)
1486 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1487 else
1488 qemu_del_polling_cb(win_chr_poll, chr);
1490 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1493 static int win_chr_init(CharDriverState *chr, const char *filename)
1495 WinCharState *s = chr->opaque;
1496 COMMCONFIG comcfg;
1497 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1498 COMSTAT comstat;
1499 DWORD size;
1500 DWORD err;
1502 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1503 if (!s->hsend) {
1504 fprintf(stderr, "Failed CreateEvent\n");
1505 goto fail;
1507 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1508 if (!s->hrecv) {
1509 fprintf(stderr, "Failed CreateEvent\n");
1510 goto fail;
1513 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1514 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1515 if (s->hcom == INVALID_HANDLE_VALUE) {
1516 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1517 s->hcom = NULL;
1518 goto fail;
1521 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1522 fprintf(stderr, "Failed SetupComm\n");
1523 goto fail;
1526 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1527 size = sizeof(COMMCONFIG);
1528 GetDefaultCommConfig(filename, &comcfg, &size);
1529 comcfg.dcb.DCBlength = sizeof(DCB);
1530 CommConfigDialog(filename, NULL, &comcfg);
1532 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1533 fprintf(stderr, "Failed SetCommState\n");
1534 goto fail;
1537 if (!SetCommMask(s->hcom, EV_ERR)) {
1538 fprintf(stderr, "Failed SetCommMask\n");
1539 goto fail;
1542 cto.ReadIntervalTimeout = MAXDWORD;
1543 if (!SetCommTimeouts(s->hcom, &cto)) {
1544 fprintf(stderr, "Failed SetCommTimeouts\n");
1545 goto fail;
1548 if (!ClearCommError(s->hcom, &err, &comstat)) {
1549 fprintf(stderr, "Failed ClearCommError\n");
1550 goto fail;
1552 qemu_add_polling_cb(win_chr_poll, chr);
1553 return 0;
1555 fail:
1556 win_chr_close(chr);
1557 return -1;
1560 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1562 WinCharState *s = chr->opaque;
1563 DWORD len, ret, size, err;
1565 len = len1;
1566 ZeroMemory(&s->osend, sizeof(s->osend));
1567 s->osend.hEvent = s->hsend;
1568 while (len > 0) {
1569 if (s->hsend)
1570 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1571 else
1572 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1573 if (!ret) {
1574 err = GetLastError();
1575 if (err == ERROR_IO_PENDING) {
1576 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1577 if (ret) {
1578 buf += size;
1579 len -= size;
1580 } else {
1581 break;
1583 } else {
1584 break;
1586 } else {
1587 buf += size;
1588 len -= size;
1591 return len1 - len;
1594 static int win_chr_read_poll(CharDriverState *chr)
1596 WinCharState *s = chr->opaque;
1598 s->max_size = qemu_chr_be_can_write(chr);
1599 return s->max_size;
1602 static void win_chr_readfile(CharDriverState *chr)
1604 WinCharState *s = chr->opaque;
1605 int ret, err;
1606 uint8_t buf[READ_BUF_LEN];
1607 DWORD size;
1609 ZeroMemory(&s->orecv, sizeof(s->orecv));
1610 s->orecv.hEvent = s->hrecv;
1611 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1612 if (!ret) {
1613 err = GetLastError();
1614 if (err == ERROR_IO_PENDING) {
1615 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1619 if (size > 0) {
1620 qemu_chr_be_write(chr, buf, size);
1624 static void win_chr_read(CharDriverState *chr)
1626 WinCharState *s = chr->opaque;
1628 if (s->len > s->max_size)
1629 s->len = s->max_size;
1630 if (s->len == 0)
1631 return;
1633 win_chr_readfile(chr);
1636 static int win_chr_poll(void *opaque)
1638 CharDriverState *chr = opaque;
1639 WinCharState *s = chr->opaque;
1640 COMSTAT status;
1641 DWORD comerr;
1643 ClearCommError(s->hcom, &comerr, &status);
1644 if (status.cbInQue > 0) {
1645 s->len = status.cbInQue;
1646 win_chr_read_poll(chr);
1647 win_chr_read(chr);
1648 return 1;
1650 return 0;
1653 static CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1655 const char *filename = qemu_opt_get(opts, "path");
1656 CharDriverState *chr;
1657 WinCharState *s;
1659 chr = g_malloc0(sizeof(CharDriverState));
1660 s = g_malloc0(sizeof(WinCharState));
1661 chr->opaque = s;
1662 chr->chr_write = win_chr_write;
1663 chr->chr_close = win_chr_close;
1665 if (win_chr_init(chr, filename) < 0) {
1666 g_free(s);
1667 g_free(chr);
1668 return NULL;
1670 qemu_chr_generic_open(chr);
1671 return chr;
1674 static int win_chr_pipe_poll(void *opaque)
1676 CharDriverState *chr = opaque;
1677 WinCharState *s = chr->opaque;
1678 DWORD size;
1680 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1681 if (size > 0) {
1682 s->len = size;
1683 win_chr_read_poll(chr);
1684 win_chr_read(chr);
1685 return 1;
1687 return 0;
1690 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1692 WinCharState *s = chr->opaque;
1693 OVERLAPPED ov;
1694 int ret;
1695 DWORD size;
1696 char openname[256];
1698 s->fpipe = TRUE;
1700 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1701 if (!s->hsend) {
1702 fprintf(stderr, "Failed CreateEvent\n");
1703 goto fail;
1705 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1706 if (!s->hrecv) {
1707 fprintf(stderr, "Failed CreateEvent\n");
1708 goto fail;
1711 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1712 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1713 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1714 PIPE_WAIT,
1715 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1716 if (s->hcom == INVALID_HANDLE_VALUE) {
1717 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1718 s->hcom = NULL;
1719 goto fail;
1722 ZeroMemory(&ov, sizeof(ov));
1723 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1724 ret = ConnectNamedPipe(s->hcom, &ov);
1725 if (ret) {
1726 fprintf(stderr, "Failed ConnectNamedPipe\n");
1727 goto fail;
1730 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1731 if (!ret) {
1732 fprintf(stderr, "Failed GetOverlappedResult\n");
1733 if (ov.hEvent) {
1734 CloseHandle(ov.hEvent);
1735 ov.hEvent = NULL;
1737 goto fail;
1740 if (ov.hEvent) {
1741 CloseHandle(ov.hEvent);
1742 ov.hEvent = NULL;
1744 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1745 return 0;
1747 fail:
1748 win_chr_close(chr);
1749 return -1;
1753 static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
1755 const char *filename = qemu_opt_get(opts, "path");
1756 CharDriverState *chr;
1757 WinCharState *s;
1759 chr = g_malloc0(sizeof(CharDriverState));
1760 s = g_malloc0(sizeof(WinCharState));
1761 chr->opaque = s;
1762 chr->chr_write = win_chr_write;
1763 chr->chr_close = win_chr_close;
1765 if (win_chr_pipe_init(chr, filename) < 0) {
1766 g_free(s);
1767 g_free(chr);
1768 return NULL;
1770 qemu_chr_generic_open(chr);
1771 return chr;
1774 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1776 CharDriverState *chr;
1777 WinCharState *s;
1779 chr = g_malloc0(sizeof(CharDriverState));
1780 s = g_malloc0(sizeof(WinCharState));
1781 s->hcom = fd_out;
1782 chr->opaque = s;
1783 chr->chr_write = win_chr_write;
1784 qemu_chr_generic_open(chr);
1785 return chr;
1788 static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
1790 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1793 static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
1795 const char *file_out = qemu_opt_get(opts, "path");
1796 HANDLE fd_out;
1798 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1799 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1800 if (fd_out == INVALID_HANDLE_VALUE) {
1801 return NULL;
1804 return qemu_chr_open_win_file(fd_out);
1807 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1809 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1810 DWORD dwSize;
1811 int len1;
1813 len1 = len;
1815 while (len1 > 0) {
1816 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
1817 break;
1819 buf += dwSize;
1820 len1 -= dwSize;
1823 return len - len1;
1826 static void win_stdio_wait_func(void *opaque)
1828 CharDriverState *chr = opaque;
1829 WinStdioCharState *stdio = chr->opaque;
1830 INPUT_RECORD buf[4];
1831 int ret;
1832 DWORD dwSize;
1833 int i;
1835 ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
1836 &dwSize);
1838 if (!ret) {
1839 /* Avoid error storm */
1840 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
1841 return;
1844 for (i = 0; i < dwSize; i++) {
1845 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
1847 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
1848 int j;
1849 if (kev->uChar.AsciiChar != 0) {
1850 for (j = 0; j < kev->wRepeatCount; j++) {
1851 if (qemu_chr_be_can_write(chr)) {
1852 uint8_t c = kev->uChar.AsciiChar;
1853 qemu_chr_be_write(chr, &c, 1);
1861 static DWORD WINAPI win_stdio_thread(LPVOID param)
1863 CharDriverState *chr = param;
1864 WinStdioCharState *stdio = chr->opaque;
1865 int ret;
1866 DWORD dwSize;
1868 while (1) {
1870 /* Wait for one byte */
1871 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
1873 /* Exit in case of error, continue if nothing read */
1874 if (!ret) {
1875 break;
1877 if (!dwSize) {
1878 continue;
1881 /* Some terminal emulator returns \r\n for Enter, just pass \n */
1882 if (stdio->win_stdio_buf == '\r') {
1883 continue;
1886 /* Signal the main thread and wait until the byte was eaten */
1887 if (!SetEvent(stdio->hInputReadyEvent)) {
1888 break;
1890 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
1891 != WAIT_OBJECT_0) {
1892 break;
1896 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
1897 return 0;
1900 static void win_stdio_thread_wait_func(void *opaque)
1902 CharDriverState *chr = opaque;
1903 WinStdioCharState *stdio = chr->opaque;
1905 if (qemu_chr_be_can_write(chr)) {
1906 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
1909 SetEvent(stdio->hInputDoneEvent);
1912 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
1914 WinStdioCharState *stdio = chr->opaque;
1915 DWORD dwMode = 0;
1917 GetConsoleMode(stdio->hStdIn, &dwMode);
1919 if (echo) {
1920 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
1921 } else {
1922 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
1926 static void win_stdio_close(CharDriverState *chr)
1928 WinStdioCharState *stdio = chr->opaque;
1930 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
1931 CloseHandle(stdio->hInputReadyEvent);
1933 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
1934 CloseHandle(stdio->hInputDoneEvent);
1936 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
1937 TerminateThread(stdio->hInputThread, 0);
1940 g_free(chr->opaque);
1941 g_free(chr);
1942 stdio_nb_clients--;
1945 static CharDriverState *qemu_chr_open_win_stdio(QemuOpts *opts)
1947 CharDriverState *chr;
1948 WinStdioCharState *stdio;
1949 DWORD dwMode;
1950 int is_console = 0;
1952 if (stdio_nb_clients >= STDIO_MAX_CLIENTS
1953 || ((display_type != DT_NOGRAPHIC) && (stdio_nb_clients != 0))) {
1954 return NULL;
1957 chr = g_malloc0(sizeof(CharDriverState));
1958 stdio = g_malloc0(sizeof(WinStdioCharState));
1960 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
1961 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
1962 fprintf(stderr, "cannot open stdio: invalid handle\n");
1963 exit(1);
1966 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
1968 chr->opaque = stdio;
1969 chr->chr_write = win_stdio_write;
1970 chr->chr_close = win_stdio_close;
1972 if (stdio_nb_clients == 0) {
1973 if (is_console) {
1974 if (qemu_add_wait_object(stdio->hStdIn,
1975 win_stdio_wait_func, chr)) {
1976 fprintf(stderr, "qemu_add_wait_object: failed\n");
1978 } else {
1979 DWORD dwId;
1981 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
1982 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
1983 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
1984 chr, 0, &dwId);
1986 if (stdio->hInputThread == INVALID_HANDLE_VALUE
1987 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
1988 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
1989 fprintf(stderr, "cannot create stdio thread or event\n");
1990 exit(1);
1992 if (qemu_add_wait_object(stdio->hInputReadyEvent,
1993 win_stdio_thread_wait_func, chr)) {
1994 fprintf(stderr, "qemu_add_wait_object: failed\n");
1999 dwMode |= ENABLE_LINE_INPUT;
2001 stdio_clients[stdio_nb_clients++] = chr;
2002 if (stdio_nb_clients == 1 && is_console) {
2003 /* set the terminal in raw mode */
2004 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2005 dwMode |= ENABLE_PROCESSED_INPUT;
2008 SetConsoleMode(stdio->hStdIn, dwMode);
2010 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2011 qemu_chr_fe_set_echo(chr, false);
2013 return chr;
2015 #endif /* !_WIN32 */
2017 /***********************************************************/
2018 /* UDP Net console */
2020 typedef struct {
2021 int fd;
2022 uint8_t buf[READ_BUF_LEN];
2023 int bufcnt;
2024 int bufptr;
2025 int max_size;
2026 } NetCharDriver;
2028 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2030 NetCharDriver *s = chr->opaque;
2032 return send(s->fd, (const void *)buf, len, 0);
2035 static int udp_chr_read_poll(void *opaque)
2037 CharDriverState *chr = opaque;
2038 NetCharDriver *s = chr->opaque;
2040 s->max_size = qemu_chr_be_can_write(chr);
2042 /* If there were any stray characters in the queue process them
2043 * first
2045 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2046 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2047 s->bufptr++;
2048 s->max_size = qemu_chr_be_can_write(chr);
2050 return s->max_size;
2053 static void udp_chr_read(void *opaque)
2055 CharDriverState *chr = opaque;
2056 NetCharDriver *s = chr->opaque;
2058 if (s->max_size == 0)
2059 return;
2060 s->bufcnt = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
2061 s->bufptr = s->bufcnt;
2062 if (s->bufcnt <= 0)
2063 return;
2065 s->bufptr = 0;
2066 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2067 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2068 s->bufptr++;
2069 s->max_size = qemu_chr_be_can_write(chr);
2073 static void udp_chr_update_read_handler(CharDriverState *chr)
2075 NetCharDriver *s = chr->opaque;
2077 if (s->fd >= 0) {
2078 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2079 udp_chr_read, NULL, chr);
2083 static void udp_chr_close(CharDriverState *chr)
2085 NetCharDriver *s = chr->opaque;
2086 if (s->fd >= 0) {
2087 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2088 closesocket(s->fd);
2090 g_free(s);
2091 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2094 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2096 CharDriverState *chr = NULL;
2097 NetCharDriver *s = NULL;
2098 int fd = -1;
2100 chr = g_malloc0(sizeof(CharDriverState));
2101 s = g_malloc0(sizeof(NetCharDriver));
2103 fd = inet_dgram_opts(opts);
2104 if (fd < 0) {
2105 fprintf(stderr, "inet_dgram_opts failed\n");
2106 goto return_err;
2109 s->fd = fd;
2110 s->bufcnt = 0;
2111 s->bufptr = 0;
2112 chr->opaque = s;
2113 chr->chr_write = udp_chr_write;
2114 chr->chr_update_read_handler = udp_chr_update_read_handler;
2115 chr->chr_close = udp_chr_close;
2116 return chr;
2118 return_err:
2119 g_free(chr);
2120 g_free(s);
2121 if (fd >= 0) {
2122 closesocket(fd);
2124 return NULL;
2127 /***********************************************************/
2128 /* TCP Net console */
2130 typedef struct {
2131 int fd, listen_fd;
2132 int connected;
2133 int max_size;
2134 int do_telnetopt;
2135 int do_nodelay;
2136 int is_unix;
2137 int msgfd;
2138 } TCPCharDriver;
2140 static void tcp_chr_accept(void *opaque);
2142 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2144 TCPCharDriver *s = chr->opaque;
2145 if (s->connected) {
2146 return send_all(s->fd, buf, len);
2147 } else {
2148 /* XXX: indicate an error ? */
2149 return len;
2153 static int tcp_chr_read_poll(void *opaque)
2155 CharDriverState *chr = opaque;
2156 TCPCharDriver *s = chr->opaque;
2157 if (!s->connected)
2158 return 0;
2159 s->max_size = qemu_chr_be_can_write(chr);
2160 return s->max_size;
2163 #define IAC 255
2164 #define IAC_BREAK 243
2165 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2166 TCPCharDriver *s,
2167 uint8_t *buf, int *size)
2169 /* Handle any telnet client's basic IAC options to satisfy char by
2170 * char mode with no echo. All IAC options will be removed from
2171 * the buf and the do_telnetopt variable will be used to track the
2172 * state of the width of the IAC information.
2174 * IAC commands come in sets of 3 bytes with the exception of the
2175 * "IAC BREAK" command and the double IAC.
2178 int i;
2179 int j = 0;
2181 for (i = 0; i < *size; i++) {
2182 if (s->do_telnetopt > 1) {
2183 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2184 /* Double IAC means send an IAC */
2185 if (j != i)
2186 buf[j] = buf[i];
2187 j++;
2188 s->do_telnetopt = 1;
2189 } else {
2190 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2191 /* Handle IAC break commands by sending a serial break */
2192 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2193 s->do_telnetopt++;
2195 s->do_telnetopt++;
2197 if (s->do_telnetopt >= 4) {
2198 s->do_telnetopt = 1;
2200 } else {
2201 if ((unsigned char)buf[i] == IAC) {
2202 s->do_telnetopt = 2;
2203 } else {
2204 if (j != i)
2205 buf[j] = buf[i];
2206 j++;
2210 *size = j;
2213 static int tcp_get_msgfd(CharDriverState *chr)
2215 TCPCharDriver *s = chr->opaque;
2216 int fd = s->msgfd;
2217 s->msgfd = -1;
2218 return fd;
2221 #ifndef _WIN32
2222 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2224 TCPCharDriver *s = chr->opaque;
2225 struct cmsghdr *cmsg;
2227 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2228 int fd;
2230 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2231 cmsg->cmsg_level != SOL_SOCKET ||
2232 cmsg->cmsg_type != SCM_RIGHTS)
2233 continue;
2235 fd = *((int *)CMSG_DATA(cmsg));
2236 if (fd < 0)
2237 continue;
2239 if (s->msgfd != -1)
2240 close(s->msgfd);
2241 s->msgfd = fd;
2245 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2247 TCPCharDriver *s = chr->opaque;
2248 struct msghdr msg = { NULL, };
2249 struct iovec iov[1];
2250 union {
2251 struct cmsghdr cmsg;
2252 char control[CMSG_SPACE(sizeof(int))];
2253 } msg_control;
2254 ssize_t ret;
2256 iov[0].iov_base = buf;
2257 iov[0].iov_len = len;
2259 msg.msg_iov = iov;
2260 msg.msg_iovlen = 1;
2261 msg.msg_control = &msg_control;
2262 msg.msg_controllen = sizeof(msg_control);
2264 ret = recvmsg(s->fd, &msg, 0);
2265 if (ret > 0 && s->is_unix)
2266 unix_process_msgfd(chr, &msg);
2268 return ret;
2270 #else
2271 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2273 TCPCharDriver *s = chr->opaque;
2274 return qemu_recv(s->fd, buf, len, 0);
2276 #endif
2278 static void tcp_chr_read(void *opaque)
2280 CharDriverState *chr = opaque;
2281 TCPCharDriver *s = chr->opaque;
2282 uint8_t buf[READ_BUF_LEN];
2283 int len, size;
2285 if (!s->connected || s->max_size <= 0)
2286 return;
2287 len = sizeof(buf);
2288 if (len > s->max_size)
2289 len = s->max_size;
2290 size = tcp_chr_recv(chr, (void *)buf, len);
2291 if (size == 0) {
2292 /* connection closed */
2293 s->connected = 0;
2294 if (s->listen_fd >= 0) {
2295 qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2297 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2298 closesocket(s->fd);
2299 s->fd = -1;
2300 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2301 } else if (size > 0) {
2302 if (s->do_telnetopt)
2303 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2304 if (size > 0)
2305 qemu_chr_be_write(chr, buf, size);
2309 #ifndef _WIN32
2310 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2312 return qemu_chr_open_fd(eventfd, eventfd);
2314 #endif
2316 static void tcp_chr_connect(void *opaque)
2318 CharDriverState *chr = opaque;
2319 TCPCharDriver *s = chr->opaque;
2321 s->connected = 1;
2322 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2323 tcp_chr_read, NULL, chr);
2324 qemu_chr_generic_open(chr);
2327 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2328 static void tcp_chr_telnet_init(int fd)
2330 char buf[3];
2331 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2332 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2333 send(fd, (char *)buf, 3, 0);
2334 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2335 send(fd, (char *)buf, 3, 0);
2336 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2337 send(fd, (char *)buf, 3, 0);
2338 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2339 send(fd, (char *)buf, 3, 0);
2342 static void socket_set_nodelay(int fd)
2344 int val = 1;
2345 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2348 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2350 TCPCharDriver *s = chr->opaque;
2351 if (s->fd != -1)
2352 return -1;
2354 socket_set_nonblock(fd);
2355 if (s->do_nodelay)
2356 socket_set_nodelay(fd);
2357 s->fd = fd;
2358 qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2359 tcp_chr_connect(chr);
2361 return 0;
2364 static void tcp_chr_accept(void *opaque)
2366 CharDriverState *chr = opaque;
2367 TCPCharDriver *s = chr->opaque;
2368 struct sockaddr_in saddr;
2369 #ifndef _WIN32
2370 struct sockaddr_un uaddr;
2371 #endif
2372 struct sockaddr *addr;
2373 socklen_t len;
2374 int fd;
2376 for(;;) {
2377 #ifndef _WIN32
2378 if (s->is_unix) {
2379 len = sizeof(uaddr);
2380 addr = (struct sockaddr *)&uaddr;
2381 } else
2382 #endif
2384 len = sizeof(saddr);
2385 addr = (struct sockaddr *)&saddr;
2387 fd = qemu_accept(s->listen_fd, addr, &len);
2388 if (fd < 0 && errno != EINTR) {
2389 return;
2390 } else if (fd >= 0) {
2391 if (s->do_telnetopt)
2392 tcp_chr_telnet_init(fd);
2393 break;
2396 if (tcp_chr_add_client(chr, fd) < 0)
2397 close(fd);
2400 static void tcp_chr_close(CharDriverState *chr)
2402 TCPCharDriver *s = chr->opaque;
2403 if (s->fd >= 0) {
2404 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2405 closesocket(s->fd);
2407 if (s->listen_fd >= 0) {
2408 qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2409 closesocket(s->listen_fd);
2411 g_free(s);
2412 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2415 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2417 CharDriverState *chr = NULL;
2418 TCPCharDriver *s = NULL;
2419 int fd = -1;
2420 int is_listen;
2421 int is_waitconnect;
2422 int do_nodelay;
2423 int is_unix;
2424 int is_telnet;
2426 is_listen = qemu_opt_get_bool(opts, "server", 0);
2427 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2428 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2429 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2430 is_unix = qemu_opt_get(opts, "path") != NULL;
2431 if (!is_listen)
2432 is_waitconnect = 0;
2434 chr = g_malloc0(sizeof(CharDriverState));
2435 s = g_malloc0(sizeof(TCPCharDriver));
2437 if (is_unix) {
2438 if (is_listen) {
2439 fd = unix_listen_opts(opts);
2440 } else {
2441 fd = unix_connect_opts(opts);
2443 } else {
2444 if (is_listen) {
2445 fd = inet_listen_opts(opts, 0);
2446 } else {
2447 fd = inet_connect_opts(opts);
2450 if (fd < 0) {
2451 goto fail;
2454 if (!is_waitconnect)
2455 socket_set_nonblock(fd);
2457 s->connected = 0;
2458 s->fd = -1;
2459 s->listen_fd = -1;
2460 s->msgfd = -1;
2461 s->is_unix = is_unix;
2462 s->do_nodelay = do_nodelay && !is_unix;
2464 chr->opaque = s;
2465 chr->chr_write = tcp_chr_write;
2466 chr->chr_close = tcp_chr_close;
2467 chr->get_msgfd = tcp_get_msgfd;
2468 chr->chr_add_client = tcp_chr_add_client;
2470 if (is_listen) {
2471 s->listen_fd = fd;
2472 qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2473 if (is_telnet)
2474 s->do_telnetopt = 1;
2476 } else {
2477 s->connected = 1;
2478 s->fd = fd;
2479 socket_set_nodelay(fd);
2480 tcp_chr_connect(chr);
2483 /* for "info chardev" monitor command */
2484 chr->filename = g_malloc(256);
2485 if (is_unix) {
2486 snprintf(chr->filename, 256, "unix:%s%s",
2487 qemu_opt_get(opts, "path"),
2488 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2489 } else if (is_telnet) {
2490 snprintf(chr->filename, 256, "telnet:%s:%s%s",
2491 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2492 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2493 } else {
2494 snprintf(chr->filename, 256, "tcp:%s:%s%s",
2495 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2496 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2499 if (is_listen && is_waitconnect) {
2500 printf("QEMU waiting for connection on: %s\n",
2501 chr->filename);
2502 tcp_chr_accept(chr);
2503 socket_set_nonblock(s->listen_fd);
2505 return chr;
2507 fail:
2508 if (fd >= 0)
2509 closesocket(fd);
2510 g_free(s);
2511 g_free(chr);
2512 return NULL;
2515 /***********************************************************/
2516 /* Memory chardev */
2517 typedef struct {
2518 size_t outbuf_size;
2519 size_t outbuf_capacity;
2520 uint8_t *outbuf;
2521 } MemoryDriver;
2523 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2525 MemoryDriver *d = chr->opaque;
2527 /* TODO: the QString implementation has the same code, we should
2528 * introduce a generic way to do this in cutils.c */
2529 if (d->outbuf_capacity < d->outbuf_size + len) {
2530 /* grow outbuf */
2531 d->outbuf_capacity += len;
2532 d->outbuf_capacity *= 2;
2533 d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
2536 memcpy(d->outbuf + d->outbuf_size, buf, len);
2537 d->outbuf_size += len;
2539 return len;
2542 void qemu_chr_init_mem(CharDriverState *chr)
2544 MemoryDriver *d;
2546 d = g_malloc(sizeof(*d));
2547 d->outbuf_size = 0;
2548 d->outbuf_capacity = 4096;
2549 d->outbuf = g_malloc0(d->outbuf_capacity);
2551 memset(chr, 0, sizeof(*chr));
2552 chr->opaque = d;
2553 chr->chr_write = mem_chr_write;
2556 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2558 MemoryDriver *d = chr->opaque;
2559 return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2562 /* NOTE: this driver can not be closed with qemu_chr_delete()! */
2563 void qemu_chr_close_mem(CharDriverState *chr)
2565 MemoryDriver *d = chr->opaque;
2567 g_free(d->outbuf);
2568 g_free(chr->opaque);
2569 chr->opaque = NULL;
2570 chr->chr_write = NULL;
2573 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2575 const MemoryDriver *d = chr->opaque;
2576 return d->outbuf_size;
2579 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2581 char host[65], port[33], width[8], height[8];
2582 int pos;
2583 const char *p;
2584 QemuOpts *opts;
2586 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1);
2587 if (NULL == opts)
2588 return NULL;
2590 if (strstart(filename, "mon:", &p)) {
2591 filename = p;
2592 qemu_opt_set(opts, "mux", "on");
2595 if (strcmp(filename, "null") == 0 ||
2596 strcmp(filename, "pty") == 0 ||
2597 strcmp(filename, "msmouse") == 0 ||
2598 strcmp(filename, "braille") == 0 ||
2599 strcmp(filename, "stdio") == 0) {
2600 qemu_opt_set(opts, "backend", filename);
2601 return opts;
2603 if (strstart(filename, "vc", &p)) {
2604 qemu_opt_set(opts, "backend", "vc");
2605 if (*p == ':') {
2606 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2607 /* pixels */
2608 qemu_opt_set(opts, "width", width);
2609 qemu_opt_set(opts, "height", height);
2610 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2611 /* chars */
2612 qemu_opt_set(opts, "cols", width);
2613 qemu_opt_set(opts, "rows", height);
2614 } else {
2615 goto fail;
2618 return opts;
2620 if (strcmp(filename, "con:") == 0) {
2621 qemu_opt_set(opts, "backend", "console");
2622 return opts;
2624 if (strstart(filename, "COM", NULL)) {
2625 qemu_opt_set(opts, "backend", "serial");
2626 qemu_opt_set(opts, "path", filename);
2627 return opts;
2629 if (strstart(filename, "file:", &p)) {
2630 qemu_opt_set(opts, "backend", "file");
2631 qemu_opt_set(opts, "path", p);
2632 return opts;
2634 if (strstart(filename, "pipe:", &p)) {
2635 qemu_opt_set(opts, "backend", "pipe");
2636 qemu_opt_set(opts, "path", p);
2637 return opts;
2639 if (strstart(filename, "tcp:", &p) ||
2640 strstart(filename, "telnet:", &p)) {
2641 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2642 host[0] = 0;
2643 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2644 goto fail;
2646 qemu_opt_set(opts, "backend", "socket");
2647 qemu_opt_set(opts, "host", host);
2648 qemu_opt_set(opts, "port", port);
2649 if (p[pos] == ',') {
2650 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2651 goto fail;
2653 if (strstart(filename, "telnet:", &p))
2654 qemu_opt_set(opts, "telnet", "on");
2655 return opts;
2657 if (strstart(filename, "udp:", &p)) {
2658 qemu_opt_set(opts, "backend", "udp");
2659 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2660 host[0] = 0;
2661 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
2662 goto fail;
2665 qemu_opt_set(opts, "host", host);
2666 qemu_opt_set(opts, "port", port);
2667 if (p[pos] == '@') {
2668 p += pos + 1;
2669 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2670 host[0] = 0;
2671 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2672 goto fail;
2675 qemu_opt_set(opts, "localaddr", host);
2676 qemu_opt_set(opts, "localport", port);
2678 return opts;
2680 if (strstart(filename, "unix:", &p)) {
2681 qemu_opt_set(opts, "backend", "socket");
2682 if (qemu_opts_do_parse(opts, p, "path") != 0)
2683 goto fail;
2684 return opts;
2686 if (strstart(filename, "/dev/parport", NULL) ||
2687 strstart(filename, "/dev/ppi", NULL)) {
2688 qemu_opt_set(opts, "backend", "parport");
2689 qemu_opt_set(opts, "path", filename);
2690 return opts;
2692 if (strstart(filename, "/dev/", NULL)) {
2693 qemu_opt_set(opts, "backend", "tty");
2694 qemu_opt_set(opts, "path", filename);
2695 return opts;
2698 fail:
2699 qemu_opts_del(opts);
2700 return NULL;
2703 static const struct {
2704 const char *name;
2705 CharDriverState *(*open)(QemuOpts *opts);
2706 } backend_table[] = {
2707 { .name = "null", .open = qemu_chr_open_null },
2708 { .name = "socket", .open = qemu_chr_open_socket },
2709 { .name = "udp", .open = qemu_chr_open_udp },
2710 { .name = "msmouse", .open = qemu_chr_open_msmouse },
2711 { .name = "vc", .open = text_console_init },
2712 #ifdef _WIN32
2713 { .name = "file", .open = qemu_chr_open_win_file_out },
2714 { .name = "pipe", .open = qemu_chr_open_win_pipe },
2715 { .name = "console", .open = qemu_chr_open_win_con },
2716 { .name = "serial", .open = qemu_chr_open_win },
2717 { .name = "stdio", .open = qemu_chr_open_win_stdio },
2718 #else
2719 { .name = "file", .open = qemu_chr_open_file_out },
2720 { .name = "pipe", .open = qemu_chr_open_pipe },
2721 { .name = "pty", .open = qemu_chr_open_pty },
2722 { .name = "stdio", .open = qemu_chr_open_stdio },
2723 #endif
2724 #ifdef CONFIG_BRLAPI
2725 { .name = "braille", .open = chr_baum_init },
2726 #endif
2727 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2728 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
2729 || defined(__FreeBSD_kernel__)
2730 { .name = "tty", .open = qemu_chr_open_tty },
2731 #endif
2732 #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) \
2733 || defined(__FreeBSD_kernel__)
2734 { .name = "parport", .open = qemu_chr_open_pp },
2735 #endif
2736 #ifdef CONFIG_SPICE
2737 { .name = "spicevmc", .open = qemu_chr_open_spice },
2738 #endif
2741 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
2742 void (*init)(struct CharDriverState *s))
2744 CharDriverState *chr;
2745 int i;
2747 if (qemu_opts_id(opts) == NULL) {
2748 fprintf(stderr, "chardev: no id specified\n");
2749 return NULL;
2752 if (qemu_opt_get(opts, "backend") == NULL) {
2753 fprintf(stderr, "chardev: \"%s\" missing backend\n",
2754 qemu_opts_id(opts));
2755 return NULL;
2757 for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
2758 if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
2759 break;
2761 if (i == ARRAY_SIZE(backend_table)) {
2762 fprintf(stderr, "chardev: backend \"%s\" not found\n",
2763 qemu_opt_get(opts, "backend"));
2764 return NULL;
2767 chr = backend_table[i].open(opts);
2768 if (!chr) {
2769 fprintf(stderr, "chardev: opening backend \"%s\" failed\n",
2770 qemu_opt_get(opts, "backend"));
2771 return NULL;
2774 if (!chr->filename)
2775 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
2776 chr->init = init;
2777 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2779 if (qemu_opt_get_bool(opts, "mux", 0)) {
2780 CharDriverState *base = chr;
2781 int len = strlen(qemu_opts_id(opts)) + 6;
2782 base->label = g_malloc(len);
2783 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
2784 chr = qemu_chr_open_mux(base);
2785 chr->filename = base->filename;
2786 chr->avail_connections = MAX_MUX;
2787 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2788 } else {
2789 chr->avail_connections = 1;
2791 chr->label = g_strdup(qemu_opts_id(opts));
2792 return chr;
2795 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2797 const char *p;
2798 CharDriverState *chr;
2799 QemuOpts *opts;
2801 if (strstart(filename, "chardev:", &p)) {
2802 return qemu_chr_find(p);
2805 opts = qemu_chr_parse_compat(label, filename);
2806 if (!opts)
2807 return NULL;
2809 chr = qemu_chr_new_from_opts(opts, init);
2810 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
2811 monitor_init(chr, MONITOR_USE_READLINE);
2813 qemu_opts_del(opts);
2814 return chr;
2817 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
2819 if (chr->chr_set_echo) {
2820 chr->chr_set_echo(chr, echo);
2824 void qemu_chr_fe_open(struct CharDriverState *chr)
2826 if (chr->chr_guest_open) {
2827 chr->chr_guest_open(chr);
2831 void qemu_chr_fe_close(struct CharDriverState *chr)
2833 if (chr->chr_guest_close) {
2834 chr->chr_guest_close(chr);
2838 void qemu_chr_delete(CharDriverState *chr)
2840 QTAILQ_REMOVE(&chardevs, chr, next);
2841 if (chr->chr_close)
2842 chr->chr_close(chr);
2843 g_free(chr->filename);
2844 g_free(chr->label);
2845 g_free(chr);
2848 ChardevInfoList *qmp_query_chardev(Error **errp)
2850 ChardevInfoList *chr_list = NULL;
2851 CharDriverState *chr;
2853 QTAILQ_FOREACH(chr, &chardevs, next) {
2854 ChardevInfoList *info = g_malloc0(sizeof(*info));
2855 info->value = g_malloc0(sizeof(*info->value));
2856 info->value->label = g_strdup(chr->label);
2857 info->value->filename = g_strdup(chr->filename);
2859 info->next = chr_list;
2860 chr_list = info;
2863 return chr_list;
2866 CharDriverState *qemu_chr_find(const char *name)
2868 CharDriverState *chr;
2870 QTAILQ_FOREACH(chr, &chardevs, next) {
2871 if (strcmp(chr->label, name) != 0)
2872 continue;
2873 return chr;
2875 return NULL;
2878 /* Get a character (serial) device interface. */
2879 CharDriverState *qemu_char_get_next_serial(void)
2881 static int next_serial;
2883 /* FIXME: This function needs to go away: use chardev properties! */
2884 return serial_hds[next_serial++];