scripts/kvm/kvm_stat: Moved DebugfsProvider
[qemu.git] / qemu-char.c
blobca53e8c376ef56856dcd5a702363c910219aceea
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu-common.h"
25 #include "monitor/monitor.h"
26 #include "sysemu/sysemu.h"
27 #include "qemu/error-report.h"
28 #include "qemu/timer.h"
29 #include "sysemu/char.h"
30 #include "hw/usb.h"
31 #include "qmp-commands.h"
32 #include "qapi/qmp-input-visitor.h"
33 #include "qapi/qmp-output-visitor.h"
34 #include "qapi-visit.h"
35 #include "qemu/base64.h"
36 #include "io/channel-socket.h"
37 #include "io/channel-file.h"
38 #include "io/channel-tls.h"
40 #include <unistd.h>
41 #include <fcntl.h>
42 #include <time.h>
43 #include <errno.h>
44 #include <sys/time.h>
45 #include <zlib.h>
47 #ifndef _WIN32
48 #include <sys/times.h>
49 #include <sys/wait.h>
50 #include <termios.h>
51 #include <sys/mman.h>
52 #include <sys/ioctl.h>
53 #include <sys/resource.h>
54 #include <sys/socket.h>
55 #include <netinet/in.h>
56 #include <net/if.h>
57 #include <arpa/inet.h>
58 #include <netdb.h>
59 #include <sys/select.h>
60 #ifdef CONFIG_BSD
61 #include <sys/stat.h>
62 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
63 #include <dev/ppbus/ppi.h>
64 #include <dev/ppbus/ppbconf.h>
65 #elif defined(__DragonFly__)
66 #include <dev/misc/ppi/ppi.h>
67 #include <bus/ppbus/ppbconf.h>
68 #endif
69 #else
70 #ifdef __linux__
71 #include <linux/ppdev.h>
72 #include <linux/parport.h>
73 #endif
74 #ifdef __sun__
75 #include <sys/stat.h>
76 #include <sys/ethernet.h>
77 #include <sys/sockio.h>
78 #include <netinet/arp.h>
79 #include <netinet/in.h>
80 #include <netinet/in_systm.h>
81 #include <netinet/ip.h>
82 #include <netinet/ip_icmp.h> // must come after ip.h
83 #include <netinet/udp.h>
84 #include <netinet/tcp.h>
85 #endif
86 #endif
87 #endif
89 #include "qemu/sockets.h"
90 #include "ui/qemu-spice.h"
92 #define READ_BUF_LEN 4096
93 #define READ_RETRIES 10
94 #define TCP_MAX_FDS 16
96 /***********************************************************/
97 /* Socket address helpers */
99 static char *SocketAddress_to_str(const char *prefix, SocketAddress *addr,
100 bool is_listen, bool is_telnet)
102 switch (addr->type) {
103 case SOCKET_ADDRESS_KIND_INET:
104 return g_strdup_printf("%s%s:%s:%s%s", prefix,
105 is_telnet ? "telnet" : "tcp", addr->u.inet->host,
106 addr->u.inet->port, is_listen ? ",server" : "");
107 break;
108 case SOCKET_ADDRESS_KIND_UNIX:
109 return g_strdup_printf("%sunix:%s%s", prefix,
110 addr->u.q_unix->path,
111 is_listen ? ",server" : "");
112 break;
113 case SOCKET_ADDRESS_KIND_FD:
114 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd->str,
115 is_listen ? ",server" : "");
116 break;
117 default:
118 abort();
122 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
123 struct sockaddr_storage *ps, socklen_t ps_len,
124 bool is_listen, bool is_telnet)
126 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
127 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
128 const char *left = "", *right = "";
130 switch (ss->ss_family) {
131 #ifndef _WIN32
132 case AF_UNIX:
133 return g_strdup_printf("unix:%s%s",
134 ((struct sockaddr_un *)(ss))->sun_path,
135 is_listen ? ",server" : "");
136 #endif
137 case AF_INET6:
138 left = "[";
139 right = "]";
140 /* fall through */
141 case AF_INET:
142 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
143 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
144 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
145 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
146 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
147 is_telnet ? "telnet" : "tcp",
148 left, shost, right, sserv,
149 is_listen ? ",server" : "",
150 left, phost, right, pserv);
152 default:
153 return g_strdup_printf("unknown");
157 /***********************************************************/
158 /* character device */
160 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
161 QTAILQ_HEAD_INITIALIZER(chardevs);
163 static void qemu_chr_free_common(CharDriverState *chr);
165 CharDriverState *qemu_chr_alloc(ChardevCommon *backend, Error **errp)
167 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
168 qemu_mutex_init(&chr->chr_write_lock);
170 if (backend->has_logfile) {
171 int flags = O_WRONLY | O_CREAT;
172 if (backend->has_logappend &&
173 backend->logappend) {
174 flags |= O_APPEND;
175 } else {
176 flags |= O_TRUNC;
178 chr->logfd = qemu_open(backend->logfile, flags, 0666);
179 if (chr->logfd < 0) {
180 error_setg_errno(errp, errno,
181 "Unable to open logfile %s",
182 backend->logfile);
183 g_free(chr);
184 return NULL;
186 } else {
187 chr->logfd = -1;
190 return chr;
193 void qemu_chr_be_event(CharDriverState *s, int event)
195 /* Keep track if the char device is open */
196 switch (event) {
197 case CHR_EVENT_OPENED:
198 s->be_open = 1;
199 break;
200 case CHR_EVENT_CLOSED:
201 s->be_open = 0;
202 break;
205 if (!s->chr_event)
206 return;
207 s->chr_event(s->handler_opaque, event);
210 void qemu_chr_be_generic_open(CharDriverState *s)
212 qemu_chr_be_event(s, CHR_EVENT_OPENED);
216 /* Not reporting errors from writing to logfile, as logs are
217 * defined to be "best effort" only */
218 static void qemu_chr_fe_write_log(CharDriverState *s,
219 const uint8_t *buf, size_t len)
221 size_t done = 0;
222 ssize_t ret;
224 if (s->logfd < 0) {
225 return;
228 while (done < len) {
229 do {
230 ret = write(s->logfd, buf + done, len - done);
231 if (ret == -1 && errno == EAGAIN) {
232 g_usleep(100);
234 } while (ret == -1 && errno == EAGAIN);
236 if (ret <= 0) {
237 return;
239 done += ret;
243 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
245 int ret;
247 qemu_mutex_lock(&s->chr_write_lock);
248 ret = s->chr_write(s, buf, len);
250 if (ret > 0) {
251 qemu_chr_fe_write_log(s, buf, ret);
254 qemu_mutex_unlock(&s->chr_write_lock);
255 return ret;
258 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
260 int offset = 0;
261 int res = 0;
263 qemu_mutex_lock(&s->chr_write_lock);
264 while (offset < len) {
265 do {
266 res = s->chr_write(s, buf + offset, len - offset);
267 if (res == -1 && errno == EAGAIN) {
268 g_usleep(100);
270 } while (res == -1 && errno == EAGAIN);
272 if (res <= 0) {
273 break;
276 offset += res;
278 if (offset > 0) {
279 qemu_chr_fe_write_log(s, buf, offset);
282 qemu_mutex_unlock(&s->chr_write_lock);
284 if (res < 0) {
285 return res;
287 return offset;
290 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
292 int offset = 0, counter = 10;
293 int res;
295 if (!s->chr_sync_read) {
296 return 0;
299 while (offset < len) {
300 do {
301 res = s->chr_sync_read(s, buf + offset, len - offset);
302 if (res == -1 && errno == EAGAIN) {
303 g_usleep(100);
305 } while (res == -1 && errno == EAGAIN);
307 if (res == 0) {
308 break;
311 if (res < 0) {
312 return res;
315 offset += res;
317 if (!counter--) {
318 break;
322 return offset;
325 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
327 if (!s->chr_ioctl)
328 return -ENOTSUP;
329 return s->chr_ioctl(s, cmd, arg);
332 int qemu_chr_be_can_write(CharDriverState *s)
334 if (!s->chr_can_read)
335 return 0;
336 return s->chr_can_read(s->handler_opaque);
339 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
341 if (s->chr_read) {
342 s->chr_read(s->handler_opaque, buf, len);
346 int qemu_chr_fe_get_msgfd(CharDriverState *s)
348 int fd;
349 return (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
352 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
354 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
357 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
359 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
362 int qemu_chr_add_client(CharDriverState *s, int fd)
364 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
367 void qemu_chr_accept_input(CharDriverState *s)
369 if (s->chr_accept_input)
370 s->chr_accept_input(s);
371 qemu_notify_event();
374 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
376 char buf[READ_BUF_LEN];
377 va_list ap;
378 va_start(ap, fmt);
379 vsnprintf(buf, sizeof(buf), fmt, ap);
380 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
381 va_end(ap);
384 static void remove_fd_in_watch(CharDriverState *chr);
386 void qemu_chr_add_handlers(CharDriverState *s,
387 IOCanReadHandler *fd_can_read,
388 IOReadHandler *fd_read,
389 IOEventHandler *fd_event,
390 void *opaque)
392 int fe_open;
394 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
395 fe_open = 0;
396 remove_fd_in_watch(s);
397 } else {
398 fe_open = 1;
400 s->chr_can_read = fd_can_read;
401 s->chr_read = fd_read;
402 s->chr_event = fd_event;
403 s->handler_opaque = opaque;
404 if (fe_open && s->chr_update_read_handler)
405 s->chr_update_read_handler(s);
407 if (!s->explicit_fe_open) {
408 qemu_chr_fe_set_open(s, fe_open);
411 /* We're connecting to an already opened device, so let's make sure we
412 also get the open event */
413 if (fe_open && s->be_open) {
414 qemu_chr_be_generic_open(s);
418 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
420 return len;
423 static CharDriverState *qemu_chr_open_null(const char *id,
424 ChardevBackend *backend,
425 ChardevReturn *ret,
426 Error **errp)
428 CharDriverState *chr;
429 ChardevCommon *common = qapi_ChardevDummy_base(backend->u.null);
431 chr = qemu_chr_alloc(common, errp);
432 if (!chr) {
433 return NULL;
435 chr->chr_write = null_chr_write;
436 chr->explicit_be_open = true;
437 return chr;
440 /* MUX driver for serial I/O splitting */
441 #define MAX_MUX 4
442 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
443 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
444 typedef struct {
445 IOCanReadHandler *chr_can_read[MAX_MUX];
446 IOReadHandler *chr_read[MAX_MUX];
447 IOEventHandler *chr_event[MAX_MUX];
448 void *ext_opaque[MAX_MUX];
449 CharDriverState *drv;
450 int focus;
451 int mux_cnt;
452 int term_got_escape;
453 int max_size;
454 /* Intermediate input buffer allows to catch escape sequences even if the
455 currently active device is not accepting any input - but only until it
456 is full as well. */
457 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
458 int prod[MAX_MUX];
459 int cons[MAX_MUX];
460 int timestamps;
462 /* Protected by the CharDriverState chr_write_lock. */
463 int linestart;
464 int64_t timestamps_start;
465 } MuxDriver;
468 /* Called with chr_write_lock held. */
469 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
471 MuxDriver *d = chr->opaque;
472 int ret;
473 if (!d->timestamps) {
474 ret = qemu_chr_fe_write(d->drv, buf, len);
475 } else {
476 int i;
478 ret = 0;
479 for (i = 0; i < len; i++) {
480 if (d->linestart) {
481 char buf1[64];
482 int64_t ti;
483 int secs;
485 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
486 if (d->timestamps_start == -1)
487 d->timestamps_start = ti;
488 ti -= d->timestamps_start;
489 secs = ti / 1000;
490 snprintf(buf1, sizeof(buf1),
491 "[%02d:%02d:%02d.%03d] ",
492 secs / 3600,
493 (secs / 60) % 60,
494 secs % 60,
495 (int)(ti % 1000));
496 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
497 d->linestart = 0;
499 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
500 if (buf[i] == '\n') {
501 d->linestart = 1;
505 return ret;
508 static const char * const mux_help[] = {
509 "% h print this help\n\r",
510 "% x exit emulator\n\r",
511 "% s save disk data back to file (if -snapshot)\n\r",
512 "% t toggle console timestamps\n\r",
513 "% b send break (magic sysrq)\n\r",
514 "% c switch between console and monitor\n\r",
515 "% % sends %\n\r",
516 NULL
519 int term_escape_char = 0x01; /* ctrl-a is used for escape */
520 static void mux_print_help(CharDriverState *chr)
522 int i, j;
523 char ebuf[15] = "Escape-Char";
524 char cbuf[50] = "\n\r";
526 if (term_escape_char > 0 && term_escape_char < 26) {
527 snprintf(cbuf, sizeof(cbuf), "\n\r");
528 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
529 } else {
530 snprintf(cbuf, sizeof(cbuf),
531 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
532 term_escape_char);
534 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
535 for (i = 0; mux_help[i] != NULL; i++) {
536 for (j=0; mux_help[i][j] != '\0'; j++) {
537 if (mux_help[i][j] == '%')
538 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
539 else
540 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
545 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
547 if (d->chr_event[mux_nr])
548 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
551 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
553 if (d->term_got_escape) {
554 d->term_got_escape = 0;
555 if (ch == term_escape_char)
556 goto send_char;
557 switch(ch) {
558 case '?':
559 case 'h':
560 mux_print_help(chr);
561 break;
562 case 'x':
564 const char *term = "QEMU: Terminated\n\r";
565 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
566 exit(0);
567 break;
569 case 's':
570 bdrv_commit_all();
571 break;
572 case 'b':
573 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
574 break;
575 case 'c':
576 /* Switch to the next registered device */
577 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
578 d->focus++;
579 if (d->focus >= d->mux_cnt)
580 d->focus = 0;
581 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
582 break;
583 case 't':
584 d->timestamps = !d->timestamps;
585 d->timestamps_start = -1;
586 d->linestart = 0;
587 break;
589 } else if (ch == term_escape_char) {
590 d->term_got_escape = 1;
591 } else {
592 send_char:
593 return 1;
595 return 0;
598 static void mux_chr_accept_input(CharDriverState *chr)
600 MuxDriver *d = chr->opaque;
601 int m = d->focus;
603 while (d->prod[m] != d->cons[m] &&
604 d->chr_can_read[m] &&
605 d->chr_can_read[m](d->ext_opaque[m])) {
606 d->chr_read[m](d->ext_opaque[m],
607 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
611 static int mux_chr_can_read(void *opaque)
613 CharDriverState *chr = opaque;
614 MuxDriver *d = chr->opaque;
615 int m = d->focus;
617 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
618 return 1;
619 if (d->chr_can_read[m])
620 return d->chr_can_read[m](d->ext_opaque[m]);
621 return 0;
624 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
626 CharDriverState *chr = opaque;
627 MuxDriver *d = chr->opaque;
628 int m = d->focus;
629 int i;
631 mux_chr_accept_input (opaque);
633 for(i = 0; i < size; i++)
634 if (mux_proc_byte(chr, d, buf[i])) {
635 if (d->prod[m] == d->cons[m] &&
636 d->chr_can_read[m] &&
637 d->chr_can_read[m](d->ext_opaque[m]))
638 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
639 else
640 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
644 static void mux_chr_event(void *opaque, int event)
646 CharDriverState *chr = opaque;
647 MuxDriver *d = chr->opaque;
648 int i;
650 /* Send the event to all registered listeners */
651 for (i = 0; i < d->mux_cnt; i++)
652 mux_chr_send_event(d, i, event);
655 static void mux_chr_update_read_handler(CharDriverState *chr)
657 MuxDriver *d = chr->opaque;
659 if (d->mux_cnt >= MAX_MUX) {
660 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
661 return;
663 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
664 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
665 d->chr_read[d->mux_cnt] = chr->chr_read;
666 d->chr_event[d->mux_cnt] = chr->chr_event;
667 /* Fix up the real driver with mux routines */
668 if (d->mux_cnt == 0) {
669 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
670 mux_chr_event, chr);
672 if (d->focus != -1) {
673 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
675 d->focus = d->mux_cnt;
676 d->mux_cnt++;
677 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
680 static bool muxes_realized;
683 * Called after processing of default and command-line-specified
684 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
685 * to a mux chardev. This is done here to ensure that
686 * output/prompts/banners are only displayed for the FE that has
687 * focus when initial command-line processing/machine init is
688 * completed.
690 * After this point, any new FE attached to any new or existing
691 * mux will receive CHR_EVENT_OPENED notifications for the BE
692 * immediately.
694 static void muxes_realize_done(Notifier *notifier, void *unused)
696 CharDriverState *chr;
698 QTAILQ_FOREACH(chr, &chardevs, next) {
699 if (chr->is_mux) {
700 MuxDriver *d = chr->opaque;
701 int i;
703 /* send OPENED to all already-attached FEs */
704 for (i = 0; i < d->mux_cnt; i++) {
705 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
707 /* mark mux as OPENED so any new FEs will immediately receive
708 * OPENED event
710 qemu_chr_be_generic_open(chr);
713 muxes_realized = true;
716 static Notifier muxes_realize_notify = {
717 .notify = muxes_realize_done,
720 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
722 MuxDriver *d = s->opaque;
723 return d->drv->chr_add_watch(d->drv, cond);
726 static CharDriverState *qemu_chr_open_mux(const char *id,
727 ChardevBackend *backend,
728 ChardevReturn *ret, Error **errp)
730 ChardevMux *mux = backend->u.mux;
731 CharDriverState *chr, *drv;
732 MuxDriver *d;
733 ChardevCommon *common = qapi_ChardevMux_base(backend->u.mux);
735 drv = qemu_chr_find(mux->chardev);
736 if (drv == NULL) {
737 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
738 return NULL;
741 chr = qemu_chr_alloc(common, errp);
742 if (!chr) {
743 return NULL;
745 d = g_new0(MuxDriver, 1);
747 chr->opaque = d;
748 d->drv = drv;
749 d->focus = -1;
750 chr->chr_write = mux_chr_write;
751 chr->chr_update_read_handler = mux_chr_update_read_handler;
752 chr->chr_accept_input = mux_chr_accept_input;
753 /* Frontend guest-open / -close notification is not support with muxes */
754 chr->chr_set_fe_open = NULL;
755 if (drv->chr_add_watch) {
756 chr->chr_add_watch = mux_chr_add_watch;
758 /* only default to opened state if we've realized the initial
759 * set of muxes
761 chr->explicit_be_open = muxes_realized ? 0 : 1;
762 chr->is_mux = 1;
764 return chr;
768 typedef struct IOWatchPoll
770 GSource parent;
772 QIOChannel *ioc;
773 GSource *src;
775 IOCanReadHandler *fd_can_read;
776 GSourceFunc fd_read;
777 void *opaque;
778 } IOWatchPoll;
780 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
782 return container_of(source, IOWatchPoll, parent);
785 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
787 IOWatchPoll *iwp = io_watch_poll_from_source(source);
788 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
789 bool was_active = iwp->src != NULL;
790 if (was_active == now_active) {
791 return FALSE;
794 if (now_active) {
795 iwp->src = qio_channel_create_watch(
796 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
797 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
798 g_source_attach(iwp->src, NULL);
799 } else {
800 g_source_destroy(iwp->src);
801 g_source_unref(iwp->src);
802 iwp->src = NULL;
804 return FALSE;
807 static gboolean io_watch_poll_check(GSource *source)
809 return FALSE;
812 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
813 gpointer user_data)
815 abort();
818 static void io_watch_poll_finalize(GSource *source)
820 /* Due to a glib bug, removing the last reference to a source
821 * inside a finalize callback causes recursive locking (and a
822 * deadlock). This is not a problem inside other callbacks,
823 * including dispatch callbacks, so we call io_remove_watch_poll
824 * to remove this source. At this point, iwp->src must
825 * be NULL, or we would leak it.
827 * This would be solved much more elegantly by child sources,
828 * but we support older glib versions that do not have them.
830 IOWatchPoll *iwp = io_watch_poll_from_source(source);
831 assert(iwp->src == NULL);
834 static GSourceFuncs io_watch_poll_funcs = {
835 .prepare = io_watch_poll_prepare,
836 .check = io_watch_poll_check,
837 .dispatch = io_watch_poll_dispatch,
838 .finalize = io_watch_poll_finalize,
841 /* Can only be used for read */
842 static guint io_add_watch_poll(QIOChannel *ioc,
843 IOCanReadHandler *fd_can_read,
844 QIOChannelFunc fd_read,
845 gpointer user_data)
847 IOWatchPoll *iwp;
848 int tag;
850 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
851 iwp->fd_can_read = fd_can_read;
852 iwp->opaque = user_data;
853 iwp->ioc = ioc;
854 iwp->fd_read = (GSourceFunc) fd_read;
855 iwp->src = NULL;
857 tag = g_source_attach(&iwp->parent, NULL);
858 g_source_unref(&iwp->parent);
859 return tag;
862 static void io_remove_watch_poll(guint tag)
864 GSource *source;
865 IOWatchPoll *iwp;
867 g_return_if_fail (tag > 0);
869 source = g_main_context_find_source_by_id(NULL, tag);
870 g_return_if_fail (source != NULL);
872 iwp = io_watch_poll_from_source(source);
873 if (iwp->src) {
874 g_source_destroy(iwp->src);
875 g_source_unref(iwp->src);
876 iwp->src = NULL;
878 g_source_destroy(&iwp->parent);
881 static void remove_fd_in_watch(CharDriverState *chr)
883 if (chr->fd_in_tag) {
884 io_remove_watch_poll(chr->fd_in_tag);
885 chr->fd_in_tag = 0;
890 static int io_channel_send_full(QIOChannel *ioc,
891 const void *buf, size_t len,
892 int *fds, size_t nfds)
894 size_t offset = 0;
896 while (offset < len) {
897 ssize_t ret = 0;
898 struct iovec iov = { .iov_base = (char *)buf + offset,
899 .iov_len = len - offset };
901 ret = qio_channel_writev_full(
902 ioc, &iov, 1,
903 fds, nfds, NULL);
904 if (ret == QIO_CHANNEL_ERR_BLOCK) {
905 errno = EAGAIN;
906 return -1;
907 } else if (ret < 0) {
908 if (offset) {
909 return offset;
912 errno = EINVAL;
913 return -1;
916 offset += ret;
919 return offset;
923 #ifndef _WIN32
924 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
926 return io_channel_send_full(ioc, buf, len, NULL, 0);
930 typedef struct FDCharDriver {
931 CharDriverState *chr;
932 QIOChannel *ioc_in, *ioc_out;
933 int max_size;
934 } FDCharDriver;
936 /* Called with chr_write_lock held. */
937 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
939 FDCharDriver *s = chr->opaque;
941 return io_channel_send(s->ioc_out, buf, len);
944 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
946 CharDriverState *chr = opaque;
947 FDCharDriver *s = chr->opaque;
948 int len;
949 uint8_t buf[READ_BUF_LEN];
950 ssize_t ret;
952 len = sizeof(buf);
953 if (len > s->max_size) {
954 len = s->max_size;
956 if (len == 0) {
957 return TRUE;
960 ret = qio_channel_read(
961 chan, (gchar *)buf, len, NULL);
962 if (ret == 0) {
963 remove_fd_in_watch(chr);
964 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
965 return FALSE;
967 if (ret > 0) {
968 qemu_chr_be_write(chr, buf, ret);
971 return TRUE;
974 static int fd_chr_read_poll(void *opaque)
976 CharDriverState *chr = opaque;
977 FDCharDriver *s = chr->opaque;
979 s->max_size = qemu_chr_be_can_write(chr);
980 return s->max_size;
983 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
985 FDCharDriver *s = chr->opaque;
986 return qio_channel_create_watch(s->ioc_out, cond);
989 static void fd_chr_update_read_handler(CharDriverState *chr)
991 FDCharDriver *s = chr->opaque;
993 remove_fd_in_watch(chr);
994 if (s->ioc_in) {
995 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
996 fd_chr_read_poll,
997 fd_chr_read, chr);
1001 static void fd_chr_close(struct CharDriverState *chr)
1003 FDCharDriver *s = chr->opaque;
1005 remove_fd_in_watch(chr);
1006 if (s->ioc_in) {
1007 object_unref(OBJECT(s->ioc_in));
1009 if (s->ioc_out) {
1010 object_unref(OBJECT(s->ioc_out));
1013 g_free(s);
1014 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1017 /* open a character device to a unix fd */
1018 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1019 ChardevCommon *backend, Error **errp)
1021 CharDriverState *chr;
1022 FDCharDriver *s;
1024 chr = qemu_chr_alloc(backend, errp);
1025 if (!chr) {
1026 return NULL;
1028 s = g_new0(FDCharDriver, 1);
1029 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1030 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1031 qemu_set_nonblock(fd_out);
1032 s->chr = chr;
1033 chr->opaque = s;
1034 chr->chr_add_watch = fd_chr_add_watch;
1035 chr->chr_write = fd_chr_write;
1036 chr->chr_update_read_handler = fd_chr_update_read_handler;
1037 chr->chr_close = fd_chr_close;
1039 return chr;
1042 static CharDriverState *qemu_chr_open_pipe(const char *id,
1043 ChardevBackend *backend,
1044 ChardevReturn *ret,
1045 Error **errp)
1047 ChardevHostdev *opts = backend->u.pipe;
1048 int fd_in, fd_out;
1049 char *filename_in;
1050 char *filename_out;
1051 const char *filename = opts->device;
1052 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.pipe);
1055 filename_in = g_strdup_printf("%s.in", filename);
1056 filename_out = g_strdup_printf("%s.out", filename);
1057 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1058 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1059 g_free(filename_in);
1060 g_free(filename_out);
1061 if (fd_in < 0 || fd_out < 0) {
1062 if (fd_in >= 0)
1063 close(fd_in);
1064 if (fd_out >= 0)
1065 close(fd_out);
1066 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1067 if (fd_in < 0) {
1068 error_setg_file_open(errp, errno, filename);
1069 return NULL;
1072 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1075 /* init terminal so that we can grab keys */
1076 static struct termios oldtty;
1077 static int old_fd0_flags;
1078 static bool stdio_in_use;
1079 static bool stdio_allow_signal;
1080 static bool stdio_echo_state;
1082 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1084 static void term_exit(void)
1086 tcsetattr (0, TCSANOW, &oldtty);
1087 fcntl(0, F_SETFL, old_fd0_flags);
1090 static void term_stdio_handler(int sig)
1092 /* restore echo after resume from suspend. */
1093 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1096 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1098 struct termios tty;
1100 stdio_echo_state = echo;
1101 tty = oldtty;
1102 if (!echo) {
1103 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1104 |INLCR|IGNCR|ICRNL|IXON);
1105 tty.c_oflag |= OPOST;
1106 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1107 tty.c_cflag &= ~(CSIZE|PARENB);
1108 tty.c_cflag |= CS8;
1109 tty.c_cc[VMIN] = 1;
1110 tty.c_cc[VTIME] = 0;
1112 if (!stdio_allow_signal)
1113 tty.c_lflag &= ~ISIG;
1115 tcsetattr (0, TCSANOW, &tty);
1118 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1120 term_exit();
1121 fd_chr_close(chr);
1124 static CharDriverState *qemu_chr_open_stdio(const char *id,
1125 ChardevBackend *backend,
1126 ChardevReturn *ret,
1127 Error **errp)
1129 ChardevStdio *opts = backend->u.stdio;
1130 CharDriverState *chr;
1131 struct sigaction act;
1132 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio);
1134 if (is_daemonized()) {
1135 error_setg(errp, "cannot use stdio with -daemonize");
1136 return NULL;
1139 if (stdio_in_use) {
1140 error_setg(errp, "cannot use stdio by multiple character devices");
1141 return NULL;
1144 stdio_in_use = true;
1145 old_fd0_flags = fcntl(0, F_GETFL);
1146 tcgetattr(0, &oldtty);
1147 qemu_set_nonblock(0);
1148 atexit(term_exit);
1150 memset(&act, 0, sizeof(act));
1151 act.sa_handler = term_stdio_handler;
1152 sigaction(SIGCONT, &act, NULL);
1154 chr = qemu_chr_open_fd(0, 1, common, errp);
1155 chr->chr_close = qemu_chr_close_stdio;
1156 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1157 if (opts->has_signal) {
1158 stdio_allow_signal = opts->signal;
1160 qemu_chr_fe_set_echo(chr, false);
1162 return chr;
1165 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1166 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1167 || defined(__GLIBC__)
1169 #define HAVE_CHARDEV_SERIAL 1
1170 #define HAVE_CHARDEV_PTY 1
1172 typedef struct {
1173 QIOChannel *ioc;
1174 int read_bytes;
1176 /* Protected by the CharDriverState chr_write_lock. */
1177 int connected;
1178 guint timer_tag;
1179 guint open_tag;
1180 } PtyCharDriver;
1182 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1183 static void pty_chr_state(CharDriverState *chr, int connected);
1185 static gboolean pty_chr_timer(gpointer opaque)
1187 struct CharDriverState *chr = opaque;
1188 PtyCharDriver *s = chr->opaque;
1190 qemu_mutex_lock(&chr->chr_write_lock);
1191 s->timer_tag = 0;
1192 s->open_tag = 0;
1193 if (!s->connected) {
1194 /* Next poll ... */
1195 pty_chr_update_read_handler_locked(chr);
1197 qemu_mutex_unlock(&chr->chr_write_lock);
1198 return FALSE;
1201 /* Called with chr_write_lock held. */
1202 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1204 PtyCharDriver *s = chr->opaque;
1206 if (s->timer_tag) {
1207 g_source_remove(s->timer_tag);
1208 s->timer_tag = 0;
1211 if (ms == 1000) {
1212 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1213 } else {
1214 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1218 /* Called with chr_write_lock held. */
1219 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1221 PtyCharDriver *s = chr->opaque;
1222 GPollFD pfd;
1223 int rc;
1224 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1226 pfd.fd = fioc->fd;
1227 pfd.events = G_IO_OUT;
1228 pfd.revents = 0;
1229 do {
1230 rc = g_poll(&pfd, 1, 0);
1231 } while (rc == -1 && errno == EINTR);
1232 assert(rc >= 0);
1234 if (pfd.revents & G_IO_HUP) {
1235 pty_chr_state(chr, 0);
1236 } else {
1237 pty_chr_state(chr, 1);
1241 static void pty_chr_update_read_handler(CharDriverState *chr)
1243 qemu_mutex_lock(&chr->chr_write_lock);
1244 pty_chr_update_read_handler_locked(chr);
1245 qemu_mutex_unlock(&chr->chr_write_lock);
1248 /* Called with chr_write_lock held. */
1249 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1251 PtyCharDriver *s = chr->opaque;
1253 if (!s->connected) {
1254 /* guest sends data, check for (re-)connect */
1255 pty_chr_update_read_handler_locked(chr);
1256 if (!s->connected) {
1257 return 0;
1260 return io_channel_send(s->ioc, buf, len);
1263 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1265 PtyCharDriver *s = chr->opaque;
1266 if (!s->connected) {
1267 return NULL;
1269 return qio_channel_create_watch(s->ioc, cond);
1272 static int pty_chr_read_poll(void *opaque)
1274 CharDriverState *chr = opaque;
1275 PtyCharDriver *s = chr->opaque;
1277 s->read_bytes = qemu_chr_be_can_write(chr);
1278 return s->read_bytes;
1281 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1283 CharDriverState *chr = opaque;
1284 PtyCharDriver *s = chr->opaque;
1285 gsize len;
1286 uint8_t buf[READ_BUF_LEN];
1287 ssize_t ret;
1289 len = sizeof(buf);
1290 if (len > s->read_bytes)
1291 len = s->read_bytes;
1292 if (len == 0) {
1293 return TRUE;
1295 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1296 if (ret <= 0) {
1297 pty_chr_state(chr, 0);
1298 return FALSE;
1299 } else {
1300 pty_chr_state(chr, 1);
1301 qemu_chr_be_write(chr, buf, ret);
1303 return TRUE;
1306 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1308 CharDriverState *chr = opaque;
1309 PtyCharDriver *s = chr->opaque;
1311 s->open_tag = 0;
1312 qemu_chr_be_generic_open(chr);
1313 return FALSE;
1316 /* Called with chr_write_lock held. */
1317 static void pty_chr_state(CharDriverState *chr, int connected)
1319 PtyCharDriver *s = chr->opaque;
1321 if (!connected) {
1322 if (s->open_tag) {
1323 g_source_remove(s->open_tag);
1324 s->open_tag = 0;
1326 remove_fd_in_watch(chr);
1327 s->connected = 0;
1328 /* (re-)connect poll interval for idle guests: once per second.
1329 * We check more frequently in case the guests sends data to
1330 * the virtual device linked to our pty. */
1331 pty_chr_rearm_timer(chr, 1000);
1332 } else {
1333 if (s->timer_tag) {
1334 g_source_remove(s->timer_tag);
1335 s->timer_tag = 0;
1337 if (!s->connected) {
1338 g_assert(s->open_tag == 0);
1339 s->connected = 1;
1340 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1342 if (!chr->fd_in_tag) {
1343 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1344 pty_chr_read_poll,
1345 pty_chr_read, chr);
1350 static void pty_chr_close(struct CharDriverState *chr)
1352 PtyCharDriver *s = chr->opaque;
1354 qemu_mutex_lock(&chr->chr_write_lock);
1355 pty_chr_state(chr, 0);
1356 object_unref(OBJECT(s->ioc));
1357 if (s->timer_tag) {
1358 g_source_remove(s->timer_tag);
1359 s->timer_tag = 0;
1361 qemu_mutex_unlock(&chr->chr_write_lock);
1362 g_free(s);
1363 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1366 static CharDriverState *qemu_chr_open_pty(const char *id,
1367 ChardevBackend *backend,
1368 ChardevReturn *ret,
1369 Error **errp)
1371 CharDriverState *chr;
1372 PtyCharDriver *s;
1373 int master_fd, slave_fd;
1374 char pty_name[PATH_MAX];
1375 ChardevCommon *common = qapi_ChardevDummy_base(backend->u.pty);
1377 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1378 if (master_fd < 0) {
1379 error_setg_errno(errp, errno, "Failed to create PTY");
1380 return NULL;
1383 close(slave_fd);
1384 qemu_set_nonblock(master_fd);
1386 chr = qemu_chr_alloc(common, errp);
1387 if (!chr) {
1388 close(master_fd);
1389 return NULL;
1392 chr->filename = g_strdup_printf("pty:%s", pty_name);
1393 ret->pty = g_strdup(pty_name);
1394 ret->has_pty = true;
1396 fprintf(stderr, "char device redirected to %s (label %s)\n",
1397 pty_name, id);
1399 s = g_new0(PtyCharDriver, 1);
1400 chr->opaque = s;
1401 chr->chr_write = pty_chr_write;
1402 chr->chr_update_read_handler = pty_chr_update_read_handler;
1403 chr->chr_close = pty_chr_close;
1404 chr->chr_add_watch = pty_chr_add_watch;
1405 chr->explicit_be_open = true;
1407 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1408 s->timer_tag = 0;
1410 return chr;
1413 static void tty_serial_init(int fd, int speed,
1414 int parity, int data_bits, int stop_bits)
1416 struct termios tty;
1417 speed_t spd;
1419 #if 0
1420 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1421 speed, parity, data_bits, stop_bits);
1422 #endif
1423 tcgetattr (fd, &tty);
1425 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1426 speed = speed * 10 / 11;
1427 do {
1428 check_speed(50);
1429 check_speed(75);
1430 check_speed(110);
1431 check_speed(134);
1432 check_speed(150);
1433 check_speed(200);
1434 check_speed(300);
1435 check_speed(600);
1436 check_speed(1200);
1437 check_speed(1800);
1438 check_speed(2400);
1439 check_speed(4800);
1440 check_speed(9600);
1441 check_speed(19200);
1442 check_speed(38400);
1443 /* Non-Posix values follow. They may be unsupported on some systems. */
1444 check_speed(57600);
1445 check_speed(115200);
1446 #ifdef B230400
1447 check_speed(230400);
1448 #endif
1449 #ifdef B460800
1450 check_speed(460800);
1451 #endif
1452 #ifdef B500000
1453 check_speed(500000);
1454 #endif
1455 #ifdef B576000
1456 check_speed(576000);
1457 #endif
1458 #ifdef B921600
1459 check_speed(921600);
1460 #endif
1461 #ifdef B1000000
1462 check_speed(1000000);
1463 #endif
1464 #ifdef B1152000
1465 check_speed(1152000);
1466 #endif
1467 #ifdef B1500000
1468 check_speed(1500000);
1469 #endif
1470 #ifdef B2000000
1471 check_speed(2000000);
1472 #endif
1473 #ifdef B2500000
1474 check_speed(2500000);
1475 #endif
1476 #ifdef B3000000
1477 check_speed(3000000);
1478 #endif
1479 #ifdef B3500000
1480 check_speed(3500000);
1481 #endif
1482 #ifdef B4000000
1483 check_speed(4000000);
1484 #endif
1485 spd = B115200;
1486 } while (0);
1488 cfsetispeed(&tty, spd);
1489 cfsetospeed(&tty, spd);
1491 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1492 |INLCR|IGNCR|ICRNL|IXON);
1493 tty.c_oflag |= OPOST;
1494 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1495 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1496 switch(data_bits) {
1497 default:
1498 case 8:
1499 tty.c_cflag |= CS8;
1500 break;
1501 case 7:
1502 tty.c_cflag |= CS7;
1503 break;
1504 case 6:
1505 tty.c_cflag |= CS6;
1506 break;
1507 case 5:
1508 tty.c_cflag |= CS5;
1509 break;
1511 switch(parity) {
1512 default:
1513 case 'N':
1514 break;
1515 case 'E':
1516 tty.c_cflag |= PARENB;
1517 break;
1518 case 'O':
1519 tty.c_cflag |= PARENB | PARODD;
1520 break;
1522 if (stop_bits == 2)
1523 tty.c_cflag |= CSTOPB;
1525 tcsetattr (fd, TCSANOW, &tty);
1528 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1530 FDCharDriver *s = chr->opaque;
1531 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1533 switch(cmd) {
1534 case CHR_IOCTL_SERIAL_SET_PARAMS:
1536 QEMUSerialSetParams *ssp = arg;
1537 tty_serial_init(fioc->fd,
1538 ssp->speed, ssp->parity,
1539 ssp->data_bits, ssp->stop_bits);
1541 break;
1542 case CHR_IOCTL_SERIAL_SET_BREAK:
1544 int enable = *(int *)arg;
1545 if (enable) {
1546 tcsendbreak(fioc->fd, 1);
1549 break;
1550 case CHR_IOCTL_SERIAL_GET_TIOCM:
1552 int sarg = 0;
1553 int *targ = (int *)arg;
1554 ioctl(fioc->fd, TIOCMGET, &sarg);
1555 *targ = 0;
1556 if (sarg & TIOCM_CTS)
1557 *targ |= CHR_TIOCM_CTS;
1558 if (sarg & TIOCM_CAR)
1559 *targ |= CHR_TIOCM_CAR;
1560 if (sarg & TIOCM_DSR)
1561 *targ |= CHR_TIOCM_DSR;
1562 if (sarg & TIOCM_RI)
1563 *targ |= CHR_TIOCM_RI;
1564 if (sarg & TIOCM_DTR)
1565 *targ |= CHR_TIOCM_DTR;
1566 if (sarg & TIOCM_RTS)
1567 *targ |= CHR_TIOCM_RTS;
1569 break;
1570 case CHR_IOCTL_SERIAL_SET_TIOCM:
1572 int sarg = *(int *)arg;
1573 int targ = 0;
1574 ioctl(fioc->fd, TIOCMGET, &targ);
1575 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1576 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1577 if (sarg & CHR_TIOCM_CTS)
1578 targ |= TIOCM_CTS;
1579 if (sarg & CHR_TIOCM_CAR)
1580 targ |= TIOCM_CAR;
1581 if (sarg & CHR_TIOCM_DSR)
1582 targ |= TIOCM_DSR;
1583 if (sarg & CHR_TIOCM_RI)
1584 targ |= TIOCM_RI;
1585 if (sarg & CHR_TIOCM_DTR)
1586 targ |= TIOCM_DTR;
1587 if (sarg & CHR_TIOCM_RTS)
1588 targ |= TIOCM_RTS;
1589 ioctl(fioc->fd, TIOCMSET, &targ);
1591 break;
1592 default:
1593 return -ENOTSUP;
1595 return 0;
1598 static void qemu_chr_close_tty(CharDriverState *chr)
1600 fd_chr_close(chr);
1603 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1604 ChardevCommon *backend,
1605 Error **errp)
1607 CharDriverState *chr;
1609 tty_serial_init(fd, 115200, 'N', 8, 1);
1610 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1611 chr->chr_ioctl = tty_serial_ioctl;
1612 chr->chr_close = qemu_chr_close_tty;
1613 return chr;
1615 #endif /* __linux__ || __sun__ */
1617 #if defined(__linux__)
1619 #define HAVE_CHARDEV_PARPORT 1
1621 typedef struct {
1622 int fd;
1623 int mode;
1624 } ParallelCharDriver;
1626 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1628 if (s->mode != mode) {
1629 int m = mode;
1630 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1631 return 0;
1632 s->mode = mode;
1634 return 1;
1637 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1639 ParallelCharDriver *drv = chr->opaque;
1640 int fd = drv->fd;
1641 uint8_t b;
1643 switch(cmd) {
1644 case CHR_IOCTL_PP_READ_DATA:
1645 if (ioctl(fd, PPRDATA, &b) < 0)
1646 return -ENOTSUP;
1647 *(uint8_t *)arg = b;
1648 break;
1649 case CHR_IOCTL_PP_WRITE_DATA:
1650 b = *(uint8_t *)arg;
1651 if (ioctl(fd, PPWDATA, &b) < 0)
1652 return -ENOTSUP;
1653 break;
1654 case CHR_IOCTL_PP_READ_CONTROL:
1655 if (ioctl(fd, PPRCONTROL, &b) < 0)
1656 return -ENOTSUP;
1657 /* Linux gives only the lowest bits, and no way to know data
1658 direction! For better compatibility set the fixed upper
1659 bits. */
1660 *(uint8_t *)arg = b | 0xc0;
1661 break;
1662 case CHR_IOCTL_PP_WRITE_CONTROL:
1663 b = *(uint8_t *)arg;
1664 if (ioctl(fd, PPWCONTROL, &b) < 0)
1665 return -ENOTSUP;
1666 break;
1667 case CHR_IOCTL_PP_READ_STATUS:
1668 if (ioctl(fd, PPRSTATUS, &b) < 0)
1669 return -ENOTSUP;
1670 *(uint8_t *)arg = b;
1671 break;
1672 case CHR_IOCTL_PP_DATA_DIR:
1673 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1674 return -ENOTSUP;
1675 break;
1676 case CHR_IOCTL_PP_EPP_READ_ADDR:
1677 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1678 struct ParallelIOArg *parg = arg;
1679 int n = read(fd, parg->buffer, parg->count);
1680 if (n != parg->count) {
1681 return -EIO;
1684 break;
1685 case CHR_IOCTL_PP_EPP_READ:
1686 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1687 struct ParallelIOArg *parg = arg;
1688 int n = read(fd, parg->buffer, parg->count);
1689 if (n != parg->count) {
1690 return -EIO;
1693 break;
1694 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1695 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1696 struct ParallelIOArg *parg = arg;
1697 int n = write(fd, parg->buffer, parg->count);
1698 if (n != parg->count) {
1699 return -EIO;
1702 break;
1703 case CHR_IOCTL_PP_EPP_WRITE:
1704 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1705 struct ParallelIOArg *parg = arg;
1706 int n = write(fd, parg->buffer, parg->count);
1707 if (n != parg->count) {
1708 return -EIO;
1711 break;
1712 default:
1713 return -ENOTSUP;
1715 return 0;
1718 static void pp_close(CharDriverState *chr)
1720 ParallelCharDriver *drv = chr->opaque;
1721 int fd = drv->fd;
1723 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1724 ioctl(fd, PPRELEASE);
1725 close(fd);
1726 g_free(drv);
1727 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1730 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1731 ChardevCommon *backend,
1732 Error **errp)
1734 CharDriverState *chr;
1735 ParallelCharDriver *drv;
1737 if (ioctl(fd, PPCLAIM) < 0) {
1738 error_setg_errno(errp, errno, "not a parallel port");
1739 close(fd);
1740 return NULL;
1743 chr = qemu_chr_alloc(backend, errp);
1744 if (!chr) {
1745 return NULL;
1748 drv = g_new0(ParallelCharDriver, 1);
1749 chr->opaque = drv;
1750 chr->chr_write = null_chr_write;
1751 chr->chr_ioctl = pp_ioctl;
1752 chr->chr_close = pp_close;
1754 drv->fd = fd;
1755 drv->mode = IEEE1284_MODE_COMPAT;
1757 return chr;
1759 #endif /* __linux__ */
1761 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1763 #define HAVE_CHARDEV_PARPORT 1
1765 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1767 int fd = (int)(intptr_t)chr->opaque;
1768 uint8_t b;
1770 switch(cmd) {
1771 case CHR_IOCTL_PP_READ_DATA:
1772 if (ioctl(fd, PPIGDATA, &b) < 0)
1773 return -ENOTSUP;
1774 *(uint8_t *)arg = b;
1775 break;
1776 case CHR_IOCTL_PP_WRITE_DATA:
1777 b = *(uint8_t *)arg;
1778 if (ioctl(fd, PPISDATA, &b) < 0)
1779 return -ENOTSUP;
1780 break;
1781 case CHR_IOCTL_PP_READ_CONTROL:
1782 if (ioctl(fd, PPIGCTRL, &b) < 0)
1783 return -ENOTSUP;
1784 *(uint8_t *)arg = b;
1785 break;
1786 case CHR_IOCTL_PP_WRITE_CONTROL:
1787 b = *(uint8_t *)arg;
1788 if (ioctl(fd, PPISCTRL, &b) < 0)
1789 return -ENOTSUP;
1790 break;
1791 case CHR_IOCTL_PP_READ_STATUS:
1792 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1793 return -ENOTSUP;
1794 *(uint8_t *)arg = b;
1795 break;
1796 default:
1797 return -ENOTSUP;
1799 return 0;
1802 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1803 ChardevBackend *backend,
1804 Error **errp)
1806 CharDriverState *chr;
1808 chr = qemu_chr_alloc(common, errp);
1809 if (!chr) {
1810 return NULL;
1812 chr->opaque = (void *)(intptr_t)fd;
1813 chr->chr_write = null_chr_write;
1814 chr->chr_ioctl = pp_ioctl;
1815 chr->explicit_be_open = true;
1816 return chr;
1818 #endif
1820 #else /* _WIN32 */
1822 #define HAVE_CHARDEV_SERIAL 1
1824 typedef struct {
1825 int max_size;
1826 HANDLE hcom, hrecv, hsend;
1827 OVERLAPPED orecv;
1828 BOOL fpipe;
1829 DWORD len;
1831 /* Protected by the CharDriverState chr_write_lock. */
1832 OVERLAPPED osend;
1833 } WinCharState;
1835 typedef struct {
1836 HANDLE hStdIn;
1837 HANDLE hInputReadyEvent;
1838 HANDLE hInputDoneEvent;
1839 HANDLE hInputThread;
1840 uint8_t win_stdio_buf;
1841 } WinStdioCharState;
1843 #define NSENDBUF 2048
1844 #define NRECVBUF 2048
1845 #define MAXCONNECT 1
1846 #define NTIMEOUT 5000
1848 static int win_chr_poll(void *opaque);
1849 static int win_chr_pipe_poll(void *opaque);
1851 static void win_chr_close(CharDriverState *chr)
1853 WinCharState *s = chr->opaque;
1855 if (s->hsend) {
1856 CloseHandle(s->hsend);
1857 s->hsend = NULL;
1859 if (s->hrecv) {
1860 CloseHandle(s->hrecv);
1861 s->hrecv = NULL;
1863 if (s->hcom) {
1864 CloseHandle(s->hcom);
1865 s->hcom = NULL;
1867 if (s->fpipe)
1868 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1869 else
1870 qemu_del_polling_cb(win_chr_poll, chr);
1872 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1875 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1877 WinCharState *s = chr->opaque;
1878 COMMCONFIG comcfg;
1879 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1880 COMSTAT comstat;
1881 DWORD size;
1882 DWORD err;
1884 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1885 if (!s->hsend) {
1886 error_setg(errp, "Failed CreateEvent");
1887 goto fail;
1889 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1890 if (!s->hrecv) {
1891 error_setg(errp, "Failed CreateEvent");
1892 goto fail;
1895 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1896 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1897 if (s->hcom == INVALID_HANDLE_VALUE) {
1898 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1899 s->hcom = NULL;
1900 goto fail;
1903 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1904 error_setg(errp, "Failed SetupComm");
1905 goto fail;
1908 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1909 size = sizeof(COMMCONFIG);
1910 GetDefaultCommConfig(filename, &comcfg, &size);
1911 comcfg.dcb.DCBlength = sizeof(DCB);
1912 CommConfigDialog(filename, NULL, &comcfg);
1914 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1915 error_setg(errp, "Failed SetCommState");
1916 goto fail;
1919 if (!SetCommMask(s->hcom, EV_ERR)) {
1920 error_setg(errp, "Failed SetCommMask");
1921 goto fail;
1924 cto.ReadIntervalTimeout = MAXDWORD;
1925 if (!SetCommTimeouts(s->hcom, &cto)) {
1926 error_setg(errp, "Failed SetCommTimeouts");
1927 goto fail;
1930 if (!ClearCommError(s->hcom, &err, &comstat)) {
1931 error_setg(errp, "Failed ClearCommError");
1932 goto fail;
1934 qemu_add_polling_cb(win_chr_poll, chr);
1935 return 0;
1937 fail:
1938 win_chr_close(chr);
1939 return -1;
1942 /* Called with chr_write_lock held. */
1943 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1945 WinCharState *s = chr->opaque;
1946 DWORD len, ret, size, err;
1948 len = len1;
1949 ZeroMemory(&s->osend, sizeof(s->osend));
1950 s->osend.hEvent = s->hsend;
1951 while (len > 0) {
1952 if (s->hsend)
1953 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1954 else
1955 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1956 if (!ret) {
1957 err = GetLastError();
1958 if (err == ERROR_IO_PENDING) {
1959 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1960 if (ret) {
1961 buf += size;
1962 len -= size;
1963 } else {
1964 break;
1966 } else {
1967 break;
1969 } else {
1970 buf += size;
1971 len -= size;
1974 return len1 - len;
1977 static int win_chr_read_poll(CharDriverState *chr)
1979 WinCharState *s = chr->opaque;
1981 s->max_size = qemu_chr_be_can_write(chr);
1982 return s->max_size;
1985 static void win_chr_readfile(CharDriverState *chr)
1987 WinCharState *s = chr->opaque;
1988 int ret, err;
1989 uint8_t buf[READ_BUF_LEN];
1990 DWORD size;
1992 ZeroMemory(&s->orecv, sizeof(s->orecv));
1993 s->orecv.hEvent = s->hrecv;
1994 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1995 if (!ret) {
1996 err = GetLastError();
1997 if (err == ERROR_IO_PENDING) {
1998 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2002 if (size > 0) {
2003 qemu_chr_be_write(chr, buf, size);
2007 static void win_chr_read(CharDriverState *chr)
2009 WinCharState *s = chr->opaque;
2011 if (s->len > s->max_size)
2012 s->len = s->max_size;
2013 if (s->len == 0)
2014 return;
2016 win_chr_readfile(chr);
2019 static int win_chr_poll(void *opaque)
2021 CharDriverState *chr = opaque;
2022 WinCharState *s = chr->opaque;
2023 COMSTAT status;
2024 DWORD comerr;
2026 ClearCommError(s->hcom, &comerr, &status);
2027 if (status.cbInQue > 0) {
2028 s->len = status.cbInQue;
2029 win_chr_read_poll(chr);
2030 win_chr_read(chr);
2031 return 1;
2033 return 0;
2036 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2037 ChardevCommon *backend,
2038 Error **errp)
2040 CharDriverState *chr;
2041 WinCharState *s;
2043 chr = qemu_chr_alloc(backend, errp);
2044 if (!chr) {
2045 return NULL;
2047 s = g_new0(WinCharState, 1);
2048 chr->opaque = s;
2049 chr->chr_write = win_chr_write;
2050 chr->chr_close = win_chr_close;
2052 if (win_chr_init(chr, filename, errp) < 0) {
2053 g_free(s);
2054 qemu_chr_free_common(chr);
2055 return NULL;
2057 return chr;
2060 static int win_chr_pipe_poll(void *opaque)
2062 CharDriverState *chr = opaque;
2063 WinCharState *s = chr->opaque;
2064 DWORD size;
2066 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2067 if (size > 0) {
2068 s->len = size;
2069 win_chr_read_poll(chr);
2070 win_chr_read(chr);
2071 return 1;
2073 return 0;
2076 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2077 Error **errp)
2079 WinCharState *s = chr->opaque;
2080 OVERLAPPED ov;
2081 int ret;
2082 DWORD size;
2083 char *openname;
2085 s->fpipe = TRUE;
2087 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2088 if (!s->hsend) {
2089 error_setg(errp, "Failed CreateEvent");
2090 goto fail;
2092 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2093 if (!s->hrecv) {
2094 error_setg(errp, "Failed CreateEvent");
2095 goto fail;
2098 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2099 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2100 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2101 PIPE_WAIT,
2102 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2103 g_free(openname);
2104 if (s->hcom == INVALID_HANDLE_VALUE) {
2105 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2106 s->hcom = NULL;
2107 goto fail;
2110 ZeroMemory(&ov, sizeof(ov));
2111 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2112 ret = ConnectNamedPipe(s->hcom, &ov);
2113 if (ret) {
2114 error_setg(errp, "Failed ConnectNamedPipe");
2115 goto fail;
2118 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2119 if (!ret) {
2120 error_setg(errp, "Failed GetOverlappedResult");
2121 if (ov.hEvent) {
2122 CloseHandle(ov.hEvent);
2123 ov.hEvent = NULL;
2125 goto fail;
2128 if (ov.hEvent) {
2129 CloseHandle(ov.hEvent);
2130 ov.hEvent = NULL;
2132 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2133 return 0;
2135 fail:
2136 win_chr_close(chr);
2137 return -1;
2141 static CharDriverState *qemu_chr_open_pipe(const char *id,
2142 ChardevBackend *backend,
2143 ChardevReturn *ret,
2144 Error **errp)
2146 ChardevHostdev *opts = backend->u.pipe;
2147 const char *filename = opts->device;
2148 CharDriverState *chr;
2149 WinCharState *s;
2150 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.pipe);
2152 chr = qemu_chr_alloc(common, errp);
2153 if (!chr) {
2154 return NULL;
2156 s = g_new0(WinCharState, 1);
2157 chr->opaque = s;
2158 chr->chr_write = win_chr_write;
2159 chr->chr_close = win_chr_close;
2161 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2162 g_free(s);
2163 qemu_chr_free_common(chr);
2164 return NULL;
2166 return chr;
2169 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2170 ChardevCommon *backend,
2171 Error **errp)
2173 CharDriverState *chr;
2174 WinCharState *s;
2176 chr = qemu_chr_alloc(backend, errp);
2177 if (!chr) {
2178 return NULL;
2180 s = g_new0(WinCharState, 1);
2181 s->hcom = fd_out;
2182 chr->opaque = s;
2183 chr->chr_write = win_chr_write;
2184 return chr;
2187 static CharDriverState *qemu_chr_open_win_con(const char *id,
2188 ChardevBackend *backend,
2189 ChardevReturn *ret,
2190 Error **errp)
2192 ChardevCommon *common = qapi_ChardevDummy_base(backend->u.console);
2193 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2194 common, errp);
2197 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2199 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2200 DWORD dwSize;
2201 int len1;
2203 len1 = len;
2205 while (len1 > 0) {
2206 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2207 break;
2209 buf += dwSize;
2210 len1 -= dwSize;
2213 return len - len1;
2216 static void win_stdio_wait_func(void *opaque)
2218 CharDriverState *chr = opaque;
2219 WinStdioCharState *stdio = chr->opaque;
2220 INPUT_RECORD buf[4];
2221 int ret;
2222 DWORD dwSize;
2223 int i;
2225 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2227 if (!ret) {
2228 /* Avoid error storm */
2229 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2230 return;
2233 for (i = 0; i < dwSize; i++) {
2234 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2236 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2237 int j;
2238 if (kev->uChar.AsciiChar != 0) {
2239 for (j = 0; j < kev->wRepeatCount; j++) {
2240 if (qemu_chr_be_can_write(chr)) {
2241 uint8_t c = kev->uChar.AsciiChar;
2242 qemu_chr_be_write(chr, &c, 1);
2250 static DWORD WINAPI win_stdio_thread(LPVOID param)
2252 CharDriverState *chr = param;
2253 WinStdioCharState *stdio = chr->opaque;
2254 int ret;
2255 DWORD dwSize;
2257 while (1) {
2259 /* Wait for one byte */
2260 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2262 /* Exit in case of error, continue if nothing read */
2263 if (!ret) {
2264 break;
2266 if (!dwSize) {
2267 continue;
2270 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2271 if (stdio->win_stdio_buf == '\r') {
2272 continue;
2275 /* Signal the main thread and wait until the byte was eaten */
2276 if (!SetEvent(stdio->hInputReadyEvent)) {
2277 break;
2279 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2280 != WAIT_OBJECT_0) {
2281 break;
2285 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2286 return 0;
2289 static void win_stdio_thread_wait_func(void *opaque)
2291 CharDriverState *chr = opaque;
2292 WinStdioCharState *stdio = chr->opaque;
2294 if (qemu_chr_be_can_write(chr)) {
2295 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2298 SetEvent(stdio->hInputDoneEvent);
2301 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2303 WinStdioCharState *stdio = chr->opaque;
2304 DWORD dwMode = 0;
2306 GetConsoleMode(stdio->hStdIn, &dwMode);
2308 if (echo) {
2309 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2310 } else {
2311 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2315 static void win_stdio_close(CharDriverState *chr)
2317 WinStdioCharState *stdio = chr->opaque;
2319 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2320 CloseHandle(stdio->hInputReadyEvent);
2322 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2323 CloseHandle(stdio->hInputDoneEvent);
2325 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2326 TerminateThread(stdio->hInputThread, 0);
2329 g_free(chr->opaque);
2330 g_free(chr);
2333 static CharDriverState *qemu_chr_open_stdio(const char *id,
2334 ChardevBackend *backend,
2335 ChardevReturn *ret,
2336 Error **errp)
2338 CharDriverState *chr;
2339 WinStdioCharState *stdio;
2340 DWORD dwMode;
2341 int is_console = 0;
2342 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio);
2344 chr = qemu_chr_alloc(common, errp);
2345 if (!chr) {
2346 return NULL;
2348 stdio = g_new0(WinStdioCharState, 1);
2350 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2351 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2352 error_setg(errp, "cannot open stdio: invalid handle");
2353 return NULL;
2356 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2358 chr->opaque = stdio;
2359 chr->chr_write = win_stdio_write;
2360 chr->chr_close = win_stdio_close;
2362 if (is_console) {
2363 if (qemu_add_wait_object(stdio->hStdIn,
2364 win_stdio_wait_func, chr)) {
2365 error_setg(errp, "qemu_add_wait_object: failed");
2366 goto err1;
2368 } else {
2369 DWORD dwId;
2371 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2372 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2373 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2374 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2375 error_setg(errp, "cannot create event");
2376 goto err2;
2378 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2379 win_stdio_thread_wait_func, chr)) {
2380 error_setg(errp, "qemu_add_wait_object: failed");
2381 goto err2;
2383 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2384 chr, 0, &dwId);
2386 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2387 error_setg(errp, "cannot create stdio thread");
2388 goto err3;
2392 dwMode |= ENABLE_LINE_INPUT;
2394 if (is_console) {
2395 /* set the terminal in raw mode */
2396 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2397 dwMode |= ENABLE_PROCESSED_INPUT;
2400 SetConsoleMode(stdio->hStdIn, dwMode);
2402 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2403 qemu_chr_fe_set_echo(chr, false);
2405 return chr;
2407 err3:
2408 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2409 err2:
2410 CloseHandle(stdio->hInputReadyEvent);
2411 CloseHandle(stdio->hInputDoneEvent);
2412 err1:
2413 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2414 return NULL;
2416 #endif /* !_WIN32 */
2419 /***********************************************************/
2420 /* UDP Net console */
2422 typedef struct {
2423 QIOChannel *ioc;
2424 uint8_t buf[READ_BUF_LEN];
2425 int bufcnt;
2426 int bufptr;
2427 int max_size;
2428 } NetCharDriver;
2430 /* Called with chr_write_lock held. */
2431 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2433 NetCharDriver *s = chr->opaque;
2435 return qio_channel_write(
2436 s->ioc, (const char *)buf, len, NULL);
2439 static int udp_chr_read_poll(void *opaque)
2441 CharDriverState *chr = opaque;
2442 NetCharDriver *s = chr->opaque;
2444 s->max_size = qemu_chr_be_can_write(chr);
2446 /* If there were any stray characters in the queue process them
2447 * first
2449 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2450 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2451 s->bufptr++;
2452 s->max_size = qemu_chr_be_can_write(chr);
2454 return s->max_size;
2457 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2459 CharDriverState *chr = opaque;
2460 NetCharDriver *s = chr->opaque;
2461 ssize_t ret;
2463 if (s->max_size == 0) {
2464 return TRUE;
2466 ret = qio_channel_read(
2467 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2468 if (ret <= 0) {
2469 remove_fd_in_watch(chr);
2470 return FALSE;
2472 s->bufcnt = ret;
2474 s->bufptr = 0;
2475 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2476 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2477 s->bufptr++;
2478 s->max_size = qemu_chr_be_can_write(chr);
2481 return TRUE;
2484 static void udp_chr_update_read_handler(CharDriverState *chr)
2486 NetCharDriver *s = chr->opaque;
2488 remove_fd_in_watch(chr);
2489 if (s->ioc) {
2490 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2491 udp_chr_read_poll,
2492 udp_chr_read, chr);
2496 static void udp_chr_close(CharDriverState *chr)
2498 NetCharDriver *s = chr->opaque;
2500 remove_fd_in_watch(chr);
2501 if (s->ioc) {
2502 object_unref(OBJECT(s->ioc));
2504 g_free(s);
2505 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2508 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2509 ChardevCommon *backend,
2510 Error **errp)
2512 CharDriverState *chr = NULL;
2513 NetCharDriver *s = NULL;
2515 chr = qemu_chr_alloc(backend, errp);
2516 if (!chr) {
2517 return NULL;
2519 s = g_new0(NetCharDriver, 1);
2521 s->ioc = QIO_CHANNEL(sioc);
2522 s->bufcnt = 0;
2523 s->bufptr = 0;
2524 chr->opaque = s;
2525 chr->chr_write = udp_chr_write;
2526 chr->chr_update_read_handler = udp_chr_update_read_handler;
2527 chr->chr_close = udp_chr_close;
2528 /* be isn't opened until we get a connection */
2529 chr->explicit_be_open = true;
2530 return chr;
2533 /***********************************************************/
2534 /* TCP Net console */
2536 typedef struct {
2537 QIOChannel *ioc; /* Client I/O channel */
2538 QIOChannelSocket *sioc; /* Client master channel */
2539 QIOChannelSocket *listen_ioc;
2540 guint listen_tag;
2541 QCryptoTLSCreds *tls_creds;
2542 int connected;
2543 int max_size;
2544 int do_telnetopt;
2545 int do_nodelay;
2546 int is_unix;
2547 int *read_msgfds;
2548 size_t read_msgfds_num;
2549 int *write_msgfds;
2550 size_t write_msgfds_num;
2552 SocketAddress *addr;
2553 bool is_listen;
2554 bool is_telnet;
2556 guint reconnect_timer;
2557 int64_t reconnect_time;
2558 bool connect_err_reported;
2559 } TCPCharDriver;
2561 static gboolean socket_reconnect_timeout(gpointer opaque);
2563 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2565 TCPCharDriver *s = chr->opaque;
2566 assert(s->connected == 0);
2567 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2568 socket_reconnect_timeout, chr);
2571 static void check_report_connect_error(CharDriverState *chr,
2572 Error *err)
2574 TCPCharDriver *s = chr->opaque;
2576 if (!s->connect_err_reported) {
2577 error_report("Unable to connect character device %s: %s",
2578 chr->label, error_get_pretty(err));
2579 s->connect_err_reported = true;
2581 qemu_chr_socket_restart_timer(chr);
2584 static gboolean tcp_chr_accept(QIOChannel *chan,
2585 GIOCondition cond,
2586 void *opaque);
2588 /* Called with chr_write_lock held. */
2589 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2591 TCPCharDriver *s = chr->opaque;
2592 if (s->connected) {
2593 int ret = io_channel_send_full(s->ioc, buf, len,
2594 s->write_msgfds,
2595 s->write_msgfds_num);
2597 /* free the written msgfds, no matter what */
2598 if (s->write_msgfds_num) {
2599 g_free(s->write_msgfds);
2600 s->write_msgfds = 0;
2601 s->write_msgfds_num = 0;
2604 return ret;
2605 } else {
2606 /* XXX: indicate an error ? */
2607 return len;
2611 static int tcp_chr_read_poll(void *opaque)
2613 CharDriverState *chr = opaque;
2614 TCPCharDriver *s = chr->opaque;
2615 if (!s->connected)
2616 return 0;
2617 s->max_size = qemu_chr_be_can_write(chr);
2618 return s->max_size;
2621 #define IAC 255
2622 #define IAC_BREAK 243
2623 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2624 TCPCharDriver *s,
2625 uint8_t *buf, int *size)
2627 /* Handle any telnet client's basic IAC options to satisfy char by
2628 * char mode with no echo. All IAC options will be removed from
2629 * the buf and the do_telnetopt variable will be used to track the
2630 * state of the width of the IAC information.
2632 * IAC commands come in sets of 3 bytes with the exception of the
2633 * "IAC BREAK" command and the double IAC.
2636 int i;
2637 int j = 0;
2639 for (i = 0; i < *size; i++) {
2640 if (s->do_telnetopt > 1) {
2641 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2642 /* Double IAC means send an IAC */
2643 if (j != i)
2644 buf[j] = buf[i];
2645 j++;
2646 s->do_telnetopt = 1;
2647 } else {
2648 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2649 /* Handle IAC break commands by sending a serial break */
2650 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2651 s->do_telnetopt++;
2653 s->do_telnetopt++;
2655 if (s->do_telnetopt >= 4) {
2656 s->do_telnetopt = 1;
2658 } else {
2659 if ((unsigned char)buf[i] == IAC) {
2660 s->do_telnetopt = 2;
2661 } else {
2662 if (j != i)
2663 buf[j] = buf[i];
2664 j++;
2668 *size = j;
2671 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2673 TCPCharDriver *s = chr->opaque;
2674 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2676 assert(num <= TCP_MAX_FDS);
2678 if (to_copy) {
2679 int i;
2681 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2683 /* Close unused fds */
2684 for (i = to_copy; i < s->read_msgfds_num; i++) {
2685 close(s->read_msgfds[i]);
2688 g_free(s->read_msgfds);
2689 s->read_msgfds = 0;
2690 s->read_msgfds_num = 0;
2693 return to_copy;
2696 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2698 TCPCharDriver *s = chr->opaque;
2700 if (!qio_channel_has_feature(s->ioc,
2701 QIO_CHANNEL_FEATURE_FD_PASS)) {
2702 return -1;
2704 /* clear old pending fd array */
2705 g_free(s->write_msgfds);
2707 if (num) {
2708 s->write_msgfds = g_new(int, num);
2709 memcpy(s->write_msgfds, fds, num * sizeof(int));
2712 s->write_msgfds_num = num;
2714 return 0;
2717 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2719 TCPCharDriver *s = chr->opaque;
2720 struct iovec iov = { .iov_base = buf, .iov_len = len };
2721 int ret;
2722 size_t i;
2723 int *msgfds = NULL;
2724 size_t msgfds_num = 0;
2726 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2727 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2728 &msgfds, &msgfds_num,
2729 NULL);
2730 } else {
2731 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2732 NULL, NULL,
2733 NULL);
2736 if (msgfds_num) {
2737 /* close and clean read_msgfds */
2738 for (i = 0; i < s->read_msgfds_num; i++) {
2739 close(s->read_msgfds[i]);
2742 if (s->read_msgfds_num) {
2743 g_free(s->read_msgfds);
2746 s->read_msgfds = msgfds;
2747 s->read_msgfds_num = msgfds_num;
2750 for (i = 0; i < s->read_msgfds_num; i++) {
2751 int fd = s->read_msgfds[i];
2752 if (fd < 0) {
2753 continue;
2756 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2757 qemu_set_block(fd);
2759 #ifndef MSG_CMSG_CLOEXEC
2760 qemu_set_cloexec(fd);
2761 #endif
2764 return ret;
2767 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2769 TCPCharDriver *s = chr->opaque;
2770 return qio_channel_create_watch(s->ioc, cond);
2773 static void tcp_chr_disconnect(CharDriverState *chr)
2775 TCPCharDriver *s = chr->opaque;
2777 s->connected = 0;
2778 if (s->listen_ioc) {
2779 s->listen_tag = qio_channel_add_watch(
2780 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
2782 remove_fd_in_watch(chr);
2783 object_unref(OBJECT(s->sioc));
2784 s->sioc = NULL;
2785 object_unref(OBJECT(s->ioc));
2786 s->ioc = NULL;
2787 g_free(chr->filename);
2788 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
2789 s->is_listen, s->is_telnet);
2790 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2791 if (s->reconnect_time) {
2792 qemu_chr_socket_restart_timer(chr);
2796 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2798 CharDriverState *chr = opaque;
2799 TCPCharDriver *s = chr->opaque;
2800 uint8_t buf[READ_BUF_LEN];
2801 int len, size;
2803 if (!s->connected || s->max_size <= 0) {
2804 return TRUE;
2806 len = sizeof(buf);
2807 if (len > s->max_size)
2808 len = s->max_size;
2809 size = tcp_chr_recv(chr, (void *)buf, len);
2810 if (size == 0 || size == -1) {
2811 /* connection closed */
2812 tcp_chr_disconnect(chr);
2813 } else if (size > 0) {
2814 if (s->do_telnetopt)
2815 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2816 if (size > 0)
2817 qemu_chr_be_write(chr, buf, size);
2820 return TRUE;
2823 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2825 TCPCharDriver *s = chr->opaque;
2826 int size;
2828 if (!s->connected) {
2829 return 0;
2832 size = tcp_chr_recv(chr, (void *) buf, len);
2833 if (size == 0) {
2834 /* connection closed */
2835 tcp_chr_disconnect(chr);
2838 return size;
2841 #ifndef _WIN32
2842 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2844 CharDriverState *chr = qemu_chr_open_fd(eventfd, eventfd, NULL, NULL);
2846 if (chr) {
2847 chr->avail_connections = 1;
2850 return chr;
2852 #endif
2854 static void tcp_chr_connect(void *opaque)
2856 CharDriverState *chr = opaque;
2857 TCPCharDriver *s = chr->opaque;
2859 g_free(chr->filename);
2860 chr->filename = sockaddr_to_str(
2861 &s->sioc->localAddr, s->sioc->localAddrLen,
2862 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
2863 s->is_listen, s->is_telnet);
2865 s->connected = 1;
2866 if (s->ioc) {
2867 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2868 tcp_chr_read_poll,
2869 tcp_chr_read, chr);
2871 qemu_chr_be_generic_open(chr);
2874 static void tcp_chr_update_read_handler(CharDriverState *chr)
2876 TCPCharDriver *s = chr->opaque;
2878 remove_fd_in_watch(chr);
2879 if (s->ioc) {
2880 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2881 tcp_chr_read_poll,
2882 tcp_chr_read, chr);
2886 typedef struct {
2887 CharDriverState *chr;
2888 char buf[12];
2889 size_t buflen;
2890 } TCPCharDriverTelnetInit;
2892 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
2893 GIOCondition cond G_GNUC_UNUSED,
2894 gpointer user_data)
2896 TCPCharDriverTelnetInit *init = user_data;
2897 ssize_t ret;
2899 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
2900 if (ret < 0) {
2901 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2902 ret = 0;
2903 } else {
2904 tcp_chr_disconnect(init->chr);
2905 return FALSE;
2908 init->buflen -= ret;
2910 if (init->buflen == 0) {
2911 tcp_chr_connect(init->chr);
2912 return FALSE;
2915 memmove(init->buf, init->buf + ret, init->buflen);
2917 return TRUE;
2920 static void tcp_chr_telnet_init(CharDriverState *chr)
2922 TCPCharDriver *s = chr->opaque;
2923 TCPCharDriverTelnetInit *init =
2924 g_new0(TCPCharDriverTelnetInit, 1);
2925 size_t n = 0;
2927 init->chr = chr;
2928 init->buflen = 12;
2930 #define IACSET(x, a, b, c) \
2931 do { \
2932 x[n++] = a; \
2933 x[n++] = b; \
2934 x[n++] = c; \
2935 } while (0)
2937 /* Prep the telnet negotion to put telnet in binary,
2938 * no echo, single char mode */
2939 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2940 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2941 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2942 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2944 #undef IACSET
2946 qio_channel_add_watch(
2947 s->ioc, G_IO_OUT,
2948 tcp_chr_telnet_init_io,
2949 init, NULL);
2953 static void tcp_chr_tls_handshake(Object *source,
2954 Error *err,
2955 gpointer user_data)
2957 CharDriverState *chr = user_data;
2958 TCPCharDriver *s = chr->opaque;
2960 if (err) {
2961 tcp_chr_disconnect(chr);
2962 } else {
2963 if (s->do_telnetopt) {
2964 tcp_chr_telnet_init(chr);
2965 } else {
2966 tcp_chr_connect(chr);
2972 static void tcp_chr_tls_init(CharDriverState *chr)
2974 TCPCharDriver *s = chr->opaque;
2975 QIOChannelTLS *tioc;
2976 Error *err = NULL;
2978 if (s->is_listen) {
2979 tioc = qio_channel_tls_new_server(
2980 s->ioc, s->tls_creds,
2981 NULL, /* XXX Use an ACL */
2982 &err);
2983 } else {
2984 tioc = qio_channel_tls_new_client(
2985 s->ioc, s->tls_creds,
2986 s->addr->u.inet->host,
2987 &err);
2989 if (tioc == NULL) {
2990 error_free(err);
2991 tcp_chr_disconnect(chr);
2993 object_unref(OBJECT(s->ioc));
2994 s->ioc = QIO_CHANNEL(tioc);
2996 qio_channel_tls_handshake(tioc,
2997 tcp_chr_tls_handshake,
2998 chr,
2999 NULL);
3003 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3005 TCPCharDriver *s = chr->opaque;
3006 if (s->ioc != NULL) {
3007 return -1;
3010 s->ioc = QIO_CHANNEL(sioc);
3011 object_ref(OBJECT(sioc));
3012 s->sioc = sioc;
3013 object_ref(OBJECT(sioc));
3015 if (s->do_nodelay) {
3016 qio_channel_set_delay(s->ioc, false);
3018 if (s->listen_tag) {
3019 g_source_remove(s->listen_tag);
3020 s->listen_tag = 0;
3023 if (s->tls_creds) {
3024 tcp_chr_tls_init(chr);
3025 } else {
3026 if (s->do_telnetopt) {
3027 tcp_chr_telnet_init(chr);
3028 } else {
3029 tcp_chr_connect(chr);
3033 return 0;
3037 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3039 int ret;
3040 QIOChannelSocket *sioc;
3042 sioc = qio_channel_socket_new_fd(fd, NULL);
3043 if (!sioc) {
3044 return -1;
3046 qio_channel_set_blocking(QIO_CHANNEL(sioc), false, NULL);
3047 ret = tcp_chr_new_client(chr, sioc);
3048 object_unref(OBJECT(sioc));
3049 return ret;
3052 static gboolean tcp_chr_accept(QIOChannel *channel,
3053 GIOCondition cond,
3054 void *opaque)
3056 CharDriverState *chr = opaque;
3057 QIOChannelSocket *sioc;
3059 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3060 NULL);
3061 if (!sioc) {
3062 return TRUE;
3065 tcp_chr_new_client(chr, sioc);
3067 object_unref(OBJECT(sioc));
3069 return TRUE;
3072 static void tcp_chr_close(CharDriverState *chr)
3074 TCPCharDriver *s = chr->opaque;
3075 int i;
3077 if (s->reconnect_timer) {
3078 g_source_remove(s->reconnect_timer);
3079 s->reconnect_timer = 0;
3081 qapi_free_SocketAddress(s->addr);
3082 remove_fd_in_watch(chr);
3083 if (s->ioc) {
3084 object_unref(OBJECT(s->ioc));
3086 if (s->listen_tag) {
3087 g_source_remove(s->listen_tag);
3088 s->listen_tag = 0;
3090 if (s->listen_ioc) {
3091 object_unref(OBJECT(s->listen_ioc));
3093 if (s->read_msgfds_num) {
3094 for (i = 0; i < s->read_msgfds_num; i++) {
3095 close(s->read_msgfds[i]);
3097 g_free(s->read_msgfds);
3099 if (s->tls_creds) {
3100 object_unref(OBJECT(s->tls_creds));
3102 if (s->write_msgfds_num) {
3103 g_free(s->write_msgfds);
3105 g_free(s);
3106 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3109 static void qemu_chr_finish_socket_connection(CharDriverState *chr,
3110 QIOChannelSocket *sioc)
3112 TCPCharDriver *s = chr->opaque;
3114 if (s->is_listen) {
3115 s->listen_ioc = sioc;
3116 s->listen_tag = qio_channel_add_watch(
3117 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
3118 } else {
3119 tcp_chr_new_client(chr, sioc);
3120 object_unref(OBJECT(sioc));
3124 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3126 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3127 CharDriverState *chr = opaque;
3128 TCPCharDriver *s = chr->opaque;
3130 if (err) {
3131 check_report_connect_error(chr, err);
3132 object_unref(src);
3133 return;
3136 s->connect_err_reported = false;
3137 qemu_chr_finish_socket_connection(chr, sioc);
3140 static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp)
3142 TCPCharDriver *s = chr->opaque;
3143 QIOChannelSocket *sioc = qio_channel_socket_new();
3145 if (s->is_listen) {
3146 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
3147 goto fail;
3149 qemu_chr_finish_socket_connection(chr, sioc);
3150 } else if (s->reconnect_time) {
3151 qio_channel_socket_connect_async(sioc, s->addr,
3152 qemu_chr_socket_connected,
3153 chr, NULL);
3154 } else {
3155 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3156 goto fail;
3158 qemu_chr_finish_socket_connection(chr, sioc);
3161 return true;
3163 fail:
3164 object_unref(OBJECT(sioc));
3165 return false;
3168 /*********************************************************/
3169 /* Ring buffer chardev */
3171 typedef struct {
3172 size_t size;
3173 size_t prod;
3174 size_t cons;
3175 uint8_t *cbuf;
3176 } RingBufCharDriver;
3178 static size_t ringbuf_count(const CharDriverState *chr)
3180 const RingBufCharDriver *d = chr->opaque;
3182 return d->prod - d->cons;
3185 /* Called with chr_write_lock held. */
3186 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3188 RingBufCharDriver *d = chr->opaque;
3189 int i;
3191 if (!buf || (len < 0)) {
3192 return -1;
3195 for (i = 0; i < len; i++ ) {
3196 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3197 if (d->prod - d->cons > d->size) {
3198 d->cons = d->prod - d->size;
3202 return 0;
3205 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3207 RingBufCharDriver *d = chr->opaque;
3208 int i;
3210 qemu_mutex_lock(&chr->chr_write_lock);
3211 for (i = 0; i < len && d->cons != d->prod; i++) {
3212 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3214 qemu_mutex_unlock(&chr->chr_write_lock);
3216 return i;
3219 static void ringbuf_chr_close(struct CharDriverState *chr)
3221 RingBufCharDriver *d = chr->opaque;
3223 g_free(d->cbuf);
3224 g_free(d);
3225 chr->opaque = NULL;
3228 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3229 ChardevBackend *backend,
3230 ChardevReturn *ret,
3231 Error **errp)
3233 ChardevRingbuf *opts = backend->u.ringbuf;
3234 ChardevCommon *common = qapi_ChardevRingbuf_base(backend->u.ringbuf);
3235 CharDriverState *chr;
3236 RingBufCharDriver *d;
3238 chr = qemu_chr_alloc(common, errp);
3239 if (!chr) {
3240 return NULL;
3242 d = g_malloc(sizeof(*d));
3244 d->size = opts->has_size ? opts->size : 65536;
3246 /* The size must be power of 2 */
3247 if (d->size & (d->size - 1)) {
3248 error_setg(errp, "size of ringbuf chardev must be power of two");
3249 goto fail;
3252 d->prod = 0;
3253 d->cons = 0;
3254 d->cbuf = g_malloc0(d->size);
3256 chr->opaque = d;
3257 chr->chr_write = ringbuf_chr_write;
3258 chr->chr_close = ringbuf_chr_close;
3260 return chr;
3262 fail:
3263 g_free(d);
3264 qemu_chr_free_common(chr);
3265 return NULL;
3268 bool chr_is_ringbuf(const CharDriverState *chr)
3270 return chr->chr_write == ringbuf_chr_write;
3273 void qmp_ringbuf_write(const char *device, const char *data,
3274 bool has_format, enum DataFormat format,
3275 Error **errp)
3277 CharDriverState *chr;
3278 const uint8_t *write_data;
3279 int ret;
3280 gsize write_count;
3282 chr = qemu_chr_find(device);
3283 if (!chr) {
3284 error_setg(errp, "Device '%s' not found", device);
3285 return;
3288 if (!chr_is_ringbuf(chr)) {
3289 error_setg(errp,"%s is not a ringbuf device", device);
3290 return;
3293 if (has_format && (format == DATA_FORMAT_BASE64)) {
3294 write_data = qbase64_decode(data, -1,
3295 &write_count,
3296 errp);
3297 if (!write_data) {
3298 return;
3300 } else {
3301 write_data = (uint8_t *)data;
3302 write_count = strlen(data);
3305 ret = ringbuf_chr_write(chr, write_data, write_count);
3307 if (write_data != (uint8_t *)data) {
3308 g_free((void *)write_data);
3311 if (ret < 0) {
3312 error_setg(errp, "Failed to write to device %s", device);
3313 return;
3317 char *qmp_ringbuf_read(const char *device, int64_t size,
3318 bool has_format, enum DataFormat format,
3319 Error **errp)
3321 CharDriverState *chr;
3322 uint8_t *read_data;
3323 size_t count;
3324 char *data;
3326 chr = qemu_chr_find(device);
3327 if (!chr) {
3328 error_setg(errp, "Device '%s' not found", device);
3329 return NULL;
3332 if (!chr_is_ringbuf(chr)) {
3333 error_setg(errp,"%s is not a ringbuf device", device);
3334 return NULL;
3337 if (size <= 0) {
3338 error_setg(errp, "size must be greater than zero");
3339 return NULL;
3342 count = ringbuf_count(chr);
3343 size = size > count ? count : size;
3344 read_data = g_malloc(size + 1);
3346 ringbuf_chr_read(chr, read_data, size);
3348 if (has_format && (format == DATA_FORMAT_BASE64)) {
3349 data = g_base64_encode(read_data, size);
3350 g_free(read_data);
3351 } else {
3353 * FIXME should read only complete, valid UTF-8 characters up
3354 * to @size bytes. Invalid sequences should be replaced by a
3355 * suitable replacement character. Except when (and only
3356 * when) ring buffer lost characters since last read, initial
3357 * continuation characters should be dropped.
3359 read_data[size] = 0;
3360 data = (char *)read_data;
3363 return data;
3366 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3368 char host[65], port[33], width[8], height[8];
3369 int pos;
3370 const char *p;
3371 QemuOpts *opts;
3372 Error *local_err = NULL;
3374 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3375 if (local_err) {
3376 error_report_err(local_err);
3377 return NULL;
3380 if (strstart(filename, "mon:", &p)) {
3381 filename = p;
3382 qemu_opt_set(opts, "mux", "on", &error_abort);
3383 if (strcmp(filename, "stdio") == 0) {
3384 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3385 * but pass it to the guest. Handle this only for compat syntax,
3386 * for -chardev syntax we have special option for this.
3387 * This is what -nographic did, redirecting+muxing serial+monitor
3388 * to stdio causing Ctrl+C to be passed to guest. */
3389 qemu_opt_set(opts, "signal", "off", &error_abort);
3393 if (strcmp(filename, "null") == 0 ||
3394 strcmp(filename, "pty") == 0 ||
3395 strcmp(filename, "msmouse") == 0 ||
3396 strcmp(filename, "braille") == 0 ||
3397 strcmp(filename, "testdev") == 0 ||
3398 strcmp(filename, "stdio") == 0) {
3399 qemu_opt_set(opts, "backend", filename, &error_abort);
3400 return opts;
3402 if (strstart(filename, "vc", &p)) {
3403 qemu_opt_set(opts, "backend", "vc", &error_abort);
3404 if (*p == ':') {
3405 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3406 /* pixels */
3407 qemu_opt_set(opts, "width", width, &error_abort);
3408 qemu_opt_set(opts, "height", height, &error_abort);
3409 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3410 /* chars */
3411 qemu_opt_set(opts, "cols", width, &error_abort);
3412 qemu_opt_set(opts, "rows", height, &error_abort);
3413 } else {
3414 goto fail;
3417 return opts;
3419 if (strcmp(filename, "con:") == 0) {
3420 qemu_opt_set(opts, "backend", "console", &error_abort);
3421 return opts;
3423 if (strstart(filename, "COM", NULL)) {
3424 qemu_opt_set(opts, "backend", "serial", &error_abort);
3425 qemu_opt_set(opts, "path", filename, &error_abort);
3426 return opts;
3428 if (strstart(filename, "file:", &p)) {
3429 qemu_opt_set(opts, "backend", "file", &error_abort);
3430 qemu_opt_set(opts, "path", p, &error_abort);
3431 return opts;
3433 if (strstart(filename, "pipe:", &p)) {
3434 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3435 qemu_opt_set(opts, "path", p, &error_abort);
3436 return opts;
3438 if (strstart(filename, "tcp:", &p) ||
3439 strstart(filename, "telnet:", &p)) {
3440 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3441 host[0] = 0;
3442 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3443 goto fail;
3445 qemu_opt_set(opts, "backend", "socket", &error_abort);
3446 qemu_opt_set(opts, "host", host, &error_abort);
3447 qemu_opt_set(opts, "port", port, &error_abort);
3448 if (p[pos] == ',') {
3449 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3450 if (local_err) {
3451 error_report_err(local_err);
3452 goto fail;
3455 if (strstart(filename, "telnet:", &p))
3456 qemu_opt_set(opts, "telnet", "on", &error_abort);
3457 return opts;
3459 if (strstart(filename, "udp:", &p)) {
3460 qemu_opt_set(opts, "backend", "udp", &error_abort);
3461 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3462 host[0] = 0;
3463 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3464 goto fail;
3467 qemu_opt_set(opts, "host", host, &error_abort);
3468 qemu_opt_set(opts, "port", port, &error_abort);
3469 if (p[pos] == '@') {
3470 p += pos + 1;
3471 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3472 host[0] = 0;
3473 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3474 goto fail;
3477 qemu_opt_set(opts, "localaddr", host, &error_abort);
3478 qemu_opt_set(opts, "localport", port, &error_abort);
3480 return opts;
3482 if (strstart(filename, "unix:", &p)) {
3483 qemu_opt_set(opts, "backend", "socket", &error_abort);
3484 qemu_opts_do_parse(opts, p, "path", &local_err);
3485 if (local_err) {
3486 error_report_err(local_err);
3487 goto fail;
3489 return opts;
3491 if (strstart(filename, "/dev/parport", NULL) ||
3492 strstart(filename, "/dev/ppi", NULL)) {
3493 qemu_opt_set(opts, "backend", "parport", &error_abort);
3494 qemu_opt_set(opts, "path", filename, &error_abort);
3495 return opts;
3497 if (strstart(filename, "/dev/", NULL)) {
3498 qemu_opt_set(opts, "backend", "tty", &error_abort);
3499 qemu_opt_set(opts, "path", filename, &error_abort);
3500 return opts;
3503 fail:
3504 qemu_opts_del(opts);
3505 return NULL;
3508 static void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3510 const char *logfile = qemu_opt_get(opts, "logfile");
3512 backend->has_logfile = logfile != NULL;
3513 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3515 backend->has_logappend = true;
3516 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3520 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3521 Error **errp)
3523 const char *path = qemu_opt_get(opts, "path");
3525 if (path == NULL) {
3526 error_setg(errp, "chardev: file: no filename given");
3527 return;
3529 backend->u.file = g_new0(ChardevFile, 1);
3530 qemu_chr_parse_common(opts, qapi_ChardevFile_base(backend->u.file));
3531 backend->u.file->out = g_strdup(path);
3533 backend->u.file->has_append = true;
3534 backend->u.file->append = qemu_opt_get_bool(opts, "append", false);
3537 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3538 Error **errp)
3540 backend->u.stdio = g_new0(ChardevStdio, 1);
3541 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(backend->u.stdio));
3542 backend->u.stdio->has_signal = true;
3543 backend->u.stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3546 #ifdef HAVE_CHARDEV_SERIAL
3547 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3548 Error **errp)
3550 const char *device = qemu_opt_get(opts, "path");
3552 if (device == NULL) {
3553 error_setg(errp, "chardev: serial/tty: no device path given");
3554 return;
3556 backend->u.serial = g_new0(ChardevHostdev, 1);
3557 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.serial));
3558 backend->u.serial->device = g_strdup(device);
3560 #endif
3562 #ifdef HAVE_CHARDEV_PARPORT
3563 static void qemu_chr_parse_parallel(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: parallel: no device path given");
3570 return;
3572 backend->u.parallel = g_new0(ChardevHostdev, 1);
3573 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.parallel));
3574 backend->u.parallel->device = g_strdup(device);
3576 #endif
3578 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3579 Error **errp)
3581 const char *device = qemu_opt_get(opts, "path");
3583 if (device == NULL) {
3584 error_setg(errp, "chardev: pipe: no device path given");
3585 return;
3587 backend->u.pipe = g_new0(ChardevHostdev, 1);
3588 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.pipe));
3589 backend->u.pipe->device = g_strdup(device);
3592 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3593 Error **errp)
3595 int val;
3597 backend->u.ringbuf = g_new0(ChardevRingbuf, 1);
3598 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(backend->u.ringbuf));
3600 val = qemu_opt_get_size(opts, "size", 0);
3601 if (val != 0) {
3602 backend->u.ringbuf->has_size = true;
3603 backend->u.ringbuf->size = val;
3607 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3608 Error **errp)
3610 const char *chardev = qemu_opt_get(opts, "chardev");
3612 if (chardev == NULL) {
3613 error_setg(errp, "chardev: mux: no chardev given");
3614 return;
3616 backend->u.mux = g_new0(ChardevMux, 1);
3617 qemu_chr_parse_common(opts, qapi_ChardevMux_base(backend->u.mux));
3618 backend->u.mux->chardev = g_strdup(chardev);
3621 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3622 Error **errp)
3624 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3625 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3626 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3627 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3628 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3629 const char *path = qemu_opt_get(opts, "path");
3630 const char *host = qemu_opt_get(opts, "host");
3631 const char *port = qemu_opt_get(opts, "port");
3632 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3633 SocketAddress *addr;
3635 if (!path) {
3636 if (!host) {
3637 error_setg(errp, "chardev: socket: no host given");
3638 return;
3640 if (!port) {
3641 error_setg(errp, "chardev: socket: no port given");
3642 return;
3644 } else {
3645 if (tls_creds) {
3646 error_setg(errp, "TLS can only be used over TCP socket");
3647 return;
3651 backend->u.socket = g_new0(ChardevSocket, 1);
3652 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(backend->u.socket));
3654 backend->u.socket->has_nodelay = true;
3655 backend->u.socket->nodelay = do_nodelay;
3656 backend->u.socket->has_server = true;
3657 backend->u.socket->server = is_listen;
3658 backend->u.socket->has_telnet = true;
3659 backend->u.socket->telnet = is_telnet;
3660 backend->u.socket->has_wait = true;
3661 backend->u.socket->wait = is_waitconnect;
3662 backend->u.socket->has_reconnect = true;
3663 backend->u.socket->reconnect = reconnect;
3664 backend->u.socket->tls_creds = g_strdup(tls_creds);
3666 addr = g_new0(SocketAddress, 1);
3667 if (path) {
3668 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3669 addr->u.q_unix = g_new0(UnixSocketAddress, 1);
3670 addr->u.q_unix->path = g_strdup(path);
3671 } else {
3672 addr->type = SOCKET_ADDRESS_KIND_INET;
3673 addr->u.inet = g_new0(InetSocketAddress, 1);
3674 addr->u.inet->host = g_strdup(host);
3675 addr->u.inet->port = g_strdup(port);
3676 addr->u.inet->has_to = qemu_opt_get(opts, "to");
3677 addr->u.inet->to = qemu_opt_get_number(opts, "to", 0);
3678 addr->u.inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3679 addr->u.inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3680 addr->u.inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3681 addr->u.inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3683 backend->u.socket->addr = addr;
3686 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3687 Error **errp)
3689 const char *host = qemu_opt_get(opts, "host");
3690 const char *port = qemu_opt_get(opts, "port");
3691 const char *localaddr = qemu_opt_get(opts, "localaddr");
3692 const char *localport = qemu_opt_get(opts, "localport");
3693 bool has_local = false;
3694 SocketAddress *addr;
3696 if (host == NULL || strlen(host) == 0) {
3697 host = "localhost";
3699 if (port == NULL || strlen(port) == 0) {
3700 error_setg(errp, "chardev: udp: remote port not specified");
3701 return;
3703 if (localport == NULL || strlen(localport) == 0) {
3704 localport = "0";
3705 } else {
3706 has_local = true;
3708 if (localaddr == NULL || strlen(localaddr) == 0) {
3709 localaddr = "";
3710 } else {
3711 has_local = true;
3714 backend->u.udp = g_new0(ChardevUdp, 1);
3715 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(backend->u.udp));
3717 addr = g_new0(SocketAddress, 1);
3718 addr->type = SOCKET_ADDRESS_KIND_INET;
3719 addr->u.inet = g_new0(InetSocketAddress, 1);
3720 addr->u.inet->host = g_strdup(host);
3721 addr->u.inet->port = g_strdup(port);
3722 addr->u.inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3723 addr->u.inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3724 addr->u.inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3725 addr->u.inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3726 backend->u.udp->remote = addr;
3728 if (has_local) {
3729 backend->u.udp->has_local = true;
3730 addr = g_new0(SocketAddress, 1);
3731 addr->type = SOCKET_ADDRESS_KIND_INET;
3732 addr->u.inet = g_new0(InetSocketAddress, 1);
3733 addr->u.inet->host = g_strdup(localaddr);
3734 addr->u.inet->port = g_strdup(localport);
3735 backend->u.udp->local = addr;
3739 typedef struct CharDriver {
3740 const char *name;
3741 ChardevBackendKind kind;
3742 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3743 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3744 ChardevReturn *ret, Error **errp);
3745 } CharDriver;
3747 static GSList *backends;
3749 void register_char_driver(const char *name, ChardevBackendKind kind,
3750 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3751 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3752 ChardevReturn *ret, Error **errp))
3754 CharDriver *s;
3756 s = g_malloc0(sizeof(*s));
3757 s->name = g_strdup(name);
3758 s->kind = kind;
3759 s->parse = parse;
3760 s->create = create;
3762 backends = g_slist_append(backends, s);
3765 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3766 void (*init)(struct CharDriverState *s),
3767 Error **errp)
3769 Error *local_err = NULL;
3770 CharDriver *cd;
3771 CharDriverState *chr;
3772 GSList *i;
3773 ChardevReturn *ret = NULL;
3774 ChardevBackend *backend;
3775 const char *id = qemu_opts_id(opts);
3776 char *bid = NULL;
3778 if (id == NULL) {
3779 error_setg(errp, "chardev: no id specified");
3780 goto err;
3783 if (qemu_opt_get(opts, "backend") == NULL) {
3784 error_setg(errp, "chardev: \"%s\" missing backend",
3785 qemu_opts_id(opts));
3786 goto err;
3788 for (i = backends; i; i = i->next) {
3789 cd = i->data;
3791 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3792 break;
3795 if (i == NULL) {
3796 error_setg(errp, "chardev: backend \"%s\" not found",
3797 qemu_opt_get(opts, "backend"));
3798 goto err;
3801 backend = g_new0(ChardevBackend, 1);
3803 if (qemu_opt_get_bool(opts, "mux", 0)) {
3804 bid = g_strdup_printf("%s-base", id);
3807 chr = NULL;
3808 backend->type = cd->kind;
3809 if (cd->parse) {
3810 cd->parse(opts, backend, &local_err);
3811 if (local_err) {
3812 error_propagate(errp, local_err);
3813 goto qapi_out;
3815 } else {
3816 ChardevCommon *cc = g_new0(ChardevCommon, 1);
3817 qemu_chr_parse_common(opts, cc);
3818 backend->u.data = cc;
3821 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3822 if (!ret) {
3823 goto qapi_out;
3826 if (bid) {
3827 qapi_free_ChardevBackend(backend);
3828 qapi_free_ChardevReturn(ret);
3829 backend = g_new0(ChardevBackend, 1);
3830 backend->u.mux = g_new0(ChardevMux, 1);
3831 backend->type = CHARDEV_BACKEND_KIND_MUX;
3832 backend->u.mux->chardev = g_strdup(bid);
3833 ret = qmp_chardev_add(id, backend, errp);
3834 if (!ret) {
3835 chr = qemu_chr_find(bid);
3836 qemu_chr_delete(chr);
3837 chr = NULL;
3838 goto qapi_out;
3842 chr = qemu_chr_find(id);
3843 chr->opts = opts;
3845 qapi_out:
3846 qapi_free_ChardevBackend(backend);
3847 qapi_free_ChardevReturn(ret);
3848 g_free(bid);
3849 return chr;
3851 err:
3852 qemu_opts_del(opts);
3853 return NULL;
3856 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3858 const char *p;
3859 CharDriverState *chr;
3860 QemuOpts *opts;
3861 Error *err = NULL;
3863 if (strstart(filename, "chardev:", &p)) {
3864 return qemu_chr_find(p);
3867 opts = qemu_chr_parse_compat(label, filename);
3868 if (!opts)
3869 return NULL;
3871 chr = qemu_chr_new_from_opts(opts, init, &err);
3872 if (err) {
3873 error_report_err(err);
3875 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3876 qemu_chr_fe_claim_no_fail(chr);
3877 monitor_init(chr, MONITOR_USE_READLINE);
3879 return chr;
3882 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3884 if (chr->chr_set_echo) {
3885 chr->chr_set_echo(chr, echo);
3889 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3891 if (chr->fe_open == fe_open) {
3892 return;
3894 chr->fe_open = fe_open;
3895 if (chr->chr_set_fe_open) {
3896 chr->chr_set_fe_open(chr, fe_open);
3900 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3902 if (chr->chr_fe_event) {
3903 chr->chr_fe_event(chr, event);
3907 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3908 GIOFunc func, void *user_data)
3910 GSource *src;
3911 guint tag;
3913 if (s->chr_add_watch == NULL) {
3914 return -ENOSYS;
3917 src = s->chr_add_watch(s, cond);
3918 if (!src) {
3919 return -EINVAL;
3922 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3923 tag = g_source_attach(src, NULL);
3924 g_source_unref(src);
3926 return tag;
3929 int qemu_chr_fe_claim(CharDriverState *s)
3931 if (s->avail_connections < 1) {
3932 return -1;
3934 s->avail_connections--;
3935 return 0;
3938 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3940 if (qemu_chr_fe_claim(s) != 0) {
3941 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3942 __func__, s->label);
3943 exit(1);
3947 void qemu_chr_fe_release(CharDriverState *s)
3949 s->avail_connections++;
3952 static void qemu_chr_free_common(CharDriverState *chr)
3954 g_free(chr->filename);
3955 g_free(chr->label);
3956 qemu_opts_del(chr->opts);
3957 if (chr->logfd != -1) {
3958 close(chr->logfd);
3960 qemu_mutex_destroy(&chr->chr_write_lock);
3961 g_free(chr);
3964 void qemu_chr_free(CharDriverState *chr)
3966 if (chr->chr_close) {
3967 chr->chr_close(chr);
3969 qemu_chr_free_common(chr);
3972 void qemu_chr_delete(CharDriverState *chr)
3974 QTAILQ_REMOVE(&chardevs, chr, next);
3975 qemu_chr_free(chr);
3978 ChardevInfoList *qmp_query_chardev(Error **errp)
3980 ChardevInfoList *chr_list = NULL;
3981 CharDriverState *chr;
3983 QTAILQ_FOREACH(chr, &chardevs, next) {
3984 ChardevInfoList *info = g_malloc0(sizeof(*info));
3985 info->value = g_malloc0(sizeof(*info->value));
3986 info->value->label = g_strdup(chr->label);
3987 info->value->filename = g_strdup(chr->filename);
3988 info->value->frontend_open = chr->fe_open;
3990 info->next = chr_list;
3991 chr_list = info;
3994 return chr_list;
3997 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
3999 ChardevBackendInfoList *backend_list = NULL;
4000 CharDriver *c = NULL;
4001 GSList *i = NULL;
4003 for (i = backends; i; i = i->next) {
4004 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4005 c = i->data;
4006 info->value = g_malloc0(sizeof(*info->value));
4007 info->value->name = g_strdup(c->name);
4009 info->next = backend_list;
4010 backend_list = info;
4013 return backend_list;
4016 CharDriverState *qemu_chr_find(const char *name)
4018 CharDriverState *chr;
4020 QTAILQ_FOREACH(chr, &chardevs, next) {
4021 if (strcmp(chr->label, name) != 0)
4022 continue;
4023 return chr;
4025 return NULL;
4028 /* Get a character (serial) device interface. */
4029 CharDriverState *qemu_char_get_next_serial(void)
4031 static int next_serial;
4032 CharDriverState *chr;
4034 /* FIXME: This function needs to go away: use chardev properties! */
4036 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
4037 chr = serial_hds[next_serial++];
4038 qemu_chr_fe_claim_no_fail(chr);
4039 return chr;
4041 return NULL;
4044 QemuOptsList qemu_chardev_opts = {
4045 .name = "chardev",
4046 .implied_opt_name = "backend",
4047 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4048 .desc = {
4050 .name = "backend",
4051 .type = QEMU_OPT_STRING,
4053 .name = "path",
4054 .type = QEMU_OPT_STRING,
4056 .name = "host",
4057 .type = QEMU_OPT_STRING,
4059 .name = "port",
4060 .type = QEMU_OPT_STRING,
4062 .name = "localaddr",
4063 .type = QEMU_OPT_STRING,
4065 .name = "localport",
4066 .type = QEMU_OPT_STRING,
4068 .name = "to",
4069 .type = QEMU_OPT_NUMBER,
4071 .name = "ipv4",
4072 .type = QEMU_OPT_BOOL,
4074 .name = "ipv6",
4075 .type = QEMU_OPT_BOOL,
4077 .name = "wait",
4078 .type = QEMU_OPT_BOOL,
4080 .name = "server",
4081 .type = QEMU_OPT_BOOL,
4083 .name = "delay",
4084 .type = QEMU_OPT_BOOL,
4086 .name = "reconnect",
4087 .type = QEMU_OPT_NUMBER,
4089 .name = "telnet",
4090 .type = QEMU_OPT_BOOL,
4092 .name = "tls-creds",
4093 .type = QEMU_OPT_STRING,
4095 .name = "width",
4096 .type = QEMU_OPT_NUMBER,
4098 .name = "height",
4099 .type = QEMU_OPT_NUMBER,
4101 .name = "cols",
4102 .type = QEMU_OPT_NUMBER,
4104 .name = "rows",
4105 .type = QEMU_OPT_NUMBER,
4107 .name = "mux",
4108 .type = QEMU_OPT_BOOL,
4110 .name = "signal",
4111 .type = QEMU_OPT_BOOL,
4113 .name = "name",
4114 .type = QEMU_OPT_STRING,
4116 .name = "debug",
4117 .type = QEMU_OPT_NUMBER,
4119 .name = "size",
4120 .type = QEMU_OPT_SIZE,
4122 .name = "chardev",
4123 .type = QEMU_OPT_STRING,
4125 .name = "append",
4126 .type = QEMU_OPT_BOOL,
4128 .name = "logfile",
4129 .type = QEMU_OPT_STRING,
4131 .name = "logappend",
4132 .type = QEMU_OPT_BOOL,
4134 { /* end of list */ }
4138 #ifdef _WIN32
4140 static CharDriverState *qmp_chardev_open_file(const char *id,
4141 ChardevBackend *backend,
4142 ChardevReturn *ret,
4143 Error **errp)
4145 ChardevFile *file = backend->u.file;
4146 ChardevCommon *common = qapi_ChardevFile_base(backend->u.file);
4147 HANDLE out;
4149 if (file->has_in) {
4150 error_setg(errp, "input file not supported");
4151 return NULL;
4154 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
4155 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
4156 if (out == INVALID_HANDLE_VALUE) {
4157 error_setg(errp, "open %s failed", file->out);
4158 return NULL;
4160 return qemu_chr_open_win_file(out, common, errp);
4163 static CharDriverState *qmp_chardev_open_serial(const char *id,
4164 ChardevBackend *backend,
4165 ChardevReturn *ret,
4166 Error **errp)
4168 ChardevHostdev *serial = backend->u.serial;
4169 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.serial);
4170 return qemu_chr_open_win_path(serial->device, common, errp);
4173 #else /* WIN32 */
4175 static int qmp_chardev_open_file_source(char *src, int flags,
4176 Error **errp)
4178 int fd = -1;
4180 TFR(fd = qemu_open(src, flags, 0666));
4181 if (fd == -1) {
4182 error_setg_file_open(errp, errno, src);
4184 return fd;
4187 static CharDriverState *qmp_chardev_open_file(const char *id,
4188 ChardevBackend *backend,
4189 ChardevReturn *ret,
4190 Error **errp)
4192 ChardevFile *file = backend->u.file;
4193 ChardevCommon *common = qapi_ChardevFile_base(backend->u.file);
4194 int flags, in = -1, out;
4196 flags = O_WRONLY | O_CREAT | O_BINARY;
4197 if (file->has_append && file->append) {
4198 flags |= O_APPEND;
4199 } else {
4200 flags |= O_TRUNC;
4203 out = qmp_chardev_open_file_source(file->out, flags, errp);
4204 if (out < 0) {
4205 return NULL;
4208 if (file->has_in) {
4209 flags = O_RDONLY;
4210 in = qmp_chardev_open_file_source(file->in, flags, errp);
4211 if (in < 0) {
4212 qemu_close(out);
4213 return NULL;
4217 return qemu_chr_open_fd(in, out, common, errp);
4220 #ifdef HAVE_CHARDEV_SERIAL
4221 static CharDriverState *qmp_chardev_open_serial(const char *id,
4222 ChardevBackend *backend,
4223 ChardevReturn *ret,
4224 Error **errp)
4226 ChardevHostdev *serial = backend->u.serial;
4227 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.serial);
4228 int fd;
4230 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4231 if (fd < 0) {
4232 return NULL;
4234 qemu_set_nonblock(fd);
4235 return qemu_chr_open_tty_fd(fd, common, errp);
4237 #endif
4239 #ifdef HAVE_CHARDEV_PARPORT
4240 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4241 ChardevBackend *backend,
4242 ChardevReturn *ret,
4243 Error **errp)
4245 ChardevHostdev *parallel = backend->u.parallel;
4246 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.parallel);
4247 int fd;
4249 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4250 if (fd < 0) {
4251 return NULL;
4253 return qemu_chr_open_pp_fd(fd, common, errp);
4255 #endif
4257 #endif /* WIN32 */
4259 static void socket_try_connect(CharDriverState *chr)
4261 Error *err = NULL;
4263 if (!qemu_chr_open_socket_fd(chr, &err)) {
4264 check_report_connect_error(chr, err);
4268 static gboolean socket_reconnect_timeout(gpointer opaque)
4270 CharDriverState *chr = opaque;
4271 TCPCharDriver *s = chr->opaque;
4273 s->reconnect_timer = 0;
4275 if (chr->be_open) {
4276 return false;
4279 socket_try_connect(chr);
4281 return false;
4284 static CharDriverState *qmp_chardev_open_socket(const char *id,
4285 ChardevBackend *backend,
4286 ChardevReturn *ret,
4287 Error **errp)
4289 CharDriverState *chr;
4290 TCPCharDriver *s;
4291 ChardevSocket *sock = backend->u.socket;
4292 SocketAddress *addr = sock->addr;
4293 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4294 bool is_listen = sock->has_server ? sock->server : true;
4295 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4296 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4297 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4298 ChardevCommon *common = qapi_ChardevSocket_base(backend->u.socket);
4300 chr = qemu_chr_alloc(common, errp);
4301 if (!chr) {
4302 return NULL;
4304 s = g_new0(TCPCharDriver, 1);
4306 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4307 s->is_listen = is_listen;
4308 s->is_telnet = is_telnet;
4309 s->do_nodelay = do_nodelay;
4310 if (sock->tls_creds) {
4311 Object *creds;
4312 creds = object_resolve_path_component(
4313 object_get_objects_root(), sock->tls_creds);
4314 if (!creds) {
4315 error_setg(errp, "No TLS credentials with id '%s'",
4316 sock->tls_creds);
4317 goto error;
4319 s->tls_creds = (QCryptoTLSCreds *)
4320 object_dynamic_cast(creds,
4321 TYPE_QCRYPTO_TLS_CREDS);
4322 if (!s->tls_creds) {
4323 error_setg(errp, "Object with id '%s' is not TLS credentials",
4324 sock->tls_creds);
4325 goto error;
4327 object_ref(OBJECT(s->tls_creds));
4328 if (is_listen) {
4329 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4330 error_setg(errp, "%s",
4331 "Expected TLS credentials for server endpoint");
4332 goto error;
4334 } else {
4335 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4336 error_setg(errp, "%s",
4337 "Expected TLS credentials for client endpoint");
4338 goto error;
4343 qapi_copy_SocketAddress(&s->addr, sock->addr);
4345 chr->opaque = s;
4346 chr->chr_write = tcp_chr_write;
4347 chr->chr_sync_read = tcp_chr_sync_read;
4348 chr->chr_close = tcp_chr_close;
4349 chr->get_msgfds = tcp_get_msgfds;
4350 chr->set_msgfds = tcp_set_msgfds;
4351 chr->chr_add_client = tcp_chr_add_client;
4352 chr->chr_add_watch = tcp_chr_add_watch;
4353 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4354 /* be isn't opened until we get a connection */
4355 chr->explicit_be_open = true;
4357 chr->filename = SocketAddress_to_str("disconnected:",
4358 addr, is_listen, is_telnet);
4360 if (is_listen) {
4361 if (is_telnet) {
4362 s->do_telnetopt = 1;
4364 } else if (reconnect > 0) {
4365 s->reconnect_time = reconnect;
4368 if (s->reconnect_time) {
4369 socket_try_connect(chr);
4370 } else if (!qemu_chr_open_socket_fd(chr, errp)) {
4371 goto error;
4374 if (is_listen && is_waitconnect) {
4375 fprintf(stderr, "QEMU waiting for connection on: %s\n",
4376 chr->filename);
4377 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
4378 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
4381 return chr;
4383 error:
4384 if (s->tls_creds) {
4385 object_unref(OBJECT(s->tls_creds));
4387 g_free(s);
4388 qemu_chr_free_common(chr);
4389 return NULL;
4392 static CharDriverState *qmp_chardev_open_udp(const char *id,
4393 ChardevBackend *backend,
4394 ChardevReturn *ret,
4395 Error **errp)
4397 ChardevUdp *udp = backend->u.udp;
4398 ChardevCommon *common = qapi_ChardevUdp_base(backend->u.udp);
4399 QIOChannelSocket *sioc = qio_channel_socket_new();
4401 if (qio_channel_socket_dgram_sync(sioc,
4402 udp->remote, udp->local,
4403 errp) < 0) {
4404 object_unref(OBJECT(sioc));
4405 return NULL;
4407 return qemu_chr_open_udp(sioc, common, errp);
4410 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4411 Error **errp)
4413 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4414 CharDriverState *chr = NULL;
4415 Error *local_err = NULL;
4416 GSList *i;
4417 CharDriver *cd;
4419 chr = qemu_chr_find(id);
4420 if (chr) {
4421 error_setg(errp, "Chardev '%s' already exists", id);
4422 g_free(ret);
4423 return NULL;
4426 for (i = backends; i; i = i->next) {
4427 cd = i->data;
4429 if (cd->kind == backend->type) {
4430 chr = cd->create(id, backend, ret, &local_err);
4431 if (local_err) {
4432 error_propagate(errp, local_err);
4433 goto out_error;
4435 break;
4439 if (chr == NULL) {
4440 assert(!i);
4441 error_setg(errp, "chardev backend not available");
4442 goto out_error;
4445 chr->label = g_strdup(id);
4446 chr->avail_connections =
4447 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4448 if (!chr->filename) {
4449 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4451 if (!chr->explicit_be_open) {
4452 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4454 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4455 return ret;
4457 out_error:
4458 g_free(ret);
4459 return NULL;
4462 void qmp_chardev_remove(const char *id, Error **errp)
4464 CharDriverState *chr;
4466 chr = qemu_chr_find(id);
4467 if (chr == NULL) {
4468 error_setg(errp, "Chardev '%s' not found", id);
4469 return;
4471 if (chr->chr_can_read || chr->chr_read ||
4472 chr->chr_event || chr->handler_opaque) {
4473 error_setg(errp, "Chardev '%s' is busy", id);
4474 return;
4476 qemu_chr_delete(chr);
4479 static void register_types(void)
4481 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4482 qemu_chr_open_null);
4483 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4484 qemu_chr_parse_socket, qmp_chardev_open_socket);
4485 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4486 qmp_chardev_open_udp);
4487 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4488 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4489 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4490 qemu_chr_parse_file_out, qmp_chardev_open_file);
4491 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4492 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4493 #if defined HAVE_CHARDEV_SERIAL
4494 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4495 qemu_chr_parse_serial, qmp_chardev_open_serial);
4496 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4497 qemu_chr_parse_serial, qmp_chardev_open_serial);
4498 #endif
4499 #ifdef HAVE_CHARDEV_PARPORT
4500 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4501 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4502 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4503 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4504 #endif
4505 #ifdef HAVE_CHARDEV_PTY
4506 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4507 qemu_chr_open_pty);
4508 #endif
4509 #ifdef _WIN32
4510 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4511 qemu_chr_open_win_con);
4512 #endif
4513 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4514 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4515 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4516 qemu_chr_open_mux);
4517 /* Bug-compatibility: */
4518 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4519 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4520 /* this must be done after machine init, since we register FEs with muxes
4521 * as part of realize functions like serial_isa_realizefn when -nographic
4522 * is specified
4524 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4527 type_init(register_types);