usb: add serial bus property
[qemu/kevin.git] / qemu-char.c
blob2c3cfe6b69bbbb8677d6a5a6275277811f190c3c
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 "monitor/monitor.h"
26 #include "ui/console.h"
27 #include "sysemu/sysemu.h"
28 #include "qemu/timer.h"
29 #include "sysemu/char.h"
30 #include "hw/usb.h"
31 #include "qmp-commands.h"
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <time.h>
36 #include <errno.h>
37 #include <sys/time.h>
38 #include <zlib.h>
40 #ifndef _WIN32
41 #include <sys/times.h>
42 #include <sys/wait.h>
43 #include <termios.h>
44 #include <sys/mman.h>
45 #include <sys/ioctl.h>
46 #include <sys/resource.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #include <net/if.h>
50 #include <arpa/inet.h>
51 #include <dirent.h>
52 #include <netdb.h>
53 #include <sys/select.h>
54 #ifdef CONFIG_BSD
55 #include <sys/stat.h>
56 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
57 #include <dev/ppbus/ppi.h>
58 #include <dev/ppbus/ppbconf.h>
59 #elif defined(__DragonFly__)
60 #include <dev/misc/ppi/ppi.h>
61 #include <bus/ppbus/ppbconf.h>
62 #endif
63 #else
64 #ifdef __linux__
65 #include <linux/ppdev.h>
66 #include <linux/parport.h>
67 #endif
68 #ifdef __sun__
69 #include <sys/stat.h>
70 #include <sys/ethernet.h>
71 #include <sys/sockio.h>
72 #include <netinet/arp.h>
73 #include <netinet/in.h>
74 #include <netinet/in_systm.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_icmp.h> // must come after ip.h
77 #include <netinet/udp.h>
78 #include <netinet/tcp.h>
79 #endif
80 #endif
81 #endif
83 #include "qemu/sockets.h"
84 #include "ui/qemu-spice.h"
86 #define READ_BUF_LEN 4096
88 /***********************************************************/
89 /* character device */
91 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
92 QTAILQ_HEAD_INITIALIZER(chardevs);
94 void qemu_chr_be_event(CharDriverState *s, int event)
96 /* Keep track if the char device is open */
97 switch (event) {
98 case CHR_EVENT_OPENED:
99 s->be_open = 1;
100 break;
101 case CHR_EVENT_CLOSED:
102 s->be_open = 0;
103 break;
106 if (!s->chr_event)
107 return;
108 s->chr_event(s->handler_opaque, event);
111 void qemu_chr_be_generic_open(CharDriverState *s)
113 qemu_chr_be_event(s, CHR_EVENT_OPENED);
116 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
118 return s->chr_write(s, buf, len);
121 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
123 int offset = 0;
124 int res;
126 while (offset < len) {
127 do {
128 res = s->chr_write(s, buf + offset, len - offset);
129 if (res == -1 && errno == EAGAIN) {
130 g_usleep(100);
132 } while (res == -1 && errno == EAGAIN);
134 if (res == 0) {
135 break;
138 if (res < 0) {
139 return res;
142 offset += res;
145 return offset;
148 int qemu_chr_fe_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_be_can_write(CharDriverState *s)
157 if (!s->chr_can_read)
158 return 0;
159 return s->chr_can_read(s->handler_opaque);
162 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
164 if (s->chr_read) {
165 s->chr_read(s->handler_opaque, buf, len);
169 int qemu_chr_fe_get_msgfd(CharDriverState *s)
171 return s->get_msgfd ? s->get_msgfd(s) : -1;
174 int qemu_chr_add_client(CharDriverState *s, int fd)
176 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
179 void qemu_chr_accept_input(CharDriverState *s)
181 if (s->chr_accept_input)
182 s->chr_accept_input(s);
183 qemu_notify_event();
186 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
188 char buf[READ_BUF_LEN];
189 va_list ap;
190 va_start(ap, fmt);
191 vsnprintf(buf, sizeof(buf), fmt, ap);
192 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
193 va_end(ap);
196 void qemu_chr_add_handlers(CharDriverState *s,
197 IOCanReadHandler *fd_can_read,
198 IOReadHandler *fd_read,
199 IOEventHandler *fd_event,
200 void *opaque)
202 int fe_open;
204 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
205 fe_open = 0;
206 } else {
207 fe_open = 1;
209 s->chr_can_read = fd_can_read;
210 s->chr_read = fd_read;
211 s->chr_event = fd_event;
212 s->handler_opaque = opaque;
213 if (s->chr_update_read_handler)
214 s->chr_update_read_handler(s);
216 if (!s->explicit_fe_open) {
217 qemu_chr_fe_set_open(s, fe_open);
220 /* We're connecting to an already opened device, so let's make sure we
221 also get the open event */
222 if (fe_open && s->be_open) {
223 qemu_chr_be_generic_open(s);
227 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
229 return len;
232 static CharDriverState *qemu_chr_open_null(void)
234 CharDriverState *chr;
236 chr = g_malloc0(sizeof(CharDriverState));
237 chr->chr_write = null_chr_write;
238 chr->explicit_be_open = true;
239 return chr;
242 /* MUX driver for serial I/O splitting */
243 #define MAX_MUX 4
244 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
245 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
246 typedef struct {
247 IOCanReadHandler *chr_can_read[MAX_MUX];
248 IOReadHandler *chr_read[MAX_MUX];
249 IOEventHandler *chr_event[MAX_MUX];
250 void *ext_opaque[MAX_MUX];
251 CharDriverState *drv;
252 int focus;
253 int mux_cnt;
254 int term_got_escape;
255 int max_size;
256 /* Intermediate input buffer allows to catch escape sequences even if the
257 currently active device is not accepting any input - but only until it
258 is full as well. */
259 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
260 int prod[MAX_MUX];
261 int cons[MAX_MUX];
262 int timestamps;
263 int linestart;
264 int64_t timestamps_start;
265 } MuxDriver;
268 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
270 MuxDriver *d = chr->opaque;
271 int ret;
272 if (!d->timestamps) {
273 ret = d->drv->chr_write(d->drv, buf, len);
274 } else {
275 int i;
277 ret = 0;
278 for (i = 0; i < len; i++) {
279 if (d->linestart) {
280 char buf1[64];
281 int64_t ti;
282 int secs;
284 ti = qemu_get_clock_ms(rt_clock);
285 if (d->timestamps_start == -1)
286 d->timestamps_start = ti;
287 ti -= d->timestamps_start;
288 secs = ti / 1000;
289 snprintf(buf1, sizeof(buf1),
290 "[%02d:%02d:%02d.%03d] ",
291 secs / 3600,
292 (secs / 60) % 60,
293 secs % 60,
294 (int)(ti % 1000));
295 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
296 d->linestart = 0;
298 ret += d->drv->chr_write(d->drv, buf+i, 1);
299 if (buf[i] == '\n') {
300 d->linestart = 1;
304 return ret;
307 static const char * const mux_help[] = {
308 "% h print this help\n\r",
309 "% x exit emulator\n\r",
310 "% s save disk data back to file (if -snapshot)\n\r",
311 "% t toggle console timestamps\n\r"
312 "% b send break (magic sysrq)\n\r",
313 "% c switch between console and monitor\n\r",
314 "% % sends %\n\r",
315 NULL
318 int term_escape_char = 0x01; /* ctrl-a is used for escape */
319 static void mux_print_help(CharDriverState *chr)
321 int i, j;
322 char ebuf[15] = "Escape-Char";
323 char cbuf[50] = "\n\r";
325 if (term_escape_char > 0 && term_escape_char < 26) {
326 snprintf(cbuf, sizeof(cbuf), "\n\r");
327 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
328 } else {
329 snprintf(cbuf, sizeof(cbuf),
330 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
331 term_escape_char);
333 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
334 for (i = 0; mux_help[i] != NULL; i++) {
335 for (j=0; mux_help[i][j] != '\0'; j++) {
336 if (mux_help[i][j] == '%')
337 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
338 else
339 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
344 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
346 if (d->chr_event[mux_nr])
347 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
350 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
352 if (d->term_got_escape) {
353 d->term_got_escape = 0;
354 if (ch == term_escape_char)
355 goto send_char;
356 switch(ch) {
357 case '?':
358 case 'h':
359 mux_print_help(chr);
360 break;
361 case 'x':
363 const char *term = "QEMU: Terminated\n\r";
364 chr->chr_write(chr,(uint8_t *)term,strlen(term));
365 exit(0);
366 break;
368 case 's':
369 bdrv_commit_all();
370 break;
371 case 'b':
372 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
373 break;
374 case 'c':
375 /* Switch to the next registered device */
376 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
377 d->focus++;
378 if (d->focus >= d->mux_cnt)
379 d->focus = 0;
380 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
381 break;
382 case 't':
383 d->timestamps = !d->timestamps;
384 d->timestamps_start = -1;
385 d->linestart = 0;
386 break;
388 } else if (ch == term_escape_char) {
389 d->term_got_escape = 1;
390 } else {
391 send_char:
392 return 1;
394 return 0;
397 static void mux_chr_accept_input(CharDriverState *chr)
399 MuxDriver *d = chr->opaque;
400 int m = d->focus;
402 while (d->prod[m] != d->cons[m] &&
403 d->chr_can_read[m] &&
404 d->chr_can_read[m](d->ext_opaque[m])) {
405 d->chr_read[m](d->ext_opaque[m],
406 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
410 static int mux_chr_can_read(void *opaque)
412 CharDriverState *chr = opaque;
413 MuxDriver *d = chr->opaque;
414 int m = d->focus;
416 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
417 return 1;
418 if (d->chr_can_read[m])
419 return d->chr_can_read[m](d->ext_opaque[m]);
420 return 0;
423 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
425 CharDriverState *chr = opaque;
426 MuxDriver *d = chr->opaque;
427 int m = d->focus;
428 int i;
430 mux_chr_accept_input (opaque);
432 for(i = 0; i < size; i++)
433 if (mux_proc_byte(chr, d, buf[i])) {
434 if (d->prod[m] == d->cons[m] &&
435 d->chr_can_read[m] &&
436 d->chr_can_read[m](d->ext_opaque[m]))
437 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
438 else
439 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
443 static void mux_chr_event(void *opaque, int event)
445 CharDriverState *chr = opaque;
446 MuxDriver *d = chr->opaque;
447 int i;
449 /* Send the event to all registered listeners */
450 for (i = 0; i < d->mux_cnt; i++)
451 mux_chr_send_event(d, i, event);
454 static void mux_chr_update_read_handler(CharDriverState *chr)
456 MuxDriver *d = chr->opaque;
458 if (d->mux_cnt >= MAX_MUX) {
459 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
460 return;
462 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
463 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
464 d->chr_read[d->mux_cnt] = chr->chr_read;
465 d->chr_event[d->mux_cnt] = chr->chr_event;
466 /* Fix up the real driver with mux routines */
467 if (d->mux_cnt == 0) {
468 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
469 mux_chr_event, chr);
471 if (d->focus != -1) {
472 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
474 d->focus = d->mux_cnt;
475 d->mux_cnt++;
476 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
479 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
481 CharDriverState *chr;
482 MuxDriver *d;
484 chr = g_malloc0(sizeof(CharDriverState));
485 d = g_malloc0(sizeof(MuxDriver));
487 chr->opaque = d;
488 d->drv = drv;
489 d->focus = -1;
490 chr->chr_write = mux_chr_write;
491 chr->chr_update_read_handler = mux_chr_update_read_handler;
492 chr->chr_accept_input = mux_chr_accept_input;
493 /* Frontend guest-open / -close notification is not support with muxes */
494 chr->chr_set_fe_open = NULL;
496 return chr;
500 #ifdef _WIN32
501 int send_all(int fd, const void *buf, int len1)
503 int ret, len;
505 len = len1;
506 while (len > 0) {
507 ret = send(fd, buf, len, 0);
508 if (ret < 0) {
509 errno = WSAGetLastError();
510 if (errno != WSAEWOULDBLOCK) {
511 return -1;
513 } else if (ret == 0) {
514 break;
515 } else {
516 buf += ret;
517 len -= ret;
520 return len1 - len;
523 #else
525 int send_all(int fd, const void *_buf, int len1)
527 int ret, len;
528 const uint8_t *buf = _buf;
530 len = len1;
531 while (len > 0) {
532 ret = write(fd, buf, len);
533 if (ret < 0) {
534 if (errno != EINTR && errno != EAGAIN)
535 return -1;
536 } else if (ret == 0) {
537 break;
538 } else {
539 buf += ret;
540 len -= ret;
543 return len1 - len;
546 int recv_all(int fd, void *_buf, int len1, bool single_read)
548 int ret, len;
549 uint8_t *buf = _buf;
551 len = len1;
552 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
553 if (ret < 0) {
554 if (errno != EINTR && errno != EAGAIN) {
555 return -1;
557 continue;
558 } else {
559 if (single_read) {
560 return ret;
562 buf += ret;
563 len -= ret;
566 return len1 - len;
569 #endif /* !_WIN32 */
571 typedef struct IOWatchPoll
573 GSource parent;
575 GIOChannel *channel;
576 GSource *src;
578 IOCanReadHandler *fd_can_read;
579 GSourceFunc fd_read;
580 void *opaque;
581 } IOWatchPoll;
583 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
585 return container_of(source, IOWatchPoll, parent);
588 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
590 IOWatchPoll *iwp = io_watch_poll_from_source(source);
591 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
592 bool was_active = iwp->src != NULL;
593 if (was_active == now_active) {
594 return FALSE;
597 if (now_active) {
598 iwp->src = g_io_create_watch(iwp->channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
599 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
600 g_source_attach(iwp->src, NULL);
601 } else {
602 g_source_destroy(iwp->src);
603 g_source_unref(iwp->src);
604 iwp->src = NULL;
606 return FALSE;
609 static gboolean io_watch_poll_check(GSource *source)
611 return FALSE;
614 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
615 gpointer user_data)
617 abort();
620 static void io_watch_poll_finalize(GSource *source)
622 /* Due to a glib bug, removing the last reference to a source
623 * inside a finalize callback causes recursive locking (and a
624 * deadlock). This is not a problem inside other callbacks,
625 * including dispatch callbacks, so we call io_remove_watch_poll
626 * to remove this source. At this point, iwp->src must
627 * be NULL, or we would leak it.
629 * This would be solved much more elegantly by child sources,
630 * but we support older glib versions that do not have them.
632 IOWatchPoll *iwp = io_watch_poll_from_source(source);
633 assert(iwp->src == NULL);
636 static GSourceFuncs io_watch_poll_funcs = {
637 .prepare = io_watch_poll_prepare,
638 .check = io_watch_poll_check,
639 .dispatch = io_watch_poll_dispatch,
640 .finalize = io_watch_poll_finalize,
643 /* Can only be used for read */
644 static guint io_add_watch_poll(GIOChannel *channel,
645 IOCanReadHandler *fd_can_read,
646 GIOFunc fd_read,
647 gpointer user_data)
649 IOWatchPoll *iwp;
650 int tag;
652 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
653 iwp->fd_can_read = fd_can_read;
654 iwp->opaque = user_data;
655 iwp->channel = channel;
656 iwp->fd_read = (GSourceFunc) fd_read;
657 iwp->src = NULL;
659 tag = g_source_attach(&iwp->parent, NULL);
660 g_source_unref(&iwp->parent);
661 return tag;
664 static void io_remove_watch_poll(guint tag)
666 GSource *source;
667 IOWatchPoll *iwp;
669 g_return_if_fail (tag > 0);
671 source = g_main_context_find_source_by_id(NULL, tag);
672 g_return_if_fail (source != NULL);
674 iwp = io_watch_poll_from_source(source);
675 if (iwp->src) {
676 g_source_destroy(iwp->src);
677 g_source_unref(iwp->src);
678 iwp->src = NULL;
680 g_source_destroy(&iwp->parent);
683 #ifndef _WIN32
684 static GIOChannel *io_channel_from_fd(int fd)
686 GIOChannel *chan;
688 if (fd == -1) {
689 return NULL;
692 chan = g_io_channel_unix_new(fd);
694 g_io_channel_set_encoding(chan, NULL, NULL);
695 g_io_channel_set_buffered(chan, FALSE);
697 return chan;
699 #endif
701 static GIOChannel *io_channel_from_socket(int fd)
703 GIOChannel *chan;
705 if (fd == -1) {
706 return NULL;
709 #ifdef _WIN32
710 chan = g_io_channel_win32_new_socket(fd);
711 #else
712 chan = g_io_channel_unix_new(fd);
713 #endif
715 g_io_channel_set_encoding(chan, NULL, NULL);
716 g_io_channel_set_buffered(chan, FALSE);
718 return chan;
721 static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
723 GIOStatus status;
724 size_t offset;
726 offset = 0;
727 while (offset < len) {
728 gsize bytes_written;
730 status = g_io_channel_write_chars(fd, buf + offset, len - offset,
731 &bytes_written, NULL);
732 if (status != G_IO_STATUS_NORMAL) {
733 if (status == G_IO_STATUS_AGAIN) {
734 /* If we've written any data, return a partial write. */
735 if (offset) {
736 break;
738 errno = EAGAIN;
739 } else {
740 errno = EINVAL;
743 return -1;
744 } else if (status == G_IO_STATUS_EOF) {
745 break;
748 offset += bytes_written;
751 return offset;
754 #ifndef _WIN32
756 typedef struct FDCharDriver {
757 CharDriverState *chr;
758 GIOChannel *fd_in, *fd_out;
759 guint fd_in_tag;
760 int max_size;
761 QTAILQ_ENTRY(FDCharDriver) node;
762 } FDCharDriver;
764 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
766 FDCharDriver *s = chr->opaque;
768 return io_channel_send(s->fd_out, buf, len);
771 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
773 CharDriverState *chr = opaque;
774 FDCharDriver *s = chr->opaque;
775 int len;
776 uint8_t buf[READ_BUF_LEN];
777 GIOStatus status;
778 gsize bytes_read;
780 len = sizeof(buf);
781 if (len > s->max_size) {
782 len = s->max_size;
784 if (len == 0) {
785 return TRUE;
788 status = g_io_channel_read_chars(chan, (gchar *)buf,
789 len, &bytes_read, NULL);
790 if (status == G_IO_STATUS_EOF) {
791 if (s->fd_in_tag) {
792 io_remove_watch_poll(s->fd_in_tag);
793 s->fd_in_tag = 0;
795 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
796 return FALSE;
798 if (status == G_IO_STATUS_NORMAL) {
799 qemu_chr_be_write(chr, buf, bytes_read);
802 return TRUE;
805 static int fd_chr_read_poll(void *opaque)
807 CharDriverState *chr = opaque;
808 FDCharDriver *s = chr->opaque;
810 s->max_size = qemu_chr_be_can_write(chr);
811 return s->max_size;
814 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
816 FDCharDriver *s = chr->opaque;
817 return g_io_create_watch(s->fd_out, cond);
820 static void fd_chr_update_read_handler(CharDriverState *chr)
822 FDCharDriver *s = chr->opaque;
824 if (s->fd_in_tag) {
825 io_remove_watch_poll(s->fd_in_tag);
826 s->fd_in_tag = 0;
829 if (s->fd_in) {
830 s->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll, fd_chr_read, chr);
834 static void fd_chr_close(struct CharDriverState *chr)
836 FDCharDriver *s = chr->opaque;
838 if (s->fd_in_tag) {
839 io_remove_watch_poll(s->fd_in_tag);
840 s->fd_in_tag = 0;
843 if (s->fd_in) {
844 g_io_channel_unref(s->fd_in);
846 if (s->fd_out) {
847 g_io_channel_unref(s->fd_out);
850 g_free(s);
851 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
854 /* open a character device to a unix fd */
855 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
857 CharDriverState *chr;
858 FDCharDriver *s;
860 chr = g_malloc0(sizeof(CharDriverState));
861 s = g_malloc0(sizeof(FDCharDriver));
862 s->fd_in = io_channel_from_fd(fd_in);
863 s->fd_out = io_channel_from_fd(fd_out);
864 fcntl(fd_out, F_SETFL, O_NONBLOCK);
865 s->chr = chr;
866 chr->opaque = s;
867 chr->chr_add_watch = fd_chr_add_watch;
868 chr->chr_write = fd_chr_write;
869 chr->chr_update_read_handler = fd_chr_update_read_handler;
870 chr->chr_close = fd_chr_close;
872 return chr;
875 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
877 int fd_in, fd_out;
878 char filename_in[256], filename_out[256];
879 const char *filename = opts->device;
881 if (filename == NULL) {
882 fprintf(stderr, "chardev: pipe: no filename given\n");
883 return NULL;
886 snprintf(filename_in, 256, "%s.in", filename);
887 snprintf(filename_out, 256, "%s.out", filename);
888 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
889 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
890 if (fd_in < 0 || fd_out < 0) {
891 if (fd_in >= 0)
892 close(fd_in);
893 if (fd_out >= 0)
894 close(fd_out);
895 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
896 if (fd_in < 0) {
897 return NULL;
900 return qemu_chr_open_fd(fd_in, fd_out);
903 /* init terminal so that we can grab keys */
904 static struct termios oldtty;
905 static int old_fd0_flags;
906 static bool stdio_allow_signal;
908 static void term_exit(void)
910 tcsetattr (0, TCSANOW, &oldtty);
911 fcntl(0, F_SETFL, old_fd0_flags);
914 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
916 struct termios tty;
918 tty = oldtty;
919 if (!echo) {
920 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
921 |INLCR|IGNCR|ICRNL|IXON);
922 tty.c_oflag |= OPOST;
923 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
924 tty.c_cflag &= ~(CSIZE|PARENB);
925 tty.c_cflag |= CS8;
926 tty.c_cc[VMIN] = 1;
927 tty.c_cc[VTIME] = 0;
929 /* if graphical mode, we allow Ctrl-C handling */
930 if (!stdio_allow_signal)
931 tty.c_lflag &= ~ISIG;
933 tcsetattr (0, TCSANOW, &tty);
936 static void qemu_chr_close_stdio(struct CharDriverState *chr)
938 term_exit();
939 fd_chr_close(chr);
942 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
944 CharDriverState *chr;
946 if (is_daemonized()) {
947 error_report("cannot use stdio with -daemonize");
948 return NULL;
950 old_fd0_flags = fcntl(0, F_GETFL);
951 tcgetattr (0, &oldtty);
952 fcntl(0, F_SETFL, O_NONBLOCK);
953 atexit(term_exit);
955 chr = qemu_chr_open_fd(0, 1);
956 chr->chr_close = qemu_chr_close_stdio;
957 chr->chr_set_echo = qemu_chr_set_echo_stdio;
958 stdio_allow_signal = display_type != DT_NOGRAPHIC;
959 if (opts->has_signal) {
960 stdio_allow_signal = opts->signal;
962 qemu_chr_fe_set_echo(chr, false);
964 return chr;
967 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
968 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
969 || defined(__GLIBC__)
971 #define HAVE_CHARDEV_TTY 1
973 typedef struct {
974 GIOChannel *fd;
975 guint fd_tag;
976 int connected;
977 int read_bytes;
978 guint timer_tag;
979 } PtyCharDriver;
981 static void pty_chr_update_read_handler(CharDriverState *chr);
982 static void pty_chr_state(CharDriverState *chr, int connected);
984 static gboolean pty_chr_timer(gpointer opaque)
986 struct CharDriverState *chr = opaque;
987 PtyCharDriver *s = chr->opaque;
989 if (s->connected) {
990 goto out;
993 /* Next poll ... */
994 pty_chr_update_read_handler(chr);
996 out:
997 s->timer_tag = 0;
998 return FALSE;
1001 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1003 PtyCharDriver *s = chr->opaque;
1005 if (s->timer_tag) {
1006 g_source_remove(s->timer_tag);
1007 s->timer_tag = 0;
1010 if (ms == 1000) {
1011 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1012 } else {
1013 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1017 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1019 PtyCharDriver *s = chr->opaque;
1021 if (!s->connected) {
1022 /* guest sends data, check for (re-)connect */
1023 pty_chr_update_read_handler(chr);
1024 return 0;
1026 return io_channel_send(s->fd, buf, len);
1029 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1031 PtyCharDriver *s = chr->opaque;
1032 return g_io_create_watch(s->fd, cond);
1035 static int pty_chr_read_poll(void *opaque)
1037 CharDriverState *chr = opaque;
1038 PtyCharDriver *s = chr->opaque;
1040 s->read_bytes = qemu_chr_be_can_write(chr);
1041 return s->read_bytes;
1044 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1046 CharDriverState *chr = opaque;
1047 PtyCharDriver *s = chr->opaque;
1048 gsize size, len;
1049 uint8_t buf[READ_BUF_LEN];
1050 GIOStatus status;
1052 len = sizeof(buf);
1053 if (len > s->read_bytes)
1054 len = s->read_bytes;
1055 if (len == 0) {
1056 return TRUE;
1058 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1059 if (status != G_IO_STATUS_NORMAL) {
1060 pty_chr_state(chr, 0);
1061 return FALSE;
1062 } else {
1063 pty_chr_state(chr, 1);
1064 qemu_chr_be_write(chr, buf, size);
1066 return TRUE;
1069 static void pty_chr_update_read_handler(CharDriverState *chr)
1071 PtyCharDriver *s = chr->opaque;
1072 GPollFD pfd;
1074 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1075 pfd.events = G_IO_OUT;
1076 pfd.revents = 0;
1077 g_poll(&pfd, 1, 0);
1078 if (pfd.revents & G_IO_HUP) {
1079 pty_chr_state(chr, 0);
1080 } else {
1081 pty_chr_state(chr, 1);
1085 static void pty_chr_state(CharDriverState *chr, int connected)
1087 PtyCharDriver *s = chr->opaque;
1089 if (!connected) {
1090 if (s->fd_tag) {
1091 io_remove_watch_poll(s->fd_tag);
1092 s->fd_tag = 0;
1094 s->connected = 0;
1095 /* (re-)connect poll interval for idle guests: once per second.
1096 * We check more frequently in case the guests sends data to
1097 * the virtual device linked to our pty. */
1098 pty_chr_rearm_timer(chr, 1000);
1099 } else {
1100 if (s->timer_tag) {
1101 g_source_remove(s->timer_tag);
1102 s->timer_tag = 0;
1104 if (!s->connected) {
1105 qemu_chr_be_generic_open(chr);
1106 s->connected = 1;
1107 s->fd_tag = io_add_watch_poll(s->fd, pty_chr_read_poll, pty_chr_read, chr);
1113 static void pty_chr_close(struct CharDriverState *chr)
1115 PtyCharDriver *s = chr->opaque;
1116 int fd;
1118 if (s->fd_tag) {
1119 io_remove_watch_poll(s->fd_tag);
1120 s->fd_tag = 0;
1122 fd = g_io_channel_unix_get_fd(s->fd);
1123 g_io_channel_unref(s->fd);
1124 close(fd);
1125 if (s->timer_tag) {
1126 g_source_remove(s->timer_tag);
1127 s->timer_tag = 0;
1129 g_free(s);
1130 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1133 static CharDriverState *qemu_chr_open_pty(const char *id,
1134 ChardevReturn *ret)
1136 CharDriverState *chr;
1137 PtyCharDriver *s;
1138 int master_fd, slave_fd;
1139 char pty_name[PATH_MAX];
1141 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1142 if (master_fd < 0) {
1143 return NULL;
1146 close(slave_fd);
1148 chr = g_malloc0(sizeof(CharDriverState));
1150 chr->filename = g_strdup_printf("pty:%s", pty_name);
1151 ret->pty = g_strdup(pty_name);
1152 ret->has_pty = true;
1154 fprintf(stderr, "char device redirected to %s (label %s)\n",
1155 pty_name, id);
1157 s = g_malloc0(sizeof(PtyCharDriver));
1158 chr->opaque = s;
1159 chr->chr_write = pty_chr_write;
1160 chr->chr_update_read_handler = pty_chr_update_read_handler;
1161 chr->chr_close = pty_chr_close;
1162 chr->chr_add_watch = pty_chr_add_watch;
1163 chr->explicit_be_open = true;
1165 s->fd = io_channel_from_fd(master_fd);
1166 s->timer_tag = 0;
1168 return chr;
1171 static void tty_serial_init(int fd, int speed,
1172 int parity, int data_bits, int stop_bits)
1174 struct termios tty;
1175 speed_t spd;
1177 #if 0
1178 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1179 speed, parity, data_bits, stop_bits);
1180 #endif
1181 tcgetattr (fd, &tty);
1183 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1184 speed = speed * 10 / 11;
1185 do {
1186 check_speed(50);
1187 check_speed(75);
1188 check_speed(110);
1189 check_speed(134);
1190 check_speed(150);
1191 check_speed(200);
1192 check_speed(300);
1193 check_speed(600);
1194 check_speed(1200);
1195 check_speed(1800);
1196 check_speed(2400);
1197 check_speed(4800);
1198 check_speed(9600);
1199 check_speed(19200);
1200 check_speed(38400);
1201 /* Non-Posix values follow. They may be unsupported on some systems. */
1202 check_speed(57600);
1203 check_speed(115200);
1204 #ifdef B230400
1205 check_speed(230400);
1206 #endif
1207 #ifdef B460800
1208 check_speed(460800);
1209 #endif
1210 #ifdef B500000
1211 check_speed(500000);
1212 #endif
1213 #ifdef B576000
1214 check_speed(576000);
1215 #endif
1216 #ifdef B921600
1217 check_speed(921600);
1218 #endif
1219 #ifdef B1000000
1220 check_speed(1000000);
1221 #endif
1222 #ifdef B1152000
1223 check_speed(1152000);
1224 #endif
1225 #ifdef B1500000
1226 check_speed(1500000);
1227 #endif
1228 #ifdef B2000000
1229 check_speed(2000000);
1230 #endif
1231 #ifdef B2500000
1232 check_speed(2500000);
1233 #endif
1234 #ifdef B3000000
1235 check_speed(3000000);
1236 #endif
1237 #ifdef B3500000
1238 check_speed(3500000);
1239 #endif
1240 #ifdef B4000000
1241 check_speed(4000000);
1242 #endif
1243 spd = B115200;
1244 } while (0);
1246 cfsetispeed(&tty, spd);
1247 cfsetospeed(&tty, spd);
1249 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1250 |INLCR|IGNCR|ICRNL|IXON);
1251 tty.c_oflag |= OPOST;
1252 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1253 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1254 switch(data_bits) {
1255 default:
1256 case 8:
1257 tty.c_cflag |= CS8;
1258 break;
1259 case 7:
1260 tty.c_cflag |= CS7;
1261 break;
1262 case 6:
1263 tty.c_cflag |= CS6;
1264 break;
1265 case 5:
1266 tty.c_cflag |= CS5;
1267 break;
1269 switch(parity) {
1270 default:
1271 case 'N':
1272 break;
1273 case 'E':
1274 tty.c_cflag |= PARENB;
1275 break;
1276 case 'O':
1277 tty.c_cflag |= PARENB | PARODD;
1278 break;
1280 if (stop_bits == 2)
1281 tty.c_cflag |= CSTOPB;
1283 tcsetattr (fd, TCSANOW, &tty);
1286 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1288 FDCharDriver *s = chr->opaque;
1290 switch(cmd) {
1291 case CHR_IOCTL_SERIAL_SET_PARAMS:
1293 QEMUSerialSetParams *ssp = arg;
1294 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1295 ssp->speed, ssp->parity,
1296 ssp->data_bits, ssp->stop_bits);
1298 break;
1299 case CHR_IOCTL_SERIAL_SET_BREAK:
1301 int enable = *(int *)arg;
1302 if (enable) {
1303 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1306 break;
1307 case CHR_IOCTL_SERIAL_GET_TIOCM:
1309 int sarg = 0;
1310 int *targ = (int *)arg;
1311 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1312 *targ = 0;
1313 if (sarg & TIOCM_CTS)
1314 *targ |= CHR_TIOCM_CTS;
1315 if (sarg & TIOCM_CAR)
1316 *targ |= CHR_TIOCM_CAR;
1317 if (sarg & TIOCM_DSR)
1318 *targ |= CHR_TIOCM_DSR;
1319 if (sarg & TIOCM_RI)
1320 *targ |= CHR_TIOCM_RI;
1321 if (sarg & TIOCM_DTR)
1322 *targ |= CHR_TIOCM_DTR;
1323 if (sarg & TIOCM_RTS)
1324 *targ |= CHR_TIOCM_RTS;
1326 break;
1327 case CHR_IOCTL_SERIAL_SET_TIOCM:
1329 int sarg = *(int *)arg;
1330 int targ = 0;
1331 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1332 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1333 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1334 if (sarg & CHR_TIOCM_CTS)
1335 targ |= TIOCM_CTS;
1336 if (sarg & CHR_TIOCM_CAR)
1337 targ |= TIOCM_CAR;
1338 if (sarg & CHR_TIOCM_DSR)
1339 targ |= TIOCM_DSR;
1340 if (sarg & CHR_TIOCM_RI)
1341 targ |= TIOCM_RI;
1342 if (sarg & CHR_TIOCM_DTR)
1343 targ |= TIOCM_DTR;
1344 if (sarg & CHR_TIOCM_RTS)
1345 targ |= TIOCM_RTS;
1346 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1348 break;
1349 default:
1350 return -ENOTSUP;
1352 return 0;
1355 static void qemu_chr_close_tty(CharDriverState *chr)
1357 FDCharDriver *s = chr->opaque;
1358 int fd = -1;
1360 if (s) {
1361 fd = g_io_channel_unix_get_fd(s->fd_in);
1364 fd_chr_close(chr);
1366 if (fd >= 0) {
1367 close(fd);
1371 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1373 CharDriverState *chr;
1375 tty_serial_init(fd, 115200, 'N', 8, 1);
1376 chr = qemu_chr_open_fd(fd, fd);
1377 chr->chr_ioctl = tty_serial_ioctl;
1378 chr->chr_close = qemu_chr_close_tty;
1379 return chr;
1381 #endif /* __linux__ || __sun__ */
1383 #if defined(__linux__)
1385 #define HAVE_CHARDEV_PARPORT 1
1387 typedef struct {
1388 int fd;
1389 int mode;
1390 } ParallelCharDriver;
1392 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1394 if (s->mode != mode) {
1395 int m = mode;
1396 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1397 return 0;
1398 s->mode = mode;
1400 return 1;
1403 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1405 ParallelCharDriver *drv = chr->opaque;
1406 int fd = drv->fd;
1407 uint8_t b;
1409 switch(cmd) {
1410 case CHR_IOCTL_PP_READ_DATA:
1411 if (ioctl(fd, PPRDATA, &b) < 0)
1412 return -ENOTSUP;
1413 *(uint8_t *)arg = b;
1414 break;
1415 case CHR_IOCTL_PP_WRITE_DATA:
1416 b = *(uint8_t *)arg;
1417 if (ioctl(fd, PPWDATA, &b) < 0)
1418 return -ENOTSUP;
1419 break;
1420 case CHR_IOCTL_PP_READ_CONTROL:
1421 if (ioctl(fd, PPRCONTROL, &b) < 0)
1422 return -ENOTSUP;
1423 /* Linux gives only the lowest bits, and no way to know data
1424 direction! For better compatibility set the fixed upper
1425 bits. */
1426 *(uint8_t *)arg = b | 0xc0;
1427 break;
1428 case CHR_IOCTL_PP_WRITE_CONTROL:
1429 b = *(uint8_t *)arg;
1430 if (ioctl(fd, PPWCONTROL, &b) < 0)
1431 return -ENOTSUP;
1432 break;
1433 case CHR_IOCTL_PP_READ_STATUS:
1434 if (ioctl(fd, PPRSTATUS, &b) < 0)
1435 return -ENOTSUP;
1436 *(uint8_t *)arg = b;
1437 break;
1438 case CHR_IOCTL_PP_DATA_DIR:
1439 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1440 return -ENOTSUP;
1441 break;
1442 case CHR_IOCTL_PP_EPP_READ_ADDR:
1443 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1444 struct ParallelIOArg *parg = arg;
1445 int n = read(fd, parg->buffer, parg->count);
1446 if (n != parg->count) {
1447 return -EIO;
1450 break;
1451 case CHR_IOCTL_PP_EPP_READ:
1452 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1453 struct ParallelIOArg *parg = arg;
1454 int n = read(fd, parg->buffer, parg->count);
1455 if (n != parg->count) {
1456 return -EIO;
1459 break;
1460 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1461 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1462 struct ParallelIOArg *parg = arg;
1463 int n = write(fd, parg->buffer, parg->count);
1464 if (n != parg->count) {
1465 return -EIO;
1468 break;
1469 case CHR_IOCTL_PP_EPP_WRITE:
1470 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1471 struct ParallelIOArg *parg = arg;
1472 int n = write(fd, parg->buffer, parg->count);
1473 if (n != parg->count) {
1474 return -EIO;
1477 break;
1478 default:
1479 return -ENOTSUP;
1481 return 0;
1484 static void pp_close(CharDriverState *chr)
1486 ParallelCharDriver *drv = chr->opaque;
1487 int fd = drv->fd;
1489 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1490 ioctl(fd, PPRELEASE);
1491 close(fd);
1492 g_free(drv);
1493 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1496 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1498 CharDriverState *chr;
1499 ParallelCharDriver *drv;
1501 if (ioctl(fd, PPCLAIM) < 0) {
1502 close(fd);
1503 return NULL;
1506 drv = g_malloc0(sizeof(ParallelCharDriver));
1507 drv->fd = fd;
1508 drv->mode = IEEE1284_MODE_COMPAT;
1510 chr = g_malloc0(sizeof(CharDriverState));
1511 chr->chr_write = null_chr_write;
1512 chr->chr_ioctl = pp_ioctl;
1513 chr->chr_close = pp_close;
1514 chr->opaque = drv;
1516 return chr;
1518 #endif /* __linux__ */
1520 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1522 #define HAVE_CHARDEV_PARPORT 1
1524 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1526 int fd = (int)(intptr_t)chr->opaque;
1527 uint8_t b;
1529 switch(cmd) {
1530 case CHR_IOCTL_PP_READ_DATA:
1531 if (ioctl(fd, PPIGDATA, &b) < 0)
1532 return -ENOTSUP;
1533 *(uint8_t *)arg = b;
1534 break;
1535 case CHR_IOCTL_PP_WRITE_DATA:
1536 b = *(uint8_t *)arg;
1537 if (ioctl(fd, PPISDATA, &b) < 0)
1538 return -ENOTSUP;
1539 break;
1540 case CHR_IOCTL_PP_READ_CONTROL:
1541 if (ioctl(fd, PPIGCTRL, &b) < 0)
1542 return -ENOTSUP;
1543 *(uint8_t *)arg = b;
1544 break;
1545 case CHR_IOCTL_PP_WRITE_CONTROL:
1546 b = *(uint8_t *)arg;
1547 if (ioctl(fd, PPISCTRL, &b) < 0)
1548 return -ENOTSUP;
1549 break;
1550 case CHR_IOCTL_PP_READ_STATUS:
1551 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1552 return -ENOTSUP;
1553 *(uint8_t *)arg = b;
1554 break;
1555 default:
1556 return -ENOTSUP;
1558 return 0;
1561 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1563 CharDriverState *chr;
1565 chr = g_malloc0(sizeof(CharDriverState));
1566 chr->opaque = (void *)(intptr_t)fd;
1567 chr->chr_write = null_chr_write;
1568 chr->chr_ioctl = pp_ioctl;
1569 chr->explicit_be_open = true;
1570 return chr;
1572 #endif
1574 #else /* _WIN32 */
1576 typedef struct {
1577 int max_size;
1578 HANDLE hcom, hrecv, hsend;
1579 OVERLAPPED orecv, osend;
1580 BOOL fpipe;
1581 DWORD len;
1582 } WinCharState;
1584 typedef struct {
1585 HANDLE hStdIn;
1586 HANDLE hInputReadyEvent;
1587 HANDLE hInputDoneEvent;
1588 HANDLE hInputThread;
1589 uint8_t win_stdio_buf;
1590 } WinStdioCharState;
1592 #define NSENDBUF 2048
1593 #define NRECVBUF 2048
1594 #define MAXCONNECT 1
1595 #define NTIMEOUT 5000
1597 static int win_chr_poll(void *opaque);
1598 static int win_chr_pipe_poll(void *opaque);
1600 static void win_chr_close(CharDriverState *chr)
1602 WinCharState *s = chr->opaque;
1604 if (s->hsend) {
1605 CloseHandle(s->hsend);
1606 s->hsend = NULL;
1608 if (s->hrecv) {
1609 CloseHandle(s->hrecv);
1610 s->hrecv = NULL;
1612 if (s->hcom) {
1613 CloseHandle(s->hcom);
1614 s->hcom = NULL;
1616 if (s->fpipe)
1617 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1618 else
1619 qemu_del_polling_cb(win_chr_poll, chr);
1621 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1624 static int win_chr_init(CharDriverState *chr, const char *filename)
1626 WinCharState *s = chr->opaque;
1627 COMMCONFIG comcfg;
1628 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1629 COMSTAT comstat;
1630 DWORD size;
1631 DWORD err;
1633 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1634 if (!s->hsend) {
1635 fprintf(stderr, "Failed CreateEvent\n");
1636 goto fail;
1638 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1639 if (!s->hrecv) {
1640 fprintf(stderr, "Failed CreateEvent\n");
1641 goto fail;
1644 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1645 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1646 if (s->hcom == INVALID_HANDLE_VALUE) {
1647 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1648 s->hcom = NULL;
1649 goto fail;
1652 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1653 fprintf(stderr, "Failed SetupComm\n");
1654 goto fail;
1657 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1658 size = sizeof(COMMCONFIG);
1659 GetDefaultCommConfig(filename, &comcfg, &size);
1660 comcfg.dcb.DCBlength = sizeof(DCB);
1661 CommConfigDialog(filename, NULL, &comcfg);
1663 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1664 fprintf(stderr, "Failed SetCommState\n");
1665 goto fail;
1668 if (!SetCommMask(s->hcom, EV_ERR)) {
1669 fprintf(stderr, "Failed SetCommMask\n");
1670 goto fail;
1673 cto.ReadIntervalTimeout = MAXDWORD;
1674 if (!SetCommTimeouts(s->hcom, &cto)) {
1675 fprintf(stderr, "Failed SetCommTimeouts\n");
1676 goto fail;
1679 if (!ClearCommError(s->hcom, &err, &comstat)) {
1680 fprintf(stderr, "Failed ClearCommError\n");
1681 goto fail;
1683 qemu_add_polling_cb(win_chr_poll, chr);
1684 return 0;
1686 fail:
1687 win_chr_close(chr);
1688 return -1;
1691 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1693 WinCharState *s = chr->opaque;
1694 DWORD len, ret, size, err;
1696 len = len1;
1697 ZeroMemory(&s->osend, sizeof(s->osend));
1698 s->osend.hEvent = s->hsend;
1699 while (len > 0) {
1700 if (s->hsend)
1701 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1702 else
1703 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1704 if (!ret) {
1705 err = GetLastError();
1706 if (err == ERROR_IO_PENDING) {
1707 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1708 if (ret) {
1709 buf += size;
1710 len -= size;
1711 } else {
1712 break;
1714 } else {
1715 break;
1717 } else {
1718 buf += size;
1719 len -= size;
1722 return len1 - len;
1725 static int win_chr_read_poll(CharDriverState *chr)
1727 WinCharState *s = chr->opaque;
1729 s->max_size = qemu_chr_be_can_write(chr);
1730 return s->max_size;
1733 static void win_chr_readfile(CharDriverState *chr)
1735 WinCharState *s = chr->opaque;
1736 int ret, err;
1737 uint8_t buf[READ_BUF_LEN];
1738 DWORD size;
1740 ZeroMemory(&s->orecv, sizeof(s->orecv));
1741 s->orecv.hEvent = s->hrecv;
1742 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1743 if (!ret) {
1744 err = GetLastError();
1745 if (err == ERROR_IO_PENDING) {
1746 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1750 if (size > 0) {
1751 qemu_chr_be_write(chr, buf, size);
1755 static void win_chr_read(CharDriverState *chr)
1757 WinCharState *s = chr->opaque;
1759 if (s->len > s->max_size)
1760 s->len = s->max_size;
1761 if (s->len == 0)
1762 return;
1764 win_chr_readfile(chr);
1767 static int win_chr_poll(void *opaque)
1769 CharDriverState *chr = opaque;
1770 WinCharState *s = chr->opaque;
1771 COMSTAT status;
1772 DWORD comerr;
1774 ClearCommError(s->hcom, &comerr, &status);
1775 if (status.cbInQue > 0) {
1776 s->len = status.cbInQue;
1777 win_chr_read_poll(chr);
1778 win_chr_read(chr);
1779 return 1;
1781 return 0;
1784 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1786 CharDriverState *chr;
1787 WinCharState *s;
1789 chr = g_malloc0(sizeof(CharDriverState));
1790 s = g_malloc0(sizeof(WinCharState));
1791 chr->opaque = s;
1792 chr->chr_write = win_chr_write;
1793 chr->chr_close = win_chr_close;
1795 if (win_chr_init(chr, filename) < 0) {
1796 g_free(s);
1797 g_free(chr);
1798 return NULL;
1800 return chr;
1803 static int win_chr_pipe_poll(void *opaque)
1805 CharDriverState *chr = opaque;
1806 WinCharState *s = chr->opaque;
1807 DWORD size;
1809 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1810 if (size > 0) {
1811 s->len = size;
1812 win_chr_read_poll(chr);
1813 win_chr_read(chr);
1814 return 1;
1816 return 0;
1819 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1821 WinCharState *s = chr->opaque;
1822 OVERLAPPED ov;
1823 int ret;
1824 DWORD size;
1825 char openname[256];
1827 s->fpipe = TRUE;
1829 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1830 if (!s->hsend) {
1831 fprintf(stderr, "Failed CreateEvent\n");
1832 goto fail;
1834 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1835 if (!s->hrecv) {
1836 fprintf(stderr, "Failed CreateEvent\n");
1837 goto fail;
1840 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1841 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1842 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1843 PIPE_WAIT,
1844 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1845 if (s->hcom == INVALID_HANDLE_VALUE) {
1846 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1847 s->hcom = NULL;
1848 goto fail;
1851 ZeroMemory(&ov, sizeof(ov));
1852 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1853 ret = ConnectNamedPipe(s->hcom, &ov);
1854 if (ret) {
1855 fprintf(stderr, "Failed ConnectNamedPipe\n");
1856 goto fail;
1859 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1860 if (!ret) {
1861 fprintf(stderr, "Failed GetOverlappedResult\n");
1862 if (ov.hEvent) {
1863 CloseHandle(ov.hEvent);
1864 ov.hEvent = NULL;
1866 goto fail;
1869 if (ov.hEvent) {
1870 CloseHandle(ov.hEvent);
1871 ov.hEvent = NULL;
1873 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1874 return 0;
1876 fail:
1877 win_chr_close(chr);
1878 return -1;
1882 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
1884 const char *filename = opts->device;
1885 CharDriverState *chr;
1886 WinCharState *s;
1888 chr = g_malloc0(sizeof(CharDriverState));
1889 s = g_malloc0(sizeof(WinCharState));
1890 chr->opaque = s;
1891 chr->chr_write = win_chr_write;
1892 chr->chr_close = win_chr_close;
1894 if (win_chr_pipe_init(chr, filename) < 0) {
1895 g_free(s);
1896 g_free(chr);
1897 return NULL;
1899 return chr;
1902 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1904 CharDriverState *chr;
1905 WinCharState *s;
1907 chr = g_malloc0(sizeof(CharDriverState));
1908 s = g_malloc0(sizeof(WinCharState));
1909 s->hcom = fd_out;
1910 chr->opaque = s;
1911 chr->chr_write = win_chr_write;
1912 return chr;
1915 static CharDriverState *qemu_chr_open_win_con(void)
1917 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1920 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1922 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1923 DWORD dwSize;
1924 int len1;
1926 len1 = len;
1928 while (len1 > 0) {
1929 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
1930 break;
1932 buf += dwSize;
1933 len1 -= dwSize;
1936 return len - len1;
1939 static void win_stdio_wait_func(void *opaque)
1941 CharDriverState *chr = opaque;
1942 WinStdioCharState *stdio = chr->opaque;
1943 INPUT_RECORD buf[4];
1944 int ret;
1945 DWORD dwSize;
1946 int i;
1948 ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
1949 &dwSize);
1951 if (!ret) {
1952 /* Avoid error storm */
1953 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
1954 return;
1957 for (i = 0; i < dwSize; i++) {
1958 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
1960 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
1961 int j;
1962 if (kev->uChar.AsciiChar != 0) {
1963 for (j = 0; j < kev->wRepeatCount; j++) {
1964 if (qemu_chr_be_can_write(chr)) {
1965 uint8_t c = kev->uChar.AsciiChar;
1966 qemu_chr_be_write(chr, &c, 1);
1974 static DWORD WINAPI win_stdio_thread(LPVOID param)
1976 CharDriverState *chr = param;
1977 WinStdioCharState *stdio = chr->opaque;
1978 int ret;
1979 DWORD dwSize;
1981 while (1) {
1983 /* Wait for one byte */
1984 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
1986 /* Exit in case of error, continue if nothing read */
1987 if (!ret) {
1988 break;
1990 if (!dwSize) {
1991 continue;
1994 /* Some terminal emulator returns \r\n for Enter, just pass \n */
1995 if (stdio->win_stdio_buf == '\r') {
1996 continue;
1999 /* Signal the main thread and wait until the byte was eaten */
2000 if (!SetEvent(stdio->hInputReadyEvent)) {
2001 break;
2003 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2004 != WAIT_OBJECT_0) {
2005 break;
2009 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2010 return 0;
2013 static void win_stdio_thread_wait_func(void *opaque)
2015 CharDriverState *chr = opaque;
2016 WinStdioCharState *stdio = chr->opaque;
2018 if (qemu_chr_be_can_write(chr)) {
2019 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2022 SetEvent(stdio->hInputDoneEvent);
2025 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2027 WinStdioCharState *stdio = chr->opaque;
2028 DWORD dwMode = 0;
2030 GetConsoleMode(stdio->hStdIn, &dwMode);
2032 if (echo) {
2033 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2034 } else {
2035 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2039 static void win_stdio_close(CharDriverState *chr)
2041 WinStdioCharState *stdio = chr->opaque;
2043 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2044 CloseHandle(stdio->hInputReadyEvent);
2046 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2047 CloseHandle(stdio->hInputDoneEvent);
2049 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2050 TerminateThread(stdio->hInputThread, 0);
2053 g_free(chr->opaque);
2054 g_free(chr);
2057 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2059 CharDriverState *chr;
2060 WinStdioCharState *stdio;
2061 DWORD dwMode;
2062 int is_console = 0;
2064 chr = g_malloc0(sizeof(CharDriverState));
2065 stdio = g_malloc0(sizeof(WinStdioCharState));
2067 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2068 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2069 fprintf(stderr, "cannot open stdio: invalid handle\n");
2070 exit(1);
2073 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2075 chr->opaque = stdio;
2076 chr->chr_write = win_stdio_write;
2077 chr->chr_close = win_stdio_close;
2079 if (is_console) {
2080 if (qemu_add_wait_object(stdio->hStdIn,
2081 win_stdio_wait_func, chr)) {
2082 fprintf(stderr, "qemu_add_wait_object: failed\n");
2084 } else {
2085 DWORD dwId;
2087 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2088 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2089 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2090 chr, 0, &dwId);
2092 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2093 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2094 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2095 fprintf(stderr, "cannot create stdio thread or event\n");
2096 exit(1);
2098 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2099 win_stdio_thread_wait_func, chr)) {
2100 fprintf(stderr, "qemu_add_wait_object: failed\n");
2104 dwMode |= ENABLE_LINE_INPUT;
2106 if (is_console) {
2107 /* set the terminal in raw mode */
2108 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2109 dwMode |= ENABLE_PROCESSED_INPUT;
2112 SetConsoleMode(stdio->hStdIn, dwMode);
2114 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2115 qemu_chr_fe_set_echo(chr, false);
2117 return chr;
2119 #endif /* !_WIN32 */
2122 /***********************************************************/
2123 /* UDP Net console */
2125 typedef struct {
2126 int fd;
2127 GIOChannel *chan;
2128 guint tag;
2129 uint8_t buf[READ_BUF_LEN];
2130 int bufcnt;
2131 int bufptr;
2132 int max_size;
2133 } NetCharDriver;
2135 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2137 NetCharDriver *s = chr->opaque;
2138 gsize bytes_written;
2139 GIOStatus status;
2141 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2142 if (status == G_IO_STATUS_EOF) {
2143 return 0;
2144 } else if (status != G_IO_STATUS_NORMAL) {
2145 return -1;
2148 return bytes_written;
2151 static int udp_chr_read_poll(void *opaque)
2153 CharDriverState *chr = opaque;
2154 NetCharDriver *s = chr->opaque;
2156 s->max_size = qemu_chr_be_can_write(chr);
2158 /* If there were any stray characters in the queue process them
2159 * first
2161 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2162 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2163 s->bufptr++;
2164 s->max_size = qemu_chr_be_can_write(chr);
2166 return s->max_size;
2169 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2171 CharDriverState *chr = opaque;
2172 NetCharDriver *s = chr->opaque;
2173 gsize bytes_read = 0;
2174 GIOStatus status;
2176 if (s->max_size == 0) {
2177 return TRUE;
2179 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2180 &bytes_read, NULL);
2181 s->bufcnt = bytes_read;
2182 s->bufptr = s->bufcnt;
2183 if (status != G_IO_STATUS_NORMAL) {
2184 if (s->tag) {
2185 io_remove_watch_poll(s->tag);
2186 s->tag = 0;
2188 return FALSE;
2191 s->bufptr = 0;
2192 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2193 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2194 s->bufptr++;
2195 s->max_size = qemu_chr_be_can_write(chr);
2198 return TRUE;
2201 static void udp_chr_update_read_handler(CharDriverState *chr)
2203 NetCharDriver *s = chr->opaque;
2205 if (s->tag) {
2206 io_remove_watch_poll(s->tag);
2207 s->tag = 0;
2210 if (s->chan) {
2211 s->tag = io_add_watch_poll(s->chan, udp_chr_read_poll, udp_chr_read, chr);
2215 static void udp_chr_close(CharDriverState *chr)
2217 NetCharDriver *s = chr->opaque;
2218 if (s->tag) {
2219 io_remove_watch_poll(s->tag);
2220 s->tag = 0;
2222 if (s->chan) {
2223 g_io_channel_unref(s->chan);
2224 closesocket(s->fd);
2226 g_free(s);
2227 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2230 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2232 CharDriverState *chr = NULL;
2233 NetCharDriver *s = NULL;
2235 chr = g_malloc0(sizeof(CharDriverState));
2236 s = g_malloc0(sizeof(NetCharDriver));
2238 s->fd = fd;
2239 s->chan = io_channel_from_socket(s->fd);
2240 s->bufcnt = 0;
2241 s->bufptr = 0;
2242 chr->opaque = s;
2243 chr->chr_write = udp_chr_write;
2244 chr->chr_update_read_handler = udp_chr_update_read_handler;
2245 chr->chr_close = udp_chr_close;
2246 /* be isn't opened until we get a connection */
2247 chr->explicit_be_open = true;
2248 return chr;
2251 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2253 Error *local_err = NULL;
2254 int fd = -1;
2256 fd = inet_dgram_opts(opts, &local_err);
2257 if (fd < 0) {
2258 return NULL;
2260 return qemu_chr_open_udp_fd(fd);
2263 /***********************************************************/
2264 /* TCP Net console */
2266 typedef struct {
2268 GIOChannel *chan, *listen_chan;
2269 guint tag, listen_tag;
2270 int fd, listen_fd;
2271 int connected;
2272 int max_size;
2273 int do_telnetopt;
2274 int do_nodelay;
2275 int is_unix;
2276 int msgfd;
2277 } TCPCharDriver;
2279 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2281 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2283 TCPCharDriver *s = chr->opaque;
2284 if (s->connected) {
2285 return io_channel_send(s->chan, buf, len);
2286 } else {
2287 /* XXX: indicate an error ? */
2288 return len;
2292 static int tcp_chr_read_poll(void *opaque)
2294 CharDriverState *chr = opaque;
2295 TCPCharDriver *s = chr->opaque;
2296 if (!s->connected)
2297 return 0;
2298 s->max_size = qemu_chr_be_can_write(chr);
2299 return s->max_size;
2302 #define IAC 255
2303 #define IAC_BREAK 243
2304 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2305 TCPCharDriver *s,
2306 uint8_t *buf, int *size)
2308 /* Handle any telnet client's basic IAC options to satisfy char by
2309 * char mode with no echo. All IAC options will be removed from
2310 * the buf and the do_telnetopt variable will be used to track the
2311 * state of the width of the IAC information.
2313 * IAC commands come in sets of 3 bytes with the exception of the
2314 * "IAC BREAK" command and the double IAC.
2317 int i;
2318 int j = 0;
2320 for (i = 0; i < *size; i++) {
2321 if (s->do_telnetopt > 1) {
2322 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2323 /* Double IAC means send an IAC */
2324 if (j != i)
2325 buf[j] = buf[i];
2326 j++;
2327 s->do_telnetopt = 1;
2328 } else {
2329 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2330 /* Handle IAC break commands by sending a serial break */
2331 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2332 s->do_telnetopt++;
2334 s->do_telnetopt++;
2336 if (s->do_telnetopt >= 4) {
2337 s->do_telnetopt = 1;
2339 } else {
2340 if ((unsigned char)buf[i] == IAC) {
2341 s->do_telnetopt = 2;
2342 } else {
2343 if (j != i)
2344 buf[j] = buf[i];
2345 j++;
2349 *size = j;
2352 static int tcp_get_msgfd(CharDriverState *chr)
2354 TCPCharDriver *s = chr->opaque;
2355 int fd = s->msgfd;
2356 s->msgfd = -1;
2357 return fd;
2360 #ifndef _WIN32
2361 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2363 TCPCharDriver *s = chr->opaque;
2364 struct cmsghdr *cmsg;
2366 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2367 int fd;
2369 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2370 cmsg->cmsg_level != SOL_SOCKET ||
2371 cmsg->cmsg_type != SCM_RIGHTS)
2372 continue;
2374 fd = *((int *)CMSG_DATA(cmsg));
2375 if (fd < 0)
2376 continue;
2378 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2379 qemu_set_block(fd);
2381 #ifndef MSG_CMSG_CLOEXEC
2382 qemu_set_cloexec(fd);
2383 #endif
2384 if (s->msgfd != -1)
2385 close(s->msgfd);
2386 s->msgfd = fd;
2390 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2392 TCPCharDriver *s = chr->opaque;
2393 struct msghdr msg = { NULL, };
2394 struct iovec iov[1];
2395 union {
2396 struct cmsghdr cmsg;
2397 char control[CMSG_SPACE(sizeof(int))];
2398 } msg_control;
2399 int flags = 0;
2400 ssize_t ret;
2402 iov[0].iov_base = buf;
2403 iov[0].iov_len = len;
2405 msg.msg_iov = iov;
2406 msg.msg_iovlen = 1;
2407 msg.msg_control = &msg_control;
2408 msg.msg_controllen = sizeof(msg_control);
2410 #ifdef MSG_CMSG_CLOEXEC
2411 flags |= MSG_CMSG_CLOEXEC;
2412 #endif
2413 ret = recvmsg(s->fd, &msg, flags);
2414 if (ret > 0 && s->is_unix) {
2415 unix_process_msgfd(chr, &msg);
2418 return ret;
2420 #else
2421 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2423 TCPCharDriver *s = chr->opaque;
2424 return qemu_recv(s->fd, buf, len, 0);
2426 #endif
2428 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2430 TCPCharDriver *s = chr->opaque;
2431 return g_io_create_watch(s->chan, cond);
2434 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2436 CharDriverState *chr = opaque;
2437 TCPCharDriver *s = chr->opaque;
2438 uint8_t buf[READ_BUF_LEN];
2439 int len, size;
2441 if (!s->connected || s->max_size <= 0) {
2442 return TRUE;
2444 len = sizeof(buf);
2445 if (len > s->max_size)
2446 len = s->max_size;
2447 size = tcp_chr_recv(chr, (void *)buf, len);
2448 if (size == 0) {
2449 /* connection closed */
2450 s->connected = 0;
2451 if (s->listen_chan) {
2452 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2454 if (s->tag) {
2455 io_remove_watch_poll(s->tag);
2456 s->tag = 0;
2458 g_io_channel_unref(s->chan);
2459 s->chan = NULL;
2460 closesocket(s->fd);
2461 s->fd = -1;
2462 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2463 } else if (size > 0) {
2464 if (s->do_telnetopt)
2465 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2466 if (size > 0)
2467 qemu_chr_be_write(chr, buf, size);
2470 return TRUE;
2473 #ifndef _WIN32
2474 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2476 return qemu_chr_open_fd(eventfd, eventfd);
2478 #endif
2480 static void tcp_chr_connect(void *opaque)
2482 CharDriverState *chr = opaque;
2483 TCPCharDriver *s = chr->opaque;
2485 s->connected = 1;
2486 if (s->chan) {
2487 s->tag = io_add_watch_poll(s->chan, tcp_chr_read_poll, tcp_chr_read, chr);
2489 qemu_chr_be_generic_open(chr);
2492 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2493 static void tcp_chr_telnet_init(int fd)
2495 char buf[3];
2496 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2497 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2498 send(fd, (char *)buf, 3, 0);
2499 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2500 send(fd, (char *)buf, 3, 0);
2501 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2502 send(fd, (char *)buf, 3, 0);
2503 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2504 send(fd, (char *)buf, 3, 0);
2507 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2509 TCPCharDriver *s = chr->opaque;
2510 if (s->fd != -1)
2511 return -1;
2513 qemu_set_nonblock(fd);
2514 if (s->do_nodelay)
2515 socket_set_nodelay(fd);
2516 s->fd = fd;
2517 s->chan = io_channel_from_socket(fd);
2518 if (s->listen_tag) {
2519 g_source_remove(s->listen_tag);
2520 s->listen_tag = 0;
2522 tcp_chr_connect(chr);
2524 return 0;
2527 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2529 CharDriverState *chr = opaque;
2530 TCPCharDriver *s = chr->opaque;
2531 struct sockaddr_in saddr;
2532 #ifndef _WIN32
2533 struct sockaddr_un uaddr;
2534 #endif
2535 struct sockaddr *addr;
2536 socklen_t len;
2537 int fd;
2539 for(;;) {
2540 #ifndef _WIN32
2541 if (s->is_unix) {
2542 len = sizeof(uaddr);
2543 addr = (struct sockaddr *)&uaddr;
2544 } else
2545 #endif
2547 len = sizeof(saddr);
2548 addr = (struct sockaddr *)&saddr;
2550 fd = qemu_accept(s->listen_fd, addr, &len);
2551 if (fd < 0 && errno != EINTR) {
2552 s->listen_tag = 0;
2553 return FALSE;
2554 } else if (fd >= 0) {
2555 if (s->do_telnetopt)
2556 tcp_chr_telnet_init(fd);
2557 break;
2560 if (tcp_chr_add_client(chr, fd) < 0)
2561 close(fd);
2563 return TRUE;
2566 static void tcp_chr_close(CharDriverState *chr)
2568 TCPCharDriver *s = chr->opaque;
2569 if (s->fd >= 0) {
2570 if (s->tag) {
2571 io_remove_watch_poll(s->tag);
2572 s->tag = 0;
2574 if (s->chan) {
2575 g_io_channel_unref(s->chan);
2577 closesocket(s->fd);
2579 if (s->listen_fd >= 0) {
2580 if (s->listen_tag) {
2581 g_source_remove(s->listen_tag);
2582 s->listen_tag = 0;
2584 if (s->listen_chan) {
2585 g_io_channel_unref(s->listen_chan);
2587 closesocket(s->listen_fd);
2589 g_free(s);
2590 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2593 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2594 bool is_listen, bool is_telnet,
2595 bool is_waitconnect,
2596 Error **errp)
2598 CharDriverState *chr = NULL;
2599 TCPCharDriver *s = NULL;
2600 char host[NI_MAXHOST], serv[NI_MAXSERV];
2601 const char *left = "", *right = "";
2602 struct sockaddr_storage ss;
2603 socklen_t ss_len = sizeof(ss);
2605 memset(&ss, 0, ss_len);
2606 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2607 error_setg(errp, "getsockname: %s", strerror(errno));
2608 return NULL;
2611 chr = g_malloc0(sizeof(CharDriverState));
2612 s = g_malloc0(sizeof(TCPCharDriver));
2614 s->connected = 0;
2615 s->fd = -1;
2616 s->listen_fd = -1;
2617 s->msgfd = -1;
2619 chr->filename = g_malloc(256);
2620 switch (ss.ss_family) {
2621 #ifndef _WIN32
2622 case AF_UNIX:
2623 s->is_unix = 1;
2624 snprintf(chr->filename, 256, "unix:%s%s",
2625 ((struct sockaddr_un *)(&ss))->sun_path,
2626 is_listen ? ",server" : "");
2627 break;
2628 #endif
2629 case AF_INET6:
2630 left = "[";
2631 right = "]";
2632 /* fall through */
2633 case AF_INET:
2634 s->do_nodelay = do_nodelay;
2635 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2636 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2637 snprintf(chr->filename, 256, "%s:%s%s%s:%s%s",
2638 is_telnet ? "telnet" : "tcp",
2639 left, host, right, serv,
2640 is_listen ? ",server" : "");
2641 break;
2644 chr->opaque = s;
2645 chr->chr_write = tcp_chr_write;
2646 chr->chr_close = tcp_chr_close;
2647 chr->get_msgfd = tcp_get_msgfd;
2648 chr->chr_add_client = tcp_chr_add_client;
2649 chr->chr_add_watch = tcp_chr_add_watch;
2650 /* be isn't opened until we get a connection */
2651 chr->explicit_be_open = true;
2653 if (is_listen) {
2654 s->listen_fd = fd;
2655 s->listen_chan = io_channel_from_socket(s->listen_fd);
2656 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2657 if (is_telnet) {
2658 s->do_telnetopt = 1;
2660 } else {
2661 s->connected = 1;
2662 s->fd = fd;
2663 socket_set_nodelay(fd);
2664 s->chan = io_channel_from_socket(s->fd);
2665 tcp_chr_connect(chr);
2668 if (is_listen && is_waitconnect) {
2669 printf("QEMU waiting for connection on: %s\n",
2670 chr->filename);
2671 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2672 qemu_set_nonblock(s->listen_fd);
2674 return chr;
2677 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2679 CharDriverState *chr = NULL;
2680 Error *local_err = NULL;
2681 int fd = -1;
2682 int is_listen;
2683 int is_waitconnect;
2684 int do_nodelay;
2685 int is_unix;
2686 int is_telnet;
2688 is_listen = qemu_opt_get_bool(opts, "server", 0);
2689 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2690 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2691 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2692 is_unix = qemu_opt_get(opts, "path") != NULL;
2693 if (!is_listen)
2694 is_waitconnect = 0;
2696 if (is_unix) {
2697 if (is_listen) {
2698 fd = unix_listen_opts(opts, &local_err);
2699 } else {
2700 fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2702 } else {
2703 if (is_listen) {
2704 fd = inet_listen_opts(opts, 0, &local_err);
2705 } else {
2706 fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2709 if (fd < 0) {
2710 goto fail;
2713 if (!is_waitconnect)
2714 qemu_set_nonblock(fd);
2716 chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2717 is_waitconnect, &local_err);
2718 if (error_is_set(&local_err)) {
2719 goto fail;
2721 return chr;
2724 fail:
2725 if (local_err) {
2726 qerror_report_err(local_err);
2727 error_free(local_err);
2729 if (fd >= 0) {
2730 closesocket(fd);
2732 if (chr) {
2733 g_free(chr->opaque);
2734 g_free(chr);
2736 return NULL;
2739 /*********************************************************/
2740 /* Ring buffer chardev */
2742 typedef struct {
2743 size_t size;
2744 size_t prod;
2745 size_t cons;
2746 uint8_t *cbuf;
2747 } RingBufCharDriver;
2749 static size_t ringbuf_count(const CharDriverState *chr)
2751 const RingBufCharDriver *d = chr->opaque;
2753 return d->prod - d->cons;
2756 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2758 RingBufCharDriver *d = chr->opaque;
2759 int i;
2761 if (!buf || (len < 0)) {
2762 return -1;
2765 for (i = 0; i < len; i++ ) {
2766 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2767 if (d->prod - d->cons > d->size) {
2768 d->cons = d->prod - d->size;
2772 return 0;
2775 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2777 RingBufCharDriver *d = chr->opaque;
2778 int i;
2780 for (i = 0; i < len && d->cons != d->prod; i++) {
2781 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2784 return i;
2787 static void ringbuf_chr_close(struct CharDriverState *chr)
2789 RingBufCharDriver *d = chr->opaque;
2791 g_free(d->cbuf);
2792 g_free(d);
2793 chr->opaque = NULL;
2796 static CharDriverState *qemu_chr_open_memory(ChardevMemory *opts,
2797 Error **errp)
2799 CharDriverState *chr;
2800 RingBufCharDriver *d;
2802 chr = g_malloc0(sizeof(CharDriverState));
2803 d = g_malloc(sizeof(*d));
2805 d->size = opts->has_size ? opts->size : 65536;
2807 /* The size must be power of 2 */
2808 if (d->size & (d->size - 1)) {
2809 error_setg(errp, "size of memory chardev must be power of two");
2810 goto fail;
2813 d->prod = 0;
2814 d->cons = 0;
2815 d->cbuf = g_malloc0(d->size);
2817 chr->opaque = d;
2818 chr->chr_write = ringbuf_chr_write;
2819 chr->chr_close = ringbuf_chr_close;
2821 return chr;
2823 fail:
2824 g_free(d);
2825 g_free(chr);
2826 return NULL;
2829 static bool chr_is_ringbuf(const CharDriverState *chr)
2831 return chr->chr_write == ringbuf_chr_write;
2834 void qmp_ringbuf_write(const char *device, const char *data,
2835 bool has_format, enum DataFormat format,
2836 Error **errp)
2838 CharDriverState *chr;
2839 const uint8_t *write_data;
2840 int ret;
2841 gsize write_count;
2843 chr = qemu_chr_find(device);
2844 if (!chr) {
2845 error_setg(errp, "Device '%s' not found", device);
2846 return;
2849 if (!chr_is_ringbuf(chr)) {
2850 error_setg(errp,"%s is not a ringbuf device", device);
2851 return;
2854 if (has_format && (format == DATA_FORMAT_BASE64)) {
2855 write_data = g_base64_decode(data, &write_count);
2856 } else {
2857 write_data = (uint8_t *)data;
2858 write_count = strlen(data);
2861 ret = ringbuf_chr_write(chr, write_data, write_count);
2863 if (write_data != (uint8_t *)data) {
2864 g_free((void *)write_data);
2867 if (ret < 0) {
2868 error_setg(errp, "Failed to write to device %s", device);
2869 return;
2873 char *qmp_ringbuf_read(const char *device, int64_t size,
2874 bool has_format, enum DataFormat format,
2875 Error **errp)
2877 CharDriverState *chr;
2878 uint8_t *read_data;
2879 size_t count;
2880 char *data;
2882 chr = qemu_chr_find(device);
2883 if (!chr) {
2884 error_setg(errp, "Device '%s' not found", device);
2885 return NULL;
2888 if (!chr_is_ringbuf(chr)) {
2889 error_setg(errp,"%s is not a ringbuf device", device);
2890 return NULL;
2893 if (size <= 0) {
2894 error_setg(errp, "size must be greater than zero");
2895 return NULL;
2898 count = ringbuf_count(chr);
2899 size = size > count ? count : size;
2900 read_data = g_malloc(size + 1);
2902 ringbuf_chr_read(chr, read_data, size);
2904 if (has_format && (format == DATA_FORMAT_BASE64)) {
2905 data = g_base64_encode(read_data, size);
2906 g_free(read_data);
2907 } else {
2909 * FIXME should read only complete, valid UTF-8 characters up
2910 * to @size bytes. Invalid sequences should be replaced by a
2911 * suitable replacement character. Except when (and only
2912 * when) ring buffer lost characters since last read, initial
2913 * continuation characters should be dropped.
2915 read_data[size] = 0;
2916 data = (char *)read_data;
2919 return data;
2922 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2924 char host[65], port[33], width[8], height[8];
2925 int pos;
2926 const char *p;
2927 QemuOpts *opts;
2928 Error *local_err = NULL;
2930 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
2931 if (error_is_set(&local_err)) {
2932 qerror_report_err(local_err);
2933 error_free(local_err);
2934 return NULL;
2937 if (strstart(filename, "mon:", &p)) {
2938 filename = p;
2939 qemu_opt_set(opts, "mux", "on");
2942 if (strcmp(filename, "null") == 0 ||
2943 strcmp(filename, "pty") == 0 ||
2944 strcmp(filename, "msmouse") == 0 ||
2945 strcmp(filename, "braille") == 0 ||
2946 strcmp(filename, "stdio") == 0) {
2947 qemu_opt_set(opts, "backend", filename);
2948 return opts;
2950 if (strstart(filename, "vc", &p)) {
2951 qemu_opt_set(opts, "backend", "vc");
2952 if (*p == ':') {
2953 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2954 /* pixels */
2955 qemu_opt_set(opts, "width", width);
2956 qemu_opt_set(opts, "height", height);
2957 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2958 /* chars */
2959 qemu_opt_set(opts, "cols", width);
2960 qemu_opt_set(opts, "rows", height);
2961 } else {
2962 goto fail;
2965 return opts;
2967 if (strcmp(filename, "con:") == 0) {
2968 qemu_opt_set(opts, "backend", "console");
2969 return opts;
2971 if (strstart(filename, "COM", NULL)) {
2972 qemu_opt_set(opts, "backend", "serial");
2973 qemu_opt_set(opts, "path", filename);
2974 return opts;
2976 if (strstart(filename, "file:", &p)) {
2977 qemu_opt_set(opts, "backend", "file");
2978 qemu_opt_set(opts, "path", p);
2979 return opts;
2981 if (strstart(filename, "pipe:", &p)) {
2982 qemu_opt_set(opts, "backend", "pipe");
2983 qemu_opt_set(opts, "path", p);
2984 return opts;
2986 if (strstart(filename, "tcp:", &p) ||
2987 strstart(filename, "telnet:", &p)) {
2988 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2989 host[0] = 0;
2990 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2991 goto fail;
2993 qemu_opt_set(opts, "backend", "socket");
2994 qemu_opt_set(opts, "host", host);
2995 qemu_opt_set(opts, "port", port);
2996 if (p[pos] == ',') {
2997 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2998 goto fail;
3000 if (strstart(filename, "telnet:", &p))
3001 qemu_opt_set(opts, "telnet", "on");
3002 return opts;
3004 if (strstart(filename, "udp:", &p)) {
3005 qemu_opt_set(opts, "backend", "udp");
3006 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3007 host[0] = 0;
3008 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3009 goto fail;
3012 qemu_opt_set(opts, "host", host);
3013 qemu_opt_set(opts, "port", port);
3014 if (p[pos] == '@') {
3015 p += pos + 1;
3016 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3017 host[0] = 0;
3018 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3019 goto fail;
3022 qemu_opt_set(opts, "localaddr", host);
3023 qemu_opt_set(opts, "localport", port);
3025 return opts;
3027 if (strstart(filename, "unix:", &p)) {
3028 qemu_opt_set(opts, "backend", "socket");
3029 if (qemu_opts_do_parse(opts, p, "path") != 0)
3030 goto fail;
3031 return opts;
3033 if (strstart(filename, "/dev/parport", NULL) ||
3034 strstart(filename, "/dev/ppi", NULL)) {
3035 qemu_opt_set(opts, "backend", "parport");
3036 qemu_opt_set(opts, "path", filename);
3037 return opts;
3039 if (strstart(filename, "/dev/", NULL)) {
3040 qemu_opt_set(opts, "backend", "tty");
3041 qemu_opt_set(opts, "path", filename);
3042 return opts;
3045 fail:
3046 qemu_opts_del(opts);
3047 return NULL;
3050 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3051 Error **errp)
3053 const char *path = qemu_opt_get(opts, "path");
3055 if (path == NULL) {
3056 error_setg(errp, "chardev: file: no filename given");
3057 return;
3059 backend->file = g_new0(ChardevFile, 1);
3060 backend->file->out = g_strdup(path);
3063 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3064 Error **errp)
3066 backend->stdio = g_new0(ChardevStdio, 1);
3067 backend->stdio->has_signal = true;
3068 backend->stdio->signal =
3069 qemu_opt_get_bool(opts, "signal", display_type != DT_NOGRAPHIC);
3072 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3073 Error **errp)
3075 const char *device = qemu_opt_get(opts, "path");
3077 if (device == NULL) {
3078 error_setg(errp, "chardev: serial/tty: no device path given");
3079 return;
3081 backend->serial = g_new0(ChardevHostdev, 1);
3082 backend->serial->device = g_strdup(device);
3085 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3086 Error **errp)
3088 const char *device = qemu_opt_get(opts, "path");
3090 if (device == NULL) {
3091 error_setg(errp, "chardev: parallel: no device path given");
3092 return;
3094 backend->parallel = g_new0(ChardevHostdev, 1);
3095 backend->parallel->device = g_strdup(device);
3098 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3099 Error **errp)
3101 const char *device = qemu_opt_get(opts, "path");
3103 if (device == NULL) {
3104 error_setg(errp, "chardev: pipe: no device path given");
3105 return;
3107 backend->pipe = g_new0(ChardevHostdev, 1);
3108 backend->pipe->device = g_strdup(device);
3111 static void qemu_chr_parse_memory(QemuOpts *opts, ChardevBackend *backend,
3112 Error **errp)
3114 int val;
3116 backend->memory = g_new0(ChardevMemory, 1);
3118 val = qemu_opt_get_number(opts, "size", 0);
3119 if (val != 0) {
3120 backend->memory->has_size = true;
3121 backend->memory->size = val;
3125 typedef struct CharDriver {
3126 const char *name;
3127 /* old, pre qapi */
3128 CharDriverState *(*open)(QemuOpts *opts);
3129 /* new, qapi-based */
3130 int kind;
3131 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3132 } CharDriver;
3134 static GSList *backends;
3136 void register_char_driver(const char *name, CharDriverState *(*open)(QemuOpts *))
3138 CharDriver *s;
3140 s = g_malloc0(sizeof(*s));
3141 s->name = g_strdup(name);
3142 s->open = open;
3144 backends = g_slist_append(backends, s);
3147 void register_char_driver_qapi(const char *name, int kind,
3148 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3150 CharDriver *s;
3152 s = g_malloc0(sizeof(*s));
3153 s->name = g_strdup(name);
3154 s->kind = kind;
3155 s->parse = parse;
3157 backends = g_slist_append(backends, s);
3160 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3161 void (*init)(struct CharDriverState *s),
3162 Error **errp)
3164 CharDriver *cd;
3165 CharDriverState *chr;
3166 GSList *i;
3168 if (qemu_opts_id(opts) == NULL) {
3169 error_setg(errp, "chardev: no id specified");
3170 goto err;
3173 if (qemu_opt_get(opts, "backend") == NULL) {
3174 error_setg(errp, "chardev: \"%s\" missing backend",
3175 qemu_opts_id(opts));
3176 goto err;
3178 for (i = backends; i; i = i->next) {
3179 cd = i->data;
3181 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3182 break;
3185 if (i == NULL) {
3186 error_setg(errp, "chardev: backend \"%s\" not found",
3187 qemu_opt_get(opts, "backend"));
3188 return NULL;
3191 if (!cd->open) {
3192 /* using new, qapi init */
3193 ChardevBackend *backend = g_new0(ChardevBackend, 1);
3194 ChardevReturn *ret = NULL;
3195 const char *id = qemu_opts_id(opts);
3196 const char *bid = NULL;
3198 if (qemu_opt_get_bool(opts, "mux", 0)) {
3199 bid = g_strdup_printf("%s-base", id);
3202 chr = NULL;
3203 backend->kind = cd->kind;
3204 if (cd->parse) {
3205 cd->parse(opts, backend, errp);
3206 if (error_is_set(errp)) {
3207 goto qapi_out;
3210 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3211 if (error_is_set(errp)) {
3212 goto qapi_out;
3215 if (bid) {
3216 qapi_free_ChardevBackend(backend);
3217 qapi_free_ChardevReturn(ret);
3218 backend = g_new0(ChardevBackend, 1);
3219 backend->mux = g_new0(ChardevMux, 1);
3220 backend->kind = CHARDEV_BACKEND_KIND_MUX;
3221 backend->mux->chardev = g_strdup(bid);
3222 ret = qmp_chardev_add(id, backend, errp);
3223 if (error_is_set(errp)) {
3224 goto qapi_out;
3228 chr = qemu_chr_find(id);
3230 qapi_out:
3231 qapi_free_ChardevBackend(backend);
3232 qapi_free_ChardevReturn(ret);
3233 return chr;
3236 chr = cd->open(opts);
3237 if (!chr) {
3238 error_setg(errp, "chardev: opening backend \"%s\" failed",
3239 qemu_opt_get(opts, "backend"));
3240 goto err;
3243 if (!chr->filename)
3244 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3245 chr->init = init;
3246 /* if we didn't create the chardev via qmp_chardev_add, we
3247 * need to send the OPENED event here
3249 if (!chr->explicit_be_open) {
3250 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
3252 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3254 if (qemu_opt_get_bool(opts, "mux", 0)) {
3255 CharDriverState *base = chr;
3256 int len = strlen(qemu_opts_id(opts)) + 6;
3257 base->label = g_malloc(len);
3258 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3259 chr = qemu_chr_open_mux(base);
3260 chr->filename = base->filename;
3261 chr->avail_connections = MAX_MUX;
3262 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3263 } else {
3264 chr->avail_connections = 1;
3266 chr->label = g_strdup(qemu_opts_id(opts));
3267 chr->opts = opts;
3268 return chr;
3270 err:
3271 qemu_opts_del(opts);
3272 return NULL;
3275 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3277 const char *p;
3278 CharDriverState *chr;
3279 QemuOpts *opts;
3280 Error *err = NULL;
3282 if (strstart(filename, "chardev:", &p)) {
3283 return qemu_chr_find(p);
3286 opts = qemu_chr_parse_compat(label, filename);
3287 if (!opts)
3288 return NULL;
3290 chr = qemu_chr_new_from_opts(opts, init, &err);
3291 if (error_is_set(&err)) {
3292 fprintf(stderr, "%s\n", error_get_pretty(err));
3293 error_free(err);
3295 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3296 qemu_chr_fe_claim_no_fail(chr);
3297 monitor_init(chr, MONITOR_USE_READLINE);
3299 return chr;
3302 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3304 if (chr->chr_set_echo) {
3305 chr->chr_set_echo(chr, echo);
3309 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3311 if (chr->fe_open == fe_open) {
3312 return;
3314 chr->fe_open = fe_open;
3315 if (chr->chr_set_fe_open) {
3316 chr->chr_set_fe_open(chr, fe_open);
3320 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3321 GIOFunc func, void *user_data)
3323 GSource *src;
3324 guint tag;
3326 if (s->chr_add_watch == NULL) {
3327 return -ENOSYS;
3330 src = s->chr_add_watch(s, cond);
3331 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3332 tag = g_source_attach(src, NULL);
3333 g_source_unref(src);
3335 return tag;
3338 int qemu_chr_fe_claim(CharDriverState *s)
3340 if (s->avail_connections < 1) {
3341 return -1;
3343 s->avail_connections--;
3344 return 0;
3347 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3349 if (qemu_chr_fe_claim(s) != 0) {
3350 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3351 __func__, s->label);
3352 exit(1);
3356 void qemu_chr_fe_release(CharDriverState *s)
3358 s->avail_connections++;
3361 void qemu_chr_delete(CharDriverState *chr)
3363 QTAILQ_REMOVE(&chardevs, chr, next);
3364 if (chr->chr_close) {
3365 chr->chr_close(chr);
3367 g_free(chr->filename);
3368 g_free(chr->label);
3369 if (chr->opts) {
3370 qemu_opts_del(chr->opts);
3372 g_free(chr);
3375 ChardevInfoList *qmp_query_chardev(Error **errp)
3377 ChardevInfoList *chr_list = NULL;
3378 CharDriverState *chr;
3380 QTAILQ_FOREACH(chr, &chardevs, next) {
3381 ChardevInfoList *info = g_malloc0(sizeof(*info));
3382 info->value = g_malloc0(sizeof(*info->value));
3383 info->value->label = g_strdup(chr->label);
3384 info->value->filename = g_strdup(chr->filename);
3386 info->next = chr_list;
3387 chr_list = info;
3390 return chr_list;
3393 CharDriverState *qemu_chr_find(const char *name)
3395 CharDriverState *chr;
3397 QTAILQ_FOREACH(chr, &chardevs, next) {
3398 if (strcmp(chr->label, name) != 0)
3399 continue;
3400 return chr;
3402 return NULL;
3405 /* Get a character (serial) device interface. */
3406 CharDriverState *qemu_char_get_next_serial(void)
3408 static int next_serial;
3409 CharDriverState *chr;
3411 /* FIXME: This function needs to go away: use chardev properties! */
3413 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3414 chr = serial_hds[next_serial++];
3415 qemu_chr_fe_claim_no_fail(chr);
3416 return chr;
3418 return NULL;
3421 QemuOptsList qemu_chardev_opts = {
3422 .name = "chardev",
3423 .implied_opt_name = "backend",
3424 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3425 .desc = {
3427 .name = "backend",
3428 .type = QEMU_OPT_STRING,
3430 .name = "path",
3431 .type = QEMU_OPT_STRING,
3433 .name = "host",
3434 .type = QEMU_OPT_STRING,
3436 .name = "port",
3437 .type = QEMU_OPT_STRING,
3439 .name = "localaddr",
3440 .type = QEMU_OPT_STRING,
3442 .name = "localport",
3443 .type = QEMU_OPT_STRING,
3445 .name = "to",
3446 .type = QEMU_OPT_NUMBER,
3448 .name = "ipv4",
3449 .type = QEMU_OPT_BOOL,
3451 .name = "ipv6",
3452 .type = QEMU_OPT_BOOL,
3454 .name = "wait",
3455 .type = QEMU_OPT_BOOL,
3457 .name = "server",
3458 .type = QEMU_OPT_BOOL,
3460 .name = "delay",
3461 .type = QEMU_OPT_BOOL,
3463 .name = "telnet",
3464 .type = QEMU_OPT_BOOL,
3466 .name = "width",
3467 .type = QEMU_OPT_NUMBER,
3469 .name = "height",
3470 .type = QEMU_OPT_NUMBER,
3472 .name = "cols",
3473 .type = QEMU_OPT_NUMBER,
3475 .name = "rows",
3476 .type = QEMU_OPT_NUMBER,
3478 .name = "mux",
3479 .type = QEMU_OPT_BOOL,
3481 .name = "signal",
3482 .type = QEMU_OPT_BOOL,
3484 .name = "name",
3485 .type = QEMU_OPT_STRING,
3487 .name = "debug",
3488 .type = QEMU_OPT_NUMBER,
3490 .name = "size",
3491 .type = QEMU_OPT_SIZE,
3493 { /* end of list */ }
3497 #ifdef _WIN32
3499 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3501 HANDLE out;
3503 if (file->in) {
3504 error_setg(errp, "input file not supported");
3505 return NULL;
3508 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3509 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3510 if (out == INVALID_HANDLE_VALUE) {
3511 error_setg(errp, "open %s failed", file->out);
3512 return NULL;
3514 return qemu_chr_open_win_file(out);
3517 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3518 Error **errp)
3520 return qemu_chr_open_win_path(serial->device);
3523 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3524 Error **errp)
3526 error_setg(errp, "character device backend type 'parallel' not supported");
3527 return NULL;
3530 #else /* WIN32 */
3532 static int qmp_chardev_open_file_source(char *src, int flags,
3533 Error **errp)
3535 int fd = -1;
3537 TFR(fd = qemu_open(src, flags, 0666));
3538 if (fd == -1) {
3539 error_setg(errp, "open %s: %s", src, strerror(errno));
3541 return fd;
3544 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3546 int flags, in = -1, out = -1;
3548 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3549 out = qmp_chardev_open_file_source(file->out, flags, errp);
3550 if (error_is_set(errp)) {
3551 return NULL;
3554 if (file->in) {
3555 flags = O_RDONLY;
3556 in = qmp_chardev_open_file_source(file->in, flags, errp);
3557 if (error_is_set(errp)) {
3558 qemu_close(out);
3559 return NULL;
3563 return qemu_chr_open_fd(in, out);
3566 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3567 Error **errp)
3569 #ifdef HAVE_CHARDEV_TTY
3570 int fd;
3572 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3573 if (error_is_set(errp)) {
3574 return NULL;
3576 qemu_set_nonblock(fd);
3577 return qemu_chr_open_tty_fd(fd);
3578 #else
3579 error_setg(errp, "character device backend type 'serial' not supported");
3580 return NULL;
3581 #endif
3584 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3585 Error **errp)
3587 #ifdef HAVE_CHARDEV_PARPORT
3588 int fd;
3590 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3591 if (error_is_set(errp)) {
3592 return NULL;
3594 return qemu_chr_open_pp_fd(fd);
3595 #else
3596 error_setg(errp, "character device backend type 'parallel' not supported");
3597 return NULL;
3598 #endif
3601 #endif /* WIN32 */
3603 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3604 Error **errp)
3606 SocketAddress *addr = sock->addr;
3607 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3608 bool is_listen = sock->has_server ? sock->server : true;
3609 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3610 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3611 int fd;
3613 if (is_listen) {
3614 fd = socket_listen(addr, errp);
3615 } else {
3616 fd = socket_connect(addr, errp, NULL, NULL);
3618 if (error_is_set(errp)) {
3619 return NULL;
3621 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3622 is_telnet, is_waitconnect, errp);
3625 static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
3626 Error **errp)
3628 int fd;
3630 fd = socket_dgram(udp->remote, udp->local, errp);
3631 if (error_is_set(errp)) {
3632 return NULL;
3634 return qemu_chr_open_udp_fd(fd);
3637 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3638 Error **errp)
3640 ChardevReturn *ret = g_new0(ChardevReturn, 1);
3641 CharDriverState *base, *chr = NULL;
3643 chr = qemu_chr_find(id);
3644 if (chr) {
3645 error_setg(errp, "Chardev '%s' already exists", id);
3646 g_free(ret);
3647 return NULL;
3650 switch (backend->kind) {
3651 case CHARDEV_BACKEND_KIND_FILE:
3652 chr = qmp_chardev_open_file(backend->file, errp);
3653 break;
3654 case CHARDEV_BACKEND_KIND_SERIAL:
3655 chr = qmp_chardev_open_serial(backend->serial, errp);
3656 break;
3657 case CHARDEV_BACKEND_KIND_PARALLEL:
3658 chr = qmp_chardev_open_parallel(backend->parallel, errp);
3659 break;
3660 case CHARDEV_BACKEND_KIND_PIPE:
3661 chr = qemu_chr_open_pipe(backend->pipe);
3662 break;
3663 case CHARDEV_BACKEND_KIND_SOCKET:
3664 chr = qmp_chardev_open_socket(backend->socket, errp);
3665 break;
3666 case CHARDEV_BACKEND_KIND_UDP:
3667 chr = qmp_chardev_open_udp(backend->udp, errp);
3668 break;
3669 #ifdef HAVE_CHARDEV_TTY
3670 case CHARDEV_BACKEND_KIND_PTY:
3671 chr = qemu_chr_open_pty(id, ret);
3672 break;
3673 #endif
3674 case CHARDEV_BACKEND_KIND_NULL:
3675 chr = qemu_chr_open_null();
3676 break;
3677 case CHARDEV_BACKEND_KIND_MUX:
3678 base = qemu_chr_find(backend->mux->chardev);
3679 if (base == NULL) {
3680 error_setg(errp, "mux: base chardev %s not found",
3681 backend->mux->chardev);
3682 break;
3684 chr = qemu_chr_open_mux(base);
3685 break;
3686 case CHARDEV_BACKEND_KIND_MSMOUSE:
3687 chr = qemu_chr_open_msmouse();
3688 break;
3689 #ifdef CONFIG_BRLAPI
3690 case CHARDEV_BACKEND_KIND_BRAILLE:
3691 chr = chr_baum_init();
3692 break;
3693 #endif
3694 case CHARDEV_BACKEND_KIND_STDIO:
3695 chr = qemu_chr_open_stdio(backend->stdio);
3696 break;
3697 #ifdef _WIN32
3698 case CHARDEV_BACKEND_KIND_CONSOLE:
3699 chr = qemu_chr_open_win_con();
3700 break;
3701 #endif
3702 #ifdef CONFIG_SPICE
3703 case CHARDEV_BACKEND_KIND_SPICEVMC:
3704 chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
3705 break;
3706 case CHARDEV_BACKEND_KIND_SPICEPORT:
3707 chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
3708 break;
3709 #endif
3710 case CHARDEV_BACKEND_KIND_VC:
3711 chr = vc_init(backend->vc);
3712 break;
3713 case CHARDEV_BACKEND_KIND_MEMORY:
3714 chr = qemu_chr_open_memory(backend->memory, errp);
3715 break;
3716 default:
3717 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3718 break;
3721 if (chr == NULL && !error_is_set(errp)) {
3722 error_setg(errp, "Failed to create chardev");
3724 if (chr) {
3725 chr->label = g_strdup(id);
3726 chr->avail_connections =
3727 (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
3728 if (!chr->filename) {
3729 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
3731 if (!chr->explicit_be_open) {
3732 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
3734 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3735 return ret;
3736 } else {
3737 g_free(ret);
3738 return NULL;
3742 void qmp_chardev_remove(const char *id, Error **errp)
3744 CharDriverState *chr;
3746 chr = qemu_chr_find(id);
3747 if (NULL == chr) {
3748 error_setg(errp, "Chardev '%s' not found", id);
3749 return;
3751 if (chr->chr_can_read || chr->chr_read ||
3752 chr->chr_event || chr->handler_opaque) {
3753 error_setg(errp, "Chardev '%s' is busy", id);
3754 return;
3756 qemu_chr_delete(chr);
3759 static void register_types(void)
3761 register_char_driver_qapi("null", CHARDEV_BACKEND_KIND_NULL, NULL);
3762 register_char_driver("socket", qemu_chr_open_socket);
3763 register_char_driver("udp", qemu_chr_open_udp);
3764 register_char_driver_qapi("memory", CHARDEV_BACKEND_KIND_MEMORY,
3765 qemu_chr_parse_memory);
3766 register_char_driver_qapi("file", CHARDEV_BACKEND_KIND_FILE,
3767 qemu_chr_parse_file_out);
3768 register_char_driver_qapi("stdio", CHARDEV_BACKEND_KIND_STDIO,
3769 qemu_chr_parse_stdio);
3770 register_char_driver_qapi("serial", CHARDEV_BACKEND_KIND_SERIAL,
3771 qemu_chr_parse_serial);
3772 register_char_driver_qapi("tty", CHARDEV_BACKEND_KIND_SERIAL,
3773 qemu_chr_parse_serial);
3774 register_char_driver_qapi("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
3775 qemu_chr_parse_parallel);
3776 register_char_driver_qapi("parport", CHARDEV_BACKEND_KIND_PARALLEL,
3777 qemu_chr_parse_parallel);
3778 register_char_driver_qapi("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
3779 register_char_driver_qapi("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
3780 register_char_driver_qapi("pipe", CHARDEV_BACKEND_KIND_PIPE,
3781 qemu_chr_parse_pipe);
3784 type_init(register_types);