migration: ensure htab_save_first completes after timeout
[qemu/ar7.git] / qemu-char.c
blobad11b75e3df0eecfc5e2e3ebb86bb99d2486f78b
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/osdep.h"
25 #include "qemu-common.h"
26 #include "monitor/monitor.h"
27 #include "sysemu/sysemu.h"
28 #include "qemu/error-report.h"
29 #include "qemu/timer.h"
30 #include "sysemu/char.h"
31 #include "hw/usb.h"
32 #include "qmp-commands.h"
33 #include "qapi/qmp-input-visitor.h"
34 #include "qapi/qmp-output-visitor.h"
35 #include "qapi-visit.h"
36 #include "qemu/base64.h"
37 #include "io/channel-socket.h"
38 #include "io/channel-file.h"
39 #include "io/channel-tls.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 <netdb.h>
55 #include <sys/select.h>
56 #ifdef CONFIG_BSD
57 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
58 #include <dev/ppbus/ppi.h>
59 #include <dev/ppbus/ppbconf.h>
60 #elif defined(__DragonFly__)
61 #include <dev/misc/ppi/ppi.h>
62 #include <bus/ppbus/ppbconf.h>
63 #endif
64 #else
65 #ifdef __linux__
66 #include <linux/ppdev.h>
67 #include <linux/parport.h>
68 #endif
69 #ifdef __sun__
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
87 #define READ_RETRIES 10
88 #define TCP_MAX_FDS 16
90 /***********************************************************/
91 /* Socket address helpers */
93 static char *SocketAddress_to_str(const char *prefix, SocketAddress *addr,
94 bool is_listen, bool is_telnet)
96 switch (addr->type) {
97 case SOCKET_ADDRESS_KIND_INET:
98 return g_strdup_printf("%s%s:%s:%s%s", prefix,
99 is_telnet ? "telnet" : "tcp", addr->u.inet->host,
100 addr->u.inet->port, is_listen ? ",server" : "");
101 break;
102 case SOCKET_ADDRESS_KIND_UNIX:
103 return g_strdup_printf("%sunix:%s%s", prefix,
104 addr->u.q_unix->path,
105 is_listen ? ",server" : "");
106 break;
107 case SOCKET_ADDRESS_KIND_FD:
108 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd->str,
109 is_listen ? ",server" : "");
110 break;
111 default:
112 abort();
116 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
117 struct sockaddr_storage *ps, socklen_t ps_len,
118 bool is_listen, bool is_telnet)
120 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
121 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
122 const char *left = "", *right = "";
124 switch (ss->ss_family) {
125 #ifndef _WIN32
126 case AF_UNIX:
127 return g_strdup_printf("unix:%s%s",
128 ((struct sockaddr_un *)(ss))->sun_path,
129 is_listen ? ",server" : "");
130 #endif
131 case AF_INET6:
132 left = "[";
133 right = "]";
134 /* fall through */
135 case AF_INET:
136 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
137 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
138 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
139 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
140 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
141 is_telnet ? "telnet" : "tcp",
142 left, shost, right, sserv,
143 is_listen ? ",server" : "",
144 left, phost, right, pserv);
146 default:
147 return g_strdup_printf("unknown");
151 /***********************************************************/
152 /* character device */
154 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
155 QTAILQ_HEAD_INITIALIZER(chardevs);
157 static void qemu_chr_free_common(CharDriverState *chr);
159 CharDriverState *qemu_chr_alloc(ChardevCommon *backend, Error **errp)
161 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
162 qemu_mutex_init(&chr->chr_write_lock);
164 if (backend->has_logfile) {
165 int flags = O_WRONLY | O_CREAT;
166 if (backend->has_logappend &&
167 backend->logappend) {
168 flags |= O_APPEND;
169 } else {
170 flags |= O_TRUNC;
172 chr->logfd = qemu_open(backend->logfile, flags, 0666);
173 if (chr->logfd < 0) {
174 error_setg_errno(errp, errno,
175 "Unable to open logfile %s",
176 backend->logfile);
177 g_free(chr);
178 return NULL;
180 } else {
181 chr->logfd = -1;
184 return chr;
187 void qemu_chr_be_event(CharDriverState *s, int event)
189 /* Keep track if the char device is open */
190 switch (event) {
191 case CHR_EVENT_OPENED:
192 s->be_open = 1;
193 break;
194 case CHR_EVENT_CLOSED:
195 s->be_open = 0;
196 break;
199 if (!s->chr_event)
200 return;
201 s->chr_event(s->handler_opaque, event);
204 void qemu_chr_be_generic_open(CharDriverState *s)
206 qemu_chr_be_event(s, CHR_EVENT_OPENED);
210 /* Not reporting errors from writing to logfile, as logs are
211 * defined to be "best effort" only */
212 static void qemu_chr_fe_write_log(CharDriverState *s,
213 const uint8_t *buf, size_t len)
215 size_t done = 0;
216 ssize_t ret;
218 if (s->logfd < 0) {
219 return;
222 while (done < len) {
223 do {
224 ret = write(s->logfd, buf + done, len - done);
225 if (ret == -1 && errno == EAGAIN) {
226 g_usleep(100);
228 } while (ret == -1 && errno == EAGAIN);
230 if (ret <= 0) {
231 return;
233 done += ret;
237 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
239 int ret;
241 qemu_mutex_lock(&s->chr_write_lock);
242 ret = s->chr_write(s, buf, len);
244 if (ret > 0) {
245 qemu_chr_fe_write_log(s, buf, ret);
248 qemu_mutex_unlock(&s->chr_write_lock);
249 return ret;
252 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
254 int offset = 0;
255 int res = 0;
257 qemu_mutex_lock(&s->chr_write_lock);
258 while (offset < len) {
259 do {
260 res = s->chr_write(s, buf + offset, len - offset);
261 if (res == -1 && errno == EAGAIN) {
262 g_usleep(100);
264 } while (res == -1 && errno == EAGAIN);
266 if (res <= 0) {
267 break;
270 offset += res;
272 if (offset > 0) {
273 qemu_chr_fe_write_log(s, buf, offset);
276 qemu_mutex_unlock(&s->chr_write_lock);
278 if (res < 0) {
279 return res;
281 return offset;
284 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
286 int offset = 0, counter = 10;
287 int res;
289 if (!s->chr_sync_read) {
290 return 0;
293 while (offset < len) {
294 do {
295 res = s->chr_sync_read(s, buf + offset, len - offset);
296 if (res == -1 && errno == EAGAIN) {
297 g_usleep(100);
299 } while (res == -1 && errno == EAGAIN);
301 if (res == 0) {
302 break;
305 if (res < 0) {
306 return res;
309 offset += res;
311 if (!counter--) {
312 break;
316 return offset;
319 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
321 if (!s->chr_ioctl)
322 return -ENOTSUP;
323 return s->chr_ioctl(s, cmd, arg);
326 int qemu_chr_be_can_write(CharDriverState *s)
328 if (!s->chr_can_read)
329 return 0;
330 return s->chr_can_read(s->handler_opaque);
333 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
335 if (s->chr_read) {
336 s->chr_read(s->handler_opaque, buf, len);
340 int qemu_chr_fe_get_msgfd(CharDriverState *s)
342 int fd;
343 return (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
346 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
348 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
351 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
353 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
356 int qemu_chr_add_client(CharDriverState *s, int fd)
358 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
361 void qemu_chr_accept_input(CharDriverState *s)
363 if (s->chr_accept_input)
364 s->chr_accept_input(s);
365 qemu_notify_event();
368 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
370 char buf[READ_BUF_LEN];
371 va_list ap;
372 va_start(ap, fmt);
373 vsnprintf(buf, sizeof(buf), fmt, ap);
374 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
375 va_end(ap);
378 static void remove_fd_in_watch(CharDriverState *chr);
380 void qemu_chr_add_handlers(CharDriverState *s,
381 IOCanReadHandler *fd_can_read,
382 IOReadHandler *fd_read,
383 IOEventHandler *fd_event,
384 void *opaque)
386 int fe_open;
388 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
389 fe_open = 0;
390 remove_fd_in_watch(s);
391 } else {
392 fe_open = 1;
394 s->chr_can_read = fd_can_read;
395 s->chr_read = fd_read;
396 s->chr_event = fd_event;
397 s->handler_opaque = opaque;
398 if (fe_open && s->chr_update_read_handler)
399 s->chr_update_read_handler(s);
401 if (!s->explicit_fe_open) {
402 qemu_chr_fe_set_open(s, fe_open);
405 /* We're connecting to an already opened device, so let's make sure we
406 also get the open event */
407 if (fe_open && s->be_open) {
408 qemu_chr_be_generic_open(s);
412 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
414 return len;
417 static CharDriverState *qemu_chr_open_null(const char *id,
418 ChardevBackend *backend,
419 ChardevReturn *ret,
420 Error **errp)
422 CharDriverState *chr;
423 ChardevCommon *common = qapi_ChardevDummy_base(backend->u.null);
425 chr = qemu_chr_alloc(common, errp);
426 if (!chr) {
427 return NULL;
429 chr->chr_write = null_chr_write;
430 chr->explicit_be_open = true;
431 return chr;
434 /* MUX driver for serial I/O splitting */
435 #define MAX_MUX 4
436 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
437 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
438 typedef struct {
439 IOCanReadHandler *chr_can_read[MAX_MUX];
440 IOReadHandler *chr_read[MAX_MUX];
441 IOEventHandler *chr_event[MAX_MUX];
442 void *ext_opaque[MAX_MUX];
443 CharDriverState *drv;
444 int focus;
445 int mux_cnt;
446 int term_got_escape;
447 int max_size;
448 /* Intermediate input buffer allows to catch escape sequences even if the
449 currently active device is not accepting any input - but only until it
450 is full as well. */
451 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
452 int prod[MAX_MUX];
453 int cons[MAX_MUX];
454 int timestamps;
456 /* Protected by the CharDriverState chr_write_lock. */
457 int linestart;
458 int64_t timestamps_start;
459 } MuxDriver;
462 /* Called with chr_write_lock held. */
463 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
465 MuxDriver *d = chr->opaque;
466 int ret;
467 if (!d->timestamps) {
468 ret = qemu_chr_fe_write(d->drv, buf, len);
469 } else {
470 int i;
472 ret = 0;
473 for (i = 0; i < len; i++) {
474 if (d->linestart) {
475 char buf1[64];
476 int64_t ti;
477 int secs;
479 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
480 if (d->timestamps_start == -1)
481 d->timestamps_start = ti;
482 ti -= d->timestamps_start;
483 secs = ti / 1000;
484 snprintf(buf1, sizeof(buf1),
485 "[%02d:%02d:%02d.%03d] ",
486 secs / 3600,
487 (secs / 60) % 60,
488 secs % 60,
489 (int)(ti % 1000));
490 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
491 d->linestart = 0;
493 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
494 if (buf[i] == '\n') {
495 d->linestart = 1;
499 return ret;
502 static const char * const mux_help[] = {
503 "% h print this help\n\r",
504 "% x exit emulator\n\r",
505 "% s save disk data back to file (if -snapshot)\n\r",
506 "% t toggle console timestamps\n\r",
507 "% b send break (magic sysrq)\n\r",
508 "% c switch between console and monitor\n\r",
509 "% % sends %\n\r",
510 NULL
513 int term_escape_char = 0x01; /* ctrl-a is used for escape */
514 static void mux_print_help(CharDriverState *chr)
516 int i, j;
517 char ebuf[15] = "Escape-Char";
518 char cbuf[50] = "\n\r";
520 if (term_escape_char > 0 && term_escape_char < 26) {
521 snprintf(cbuf, sizeof(cbuf), "\n\r");
522 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
523 } else {
524 snprintf(cbuf, sizeof(cbuf),
525 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
526 term_escape_char);
528 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
529 for (i = 0; mux_help[i] != NULL; i++) {
530 for (j=0; mux_help[i][j] != '\0'; j++) {
531 if (mux_help[i][j] == '%')
532 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
533 else
534 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
539 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
541 if (d->chr_event[mux_nr])
542 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
545 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
547 if (d->term_got_escape) {
548 d->term_got_escape = 0;
549 if (ch == term_escape_char)
550 goto send_char;
551 switch(ch) {
552 case '?':
553 case 'h':
554 mux_print_help(chr);
555 break;
556 case 'x':
558 const char *term = "QEMU: Terminated\n\r";
559 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
560 exit(0);
561 break;
563 case 's':
564 bdrv_commit_all();
565 break;
566 case 'b':
567 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
568 break;
569 case 'c':
570 /* Switch to the next registered device */
571 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
572 d->focus++;
573 if (d->focus >= d->mux_cnt)
574 d->focus = 0;
575 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
576 break;
577 case 't':
578 d->timestamps = !d->timestamps;
579 d->timestamps_start = -1;
580 d->linestart = 0;
581 break;
583 } else if (ch == term_escape_char) {
584 d->term_got_escape = 1;
585 } else {
586 send_char:
587 return 1;
589 return 0;
592 static void mux_chr_accept_input(CharDriverState *chr)
594 MuxDriver *d = chr->opaque;
595 int m = d->focus;
597 while (d->prod[m] != d->cons[m] &&
598 d->chr_can_read[m] &&
599 d->chr_can_read[m](d->ext_opaque[m])) {
600 d->chr_read[m](d->ext_opaque[m],
601 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
605 static int mux_chr_can_read(void *opaque)
607 CharDriverState *chr = opaque;
608 MuxDriver *d = chr->opaque;
609 int m = d->focus;
611 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
612 return 1;
613 if (d->chr_can_read[m])
614 return d->chr_can_read[m](d->ext_opaque[m]);
615 return 0;
618 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
620 CharDriverState *chr = opaque;
621 MuxDriver *d = chr->opaque;
622 int m = d->focus;
623 int i;
625 mux_chr_accept_input (opaque);
627 for(i = 0; i < size; i++)
628 if (mux_proc_byte(chr, d, buf[i])) {
629 if (d->prod[m] == d->cons[m] &&
630 d->chr_can_read[m] &&
631 d->chr_can_read[m](d->ext_opaque[m]))
632 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
633 else
634 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
638 static void mux_chr_event(void *opaque, int event)
640 CharDriverState *chr = opaque;
641 MuxDriver *d = chr->opaque;
642 int i;
644 /* Send the event to all registered listeners */
645 for (i = 0; i < d->mux_cnt; i++)
646 mux_chr_send_event(d, i, event);
649 static void mux_chr_update_read_handler(CharDriverState *chr)
651 MuxDriver *d = chr->opaque;
653 if (d->mux_cnt >= MAX_MUX) {
654 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
655 return;
657 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
658 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
659 d->chr_read[d->mux_cnt] = chr->chr_read;
660 d->chr_event[d->mux_cnt] = chr->chr_event;
661 /* Fix up the real driver with mux routines */
662 if (d->mux_cnt == 0) {
663 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
664 mux_chr_event, chr);
666 if (d->focus != -1) {
667 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
669 d->focus = d->mux_cnt;
670 d->mux_cnt++;
671 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
674 static bool muxes_realized;
677 * Called after processing of default and command-line-specified
678 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
679 * to a mux chardev. This is done here to ensure that
680 * output/prompts/banners are only displayed for the FE that has
681 * focus when initial command-line processing/machine init is
682 * completed.
684 * After this point, any new FE attached to any new or existing
685 * mux will receive CHR_EVENT_OPENED notifications for the BE
686 * immediately.
688 static void muxes_realize_done(Notifier *notifier, void *unused)
690 CharDriverState *chr;
692 QTAILQ_FOREACH(chr, &chardevs, next) {
693 if (chr->is_mux) {
694 MuxDriver *d = chr->opaque;
695 int i;
697 /* send OPENED to all already-attached FEs */
698 for (i = 0; i < d->mux_cnt; i++) {
699 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
701 /* mark mux as OPENED so any new FEs will immediately receive
702 * OPENED event
704 qemu_chr_be_generic_open(chr);
707 muxes_realized = true;
710 static Notifier muxes_realize_notify = {
711 .notify = muxes_realize_done,
714 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
716 MuxDriver *d = s->opaque;
717 return d->drv->chr_add_watch(d->drv, cond);
720 static CharDriverState *qemu_chr_open_mux(const char *id,
721 ChardevBackend *backend,
722 ChardevReturn *ret, Error **errp)
724 ChardevMux *mux = backend->u.mux;
725 CharDriverState *chr, *drv;
726 MuxDriver *d;
727 ChardevCommon *common = qapi_ChardevMux_base(backend->u.mux);
729 drv = qemu_chr_find(mux->chardev);
730 if (drv == NULL) {
731 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
732 return NULL;
735 chr = qemu_chr_alloc(common, errp);
736 if (!chr) {
737 return NULL;
739 d = g_new0(MuxDriver, 1);
741 chr->opaque = d;
742 d->drv = drv;
743 d->focus = -1;
744 chr->chr_write = mux_chr_write;
745 chr->chr_update_read_handler = mux_chr_update_read_handler;
746 chr->chr_accept_input = mux_chr_accept_input;
747 /* Frontend guest-open / -close notification is not support with muxes */
748 chr->chr_set_fe_open = NULL;
749 if (drv->chr_add_watch) {
750 chr->chr_add_watch = mux_chr_add_watch;
752 /* only default to opened state if we've realized the initial
753 * set of muxes
755 chr->explicit_be_open = muxes_realized ? 0 : 1;
756 chr->is_mux = 1;
758 return chr;
762 typedef struct IOWatchPoll
764 GSource parent;
766 QIOChannel *ioc;
767 GSource *src;
769 IOCanReadHandler *fd_can_read;
770 GSourceFunc fd_read;
771 void *opaque;
772 } IOWatchPoll;
774 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
776 return container_of(source, IOWatchPoll, parent);
779 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
781 IOWatchPoll *iwp = io_watch_poll_from_source(source);
782 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
783 bool was_active = iwp->src != NULL;
784 if (was_active == now_active) {
785 return FALSE;
788 if (now_active) {
789 iwp->src = qio_channel_create_watch(
790 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
791 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
792 g_source_attach(iwp->src, NULL);
793 } else {
794 g_source_destroy(iwp->src);
795 g_source_unref(iwp->src);
796 iwp->src = NULL;
798 return FALSE;
801 static gboolean io_watch_poll_check(GSource *source)
803 return FALSE;
806 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
807 gpointer user_data)
809 abort();
812 static void io_watch_poll_finalize(GSource *source)
814 /* Due to a glib bug, removing the last reference to a source
815 * inside a finalize callback causes recursive locking (and a
816 * deadlock). This is not a problem inside other callbacks,
817 * including dispatch callbacks, so we call io_remove_watch_poll
818 * to remove this source. At this point, iwp->src must
819 * be NULL, or we would leak it.
821 * This would be solved much more elegantly by child sources,
822 * but we support older glib versions that do not have them.
824 IOWatchPoll *iwp = io_watch_poll_from_source(source);
825 assert(iwp->src == NULL);
828 static GSourceFuncs io_watch_poll_funcs = {
829 .prepare = io_watch_poll_prepare,
830 .check = io_watch_poll_check,
831 .dispatch = io_watch_poll_dispatch,
832 .finalize = io_watch_poll_finalize,
835 /* Can only be used for read */
836 static guint io_add_watch_poll(QIOChannel *ioc,
837 IOCanReadHandler *fd_can_read,
838 QIOChannelFunc fd_read,
839 gpointer user_data)
841 IOWatchPoll *iwp;
842 int tag;
844 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
845 iwp->fd_can_read = fd_can_read;
846 iwp->opaque = user_data;
847 iwp->ioc = ioc;
848 iwp->fd_read = (GSourceFunc) fd_read;
849 iwp->src = NULL;
851 tag = g_source_attach(&iwp->parent, NULL);
852 g_source_unref(&iwp->parent);
853 return tag;
856 static void io_remove_watch_poll(guint tag)
858 GSource *source;
859 IOWatchPoll *iwp;
861 g_return_if_fail (tag > 0);
863 source = g_main_context_find_source_by_id(NULL, tag);
864 g_return_if_fail (source != NULL);
866 iwp = io_watch_poll_from_source(source);
867 if (iwp->src) {
868 g_source_destroy(iwp->src);
869 g_source_unref(iwp->src);
870 iwp->src = NULL;
872 g_source_destroy(&iwp->parent);
875 static void remove_fd_in_watch(CharDriverState *chr)
877 if (chr->fd_in_tag) {
878 io_remove_watch_poll(chr->fd_in_tag);
879 chr->fd_in_tag = 0;
884 static int io_channel_send_full(QIOChannel *ioc,
885 const void *buf, size_t len,
886 int *fds, size_t nfds)
888 size_t offset = 0;
890 while (offset < len) {
891 ssize_t ret = 0;
892 struct iovec iov = { .iov_base = (char *)buf + offset,
893 .iov_len = len - offset };
895 ret = qio_channel_writev_full(
896 ioc, &iov, 1,
897 fds, nfds, NULL);
898 if (ret == QIO_CHANNEL_ERR_BLOCK) {
899 if (offset) {
900 return offset;
903 errno = EAGAIN;
904 return -1;
905 } else if (ret < 0) {
906 errno = EINVAL;
907 return -1;
910 offset += ret;
913 return offset;
917 #ifndef _WIN32
918 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
920 return io_channel_send_full(ioc, buf, len, NULL, 0);
924 typedef struct FDCharDriver {
925 CharDriverState *chr;
926 QIOChannel *ioc_in, *ioc_out;
927 int max_size;
928 } FDCharDriver;
930 /* Called with chr_write_lock held. */
931 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
933 FDCharDriver *s = chr->opaque;
935 return io_channel_send(s->ioc_out, buf, len);
938 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
940 CharDriverState *chr = opaque;
941 FDCharDriver *s = chr->opaque;
942 int len;
943 uint8_t buf[READ_BUF_LEN];
944 ssize_t ret;
946 len = sizeof(buf);
947 if (len > s->max_size) {
948 len = s->max_size;
950 if (len == 0) {
951 return TRUE;
954 ret = qio_channel_read(
955 chan, (gchar *)buf, len, NULL);
956 if (ret == 0) {
957 remove_fd_in_watch(chr);
958 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
959 return FALSE;
961 if (ret > 0) {
962 qemu_chr_be_write(chr, buf, ret);
965 return TRUE;
968 static int fd_chr_read_poll(void *opaque)
970 CharDriverState *chr = opaque;
971 FDCharDriver *s = chr->opaque;
973 s->max_size = qemu_chr_be_can_write(chr);
974 return s->max_size;
977 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
979 FDCharDriver *s = chr->opaque;
980 return qio_channel_create_watch(s->ioc_out, cond);
983 static void fd_chr_update_read_handler(CharDriverState *chr)
985 FDCharDriver *s = chr->opaque;
987 remove_fd_in_watch(chr);
988 if (s->ioc_in) {
989 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
990 fd_chr_read_poll,
991 fd_chr_read, chr);
995 static void fd_chr_close(struct CharDriverState *chr)
997 FDCharDriver *s = chr->opaque;
999 remove_fd_in_watch(chr);
1000 if (s->ioc_in) {
1001 object_unref(OBJECT(s->ioc_in));
1003 if (s->ioc_out) {
1004 object_unref(OBJECT(s->ioc_out));
1007 g_free(s);
1008 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1011 /* open a character device to a unix fd */
1012 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1013 ChardevCommon *backend, Error **errp)
1015 CharDriverState *chr;
1016 FDCharDriver *s;
1018 chr = qemu_chr_alloc(backend, errp);
1019 if (!chr) {
1020 return NULL;
1022 s = g_new0(FDCharDriver, 1);
1023 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1024 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1025 qemu_set_nonblock(fd_out);
1026 s->chr = chr;
1027 chr->opaque = s;
1028 chr->chr_add_watch = fd_chr_add_watch;
1029 chr->chr_write = fd_chr_write;
1030 chr->chr_update_read_handler = fd_chr_update_read_handler;
1031 chr->chr_close = fd_chr_close;
1033 return chr;
1036 static CharDriverState *qemu_chr_open_pipe(const char *id,
1037 ChardevBackend *backend,
1038 ChardevReturn *ret,
1039 Error **errp)
1041 ChardevHostdev *opts = backend->u.pipe;
1042 int fd_in, fd_out;
1043 char *filename_in;
1044 char *filename_out;
1045 const char *filename = opts->device;
1046 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.pipe);
1049 filename_in = g_strdup_printf("%s.in", filename);
1050 filename_out = g_strdup_printf("%s.out", filename);
1051 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1052 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1053 g_free(filename_in);
1054 g_free(filename_out);
1055 if (fd_in < 0 || fd_out < 0) {
1056 if (fd_in >= 0)
1057 close(fd_in);
1058 if (fd_out >= 0)
1059 close(fd_out);
1060 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1061 if (fd_in < 0) {
1062 error_setg_file_open(errp, errno, filename);
1063 return NULL;
1066 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1069 /* init terminal so that we can grab keys */
1070 static struct termios oldtty;
1071 static int old_fd0_flags;
1072 static bool stdio_in_use;
1073 static bool stdio_allow_signal;
1074 static bool stdio_echo_state;
1076 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1078 static void term_exit(void)
1080 tcsetattr (0, TCSANOW, &oldtty);
1081 fcntl(0, F_SETFL, old_fd0_flags);
1084 static void term_stdio_handler(int sig)
1086 /* restore echo after resume from suspend. */
1087 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1090 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1092 struct termios tty;
1094 stdio_echo_state = echo;
1095 tty = oldtty;
1096 if (!echo) {
1097 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1098 |INLCR|IGNCR|ICRNL|IXON);
1099 tty.c_oflag |= OPOST;
1100 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1101 tty.c_cflag &= ~(CSIZE|PARENB);
1102 tty.c_cflag |= CS8;
1103 tty.c_cc[VMIN] = 1;
1104 tty.c_cc[VTIME] = 0;
1106 if (!stdio_allow_signal)
1107 tty.c_lflag &= ~ISIG;
1109 tcsetattr (0, TCSANOW, &tty);
1112 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1114 term_exit();
1115 fd_chr_close(chr);
1118 static CharDriverState *qemu_chr_open_stdio(const char *id,
1119 ChardevBackend *backend,
1120 ChardevReturn *ret,
1121 Error **errp)
1123 ChardevStdio *opts = backend->u.stdio;
1124 CharDriverState *chr;
1125 struct sigaction act;
1126 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio);
1128 if (is_daemonized()) {
1129 error_setg(errp, "cannot use stdio with -daemonize");
1130 return NULL;
1133 if (stdio_in_use) {
1134 error_setg(errp, "cannot use stdio by multiple character devices");
1135 return NULL;
1138 stdio_in_use = true;
1139 old_fd0_flags = fcntl(0, F_GETFL);
1140 tcgetattr(0, &oldtty);
1141 qemu_set_nonblock(0);
1142 atexit(term_exit);
1144 memset(&act, 0, sizeof(act));
1145 act.sa_handler = term_stdio_handler;
1146 sigaction(SIGCONT, &act, NULL);
1148 chr = qemu_chr_open_fd(0, 1, common, errp);
1149 chr->chr_close = qemu_chr_close_stdio;
1150 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1151 if (opts->has_signal) {
1152 stdio_allow_signal = opts->signal;
1154 qemu_chr_fe_set_echo(chr, false);
1156 return chr;
1159 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1160 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1161 || defined(__GLIBC__)
1163 #define HAVE_CHARDEV_SERIAL 1
1164 #define HAVE_CHARDEV_PTY 1
1166 typedef struct {
1167 QIOChannel *ioc;
1168 int read_bytes;
1170 /* Protected by the CharDriverState chr_write_lock. */
1171 int connected;
1172 guint timer_tag;
1173 guint open_tag;
1174 } PtyCharDriver;
1176 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1177 static void pty_chr_state(CharDriverState *chr, int connected);
1179 static gboolean pty_chr_timer(gpointer opaque)
1181 struct CharDriverState *chr = opaque;
1182 PtyCharDriver *s = chr->opaque;
1184 qemu_mutex_lock(&chr->chr_write_lock);
1185 s->timer_tag = 0;
1186 s->open_tag = 0;
1187 if (!s->connected) {
1188 /* Next poll ... */
1189 pty_chr_update_read_handler_locked(chr);
1191 qemu_mutex_unlock(&chr->chr_write_lock);
1192 return FALSE;
1195 /* Called with chr_write_lock held. */
1196 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1198 PtyCharDriver *s = chr->opaque;
1200 if (s->timer_tag) {
1201 g_source_remove(s->timer_tag);
1202 s->timer_tag = 0;
1205 if (ms == 1000) {
1206 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1207 } else {
1208 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1212 /* Called with chr_write_lock held. */
1213 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1215 PtyCharDriver *s = chr->opaque;
1216 GPollFD pfd;
1217 int rc;
1218 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1220 pfd.fd = fioc->fd;
1221 pfd.events = G_IO_OUT;
1222 pfd.revents = 0;
1223 do {
1224 rc = g_poll(&pfd, 1, 0);
1225 } while (rc == -1 && errno == EINTR);
1226 assert(rc >= 0);
1228 if (pfd.revents & G_IO_HUP) {
1229 pty_chr_state(chr, 0);
1230 } else {
1231 pty_chr_state(chr, 1);
1235 static void pty_chr_update_read_handler(CharDriverState *chr)
1237 qemu_mutex_lock(&chr->chr_write_lock);
1238 pty_chr_update_read_handler_locked(chr);
1239 qemu_mutex_unlock(&chr->chr_write_lock);
1242 /* Called with chr_write_lock held. */
1243 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1245 PtyCharDriver *s = chr->opaque;
1247 if (!s->connected) {
1248 /* guest sends data, check for (re-)connect */
1249 pty_chr_update_read_handler_locked(chr);
1250 if (!s->connected) {
1251 return 0;
1254 return io_channel_send(s->ioc, buf, len);
1257 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1259 PtyCharDriver *s = chr->opaque;
1260 if (!s->connected) {
1261 return NULL;
1263 return qio_channel_create_watch(s->ioc, cond);
1266 static int pty_chr_read_poll(void *opaque)
1268 CharDriverState *chr = opaque;
1269 PtyCharDriver *s = chr->opaque;
1271 s->read_bytes = qemu_chr_be_can_write(chr);
1272 return s->read_bytes;
1275 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1277 CharDriverState *chr = opaque;
1278 PtyCharDriver *s = chr->opaque;
1279 gsize len;
1280 uint8_t buf[READ_BUF_LEN];
1281 ssize_t ret;
1283 len = sizeof(buf);
1284 if (len > s->read_bytes)
1285 len = s->read_bytes;
1286 if (len == 0) {
1287 return TRUE;
1289 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1290 if (ret <= 0) {
1291 pty_chr_state(chr, 0);
1292 return FALSE;
1293 } else {
1294 pty_chr_state(chr, 1);
1295 qemu_chr_be_write(chr, buf, ret);
1297 return TRUE;
1300 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1302 CharDriverState *chr = opaque;
1303 PtyCharDriver *s = chr->opaque;
1305 s->open_tag = 0;
1306 qemu_chr_be_generic_open(chr);
1307 return FALSE;
1310 /* Called with chr_write_lock held. */
1311 static void pty_chr_state(CharDriverState *chr, int connected)
1313 PtyCharDriver *s = chr->opaque;
1315 if (!connected) {
1316 if (s->open_tag) {
1317 g_source_remove(s->open_tag);
1318 s->open_tag = 0;
1320 remove_fd_in_watch(chr);
1321 s->connected = 0;
1322 /* (re-)connect poll interval for idle guests: once per second.
1323 * We check more frequently in case the guests sends data to
1324 * the virtual device linked to our pty. */
1325 pty_chr_rearm_timer(chr, 1000);
1326 } else {
1327 if (s->timer_tag) {
1328 g_source_remove(s->timer_tag);
1329 s->timer_tag = 0;
1331 if (!s->connected) {
1332 g_assert(s->open_tag == 0);
1333 s->connected = 1;
1334 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1336 if (!chr->fd_in_tag) {
1337 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1338 pty_chr_read_poll,
1339 pty_chr_read, chr);
1344 static void pty_chr_close(struct CharDriverState *chr)
1346 PtyCharDriver *s = chr->opaque;
1348 qemu_mutex_lock(&chr->chr_write_lock);
1349 pty_chr_state(chr, 0);
1350 object_unref(OBJECT(s->ioc));
1351 if (s->timer_tag) {
1352 g_source_remove(s->timer_tag);
1353 s->timer_tag = 0;
1355 qemu_mutex_unlock(&chr->chr_write_lock);
1356 g_free(s);
1357 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1360 static CharDriverState *qemu_chr_open_pty(const char *id,
1361 ChardevBackend *backend,
1362 ChardevReturn *ret,
1363 Error **errp)
1365 CharDriverState *chr;
1366 PtyCharDriver *s;
1367 int master_fd, slave_fd;
1368 char pty_name[PATH_MAX];
1369 ChardevCommon *common = qapi_ChardevDummy_base(backend->u.pty);
1371 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1372 if (master_fd < 0) {
1373 error_setg_errno(errp, errno, "Failed to create PTY");
1374 return NULL;
1377 close(slave_fd);
1378 qemu_set_nonblock(master_fd);
1380 chr = qemu_chr_alloc(common, errp);
1381 if (!chr) {
1382 close(master_fd);
1383 return NULL;
1386 chr->filename = g_strdup_printf("pty:%s", pty_name);
1387 ret->pty = g_strdup(pty_name);
1388 ret->has_pty = true;
1390 fprintf(stderr, "char device redirected to %s (label %s)\n",
1391 pty_name, id);
1393 s = g_new0(PtyCharDriver, 1);
1394 chr->opaque = s;
1395 chr->chr_write = pty_chr_write;
1396 chr->chr_update_read_handler = pty_chr_update_read_handler;
1397 chr->chr_close = pty_chr_close;
1398 chr->chr_add_watch = pty_chr_add_watch;
1399 chr->explicit_be_open = true;
1401 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1402 s->timer_tag = 0;
1404 return chr;
1407 static void tty_serial_init(int fd, int speed,
1408 int parity, int data_bits, int stop_bits)
1410 struct termios tty;
1411 speed_t spd;
1413 #if 0
1414 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1415 speed, parity, data_bits, stop_bits);
1416 #endif
1417 tcgetattr (fd, &tty);
1419 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1420 speed = speed * 10 / 11;
1421 do {
1422 check_speed(50);
1423 check_speed(75);
1424 check_speed(110);
1425 check_speed(134);
1426 check_speed(150);
1427 check_speed(200);
1428 check_speed(300);
1429 check_speed(600);
1430 check_speed(1200);
1431 check_speed(1800);
1432 check_speed(2400);
1433 check_speed(4800);
1434 check_speed(9600);
1435 check_speed(19200);
1436 check_speed(38400);
1437 /* Non-Posix values follow. They may be unsupported on some systems. */
1438 check_speed(57600);
1439 check_speed(115200);
1440 #ifdef B230400
1441 check_speed(230400);
1442 #endif
1443 #ifdef B460800
1444 check_speed(460800);
1445 #endif
1446 #ifdef B500000
1447 check_speed(500000);
1448 #endif
1449 #ifdef B576000
1450 check_speed(576000);
1451 #endif
1452 #ifdef B921600
1453 check_speed(921600);
1454 #endif
1455 #ifdef B1000000
1456 check_speed(1000000);
1457 #endif
1458 #ifdef B1152000
1459 check_speed(1152000);
1460 #endif
1461 #ifdef B1500000
1462 check_speed(1500000);
1463 #endif
1464 #ifdef B2000000
1465 check_speed(2000000);
1466 #endif
1467 #ifdef B2500000
1468 check_speed(2500000);
1469 #endif
1470 #ifdef B3000000
1471 check_speed(3000000);
1472 #endif
1473 #ifdef B3500000
1474 check_speed(3500000);
1475 #endif
1476 #ifdef B4000000
1477 check_speed(4000000);
1478 #endif
1479 spd = B115200;
1480 } while (0);
1482 cfsetispeed(&tty, spd);
1483 cfsetospeed(&tty, spd);
1485 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1486 |INLCR|IGNCR|ICRNL|IXON);
1487 tty.c_oflag |= OPOST;
1488 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1489 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1490 switch(data_bits) {
1491 default:
1492 case 8:
1493 tty.c_cflag |= CS8;
1494 break;
1495 case 7:
1496 tty.c_cflag |= CS7;
1497 break;
1498 case 6:
1499 tty.c_cflag |= CS6;
1500 break;
1501 case 5:
1502 tty.c_cflag |= CS5;
1503 break;
1505 switch(parity) {
1506 default:
1507 case 'N':
1508 break;
1509 case 'E':
1510 tty.c_cflag |= PARENB;
1511 break;
1512 case 'O':
1513 tty.c_cflag |= PARENB | PARODD;
1514 break;
1516 if (stop_bits == 2)
1517 tty.c_cflag |= CSTOPB;
1519 tcsetattr (fd, TCSANOW, &tty);
1522 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1524 FDCharDriver *s = chr->opaque;
1525 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1527 switch(cmd) {
1528 case CHR_IOCTL_SERIAL_SET_PARAMS:
1530 QEMUSerialSetParams *ssp = arg;
1531 tty_serial_init(fioc->fd,
1532 ssp->speed, ssp->parity,
1533 ssp->data_bits, ssp->stop_bits);
1535 break;
1536 case CHR_IOCTL_SERIAL_SET_BREAK:
1538 int enable = *(int *)arg;
1539 if (enable) {
1540 tcsendbreak(fioc->fd, 1);
1543 break;
1544 case CHR_IOCTL_SERIAL_GET_TIOCM:
1546 int sarg = 0;
1547 int *targ = (int *)arg;
1548 ioctl(fioc->fd, TIOCMGET, &sarg);
1549 *targ = 0;
1550 if (sarg & TIOCM_CTS)
1551 *targ |= CHR_TIOCM_CTS;
1552 if (sarg & TIOCM_CAR)
1553 *targ |= CHR_TIOCM_CAR;
1554 if (sarg & TIOCM_DSR)
1555 *targ |= CHR_TIOCM_DSR;
1556 if (sarg & TIOCM_RI)
1557 *targ |= CHR_TIOCM_RI;
1558 if (sarg & TIOCM_DTR)
1559 *targ |= CHR_TIOCM_DTR;
1560 if (sarg & TIOCM_RTS)
1561 *targ |= CHR_TIOCM_RTS;
1563 break;
1564 case CHR_IOCTL_SERIAL_SET_TIOCM:
1566 int sarg = *(int *)arg;
1567 int targ = 0;
1568 ioctl(fioc->fd, TIOCMGET, &targ);
1569 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1570 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1571 if (sarg & CHR_TIOCM_CTS)
1572 targ |= TIOCM_CTS;
1573 if (sarg & CHR_TIOCM_CAR)
1574 targ |= TIOCM_CAR;
1575 if (sarg & CHR_TIOCM_DSR)
1576 targ |= TIOCM_DSR;
1577 if (sarg & CHR_TIOCM_RI)
1578 targ |= TIOCM_RI;
1579 if (sarg & CHR_TIOCM_DTR)
1580 targ |= TIOCM_DTR;
1581 if (sarg & CHR_TIOCM_RTS)
1582 targ |= TIOCM_RTS;
1583 ioctl(fioc->fd, TIOCMSET, &targ);
1585 break;
1586 default:
1587 return -ENOTSUP;
1589 return 0;
1592 static void qemu_chr_close_tty(CharDriverState *chr)
1594 fd_chr_close(chr);
1597 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1598 ChardevCommon *backend,
1599 Error **errp)
1601 CharDriverState *chr;
1603 tty_serial_init(fd, 115200, 'N', 8, 1);
1604 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1605 chr->chr_ioctl = tty_serial_ioctl;
1606 chr->chr_close = qemu_chr_close_tty;
1607 return chr;
1609 #endif /* __linux__ || __sun__ */
1611 #if defined(__linux__)
1613 #define HAVE_CHARDEV_PARPORT 1
1615 typedef struct {
1616 int fd;
1617 int mode;
1618 } ParallelCharDriver;
1620 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1622 if (s->mode != mode) {
1623 int m = mode;
1624 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1625 return 0;
1626 s->mode = mode;
1628 return 1;
1631 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1633 ParallelCharDriver *drv = chr->opaque;
1634 int fd = drv->fd;
1635 uint8_t b;
1637 switch(cmd) {
1638 case CHR_IOCTL_PP_READ_DATA:
1639 if (ioctl(fd, PPRDATA, &b) < 0)
1640 return -ENOTSUP;
1641 *(uint8_t *)arg = b;
1642 break;
1643 case CHR_IOCTL_PP_WRITE_DATA:
1644 b = *(uint8_t *)arg;
1645 if (ioctl(fd, PPWDATA, &b) < 0)
1646 return -ENOTSUP;
1647 break;
1648 case CHR_IOCTL_PP_READ_CONTROL:
1649 if (ioctl(fd, PPRCONTROL, &b) < 0)
1650 return -ENOTSUP;
1651 /* Linux gives only the lowest bits, and no way to know data
1652 direction! For better compatibility set the fixed upper
1653 bits. */
1654 *(uint8_t *)arg = b | 0xc0;
1655 break;
1656 case CHR_IOCTL_PP_WRITE_CONTROL:
1657 b = *(uint8_t *)arg;
1658 if (ioctl(fd, PPWCONTROL, &b) < 0)
1659 return -ENOTSUP;
1660 break;
1661 case CHR_IOCTL_PP_READ_STATUS:
1662 if (ioctl(fd, PPRSTATUS, &b) < 0)
1663 return -ENOTSUP;
1664 *(uint8_t *)arg = b;
1665 break;
1666 case CHR_IOCTL_PP_DATA_DIR:
1667 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1668 return -ENOTSUP;
1669 break;
1670 case CHR_IOCTL_PP_EPP_READ_ADDR:
1671 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1672 struct ParallelIOArg *parg = arg;
1673 int n = read(fd, parg->buffer, parg->count);
1674 if (n != parg->count) {
1675 return -EIO;
1678 break;
1679 case CHR_IOCTL_PP_EPP_READ:
1680 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1681 struct ParallelIOArg *parg = arg;
1682 int n = read(fd, parg->buffer, parg->count);
1683 if (n != parg->count) {
1684 return -EIO;
1687 break;
1688 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1689 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1690 struct ParallelIOArg *parg = arg;
1691 int n = write(fd, parg->buffer, parg->count);
1692 if (n != parg->count) {
1693 return -EIO;
1696 break;
1697 case CHR_IOCTL_PP_EPP_WRITE:
1698 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1699 struct ParallelIOArg *parg = arg;
1700 int n = write(fd, parg->buffer, parg->count);
1701 if (n != parg->count) {
1702 return -EIO;
1705 break;
1706 default:
1707 return -ENOTSUP;
1709 return 0;
1712 static void pp_close(CharDriverState *chr)
1714 ParallelCharDriver *drv = chr->opaque;
1715 int fd = drv->fd;
1717 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1718 ioctl(fd, PPRELEASE);
1719 close(fd);
1720 g_free(drv);
1721 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1724 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1725 ChardevCommon *backend,
1726 Error **errp)
1728 CharDriverState *chr;
1729 ParallelCharDriver *drv;
1731 if (ioctl(fd, PPCLAIM) < 0) {
1732 error_setg_errno(errp, errno, "not a parallel port");
1733 close(fd);
1734 return NULL;
1737 chr = qemu_chr_alloc(backend, errp);
1738 if (!chr) {
1739 return NULL;
1742 drv = g_new0(ParallelCharDriver, 1);
1743 chr->opaque = drv;
1744 chr->chr_write = null_chr_write;
1745 chr->chr_ioctl = pp_ioctl;
1746 chr->chr_close = pp_close;
1748 drv->fd = fd;
1749 drv->mode = IEEE1284_MODE_COMPAT;
1751 return chr;
1753 #endif /* __linux__ */
1755 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1757 #define HAVE_CHARDEV_PARPORT 1
1759 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1761 int fd = (int)(intptr_t)chr->opaque;
1762 uint8_t b;
1764 switch(cmd) {
1765 case CHR_IOCTL_PP_READ_DATA:
1766 if (ioctl(fd, PPIGDATA, &b) < 0)
1767 return -ENOTSUP;
1768 *(uint8_t *)arg = b;
1769 break;
1770 case CHR_IOCTL_PP_WRITE_DATA:
1771 b = *(uint8_t *)arg;
1772 if (ioctl(fd, PPISDATA, &b) < 0)
1773 return -ENOTSUP;
1774 break;
1775 case CHR_IOCTL_PP_READ_CONTROL:
1776 if (ioctl(fd, PPIGCTRL, &b) < 0)
1777 return -ENOTSUP;
1778 *(uint8_t *)arg = b;
1779 break;
1780 case CHR_IOCTL_PP_WRITE_CONTROL:
1781 b = *(uint8_t *)arg;
1782 if (ioctl(fd, PPISCTRL, &b) < 0)
1783 return -ENOTSUP;
1784 break;
1785 case CHR_IOCTL_PP_READ_STATUS:
1786 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1787 return -ENOTSUP;
1788 *(uint8_t *)arg = b;
1789 break;
1790 default:
1791 return -ENOTSUP;
1793 return 0;
1796 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1797 ChardevCommon *backend,
1798 Error **errp)
1800 CharDriverState *chr;
1802 chr = qemu_chr_alloc(backend, errp);
1803 if (!chr) {
1804 return NULL;
1806 chr->opaque = (void *)(intptr_t)fd;
1807 chr->chr_write = null_chr_write;
1808 chr->chr_ioctl = pp_ioctl;
1809 chr->explicit_be_open = true;
1810 return chr;
1812 #endif
1814 #else /* _WIN32 */
1816 #define HAVE_CHARDEV_SERIAL 1
1818 typedef struct {
1819 int max_size;
1820 HANDLE hcom, hrecv, hsend;
1821 OVERLAPPED orecv;
1822 BOOL fpipe;
1823 DWORD len;
1825 /* Protected by the CharDriverState chr_write_lock. */
1826 OVERLAPPED osend;
1827 } WinCharState;
1829 typedef struct {
1830 HANDLE hStdIn;
1831 HANDLE hInputReadyEvent;
1832 HANDLE hInputDoneEvent;
1833 HANDLE hInputThread;
1834 uint8_t win_stdio_buf;
1835 } WinStdioCharState;
1837 #define NSENDBUF 2048
1838 #define NRECVBUF 2048
1839 #define MAXCONNECT 1
1840 #define NTIMEOUT 5000
1842 static int win_chr_poll(void *opaque);
1843 static int win_chr_pipe_poll(void *opaque);
1845 static void win_chr_close(CharDriverState *chr)
1847 WinCharState *s = chr->opaque;
1849 if (s->hsend) {
1850 CloseHandle(s->hsend);
1851 s->hsend = NULL;
1853 if (s->hrecv) {
1854 CloseHandle(s->hrecv);
1855 s->hrecv = NULL;
1857 if (s->hcom) {
1858 CloseHandle(s->hcom);
1859 s->hcom = NULL;
1861 if (s->fpipe)
1862 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1863 else
1864 qemu_del_polling_cb(win_chr_poll, chr);
1866 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1869 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1871 WinCharState *s = chr->opaque;
1872 COMMCONFIG comcfg;
1873 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1874 COMSTAT comstat;
1875 DWORD size;
1876 DWORD err;
1878 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1879 if (!s->hsend) {
1880 error_setg(errp, "Failed CreateEvent");
1881 goto fail;
1883 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1884 if (!s->hrecv) {
1885 error_setg(errp, "Failed CreateEvent");
1886 goto fail;
1889 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1890 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1891 if (s->hcom == INVALID_HANDLE_VALUE) {
1892 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1893 s->hcom = NULL;
1894 goto fail;
1897 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1898 error_setg(errp, "Failed SetupComm");
1899 goto fail;
1902 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1903 size = sizeof(COMMCONFIG);
1904 GetDefaultCommConfig(filename, &comcfg, &size);
1905 comcfg.dcb.DCBlength = sizeof(DCB);
1906 CommConfigDialog(filename, NULL, &comcfg);
1908 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1909 error_setg(errp, "Failed SetCommState");
1910 goto fail;
1913 if (!SetCommMask(s->hcom, EV_ERR)) {
1914 error_setg(errp, "Failed SetCommMask");
1915 goto fail;
1918 cto.ReadIntervalTimeout = MAXDWORD;
1919 if (!SetCommTimeouts(s->hcom, &cto)) {
1920 error_setg(errp, "Failed SetCommTimeouts");
1921 goto fail;
1924 if (!ClearCommError(s->hcom, &err, &comstat)) {
1925 error_setg(errp, "Failed ClearCommError");
1926 goto fail;
1928 qemu_add_polling_cb(win_chr_poll, chr);
1929 return 0;
1931 fail:
1932 win_chr_close(chr);
1933 return -1;
1936 /* Called with chr_write_lock held. */
1937 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1939 WinCharState *s = chr->opaque;
1940 DWORD len, ret, size, err;
1942 len = len1;
1943 ZeroMemory(&s->osend, sizeof(s->osend));
1944 s->osend.hEvent = s->hsend;
1945 while (len > 0) {
1946 if (s->hsend)
1947 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1948 else
1949 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1950 if (!ret) {
1951 err = GetLastError();
1952 if (err == ERROR_IO_PENDING) {
1953 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1954 if (ret) {
1955 buf += size;
1956 len -= size;
1957 } else {
1958 break;
1960 } else {
1961 break;
1963 } else {
1964 buf += size;
1965 len -= size;
1968 return len1 - len;
1971 static int win_chr_read_poll(CharDriverState *chr)
1973 WinCharState *s = chr->opaque;
1975 s->max_size = qemu_chr_be_can_write(chr);
1976 return s->max_size;
1979 static void win_chr_readfile(CharDriverState *chr)
1981 WinCharState *s = chr->opaque;
1982 int ret, err;
1983 uint8_t buf[READ_BUF_LEN];
1984 DWORD size;
1986 ZeroMemory(&s->orecv, sizeof(s->orecv));
1987 s->orecv.hEvent = s->hrecv;
1988 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1989 if (!ret) {
1990 err = GetLastError();
1991 if (err == ERROR_IO_PENDING) {
1992 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1996 if (size > 0) {
1997 qemu_chr_be_write(chr, buf, size);
2001 static void win_chr_read(CharDriverState *chr)
2003 WinCharState *s = chr->opaque;
2005 if (s->len > s->max_size)
2006 s->len = s->max_size;
2007 if (s->len == 0)
2008 return;
2010 win_chr_readfile(chr);
2013 static int win_chr_poll(void *opaque)
2015 CharDriverState *chr = opaque;
2016 WinCharState *s = chr->opaque;
2017 COMSTAT status;
2018 DWORD comerr;
2020 ClearCommError(s->hcom, &comerr, &status);
2021 if (status.cbInQue > 0) {
2022 s->len = status.cbInQue;
2023 win_chr_read_poll(chr);
2024 win_chr_read(chr);
2025 return 1;
2027 return 0;
2030 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2031 ChardevCommon *backend,
2032 Error **errp)
2034 CharDriverState *chr;
2035 WinCharState *s;
2037 chr = qemu_chr_alloc(backend, errp);
2038 if (!chr) {
2039 return NULL;
2041 s = g_new0(WinCharState, 1);
2042 chr->opaque = s;
2043 chr->chr_write = win_chr_write;
2044 chr->chr_close = win_chr_close;
2046 if (win_chr_init(chr, filename, errp) < 0) {
2047 g_free(s);
2048 qemu_chr_free_common(chr);
2049 return NULL;
2051 return chr;
2054 static int win_chr_pipe_poll(void *opaque)
2056 CharDriverState *chr = opaque;
2057 WinCharState *s = chr->opaque;
2058 DWORD size;
2060 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2061 if (size > 0) {
2062 s->len = size;
2063 win_chr_read_poll(chr);
2064 win_chr_read(chr);
2065 return 1;
2067 return 0;
2070 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2071 Error **errp)
2073 WinCharState *s = chr->opaque;
2074 OVERLAPPED ov;
2075 int ret;
2076 DWORD size;
2077 char *openname;
2079 s->fpipe = TRUE;
2081 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2082 if (!s->hsend) {
2083 error_setg(errp, "Failed CreateEvent");
2084 goto fail;
2086 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2087 if (!s->hrecv) {
2088 error_setg(errp, "Failed CreateEvent");
2089 goto fail;
2092 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2093 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2094 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2095 PIPE_WAIT,
2096 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2097 g_free(openname);
2098 if (s->hcom == INVALID_HANDLE_VALUE) {
2099 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2100 s->hcom = NULL;
2101 goto fail;
2104 ZeroMemory(&ov, sizeof(ov));
2105 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2106 ret = ConnectNamedPipe(s->hcom, &ov);
2107 if (ret) {
2108 error_setg(errp, "Failed ConnectNamedPipe");
2109 goto fail;
2112 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2113 if (!ret) {
2114 error_setg(errp, "Failed GetOverlappedResult");
2115 if (ov.hEvent) {
2116 CloseHandle(ov.hEvent);
2117 ov.hEvent = NULL;
2119 goto fail;
2122 if (ov.hEvent) {
2123 CloseHandle(ov.hEvent);
2124 ov.hEvent = NULL;
2126 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2127 return 0;
2129 fail:
2130 win_chr_close(chr);
2131 return -1;
2135 static CharDriverState *qemu_chr_open_pipe(const char *id,
2136 ChardevBackend *backend,
2137 ChardevReturn *ret,
2138 Error **errp)
2140 ChardevHostdev *opts = backend->u.pipe;
2141 const char *filename = opts->device;
2142 CharDriverState *chr;
2143 WinCharState *s;
2144 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.pipe);
2146 chr = qemu_chr_alloc(common, errp);
2147 if (!chr) {
2148 return NULL;
2150 s = g_new0(WinCharState, 1);
2151 chr->opaque = s;
2152 chr->chr_write = win_chr_write;
2153 chr->chr_close = win_chr_close;
2155 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2156 g_free(s);
2157 qemu_chr_free_common(chr);
2158 return NULL;
2160 return chr;
2163 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2164 ChardevCommon *backend,
2165 Error **errp)
2167 CharDriverState *chr;
2168 WinCharState *s;
2170 chr = qemu_chr_alloc(backend, errp);
2171 if (!chr) {
2172 return NULL;
2174 s = g_new0(WinCharState, 1);
2175 s->hcom = fd_out;
2176 chr->opaque = s;
2177 chr->chr_write = win_chr_write;
2178 return chr;
2181 static CharDriverState *qemu_chr_open_win_con(const char *id,
2182 ChardevBackend *backend,
2183 ChardevReturn *ret,
2184 Error **errp)
2186 ChardevCommon *common = qapi_ChardevDummy_base(backend->u.console);
2187 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2188 common, errp);
2191 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2193 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2194 DWORD dwSize;
2195 int len1;
2197 len1 = len;
2199 while (len1 > 0) {
2200 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2201 break;
2203 buf += dwSize;
2204 len1 -= dwSize;
2207 return len - len1;
2210 static void win_stdio_wait_func(void *opaque)
2212 CharDriverState *chr = opaque;
2213 WinStdioCharState *stdio = chr->opaque;
2214 INPUT_RECORD buf[4];
2215 int ret;
2216 DWORD dwSize;
2217 int i;
2219 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2221 if (!ret) {
2222 /* Avoid error storm */
2223 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2224 return;
2227 for (i = 0; i < dwSize; i++) {
2228 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2230 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2231 int j;
2232 if (kev->uChar.AsciiChar != 0) {
2233 for (j = 0; j < kev->wRepeatCount; j++) {
2234 if (qemu_chr_be_can_write(chr)) {
2235 uint8_t c = kev->uChar.AsciiChar;
2236 qemu_chr_be_write(chr, &c, 1);
2244 static DWORD WINAPI win_stdio_thread(LPVOID param)
2246 CharDriverState *chr = param;
2247 WinStdioCharState *stdio = chr->opaque;
2248 int ret;
2249 DWORD dwSize;
2251 while (1) {
2253 /* Wait for one byte */
2254 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2256 /* Exit in case of error, continue if nothing read */
2257 if (!ret) {
2258 break;
2260 if (!dwSize) {
2261 continue;
2264 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2265 if (stdio->win_stdio_buf == '\r') {
2266 continue;
2269 /* Signal the main thread and wait until the byte was eaten */
2270 if (!SetEvent(stdio->hInputReadyEvent)) {
2271 break;
2273 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2274 != WAIT_OBJECT_0) {
2275 break;
2279 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2280 return 0;
2283 static void win_stdio_thread_wait_func(void *opaque)
2285 CharDriverState *chr = opaque;
2286 WinStdioCharState *stdio = chr->opaque;
2288 if (qemu_chr_be_can_write(chr)) {
2289 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2292 SetEvent(stdio->hInputDoneEvent);
2295 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2297 WinStdioCharState *stdio = chr->opaque;
2298 DWORD dwMode = 0;
2300 GetConsoleMode(stdio->hStdIn, &dwMode);
2302 if (echo) {
2303 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2304 } else {
2305 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2309 static void win_stdio_close(CharDriverState *chr)
2311 WinStdioCharState *stdio = chr->opaque;
2313 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2314 CloseHandle(stdio->hInputReadyEvent);
2316 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2317 CloseHandle(stdio->hInputDoneEvent);
2319 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2320 TerminateThread(stdio->hInputThread, 0);
2323 g_free(chr->opaque);
2324 g_free(chr);
2327 static CharDriverState *qemu_chr_open_stdio(const char *id,
2328 ChardevBackend *backend,
2329 ChardevReturn *ret,
2330 Error **errp)
2332 CharDriverState *chr;
2333 WinStdioCharState *stdio;
2334 DWORD dwMode;
2335 int is_console = 0;
2336 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio);
2338 chr = qemu_chr_alloc(common, errp);
2339 if (!chr) {
2340 return NULL;
2342 stdio = g_new0(WinStdioCharState, 1);
2344 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2345 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2346 error_setg(errp, "cannot open stdio: invalid handle");
2347 return NULL;
2350 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2352 chr->opaque = stdio;
2353 chr->chr_write = win_stdio_write;
2354 chr->chr_close = win_stdio_close;
2356 if (is_console) {
2357 if (qemu_add_wait_object(stdio->hStdIn,
2358 win_stdio_wait_func, chr)) {
2359 error_setg(errp, "qemu_add_wait_object: failed");
2360 goto err1;
2362 } else {
2363 DWORD dwId;
2365 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2366 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2367 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2368 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2369 error_setg(errp, "cannot create event");
2370 goto err2;
2372 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2373 win_stdio_thread_wait_func, chr)) {
2374 error_setg(errp, "qemu_add_wait_object: failed");
2375 goto err2;
2377 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2378 chr, 0, &dwId);
2380 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2381 error_setg(errp, "cannot create stdio thread");
2382 goto err3;
2386 dwMode |= ENABLE_LINE_INPUT;
2388 if (is_console) {
2389 /* set the terminal in raw mode */
2390 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2391 dwMode |= ENABLE_PROCESSED_INPUT;
2394 SetConsoleMode(stdio->hStdIn, dwMode);
2396 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2397 qemu_chr_fe_set_echo(chr, false);
2399 return chr;
2401 err3:
2402 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2403 err2:
2404 CloseHandle(stdio->hInputReadyEvent);
2405 CloseHandle(stdio->hInputDoneEvent);
2406 err1:
2407 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2408 return NULL;
2410 #endif /* !_WIN32 */
2413 /***********************************************************/
2414 /* UDP Net console */
2416 typedef struct {
2417 QIOChannel *ioc;
2418 uint8_t buf[READ_BUF_LEN];
2419 int bufcnt;
2420 int bufptr;
2421 int max_size;
2422 } NetCharDriver;
2424 /* Called with chr_write_lock held. */
2425 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2427 NetCharDriver *s = chr->opaque;
2429 return qio_channel_write(
2430 s->ioc, (const char *)buf, len, NULL);
2433 static int udp_chr_read_poll(void *opaque)
2435 CharDriverState *chr = opaque;
2436 NetCharDriver *s = chr->opaque;
2438 s->max_size = qemu_chr_be_can_write(chr);
2440 /* If there were any stray characters in the queue process them
2441 * first
2443 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2444 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2445 s->bufptr++;
2446 s->max_size = qemu_chr_be_can_write(chr);
2448 return s->max_size;
2451 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2453 CharDriverState *chr = opaque;
2454 NetCharDriver *s = chr->opaque;
2455 ssize_t ret;
2457 if (s->max_size == 0) {
2458 return TRUE;
2460 ret = qio_channel_read(
2461 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2462 if (ret <= 0) {
2463 remove_fd_in_watch(chr);
2464 return FALSE;
2466 s->bufcnt = ret;
2468 s->bufptr = 0;
2469 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2470 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2471 s->bufptr++;
2472 s->max_size = qemu_chr_be_can_write(chr);
2475 return TRUE;
2478 static void udp_chr_update_read_handler(CharDriverState *chr)
2480 NetCharDriver *s = chr->opaque;
2482 remove_fd_in_watch(chr);
2483 if (s->ioc) {
2484 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2485 udp_chr_read_poll,
2486 udp_chr_read, chr);
2490 static void udp_chr_close(CharDriverState *chr)
2492 NetCharDriver *s = chr->opaque;
2494 remove_fd_in_watch(chr);
2495 if (s->ioc) {
2496 object_unref(OBJECT(s->ioc));
2498 g_free(s);
2499 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2502 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2503 ChardevCommon *backend,
2504 Error **errp)
2506 CharDriverState *chr = NULL;
2507 NetCharDriver *s = NULL;
2509 chr = qemu_chr_alloc(backend, errp);
2510 if (!chr) {
2511 return NULL;
2513 s = g_new0(NetCharDriver, 1);
2515 s->ioc = QIO_CHANNEL(sioc);
2516 s->bufcnt = 0;
2517 s->bufptr = 0;
2518 chr->opaque = s;
2519 chr->chr_write = udp_chr_write;
2520 chr->chr_update_read_handler = udp_chr_update_read_handler;
2521 chr->chr_close = udp_chr_close;
2522 /* be isn't opened until we get a connection */
2523 chr->explicit_be_open = true;
2524 return chr;
2527 /***********************************************************/
2528 /* TCP Net console */
2530 typedef struct {
2531 QIOChannel *ioc; /* Client I/O channel */
2532 QIOChannelSocket *sioc; /* Client master channel */
2533 QIOChannelSocket *listen_ioc;
2534 guint listen_tag;
2535 QCryptoTLSCreds *tls_creds;
2536 int connected;
2537 int max_size;
2538 int do_telnetopt;
2539 int do_nodelay;
2540 int is_unix;
2541 int *read_msgfds;
2542 size_t read_msgfds_num;
2543 int *write_msgfds;
2544 size_t write_msgfds_num;
2546 SocketAddress *addr;
2547 bool is_listen;
2548 bool is_telnet;
2550 guint reconnect_timer;
2551 int64_t reconnect_time;
2552 bool connect_err_reported;
2553 } TCPCharDriver;
2555 static gboolean socket_reconnect_timeout(gpointer opaque);
2557 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2559 TCPCharDriver *s = chr->opaque;
2560 assert(s->connected == 0);
2561 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2562 socket_reconnect_timeout, chr);
2565 static void check_report_connect_error(CharDriverState *chr,
2566 Error *err)
2568 TCPCharDriver *s = chr->opaque;
2570 if (!s->connect_err_reported) {
2571 error_report("Unable to connect character device %s: %s",
2572 chr->label, error_get_pretty(err));
2573 s->connect_err_reported = true;
2575 qemu_chr_socket_restart_timer(chr);
2578 static gboolean tcp_chr_accept(QIOChannel *chan,
2579 GIOCondition cond,
2580 void *opaque);
2582 /* Called with chr_write_lock held. */
2583 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2585 TCPCharDriver *s = chr->opaque;
2586 if (s->connected) {
2587 int ret = io_channel_send_full(s->ioc, buf, len,
2588 s->write_msgfds,
2589 s->write_msgfds_num);
2591 /* free the written msgfds, no matter what */
2592 if (s->write_msgfds_num) {
2593 g_free(s->write_msgfds);
2594 s->write_msgfds = 0;
2595 s->write_msgfds_num = 0;
2598 return ret;
2599 } else {
2600 /* XXX: indicate an error ? */
2601 return len;
2605 static int tcp_chr_read_poll(void *opaque)
2607 CharDriverState *chr = opaque;
2608 TCPCharDriver *s = chr->opaque;
2609 if (!s->connected)
2610 return 0;
2611 s->max_size = qemu_chr_be_can_write(chr);
2612 return s->max_size;
2615 #define IAC 255
2616 #define IAC_BREAK 243
2617 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2618 TCPCharDriver *s,
2619 uint8_t *buf, int *size)
2621 /* Handle any telnet client's basic IAC options to satisfy char by
2622 * char mode with no echo. All IAC options will be removed from
2623 * the buf and the do_telnetopt variable will be used to track the
2624 * state of the width of the IAC information.
2626 * IAC commands come in sets of 3 bytes with the exception of the
2627 * "IAC BREAK" command and the double IAC.
2630 int i;
2631 int j = 0;
2633 for (i = 0; i < *size; i++) {
2634 if (s->do_telnetopt > 1) {
2635 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2636 /* Double IAC means send an IAC */
2637 if (j != i)
2638 buf[j] = buf[i];
2639 j++;
2640 s->do_telnetopt = 1;
2641 } else {
2642 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2643 /* Handle IAC break commands by sending a serial break */
2644 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2645 s->do_telnetopt++;
2647 s->do_telnetopt++;
2649 if (s->do_telnetopt >= 4) {
2650 s->do_telnetopt = 1;
2652 } else {
2653 if ((unsigned char)buf[i] == IAC) {
2654 s->do_telnetopt = 2;
2655 } else {
2656 if (j != i)
2657 buf[j] = buf[i];
2658 j++;
2662 *size = j;
2665 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2667 TCPCharDriver *s = chr->opaque;
2668 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2670 assert(num <= TCP_MAX_FDS);
2672 if (to_copy) {
2673 int i;
2675 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2677 /* Close unused fds */
2678 for (i = to_copy; i < s->read_msgfds_num; i++) {
2679 close(s->read_msgfds[i]);
2682 g_free(s->read_msgfds);
2683 s->read_msgfds = 0;
2684 s->read_msgfds_num = 0;
2687 return to_copy;
2690 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2692 TCPCharDriver *s = chr->opaque;
2694 if (!qio_channel_has_feature(s->ioc,
2695 QIO_CHANNEL_FEATURE_FD_PASS)) {
2696 return -1;
2698 /* clear old pending fd array */
2699 g_free(s->write_msgfds);
2701 if (num) {
2702 s->write_msgfds = g_new(int, num);
2703 memcpy(s->write_msgfds, fds, num * sizeof(int));
2706 s->write_msgfds_num = num;
2708 return 0;
2711 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2713 TCPCharDriver *s = chr->opaque;
2714 struct iovec iov = { .iov_base = buf, .iov_len = len };
2715 int ret;
2716 size_t i;
2717 int *msgfds = NULL;
2718 size_t msgfds_num = 0;
2720 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2721 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2722 &msgfds, &msgfds_num,
2723 NULL);
2724 } else {
2725 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2726 NULL, NULL,
2727 NULL);
2730 if (msgfds_num) {
2731 /* close and clean read_msgfds */
2732 for (i = 0; i < s->read_msgfds_num; i++) {
2733 close(s->read_msgfds[i]);
2736 if (s->read_msgfds_num) {
2737 g_free(s->read_msgfds);
2740 s->read_msgfds = msgfds;
2741 s->read_msgfds_num = msgfds_num;
2744 for (i = 0; i < s->read_msgfds_num; i++) {
2745 int fd = s->read_msgfds[i];
2746 if (fd < 0) {
2747 continue;
2750 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2751 qemu_set_block(fd);
2753 #ifndef MSG_CMSG_CLOEXEC
2754 qemu_set_cloexec(fd);
2755 #endif
2758 return ret;
2761 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2763 TCPCharDriver *s = chr->opaque;
2764 return qio_channel_create_watch(s->ioc, cond);
2767 static void tcp_chr_disconnect(CharDriverState *chr)
2769 TCPCharDriver *s = chr->opaque;
2771 s->connected = 0;
2772 if (s->listen_ioc) {
2773 s->listen_tag = qio_channel_add_watch(
2774 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
2776 remove_fd_in_watch(chr);
2777 object_unref(OBJECT(s->sioc));
2778 s->sioc = NULL;
2779 object_unref(OBJECT(s->ioc));
2780 s->ioc = NULL;
2781 g_free(chr->filename);
2782 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
2783 s->is_listen, s->is_telnet);
2784 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2785 if (s->reconnect_time) {
2786 qemu_chr_socket_restart_timer(chr);
2790 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2792 CharDriverState *chr = opaque;
2793 TCPCharDriver *s = chr->opaque;
2794 uint8_t buf[READ_BUF_LEN];
2795 int len, size;
2797 if (!s->connected || s->max_size <= 0) {
2798 return TRUE;
2800 len = sizeof(buf);
2801 if (len > s->max_size)
2802 len = s->max_size;
2803 size = tcp_chr_recv(chr, (void *)buf, len);
2804 if (size == 0 || size == -1) {
2805 /* connection closed */
2806 tcp_chr_disconnect(chr);
2807 } else if (size > 0) {
2808 if (s->do_telnetopt)
2809 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2810 if (size > 0)
2811 qemu_chr_be_write(chr, buf, size);
2814 return TRUE;
2817 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2819 TCPCharDriver *s = chr->opaque;
2820 int size;
2822 if (!s->connected) {
2823 return 0;
2826 size = tcp_chr_recv(chr, (void *) buf, len);
2827 if (size == 0) {
2828 /* connection closed */
2829 tcp_chr_disconnect(chr);
2832 return size;
2835 static void tcp_chr_connect(void *opaque)
2837 CharDriverState *chr = opaque;
2838 TCPCharDriver *s = chr->opaque;
2840 g_free(chr->filename);
2841 chr->filename = sockaddr_to_str(
2842 &s->sioc->localAddr, s->sioc->localAddrLen,
2843 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
2844 s->is_listen, s->is_telnet);
2846 s->connected = 1;
2847 if (s->ioc) {
2848 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2849 tcp_chr_read_poll,
2850 tcp_chr_read, chr);
2852 qemu_chr_be_generic_open(chr);
2855 static void tcp_chr_update_read_handler(CharDriverState *chr)
2857 TCPCharDriver *s = chr->opaque;
2859 if (!s->connected) {
2860 return;
2863 remove_fd_in_watch(chr);
2864 if (s->ioc) {
2865 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2866 tcp_chr_read_poll,
2867 tcp_chr_read, chr);
2871 typedef struct {
2872 CharDriverState *chr;
2873 char buf[12];
2874 size_t buflen;
2875 } TCPCharDriverTelnetInit;
2877 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
2878 GIOCondition cond G_GNUC_UNUSED,
2879 gpointer user_data)
2881 TCPCharDriverTelnetInit *init = user_data;
2882 ssize_t ret;
2884 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
2885 if (ret < 0) {
2886 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2887 ret = 0;
2888 } else {
2889 tcp_chr_disconnect(init->chr);
2890 return FALSE;
2893 init->buflen -= ret;
2895 if (init->buflen == 0) {
2896 tcp_chr_connect(init->chr);
2897 return FALSE;
2900 memmove(init->buf, init->buf + ret, init->buflen);
2902 return TRUE;
2905 static void tcp_chr_telnet_init(CharDriverState *chr)
2907 TCPCharDriver *s = chr->opaque;
2908 TCPCharDriverTelnetInit *init =
2909 g_new0(TCPCharDriverTelnetInit, 1);
2910 size_t n = 0;
2912 init->chr = chr;
2913 init->buflen = 12;
2915 #define IACSET(x, a, b, c) \
2916 do { \
2917 x[n++] = a; \
2918 x[n++] = b; \
2919 x[n++] = c; \
2920 } while (0)
2922 /* Prep the telnet negotion to put telnet in binary,
2923 * no echo, single char mode */
2924 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2925 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2926 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2927 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2929 #undef IACSET
2931 qio_channel_add_watch(
2932 s->ioc, G_IO_OUT,
2933 tcp_chr_telnet_init_io,
2934 init, NULL);
2938 static void tcp_chr_tls_handshake(Object *source,
2939 Error *err,
2940 gpointer user_data)
2942 CharDriverState *chr = user_data;
2943 TCPCharDriver *s = chr->opaque;
2945 if (err) {
2946 tcp_chr_disconnect(chr);
2947 } else {
2948 if (s->do_telnetopt) {
2949 tcp_chr_telnet_init(chr);
2950 } else {
2951 tcp_chr_connect(chr);
2957 static void tcp_chr_tls_init(CharDriverState *chr)
2959 TCPCharDriver *s = chr->opaque;
2960 QIOChannelTLS *tioc;
2961 Error *err = NULL;
2963 if (s->is_listen) {
2964 tioc = qio_channel_tls_new_server(
2965 s->ioc, s->tls_creds,
2966 NULL, /* XXX Use an ACL */
2967 &err);
2968 } else {
2969 tioc = qio_channel_tls_new_client(
2970 s->ioc, s->tls_creds,
2971 s->addr->u.inet->host,
2972 &err);
2974 if (tioc == NULL) {
2975 error_free(err);
2976 tcp_chr_disconnect(chr);
2978 object_unref(OBJECT(s->ioc));
2979 s->ioc = QIO_CHANNEL(tioc);
2981 qio_channel_tls_handshake(tioc,
2982 tcp_chr_tls_handshake,
2983 chr,
2984 NULL);
2988 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
2990 TCPCharDriver *s = chr->opaque;
2991 if (s->ioc != NULL) {
2992 return -1;
2995 s->ioc = QIO_CHANNEL(sioc);
2996 object_ref(OBJECT(sioc));
2997 s->sioc = sioc;
2998 object_ref(OBJECT(sioc));
3000 if (s->do_nodelay) {
3001 qio_channel_set_delay(s->ioc, false);
3003 if (s->listen_tag) {
3004 g_source_remove(s->listen_tag);
3005 s->listen_tag = 0;
3008 if (s->tls_creds) {
3009 tcp_chr_tls_init(chr);
3010 } else {
3011 if (s->do_telnetopt) {
3012 tcp_chr_telnet_init(chr);
3013 } else {
3014 tcp_chr_connect(chr);
3018 return 0;
3022 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3024 int ret;
3025 QIOChannelSocket *sioc;
3027 sioc = qio_channel_socket_new_fd(fd, NULL);
3028 if (!sioc) {
3029 return -1;
3031 qio_channel_set_blocking(QIO_CHANNEL(sioc), false, NULL);
3032 ret = tcp_chr_new_client(chr, sioc);
3033 object_unref(OBJECT(sioc));
3034 return ret;
3037 static gboolean tcp_chr_accept(QIOChannel *channel,
3038 GIOCondition cond,
3039 void *opaque)
3041 CharDriverState *chr = opaque;
3042 QIOChannelSocket *sioc;
3044 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3045 NULL);
3046 if (!sioc) {
3047 return TRUE;
3050 tcp_chr_new_client(chr, sioc);
3052 object_unref(OBJECT(sioc));
3054 return TRUE;
3057 static void tcp_chr_close(CharDriverState *chr)
3059 TCPCharDriver *s = chr->opaque;
3060 int i;
3062 if (s->reconnect_timer) {
3063 g_source_remove(s->reconnect_timer);
3064 s->reconnect_timer = 0;
3066 qapi_free_SocketAddress(s->addr);
3067 remove_fd_in_watch(chr);
3068 if (s->ioc) {
3069 object_unref(OBJECT(s->ioc));
3071 if (s->listen_tag) {
3072 g_source_remove(s->listen_tag);
3073 s->listen_tag = 0;
3075 if (s->listen_ioc) {
3076 object_unref(OBJECT(s->listen_ioc));
3078 if (s->read_msgfds_num) {
3079 for (i = 0; i < s->read_msgfds_num; i++) {
3080 close(s->read_msgfds[i]);
3082 g_free(s->read_msgfds);
3084 if (s->tls_creds) {
3085 object_unref(OBJECT(s->tls_creds));
3087 if (s->write_msgfds_num) {
3088 g_free(s->write_msgfds);
3090 g_free(s);
3091 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3094 static void qemu_chr_finish_socket_connection(CharDriverState *chr,
3095 QIOChannelSocket *sioc)
3097 TCPCharDriver *s = chr->opaque;
3099 if (s->is_listen) {
3100 s->listen_ioc = sioc;
3101 s->listen_tag = qio_channel_add_watch(
3102 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
3103 } else {
3104 tcp_chr_new_client(chr, sioc);
3105 object_unref(OBJECT(sioc));
3109 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3111 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3112 CharDriverState *chr = opaque;
3113 TCPCharDriver *s = chr->opaque;
3115 if (err) {
3116 check_report_connect_error(chr, err);
3117 object_unref(src);
3118 return;
3121 s->connect_err_reported = false;
3122 qemu_chr_finish_socket_connection(chr, sioc);
3125 static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp)
3127 TCPCharDriver *s = chr->opaque;
3128 QIOChannelSocket *sioc = qio_channel_socket_new();
3130 if (s->is_listen) {
3131 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
3132 goto fail;
3134 qemu_chr_finish_socket_connection(chr, sioc);
3135 } else if (s->reconnect_time) {
3136 qio_channel_socket_connect_async(sioc, s->addr,
3137 qemu_chr_socket_connected,
3138 chr, NULL);
3139 } else {
3140 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3141 goto fail;
3143 qemu_chr_finish_socket_connection(chr, sioc);
3146 return true;
3148 fail:
3149 object_unref(OBJECT(sioc));
3150 return false;
3153 /*********************************************************/
3154 /* Ring buffer chardev */
3156 typedef struct {
3157 size_t size;
3158 size_t prod;
3159 size_t cons;
3160 uint8_t *cbuf;
3161 } RingBufCharDriver;
3163 static size_t ringbuf_count(const CharDriverState *chr)
3165 const RingBufCharDriver *d = chr->opaque;
3167 return d->prod - d->cons;
3170 /* Called with chr_write_lock held. */
3171 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3173 RingBufCharDriver *d = chr->opaque;
3174 int i;
3176 if (!buf || (len < 0)) {
3177 return -1;
3180 for (i = 0; i < len; i++ ) {
3181 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3182 if (d->prod - d->cons > d->size) {
3183 d->cons = d->prod - d->size;
3187 return 0;
3190 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3192 RingBufCharDriver *d = chr->opaque;
3193 int i;
3195 qemu_mutex_lock(&chr->chr_write_lock);
3196 for (i = 0; i < len && d->cons != d->prod; i++) {
3197 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3199 qemu_mutex_unlock(&chr->chr_write_lock);
3201 return i;
3204 static void ringbuf_chr_close(struct CharDriverState *chr)
3206 RingBufCharDriver *d = chr->opaque;
3208 g_free(d->cbuf);
3209 g_free(d);
3210 chr->opaque = NULL;
3213 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3214 ChardevBackend *backend,
3215 ChardevReturn *ret,
3216 Error **errp)
3218 ChardevRingbuf *opts = backend->u.ringbuf;
3219 ChardevCommon *common = qapi_ChardevRingbuf_base(backend->u.ringbuf);
3220 CharDriverState *chr;
3221 RingBufCharDriver *d;
3223 chr = qemu_chr_alloc(common, errp);
3224 if (!chr) {
3225 return NULL;
3227 d = g_malloc(sizeof(*d));
3229 d->size = opts->has_size ? opts->size : 65536;
3231 /* The size must be power of 2 */
3232 if (d->size & (d->size - 1)) {
3233 error_setg(errp, "size of ringbuf chardev must be power of two");
3234 goto fail;
3237 d->prod = 0;
3238 d->cons = 0;
3239 d->cbuf = g_malloc0(d->size);
3241 chr->opaque = d;
3242 chr->chr_write = ringbuf_chr_write;
3243 chr->chr_close = ringbuf_chr_close;
3245 return chr;
3247 fail:
3248 g_free(d);
3249 qemu_chr_free_common(chr);
3250 return NULL;
3253 bool chr_is_ringbuf(const CharDriverState *chr)
3255 return chr->chr_write == ringbuf_chr_write;
3258 void qmp_ringbuf_write(const char *device, const char *data,
3259 bool has_format, enum DataFormat format,
3260 Error **errp)
3262 CharDriverState *chr;
3263 const uint8_t *write_data;
3264 int ret;
3265 gsize write_count;
3267 chr = qemu_chr_find(device);
3268 if (!chr) {
3269 error_setg(errp, "Device '%s' not found", device);
3270 return;
3273 if (!chr_is_ringbuf(chr)) {
3274 error_setg(errp,"%s is not a ringbuf device", device);
3275 return;
3278 if (has_format && (format == DATA_FORMAT_BASE64)) {
3279 write_data = qbase64_decode(data, -1,
3280 &write_count,
3281 errp);
3282 if (!write_data) {
3283 return;
3285 } else {
3286 write_data = (uint8_t *)data;
3287 write_count = strlen(data);
3290 ret = ringbuf_chr_write(chr, write_data, write_count);
3292 if (write_data != (uint8_t *)data) {
3293 g_free((void *)write_data);
3296 if (ret < 0) {
3297 error_setg(errp, "Failed to write to device %s", device);
3298 return;
3302 char *qmp_ringbuf_read(const char *device, int64_t size,
3303 bool has_format, enum DataFormat format,
3304 Error **errp)
3306 CharDriverState *chr;
3307 uint8_t *read_data;
3308 size_t count;
3309 char *data;
3311 chr = qemu_chr_find(device);
3312 if (!chr) {
3313 error_setg(errp, "Device '%s' not found", device);
3314 return NULL;
3317 if (!chr_is_ringbuf(chr)) {
3318 error_setg(errp,"%s is not a ringbuf device", device);
3319 return NULL;
3322 if (size <= 0) {
3323 error_setg(errp, "size must be greater than zero");
3324 return NULL;
3327 count = ringbuf_count(chr);
3328 size = size > count ? count : size;
3329 read_data = g_malloc(size + 1);
3331 ringbuf_chr_read(chr, read_data, size);
3333 if (has_format && (format == DATA_FORMAT_BASE64)) {
3334 data = g_base64_encode(read_data, size);
3335 g_free(read_data);
3336 } else {
3338 * FIXME should read only complete, valid UTF-8 characters up
3339 * to @size bytes. Invalid sequences should be replaced by a
3340 * suitable replacement character. Except when (and only
3341 * when) ring buffer lost characters since last read, initial
3342 * continuation characters should be dropped.
3344 read_data[size] = 0;
3345 data = (char *)read_data;
3348 return data;
3351 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3353 char host[65], port[33], width[8], height[8];
3354 int pos;
3355 const char *p;
3356 QemuOpts *opts;
3357 Error *local_err = NULL;
3359 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3360 if (local_err) {
3361 error_report_err(local_err);
3362 return NULL;
3365 if (strstart(filename, "mon:", &p)) {
3366 filename = p;
3367 qemu_opt_set(opts, "mux", "on", &error_abort);
3368 if (strcmp(filename, "stdio") == 0) {
3369 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3370 * but pass it to the guest. Handle this only for compat syntax,
3371 * for -chardev syntax we have special option for this.
3372 * This is what -nographic did, redirecting+muxing serial+monitor
3373 * to stdio causing Ctrl+C to be passed to guest. */
3374 qemu_opt_set(opts, "signal", "off", &error_abort);
3378 if (strcmp(filename, "null") == 0 ||
3379 strcmp(filename, "pty") == 0 ||
3380 strcmp(filename, "msmouse") == 0 ||
3381 strcmp(filename, "braille") == 0 ||
3382 strcmp(filename, "testdev") == 0 ||
3383 strcmp(filename, "stdio") == 0) {
3384 qemu_opt_set(opts, "backend", filename, &error_abort);
3385 return opts;
3387 if (strstart(filename, "vc", &p)) {
3388 qemu_opt_set(opts, "backend", "vc", &error_abort);
3389 if (*p == ':') {
3390 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3391 /* pixels */
3392 qemu_opt_set(opts, "width", width, &error_abort);
3393 qemu_opt_set(opts, "height", height, &error_abort);
3394 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3395 /* chars */
3396 qemu_opt_set(opts, "cols", width, &error_abort);
3397 qemu_opt_set(opts, "rows", height, &error_abort);
3398 } else {
3399 goto fail;
3402 return opts;
3404 if (strcmp(filename, "con:") == 0) {
3405 qemu_opt_set(opts, "backend", "console", &error_abort);
3406 return opts;
3408 if (strstart(filename, "COM", NULL)) {
3409 qemu_opt_set(opts, "backend", "serial", &error_abort);
3410 qemu_opt_set(opts, "path", filename, &error_abort);
3411 return opts;
3413 if (strstart(filename, "file:", &p)) {
3414 qemu_opt_set(opts, "backend", "file", &error_abort);
3415 qemu_opt_set(opts, "path", p, &error_abort);
3416 return opts;
3418 if (strstart(filename, "pipe:", &p)) {
3419 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3420 qemu_opt_set(opts, "path", p, &error_abort);
3421 return opts;
3423 if (strstart(filename, "tcp:", &p) ||
3424 strstart(filename, "telnet:", &p)) {
3425 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3426 host[0] = 0;
3427 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3428 goto fail;
3430 qemu_opt_set(opts, "backend", "socket", &error_abort);
3431 qemu_opt_set(opts, "host", host, &error_abort);
3432 qemu_opt_set(opts, "port", port, &error_abort);
3433 if (p[pos] == ',') {
3434 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3435 if (local_err) {
3436 error_report_err(local_err);
3437 goto fail;
3440 if (strstart(filename, "telnet:", &p))
3441 qemu_opt_set(opts, "telnet", "on", &error_abort);
3442 return opts;
3444 if (strstart(filename, "udp:", &p)) {
3445 qemu_opt_set(opts, "backend", "udp", &error_abort);
3446 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3447 host[0] = 0;
3448 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3449 goto fail;
3452 qemu_opt_set(opts, "host", host, &error_abort);
3453 qemu_opt_set(opts, "port", port, &error_abort);
3454 if (p[pos] == '@') {
3455 p += pos + 1;
3456 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3457 host[0] = 0;
3458 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3459 goto fail;
3462 qemu_opt_set(opts, "localaddr", host, &error_abort);
3463 qemu_opt_set(opts, "localport", port, &error_abort);
3465 return opts;
3467 if (strstart(filename, "unix:", &p)) {
3468 qemu_opt_set(opts, "backend", "socket", &error_abort);
3469 qemu_opts_do_parse(opts, p, "path", &local_err);
3470 if (local_err) {
3471 error_report_err(local_err);
3472 goto fail;
3474 return opts;
3476 if (strstart(filename, "/dev/parport", NULL) ||
3477 strstart(filename, "/dev/ppi", NULL)) {
3478 qemu_opt_set(opts, "backend", "parport", &error_abort);
3479 qemu_opt_set(opts, "path", filename, &error_abort);
3480 return opts;
3482 if (strstart(filename, "/dev/", NULL)) {
3483 qemu_opt_set(opts, "backend", "tty", &error_abort);
3484 qemu_opt_set(opts, "path", filename, &error_abort);
3485 return opts;
3488 fail:
3489 qemu_opts_del(opts);
3490 return NULL;
3493 static void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3495 const char *logfile = qemu_opt_get(opts, "logfile");
3497 backend->has_logfile = logfile != NULL;
3498 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3500 backend->has_logappend = true;
3501 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3505 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3506 Error **errp)
3508 const char *path = qemu_opt_get(opts, "path");
3510 if (path == NULL) {
3511 error_setg(errp, "chardev: file: no filename given");
3512 return;
3514 backend->u.file = g_new0(ChardevFile, 1);
3515 qemu_chr_parse_common(opts, qapi_ChardevFile_base(backend->u.file));
3516 backend->u.file->out = g_strdup(path);
3518 backend->u.file->has_append = true;
3519 backend->u.file->append = qemu_opt_get_bool(opts, "append", false);
3522 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3523 Error **errp)
3525 backend->u.stdio = g_new0(ChardevStdio, 1);
3526 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(backend->u.stdio));
3527 backend->u.stdio->has_signal = true;
3528 backend->u.stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3531 #ifdef HAVE_CHARDEV_SERIAL
3532 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3533 Error **errp)
3535 const char *device = qemu_opt_get(opts, "path");
3537 if (device == NULL) {
3538 error_setg(errp, "chardev: serial/tty: no device path given");
3539 return;
3541 backend->u.serial = g_new0(ChardevHostdev, 1);
3542 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.serial));
3543 backend->u.serial->device = g_strdup(device);
3545 #endif
3547 #ifdef HAVE_CHARDEV_PARPORT
3548 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3549 Error **errp)
3551 const char *device = qemu_opt_get(opts, "path");
3553 if (device == NULL) {
3554 error_setg(errp, "chardev: parallel: no device path given");
3555 return;
3557 backend->u.parallel = g_new0(ChardevHostdev, 1);
3558 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.parallel));
3559 backend->u.parallel->device = g_strdup(device);
3561 #endif
3563 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3564 Error **errp)
3566 const char *device = qemu_opt_get(opts, "path");
3568 if (device == NULL) {
3569 error_setg(errp, "chardev: pipe: no device path given");
3570 return;
3572 backend->u.pipe = g_new0(ChardevHostdev, 1);
3573 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.pipe));
3574 backend->u.pipe->device = g_strdup(device);
3577 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3578 Error **errp)
3580 int val;
3582 backend->u.ringbuf = g_new0(ChardevRingbuf, 1);
3583 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(backend->u.ringbuf));
3585 val = qemu_opt_get_size(opts, "size", 0);
3586 if (val != 0) {
3587 backend->u.ringbuf->has_size = true;
3588 backend->u.ringbuf->size = val;
3592 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3593 Error **errp)
3595 const char *chardev = qemu_opt_get(opts, "chardev");
3597 if (chardev == NULL) {
3598 error_setg(errp, "chardev: mux: no chardev given");
3599 return;
3601 backend->u.mux = g_new0(ChardevMux, 1);
3602 qemu_chr_parse_common(opts, qapi_ChardevMux_base(backend->u.mux));
3603 backend->u.mux->chardev = g_strdup(chardev);
3606 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3607 Error **errp)
3609 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3610 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3611 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3612 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3613 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3614 const char *path = qemu_opt_get(opts, "path");
3615 const char *host = qemu_opt_get(opts, "host");
3616 const char *port = qemu_opt_get(opts, "port");
3617 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3618 SocketAddress *addr;
3620 if (!path) {
3621 if (!host) {
3622 error_setg(errp, "chardev: socket: no host given");
3623 return;
3625 if (!port) {
3626 error_setg(errp, "chardev: socket: no port given");
3627 return;
3629 } else {
3630 if (tls_creds) {
3631 error_setg(errp, "TLS can only be used over TCP socket");
3632 return;
3636 backend->u.socket = g_new0(ChardevSocket, 1);
3637 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(backend->u.socket));
3639 backend->u.socket->has_nodelay = true;
3640 backend->u.socket->nodelay = do_nodelay;
3641 backend->u.socket->has_server = true;
3642 backend->u.socket->server = is_listen;
3643 backend->u.socket->has_telnet = true;
3644 backend->u.socket->telnet = is_telnet;
3645 backend->u.socket->has_wait = true;
3646 backend->u.socket->wait = is_waitconnect;
3647 backend->u.socket->has_reconnect = true;
3648 backend->u.socket->reconnect = reconnect;
3649 backend->u.socket->tls_creds = g_strdup(tls_creds);
3651 addr = g_new0(SocketAddress, 1);
3652 if (path) {
3653 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3654 addr->u.q_unix = g_new0(UnixSocketAddress, 1);
3655 addr->u.q_unix->path = g_strdup(path);
3656 } else {
3657 addr->type = SOCKET_ADDRESS_KIND_INET;
3658 addr->u.inet = g_new0(InetSocketAddress, 1);
3659 addr->u.inet->host = g_strdup(host);
3660 addr->u.inet->port = g_strdup(port);
3661 addr->u.inet->has_to = qemu_opt_get(opts, "to");
3662 addr->u.inet->to = qemu_opt_get_number(opts, "to", 0);
3663 addr->u.inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3664 addr->u.inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3665 addr->u.inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3666 addr->u.inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3668 backend->u.socket->addr = addr;
3671 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3672 Error **errp)
3674 const char *host = qemu_opt_get(opts, "host");
3675 const char *port = qemu_opt_get(opts, "port");
3676 const char *localaddr = qemu_opt_get(opts, "localaddr");
3677 const char *localport = qemu_opt_get(opts, "localport");
3678 bool has_local = false;
3679 SocketAddress *addr;
3681 if (host == NULL || strlen(host) == 0) {
3682 host = "localhost";
3684 if (port == NULL || strlen(port) == 0) {
3685 error_setg(errp, "chardev: udp: remote port not specified");
3686 return;
3688 if (localport == NULL || strlen(localport) == 0) {
3689 localport = "0";
3690 } else {
3691 has_local = true;
3693 if (localaddr == NULL || strlen(localaddr) == 0) {
3694 localaddr = "";
3695 } else {
3696 has_local = true;
3699 backend->u.udp = g_new0(ChardevUdp, 1);
3700 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(backend->u.udp));
3702 addr = g_new0(SocketAddress, 1);
3703 addr->type = SOCKET_ADDRESS_KIND_INET;
3704 addr->u.inet = g_new0(InetSocketAddress, 1);
3705 addr->u.inet->host = g_strdup(host);
3706 addr->u.inet->port = g_strdup(port);
3707 addr->u.inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3708 addr->u.inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3709 addr->u.inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3710 addr->u.inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3711 backend->u.udp->remote = addr;
3713 if (has_local) {
3714 backend->u.udp->has_local = true;
3715 addr = g_new0(SocketAddress, 1);
3716 addr->type = SOCKET_ADDRESS_KIND_INET;
3717 addr->u.inet = g_new0(InetSocketAddress, 1);
3718 addr->u.inet->host = g_strdup(localaddr);
3719 addr->u.inet->port = g_strdup(localport);
3720 backend->u.udp->local = addr;
3724 typedef struct CharDriver {
3725 const char *name;
3726 ChardevBackendKind kind;
3727 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3728 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3729 ChardevReturn *ret, Error **errp);
3730 } CharDriver;
3732 static GSList *backends;
3734 void register_char_driver(const char *name, ChardevBackendKind kind,
3735 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3736 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3737 ChardevReturn *ret, Error **errp))
3739 CharDriver *s;
3741 s = g_malloc0(sizeof(*s));
3742 s->name = g_strdup(name);
3743 s->kind = kind;
3744 s->parse = parse;
3745 s->create = create;
3747 backends = g_slist_append(backends, s);
3750 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3751 void (*init)(struct CharDriverState *s),
3752 Error **errp)
3754 Error *local_err = NULL;
3755 CharDriver *cd;
3756 CharDriverState *chr;
3757 GSList *i;
3758 ChardevReturn *ret = NULL;
3759 ChardevBackend *backend;
3760 const char *id = qemu_opts_id(opts);
3761 char *bid = NULL;
3763 if (id == NULL) {
3764 error_setg(errp, "chardev: no id specified");
3765 goto err;
3768 if (qemu_opt_get(opts, "backend") == NULL) {
3769 error_setg(errp, "chardev: \"%s\" missing backend",
3770 qemu_opts_id(opts));
3771 goto err;
3773 for (i = backends; i; i = i->next) {
3774 cd = i->data;
3776 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3777 break;
3780 if (i == NULL) {
3781 error_setg(errp, "chardev: backend \"%s\" not found",
3782 qemu_opt_get(opts, "backend"));
3783 goto err;
3786 backend = g_new0(ChardevBackend, 1);
3788 if (qemu_opt_get_bool(opts, "mux", 0)) {
3789 bid = g_strdup_printf("%s-base", id);
3792 chr = NULL;
3793 backend->type = cd->kind;
3794 if (cd->parse) {
3795 cd->parse(opts, backend, &local_err);
3796 if (local_err) {
3797 error_propagate(errp, local_err);
3798 goto qapi_out;
3800 } else {
3801 ChardevCommon *cc = g_new0(ChardevCommon, 1);
3802 qemu_chr_parse_common(opts, cc);
3803 backend->u.data = cc;
3806 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3807 if (!ret) {
3808 goto qapi_out;
3811 if (bid) {
3812 qapi_free_ChardevBackend(backend);
3813 qapi_free_ChardevReturn(ret);
3814 backend = g_new0(ChardevBackend, 1);
3815 backend->u.mux = g_new0(ChardevMux, 1);
3816 backend->type = CHARDEV_BACKEND_KIND_MUX;
3817 backend->u.mux->chardev = g_strdup(bid);
3818 ret = qmp_chardev_add(id, backend, errp);
3819 if (!ret) {
3820 chr = qemu_chr_find(bid);
3821 qemu_chr_delete(chr);
3822 chr = NULL;
3823 goto qapi_out;
3827 chr = qemu_chr_find(id);
3828 chr->opts = opts;
3830 qapi_out:
3831 qapi_free_ChardevBackend(backend);
3832 qapi_free_ChardevReturn(ret);
3833 g_free(bid);
3834 return chr;
3836 err:
3837 qemu_opts_del(opts);
3838 return NULL;
3841 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3843 const char *p;
3844 CharDriverState *chr;
3845 QemuOpts *opts;
3846 Error *err = NULL;
3848 if (strstart(filename, "chardev:", &p)) {
3849 return qemu_chr_find(p);
3852 opts = qemu_chr_parse_compat(label, filename);
3853 if (!opts)
3854 return NULL;
3856 chr = qemu_chr_new_from_opts(opts, init, &err);
3857 if (err) {
3858 error_report_err(err);
3860 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3861 qemu_chr_fe_claim_no_fail(chr);
3862 monitor_init(chr, MONITOR_USE_READLINE);
3864 return chr;
3867 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3869 if (chr->chr_set_echo) {
3870 chr->chr_set_echo(chr, echo);
3874 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3876 if (chr->fe_open == fe_open) {
3877 return;
3879 chr->fe_open = fe_open;
3880 if (chr->chr_set_fe_open) {
3881 chr->chr_set_fe_open(chr, fe_open);
3885 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3887 if (chr->chr_fe_event) {
3888 chr->chr_fe_event(chr, event);
3892 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3893 GIOFunc func, void *user_data)
3895 GSource *src;
3896 guint tag;
3898 if (s->chr_add_watch == NULL) {
3899 return -ENOSYS;
3902 src = s->chr_add_watch(s, cond);
3903 if (!src) {
3904 return -EINVAL;
3907 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3908 tag = g_source_attach(src, NULL);
3909 g_source_unref(src);
3911 return tag;
3914 int qemu_chr_fe_claim(CharDriverState *s)
3916 if (s->avail_connections < 1) {
3917 return -1;
3919 s->avail_connections--;
3920 return 0;
3923 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3925 if (qemu_chr_fe_claim(s) != 0) {
3926 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3927 __func__, s->label);
3928 exit(1);
3932 void qemu_chr_fe_release(CharDriverState *s)
3934 s->avail_connections++;
3937 static void qemu_chr_free_common(CharDriverState *chr)
3939 g_free(chr->filename);
3940 g_free(chr->label);
3941 qemu_opts_del(chr->opts);
3942 if (chr->logfd != -1) {
3943 close(chr->logfd);
3945 qemu_mutex_destroy(&chr->chr_write_lock);
3946 g_free(chr);
3949 void qemu_chr_free(CharDriverState *chr)
3951 if (chr->chr_close) {
3952 chr->chr_close(chr);
3954 qemu_chr_free_common(chr);
3957 void qemu_chr_delete(CharDriverState *chr)
3959 QTAILQ_REMOVE(&chardevs, chr, next);
3960 qemu_chr_free(chr);
3963 ChardevInfoList *qmp_query_chardev(Error **errp)
3965 ChardevInfoList *chr_list = NULL;
3966 CharDriverState *chr;
3968 QTAILQ_FOREACH(chr, &chardevs, next) {
3969 ChardevInfoList *info = g_malloc0(sizeof(*info));
3970 info->value = g_malloc0(sizeof(*info->value));
3971 info->value->label = g_strdup(chr->label);
3972 info->value->filename = g_strdup(chr->filename);
3973 info->value->frontend_open = chr->fe_open;
3975 info->next = chr_list;
3976 chr_list = info;
3979 return chr_list;
3982 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
3984 ChardevBackendInfoList *backend_list = NULL;
3985 CharDriver *c = NULL;
3986 GSList *i = NULL;
3988 for (i = backends; i; i = i->next) {
3989 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
3990 c = i->data;
3991 info->value = g_malloc0(sizeof(*info->value));
3992 info->value->name = g_strdup(c->name);
3994 info->next = backend_list;
3995 backend_list = info;
3998 return backend_list;
4001 CharDriverState *qemu_chr_find(const char *name)
4003 CharDriverState *chr;
4005 QTAILQ_FOREACH(chr, &chardevs, next) {
4006 if (strcmp(chr->label, name) != 0)
4007 continue;
4008 return chr;
4010 return NULL;
4013 /* Get a character (serial) device interface. */
4014 CharDriverState *qemu_char_get_next_serial(void)
4016 static int next_serial;
4017 CharDriverState *chr;
4019 /* FIXME: This function needs to go away: use chardev properties! */
4021 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
4022 chr = serial_hds[next_serial++];
4023 qemu_chr_fe_claim_no_fail(chr);
4024 return chr;
4026 return NULL;
4029 QemuOptsList qemu_chardev_opts = {
4030 .name = "chardev",
4031 .implied_opt_name = "backend",
4032 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4033 .desc = {
4035 .name = "backend",
4036 .type = QEMU_OPT_STRING,
4038 .name = "path",
4039 .type = QEMU_OPT_STRING,
4041 .name = "host",
4042 .type = QEMU_OPT_STRING,
4044 .name = "port",
4045 .type = QEMU_OPT_STRING,
4047 .name = "localaddr",
4048 .type = QEMU_OPT_STRING,
4050 .name = "localport",
4051 .type = QEMU_OPT_STRING,
4053 .name = "to",
4054 .type = QEMU_OPT_NUMBER,
4056 .name = "ipv4",
4057 .type = QEMU_OPT_BOOL,
4059 .name = "ipv6",
4060 .type = QEMU_OPT_BOOL,
4062 .name = "wait",
4063 .type = QEMU_OPT_BOOL,
4065 .name = "server",
4066 .type = QEMU_OPT_BOOL,
4068 .name = "delay",
4069 .type = QEMU_OPT_BOOL,
4071 .name = "reconnect",
4072 .type = QEMU_OPT_NUMBER,
4074 .name = "telnet",
4075 .type = QEMU_OPT_BOOL,
4077 .name = "tls-creds",
4078 .type = QEMU_OPT_STRING,
4080 .name = "width",
4081 .type = QEMU_OPT_NUMBER,
4083 .name = "height",
4084 .type = QEMU_OPT_NUMBER,
4086 .name = "cols",
4087 .type = QEMU_OPT_NUMBER,
4089 .name = "rows",
4090 .type = QEMU_OPT_NUMBER,
4092 .name = "mux",
4093 .type = QEMU_OPT_BOOL,
4095 .name = "signal",
4096 .type = QEMU_OPT_BOOL,
4098 .name = "name",
4099 .type = QEMU_OPT_STRING,
4101 .name = "debug",
4102 .type = QEMU_OPT_NUMBER,
4104 .name = "size",
4105 .type = QEMU_OPT_SIZE,
4107 .name = "chardev",
4108 .type = QEMU_OPT_STRING,
4110 .name = "append",
4111 .type = QEMU_OPT_BOOL,
4113 .name = "logfile",
4114 .type = QEMU_OPT_STRING,
4116 .name = "logappend",
4117 .type = QEMU_OPT_BOOL,
4119 { /* end of list */ }
4123 #ifdef _WIN32
4125 static CharDriverState *qmp_chardev_open_file(const char *id,
4126 ChardevBackend *backend,
4127 ChardevReturn *ret,
4128 Error **errp)
4130 ChardevFile *file = backend->u.file;
4131 ChardevCommon *common = qapi_ChardevFile_base(backend->u.file);
4132 HANDLE out;
4134 if (file->has_in) {
4135 error_setg(errp, "input file not supported");
4136 return NULL;
4139 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
4140 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
4141 if (out == INVALID_HANDLE_VALUE) {
4142 error_setg(errp, "open %s failed", file->out);
4143 return NULL;
4145 return qemu_chr_open_win_file(out, common, errp);
4148 static CharDriverState *qmp_chardev_open_serial(const char *id,
4149 ChardevBackend *backend,
4150 ChardevReturn *ret,
4151 Error **errp)
4153 ChardevHostdev *serial = backend->u.serial;
4154 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.serial);
4155 return qemu_chr_open_win_path(serial->device, common, errp);
4158 #else /* WIN32 */
4160 static int qmp_chardev_open_file_source(char *src, int flags,
4161 Error **errp)
4163 int fd = -1;
4165 TFR(fd = qemu_open(src, flags, 0666));
4166 if (fd == -1) {
4167 error_setg_file_open(errp, errno, src);
4169 return fd;
4172 static CharDriverState *qmp_chardev_open_file(const char *id,
4173 ChardevBackend *backend,
4174 ChardevReturn *ret,
4175 Error **errp)
4177 ChardevFile *file = backend->u.file;
4178 ChardevCommon *common = qapi_ChardevFile_base(backend->u.file);
4179 int flags, in = -1, out;
4181 flags = O_WRONLY | O_CREAT | O_BINARY;
4182 if (file->has_append && file->append) {
4183 flags |= O_APPEND;
4184 } else {
4185 flags |= O_TRUNC;
4188 out = qmp_chardev_open_file_source(file->out, flags, errp);
4189 if (out < 0) {
4190 return NULL;
4193 if (file->has_in) {
4194 flags = O_RDONLY;
4195 in = qmp_chardev_open_file_source(file->in, flags, errp);
4196 if (in < 0) {
4197 qemu_close(out);
4198 return NULL;
4202 return qemu_chr_open_fd(in, out, common, errp);
4205 #ifdef HAVE_CHARDEV_SERIAL
4206 static CharDriverState *qmp_chardev_open_serial(const char *id,
4207 ChardevBackend *backend,
4208 ChardevReturn *ret,
4209 Error **errp)
4211 ChardevHostdev *serial = backend->u.serial;
4212 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.serial);
4213 int fd;
4215 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4216 if (fd < 0) {
4217 return NULL;
4219 qemu_set_nonblock(fd);
4220 return qemu_chr_open_tty_fd(fd, common, errp);
4222 #endif
4224 #ifdef HAVE_CHARDEV_PARPORT
4225 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4226 ChardevBackend *backend,
4227 ChardevReturn *ret,
4228 Error **errp)
4230 ChardevHostdev *parallel = backend->u.parallel;
4231 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.parallel);
4232 int fd;
4234 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4235 if (fd < 0) {
4236 return NULL;
4238 return qemu_chr_open_pp_fd(fd, common, errp);
4240 #endif
4242 #endif /* WIN32 */
4244 static void socket_try_connect(CharDriverState *chr)
4246 Error *err = NULL;
4248 if (!qemu_chr_open_socket_fd(chr, &err)) {
4249 check_report_connect_error(chr, err);
4253 static gboolean socket_reconnect_timeout(gpointer opaque)
4255 CharDriverState *chr = opaque;
4256 TCPCharDriver *s = chr->opaque;
4258 s->reconnect_timer = 0;
4260 if (chr->be_open) {
4261 return false;
4264 socket_try_connect(chr);
4266 return false;
4269 static CharDriverState *qmp_chardev_open_socket(const char *id,
4270 ChardevBackend *backend,
4271 ChardevReturn *ret,
4272 Error **errp)
4274 CharDriverState *chr;
4275 TCPCharDriver *s;
4276 ChardevSocket *sock = backend->u.socket;
4277 SocketAddress *addr = sock->addr;
4278 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4279 bool is_listen = sock->has_server ? sock->server : true;
4280 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4281 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4282 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4283 ChardevCommon *common = qapi_ChardevSocket_base(backend->u.socket);
4285 chr = qemu_chr_alloc(common, errp);
4286 if (!chr) {
4287 return NULL;
4289 s = g_new0(TCPCharDriver, 1);
4291 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4292 s->is_listen = is_listen;
4293 s->is_telnet = is_telnet;
4294 s->do_nodelay = do_nodelay;
4295 if (sock->tls_creds) {
4296 Object *creds;
4297 creds = object_resolve_path_component(
4298 object_get_objects_root(), sock->tls_creds);
4299 if (!creds) {
4300 error_setg(errp, "No TLS credentials with id '%s'",
4301 sock->tls_creds);
4302 goto error;
4304 s->tls_creds = (QCryptoTLSCreds *)
4305 object_dynamic_cast(creds,
4306 TYPE_QCRYPTO_TLS_CREDS);
4307 if (!s->tls_creds) {
4308 error_setg(errp, "Object with id '%s' is not TLS credentials",
4309 sock->tls_creds);
4310 goto error;
4312 object_ref(OBJECT(s->tls_creds));
4313 if (is_listen) {
4314 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4315 error_setg(errp, "%s",
4316 "Expected TLS credentials for server endpoint");
4317 goto error;
4319 } else {
4320 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4321 error_setg(errp, "%s",
4322 "Expected TLS credentials for client endpoint");
4323 goto error;
4328 qapi_copy_SocketAddress(&s->addr, sock->addr);
4330 chr->opaque = s;
4331 chr->chr_write = tcp_chr_write;
4332 chr->chr_sync_read = tcp_chr_sync_read;
4333 chr->chr_close = tcp_chr_close;
4334 chr->get_msgfds = tcp_get_msgfds;
4335 chr->set_msgfds = tcp_set_msgfds;
4336 chr->chr_add_client = tcp_chr_add_client;
4337 chr->chr_add_watch = tcp_chr_add_watch;
4338 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4339 /* be isn't opened until we get a connection */
4340 chr->explicit_be_open = true;
4342 chr->filename = SocketAddress_to_str("disconnected:",
4343 addr, is_listen, is_telnet);
4345 if (is_listen) {
4346 if (is_telnet) {
4347 s->do_telnetopt = 1;
4349 } else if (reconnect > 0) {
4350 s->reconnect_time = reconnect;
4353 if (s->reconnect_time) {
4354 socket_try_connect(chr);
4355 } else if (!qemu_chr_open_socket_fd(chr, errp)) {
4356 goto error;
4359 if (is_listen && is_waitconnect) {
4360 fprintf(stderr, "QEMU waiting for connection on: %s\n",
4361 chr->filename);
4362 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
4363 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
4366 return chr;
4368 error:
4369 if (s->tls_creds) {
4370 object_unref(OBJECT(s->tls_creds));
4372 g_free(s);
4373 qemu_chr_free_common(chr);
4374 return NULL;
4377 static CharDriverState *qmp_chardev_open_udp(const char *id,
4378 ChardevBackend *backend,
4379 ChardevReturn *ret,
4380 Error **errp)
4382 ChardevUdp *udp = backend->u.udp;
4383 ChardevCommon *common = qapi_ChardevUdp_base(backend->u.udp);
4384 QIOChannelSocket *sioc = qio_channel_socket_new();
4386 if (qio_channel_socket_dgram_sync(sioc,
4387 udp->local, udp->remote,
4388 errp) < 0) {
4389 object_unref(OBJECT(sioc));
4390 return NULL;
4392 return qemu_chr_open_udp(sioc, common, errp);
4395 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4396 Error **errp)
4398 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4399 CharDriverState *chr = NULL;
4400 Error *local_err = NULL;
4401 GSList *i;
4402 CharDriver *cd;
4404 chr = qemu_chr_find(id);
4405 if (chr) {
4406 error_setg(errp, "Chardev '%s' already exists", id);
4407 g_free(ret);
4408 return NULL;
4411 for (i = backends; i; i = i->next) {
4412 cd = i->data;
4414 if (cd->kind == backend->type) {
4415 chr = cd->create(id, backend, ret, &local_err);
4416 if (local_err) {
4417 error_propagate(errp, local_err);
4418 goto out_error;
4420 break;
4424 if (chr == NULL) {
4425 assert(!i);
4426 error_setg(errp, "chardev backend not available");
4427 goto out_error;
4430 chr->label = g_strdup(id);
4431 chr->avail_connections =
4432 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4433 if (!chr->filename) {
4434 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4436 if (!chr->explicit_be_open) {
4437 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4439 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4440 return ret;
4442 out_error:
4443 g_free(ret);
4444 return NULL;
4447 void qmp_chardev_remove(const char *id, Error **errp)
4449 CharDriverState *chr;
4451 chr = qemu_chr_find(id);
4452 if (chr == NULL) {
4453 error_setg(errp, "Chardev '%s' not found", id);
4454 return;
4456 if (chr->chr_can_read || chr->chr_read ||
4457 chr->chr_event || chr->handler_opaque) {
4458 error_setg(errp, "Chardev '%s' is busy", id);
4459 return;
4461 qemu_chr_delete(chr);
4464 static void register_types(void)
4466 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4467 qemu_chr_open_null);
4468 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4469 qemu_chr_parse_socket, qmp_chardev_open_socket);
4470 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4471 qmp_chardev_open_udp);
4472 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4473 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4474 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4475 qemu_chr_parse_file_out, qmp_chardev_open_file);
4476 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4477 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4478 #if defined HAVE_CHARDEV_SERIAL
4479 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4480 qemu_chr_parse_serial, qmp_chardev_open_serial);
4481 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4482 qemu_chr_parse_serial, qmp_chardev_open_serial);
4483 #endif
4484 #ifdef HAVE_CHARDEV_PARPORT
4485 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4486 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4487 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4488 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4489 #endif
4490 #ifdef HAVE_CHARDEV_PTY
4491 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4492 qemu_chr_open_pty);
4493 #endif
4494 #ifdef _WIN32
4495 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4496 qemu_chr_open_win_con);
4497 #endif
4498 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4499 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4500 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4501 qemu_chr_open_mux);
4502 /* Bug-compatibility: */
4503 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4504 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4505 /* this must be done after machine init, since we register FEs with muxes
4506 * as part of realize functions like serial_isa_realizefn when -nographic
4507 * is specified
4509 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4512 type_init(register_types);