build: Don't redefine 'inline'
[qemu/armbru.git] / qemu-char.c
blob1b7d5dac7637a79aa88006c69f9f690265024347
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
25 #include "qemu-common.h"
26 #include "monitor/monitor.h"
27 #include "sysemu/sysemu.h"
28 #include "qemu/error-report.h"
29 #include "qemu/timer.h"
30 #include "sysemu/char.h"
31 #include "hw/usb.h"
32 #include "qmp-commands.h"
33 #include "qapi/qmp-input-visitor.h"
34 #include "qapi/qmp-output-visitor.h"
35 #include "qapi-visit.h"
36 #include "qemu/base64.h"
37 #include "io/channel-socket.h"
38 #include "io/channel-file.h"
39 #include "io/channel-tls.h"
41 #include <zlib.h>
43 #ifndef _WIN32
44 #include <sys/times.h>
45 #include <sys/wait.h>
46 #include <termios.h>
47 #include <sys/mman.h>
48 #include <sys/ioctl.h>
49 #include <sys/resource.h>
50 #include <sys/socket.h>
51 #include <netinet/in.h>
52 #include <net/if.h>
53 #include <arpa/inet.h>
54 #include <netdb.h>
55 #include <sys/select.h>
56 #ifdef CONFIG_BSD
57 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
58 #include <dev/ppbus/ppi.h>
59 #include <dev/ppbus/ppbconf.h>
60 #elif defined(__DragonFly__)
61 #include <dev/misc/ppi/ppi.h>
62 #include <bus/ppbus/ppbconf.h>
63 #endif
64 #else
65 #ifdef __linux__
66 #include <linux/ppdev.h>
67 #include <linux/parport.h>
68 #endif
69 #ifdef __sun__
70 #include <sys/ethernet.h>
71 #include <sys/sockio.h>
72 #include <netinet/arp.h>
73 #include <netinet/in.h>
74 #include <netinet/in_systm.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_icmp.h> // must come after ip.h
77 #include <netinet/udp.h>
78 #include <netinet/tcp.h>
79 #endif
80 #endif
81 #endif
83 #include "qemu/sockets.h"
84 #include "ui/qemu-spice.h"
86 #define READ_BUF_LEN 4096
87 #define READ_RETRIES 10
88 #define TCP_MAX_FDS 16
90 /***********************************************************/
91 /* Socket address helpers */
93 static char *SocketAddress_to_str(const char *prefix, SocketAddress *addr,
94 bool is_listen, bool is_telnet)
96 switch (addr->type) {
97 case SOCKET_ADDRESS_KIND_INET:
98 return g_strdup_printf("%s%s:%s:%s%s", prefix,
99 is_telnet ? "telnet" : "tcp", addr->u.inet->host,
100 addr->u.inet->port, is_listen ? ",server" : "");
101 break;
102 case SOCKET_ADDRESS_KIND_UNIX:
103 return g_strdup_printf("%sunix:%s%s", prefix,
104 addr->u.q_unix->path,
105 is_listen ? ",server" : "");
106 break;
107 case SOCKET_ADDRESS_KIND_FD:
108 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd->str,
109 is_listen ? ",server" : "");
110 break;
111 default:
112 abort();
116 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
117 struct sockaddr_storage *ps, socklen_t ps_len,
118 bool is_listen, bool is_telnet)
120 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
121 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
122 const char *left = "", *right = "";
124 switch (ss->ss_family) {
125 #ifndef _WIN32
126 case AF_UNIX:
127 return g_strdup_printf("unix:%s%s",
128 ((struct sockaddr_un *)(ss))->sun_path,
129 is_listen ? ",server" : "");
130 #endif
131 case AF_INET6:
132 left = "[";
133 right = "]";
134 /* fall through */
135 case AF_INET:
136 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
137 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
138 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
139 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
140 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
141 is_telnet ? "telnet" : "tcp",
142 left, shost, right, sserv,
143 is_listen ? ",server" : "",
144 left, phost, right, pserv);
146 default:
147 return g_strdup_printf("unknown");
151 /***********************************************************/
152 /* character device */
154 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
155 QTAILQ_HEAD_INITIALIZER(chardevs);
157 static void qemu_chr_free_common(CharDriverState *chr);
159 CharDriverState *qemu_chr_alloc(ChardevCommon *backend, Error **errp)
161 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
162 qemu_mutex_init(&chr->chr_write_lock);
164 if (backend->has_logfile) {
165 int flags = O_WRONLY | O_CREAT;
166 if (backend->has_logappend &&
167 backend->logappend) {
168 flags |= O_APPEND;
169 } else {
170 flags |= O_TRUNC;
172 chr->logfd = qemu_open(backend->logfile, flags, 0666);
173 if (chr->logfd < 0) {
174 error_setg_errno(errp, errno,
175 "Unable to open logfile %s",
176 backend->logfile);
177 g_free(chr);
178 return NULL;
180 } else {
181 chr->logfd = -1;
184 return chr;
187 void qemu_chr_be_event(CharDriverState *s, int event)
189 /* Keep track if the char device is open */
190 switch (event) {
191 case CHR_EVENT_OPENED:
192 s->be_open = 1;
193 break;
194 case CHR_EVENT_CLOSED:
195 s->be_open = 0;
196 break;
199 if (!s->chr_event)
200 return;
201 s->chr_event(s->handler_opaque, event);
204 void qemu_chr_be_generic_open(CharDriverState *s)
206 qemu_chr_be_event(s, CHR_EVENT_OPENED);
210 /* Not reporting errors from writing to logfile, as logs are
211 * defined to be "best effort" only */
212 static void qemu_chr_fe_write_log(CharDriverState *s,
213 const uint8_t *buf, size_t len)
215 size_t done = 0;
216 ssize_t ret;
218 if (s->logfd < 0) {
219 return;
222 while (done < len) {
223 do {
224 ret = write(s->logfd, buf + done, len - done);
225 if (ret == -1 && errno == EAGAIN) {
226 g_usleep(100);
228 } while (ret == -1 && errno == EAGAIN);
230 if (ret <= 0) {
231 return;
233 done += ret;
237 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
239 int ret;
241 qemu_mutex_lock(&s->chr_write_lock);
242 ret = s->chr_write(s, buf, len);
244 if (ret > 0) {
245 qemu_chr_fe_write_log(s, buf, ret);
248 qemu_mutex_unlock(&s->chr_write_lock);
249 return ret;
252 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
254 int offset = 0;
255 int res = 0;
257 qemu_mutex_lock(&s->chr_write_lock);
258 while (offset < len) {
259 do {
260 res = s->chr_write(s, buf + offset, len - offset);
261 if (res == -1 && errno == EAGAIN) {
262 g_usleep(100);
264 } while (res == -1 && errno == EAGAIN);
266 if (res <= 0) {
267 break;
270 offset += res;
272 if (offset > 0) {
273 qemu_chr_fe_write_log(s, buf, offset);
276 qemu_mutex_unlock(&s->chr_write_lock);
278 if (res < 0) {
279 return res;
281 return offset;
284 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
286 int offset = 0, counter = 10;
287 int res;
289 if (!s->chr_sync_read) {
290 return 0;
293 while (offset < len) {
294 do {
295 res = s->chr_sync_read(s, buf + offset, len - offset);
296 if (res == -1 && errno == EAGAIN) {
297 g_usleep(100);
299 } while (res == -1 && errno == EAGAIN);
301 if (res == 0) {
302 break;
305 if (res < 0) {
306 return res;
309 offset += res;
311 if (!counter--) {
312 break;
316 return offset;
319 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
321 if (!s->chr_ioctl)
322 return -ENOTSUP;
323 return s->chr_ioctl(s, cmd, arg);
326 int qemu_chr_be_can_write(CharDriverState *s)
328 if (!s->chr_can_read)
329 return 0;
330 return s->chr_can_read(s->handler_opaque);
333 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
335 if (s->chr_read) {
336 s->chr_read(s->handler_opaque, buf, len);
340 int qemu_chr_fe_get_msgfd(CharDriverState *s)
342 int fd;
343 return (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
346 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
348 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
351 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
353 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
356 int qemu_chr_add_client(CharDriverState *s, int fd)
358 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
361 void qemu_chr_accept_input(CharDriverState *s)
363 if (s->chr_accept_input)
364 s->chr_accept_input(s);
365 qemu_notify_event();
368 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
370 char buf[READ_BUF_LEN];
371 va_list ap;
372 va_start(ap, fmt);
373 vsnprintf(buf, sizeof(buf), fmt, ap);
374 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
375 va_end(ap);
378 static void remove_fd_in_watch(CharDriverState *chr);
380 void qemu_chr_add_handlers(CharDriverState *s,
381 IOCanReadHandler *fd_can_read,
382 IOReadHandler *fd_read,
383 IOEventHandler *fd_event,
384 void *opaque)
386 int fe_open;
388 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
389 fe_open = 0;
390 remove_fd_in_watch(s);
391 } else {
392 fe_open = 1;
394 s->chr_can_read = fd_can_read;
395 s->chr_read = fd_read;
396 s->chr_event = fd_event;
397 s->handler_opaque = opaque;
398 if (fe_open && s->chr_update_read_handler)
399 s->chr_update_read_handler(s);
401 if (!s->explicit_fe_open) {
402 qemu_chr_fe_set_open(s, fe_open);
405 /* We're connecting to an already opened device, so let's make sure we
406 also get the open event */
407 if (fe_open && s->be_open) {
408 qemu_chr_be_generic_open(s);
412 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
414 return len;
417 static CharDriverState *qemu_chr_open_null(const char *id,
418 ChardevBackend *backend,
419 ChardevReturn *ret,
420 Error **errp)
422 CharDriverState *chr;
423 ChardevCommon *common = qapi_ChardevDummy_base(backend->u.null);
425 chr = qemu_chr_alloc(common, errp);
426 if (!chr) {
427 return NULL;
429 chr->chr_write = null_chr_write;
430 chr->explicit_be_open = true;
431 return chr;
434 /* MUX driver for serial I/O splitting */
435 #define MAX_MUX 4
436 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
437 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
438 typedef struct {
439 IOCanReadHandler *chr_can_read[MAX_MUX];
440 IOReadHandler *chr_read[MAX_MUX];
441 IOEventHandler *chr_event[MAX_MUX];
442 void *ext_opaque[MAX_MUX];
443 CharDriverState *drv;
444 int focus;
445 int mux_cnt;
446 int term_got_escape;
447 int max_size;
448 /* Intermediate input buffer allows to catch escape sequences even if the
449 currently active device is not accepting any input - but only until it
450 is full as well. */
451 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
452 int prod[MAX_MUX];
453 int cons[MAX_MUX];
454 int timestamps;
456 /* Protected by the CharDriverState chr_write_lock. */
457 int linestart;
458 int64_t timestamps_start;
459 } MuxDriver;
462 /* Called with chr_write_lock held. */
463 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
465 MuxDriver *d = chr->opaque;
466 int ret;
467 if (!d->timestamps) {
468 ret = qemu_chr_fe_write(d->drv, buf, len);
469 } else {
470 int i;
472 ret = 0;
473 for (i = 0; i < len; i++) {
474 if (d->linestart) {
475 char buf1[64];
476 int64_t ti;
477 int secs;
479 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
480 if (d->timestamps_start == -1)
481 d->timestamps_start = ti;
482 ti -= d->timestamps_start;
483 secs = ti / 1000;
484 snprintf(buf1, sizeof(buf1),
485 "[%02d:%02d:%02d.%03d] ",
486 secs / 3600,
487 (secs / 60) % 60,
488 secs % 60,
489 (int)(ti % 1000));
490 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
491 d->linestart = 0;
493 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
494 if (buf[i] == '\n') {
495 d->linestart = 1;
499 return ret;
502 static const char * const mux_help[] = {
503 "% h print this help\n\r",
504 "% x exit emulator\n\r",
505 "% s save disk data back to file (if -snapshot)\n\r",
506 "% t toggle console timestamps\n\r",
507 "% b send break (magic sysrq)\n\r",
508 "% c switch between console and monitor\n\r",
509 "% % sends %\n\r",
510 NULL
513 int term_escape_char = 0x01; /* ctrl-a is used for escape */
514 static void mux_print_help(CharDriverState *chr)
516 int i, j;
517 char ebuf[15] = "Escape-Char";
518 char cbuf[50] = "\n\r";
520 if (term_escape_char > 0 && term_escape_char < 26) {
521 snprintf(cbuf, sizeof(cbuf), "\n\r");
522 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
523 } else {
524 snprintf(cbuf, sizeof(cbuf),
525 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
526 term_escape_char);
528 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
529 for (i = 0; mux_help[i] != NULL; i++) {
530 for (j=0; mux_help[i][j] != '\0'; j++) {
531 if (mux_help[i][j] == '%')
532 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
533 else
534 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
539 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
541 if (d->chr_event[mux_nr])
542 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
545 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
547 if (d->term_got_escape) {
548 d->term_got_escape = 0;
549 if (ch == term_escape_char)
550 goto send_char;
551 switch(ch) {
552 case '?':
553 case 'h':
554 mux_print_help(chr);
555 break;
556 case 'x':
558 const char *term = "QEMU: Terminated\n\r";
559 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
560 exit(0);
561 break;
563 case 's':
564 bdrv_commit_all();
565 break;
566 case 'b':
567 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
568 break;
569 case 'c':
570 /* Switch to the next registered device */
571 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
572 d->focus++;
573 if (d->focus >= d->mux_cnt)
574 d->focus = 0;
575 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
576 break;
577 case 't':
578 d->timestamps = !d->timestamps;
579 d->timestamps_start = -1;
580 d->linestart = 0;
581 break;
583 } else if (ch == term_escape_char) {
584 d->term_got_escape = 1;
585 } else {
586 send_char:
587 return 1;
589 return 0;
592 static void mux_chr_accept_input(CharDriverState *chr)
594 MuxDriver *d = chr->opaque;
595 int m = d->focus;
597 while (d->prod[m] != d->cons[m] &&
598 d->chr_can_read[m] &&
599 d->chr_can_read[m](d->ext_opaque[m])) {
600 d->chr_read[m](d->ext_opaque[m],
601 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
605 static int mux_chr_can_read(void *opaque)
607 CharDriverState *chr = opaque;
608 MuxDriver *d = chr->opaque;
609 int m = d->focus;
611 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
612 return 1;
613 if (d->chr_can_read[m])
614 return d->chr_can_read[m](d->ext_opaque[m]);
615 return 0;
618 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
620 CharDriverState *chr = opaque;
621 MuxDriver *d = chr->opaque;
622 int m = d->focus;
623 int i;
625 mux_chr_accept_input (opaque);
627 for(i = 0; i < size; i++)
628 if (mux_proc_byte(chr, d, buf[i])) {
629 if (d->prod[m] == d->cons[m] &&
630 d->chr_can_read[m] &&
631 d->chr_can_read[m](d->ext_opaque[m]))
632 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
633 else
634 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
638 static void mux_chr_event(void *opaque, int event)
640 CharDriverState *chr = opaque;
641 MuxDriver *d = chr->opaque;
642 int i;
644 /* Send the event to all registered listeners */
645 for (i = 0; i < d->mux_cnt; i++)
646 mux_chr_send_event(d, i, event);
649 static void mux_chr_update_read_handler(CharDriverState *chr)
651 MuxDriver *d = chr->opaque;
653 if (d->mux_cnt >= MAX_MUX) {
654 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
655 return;
657 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
658 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
659 d->chr_read[d->mux_cnt] = chr->chr_read;
660 d->chr_event[d->mux_cnt] = chr->chr_event;
661 /* Fix up the real driver with mux routines */
662 if (d->mux_cnt == 0) {
663 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
664 mux_chr_event, chr);
666 if (d->focus != -1) {
667 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
669 d->focus = d->mux_cnt;
670 d->mux_cnt++;
671 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
674 static bool muxes_realized;
677 * Called after processing of default and command-line-specified
678 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
679 * to a mux chardev. This is done here to ensure that
680 * output/prompts/banners are only displayed for the FE that has
681 * focus when initial command-line processing/machine init is
682 * completed.
684 * After this point, any new FE attached to any new or existing
685 * mux will receive CHR_EVENT_OPENED notifications for the BE
686 * immediately.
688 static void muxes_realize_done(Notifier *notifier, void *unused)
690 CharDriverState *chr;
692 QTAILQ_FOREACH(chr, &chardevs, next) {
693 if (chr->is_mux) {
694 MuxDriver *d = chr->opaque;
695 int i;
697 /* send OPENED to all already-attached FEs */
698 for (i = 0; i < d->mux_cnt; i++) {
699 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
701 /* mark mux as OPENED so any new FEs will immediately receive
702 * OPENED event
704 qemu_chr_be_generic_open(chr);
707 muxes_realized = true;
710 static Notifier muxes_realize_notify = {
711 .notify = muxes_realize_done,
714 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
716 MuxDriver *d = s->opaque;
717 return d->drv->chr_add_watch(d->drv, cond);
720 static CharDriverState *qemu_chr_open_mux(const char *id,
721 ChardevBackend *backend,
722 ChardevReturn *ret, Error **errp)
724 ChardevMux *mux = backend->u.mux;
725 CharDriverState *chr, *drv;
726 MuxDriver *d;
727 ChardevCommon *common = qapi_ChardevMux_base(backend->u.mux);
729 drv = qemu_chr_find(mux->chardev);
730 if (drv == NULL) {
731 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
732 return NULL;
735 chr = qemu_chr_alloc(common, errp);
736 if (!chr) {
737 return NULL;
739 d = g_new0(MuxDriver, 1);
741 chr->opaque = d;
742 d->drv = drv;
743 d->focus = -1;
744 chr->chr_write = mux_chr_write;
745 chr->chr_update_read_handler = mux_chr_update_read_handler;
746 chr->chr_accept_input = mux_chr_accept_input;
747 /* Frontend guest-open / -close notification is not support with muxes */
748 chr->chr_set_fe_open = NULL;
749 if (drv->chr_add_watch) {
750 chr->chr_add_watch = mux_chr_add_watch;
752 /* only default to opened state if we've realized the initial
753 * set of muxes
755 chr->explicit_be_open = muxes_realized ? 0 : 1;
756 chr->is_mux = 1;
758 return chr;
762 typedef struct IOWatchPoll
764 GSource parent;
766 QIOChannel *ioc;
767 GSource *src;
769 IOCanReadHandler *fd_can_read;
770 GSourceFunc fd_read;
771 void *opaque;
772 } IOWatchPoll;
774 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
776 return container_of(source, IOWatchPoll, parent);
779 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
781 IOWatchPoll *iwp = io_watch_poll_from_source(source);
782 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
783 bool was_active = iwp->src != NULL;
784 if (was_active == now_active) {
785 return FALSE;
788 if (now_active) {
789 iwp->src = qio_channel_create_watch(
790 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
791 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
792 g_source_attach(iwp->src, NULL);
793 } else {
794 g_source_destroy(iwp->src);
795 g_source_unref(iwp->src);
796 iwp->src = NULL;
798 return FALSE;
801 static gboolean io_watch_poll_check(GSource *source)
803 return FALSE;
806 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
807 gpointer user_data)
809 abort();
812 static void io_watch_poll_finalize(GSource *source)
814 /* Due to a glib bug, removing the last reference to a source
815 * inside a finalize callback causes recursive locking (and a
816 * deadlock). This is not a problem inside other callbacks,
817 * including dispatch callbacks, so we call io_remove_watch_poll
818 * to remove this source. At this point, iwp->src must
819 * be NULL, or we would leak it.
821 * This would be solved much more elegantly by child sources,
822 * but we support older glib versions that do not have them.
824 IOWatchPoll *iwp = io_watch_poll_from_source(source);
825 assert(iwp->src == NULL);
828 static GSourceFuncs io_watch_poll_funcs = {
829 .prepare = io_watch_poll_prepare,
830 .check = io_watch_poll_check,
831 .dispatch = io_watch_poll_dispatch,
832 .finalize = io_watch_poll_finalize,
835 /* Can only be used for read */
836 static guint io_add_watch_poll(QIOChannel *ioc,
837 IOCanReadHandler *fd_can_read,
838 QIOChannelFunc fd_read,
839 gpointer user_data)
841 IOWatchPoll *iwp;
842 int tag;
844 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
845 iwp->fd_can_read = fd_can_read;
846 iwp->opaque = user_data;
847 iwp->ioc = ioc;
848 iwp->fd_read = (GSourceFunc) fd_read;
849 iwp->src = NULL;
851 tag = g_source_attach(&iwp->parent, NULL);
852 g_source_unref(&iwp->parent);
853 return tag;
856 static void io_remove_watch_poll(guint tag)
858 GSource *source;
859 IOWatchPoll *iwp;
861 g_return_if_fail (tag > 0);
863 source = g_main_context_find_source_by_id(NULL, tag);
864 g_return_if_fail (source != NULL);
866 iwp = io_watch_poll_from_source(source);
867 if (iwp->src) {
868 g_source_destroy(iwp->src);
869 g_source_unref(iwp->src);
870 iwp->src = NULL;
872 g_source_destroy(&iwp->parent);
875 static void remove_fd_in_watch(CharDriverState *chr)
877 if (chr->fd_in_tag) {
878 io_remove_watch_poll(chr->fd_in_tag);
879 chr->fd_in_tag = 0;
884 static int io_channel_send_full(QIOChannel *ioc,
885 const void *buf, size_t len,
886 int *fds, size_t nfds)
888 size_t offset = 0;
890 while (offset < len) {
891 ssize_t ret = 0;
892 struct iovec iov = { .iov_base = (char *)buf + offset,
893 .iov_len = len - offset };
895 ret = qio_channel_writev_full(
896 ioc, &iov, 1,
897 fds, nfds, NULL);
898 if (ret == QIO_CHANNEL_ERR_BLOCK) {
899 errno = EAGAIN;
900 return -1;
901 } else if (ret < 0) {
902 if (offset) {
903 return offset;
906 errno = EINVAL;
907 return -1;
910 offset += ret;
913 return offset;
917 #ifndef _WIN32
918 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
920 return io_channel_send_full(ioc, buf, len, NULL, 0);
924 typedef struct FDCharDriver {
925 CharDriverState *chr;
926 QIOChannel *ioc_in, *ioc_out;
927 int max_size;
928 } FDCharDriver;
930 /* Called with chr_write_lock held. */
931 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
933 FDCharDriver *s = chr->opaque;
935 return io_channel_send(s->ioc_out, buf, len);
938 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
940 CharDriverState *chr = opaque;
941 FDCharDriver *s = chr->opaque;
942 int len;
943 uint8_t buf[READ_BUF_LEN];
944 ssize_t ret;
946 len = sizeof(buf);
947 if (len > s->max_size) {
948 len = s->max_size;
950 if (len == 0) {
951 return TRUE;
954 ret = qio_channel_read(
955 chan, (gchar *)buf, len, NULL);
956 if (ret == 0) {
957 remove_fd_in_watch(chr);
958 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
959 return FALSE;
961 if (ret > 0) {
962 qemu_chr_be_write(chr, buf, ret);
965 return TRUE;
968 static int fd_chr_read_poll(void *opaque)
970 CharDriverState *chr = opaque;
971 FDCharDriver *s = chr->opaque;
973 s->max_size = qemu_chr_be_can_write(chr);
974 return s->max_size;
977 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
979 FDCharDriver *s = chr->opaque;
980 return qio_channel_create_watch(s->ioc_out, cond);
983 static void fd_chr_update_read_handler(CharDriverState *chr)
985 FDCharDriver *s = chr->opaque;
987 remove_fd_in_watch(chr);
988 if (s->ioc_in) {
989 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
990 fd_chr_read_poll,
991 fd_chr_read, chr);
995 static void fd_chr_close(struct CharDriverState *chr)
997 FDCharDriver *s = chr->opaque;
999 remove_fd_in_watch(chr);
1000 if (s->ioc_in) {
1001 object_unref(OBJECT(s->ioc_in));
1003 if (s->ioc_out) {
1004 object_unref(OBJECT(s->ioc_out));
1007 g_free(s);
1008 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1011 /* open a character device to a unix fd */
1012 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1013 ChardevCommon *backend, Error **errp)
1015 CharDriverState *chr;
1016 FDCharDriver *s;
1018 chr = qemu_chr_alloc(backend, errp);
1019 if (!chr) {
1020 return NULL;
1022 s = g_new0(FDCharDriver, 1);
1023 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1024 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1025 qemu_set_nonblock(fd_out);
1026 s->chr = chr;
1027 chr->opaque = s;
1028 chr->chr_add_watch = fd_chr_add_watch;
1029 chr->chr_write = fd_chr_write;
1030 chr->chr_update_read_handler = fd_chr_update_read_handler;
1031 chr->chr_close = fd_chr_close;
1033 return chr;
1036 static CharDriverState *qemu_chr_open_pipe(const char *id,
1037 ChardevBackend *backend,
1038 ChardevReturn *ret,
1039 Error **errp)
1041 ChardevHostdev *opts = backend->u.pipe;
1042 int fd_in, fd_out;
1043 char *filename_in;
1044 char *filename_out;
1045 const char *filename = opts->device;
1046 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.pipe);
1049 filename_in = g_strdup_printf("%s.in", filename);
1050 filename_out = g_strdup_printf("%s.out", filename);
1051 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1052 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1053 g_free(filename_in);
1054 g_free(filename_out);
1055 if (fd_in < 0 || fd_out < 0) {
1056 if (fd_in >= 0)
1057 close(fd_in);
1058 if (fd_out >= 0)
1059 close(fd_out);
1060 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1061 if (fd_in < 0) {
1062 error_setg_file_open(errp, errno, filename);
1063 return NULL;
1066 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1069 /* init terminal so that we can grab keys */
1070 static struct termios oldtty;
1071 static int old_fd0_flags;
1072 static bool stdio_in_use;
1073 static bool stdio_allow_signal;
1074 static bool stdio_echo_state;
1076 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1078 static void term_exit(void)
1080 tcsetattr (0, TCSANOW, &oldtty);
1081 fcntl(0, F_SETFL, old_fd0_flags);
1084 static void term_stdio_handler(int sig)
1086 /* restore echo after resume from suspend. */
1087 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1090 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1092 struct termios tty;
1094 stdio_echo_state = echo;
1095 tty = oldtty;
1096 if (!echo) {
1097 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1098 |INLCR|IGNCR|ICRNL|IXON);
1099 tty.c_oflag |= OPOST;
1100 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1101 tty.c_cflag &= ~(CSIZE|PARENB);
1102 tty.c_cflag |= CS8;
1103 tty.c_cc[VMIN] = 1;
1104 tty.c_cc[VTIME] = 0;
1106 if (!stdio_allow_signal)
1107 tty.c_lflag &= ~ISIG;
1109 tcsetattr (0, TCSANOW, &tty);
1112 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1114 term_exit();
1115 fd_chr_close(chr);
1118 static CharDriverState *qemu_chr_open_stdio(const char *id,
1119 ChardevBackend *backend,
1120 ChardevReturn *ret,
1121 Error **errp)
1123 ChardevStdio *opts = backend->u.stdio;
1124 CharDriverState *chr;
1125 struct sigaction act;
1126 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio);
1128 if (is_daemonized()) {
1129 error_setg(errp, "cannot use stdio with -daemonize");
1130 return NULL;
1133 if (stdio_in_use) {
1134 error_setg(errp, "cannot use stdio by multiple character devices");
1135 return NULL;
1138 stdio_in_use = true;
1139 old_fd0_flags = fcntl(0, F_GETFL);
1140 tcgetattr(0, &oldtty);
1141 qemu_set_nonblock(0);
1142 atexit(term_exit);
1144 memset(&act, 0, sizeof(act));
1145 act.sa_handler = term_stdio_handler;
1146 sigaction(SIGCONT, &act, NULL);
1148 chr = qemu_chr_open_fd(0, 1, common, errp);
1149 chr->chr_close = qemu_chr_close_stdio;
1150 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1151 if (opts->has_signal) {
1152 stdio_allow_signal = opts->signal;
1154 qemu_chr_fe_set_echo(chr, false);
1156 return chr;
1159 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1160 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1161 || defined(__GLIBC__)
1163 #define HAVE_CHARDEV_SERIAL 1
1164 #define HAVE_CHARDEV_PTY 1
1166 typedef struct {
1167 QIOChannel *ioc;
1168 int read_bytes;
1170 /* Protected by the CharDriverState chr_write_lock. */
1171 int connected;
1172 guint timer_tag;
1173 guint open_tag;
1174 int slave_fd;
1175 } PtyCharDriver;
1177 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1178 static void pty_chr_state(CharDriverState *chr, int connected);
1180 static gboolean pty_chr_timer(gpointer opaque)
1182 struct CharDriverState *chr = opaque;
1183 PtyCharDriver *s = chr->opaque;
1185 qemu_mutex_lock(&chr->chr_write_lock);
1186 s->timer_tag = 0;
1187 s->open_tag = 0;
1188 if (!s->connected) {
1189 /* Next poll ... */
1190 pty_chr_update_read_handler_locked(chr);
1192 qemu_mutex_unlock(&chr->chr_write_lock);
1193 return FALSE;
1196 /* Called with chr_write_lock held. */
1197 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1199 PtyCharDriver *s = chr->opaque;
1201 if (s->timer_tag) {
1202 g_source_remove(s->timer_tag);
1203 s->timer_tag = 0;
1206 if (ms == 1000) {
1207 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1208 } else {
1209 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1213 /* Called with chr_write_lock held. */
1214 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1216 PtyCharDriver *s = chr->opaque;
1217 GPollFD pfd;
1218 int rc;
1219 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1221 pfd.fd = fioc->fd;
1222 pfd.events = G_IO_OUT;
1223 pfd.revents = 0;
1224 do {
1225 rc = g_poll(&pfd, 1, 0);
1226 } while (rc == -1 && errno == EINTR);
1227 assert(rc >= 0);
1229 if (pfd.revents & G_IO_HUP) {
1230 pty_chr_state(chr, 0);
1231 } else {
1232 pty_chr_state(chr, 1);
1236 static void pty_chr_update_read_handler(CharDriverState *chr)
1238 qemu_mutex_lock(&chr->chr_write_lock);
1239 pty_chr_update_read_handler_locked(chr);
1240 qemu_mutex_unlock(&chr->chr_write_lock);
1243 /* Called with chr_write_lock held. */
1244 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1246 PtyCharDriver *s = chr->opaque;
1248 if (!s->connected) {
1249 /* guest sends data, check for (re-)connect */
1250 pty_chr_update_read_handler_locked(chr);
1251 if (!s->connected) {
1252 return 0;
1255 return io_channel_send(s->ioc, buf, len);
1258 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1260 PtyCharDriver *s = chr->opaque;
1261 if (!s->connected) {
1262 return NULL;
1264 return qio_channel_create_watch(s->ioc, cond);
1267 static int pty_chr_read_poll(void *opaque)
1269 CharDriverState *chr = opaque;
1270 PtyCharDriver *s = chr->opaque;
1272 s->read_bytes = qemu_chr_be_can_write(chr);
1273 return s->read_bytes;
1276 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1278 CharDriverState *chr = opaque;
1279 PtyCharDriver *s = chr->opaque;
1280 gsize len;
1281 uint8_t buf[READ_BUF_LEN];
1282 ssize_t ret;
1284 len = sizeof(buf);
1285 if (len > s->read_bytes)
1286 len = s->read_bytes;
1287 if (len == 0) {
1288 return TRUE;
1290 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1291 if (ret <= 0) {
1292 pty_chr_state(chr, 0);
1293 return FALSE;
1294 } else {
1295 pty_chr_state(chr, 1);
1296 qemu_chr_be_write(chr, buf, ret);
1298 return TRUE;
1301 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1303 CharDriverState *chr = opaque;
1304 PtyCharDriver *s = chr->opaque;
1306 s->open_tag = 0;
1307 qemu_chr_be_generic_open(chr);
1308 return FALSE;
1311 /* Called with chr_write_lock held. */
1312 static void pty_chr_state(CharDriverState *chr, int connected)
1314 PtyCharDriver *s = chr->opaque;
1316 if (!connected) {
1317 if (s->open_tag) {
1318 g_source_remove(s->open_tag);
1319 s->open_tag = 0;
1321 remove_fd_in_watch(chr);
1322 s->connected = 0;
1323 /* (re-)connect poll interval for idle guests: once per second.
1324 * We check more frequently in case the guests sends data to
1325 * the virtual device linked to our pty. */
1326 pty_chr_rearm_timer(chr, 1000);
1327 } else {
1328 if (s->timer_tag) {
1329 g_source_remove(s->timer_tag);
1330 s->timer_tag = 0;
1332 if (!s->connected) {
1333 g_assert(s->open_tag == 0);
1334 s->connected = 1;
1335 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1337 if (!chr->fd_in_tag) {
1338 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1339 pty_chr_read_poll,
1340 pty_chr_read, chr);
1345 static void pty_chr_close(struct CharDriverState *chr)
1347 PtyCharDriver *s = chr->opaque;
1349 qemu_mutex_lock(&chr->chr_write_lock);
1350 pty_chr_state(chr, 0);
1351 close(s->slave_fd);
1352 object_unref(OBJECT(s->ioc));
1353 if (s->timer_tag) {
1354 g_source_remove(s->timer_tag);
1355 s->timer_tag = 0;
1357 qemu_mutex_unlock(&chr->chr_write_lock);
1358 g_free(s);
1359 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1362 static CharDriverState *qemu_chr_open_pty(const char *id,
1363 ChardevBackend *backend,
1364 ChardevReturn *ret,
1365 Error **errp)
1367 CharDriverState *chr;
1368 PtyCharDriver *s;
1369 int master_fd, slave_fd;
1370 char pty_name[PATH_MAX];
1371 ChardevCommon *common = qapi_ChardevDummy_base(backend->u.pty);
1373 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1374 if (master_fd < 0) {
1375 error_setg_errno(errp, errno, "Failed to create PTY");
1376 return NULL;
1379 qemu_set_nonblock(master_fd);
1381 chr = qemu_chr_alloc(common, errp);
1382 if (!chr) {
1383 close(master_fd);
1384 return NULL;
1387 chr->filename = g_strdup_printf("pty:%s", pty_name);
1388 ret->pty = g_strdup(pty_name);
1389 ret->has_pty = true;
1391 fprintf(stderr, "char device redirected to %s (label %s)\n",
1392 pty_name, id);
1394 s = g_new0(PtyCharDriver, 1);
1395 chr->opaque = s;
1396 chr->chr_write = pty_chr_write;
1397 chr->chr_update_read_handler = pty_chr_update_read_handler;
1398 chr->chr_close = pty_chr_close;
1399 chr->chr_add_watch = pty_chr_add_watch;
1400 chr->explicit_be_open = true;
1402 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1403 s->slave_fd = slave_fd;
1404 s->timer_tag = 0;
1406 return chr;
1409 static void tty_serial_init(int fd, int speed,
1410 int parity, int data_bits, int stop_bits)
1412 struct termios tty;
1413 speed_t spd;
1415 #if 0
1416 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1417 speed, parity, data_bits, stop_bits);
1418 #endif
1419 tcgetattr (fd, &tty);
1421 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1422 speed = speed * 10 / 11;
1423 do {
1424 check_speed(50);
1425 check_speed(75);
1426 check_speed(110);
1427 check_speed(134);
1428 check_speed(150);
1429 check_speed(200);
1430 check_speed(300);
1431 check_speed(600);
1432 check_speed(1200);
1433 check_speed(1800);
1434 check_speed(2400);
1435 check_speed(4800);
1436 check_speed(9600);
1437 check_speed(19200);
1438 check_speed(38400);
1439 /* Non-Posix values follow. They may be unsupported on some systems. */
1440 check_speed(57600);
1441 check_speed(115200);
1442 #ifdef B230400
1443 check_speed(230400);
1444 #endif
1445 #ifdef B460800
1446 check_speed(460800);
1447 #endif
1448 #ifdef B500000
1449 check_speed(500000);
1450 #endif
1451 #ifdef B576000
1452 check_speed(576000);
1453 #endif
1454 #ifdef B921600
1455 check_speed(921600);
1456 #endif
1457 #ifdef B1000000
1458 check_speed(1000000);
1459 #endif
1460 #ifdef B1152000
1461 check_speed(1152000);
1462 #endif
1463 #ifdef B1500000
1464 check_speed(1500000);
1465 #endif
1466 #ifdef B2000000
1467 check_speed(2000000);
1468 #endif
1469 #ifdef B2500000
1470 check_speed(2500000);
1471 #endif
1472 #ifdef B3000000
1473 check_speed(3000000);
1474 #endif
1475 #ifdef B3500000
1476 check_speed(3500000);
1477 #endif
1478 #ifdef B4000000
1479 check_speed(4000000);
1480 #endif
1481 spd = B115200;
1482 } while (0);
1484 cfsetispeed(&tty, spd);
1485 cfsetospeed(&tty, spd);
1487 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1488 |INLCR|IGNCR|ICRNL|IXON);
1489 tty.c_oflag |= OPOST;
1490 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1491 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1492 switch(data_bits) {
1493 default:
1494 case 8:
1495 tty.c_cflag |= CS8;
1496 break;
1497 case 7:
1498 tty.c_cflag |= CS7;
1499 break;
1500 case 6:
1501 tty.c_cflag |= CS6;
1502 break;
1503 case 5:
1504 tty.c_cflag |= CS5;
1505 break;
1507 switch(parity) {
1508 default:
1509 case 'N':
1510 break;
1511 case 'E':
1512 tty.c_cflag |= PARENB;
1513 break;
1514 case 'O':
1515 tty.c_cflag |= PARENB | PARODD;
1516 break;
1518 if (stop_bits == 2)
1519 tty.c_cflag |= CSTOPB;
1521 tcsetattr (fd, TCSANOW, &tty);
1524 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1526 FDCharDriver *s = chr->opaque;
1527 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1529 switch(cmd) {
1530 case CHR_IOCTL_SERIAL_SET_PARAMS:
1532 QEMUSerialSetParams *ssp = arg;
1533 tty_serial_init(fioc->fd,
1534 ssp->speed, ssp->parity,
1535 ssp->data_bits, ssp->stop_bits);
1537 break;
1538 case CHR_IOCTL_SERIAL_SET_BREAK:
1540 int enable = *(int *)arg;
1541 if (enable) {
1542 tcsendbreak(fioc->fd, 1);
1545 break;
1546 case CHR_IOCTL_SERIAL_GET_TIOCM:
1548 int sarg = 0;
1549 int *targ = (int *)arg;
1550 ioctl(fioc->fd, TIOCMGET, &sarg);
1551 *targ = 0;
1552 if (sarg & TIOCM_CTS)
1553 *targ |= CHR_TIOCM_CTS;
1554 if (sarg & TIOCM_CAR)
1555 *targ |= CHR_TIOCM_CAR;
1556 if (sarg & TIOCM_DSR)
1557 *targ |= CHR_TIOCM_DSR;
1558 if (sarg & TIOCM_RI)
1559 *targ |= CHR_TIOCM_RI;
1560 if (sarg & TIOCM_DTR)
1561 *targ |= CHR_TIOCM_DTR;
1562 if (sarg & TIOCM_RTS)
1563 *targ |= CHR_TIOCM_RTS;
1565 break;
1566 case CHR_IOCTL_SERIAL_SET_TIOCM:
1568 int sarg = *(int *)arg;
1569 int targ = 0;
1570 ioctl(fioc->fd, TIOCMGET, &targ);
1571 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1572 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1573 if (sarg & CHR_TIOCM_CTS)
1574 targ |= TIOCM_CTS;
1575 if (sarg & CHR_TIOCM_CAR)
1576 targ |= TIOCM_CAR;
1577 if (sarg & CHR_TIOCM_DSR)
1578 targ |= TIOCM_DSR;
1579 if (sarg & CHR_TIOCM_RI)
1580 targ |= TIOCM_RI;
1581 if (sarg & CHR_TIOCM_DTR)
1582 targ |= TIOCM_DTR;
1583 if (sarg & CHR_TIOCM_RTS)
1584 targ |= TIOCM_RTS;
1585 ioctl(fioc->fd, TIOCMSET, &targ);
1587 break;
1588 default:
1589 return -ENOTSUP;
1591 return 0;
1594 static void qemu_chr_close_tty(CharDriverState *chr)
1596 fd_chr_close(chr);
1599 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1600 ChardevCommon *backend,
1601 Error **errp)
1603 CharDriverState *chr;
1605 tty_serial_init(fd, 115200, 'N', 8, 1);
1606 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1607 chr->chr_ioctl = tty_serial_ioctl;
1608 chr->chr_close = qemu_chr_close_tty;
1609 return chr;
1611 #endif /* __linux__ || __sun__ */
1613 #if defined(__linux__)
1615 #define HAVE_CHARDEV_PARPORT 1
1617 typedef struct {
1618 int fd;
1619 int mode;
1620 } ParallelCharDriver;
1622 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1624 if (s->mode != mode) {
1625 int m = mode;
1626 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1627 return 0;
1628 s->mode = mode;
1630 return 1;
1633 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1635 ParallelCharDriver *drv = chr->opaque;
1636 int fd = drv->fd;
1637 uint8_t b;
1639 switch(cmd) {
1640 case CHR_IOCTL_PP_READ_DATA:
1641 if (ioctl(fd, PPRDATA, &b) < 0)
1642 return -ENOTSUP;
1643 *(uint8_t *)arg = b;
1644 break;
1645 case CHR_IOCTL_PP_WRITE_DATA:
1646 b = *(uint8_t *)arg;
1647 if (ioctl(fd, PPWDATA, &b) < 0)
1648 return -ENOTSUP;
1649 break;
1650 case CHR_IOCTL_PP_READ_CONTROL:
1651 if (ioctl(fd, PPRCONTROL, &b) < 0)
1652 return -ENOTSUP;
1653 /* Linux gives only the lowest bits, and no way to know data
1654 direction! For better compatibility set the fixed upper
1655 bits. */
1656 *(uint8_t *)arg = b | 0xc0;
1657 break;
1658 case CHR_IOCTL_PP_WRITE_CONTROL:
1659 b = *(uint8_t *)arg;
1660 if (ioctl(fd, PPWCONTROL, &b) < 0)
1661 return -ENOTSUP;
1662 break;
1663 case CHR_IOCTL_PP_READ_STATUS:
1664 if (ioctl(fd, PPRSTATUS, &b) < 0)
1665 return -ENOTSUP;
1666 *(uint8_t *)arg = b;
1667 break;
1668 case CHR_IOCTL_PP_DATA_DIR:
1669 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1670 return -ENOTSUP;
1671 break;
1672 case CHR_IOCTL_PP_EPP_READ_ADDR:
1673 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1674 struct ParallelIOArg *parg = arg;
1675 int n = read(fd, parg->buffer, parg->count);
1676 if (n != parg->count) {
1677 return -EIO;
1680 break;
1681 case CHR_IOCTL_PP_EPP_READ:
1682 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1683 struct ParallelIOArg *parg = arg;
1684 int n = read(fd, parg->buffer, parg->count);
1685 if (n != parg->count) {
1686 return -EIO;
1689 break;
1690 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1691 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1692 struct ParallelIOArg *parg = arg;
1693 int n = write(fd, parg->buffer, parg->count);
1694 if (n != parg->count) {
1695 return -EIO;
1698 break;
1699 case CHR_IOCTL_PP_EPP_WRITE:
1700 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1701 struct ParallelIOArg *parg = arg;
1702 int n = write(fd, parg->buffer, parg->count);
1703 if (n != parg->count) {
1704 return -EIO;
1707 break;
1708 default:
1709 return -ENOTSUP;
1711 return 0;
1714 static void pp_close(CharDriverState *chr)
1716 ParallelCharDriver *drv = chr->opaque;
1717 int fd = drv->fd;
1719 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1720 ioctl(fd, PPRELEASE);
1721 close(fd);
1722 g_free(drv);
1723 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1726 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1727 ChardevCommon *backend,
1728 Error **errp)
1730 CharDriverState *chr;
1731 ParallelCharDriver *drv;
1733 if (ioctl(fd, PPCLAIM) < 0) {
1734 error_setg_errno(errp, errno, "not a parallel port");
1735 close(fd);
1736 return NULL;
1739 chr = qemu_chr_alloc(backend, errp);
1740 if (!chr) {
1741 return NULL;
1744 drv = g_new0(ParallelCharDriver, 1);
1745 chr->opaque = drv;
1746 chr->chr_write = null_chr_write;
1747 chr->chr_ioctl = pp_ioctl;
1748 chr->chr_close = pp_close;
1750 drv->fd = fd;
1751 drv->mode = IEEE1284_MODE_COMPAT;
1753 return chr;
1755 #endif /* __linux__ */
1757 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1759 #define HAVE_CHARDEV_PARPORT 1
1761 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1763 int fd = (int)(intptr_t)chr->opaque;
1764 uint8_t b;
1766 switch(cmd) {
1767 case CHR_IOCTL_PP_READ_DATA:
1768 if (ioctl(fd, PPIGDATA, &b) < 0)
1769 return -ENOTSUP;
1770 *(uint8_t *)arg = b;
1771 break;
1772 case CHR_IOCTL_PP_WRITE_DATA:
1773 b = *(uint8_t *)arg;
1774 if (ioctl(fd, PPISDATA, &b) < 0)
1775 return -ENOTSUP;
1776 break;
1777 case CHR_IOCTL_PP_READ_CONTROL:
1778 if (ioctl(fd, PPIGCTRL, &b) < 0)
1779 return -ENOTSUP;
1780 *(uint8_t *)arg = b;
1781 break;
1782 case CHR_IOCTL_PP_WRITE_CONTROL:
1783 b = *(uint8_t *)arg;
1784 if (ioctl(fd, PPISCTRL, &b) < 0)
1785 return -ENOTSUP;
1786 break;
1787 case CHR_IOCTL_PP_READ_STATUS:
1788 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1789 return -ENOTSUP;
1790 *(uint8_t *)arg = b;
1791 break;
1792 default:
1793 return -ENOTSUP;
1795 return 0;
1798 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1799 ChardevCommon *backend,
1800 Error **errp)
1802 CharDriverState *chr;
1804 chr = qemu_chr_alloc(backend, errp);
1805 if (!chr) {
1806 return NULL;
1808 chr->opaque = (void *)(intptr_t)fd;
1809 chr->chr_write = null_chr_write;
1810 chr->chr_ioctl = pp_ioctl;
1811 chr->explicit_be_open = true;
1812 return chr;
1814 #endif
1816 #else /* _WIN32 */
1818 #define HAVE_CHARDEV_SERIAL 1
1820 typedef struct {
1821 int max_size;
1822 HANDLE hcom, hrecv, hsend;
1823 OVERLAPPED orecv;
1824 BOOL fpipe;
1825 DWORD len;
1827 /* Protected by the CharDriverState chr_write_lock. */
1828 OVERLAPPED osend;
1829 } WinCharState;
1831 typedef struct {
1832 HANDLE hStdIn;
1833 HANDLE hInputReadyEvent;
1834 HANDLE hInputDoneEvent;
1835 HANDLE hInputThread;
1836 uint8_t win_stdio_buf;
1837 } WinStdioCharState;
1839 #define NSENDBUF 2048
1840 #define NRECVBUF 2048
1841 #define MAXCONNECT 1
1842 #define NTIMEOUT 5000
1844 static int win_chr_poll(void *opaque);
1845 static int win_chr_pipe_poll(void *opaque);
1847 static void win_chr_close(CharDriverState *chr)
1849 WinCharState *s = chr->opaque;
1851 if (s->hsend) {
1852 CloseHandle(s->hsend);
1853 s->hsend = NULL;
1855 if (s->hrecv) {
1856 CloseHandle(s->hrecv);
1857 s->hrecv = NULL;
1859 if (s->hcom) {
1860 CloseHandle(s->hcom);
1861 s->hcom = NULL;
1863 if (s->fpipe)
1864 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1865 else
1866 qemu_del_polling_cb(win_chr_poll, chr);
1868 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1871 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1873 WinCharState *s = chr->opaque;
1874 COMMCONFIG comcfg;
1875 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1876 COMSTAT comstat;
1877 DWORD size;
1878 DWORD err;
1880 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1881 if (!s->hsend) {
1882 error_setg(errp, "Failed CreateEvent");
1883 goto fail;
1885 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1886 if (!s->hrecv) {
1887 error_setg(errp, "Failed CreateEvent");
1888 goto fail;
1891 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1892 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1893 if (s->hcom == INVALID_HANDLE_VALUE) {
1894 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1895 s->hcom = NULL;
1896 goto fail;
1899 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1900 error_setg(errp, "Failed SetupComm");
1901 goto fail;
1904 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1905 size = sizeof(COMMCONFIG);
1906 GetDefaultCommConfig(filename, &comcfg, &size);
1907 comcfg.dcb.DCBlength = sizeof(DCB);
1908 CommConfigDialog(filename, NULL, &comcfg);
1910 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1911 error_setg(errp, "Failed SetCommState");
1912 goto fail;
1915 if (!SetCommMask(s->hcom, EV_ERR)) {
1916 error_setg(errp, "Failed SetCommMask");
1917 goto fail;
1920 cto.ReadIntervalTimeout = MAXDWORD;
1921 if (!SetCommTimeouts(s->hcom, &cto)) {
1922 error_setg(errp, "Failed SetCommTimeouts");
1923 goto fail;
1926 if (!ClearCommError(s->hcom, &err, &comstat)) {
1927 error_setg(errp, "Failed ClearCommError");
1928 goto fail;
1930 qemu_add_polling_cb(win_chr_poll, chr);
1931 return 0;
1933 fail:
1934 win_chr_close(chr);
1935 return -1;
1938 /* Called with chr_write_lock held. */
1939 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1941 WinCharState *s = chr->opaque;
1942 DWORD len, ret, size, err;
1944 len = len1;
1945 ZeroMemory(&s->osend, sizeof(s->osend));
1946 s->osend.hEvent = s->hsend;
1947 while (len > 0) {
1948 if (s->hsend)
1949 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1950 else
1951 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1952 if (!ret) {
1953 err = GetLastError();
1954 if (err == ERROR_IO_PENDING) {
1955 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1956 if (ret) {
1957 buf += size;
1958 len -= size;
1959 } else {
1960 break;
1962 } else {
1963 break;
1965 } else {
1966 buf += size;
1967 len -= size;
1970 return len1 - len;
1973 static int win_chr_read_poll(CharDriverState *chr)
1975 WinCharState *s = chr->opaque;
1977 s->max_size = qemu_chr_be_can_write(chr);
1978 return s->max_size;
1981 static void win_chr_readfile(CharDriverState *chr)
1983 WinCharState *s = chr->opaque;
1984 int ret, err;
1985 uint8_t buf[READ_BUF_LEN];
1986 DWORD size;
1988 ZeroMemory(&s->orecv, sizeof(s->orecv));
1989 s->orecv.hEvent = s->hrecv;
1990 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1991 if (!ret) {
1992 err = GetLastError();
1993 if (err == ERROR_IO_PENDING) {
1994 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1998 if (size > 0) {
1999 qemu_chr_be_write(chr, buf, size);
2003 static void win_chr_read(CharDriverState *chr)
2005 WinCharState *s = chr->opaque;
2007 if (s->len > s->max_size)
2008 s->len = s->max_size;
2009 if (s->len == 0)
2010 return;
2012 win_chr_readfile(chr);
2015 static int win_chr_poll(void *opaque)
2017 CharDriverState *chr = opaque;
2018 WinCharState *s = chr->opaque;
2019 COMSTAT status;
2020 DWORD comerr;
2022 ClearCommError(s->hcom, &comerr, &status);
2023 if (status.cbInQue > 0) {
2024 s->len = status.cbInQue;
2025 win_chr_read_poll(chr);
2026 win_chr_read(chr);
2027 return 1;
2029 return 0;
2032 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2033 ChardevCommon *backend,
2034 Error **errp)
2036 CharDriverState *chr;
2037 WinCharState *s;
2039 chr = qemu_chr_alloc(backend, errp);
2040 if (!chr) {
2041 return NULL;
2043 s = g_new0(WinCharState, 1);
2044 chr->opaque = s;
2045 chr->chr_write = win_chr_write;
2046 chr->chr_close = win_chr_close;
2048 if (win_chr_init(chr, filename, errp) < 0) {
2049 g_free(s);
2050 qemu_chr_free_common(chr);
2051 return NULL;
2053 return chr;
2056 static int win_chr_pipe_poll(void *opaque)
2058 CharDriverState *chr = opaque;
2059 WinCharState *s = chr->opaque;
2060 DWORD size;
2062 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2063 if (size > 0) {
2064 s->len = size;
2065 win_chr_read_poll(chr);
2066 win_chr_read(chr);
2067 return 1;
2069 return 0;
2072 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2073 Error **errp)
2075 WinCharState *s = chr->opaque;
2076 OVERLAPPED ov;
2077 int ret;
2078 DWORD size;
2079 char *openname;
2081 s->fpipe = TRUE;
2083 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2084 if (!s->hsend) {
2085 error_setg(errp, "Failed CreateEvent");
2086 goto fail;
2088 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2089 if (!s->hrecv) {
2090 error_setg(errp, "Failed CreateEvent");
2091 goto fail;
2094 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2095 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2096 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2097 PIPE_WAIT,
2098 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2099 g_free(openname);
2100 if (s->hcom == INVALID_HANDLE_VALUE) {
2101 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2102 s->hcom = NULL;
2103 goto fail;
2106 ZeroMemory(&ov, sizeof(ov));
2107 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2108 ret = ConnectNamedPipe(s->hcom, &ov);
2109 if (ret) {
2110 error_setg(errp, "Failed ConnectNamedPipe");
2111 goto fail;
2114 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2115 if (!ret) {
2116 error_setg(errp, "Failed GetOverlappedResult");
2117 if (ov.hEvent) {
2118 CloseHandle(ov.hEvent);
2119 ov.hEvent = NULL;
2121 goto fail;
2124 if (ov.hEvent) {
2125 CloseHandle(ov.hEvent);
2126 ov.hEvent = NULL;
2128 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2129 return 0;
2131 fail:
2132 win_chr_close(chr);
2133 return -1;
2137 static CharDriverState *qemu_chr_open_pipe(const char *id,
2138 ChardevBackend *backend,
2139 ChardevReturn *ret,
2140 Error **errp)
2142 ChardevHostdev *opts = backend->u.pipe;
2143 const char *filename = opts->device;
2144 CharDriverState *chr;
2145 WinCharState *s;
2146 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.pipe);
2148 chr = qemu_chr_alloc(common, errp);
2149 if (!chr) {
2150 return NULL;
2152 s = g_new0(WinCharState, 1);
2153 chr->opaque = s;
2154 chr->chr_write = win_chr_write;
2155 chr->chr_close = win_chr_close;
2157 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2158 g_free(s);
2159 qemu_chr_free_common(chr);
2160 return NULL;
2162 return chr;
2165 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2166 ChardevCommon *backend,
2167 Error **errp)
2169 CharDriverState *chr;
2170 WinCharState *s;
2172 chr = qemu_chr_alloc(backend, errp);
2173 if (!chr) {
2174 return NULL;
2176 s = g_new0(WinCharState, 1);
2177 s->hcom = fd_out;
2178 chr->opaque = s;
2179 chr->chr_write = win_chr_write;
2180 return chr;
2183 static CharDriverState *qemu_chr_open_win_con(const char *id,
2184 ChardevBackend *backend,
2185 ChardevReturn *ret,
2186 Error **errp)
2188 ChardevCommon *common = qapi_ChardevDummy_base(backend->u.console);
2189 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2190 common, errp);
2193 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2195 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2196 DWORD dwSize;
2197 int len1;
2199 len1 = len;
2201 while (len1 > 0) {
2202 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2203 break;
2205 buf += dwSize;
2206 len1 -= dwSize;
2209 return len - len1;
2212 static void win_stdio_wait_func(void *opaque)
2214 CharDriverState *chr = opaque;
2215 WinStdioCharState *stdio = chr->opaque;
2216 INPUT_RECORD buf[4];
2217 int ret;
2218 DWORD dwSize;
2219 int i;
2221 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2223 if (!ret) {
2224 /* Avoid error storm */
2225 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2226 return;
2229 for (i = 0; i < dwSize; i++) {
2230 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2232 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2233 int j;
2234 if (kev->uChar.AsciiChar != 0) {
2235 for (j = 0; j < kev->wRepeatCount; j++) {
2236 if (qemu_chr_be_can_write(chr)) {
2237 uint8_t c = kev->uChar.AsciiChar;
2238 qemu_chr_be_write(chr, &c, 1);
2246 static DWORD WINAPI win_stdio_thread(LPVOID param)
2248 CharDriverState *chr = param;
2249 WinStdioCharState *stdio = chr->opaque;
2250 int ret;
2251 DWORD dwSize;
2253 while (1) {
2255 /* Wait for one byte */
2256 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2258 /* Exit in case of error, continue if nothing read */
2259 if (!ret) {
2260 break;
2262 if (!dwSize) {
2263 continue;
2266 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2267 if (stdio->win_stdio_buf == '\r') {
2268 continue;
2271 /* Signal the main thread and wait until the byte was eaten */
2272 if (!SetEvent(stdio->hInputReadyEvent)) {
2273 break;
2275 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2276 != WAIT_OBJECT_0) {
2277 break;
2281 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2282 return 0;
2285 static void win_stdio_thread_wait_func(void *opaque)
2287 CharDriverState *chr = opaque;
2288 WinStdioCharState *stdio = chr->opaque;
2290 if (qemu_chr_be_can_write(chr)) {
2291 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2294 SetEvent(stdio->hInputDoneEvent);
2297 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2299 WinStdioCharState *stdio = chr->opaque;
2300 DWORD dwMode = 0;
2302 GetConsoleMode(stdio->hStdIn, &dwMode);
2304 if (echo) {
2305 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2306 } else {
2307 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2311 static void win_stdio_close(CharDriverState *chr)
2313 WinStdioCharState *stdio = chr->opaque;
2315 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2316 CloseHandle(stdio->hInputReadyEvent);
2318 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2319 CloseHandle(stdio->hInputDoneEvent);
2321 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2322 TerminateThread(stdio->hInputThread, 0);
2325 g_free(chr->opaque);
2326 g_free(chr);
2329 static CharDriverState *qemu_chr_open_stdio(const char *id,
2330 ChardevBackend *backend,
2331 ChardevReturn *ret,
2332 Error **errp)
2334 CharDriverState *chr;
2335 WinStdioCharState *stdio;
2336 DWORD dwMode;
2337 int is_console = 0;
2338 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio);
2340 chr = qemu_chr_alloc(common, errp);
2341 if (!chr) {
2342 return NULL;
2344 stdio = g_new0(WinStdioCharState, 1);
2346 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2347 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2348 error_setg(errp, "cannot open stdio: invalid handle");
2349 return NULL;
2352 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2354 chr->opaque = stdio;
2355 chr->chr_write = win_stdio_write;
2356 chr->chr_close = win_stdio_close;
2358 if (is_console) {
2359 if (qemu_add_wait_object(stdio->hStdIn,
2360 win_stdio_wait_func, chr)) {
2361 error_setg(errp, "qemu_add_wait_object: failed");
2362 goto err1;
2364 } else {
2365 DWORD dwId;
2367 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2368 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2369 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2370 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2371 error_setg(errp, "cannot create event");
2372 goto err2;
2374 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2375 win_stdio_thread_wait_func, chr)) {
2376 error_setg(errp, "qemu_add_wait_object: failed");
2377 goto err2;
2379 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2380 chr, 0, &dwId);
2382 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2383 error_setg(errp, "cannot create stdio thread");
2384 goto err3;
2388 dwMode |= ENABLE_LINE_INPUT;
2390 if (is_console) {
2391 /* set the terminal in raw mode */
2392 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2393 dwMode |= ENABLE_PROCESSED_INPUT;
2396 SetConsoleMode(stdio->hStdIn, dwMode);
2398 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2399 qemu_chr_fe_set_echo(chr, false);
2401 return chr;
2403 err3:
2404 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2405 err2:
2406 CloseHandle(stdio->hInputReadyEvent);
2407 CloseHandle(stdio->hInputDoneEvent);
2408 err1:
2409 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2410 return NULL;
2412 #endif /* !_WIN32 */
2415 /***********************************************************/
2416 /* UDP Net console */
2418 typedef struct {
2419 QIOChannel *ioc;
2420 uint8_t buf[READ_BUF_LEN];
2421 int bufcnt;
2422 int bufptr;
2423 int max_size;
2424 } NetCharDriver;
2426 /* Called with chr_write_lock held. */
2427 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2429 NetCharDriver *s = chr->opaque;
2431 return qio_channel_write(
2432 s->ioc, (const char *)buf, len, NULL);
2435 static int udp_chr_read_poll(void *opaque)
2437 CharDriverState *chr = opaque;
2438 NetCharDriver *s = chr->opaque;
2440 s->max_size = qemu_chr_be_can_write(chr);
2442 /* If there were any stray characters in the queue process them
2443 * first
2445 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2446 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2447 s->bufptr++;
2448 s->max_size = qemu_chr_be_can_write(chr);
2450 return s->max_size;
2453 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2455 CharDriverState *chr = opaque;
2456 NetCharDriver *s = chr->opaque;
2457 ssize_t ret;
2459 if (s->max_size == 0) {
2460 return TRUE;
2462 ret = qio_channel_read(
2463 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2464 if (ret <= 0) {
2465 remove_fd_in_watch(chr);
2466 return FALSE;
2468 s->bufcnt = ret;
2470 s->bufptr = 0;
2471 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2472 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2473 s->bufptr++;
2474 s->max_size = qemu_chr_be_can_write(chr);
2477 return TRUE;
2480 static void udp_chr_update_read_handler(CharDriverState *chr)
2482 NetCharDriver *s = chr->opaque;
2484 remove_fd_in_watch(chr);
2485 if (s->ioc) {
2486 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2487 udp_chr_read_poll,
2488 udp_chr_read, chr);
2492 static void udp_chr_close(CharDriverState *chr)
2494 NetCharDriver *s = chr->opaque;
2496 remove_fd_in_watch(chr);
2497 if (s->ioc) {
2498 object_unref(OBJECT(s->ioc));
2500 g_free(s);
2501 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2504 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2505 ChardevCommon *backend,
2506 Error **errp)
2508 CharDriverState *chr = NULL;
2509 NetCharDriver *s = NULL;
2511 chr = qemu_chr_alloc(backend, errp);
2512 if (!chr) {
2513 return NULL;
2515 s = g_new0(NetCharDriver, 1);
2517 s->ioc = QIO_CHANNEL(sioc);
2518 s->bufcnt = 0;
2519 s->bufptr = 0;
2520 chr->opaque = s;
2521 chr->chr_write = udp_chr_write;
2522 chr->chr_update_read_handler = udp_chr_update_read_handler;
2523 chr->chr_close = udp_chr_close;
2524 /* be isn't opened until we get a connection */
2525 chr->explicit_be_open = true;
2526 return chr;
2529 /***********************************************************/
2530 /* TCP Net console */
2532 typedef struct {
2533 QIOChannel *ioc; /* Client I/O channel */
2534 QIOChannelSocket *sioc; /* Client master channel */
2535 QIOChannelSocket *listen_ioc;
2536 guint listen_tag;
2537 QCryptoTLSCreds *tls_creds;
2538 int connected;
2539 int max_size;
2540 int do_telnetopt;
2541 int do_nodelay;
2542 int is_unix;
2543 int *read_msgfds;
2544 size_t read_msgfds_num;
2545 int *write_msgfds;
2546 size_t write_msgfds_num;
2548 SocketAddress *addr;
2549 bool is_listen;
2550 bool is_telnet;
2552 guint reconnect_timer;
2553 int64_t reconnect_time;
2554 bool connect_err_reported;
2555 } TCPCharDriver;
2557 static gboolean socket_reconnect_timeout(gpointer opaque);
2559 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2561 TCPCharDriver *s = chr->opaque;
2562 assert(s->connected == 0);
2563 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2564 socket_reconnect_timeout, chr);
2567 static void check_report_connect_error(CharDriverState *chr,
2568 Error *err)
2570 TCPCharDriver *s = chr->opaque;
2572 if (!s->connect_err_reported) {
2573 error_report("Unable to connect character device %s: %s",
2574 chr->label, error_get_pretty(err));
2575 s->connect_err_reported = true;
2577 qemu_chr_socket_restart_timer(chr);
2580 static gboolean tcp_chr_accept(QIOChannel *chan,
2581 GIOCondition cond,
2582 void *opaque);
2584 /* Called with chr_write_lock held. */
2585 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2587 TCPCharDriver *s = chr->opaque;
2588 if (s->connected) {
2589 int ret = io_channel_send_full(s->ioc, buf, len,
2590 s->write_msgfds,
2591 s->write_msgfds_num);
2593 /* free the written msgfds, no matter what */
2594 if (s->write_msgfds_num) {
2595 g_free(s->write_msgfds);
2596 s->write_msgfds = 0;
2597 s->write_msgfds_num = 0;
2600 return ret;
2601 } else {
2602 /* XXX: indicate an error ? */
2603 return len;
2607 static int tcp_chr_read_poll(void *opaque)
2609 CharDriverState *chr = opaque;
2610 TCPCharDriver *s = chr->opaque;
2611 if (!s->connected)
2612 return 0;
2613 s->max_size = qemu_chr_be_can_write(chr);
2614 return s->max_size;
2617 #define IAC 255
2618 #define IAC_BREAK 243
2619 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2620 TCPCharDriver *s,
2621 uint8_t *buf, int *size)
2623 /* Handle any telnet client's basic IAC options to satisfy char by
2624 * char mode with no echo. All IAC options will be removed from
2625 * the buf and the do_telnetopt variable will be used to track the
2626 * state of the width of the IAC information.
2628 * IAC commands come in sets of 3 bytes with the exception of the
2629 * "IAC BREAK" command and the double IAC.
2632 int i;
2633 int j = 0;
2635 for (i = 0; i < *size; i++) {
2636 if (s->do_telnetopt > 1) {
2637 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2638 /* Double IAC means send an IAC */
2639 if (j != i)
2640 buf[j] = buf[i];
2641 j++;
2642 s->do_telnetopt = 1;
2643 } else {
2644 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2645 /* Handle IAC break commands by sending a serial break */
2646 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2647 s->do_telnetopt++;
2649 s->do_telnetopt++;
2651 if (s->do_telnetopt >= 4) {
2652 s->do_telnetopt = 1;
2654 } else {
2655 if ((unsigned char)buf[i] == IAC) {
2656 s->do_telnetopt = 2;
2657 } else {
2658 if (j != i)
2659 buf[j] = buf[i];
2660 j++;
2664 *size = j;
2667 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2669 TCPCharDriver *s = chr->opaque;
2670 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2672 assert(num <= TCP_MAX_FDS);
2674 if (to_copy) {
2675 int i;
2677 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2679 /* Close unused fds */
2680 for (i = to_copy; i < s->read_msgfds_num; i++) {
2681 close(s->read_msgfds[i]);
2684 g_free(s->read_msgfds);
2685 s->read_msgfds = 0;
2686 s->read_msgfds_num = 0;
2689 return to_copy;
2692 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2694 TCPCharDriver *s = chr->opaque;
2696 if (!qio_channel_has_feature(s->ioc,
2697 QIO_CHANNEL_FEATURE_FD_PASS)) {
2698 return -1;
2700 /* clear old pending fd array */
2701 g_free(s->write_msgfds);
2703 if (num) {
2704 s->write_msgfds = g_new(int, num);
2705 memcpy(s->write_msgfds, fds, num * sizeof(int));
2708 s->write_msgfds_num = num;
2710 return 0;
2713 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2715 TCPCharDriver *s = chr->opaque;
2716 struct iovec iov = { .iov_base = buf, .iov_len = len };
2717 int ret;
2718 size_t i;
2719 int *msgfds = NULL;
2720 size_t msgfds_num = 0;
2722 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2723 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2724 &msgfds, &msgfds_num,
2725 NULL);
2726 } else {
2727 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2728 NULL, NULL,
2729 NULL);
2732 if (msgfds_num) {
2733 /* close and clean read_msgfds */
2734 for (i = 0; i < s->read_msgfds_num; i++) {
2735 close(s->read_msgfds[i]);
2738 if (s->read_msgfds_num) {
2739 g_free(s->read_msgfds);
2742 s->read_msgfds = msgfds;
2743 s->read_msgfds_num = msgfds_num;
2746 for (i = 0; i < s->read_msgfds_num; i++) {
2747 int fd = s->read_msgfds[i];
2748 if (fd < 0) {
2749 continue;
2752 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2753 qemu_set_block(fd);
2755 #ifndef MSG_CMSG_CLOEXEC
2756 qemu_set_cloexec(fd);
2757 #endif
2760 return ret;
2763 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2765 TCPCharDriver *s = chr->opaque;
2766 return qio_channel_create_watch(s->ioc, cond);
2769 static void tcp_chr_disconnect(CharDriverState *chr)
2771 TCPCharDriver *s = chr->opaque;
2773 s->connected = 0;
2774 if (s->listen_ioc) {
2775 s->listen_tag = qio_channel_add_watch(
2776 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
2778 remove_fd_in_watch(chr);
2779 object_unref(OBJECT(s->sioc));
2780 s->sioc = NULL;
2781 object_unref(OBJECT(s->ioc));
2782 s->ioc = NULL;
2783 g_free(chr->filename);
2784 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
2785 s->is_listen, s->is_telnet);
2786 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2787 if (s->reconnect_time) {
2788 qemu_chr_socket_restart_timer(chr);
2792 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2794 CharDriverState *chr = opaque;
2795 TCPCharDriver *s = chr->opaque;
2796 uint8_t buf[READ_BUF_LEN];
2797 int len, size;
2799 if (!s->connected || s->max_size <= 0) {
2800 return TRUE;
2802 len = sizeof(buf);
2803 if (len > s->max_size)
2804 len = s->max_size;
2805 size = tcp_chr_recv(chr, (void *)buf, len);
2806 if (size == 0 || size == -1) {
2807 /* connection closed */
2808 tcp_chr_disconnect(chr);
2809 } else if (size > 0) {
2810 if (s->do_telnetopt)
2811 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2812 if (size > 0)
2813 qemu_chr_be_write(chr, buf, size);
2816 return TRUE;
2819 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2821 TCPCharDriver *s = chr->opaque;
2822 int size;
2824 if (!s->connected) {
2825 return 0;
2828 size = tcp_chr_recv(chr, (void *) buf, len);
2829 if (size == 0) {
2830 /* connection closed */
2831 tcp_chr_disconnect(chr);
2834 return size;
2837 static void tcp_chr_connect(void *opaque)
2839 CharDriverState *chr = opaque;
2840 TCPCharDriver *s = chr->opaque;
2842 g_free(chr->filename);
2843 chr->filename = sockaddr_to_str(
2844 &s->sioc->localAddr, s->sioc->localAddrLen,
2845 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
2846 s->is_listen, s->is_telnet);
2848 s->connected = 1;
2849 if (s->ioc) {
2850 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2851 tcp_chr_read_poll,
2852 tcp_chr_read, chr);
2854 qemu_chr_be_generic_open(chr);
2857 static void tcp_chr_update_read_handler(CharDriverState *chr)
2859 TCPCharDriver *s = chr->opaque;
2861 if (!s->connected) {
2862 return;
2865 remove_fd_in_watch(chr);
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);
2873 typedef struct {
2874 CharDriverState *chr;
2875 char buf[12];
2876 size_t buflen;
2877 } TCPCharDriverTelnetInit;
2879 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
2880 GIOCondition cond G_GNUC_UNUSED,
2881 gpointer user_data)
2883 TCPCharDriverTelnetInit *init = user_data;
2884 ssize_t ret;
2886 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
2887 if (ret < 0) {
2888 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2889 ret = 0;
2890 } else {
2891 tcp_chr_disconnect(init->chr);
2892 return FALSE;
2895 init->buflen -= ret;
2897 if (init->buflen == 0) {
2898 tcp_chr_connect(init->chr);
2899 return FALSE;
2902 memmove(init->buf, init->buf + ret, init->buflen);
2904 return TRUE;
2907 static void tcp_chr_telnet_init(CharDriverState *chr)
2909 TCPCharDriver *s = chr->opaque;
2910 TCPCharDriverTelnetInit *init =
2911 g_new0(TCPCharDriverTelnetInit, 1);
2912 size_t n = 0;
2914 init->chr = chr;
2915 init->buflen = 12;
2917 #define IACSET(x, a, b, c) \
2918 do { \
2919 x[n++] = a; \
2920 x[n++] = b; \
2921 x[n++] = c; \
2922 } while (0)
2924 /* Prep the telnet negotion to put telnet in binary,
2925 * no echo, single char mode */
2926 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2927 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2928 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2929 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2931 #undef IACSET
2933 qio_channel_add_watch(
2934 s->ioc, G_IO_OUT,
2935 tcp_chr_telnet_init_io,
2936 init, NULL);
2940 static void tcp_chr_tls_handshake(Object *source,
2941 Error *err,
2942 gpointer user_data)
2944 CharDriverState *chr = user_data;
2945 TCPCharDriver *s = chr->opaque;
2947 if (err) {
2948 tcp_chr_disconnect(chr);
2949 } else {
2950 if (s->do_telnetopt) {
2951 tcp_chr_telnet_init(chr);
2952 } else {
2953 tcp_chr_connect(chr);
2959 static void tcp_chr_tls_init(CharDriverState *chr)
2961 TCPCharDriver *s = chr->opaque;
2962 QIOChannelTLS *tioc;
2963 Error *err = NULL;
2965 if (s->is_listen) {
2966 tioc = qio_channel_tls_new_server(
2967 s->ioc, s->tls_creds,
2968 NULL, /* XXX Use an ACL */
2969 &err);
2970 } else {
2971 tioc = qio_channel_tls_new_client(
2972 s->ioc, s->tls_creds,
2973 s->addr->u.inet->host,
2974 &err);
2976 if (tioc == NULL) {
2977 error_free(err);
2978 tcp_chr_disconnect(chr);
2980 object_unref(OBJECT(s->ioc));
2981 s->ioc = QIO_CHANNEL(tioc);
2983 qio_channel_tls_handshake(tioc,
2984 tcp_chr_tls_handshake,
2985 chr,
2986 NULL);
2990 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
2992 TCPCharDriver *s = chr->opaque;
2993 if (s->ioc != NULL) {
2994 return -1;
2997 s->ioc = QIO_CHANNEL(sioc);
2998 object_ref(OBJECT(sioc));
2999 s->sioc = sioc;
3000 object_ref(OBJECT(sioc));
3002 if (s->do_nodelay) {
3003 qio_channel_set_delay(s->ioc, false);
3005 if (s->listen_tag) {
3006 g_source_remove(s->listen_tag);
3007 s->listen_tag = 0;
3010 if (s->tls_creds) {
3011 tcp_chr_tls_init(chr);
3012 } else {
3013 if (s->do_telnetopt) {
3014 tcp_chr_telnet_init(chr);
3015 } else {
3016 tcp_chr_connect(chr);
3020 return 0;
3024 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3026 int ret;
3027 QIOChannelSocket *sioc;
3029 sioc = qio_channel_socket_new_fd(fd, NULL);
3030 if (!sioc) {
3031 return -1;
3033 qio_channel_set_blocking(QIO_CHANNEL(sioc), false, NULL);
3034 ret = tcp_chr_new_client(chr, sioc);
3035 object_unref(OBJECT(sioc));
3036 return ret;
3039 static gboolean tcp_chr_accept(QIOChannel *channel,
3040 GIOCondition cond,
3041 void *opaque)
3043 CharDriverState *chr = opaque;
3044 QIOChannelSocket *sioc;
3046 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3047 NULL);
3048 if (!sioc) {
3049 return TRUE;
3052 tcp_chr_new_client(chr, sioc);
3054 object_unref(OBJECT(sioc));
3056 return TRUE;
3059 static void tcp_chr_close(CharDriverState *chr)
3061 TCPCharDriver *s = chr->opaque;
3062 int i;
3064 if (s->reconnect_timer) {
3065 g_source_remove(s->reconnect_timer);
3066 s->reconnect_timer = 0;
3068 qapi_free_SocketAddress(s->addr);
3069 remove_fd_in_watch(chr);
3070 if (s->ioc) {
3071 object_unref(OBJECT(s->ioc));
3073 if (s->listen_tag) {
3074 g_source_remove(s->listen_tag);
3075 s->listen_tag = 0;
3077 if (s->listen_ioc) {
3078 object_unref(OBJECT(s->listen_ioc));
3080 if (s->read_msgfds_num) {
3081 for (i = 0; i < s->read_msgfds_num; i++) {
3082 close(s->read_msgfds[i]);
3084 g_free(s->read_msgfds);
3086 if (s->tls_creds) {
3087 object_unref(OBJECT(s->tls_creds));
3089 if (s->write_msgfds_num) {
3090 g_free(s->write_msgfds);
3092 g_free(s);
3093 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3096 static void qemu_chr_finish_socket_connection(CharDriverState *chr,
3097 QIOChannelSocket *sioc)
3099 TCPCharDriver *s = chr->opaque;
3101 if (s->is_listen) {
3102 s->listen_ioc = sioc;
3103 s->listen_tag = qio_channel_add_watch(
3104 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
3105 } else {
3106 tcp_chr_new_client(chr, sioc);
3107 object_unref(OBJECT(sioc));
3111 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3113 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3114 CharDriverState *chr = opaque;
3115 TCPCharDriver *s = chr->opaque;
3117 if (err) {
3118 check_report_connect_error(chr, err);
3119 object_unref(src);
3120 return;
3123 s->connect_err_reported = false;
3124 qemu_chr_finish_socket_connection(chr, sioc);
3127 static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp)
3129 TCPCharDriver *s = chr->opaque;
3130 QIOChannelSocket *sioc = qio_channel_socket_new();
3132 if (s->is_listen) {
3133 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
3134 goto fail;
3136 qemu_chr_finish_socket_connection(chr, sioc);
3137 } else if (s->reconnect_time) {
3138 qio_channel_socket_connect_async(sioc, s->addr,
3139 qemu_chr_socket_connected,
3140 chr, NULL);
3141 } else {
3142 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3143 goto fail;
3145 qemu_chr_finish_socket_connection(chr, sioc);
3148 return true;
3150 fail:
3151 object_unref(OBJECT(sioc));
3152 return false;
3155 /*********************************************************/
3156 /* Ring buffer chardev */
3158 typedef struct {
3159 size_t size;
3160 size_t prod;
3161 size_t cons;
3162 uint8_t *cbuf;
3163 } RingBufCharDriver;
3165 static size_t ringbuf_count(const CharDriverState *chr)
3167 const RingBufCharDriver *d = chr->opaque;
3169 return d->prod - d->cons;
3172 /* Called with chr_write_lock held. */
3173 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3175 RingBufCharDriver *d = chr->opaque;
3176 int i;
3178 if (!buf || (len < 0)) {
3179 return -1;
3182 for (i = 0; i < len; i++ ) {
3183 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3184 if (d->prod - d->cons > d->size) {
3185 d->cons = d->prod - d->size;
3189 return 0;
3192 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3194 RingBufCharDriver *d = chr->opaque;
3195 int i;
3197 qemu_mutex_lock(&chr->chr_write_lock);
3198 for (i = 0; i < len && d->cons != d->prod; i++) {
3199 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3201 qemu_mutex_unlock(&chr->chr_write_lock);
3203 return i;
3206 static void ringbuf_chr_close(struct CharDriverState *chr)
3208 RingBufCharDriver *d = chr->opaque;
3210 g_free(d->cbuf);
3211 g_free(d);
3212 chr->opaque = NULL;
3215 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3216 ChardevBackend *backend,
3217 ChardevReturn *ret,
3218 Error **errp)
3220 ChardevRingbuf *opts = backend->u.ringbuf;
3221 ChardevCommon *common = qapi_ChardevRingbuf_base(backend->u.ringbuf);
3222 CharDriverState *chr;
3223 RingBufCharDriver *d;
3225 chr = qemu_chr_alloc(common, errp);
3226 if (!chr) {
3227 return NULL;
3229 d = g_malloc(sizeof(*d));
3231 d->size = opts->has_size ? opts->size : 65536;
3233 /* The size must be power of 2 */
3234 if (d->size & (d->size - 1)) {
3235 error_setg(errp, "size of ringbuf chardev must be power of two");
3236 goto fail;
3239 d->prod = 0;
3240 d->cons = 0;
3241 d->cbuf = g_malloc0(d->size);
3243 chr->opaque = d;
3244 chr->chr_write = ringbuf_chr_write;
3245 chr->chr_close = ringbuf_chr_close;
3247 return chr;
3249 fail:
3250 g_free(d);
3251 qemu_chr_free_common(chr);
3252 return NULL;
3255 bool chr_is_ringbuf(const CharDriverState *chr)
3257 return chr->chr_write == ringbuf_chr_write;
3260 void qmp_ringbuf_write(const char *device, const char *data,
3261 bool has_format, enum DataFormat format,
3262 Error **errp)
3264 CharDriverState *chr;
3265 const uint8_t *write_data;
3266 int ret;
3267 gsize write_count;
3269 chr = qemu_chr_find(device);
3270 if (!chr) {
3271 error_setg(errp, "Device '%s' not found", device);
3272 return;
3275 if (!chr_is_ringbuf(chr)) {
3276 error_setg(errp,"%s is not a ringbuf device", device);
3277 return;
3280 if (has_format && (format == DATA_FORMAT_BASE64)) {
3281 write_data = qbase64_decode(data, -1,
3282 &write_count,
3283 errp);
3284 if (!write_data) {
3285 return;
3287 } else {
3288 write_data = (uint8_t *)data;
3289 write_count = strlen(data);
3292 ret = ringbuf_chr_write(chr, write_data, write_count);
3294 if (write_data != (uint8_t *)data) {
3295 g_free((void *)write_data);
3298 if (ret < 0) {
3299 error_setg(errp, "Failed to write to device %s", device);
3300 return;
3304 char *qmp_ringbuf_read(const char *device, int64_t size,
3305 bool has_format, enum DataFormat format,
3306 Error **errp)
3308 CharDriverState *chr;
3309 uint8_t *read_data;
3310 size_t count;
3311 char *data;
3313 chr = qemu_chr_find(device);
3314 if (!chr) {
3315 error_setg(errp, "Device '%s' not found", device);
3316 return NULL;
3319 if (!chr_is_ringbuf(chr)) {
3320 error_setg(errp,"%s is not a ringbuf device", device);
3321 return NULL;
3324 if (size <= 0) {
3325 error_setg(errp, "size must be greater than zero");
3326 return NULL;
3329 count = ringbuf_count(chr);
3330 size = size > count ? count : size;
3331 read_data = g_malloc(size + 1);
3333 ringbuf_chr_read(chr, read_data, size);
3335 if (has_format && (format == DATA_FORMAT_BASE64)) {
3336 data = g_base64_encode(read_data, size);
3337 g_free(read_data);
3338 } else {
3340 * FIXME should read only complete, valid UTF-8 characters up
3341 * to @size bytes. Invalid sequences should be replaced by a
3342 * suitable replacement character. Except when (and only
3343 * when) ring buffer lost characters since last read, initial
3344 * continuation characters should be dropped.
3346 read_data[size] = 0;
3347 data = (char *)read_data;
3350 return data;
3353 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3355 char host[65], port[33], width[8], height[8];
3356 int pos;
3357 const char *p;
3358 QemuOpts *opts;
3359 Error *local_err = NULL;
3361 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3362 if (local_err) {
3363 error_report_err(local_err);
3364 return NULL;
3367 if (strstart(filename, "mon:", &p)) {
3368 filename = p;
3369 qemu_opt_set(opts, "mux", "on", &error_abort);
3370 if (strcmp(filename, "stdio") == 0) {
3371 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3372 * but pass it to the guest. Handle this only for compat syntax,
3373 * for -chardev syntax we have special option for this.
3374 * This is what -nographic did, redirecting+muxing serial+monitor
3375 * to stdio causing Ctrl+C to be passed to guest. */
3376 qemu_opt_set(opts, "signal", "off", &error_abort);
3380 if (strcmp(filename, "null") == 0 ||
3381 strcmp(filename, "pty") == 0 ||
3382 strcmp(filename, "msmouse") == 0 ||
3383 strcmp(filename, "braille") == 0 ||
3384 strcmp(filename, "testdev") == 0 ||
3385 strcmp(filename, "stdio") == 0) {
3386 qemu_opt_set(opts, "backend", filename, &error_abort);
3387 return opts;
3389 if (strstart(filename, "vc", &p)) {
3390 qemu_opt_set(opts, "backend", "vc", &error_abort);
3391 if (*p == ':') {
3392 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3393 /* pixels */
3394 qemu_opt_set(opts, "width", width, &error_abort);
3395 qemu_opt_set(opts, "height", height, &error_abort);
3396 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3397 /* chars */
3398 qemu_opt_set(opts, "cols", width, &error_abort);
3399 qemu_opt_set(opts, "rows", height, &error_abort);
3400 } else {
3401 goto fail;
3404 return opts;
3406 if (strcmp(filename, "con:") == 0) {
3407 qemu_opt_set(opts, "backend", "console", &error_abort);
3408 return opts;
3410 if (strstart(filename, "COM", NULL)) {
3411 qemu_opt_set(opts, "backend", "serial", &error_abort);
3412 qemu_opt_set(opts, "path", filename, &error_abort);
3413 return opts;
3415 if (strstart(filename, "file:", &p)) {
3416 qemu_opt_set(opts, "backend", "file", &error_abort);
3417 qemu_opt_set(opts, "path", p, &error_abort);
3418 return opts;
3420 if (strstart(filename, "pipe:", &p)) {
3421 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3422 qemu_opt_set(opts, "path", p, &error_abort);
3423 return opts;
3425 if (strstart(filename, "tcp:", &p) ||
3426 strstart(filename, "telnet:", &p)) {
3427 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3428 host[0] = 0;
3429 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3430 goto fail;
3432 qemu_opt_set(opts, "backend", "socket", &error_abort);
3433 qemu_opt_set(opts, "host", host, &error_abort);
3434 qemu_opt_set(opts, "port", port, &error_abort);
3435 if (p[pos] == ',') {
3436 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3437 if (local_err) {
3438 error_report_err(local_err);
3439 goto fail;
3442 if (strstart(filename, "telnet:", &p))
3443 qemu_opt_set(opts, "telnet", "on", &error_abort);
3444 return opts;
3446 if (strstart(filename, "udp:", &p)) {
3447 qemu_opt_set(opts, "backend", "udp", &error_abort);
3448 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3449 host[0] = 0;
3450 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3451 goto fail;
3454 qemu_opt_set(opts, "host", host, &error_abort);
3455 qemu_opt_set(opts, "port", port, &error_abort);
3456 if (p[pos] == '@') {
3457 p += pos + 1;
3458 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3459 host[0] = 0;
3460 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3461 goto fail;
3464 qemu_opt_set(opts, "localaddr", host, &error_abort);
3465 qemu_opt_set(opts, "localport", port, &error_abort);
3467 return opts;
3469 if (strstart(filename, "unix:", &p)) {
3470 qemu_opt_set(opts, "backend", "socket", &error_abort);
3471 qemu_opts_do_parse(opts, p, "path", &local_err);
3472 if (local_err) {
3473 error_report_err(local_err);
3474 goto fail;
3476 return opts;
3478 if (strstart(filename, "/dev/parport", NULL) ||
3479 strstart(filename, "/dev/ppi", NULL)) {
3480 qemu_opt_set(opts, "backend", "parport", &error_abort);
3481 qemu_opt_set(opts, "path", filename, &error_abort);
3482 return opts;
3484 if (strstart(filename, "/dev/", NULL)) {
3485 qemu_opt_set(opts, "backend", "tty", &error_abort);
3486 qemu_opt_set(opts, "path", filename, &error_abort);
3487 return opts;
3490 fail:
3491 qemu_opts_del(opts);
3492 return NULL;
3495 static void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3497 const char *logfile = qemu_opt_get(opts, "logfile");
3499 backend->has_logfile = logfile != NULL;
3500 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3502 backend->has_logappend = true;
3503 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3507 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3508 Error **errp)
3510 const char *path = qemu_opt_get(opts, "path");
3512 if (path == NULL) {
3513 error_setg(errp, "chardev: file: no filename given");
3514 return;
3516 backend->u.file = g_new0(ChardevFile, 1);
3517 qemu_chr_parse_common(opts, qapi_ChardevFile_base(backend->u.file));
3518 backend->u.file->out = g_strdup(path);
3520 backend->u.file->has_append = true;
3521 backend->u.file->append = qemu_opt_get_bool(opts, "append", false);
3524 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3525 Error **errp)
3527 backend->u.stdio = g_new0(ChardevStdio, 1);
3528 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(backend->u.stdio));
3529 backend->u.stdio->has_signal = true;
3530 backend->u.stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3533 #ifdef HAVE_CHARDEV_SERIAL
3534 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3535 Error **errp)
3537 const char *device = qemu_opt_get(opts, "path");
3539 if (device == NULL) {
3540 error_setg(errp, "chardev: serial/tty: no device path given");
3541 return;
3543 backend->u.serial = g_new0(ChardevHostdev, 1);
3544 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.serial));
3545 backend->u.serial->device = g_strdup(device);
3547 #endif
3549 #ifdef HAVE_CHARDEV_PARPORT
3550 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3551 Error **errp)
3553 const char *device = qemu_opt_get(opts, "path");
3555 if (device == NULL) {
3556 error_setg(errp, "chardev: parallel: no device path given");
3557 return;
3559 backend->u.parallel = g_new0(ChardevHostdev, 1);
3560 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.parallel));
3561 backend->u.parallel->device = g_strdup(device);
3563 #endif
3565 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3566 Error **errp)
3568 const char *device = qemu_opt_get(opts, "path");
3570 if (device == NULL) {
3571 error_setg(errp, "chardev: pipe: no device path given");
3572 return;
3574 backend->u.pipe = g_new0(ChardevHostdev, 1);
3575 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.pipe));
3576 backend->u.pipe->device = g_strdup(device);
3579 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3580 Error **errp)
3582 int val;
3584 backend->u.ringbuf = g_new0(ChardevRingbuf, 1);
3585 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(backend->u.ringbuf));
3587 val = qemu_opt_get_size(opts, "size", 0);
3588 if (val != 0) {
3589 backend->u.ringbuf->has_size = true;
3590 backend->u.ringbuf->size = val;
3594 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3595 Error **errp)
3597 const char *chardev = qemu_opt_get(opts, "chardev");
3599 if (chardev == NULL) {
3600 error_setg(errp, "chardev: mux: no chardev given");
3601 return;
3603 backend->u.mux = g_new0(ChardevMux, 1);
3604 qemu_chr_parse_common(opts, qapi_ChardevMux_base(backend->u.mux));
3605 backend->u.mux->chardev = g_strdup(chardev);
3608 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3609 Error **errp)
3611 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3612 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3613 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3614 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3615 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3616 const char *path = qemu_opt_get(opts, "path");
3617 const char *host = qemu_opt_get(opts, "host");
3618 const char *port = qemu_opt_get(opts, "port");
3619 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3620 SocketAddress *addr;
3622 if (!path) {
3623 if (!host) {
3624 error_setg(errp, "chardev: socket: no host given");
3625 return;
3627 if (!port) {
3628 error_setg(errp, "chardev: socket: no port given");
3629 return;
3631 } else {
3632 if (tls_creds) {
3633 error_setg(errp, "TLS can only be used over TCP socket");
3634 return;
3638 backend->u.socket = g_new0(ChardevSocket, 1);
3639 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(backend->u.socket));
3641 backend->u.socket->has_nodelay = true;
3642 backend->u.socket->nodelay = do_nodelay;
3643 backend->u.socket->has_server = true;
3644 backend->u.socket->server = is_listen;
3645 backend->u.socket->has_telnet = true;
3646 backend->u.socket->telnet = is_telnet;
3647 backend->u.socket->has_wait = true;
3648 backend->u.socket->wait = is_waitconnect;
3649 backend->u.socket->has_reconnect = true;
3650 backend->u.socket->reconnect = reconnect;
3651 backend->u.socket->tls_creds = g_strdup(tls_creds);
3653 addr = g_new0(SocketAddress, 1);
3654 if (path) {
3655 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3656 addr->u.q_unix = g_new0(UnixSocketAddress, 1);
3657 addr->u.q_unix->path = g_strdup(path);
3658 } else {
3659 addr->type = SOCKET_ADDRESS_KIND_INET;
3660 addr->u.inet = g_new0(InetSocketAddress, 1);
3661 addr->u.inet->host = g_strdup(host);
3662 addr->u.inet->port = g_strdup(port);
3663 addr->u.inet->has_to = qemu_opt_get(opts, "to");
3664 addr->u.inet->to = qemu_opt_get_number(opts, "to", 0);
3665 addr->u.inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3666 addr->u.inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3667 addr->u.inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3668 addr->u.inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3670 backend->u.socket->addr = addr;
3673 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3674 Error **errp)
3676 const char *host = qemu_opt_get(opts, "host");
3677 const char *port = qemu_opt_get(opts, "port");
3678 const char *localaddr = qemu_opt_get(opts, "localaddr");
3679 const char *localport = qemu_opt_get(opts, "localport");
3680 bool has_local = false;
3681 SocketAddress *addr;
3683 if (host == NULL || strlen(host) == 0) {
3684 host = "localhost";
3686 if (port == NULL || strlen(port) == 0) {
3687 error_setg(errp, "chardev: udp: remote port not specified");
3688 return;
3690 if (localport == NULL || strlen(localport) == 0) {
3691 localport = "0";
3692 } else {
3693 has_local = true;
3695 if (localaddr == NULL || strlen(localaddr) == 0) {
3696 localaddr = "";
3697 } else {
3698 has_local = true;
3701 backend->u.udp = g_new0(ChardevUdp, 1);
3702 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(backend->u.udp));
3704 addr = g_new0(SocketAddress, 1);
3705 addr->type = SOCKET_ADDRESS_KIND_INET;
3706 addr->u.inet = g_new0(InetSocketAddress, 1);
3707 addr->u.inet->host = g_strdup(host);
3708 addr->u.inet->port = g_strdup(port);
3709 addr->u.inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3710 addr->u.inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3711 addr->u.inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3712 addr->u.inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3713 backend->u.udp->remote = addr;
3715 if (has_local) {
3716 backend->u.udp->has_local = true;
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(localaddr);
3721 addr->u.inet->port = g_strdup(localport);
3722 backend->u.udp->local = addr;
3726 typedef struct CharDriver {
3727 const char *name;
3728 ChardevBackendKind kind;
3729 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3730 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3731 ChardevReturn *ret, Error **errp);
3732 } CharDriver;
3734 static GSList *backends;
3736 void register_char_driver(const char *name, ChardevBackendKind kind,
3737 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3738 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3739 ChardevReturn *ret, Error **errp))
3741 CharDriver *s;
3743 s = g_malloc0(sizeof(*s));
3744 s->name = g_strdup(name);
3745 s->kind = kind;
3746 s->parse = parse;
3747 s->create = create;
3749 backends = g_slist_append(backends, s);
3752 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3753 void (*init)(struct CharDriverState *s),
3754 Error **errp)
3756 Error *local_err = NULL;
3757 CharDriver *cd;
3758 CharDriverState *chr;
3759 GSList *i;
3760 ChardevReturn *ret = NULL;
3761 ChardevBackend *backend;
3762 const char *id = qemu_opts_id(opts);
3763 char *bid = NULL;
3765 if (id == NULL) {
3766 error_setg(errp, "chardev: no id specified");
3767 goto err;
3770 if (qemu_opt_get(opts, "backend") == NULL) {
3771 error_setg(errp, "chardev: \"%s\" missing backend",
3772 qemu_opts_id(opts));
3773 goto err;
3775 for (i = backends; i; i = i->next) {
3776 cd = i->data;
3778 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3779 break;
3782 if (i == NULL) {
3783 error_setg(errp, "chardev: backend \"%s\" not found",
3784 qemu_opt_get(opts, "backend"));
3785 goto err;
3788 backend = g_new0(ChardevBackend, 1);
3790 if (qemu_opt_get_bool(opts, "mux", 0)) {
3791 bid = g_strdup_printf("%s-base", id);
3794 chr = NULL;
3795 backend->type = cd->kind;
3796 if (cd->parse) {
3797 cd->parse(opts, backend, &local_err);
3798 if (local_err) {
3799 error_propagate(errp, local_err);
3800 goto qapi_out;
3802 } else {
3803 ChardevCommon *cc = g_new0(ChardevCommon, 1);
3804 qemu_chr_parse_common(opts, cc);
3805 backend->u.data = cc;
3808 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3809 if (!ret) {
3810 goto qapi_out;
3813 if (bid) {
3814 qapi_free_ChardevBackend(backend);
3815 qapi_free_ChardevReturn(ret);
3816 backend = g_new0(ChardevBackend, 1);
3817 backend->u.mux = g_new0(ChardevMux, 1);
3818 backend->type = CHARDEV_BACKEND_KIND_MUX;
3819 backend->u.mux->chardev = g_strdup(bid);
3820 ret = qmp_chardev_add(id, backend, errp);
3821 if (!ret) {
3822 chr = qemu_chr_find(bid);
3823 qemu_chr_delete(chr);
3824 chr = NULL;
3825 goto qapi_out;
3829 chr = qemu_chr_find(id);
3830 chr->opts = opts;
3832 qapi_out:
3833 qapi_free_ChardevBackend(backend);
3834 qapi_free_ChardevReturn(ret);
3835 g_free(bid);
3836 return chr;
3838 err:
3839 qemu_opts_del(opts);
3840 return NULL;
3843 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3845 const char *p;
3846 CharDriverState *chr;
3847 QemuOpts *opts;
3848 Error *err = NULL;
3850 if (strstart(filename, "chardev:", &p)) {
3851 return qemu_chr_find(p);
3854 opts = qemu_chr_parse_compat(label, filename);
3855 if (!opts)
3856 return NULL;
3858 chr = qemu_chr_new_from_opts(opts, init, &err);
3859 if (err) {
3860 error_report_err(err);
3862 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3863 qemu_chr_fe_claim_no_fail(chr);
3864 monitor_init(chr, MONITOR_USE_READLINE);
3866 return chr;
3869 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3871 if (chr->chr_set_echo) {
3872 chr->chr_set_echo(chr, echo);
3876 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3878 if (chr->fe_open == fe_open) {
3879 return;
3881 chr->fe_open = fe_open;
3882 if (chr->chr_set_fe_open) {
3883 chr->chr_set_fe_open(chr, fe_open);
3887 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3889 if (chr->chr_fe_event) {
3890 chr->chr_fe_event(chr, event);
3894 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3895 GIOFunc func, void *user_data)
3897 GSource *src;
3898 guint tag;
3900 if (s->chr_add_watch == NULL) {
3901 return -ENOSYS;
3904 src = s->chr_add_watch(s, cond);
3905 if (!src) {
3906 return -EINVAL;
3909 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3910 tag = g_source_attach(src, NULL);
3911 g_source_unref(src);
3913 return tag;
3916 int qemu_chr_fe_claim(CharDriverState *s)
3918 if (s->avail_connections < 1) {
3919 return -1;
3921 s->avail_connections--;
3922 return 0;
3925 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3927 if (qemu_chr_fe_claim(s) != 0) {
3928 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3929 __func__, s->label);
3930 exit(1);
3934 void qemu_chr_fe_release(CharDriverState *s)
3936 s->avail_connections++;
3939 static void qemu_chr_free_common(CharDriverState *chr)
3941 g_free(chr->filename);
3942 g_free(chr->label);
3943 qemu_opts_del(chr->opts);
3944 if (chr->logfd != -1) {
3945 close(chr->logfd);
3947 qemu_mutex_destroy(&chr->chr_write_lock);
3948 g_free(chr);
3951 void qemu_chr_free(CharDriverState *chr)
3953 if (chr->chr_close) {
3954 chr->chr_close(chr);
3956 qemu_chr_free_common(chr);
3959 void qemu_chr_delete(CharDriverState *chr)
3961 QTAILQ_REMOVE(&chardevs, chr, next);
3962 qemu_chr_free(chr);
3965 ChardevInfoList *qmp_query_chardev(Error **errp)
3967 ChardevInfoList *chr_list = NULL;
3968 CharDriverState *chr;
3970 QTAILQ_FOREACH(chr, &chardevs, next) {
3971 ChardevInfoList *info = g_malloc0(sizeof(*info));
3972 info->value = g_malloc0(sizeof(*info->value));
3973 info->value->label = g_strdup(chr->label);
3974 info->value->filename = g_strdup(chr->filename);
3975 info->value->frontend_open = chr->fe_open;
3977 info->next = chr_list;
3978 chr_list = info;
3981 return chr_list;
3984 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
3986 ChardevBackendInfoList *backend_list = NULL;
3987 CharDriver *c = NULL;
3988 GSList *i = NULL;
3990 for (i = backends; i; i = i->next) {
3991 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
3992 c = i->data;
3993 info->value = g_malloc0(sizeof(*info->value));
3994 info->value->name = g_strdup(c->name);
3996 info->next = backend_list;
3997 backend_list = info;
4000 return backend_list;
4003 CharDriverState *qemu_chr_find(const char *name)
4005 CharDriverState *chr;
4007 QTAILQ_FOREACH(chr, &chardevs, next) {
4008 if (strcmp(chr->label, name) != 0)
4009 continue;
4010 return chr;
4012 return NULL;
4015 /* Get a character (serial) device interface. */
4016 CharDriverState *qemu_char_get_next_serial(void)
4018 static int next_serial;
4019 CharDriverState *chr;
4021 /* FIXME: This function needs to go away: use chardev properties! */
4023 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
4024 chr = serial_hds[next_serial++];
4025 qemu_chr_fe_claim_no_fail(chr);
4026 return chr;
4028 return NULL;
4031 QemuOptsList qemu_chardev_opts = {
4032 .name = "chardev",
4033 .implied_opt_name = "backend",
4034 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4035 .desc = {
4037 .name = "backend",
4038 .type = QEMU_OPT_STRING,
4040 .name = "path",
4041 .type = QEMU_OPT_STRING,
4043 .name = "host",
4044 .type = QEMU_OPT_STRING,
4046 .name = "port",
4047 .type = QEMU_OPT_STRING,
4049 .name = "localaddr",
4050 .type = QEMU_OPT_STRING,
4052 .name = "localport",
4053 .type = QEMU_OPT_STRING,
4055 .name = "to",
4056 .type = QEMU_OPT_NUMBER,
4058 .name = "ipv4",
4059 .type = QEMU_OPT_BOOL,
4061 .name = "ipv6",
4062 .type = QEMU_OPT_BOOL,
4064 .name = "wait",
4065 .type = QEMU_OPT_BOOL,
4067 .name = "server",
4068 .type = QEMU_OPT_BOOL,
4070 .name = "delay",
4071 .type = QEMU_OPT_BOOL,
4073 .name = "reconnect",
4074 .type = QEMU_OPT_NUMBER,
4076 .name = "telnet",
4077 .type = QEMU_OPT_BOOL,
4079 .name = "tls-creds",
4080 .type = QEMU_OPT_STRING,
4082 .name = "width",
4083 .type = QEMU_OPT_NUMBER,
4085 .name = "height",
4086 .type = QEMU_OPT_NUMBER,
4088 .name = "cols",
4089 .type = QEMU_OPT_NUMBER,
4091 .name = "rows",
4092 .type = QEMU_OPT_NUMBER,
4094 .name = "mux",
4095 .type = QEMU_OPT_BOOL,
4097 .name = "signal",
4098 .type = QEMU_OPT_BOOL,
4100 .name = "name",
4101 .type = QEMU_OPT_STRING,
4103 .name = "debug",
4104 .type = QEMU_OPT_NUMBER,
4106 .name = "size",
4107 .type = QEMU_OPT_SIZE,
4109 .name = "chardev",
4110 .type = QEMU_OPT_STRING,
4112 .name = "append",
4113 .type = QEMU_OPT_BOOL,
4115 .name = "logfile",
4116 .type = QEMU_OPT_STRING,
4118 .name = "logappend",
4119 .type = QEMU_OPT_BOOL,
4121 { /* end of list */ }
4125 #ifdef _WIN32
4127 static CharDriverState *qmp_chardev_open_file(const char *id,
4128 ChardevBackend *backend,
4129 ChardevReturn *ret,
4130 Error **errp)
4132 ChardevFile *file = backend->u.file;
4133 ChardevCommon *common = qapi_ChardevFile_base(backend->u.file);
4134 HANDLE out;
4136 if (file->has_in) {
4137 error_setg(errp, "input file not supported");
4138 return NULL;
4141 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
4142 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
4143 if (out == INVALID_HANDLE_VALUE) {
4144 error_setg(errp, "open %s failed", file->out);
4145 return NULL;
4147 return qemu_chr_open_win_file(out, common, errp);
4150 static CharDriverState *qmp_chardev_open_serial(const char *id,
4151 ChardevBackend *backend,
4152 ChardevReturn *ret,
4153 Error **errp)
4155 ChardevHostdev *serial = backend->u.serial;
4156 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.serial);
4157 return qemu_chr_open_win_path(serial->device, common, errp);
4160 #else /* WIN32 */
4162 static int qmp_chardev_open_file_source(char *src, int flags,
4163 Error **errp)
4165 int fd = -1;
4167 TFR(fd = qemu_open(src, flags, 0666));
4168 if (fd == -1) {
4169 error_setg_file_open(errp, errno, src);
4171 return fd;
4174 static CharDriverState *qmp_chardev_open_file(const char *id,
4175 ChardevBackend *backend,
4176 ChardevReturn *ret,
4177 Error **errp)
4179 ChardevFile *file = backend->u.file;
4180 ChardevCommon *common = qapi_ChardevFile_base(backend->u.file);
4181 int flags, in = -1, out;
4183 flags = O_WRONLY | O_CREAT | O_BINARY;
4184 if (file->has_append && file->append) {
4185 flags |= O_APPEND;
4186 } else {
4187 flags |= O_TRUNC;
4190 out = qmp_chardev_open_file_source(file->out, flags, errp);
4191 if (out < 0) {
4192 return NULL;
4195 if (file->has_in) {
4196 flags = O_RDONLY;
4197 in = qmp_chardev_open_file_source(file->in, flags, errp);
4198 if (in < 0) {
4199 qemu_close(out);
4200 return NULL;
4204 return qemu_chr_open_fd(in, out, common, errp);
4207 #ifdef HAVE_CHARDEV_SERIAL
4208 static CharDriverState *qmp_chardev_open_serial(const char *id,
4209 ChardevBackend *backend,
4210 ChardevReturn *ret,
4211 Error **errp)
4213 ChardevHostdev *serial = backend->u.serial;
4214 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.serial);
4215 int fd;
4217 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4218 if (fd < 0) {
4219 return NULL;
4221 qemu_set_nonblock(fd);
4222 return qemu_chr_open_tty_fd(fd, common, errp);
4224 #endif
4226 #ifdef HAVE_CHARDEV_PARPORT
4227 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4228 ChardevBackend *backend,
4229 ChardevReturn *ret,
4230 Error **errp)
4232 ChardevHostdev *parallel = backend->u.parallel;
4233 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.parallel);
4234 int fd;
4236 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4237 if (fd < 0) {
4238 return NULL;
4240 return qemu_chr_open_pp_fd(fd, common, errp);
4242 #endif
4244 #endif /* WIN32 */
4246 static void socket_try_connect(CharDriverState *chr)
4248 Error *err = NULL;
4250 if (!qemu_chr_open_socket_fd(chr, &err)) {
4251 check_report_connect_error(chr, err);
4255 static gboolean socket_reconnect_timeout(gpointer opaque)
4257 CharDriverState *chr = opaque;
4258 TCPCharDriver *s = chr->opaque;
4260 s->reconnect_timer = 0;
4262 if (chr->be_open) {
4263 return false;
4266 socket_try_connect(chr);
4268 return false;
4271 static CharDriverState *qmp_chardev_open_socket(const char *id,
4272 ChardevBackend *backend,
4273 ChardevReturn *ret,
4274 Error **errp)
4276 CharDriverState *chr;
4277 TCPCharDriver *s;
4278 ChardevSocket *sock = backend->u.socket;
4279 SocketAddress *addr = sock->addr;
4280 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4281 bool is_listen = sock->has_server ? sock->server : true;
4282 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4283 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4284 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4285 ChardevCommon *common = qapi_ChardevSocket_base(backend->u.socket);
4287 chr = qemu_chr_alloc(common, errp);
4288 if (!chr) {
4289 return NULL;
4291 s = g_new0(TCPCharDriver, 1);
4293 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4294 s->is_listen = is_listen;
4295 s->is_telnet = is_telnet;
4296 s->do_nodelay = do_nodelay;
4297 if (sock->tls_creds) {
4298 Object *creds;
4299 creds = object_resolve_path_component(
4300 object_get_objects_root(), sock->tls_creds);
4301 if (!creds) {
4302 error_setg(errp, "No TLS credentials with id '%s'",
4303 sock->tls_creds);
4304 goto error;
4306 s->tls_creds = (QCryptoTLSCreds *)
4307 object_dynamic_cast(creds,
4308 TYPE_QCRYPTO_TLS_CREDS);
4309 if (!s->tls_creds) {
4310 error_setg(errp, "Object with id '%s' is not TLS credentials",
4311 sock->tls_creds);
4312 goto error;
4314 object_ref(OBJECT(s->tls_creds));
4315 if (is_listen) {
4316 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4317 error_setg(errp, "%s",
4318 "Expected TLS credentials for server endpoint");
4319 goto error;
4321 } else {
4322 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4323 error_setg(errp, "%s",
4324 "Expected TLS credentials for client endpoint");
4325 goto error;
4330 qapi_copy_SocketAddress(&s->addr, sock->addr);
4332 chr->opaque = s;
4333 chr->chr_write = tcp_chr_write;
4334 chr->chr_sync_read = tcp_chr_sync_read;
4335 chr->chr_close = tcp_chr_close;
4336 chr->get_msgfds = tcp_get_msgfds;
4337 chr->set_msgfds = tcp_set_msgfds;
4338 chr->chr_add_client = tcp_chr_add_client;
4339 chr->chr_add_watch = tcp_chr_add_watch;
4340 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4341 /* be isn't opened until we get a connection */
4342 chr->explicit_be_open = true;
4344 chr->filename = SocketAddress_to_str("disconnected:",
4345 addr, is_listen, is_telnet);
4347 if (is_listen) {
4348 if (is_telnet) {
4349 s->do_telnetopt = 1;
4351 } else if (reconnect > 0) {
4352 s->reconnect_time = reconnect;
4355 if (s->reconnect_time) {
4356 socket_try_connect(chr);
4357 } else if (!qemu_chr_open_socket_fd(chr, errp)) {
4358 goto error;
4361 if (is_listen && is_waitconnect) {
4362 fprintf(stderr, "QEMU waiting for connection on: %s\n",
4363 chr->filename);
4364 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
4365 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
4368 return chr;
4370 error:
4371 if (s->tls_creds) {
4372 object_unref(OBJECT(s->tls_creds));
4374 g_free(s);
4375 qemu_chr_free_common(chr);
4376 return NULL;
4379 static CharDriverState *qmp_chardev_open_udp(const char *id,
4380 ChardevBackend *backend,
4381 ChardevReturn *ret,
4382 Error **errp)
4384 ChardevUdp *udp = backend->u.udp;
4385 ChardevCommon *common = qapi_ChardevUdp_base(backend->u.udp);
4386 QIOChannelSocket *sioc = qio_channel_socket_new();
4388 if (qio_channel_socket_dgram_sync(sioc,
4389 udp->local, udp->remote,
4390 errp) < 0) {
4391 object_unref(OBJECT(sioc));
4392 return NULL;
4394 return qemu_chr_open_udp(sioc, common, errp);
4397 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4398 Error **errp)
4400 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4401 CharDriverState *chr = NULL;
4402 Error *local_err = NULL;
4403 GSList *i;
4404 CharDriver *cd;
4406 chr = qemu_chr_find(id);
4407 if (chr) {
4408 error_setg(errp, "Chardev '%s' already exists", id);
4409 g_free(ret);
4410 return NULL;
4413 for (i = backends; i; i = i->next) {
4414 cd = i->data;
4416 if (cd->kind == backend->type) {
4417 chr = cd->create(id, backend, ret, &local_err);
4418 if (local_err) {
4419 error_propagate(errp, local_err);
4420 goto out_error;
4422 break;
4426 if (chr == NULL) {
4427 assert(!i);
4428 error_setg(errp, "chardev backend not available");
4429 goto out_error;
4432 chr->label = g_strdup(id);
4433 chr->avail_connections =
4434 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4435 if (!chr->filename) {
4436 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4438 if (!chr->explicit_be_open) {
4439 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4441 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4442 return ret;
4444 out_error:
4445 g_free(ret);
4446 return NULL;
4449 void qmp_chardev_remove(const char *id, Error **errp)
4451 CharDriverState *chr;
4453 chr = qemu_chr_find(id);
4454 if (chr == NULL) {
4455 error_setg(errp, "Chardev '%s' not found", id);
4456 return;
4458 if (chr->chr_can_read || chr->chr_read ||
4459 chr->chr_event || chr->handler_opaque) {
4460 error_setg(errp, "Chardev '%s' is busy", id);
4461 return;
4463 qemu_chr_delete(chr);
4466 static void register_types(void)
4468 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4469 qemu_chr_open_null);
4470 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4471 qemu_chr_parse_socket, qmp_chardev_open_socket);
4472 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4473 qmp_chardev_open_udp);
4474 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4475 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4476 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4477 qemu_chr_parse_file_out, qmp_chardev_open_file);
4478 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4479 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4480 #if defined HAVE_CHARDEV_SERIAL
4481 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4482 qemu_chr_parse_serial, qmp_chardev_open_serial);
4483 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4484 qemu_chr_parse_serial, qmp_chardev_open_serial);
4485 #endif
4486 #ifdef HAVE_CHARDEV_PARPORT
4487 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4488 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4489 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4490 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4491 #endif
4492 #ifdef HAVE_CHARDEV_PTY
4493 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4494 qemu_chr_open_pty);
4495 #endif
4496 #ifdef _WIN32
4497 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4498 qemu_chr_open_win_con);
4499 #endif
4500 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4501 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4502 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4503 qemu_chr_open_mux);
4504 /* Bug-compatibility: */
4505 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4506 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4507 /* this must be done after machine init, since we register FEs with muxes
4508 * as part of realize functions like serial_isa_realizefn when -nographic
4509 * is specified
4511 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4514 type_init(register_types);