sockets: remove use of QemuOpts from socket_dgram
[qemu.git] / qemu-char.c
blobe133f4fc35d7ebe5ecb8848e1f2f6046646c4088
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu-common.h"
25 #include "monitor/monitor.h"
26 #include "sysemu/sysemu.h"
27 #include "qemu/error-report.h"
28 #include "qemu/timer.h"
29 #include "sysemu/char.h"
30 #include "hw/usb.h"
31 #include "qmp-commands.h"
32 #include "qapi/qmp-input-visitor.h"
33 #include "qapi/qmp-output-visitor.h"
34 #include "qapi-visit.h"
35 #include "qemu/base64.h"
37 #include <unistd.h>
38 #include <fcntl.h>
39 #include <time.h>
40 #include <errno.h>
41 #include <sys/time.h>
42 #include <zlib.h>
44 #ifndef _WIN32
45 #include <sys/times.h>
46 #include <sys/wait.h>
47 #include <termios.h>
48 #include <sys/mman.h>
49 #include <sys/ioctl.h>
50 #include <sys/resource.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <net/if.h>
54 #include <arpa/inet.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef CONFIG_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
60 #include <dev/ppbus/ppi.h>
61 #include <dev/ppbus/ppbconf.h>
62 #elif defined(__DragonFly__)
63 #include <dev/misc/ppi/ppi.h>
64 #include <bus/ppbus/ppbconf.h>
65 #endif
66 #else
67 #ifdef __linux__
68 #include <linux/ppdev.h>
69 #include <linux/parport.h>
70 #endif
71 #ifdef __sun__
72 #include <sys/stat.h>
73 #include <sys/ethernet.h>
74 #include <sys/sockio.h>
75 #include <netinet/arp.h>
76 #include <netinet/in.h>
77 #include <netinet/in_systm.h>
78 #include <netinet/ip.h>
79 #include <netinet/ip_icmp.h> // must come after ip.h
80 #include <netinet/udp.h>
81 #include <netinet/tcp.h>
82 #endif
83 #endif
84 #endif
86 #include "qemu/sockets.h"
87 #include "ui/qemu-spice.h"
89 #define READ_BUF_LEN 4096
90 #define READ_RETRIES 10
91 #define CHR_MAX_FILENAME_SIZE 256
92 #define TCP_MAX_FDS 16
94 /***********************************************************/
95 /* Socket address helpers */
97 static int SocketAddress_to_str(char *dest, int max_len,
98 const char *prefix, SocketAddress *addr,
99 bool is_listen, bool is_telnet)
101 switch (addr->type) {
102 case SOCKET_ADDRESS_KIND_INET:
103 return snprintf(dest, max_len, "%s%s:%s:%s%s", prefix,
104 is_telnet ? "telnet" : "tcp", addr->u.inet->host,
105 addr->u.inet->port, is_listen ? ",server" : "");
106 break;
107 case SOCKET_ADDRESS_KIND_UNIX:
108 return snprintf(dest, max_len, "%sunix:%s%s", prefix,
109 addr->u.q_unix->path, is_listen ? ",server" : "");
110 break;
111 case SOCKET_ADDRESS_KIND_FD:
112 return snprintf(dest, max_len, "%sfd:%s%s", prefix, addr->u.fd->str,
113 is_listen ? ",server" : "");
114 break;
115 default:
116 abort();
120 static int sockaddr_to_str(char *dest, int max_len,
121 struct sockaddr_storage *ss, socklen_t ss_len,
122 struct sockaddr_storage *ps, socklen_t ps_len,
123 bool is_listen, bool is_telnet)
125 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
126 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
127 const char *left = "", *right = "";
129 switch (ss->ss_family) {
130 #ifndef _WIN32
131 case AF_UNIX:
132 return snprintf(dest, max_len, "unix:%s%s",
133 ((struct sockaddr_un *)(ss))->sun_path,
134 is_listen ? ",server" : "");
135 #endif
136 case AF_INET6:
137 left = "[";
138 right = "]";
139 /* fall through */
140 case AF_INET:
141 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
142 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
143 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
144 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
145 return snprintf(dest, max_len, "%s:%s%s%s:%s%s <-> %s%s%s:%s",
146 is_telnet ? "telnet" : "tcp",
147 left, shost, right, sserv,
148 is_listen ? ",server" : "",
149 left, phost, right, pserv);
151 default:
152 return snprintf(dest, max_len, "unknown");
156 /***********************************************************/
157 /* character device */
159 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
160 QTAILQ_HEAD_INITIALIZER(chardevs);
162 static void qemu_chr_free_common(CharDriverState *chr);
164 CharDriverState *qemu_chr_alloc(ChardevCommon *backend, Error **errp)
166 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
167 qemu_mutex_init(&chr->chr_write_lock);
169 if (backend->has_logfile) {
170 int flags = O_WRONLY | O_CREAT;
171 if (backend->has_logappend &&
172 backend->logappend) {
173 flags |= O_APPEND;
174 } else {
175 flags |= O_TRUNC;
177 chr->logfd = qemu_open(backend->logfile, flags, 0666);
178 if (chr->logfd < 0) {
179 error_setg_errno(errp, errno,
180 "Unable to open logfile %s",
181 backend->logfile);
182 g_free(chr);
183 return NULL;
185 } else {
186 chr->logfd = -1;
189 return chr;
192 void qemu_chr_be_event(CharDriverState *s, int event)
194 /* Keep track if the char device is open */
195 switch (event) {
196 case CHR_EVENT_OPENED:
197 s->be_open = 1;
198 break;
199 case CHR_EVENT_CLOSED:
200 s->be_open = 0;
201 break;
204 if (!s->chr_event)
205 return;
206 s->chr_event(s->handler_opaque, event);
209 void qemu_chr_be_generic_open(CharDriverState *s)
211 qemu_chr_be_event(s, CHR_EVENT_OPENED);
215 /* Not reporting errors from writing to logfile, as logs are
216 * defined to be "best effort" only */
217 static void qemu_chr_fe_write_log(CharDriverState *s,
218 const uint8_t *buf, size_t len)
220 size_t done = 0;
221 ssize_t ret;
223 if (s->logfd < 0) {
224 return;
227 while (done < len) {
228 do {
229 ret = write(s->logfd, buf + done, len - done);
230 if (ret == -1 && errno == EAGAIN) {
231 g_usleep(100);
233 } while (ret == -1 && errno == EAGAIN);
235 if (ret <= 0) {
236 return;
238 done += ret;
242 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
244 int ret;
246 qemu_mutex_lock(&s->chr_write_lock);
247 ret = s->chr_write(s, buf, len);
249 if (ret > 0) {
250 qemu_chr_fe_write_log(s, buf, ret);
253 qemu_mutex_unlock(&s->chr_write_lock);
254 return ret;
257 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
259 int offset = 0;
260 int res = 0;
262 qemu_mutex_lock(&s->chr_write_lock);
263 while (offset < len) {
264 do {
265 res = s->chr_write(s, buf + offset, len - offset);
266 if (res == -1 && errno == EAGAIN) {
267 g_usleep(100);
269 } while (res == -1 && errno == EAGAIN);
271 if (res <= 0) {
272 break;
275 offset += res;
277 if (offset > 0) {
278 qemu_chr_fe_write_log(s, buf, offset);
281 qemu_mutex_unlock(&s->chr_write_lock);
283 if (res < 0) {
284 return res;
286 return offset;
289 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
291 int offset = 0, counter = 10;
292 int res;
294 if (!s->chr_sync_read) {
295 return 0;
298 while (offset < len) {
299 do {
300 res = s->chr_sync_read(s, buf + offset, len - offset);
301 if (res == -1 && errno == EAGAIN) {
302 g_usleep(100);
304 } while (res == -1 && errno == EAGAIN);
306 if (res == 0) {
307 break;
310 if (res < 0) {
311 return res;
314 offset += res;
316 if (!counter--) {
317 break;
321 return offset;
324 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
326 if (!s->chr_ioctl)
327 return -ENOTSUP;
328 return s->chr_ioctl(s, cmd, arg);
331 int qemu_chr_be_can_write(CharDriverState *s)
333 if (!s->chr_can_read)
334 return 0;
335 return s->chr_can_read(s->handler_opaque);
338 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
340 if (s->chr_read) {
341 s->chr_read(s->handler_opaque, buf, len);
345 int qemu_chr_fe_get_msgfd(CharDriverState *s)
347 int fd;
348 return (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
351 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
353 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
356 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
358 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
361 int qemu_chr_add_client(CharDriverState *s, int fd)
363 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
366 void qemu_chr_accept_input(CharDriverState *s)
368 if (s->chr_accept_input)
369 s->chr_accept_input(s);
370 qemu_notify_event();
373 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
375 char buf[READ_BUF_LEN];
376 va_list ap;
377 va_start(ap, fmt);
378 vsnprintf(buf, sizeof(buf), fmt, ap);
379 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
380 va_end(ap);
383 static void remove_fd_in_watch(CharDriverState *chr);
385 void qemu_chr_add_handlers(CharDriverState *s,
386 IOCanReadHandler *fd_can_read,
387 IOReadHandler *fd_read,
388 IOEventHandler *fd_event,
389 void *opaque)
391 int fe_open;
393 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
394 fe_open = 0;
395 remove_fd_in_watch(s);
396 } else {
397 fe_open = 1;
399 s->chr_can_read = fd_can_read;
400 s->chr_read = fd_read;
401 s->chr_event = fd_event;
402 s->handler_opaque = opaque;
403 if (fe_open && s->chr_update_read_handler)
404 s->chr_update_read_handler(s);
406 if (!s->explicit_fe_open) {
407 qemu_chr_fe_set_open(s, fe_open);
410 /* We're connecting to an already opened device, so let's make sure we
411 also get the open event */
412 if (fe_open && s->be_open) {
413 qemu_chr_be_generic_open(s);
417 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
419 return len;
422 static CharDriverState *qemu_chr_open_null(const char *id,
423 ChardevBackend *backend,
424 ChardevReturn *ret,
425 Error **errp)
427 CharDriverState *chr;
428 ChardevCommon *common = qapi_ChardevDummy_base(backend->u.null);
430 chr = qemu_chr_alloc(common, errp);
431 if (!chr) {
432 return NULL;
434 chr->chr_write = null_chr_write;
435 chr->explicit_be_open = true;
436 return chr;
439 /* MUX driver for serial I/O splitting */
440 #define MAX_MUX 4
441 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
442 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
443 typedef struct {
444 IOCanReadHandler *chr_can_read[MAX_MUX];
445 IOReadHandler *chr_read[MAX_MUX];
446 IOEventHandler *chr_event[MAX_MUX];
447 void *ext_opaque[MAX_MUX];
448 CharDriverState *drv;
449 int focus;
450 int mux_cnt;
451 int term_got_escape;
452 int max_size;
453 /* Intermediate input buffer allows to catch escape sequences even if the
454 currently active device is not accepting any input - but only until it
455 is full as well. */
456 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
457 int prod[MAX_MUX];
458 int cons[MAX_MUX];
459 int timestamps;
461 /* Protected by the CharDriverState chr_write_lock. */
462 int linestart;
463 int64_t timestamps_start;
464 } MuxDriver;
467 /* Called with chr_write_lock held. */
468 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
470 MuxDriver *d = chr->opaque;
471 int ret;
472 if (!d->timestamps) {
473 ret = qemu_chr_fe_write(d->drv, buf, len);
474 } else {
475 int i;
477 ret = 0;
478 for (i = 0; i < len; i++) {
479 if (d->linestart) {
480 char buf1[64];
481 int64_t ti;
482 int secs;
484 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
485 if (d->timestamps_start == -1)
486 d->timestamps_start = ti;
487 ti -= d->timestamps_start;
488 secs = ti / 1000;
489 snprintf(buf1, sizeof(buf1),
490 "[%02d:%02d:%02d.%03d] ",
491 secs / 3600,
492 (secs / 60) % 60,
493 secs % 60,
494 (int)(ti % 1000));
495 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
496 d->linestart = 0;
498 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
499 if (buf[i] == '\n') {
500 d->linestart = 1;
504 return ret;
507 static const char * const mux_help[] = {
508 "% h print this help\n\r",
509 "% x exit emulator\n\r",
510 "% s save disk data back to file (if -snapshot)\n\r",
511 "% t toggle console timestamps\n\r",
512 "% b send break (magic sysrq)\n\r",
513 "% c switch between console and monitor\n\r",
514 "% % sends %\n\r",
515 NULL
518 int term_escape_char = 0x01; /* ctrl-a is used for escape */
519 static void mux_print_help(CharDriverState *chr)
521 int i, j;
522 char ebuf[15] = "Escape-Char";
523 char cbuf[50] = "\n\r";
525 if (term_escape_char > 0 && term_escape_char < 26) {
526 snprintf(cbuf, sizeof(cbuf), "\n\r");
527 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
528 } else {
529 snprintf(cbuf, sizeof(cbuf),
530 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
531 term_escape_char);
533 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
534 for (i = 0; mux_help[i] != NULL; i++) {
535 for (j=0; mux_help[i][j] != '\0'; j++) {
536 if (mux_help[i][j] == '%')
537 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
538 else
539 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
544 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
546 if (d->chr_event[mux_nr])
547 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
550 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
552 if (d->term_got_escape) {
553 d->term_got_escape = 0;
554 if (ch == term_escape_char)
555 goto send_char;
556 switch(ch) {
557 case '?':
558 case 'h':
559 mux_print_help(chr);
560 break;
561 case 'x':
563 const char *term = "QEMU: Terminated\n\r";
564 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
565 exit(0);
566 break;
568 case 's':
569 bdrv_commit_all();
570 break;
571 case 'b':
572 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
573 break;
574 case 'c':
575 /* Switch to the next registered device */
576 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
577 d->focus++;
578 if (d->focus >= d->mux_cnt)
579 d->focus = 0;
580 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
581 break;
582 case 't':
583 d->timestamps = !d->timestamps;
584 d->timestamps_start = -1;
585 d->linestart = 0;
586 break;
588 } else if (ch == term_escape_char) {
589 d->term_got_escape = 1;
590 } else {
591 send_char:
592 return 1;
594 return 0;
597 static void mux_chr_accept_input(CharDriverState *chr)
599 MuxDriver *d = chr->opaque;
600 int m = d->focus;
602 while (d->prod[m] != d->cons[m] &&
603 d->chr_can_read[m] &&
604 d->chr_can_read[m](d->ext_opaque[m])) {
605 d->chr_read[m](d->ext_opaque[m],
606 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
610 static int mux_chr_can_read(void *opaque)
612 CharDriverState *chr = opaque;
613 MuxDriver *d = chr->opaque;
614 int m = d->focus;
616 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
617 return 1;
618 if (d->chr_can_read[m])
619 return d->chr_can_read[m](d->ext_opaque[m]);
620 return 0;
623 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
625 CharDriverState *chr = opaque;
626 MuxDriver *d = chr->opaque;
627 int m = d->focus;
628 int i;
630 mux_chr_accept_input (opaque);
632 for(i = 0; i < size; i++)
633 if (mux_proc_byte(chr, d, buf[i])) {
634 if (d->prod[m] == d->cons[m] &&
635 d->chr_can_read[m] &&
636 d->chr_can_read[m](d->ext_opaque[m]))
637 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
638 else
639 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
643 static void mux_chr_event(void *opaque, int event)
645 CharDriverState *chr = opaque;
646 MuxDriver *d = chr->opaque;
647 int i;
649 /* Send the event to all registered listeners */
650 for (i = 0; i < d->mux_cnt; i++)
651 mux_chr_send_event(d, i, event);
654 static void mux_chr_update_read_handler(CharDriverState *chr)
656 MuxDriver *d = chr->opaque;
658 if (d->mux_cnt >= MAX_MUX) {
659 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
660 return;
662 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
663 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
664 d->chr_read[d->mux_cnt] = chr->chr_read;
665 d->chr_event[d->mux_cnt] = chr->chr_event;
666 /* Fix up the real driver with mux routines */
667 if (d->mux_cnt == 0) {
668 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
669 mux_chr_event, chr);
671 if (d->focus != -1) {
672 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
674 d->focus = d->mux_cnt;
675 d->mux_cnt++;
676 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
679 static bool muxes_realized;
682 * Called after processing of default and command-line-specified
683 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
684 * to a mux chardev. This is done here to ensure that
685 * output/prompts/banners are only displayed for the FE that has
686 * focus when initial command-line processing/machine init is
687 * completed.
689 * After this point, any new FE attached to any new or existing
690 * mux will receive CHR_EVENT_OPENED notifications for the BE
691 * immediately.
693 static void muxes_realize_done(Notifier *notifier, void *unused)
695 CharDriverState *chr;
697 QTAILQ_FOREACH(chr, &chardevs, next) {
698 if (chr->is_mux) {
699 MuxDriver *d = chr->opaque;
700 int i;
702 /* send OPENED to all already-attached FEs */
703 for (i = 0; i < d->mux_cnt; i++) {
704 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
706 /* mark mux as OPENED so any new FEs will immediately receive
707 * OPENED event
709 qemu_chr_be_generic_open(chr);
712 muxes_realized = true;
715 static Notifier muxes_realize_notify = {
716 .notify = muxes_realize_done,
719 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
721 MuxDriver *d = s->opaque;
722 return d->drv->chr_add_watch(d->drv, cond);
725 static CharDriverState *qemu_chr_open_mux(const char *id,
726 ChardevBackend *backend,
727 ChardevReturn *ret, Error **errp)
729 ChardevMux *mux = backend->u.mux;
730 CharDriverState *chr, *drv;
731 MuxDriver *d;
732 ChardevCommon *common = qapi_ChardevMux_base(backend->u.mux);
734 drv = qemu_chr_find(mux->chardev);
735 if (drv == NULL) {
736 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
737 return NULL;
740 chr = qemu_chr_alloc(common, errp);
741 if (!chr) {
742 return NULL;
744 d = g_new0(MuxDriver, 1);
746 chr->opaque = d;
747 d->drv = drv;
748 d->focus = -1;
749 chr->chr_write = mux_chr_write;
750 chr->chr_update_read_handler = mux_chr_update_read_handler;
751 chr->chr_accept_input = mux_chr_accept_input;
752 /* Frontend guest-open / -close notification is not support with muxes */
753 chr->chr_set_fe_open = NULL;
754 if (drv->chr_add_watch) {
755 chr->chr_add_watch = mux_chr_add_watch;
757 /* only default to opened state if we've realized the initial
758 * set of muxes
760 chr->explicit_be_open = muxes_realized ? 0 : 1;
761 chr->is_mux = 1;
763 return chr;
767 typedef struct IOWatchPoll
769 GSource parent;
771 GIOChannel *channel;
772 GSource *src;
774 IOCanReadHandler *fd_can_read;
775 GSourceFunc fd_read;
776 void *opaque;
777 } IOWatchPoll;
779 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
781 return container_of(source, IOWatchPoll, parent);
784 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
786 IOWatchPoll *iwp = io_watch_poll_from_source(source);
787 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
788 bool was_active = iwp->src != NULL;
789 if (was_active == now_active) {
790 return FALSE;
793 if (now_active) {
794 iwp->src = g_io_create_watch(iwp->channel,
795 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
796 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
797 g_source_attach(iwp->src, NULL);
798 } else {
799 g_source_destroy(iwp->src);
800 g_source_unref(iwp->src);
801 iwp->src = NULL;
803 return FALSE;
806 static gboolean io_watch_poll_check(GSource *source)
808 return FALSE;
811 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
812 gpointer user_data)
814 abort();
817 static void io_watch_poll_finalize(GSource *source)
819 /* Due to a glib bug, removing the last reference to a source
820 * inside a finalize callback causes recursive locking (and a
821 * deadlock). This is not a problem inside other callbacks,
822 * including dispatch callbacks, so we call io_remove_watch_poll
823 * to remove this source. At this point, iwp->src must
824 * be NULL, or we would leak it.
826 * This would be solved much more elegantly by child sources,
827 * but we support older glib versions that do not have them.
829 IOWatchPoll *iwp = io_watch_poll_from_source(source);
830 assert(iwp->src == NULL);
833 static GSourceFuncs io_watch_poll_funcs = {
834 .prepare = io_watch_poll_prepare,
835 .check = io_watch_poll_check,
836 .dispatch = io_watch_poll_dispatch,
837 .finalize = io_watch_poll_finalize,
840 /* Can only be used for read */
841 static guint io_add_watch_poll(GIOChannel *channel,
842 IOCanReadHandler *fd_can_read,
843 GIOFunc fd_read,
844 gpointer user_data)
846 IOWatchPoll *iwp;
847 int tag;
849 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
850 iwp->fd_can_read = fd_can_read;
851 iwp->opaque = user_data;
852 iwp->channel = channel;
853 iwp->fd_read = (GSourceFunc) fd_read;
854 iwp->src = NULL;
856 tag = g_source_attach(&iwp->parent, NULL);
857 g_source_unref(&iwp->parent);
858 return tag;
861 static void io_remove_watch_poll(guint tag)
863 GSource *source;
864 IOWatchPoll *iwp;
866 g_return_if_fail (tag > 0);
868 source = g_main_context_find_source_by_id(NULL, tag);
869 g_return_if_fail (source != NULL);
871 iwp = io_watch_poll_from_source(source);
872 if (iwp->src) {
873 g_source_destroy(iwp->src);
874 g_source_unref(iwp->src);
875 iwp->src = NULL;
877 g_source_destroy(&iwp->parent);
880 static void remove_fd_in_watch(CharDriverState *chr)
882 if (chr->fd_in_tag) {
883 io_remove_watch_poll(chr->fd_in_tag);
884 chr->fd_in_tag = 0;
888 #ifndef _WIN32
889 static GIOChannel *io_channel_from_fd(int fd)
891 GIOChannel *chan;
893 if (fd == -1) {
894 return NULL;
897 chan = g_io_channel_unix_new(fd);
899 g_io_channel_set_encoding(chan, NULL, NULL);
900 g_io_channel_set_buffered(chan, FALSE);
902 return chan;
904 #endif
906 static GIOChannel *io_channel_from_socket(int fd)
908 GIOChannel *chan;
910 if (fd == -1) {
911 return NULL;
914 #ifdef _WIN32
915 chan = g_io_channel_win32_new_socket(fd);
916 #else
917 chan = g_io_channel_unix_new(fd);
918 #endif
920 g_io_channel_set_encoding(chan, NULL, NULL);
921 g_io_channel_set_buffered(chan, FALSE);
923 return chan;
926 static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
928 size_t offset = 0;
929 GIOStatus status = G_IO_STATUS_NORMAL;
931 while (offset < len && status == G_IO_STATUS_NORMAL) {
932 gsize bytes_written = 0;
934 status = g_io_channel_write_chars(fd, buf + offset, len - offset,
935 &bytes_written, NULL);
936 offset += bytes_written;
939 if (offset > 0) {
940 return offset;
942 switch (status) {
943 case G_IO_STATUS_NORMAL:
944 g_assert(len == 0);
945 return 0;
946 case G_IO_STATUS_AGAIN:
947 errno = EAGAIN;
948 return -1;
949 default:
950 break;
952 errno = EINVAL;
953 return -1;
956 #ifndef _WIN32
958 typedef struct FDCharDriver {
959 CharDriverState *chr;
960 GIOChannel *fd_in, *fd_out;
961 int max_size;
962 } FDCharDriver;
964 /* Called with chr_write_lock held. */
965 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
967 FDCharDriver *s = chr->opaque;
969 return io_channel_send(s->fd_out, buf, len);
972 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
974 CharDriverState *chr = opaque;
975 FDCharDriver *s = chr->opaque;
976 int len;
977 uint8_t buf[READ_BUF_LEN];
978 GIOStatus status;
979 gsize bytes_read;
981 len = sizeof(buf);
982 if (len > s->max_size) {
983 len = s->max_size;
985 if (len == 0) {
986 return TRUE;
989 status = g_io_channel_read_chars(chan, (gchar *)buf,
990 len, &bytes_read, NULL);
991 if (status == G_IO_STATUS_EOF) {
992 remove_fd_in_watch(chr);
993 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
994 return FALSE;
996 if (status == G_IO_STATUS_NORMAL) {
997 qemu_chr_be_write(chr, buf, bytes_read);
1000 return TRUE;
1003 static int fd_chr_read_poll(void *opaque)
1005 CharDriverState *chr = opaque;
1006 FDCharDriver *s = chr->opaque;
1008 s->max_size = qemu_chr_be_can_write(chr);
1009 return s->max_size;
1012 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1014 FDCharDriver *s = chr->opaque;
1015 return g_io_create_watch(s->fd_out, cond);
1018 static void fd_chr_update_read_handler(CharDriverState *chr)
1020 FDCharDriver *s = chr->opaque;
1022 remove_fd_in_watch(chr);
1023 if (s->fd_in) {
1024 chr->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll,
1025 fd_chr_read, chr);
1029 static void fd_chr_close(struct CharDriverState *chr)
1031 FDCharDriver *s = chr->opaque;
1033 remove_fd_in_watch(chr);
1034 if (s->fd_in) {
1035 g_io_channel_unref(s->fd_in);
1037 if (s->fd_out) {
1038 g_io_channel_unref(s->fd_out);
1041 g_free(s);
1042 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1045 /* open a character device to a unix fd */
1046 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1047 ChardevCommon *backend, Error **errp)
1049 CharDriverState *chr;
1050 FDCharDriver *s;
1052 chr = qemu_chr_alloc(backend, errp);
1053 if (!chr) {
1054 return NULL;
1056 s = g_new0(FDCharDriver, 1);
1057 s->fd_in = io_channel_from_fd(fd_in);
1058 s->fd_out = io_channel_from_fd(fd_out);
1059 qemu_set_nonblock(fd_out);
1060 s->chr = chr;
1061 chr->opaque = s;
1062 chr->chr_add_watch = fd_chr_add_watch;
1063 chr->chr_write = fd_chr_write;
1064 chr->chr_update_read_handler = fd_chr_update_read_handler;
1065 chr->chr_close = fd_chr_close;
1067 return chr;
1070 static CharDriverState *qemu_chr_open_pipe(const char *id,
1071 ChardevBackend *backend,
1072 ChardevReturn *ret,
1073 Error **errp)
1075 ChardevHostdev *opts = backend->u.pipe;
1076 int fd_in, fd_out;
1077 char filename_in[CHR_MAX_FILENAME_SIZE];
1078 char filename_out[CHR_MAX_FILENAME_SIZE];
1079 const char *filename = opts->device;
1080 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.pipe);
1082 snprintf(filename_in, CHR_MAX_FILENAME_SIZE, "%s.in", filename);
1083 snprintf(filename_out, CHR_MAX_FILENAME_SIZE, "%s.out", filename);
1084 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1085 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1086 if (fd_in < 0 || fd_out < 0) {
1087 if (fd_in >= 0)
1088 close(fd_in);
1089 if (fd_out >= 0)
1090 close(fd_out);
1091 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1092 if (fd_in < 0) {
1093 error_setg_file_open(errp, errno, filename);
1094 return NULL;
1097 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1100 /* init terminal so that we can grab keys */
1101 static struct termios oldtty;
1102 static int old_fd0_flags;
1103 static bool stdio_in_use;
1104 static bool stdio_allow_signal;
1105 static bool stdio_echo_state;
1107 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1109 static void term_exit(void)
1111 tcsetattr (0, TCSANOW, &oldtty);
1112 fcntl(0, F_SETFL, old_fd0_flags);
1115 static void term_stdio_handler(int sig)
1117 /* restore echo after resume from suspend. */
1118 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1121 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1123 struct termios tty;
1125 stdio_echo_state = echo;
1126 tty = oldtty;
1127 if (!echo) {
1128 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1129 |INLCR|IGNCR|ICRNL|IXON);
1130 tty.c_oflag |= OPOST;
1131 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1132 tty.c_cflag &= ~(CSIZE|PARENB);
1133 tty.c_cflag |= CS8;
1134 tty.c_cc[VMIN] = 1;
1135 tty.c_cc[VTIME] = 0;
1137 if (!stdio_allow_signal)
1138 tty.c_lflag &= ~ISIG;
1140 tcsetattr (0, TCSANOW, &tty);
1143 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1145 term_exit();
1146 fd_chr_close(chr);
1149 static CharDriverState *qemu_chr_open_stdio(const char *id,
1150 ChardevBackend *backend,
1151 ChardevReturn *ret,
1152 Error **errp)
1154 ChardevStdio *opts = backend->u.stdio;
1155 CharDriverState *chr;
1156 struct sigaction act;
1157 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio);
1159 if (is_daemonized()) {
1160 error_setg(errp, "cannot use stdio with -daemonize");
1161 return NULL;
1164 if (stdio_in_use) {
1165 error_setg(errp, "cannot use stdio by multiple character devices");
1166 return NULL;
1169 stdio_in_use = true;
1170 old_fd0_flags = fcntl(0, F_GETFL);
1171 tcgetattr(0, &oldtty);
1172 qemu_set_nonblock(0);
1173 atexit(term_exit);
1175 memset(&act, 0, sizeof(act));
1176 act.sa_handler = term_stdio_handler;
1177 sigaction(SIGCONT, &act, NULL);
1179 chr = qemu_chr_open_fd(0, 1, common, errp);
1180 chr->chr_close = qemu_chr_close_stdio;
1181 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1182 if (opts->has_signal) {
1183 stdio_allow_signal = opts->signal;
1185 qemu_chr_fe_set_echo(chr, false);
1187 return chr;
1190 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1191 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1192 || defined(__GLIBC__)
1194 #define HAVE_CHARDEV_SERIAL 1
1195 #define HAVE_CHARDEV_PTY 1
1197 typedef struct {
1198 GIOChannel *fd;
1199 int read_bytes;
1201 /* Protected by the CharDriverState chr_write_lock. */
1202 int connected;
1203 guint timer_tag;
1204 guint open_tag;
1205 } PtyCharDriver;
1207 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1208 static void pty_chr_state(CharDriverState *chr, int connected);
1210 static gboolean pty_chr_timer(gpointer opaque)
1212 struct CharDriverState *chr = opaque;
1213 PtyCharDriver *s = chr->opaque;
1215 qemu_mutex_lock(&chr->chr_write_lock);
1216 s->timer_tag = 0;
1217 s->open_tag = 0;
1218 if (!s->connected) {
1219 /* Next poll ... */
1220 pty_chr_update_read_handler_locked(chr);
1222 qemu_mutex_unlock(&chr->chr_write_lock);
1223 return FALSE;
1226 /* Called with chr_write_lock held. */
1227 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1229 PtyCharDriver *s = chr->opaque;
1231 if (s->timer_tag) {
1232 g_source_remove(s->timer_tag);
1233 s->timer_tag = 0;
1236 if (ms == 1000) {
1237 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1238 } else {
1239 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1243 /* Called with chr_write_lock held. */
1244 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1246 PtyCharDriver *s = chr->opaque;
1247 GPollFD pfd;
1248 int rc;
1250 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1251 pfd.events = G_IO_OUT;
1252 pfd.revents = 0;
1253 do {
1254 rc = g_poll(&pfd, 1, 0);
1255 } while (rc == -1 && errno == EINTR);
1256 assert(rc >= 0);
1258 if (pfd.revents & G_IO_HUP) {
1259 pty_chr_state(chr, 0);
1260 } else {
1261 pty_chr_state(chr, 1);
1265 static void pty_chr_update_read_handler(CharDriverState *chr)
1267 qemu_mutex_lock(&chr->chr_write_lock);
1268 pty_chr_update_read_handler_locked(chr);
1269 qemu_mutex_unlock(&chr->chr_write_lock);
1272 /* Called with chr_write_lock held. */
1273 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1275 PtyCharDriver *s = chr->opaque;
1277 if (!s->connected) {
1278 /* guest sends data, check for (re-)connect */
1279 pty_chr_update_read_handler_locked(chr);
1280 if (!s->connected) {
1281 return 0;
1284 return io_channel_send(s->fd, buf, len);
1287 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1289 PtyCharDriver *s = chr->opaque;
1290 if (!s->connected) {
1291 return NULL;
1293 return g_io_create_watch(s->fd, cond);
1296 static int pty_chr_read_poll(void *opaque)
1298 CharDriverState *chr = opaque;
1299 PtyCharDriver *s = chr->opaque;
1301 s->read_bytes = qemu_chr_be_can_write(chr);
1302 return s->read_bytes;
1305 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1307 CharDriverState *chr = opaque;
1308 PtyCharDriver *s = chr->opaque;
1309 gsize size, len;
1310 uint8_t buf[READ_BUF_LEN];
1311 GIOStatus status;
1313 len = sizeof(buf);
1314 if (len > s->read_bytes)
1315 len = s->read_bytes;
1316 if (len == 0) {
1317 return TRUE;
1319 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1320 if (status != G_IO_STATUS_NORMAL) {
1321 pty_chr_state(chr, 0);
1322 return FALSE;
1323 } else {
1324 pty_chr_state(chr, 1);
1325 qemu_chr_be_write(chr, buf, size);
1327 return TRUE;
1330 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1332 CharDriverState *chr = opaque;
1333 PtyCharDriver *s = chr->opaque;
1335 s->open_tag = 0;
1336 qemu_chr_be_generic_open(chr);
1337 return FALSE;
1340 /* Called with chr_write_lock held. */
1341 static void pty_chr_state(CharDriverState *chr, int connected)
1343 PtyCharDriver *s = chr->opaque;
1345 if (!connected) {
1346 if (s->open_tag) {
1347 g_source_remove(s->open_tag);
1348 s->open_tag = 0;
1350 remove_fd_in_watch(chr);
1351 s->connected = 0;
1352 /* (re-)connect poll interval for idle guests: once per second.
1353 * We check more frequently in case the guests sends data to
1354 * the virtual device linked to our pty. */
1355 pty_chr_rearm_timer(chr, 1000);
1356 } else {
1357 if (s->timer_tag) {
1358 g_source_remove(s->timer_tag);
1359 s->timer_tag = 0;
1361 if (!s->connected) {
1362 g_assert(s->open_tag == 0);
1363 s->connected = 1;
1364 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1366 if (!chr->fd_in_tag) {
1367 chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
1368 pty_chr_read, chr);
1373 static void pty_chr_close(struct CharDriverState *chr)
1375 PtyCharDriver *s = chr->opaque;
1376 int fd;
1378 qemu_mutex_lock(&chr->chr_write_lock);
1379 pty_chr_state(chr, 0);
1380 fd = g_io_channel_unix_get_fd(s->fd);
1381 g_io_channel_unref(s->fd);
1382 close(fd);
1383 if (s->timer_tag) {
1384 g_source_remove(s->timer_tag);
1385 s->timer_tag = 0;
1387 qemu_mutex_unlock(&chr->chr_write_lock);
1388 g_free(s);
1389 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1392 static CharDriverState *qemu_chr_open_pty(const char *id,
1393 ChardevBackend *backend,
1394 ChardevReturn *ret,
1395 Error **errp)
1397 CharDriverState *chr;
1398 PtyCharDriver *s;
1399 int master_fd, slave_fd;
1400 char pty_name[PATH_MAX];
1401 ChardevCommon *common = qapi_ChardevDummy_base(backend->u.pty);
1403 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1404 if (master_fd < 0) {
1405 error_setg_errno(errp, errno, "Failed to create PTY");
1406 return NULL;
1409 close(slave_fd);
1410 qemu_set_nonblock(master_fd);
1412 chr = qemu_chr_alloc(common, errp);
1413 if (!chr) {
1414 close(master_fd);
1415 return NULL;
1418 chr->filename = g_strdup_printf("pty:%s", pty_name);
1419 ret->pty = g_strdup(pty_name);
1420 ret->has_pty = true;
1422 fprintf(stderr, "char device redirected to %s (label %s)\n",
1423 pty_name, id);
1425 s = g_new0(PtyCharDriver, 1);
1426 chr->opaque = s;
1427 chr->chr_write = pty_chr_write;
1428 chr->chr_update_read_handler = pty_chr_update_read_handler;
1429 chr->chr_close = pty_chr_close;
1430 chr->chr_add_watch = pty_chr_add_watch;
1431 chr->explicit_be_open = true;
1433 s->fd = io_channel_from_fd(master_fd);
1434 s->timer_tag = 0;
1436 return chr;
1439 static void tty_serial_init(int fd, int speed,
1440 int parity, int data_bits, int stop_bits)
1442 struct termios tty;
1443 speed_t spd;
1445 #if 0
1446 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1447 speed, parity, data_bits, stop_bits);
1448 #endif
1449 tcgetattr (fd, &tty);
1451 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1452 speed = speed * 10 / 11;
1453 do {
1454 check_speed(50);
1455 check_speed(75);
1456 check_speed(110);
1457 check_speed(134);
1458 check_speed(150);
1459 check_speed(200);
1460 check_speed(300);
1461 check_speed(600);
1462 check_speed(1200);
1463 check_speed(1800);
1464 check_speed(2400);
1465 check_speed(4800);
1466 check_speed(9600);
1467 check_speed(19200);
1468 check_speed(38400);
1469 /* Non-Posix values follow. They may be unsupported on some systems. */
1470 check_speed(57600);
1471 check_speed(115200);
1472 #ifdef B230400
1473 check_speed(230400);
1474 #endif
1475 #ifdef B460800
1476 check_speed(460800);
1477 #endif
1478 #ifdef B500000
1479 check_speed(500000);
1480 #endif
1481 #ifdef B576000
1482 check_speed(576000);
1483 #endif
1484 #ifdef B921600
1485 check_speed(921600);
1486 #endif
1487 #ifdef B1000000
1488 check_speed(1000000);
1489 #endif
1490 #ifdef B1152000
1491 check_speed(1152000);
1492 #endif
1493 #ifdef B1500000
1494 check_speed(1500000);
1495 #endif
1496 #ifdef B2000000
1497 check_speed(2000000);
1498 #endif
1499 #ifdef B2500000
1500 check_speed(2500000);
1501 #endif
1502 #ifdef B3000000
1503 check_speed(3000000);
1504 #endif
1505 #ifdef B3500000
1506 check_speed(3500000);
1507 #endif
1508 #ifdef B4000000
1509 check_speed(4000000);
1510 #endif
1511 spd = B115200;
1512 } while (0);
1514 cfsetispeed(&tty, spd);
1515 cfsetospeed(&tty, spd);
1517 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1518 |INLCR|IGNCR|ICRNL|IXON);
1519 tty.c_oflag |= OPOST;
1520 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1521 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1522 switch(data_bits) {
1523 default:
1524 case 8:
1525 tty.c_cflag |= CS8;
1526 break;
1527 case 7:
1528 tty.c_cflag |= CS7;
1529 break;
1530 case 6:
1531 tty.c_cflag |= CS6;
1532 break;
1533 case 5:
1534 tty.c_cflag |= CS5;
1535 break;
1537 switch(parity) {
1538 default:
1539 case 'N':
1540 break;
1541 case 'E':
1542 tty.c_cflag |= PARENB;
1543 break;
1544 case 'O':
1545 tty.c_cflag |= PARENB | PARODD;
1546 break;
1548 if (stop_bits == 2)
1549 tty.c_cflag |= CSTOPB;
1551 tcsetattr (fd, TCSANOW, &tty);
1554 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1556 FDCharDriver *s = chr->opaque;
1558 switch(cmd) {
1559 case CHR_IOCTL_SERIAL_SET_PARAMS:
1561 QEMUSerialSetParams *ssp = arg;
1562 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1563 ssp->speed, ssp->parity,
1564 ssp->data_bits, ssp->stop_bits);
1566 break;
1567 case CHR_IOCTL_SERIAL_SET_BREAK:
1569 int enable = *(int *)arg;
1570 if (enable) {
1571 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1574 break;
1575 case CHR_IOCTL_SERIAL_GET_TIOCM:
1577 int sarg = 0;
1578 int *targ = (int *)arg;
1579 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1580 *targ = 0;
1581 if (sarg & TIOCM_CTS)
1582 *targ |= CHR_TIOCM_CTS;
1583 if (sarg & TIOCM_CAR)
1584 *targ |= CHR_TIOCM_CAR;
1585 if (sarg & TIOCM_DSR)
1586 *targ |= CHR_TIOCM_DSR;
1587 if (sarg & TIOCM_RI)
1588 *targ |= CHR_TIOCM_RI;
1589 if (sarg & TIOCM_DTR)
1590 *targ |= CHR_TIOCM_DTR;
1591 if (sarg & TIOCM_RTS)
1592 *targ |= CHR_TIOCM_RTS;
1594 break;
1595 case CHR_IOCTL_SERIAL_SET_TIOCM:
1597 int sarg = *(int *)arg;
1598 int targ = 0;
1599 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1600 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1601 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1602 if (sarg & CHR_TIOCM_CTS)
1603 targ |= TIOCM_CTS;
1604 if (sarg & CHR_TIOCM_CAR)
1605 targ |= TIOCM_CAR;
1606 if (sarg & CHR_TIOCM_DSR)
1607 targ |= TIOCM_DSR;
1608 if (sarg & CHR_TIOCM_RI)
1609 targ |= TIOCM_RI;
1610 if (sarg & CHR_TIOCM_DTR)
1611 targ |= TIOCM_DTR;
1612 if (sarg & CHR_TIOCM_RTS)
1613 targ |= TIOCM_RTS;
1614 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1616 break;
1617 default:
1618 return -ENOTSUP;
1620 return 0;
1623 static void qemu_chr_close_tty(CharDriverState *chr)
1625 FDCharDriver *s = chr->opaque;
1626 int fd = -1;
1628 if (s) {
1629 fd = g_io_channel_unix_get_fd(s->fd_in);
1632 fd_chr_close(chr);
1634 if (fd >= 0) {
1635 close(fd);
1639 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1640 ChardevCommon *backend,
1641 Error **errp)
1643 CharDriverState *chr;
1645 tty_serial_init(fd, 115200, 'N', 8, 1);
1646 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1647 chr->chr_ioctl = tty_serial_ioctl;
1648 chr->chr_close = qemu_chr_close_tty;
1649 return chr;
1651 #endif /* __linux__ || __sun__ */
1653 #if defined(__linux__)
1655 #define HAVE_CHARDEV_PARPORT 1
1657 typedef struct {
1658 int fd;
1659 int mode;
1660 } ParallelCharDriver;
1662 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1664 if (s->mode != mode) {
1665 int m = mode;
1666 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1667 return 0;
1668 s->mode = mode;
1670 return 1;
1673 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1675 ParallelCharDriver *drv = chr->opaque;
1676 int fd = drv->fd;
1677 uint8_t b;
1679 switch(cmd) {
1680 case CHR_IOCTL_PP_READ_DATA:
1681 if (ioctl(fd, PPRDATA, &b) < 0)
1682 return -ENOTSUP;
1683 *(uint8_t *)arg = b;
1684 break;
1685 case CHR_IOCTL_PP_WRITE_DATA:
1686 b = *(uint8_t *)arg;
1687 if (ioctl(fd, PPWDATA, &b) < 0)
1688 return -ENOTSUP;
1689 break;
1690 case CHR_IOCTL_PP_READ_CONTROL:
1691 if (ioctl(fd, PPRCONTROL, &b) < 0)
1692 return -ENOTSUP;
1693 /* Linux gives only the lowest bits, and no way to know data
1694 direction! For better compatibility set the fixed upper
1695 bits. */
1696 *(uint8_t *)arg = b | 0xc0;
1697 break;
1698 case CHR_IOCTL_PP_WRITE_CONTROL:
1699 b = *(uint8_t *)arg;
1700 if (ioctl(fd, PPWCONTROL, &b) < 0)
1701 return -ENOTSUP;
1702 break;
1703 case CHR_IOCTL_PP_READ_STATUS:
1704 if (ioctl(fd, PPRSTATUS, &b) < 0)
1705 return -ENOTSUP;
1706 *(uint8_t *)arg = b;
1707 break;
1708 case CHR_IOCTL_PP_DATA_DIR:
1709 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1710 return -ENOTSUP;
1711 break;
1712 case CHR_IOCTL_PP_EPP_READ_ADDR:
1713 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1714 struct ParallelIOArg *parg = arg;
1715 int n = read(fd, parg->buffer, parg->count);
1716 if (n != parg->count) {
1717 return -EIO;
1720 break;
1721 case CHR_IOCTL_PP_EPP_READ:
1722 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1723 struct ParallelIOArg *parg = arg;
1724 int n = read(fd, parg->buffer, parg->count);
1725 if (n != parg->count) {
1726 return -EIO;
1729 break;
1730 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1731 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1732 struct ParallelIOArg *parg = arg;
1733 int n = write(fd, parg->buffer, parg->count);
1734 if (n != parg->count) {
1735 return -EIO;
1738 break;
1739 case CHR_IOCTL_PP_EPP_WRITE:
1740 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1741 struct ParallelIOArg *parg = arg;
1742 int n = write(fd, parg->buffer, parg->count);
1743 if (n != parg->count) {
1744 return -EIO;
1747 break;
1748 default:
1749 return -ENOTSUP;
1751 return 0;
1754 static void pp_close(CharDriverState *chr)
1756 ParallelCharDriver *drv = chr->opaque;
1757 int fd = drv->fd;
1759 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1760 ioctl(fd, PPRELEASE);
1761 close(fd);
1762 g_free(drv);
1763 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1766 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1767 ChardevCommon *backend,
1768 Error **errp)
1770 CharDriverState *chr;
1771 ParallelCharDriver *drv;
1773 if (ioctl(fd, PPCLAIM) < 0) {
1774 error_setg_errno(errp, errno, "not a parallel port");
1775 close(fd);
1776 return NULL;
1779 drv = g_new0(ParallelCharDriver, 1);
1780 drv->fd = fd;
1781 drv->mode = IEEE1284_MODE_COMPAT;
1783 chr = qemu_chr_alloc(backend, errp);
1784 if (!chr) {
1785 return NULL;
1787 chr->chr_write = null_chr_write;
1788 chr->chr_ioctl = pp_ioctl;
1789 chr->chr_close = pp_close;
1790 chr->opaque = drv;
1792 return chr;
1794 #endif /* __linux__ */
1796 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1798 #define HAVE_CHARDEV_PARPORT 1
1800 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1802 int fd = (int)(intptr_t)chr->opaque;
1803 uint8_t b;
1805 switch(cmd) {
1806 case CHR_IOCTL_PP_READ_DATA:
1807 if (ioctl(fd, PPIGDATA, &b) < 0)
1808 return -ENOTSUP;
1809 *(uint8_t *)arg = b;
1810 break;
1811 case CHR_IOCTL_PP_WRITE_DATA:
1812 b = *(uint8_t *)arg;
1813 if (ioctl(fd, PPISDATA, &b) < 0)
1814 return -ENOTSUP;
1815 break;
1816 case CHR_IOCTL_PP_READ_CONTROL:
1817 if (ioctl(fd, PPIGCTRL, &b) < 0)
1818 return -ENOTSUP;
1819 *(uint8_t *)arg = b;
1820 break;
1821 case CHR_IOCTL_PP_WRITE_CONTROL:
1822 b = *(uint8_t *)arg;
1823 if (ioctl(fd, PPISCTRL, &b) < 0)
1824 return -ENOTSUP;
1825 break;
1826 case CHR_IOCTL_PP_READ_STATUS:
1827 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1828 return -ENOTSUP;
1829 *(uint8_t *)arg = b;
1830 break;
1831 default:
1832 return -ENOTSUP;
1834 return 0;
1837 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1838 ChardevBackend *backend,
1839 Error **errp)
1841 CharDriverState *chr;
1843 chr = qemu_chr_alloc(common, errp);
1844 if (!chr) {
1845 return NULL;
1847 chr->opaque = (void *)(intptr_t)fd;
1848 chr->chr_write = null_chr_write;
1849 chr->chr_ioctl = pp_ioctl;
1850 chr->explicit_be_open = true;
1851 return chr;
1853 #endif
1855 #else /* _WIN32 */
1857 #define HAVE_CHARDEV_SERIAL 1
1859 typedef struct {
1860 int max_size;
1861 HANDLE hcom, hrecv, hsend;
1862 OVERLAPPED orecv;
1863 BOOL fpipe;
1864 DWORD len;
1866 /* Protected by the CharDriverState chr_write_lock. */
1867 OVERLAPPED osend;
1868 } WinCharState;
1870 typedef struct {
1871 HANDLE hStdIn;
1872 HANDLE hInputReadyEvent;
1873 HANDLE hInputDoneEvent;
1874 HANDLE hInputThread;
1875 uint8_t win_stdio_buf;
1876 } WinStdioCharState;
1878 #define NSENDBUF 2048
1879 #define NRECVBUF 2048
1880 #define MAXCONNECT 1
1881 #define NTIMEOUT 5000
1883 static int win_chr_poll(void *opaque);
1884 static int win_chr_pipe_poll(void *opaque);
1886 static void win_chr_close(CharDriverState *chr)
1888 WinCharState *s = chr->opaque;
1890 if (s->hsend) {
1891 CloseHandle(s->hsend);
1892 s->hsend = NULL;
1894 if (s->hrecv) {
1895 CloseHandle(s->hrecv);
1896 s->hrecv = NULL;
1898 if (s->hcom) {
1899 CloseHandle(s->hcom);
1900 s->hcom = NULL;
1902 if (s->fpipe)
1903 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1904 else
1905 qemu_del_polling_cb(win_chr_poll, chr);
1907 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1910 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1912 WinCharState *s = chr->opaque;
1913 COMMCONFIG comcfg;
1914 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1915 COMSTAT comstat;
1916 DWORD size;
1917 DWORD err;
1919 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1920 if (!s->hsend) {
1921 error_setg(errp, "Failed CreateEvent");
1922 goto fail;
1924 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1925 if (!s->hrecv) {
1926 error_setg(errp, "Failed CreateEvent");
1927 goto fail;
1930 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1931 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1932 if (s->hcom == INVALID_HANDLE_VALUE) {
1933 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1934 s->hcom = NULL;
1935 goto fail;
1938 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1939 error_setg(errp, "Failed SetupComm");
1940 goto fail;
1943 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1944 size = sizeof(COMMCONFIG);
1945 GetDefaultCommConfig(filename, &comcfg, &size);
1946 comcfg.dcb.DCBlength = sizeof(DCB);
1947 CommConfigDialog(filename, NULL, &comcfg);
1949 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1950 error_setg(errp, "Failed SetCommState");
1951 goto fail;
1954 if (!SetCommMask(s->hcom, EV_ERR)) {
1955 error_setg(errp, "Failed SetCommMask");
1956 goto fail;
1959 cto.ReadIntervalTimeout = MAXDWORD;
1960 if (!SetCommTimeouts(s->hcom, &cto)) {
1961 error_setg(errp, "Failed SetCommTimeouts");
1962 goto fail;
1965 if (!ClearCommError(s->hcom, &err, &comstat)) {
1966 error_setg(errp, "Failed ClearCommError");
1967 goto fail;
1969 qemu_add_polling_cb(win_chr_poll, chr);
1970 return 0;
1972 fail:
1973 win_chr_close(chr);
1974 return -1;
1977 /* Called with chr_write_lock held. */
1978 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1980 WinCharState *s = chr->opaque;
1981 DWORD len, ret, size, err;
1983 len = len1;
1984 ZeroMemory(&s->osend, sizeof(s->osend));
1985 s->osend.hEvent = s->hsend;
1986 while (len > 0) {
1987 if (s->hsend)
1988 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1989 else
1990 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1991 if (!ret) {
1992 err = GetLastError();
1993 if (err == ERROR_IO_PENDING) {
1994 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1995 if (ret) {
1996 buf += size;
1997 len -= size;
1998 } else {
1999 break;
2001 } else {
2002 break;
2004 } else {
2005 buf += size;
2006 len -= size;
2009 return len1 - len;
2012 static int win_chr_read_poll(CharDriverState *chr)
2014 WinCharState *s = chr->opaque;
2016 s->max_size = qemu_chr_be_can_write(chr);
2017 return s->max_size;
2020 static void win_chr_readfile(CharDriverState *chr)
2022 WinCharState *s = chr->opaque;
2023 int ret, err;
2024 uint8_t buf[READ_BUF_LEN];
2025 DWORD size;
2027 ZeroMemory(&s->orecv, sizeof(s->orecv));
2028 s->orecv.hEvent = s->hrecv;
2029 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2030 if (!ret) {
2031 err = GetLastError();
2032 if (err == ERROR_IO_PENDING) {
2033 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2037 if (size > 0) {
2038 qemu_chr_be_write(chr, buf, size);
2042 static void win_chr_read(CharDriverState *chr)
2044 WinCharState *s = chr->opaque;
2046 if (s->len > s->max_size)
2047 s->len = s->max_size;
2048 if (s->len == 0)
2049 return;
2051 win_chr_readfile(chr);
2054 static int win_chr_poll(void *opaque)
2056 CharDriverState *chr = opaque;
2057 WinCharState *s = chr->opaque;
2058 COMSTAT status;
2059 DWORD comerr;
2061 ClearCommError(s->hcom, &comerr, &status);
2062 if (status.cbInQue > 0) {
2063 s->len = status.cbInQue;
2064 win_chr_read_poll(chr);
2065 win_chr_read(chr);
2066 return 1;
2068 return 0;
2071 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2072 ChardevCommon *backend,
2073 Error **errp)
2075 CharDriverState *chr;
2076 WinCharState *s;
2078 chr = qemu_chr_alloc(backend, errp);
2079 if (!chr) {
2080 return NULL;
2082 s = g_new0(WinCharState, 1);
2083 chr->opaque = s;
2084 chr->chr_write = win_chr_write;
2085 chr->chr_close = win_chr_close;
2087 if (win_chr_init(chr, filename, errp) < 0) {
2088 g_free(s);
2089 qemu_chr_free_common(chr);
2090 return NULL;
2092 return chr;
2095 static int win_chr_pipe_poll(void *opaque)
2097 CharDriverState *chr = opaque;
2098 WinCharState *s = chr->opaque;
2099 DWORD size;
2101 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2102 if (size > 0) {
2103 s->len = size;
2104 win_chr_read_poll(chr);
2105 win_chr_read(chr);
2106 return 1;
2108 return 0;
2111 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2112 Error **errp)
2114 WinCharState *s = chr->opaque;
2115 OVERLAPPED ov;
2116 int ret;
2117 DWORD size;
2118 char openname[CHR_MAX_FILENAME_SIZE];
2120 s->fpipe = TRUE;
2122 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2123 if (!s->hsend) {
2124 error_setg(errp, "Failed CreateEvent");
2125 goto fail;
2127 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2128 if (!s->hrecv) {
2129 error_setg(errp, "Failed CreateEvent");
2130 goto fail;
2133 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2134 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2135 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2136 PIPE_WAIT,
2137 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2138 if (s->hcom == INVALID_HANDLE_VALUE) {
2139 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2140 s->hcom = NULL;
2141 goto fail;
2144 ZeroMemory(&ov, sizeof(ov));
2145 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2146 ret = ConnectNamedPipe(s->hcom, &ov);
2147 if (ret) {
2148 error_setg(errp, "Failed ConnectNamedPipe");
2149 goto fail;
2152 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2153 if (!ret) {
2154 error_setg(errp, "Failed GetOverlappedResult");
2155 if (ov.hEvent) {
2156 CloseHandle(ov.hEvent);
2157 ov.hEvent = NULL;
2159 goto fail;
2162 if (ov.hEvent) {
2163 CloseHandle(ov.hEvent);
2164 ov.hEvent = NULL;
2166 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2167 return 0;
2169 fail:
2170 win_chr_close(chr);
2171 return -1;
2175 static CharDriverState *qemu_chr_open_pipe(const char *id,
2176 ChardevBackend *backend,
2177 ChardevReturn *ret,
2178 Error **errp)
2180 ChardevHostdev *opts = backend->u.pipe;
2181 const char *filename = opts->device;
2182 CharDriverState *chr;
2183 WinCharState *s;
2184 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.pipe);
2186 chr = qemu_chr_alloc(common, errp);
2187 if (!chr) {
2188 return NULL;
2190 s = g_new0(WinCharState, 1);
2191 chr->opaque = s;
2192 chr->chr_write = win_chr_write;
2193 chr->chr_close = win_chr_close;
2195 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2196 g_free(s);
2197 qemu_chr_free_common(chr);
2198 return NULL;
2200 return chr;
2203 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2204 ChardevCommon *backend,
2205 Error **errp)
2207 CharDriverState *chr;
2208 WinCharState *s;
2210 chr = qemu_chr_alloc(backend, errp);
2211 if (!chr) {
2212 return NULL;
2214 s = g_new0(WinCharState, 1);
2215 s->hcom = fd_out;
2216 chr->opaque = s;
2217 chr->chr_write = win_chr_write;
2218 return chr;
2221 static CharDriverState *qemu_chr_open_win_con(const char *id,
2222 ChardevBackend *backend,
2223 ChardevReturn *ret,
2224 Error **errp)
2226 ChardevCommon *common = qapi_ChardevDummy_base(backend->u.console);
2227 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2228 common, errp);
2231 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2233 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2234 DWORD dwSize;
2235 int len1;
2237 len1 = len;
2239 while (len1 > 0) {
2240 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2241 break;
2243 buf += dwSize;
2244 len1 -= dwSize;
2247 return len - len1;
2250 static void win_stdio_wait_func(void *opaque)
2252 CharDriverState *chr = opaque;
2253 WinStdioCharState *stdio = chr->opaque;
2254 INPUT_RECORD buf[4];
2255 int ret;
2256 DWORD dwSize;
2257 int i;
2259 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2261 if (!ret) {
2262 /* Avoid error storm */
2263 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2264 return;
2267 for (i = 0; i < dwSize; i++) {
2268 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2270 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2271 int j;
2272 if (kev->uChar.AsciiChar != 0) {
2273 for (j = 0; j < kev->wRepeatCount; j++) {
2274 if (qemu_chr_be_can_write(chr)) {
2275 uint8_t c = kev->uChar.AsciiChar;
2276 qemu_chr_be_write(chr, &c, 1);
2284 static DWORD WINAPI win_stdio_thread(LPVOID param)
2286 CharDriverState *chr = param;
2287 WinStdioCharState *stdio = chr->opaque;
2288 int ret;
2289 DWORD dwSize;
2291 while (1) {
2293 /* Wait for one byte */
2294 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2296 /* Exit in case of error, continue if nothing read */
2297 if (!ret) {
2298 break;
2300 if (!dwSize) {
2301 continue;
2304 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2305 if (stdio->win_stdio_buf == '\r') {
2306 continue;
2309 /* Signal the main thread and wait until the byte was eaten */
2310 if (!SetEvent(stdio->hInputReadyEvent)) {
2311 break;
2313 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2314 != WAIT_OBJECT_0) {
2315 break;
2319 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2320 return 0;
2323 static void win_stdio_thread_wait_func(void *opaque)
2325 CharDriverState *chr = opaque;
2326 WinStdioCharState *stdio = chr->opaque;
2328 if (qemu_chr_be_can_write(chr)) {
2329 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2332 SetEvent(stdio->hInputDoneEvent);
2335 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2337 WinStdioCharState *stdio = chr->opaque;
2338 DWORD dwMode = 0;
2340 GetConsoleMode(stdio->hStdIn, &dwMode);
2342 if (echo) {
2343 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2344 } else {
2345 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2349 static void win_stdio_close(CharDriverState *chr)
2351 WinStdioCharState *stdio = chr->opaque;
2353 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2354 CloseHandle(stdio->hInputReadyEvent);
2356 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2357 CloseHandle(stdio->hInputDoneEvent);
2359 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2360 TerminateThread(stdio->hInputThread, 0);
2363 g_free(chr->opaque);
2364 g_free(chr);
2367 static CharDriverState *qemu_chr_open_stdio(const char *id,
2368 ChardevBackend *backend,
2369 ChardevReturn *ret,
2370 Error **errp)
2372 CharDriverState *chr;
2373 WinStdioCharState *stdio;
2374 DWORD dwMode;
2375 int is_console = 0;
2376 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio);
2378 chr = qemu_chr_alloc(common, errp);
2379 if (!chr) {
2380 return NULL;
2382 stdio = g_new0(WinStdioCharState, 1);
2384 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2385 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2386 error_setg(errp, "cannot open stdio: invalid handle");
2387 return NULL;
2390 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2392 chr->opaque = stdio;
2393 chr->chr_write = win_stdio_write;
2394 chr->chr_close = win_stdio_close;
2396 if (is_console) {
2397 if (qemu_add_wait_object(stdio->hStdIn,
2398 win_stdio_wait_func, chr)) {
2399 error_setg(errp, "qemu_add_wait_object: failed");
2400 goto err1;
2402 } else {
2403 DWORD dwId;
2405 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2406 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2407 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2408 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2409 error_setg(errp, "cannot create event");
2410 goto err2;
2412 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2413 win_stdio_thread_wait_func, chr)) {
2414 error_setg(errp, "qemu_add_wait_object: failed");
2415 goto err2;
2417 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2418 chr, 0, &dwId);
2420 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2421 error_setg(errp, "cannot create stdio thread");
2422 goto err3;
2426 dwMode |= ENABLE_LINE_INPUT;
2428 if (is_console) {
2429 /* set the terminal in raw mode */
2430 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2431 dwMode |= ENABLE_PROCESSED_INPUT;
2434 SetConsoleMode(stdio->hStdIn, dwMode);
2436 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2437 qemu_chr_fe_set_echo(chr, false);
2439 return chr;
2441 err3:
2442 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2443 err2:
2444 CloseHandle(stdio->hInputReadyEvent);
2445 CloseHandle(stdio->hInputDoneEvent);
2446 err1:
2447 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2448 return NULL;
2450 #endif /* !_WIN32 */
2453 /***********************************************************/
2454 /* UDP Net console */
2456 typedef struct {
2457 int fd;
2458 GIOChannel *chan;
2459 uint8_t buf[READ_BUF_LEN];
2460 int bufcnt;
2461 int bufptr;
2462 int max_size;
2463 } NetCharDriver;
2465 /* Called with chr_write_lock held. */
2466 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2468 NetCharDriver *s = chr->opaque;
2469 gsize bytes_written;
2470 GIOStatus status;
2472 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2473 if (status == G_IO_STATUS_EOF) {
2474 return 0;
2475 } else if (status != G_IO_STATUS_NORMAL) {
2476 return -1;
2479 return bytes_written;
2482 static int udp_chr_read_poll(void *opaque)
2484 CharDriverState *chr = opaque;
2485 NetCharDriver *s = chr->opaque;
2487 s->max_size = qemu_chr_be_can_write(chr);
2489 /* If there were any stray characters in the queue process them
2490 * first
2492 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2493 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2494 s->bufptr++;
2495 s->max_size = qemu_chr_be_can_write(chr);
2497 return s->max_size;
2500 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2502 CharDriverState *chr = opaque;
2503 NetCharDriver *s = chr->opaque;
2504 gsize bytes_read = 0;
2505 GIOStatus status;
2507 if (s->max_size == 0) {
2508 return TRUE;
2510 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2511 &bytes_read, NULL);
2512 s->bufcnt = bytes_read;
2513 s->bufptr = s->bufcnt;
2514 if (status != G_IO_STATUS_NORMAL) {
2515 remove_fd_in_watch(chr);
2516 return FALSE;
2519 s->bufptr = 0;
2520 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2521 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2522 s->bufptr++;
2523 s->max_size = qemu_chr_be_can_write(chr);
2526 return TRUE;
2529 static void udp_chr_update_read_handler(CharDriverState *chr)
2531 NetCharDriver *s = chr->opaque;
2533 remove_fd_in_watch(chr);
2534 if (s->chan) {
2535 chr->fd_in_tag = io_add_watch_poll(s->chan, udp_chr_read_poll,
2536 udp_chr_read, chr);
2540 static void udp_chr_close(CharDriverState *chr)
2542 NetCharDriver *s = chr->opaque;
2544 remove_fd_in_watch(chr);
2545 if (s->chan) {
2546 g_io_channel_unref(s->chan);
2547 closesocket(s->fd);
2549 g_free(s);
2550 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2553 static CharDriverState *qemu_chr_open_udp_fd(int fd,
2554 ChardevCommon *backend,
2555 Error **errp)
2557 CharDriverState *chr = NULL;
2558 NetCharDriver *s = NULL;
2560 chr = qemu_chr_alloc(backend, errp);
2561 if (!chr) {
2562 return NULL;
2564 s = g_new0(NetCharDriver, 1);
2566 s->fd = fd;
2567 s->chan = io_channel_from_socket(s->fd);
2568 s->bufcnt = 0;
2569 s->bufptr = 0;
2570 chr->opaque = s;
2571 chr->chr_write = udp_chr_write;
2572 chr->chr_update_read_handler = udp_chr_update_read_handler;
2573 chr->chr_close = udp_chr_close;
2574 /* be isn't opened until we get a connection */
2575 chr->explicit_be_open = true;
2576 return chr;
2579 /***********************************************************/
2580 /* TCP Net console */
2582 typedef struct {
2584 GIOChannel *chan, *listen_chan;
2585 guint listen_tag;
2586 int fd, listen_fd;
2587 int connected;
2588 int max_size;
2589 int do_telnetopt;
2590 int do_nodelay;
2591 int is_unix;
2592 int *read_msgfds;
2593 int read_msgfds_num;
2594 int *write_msgfds;
2595 int write_msgfds_num;
2597 SocketAddress *addr;
2598 bool is_listen;
2599 bool is_telnet;
2601 guint reconnect_timer;
2602 int64_t reconnect_time;
2603 bool connect_err_reported;
2604 } TCPCharDriver;
2606 static gboolean socket_reconnect_timeout(gpointer opaque);
2608 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2610 TCPCharDriver *s = chr->opaque;
2611 assert(s->connected == 0);
2612 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2613 socket_reconnect_timeout, chr);
2616 static void check_report_connect_error(CharDriverState *chr,
2617 Error *err)
2619 TCPCharDriver *s = chr->opaque;
2621 if (!s->connect_err_reported) {
2622 error_report("Unable to connect character device %s: %s",
2623 chr->label, error_get_pretty(err));
2624 s->connect_err_reported = true;
2626 qemu_chr_socket_restart_timer(chr);
2629 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2631 #ifndef _WIN32
2632 static int unix_send_msgfds(CharDriverState *chr, const uint8_t *buf, int len)
2634 TCPCharDriver *s = chr->opaque;
2635 struct msghdr msgh;
2636 struct iovec iov;
2637 int r;
2639 size_t fd_size = s->write_msgfds_num * sizeof(int);
2640 char control[CMSG_SPACE(fd_size)];
2641 struct cmsghdr *cmsg;
2643 memset(&msgh, 0, sizeof(msgh));
2644 memset(control, 0, sizeof(control));
2646 /* set the payload */
2647 iov.iov_base = (uint8_t *) buf;
2648 iov.iov_len = len;
2650 msgh.msg_iov = &iov;
2651 msgh.msg_iovlen = 1;
2653 msgh.msg_control = control;
2654 msgh.msg_controllen = sizeof(control);
2656 cmsg = CMSG_FIRSTHDR(&msgh);
2658 cmsg->cmsg_len = CMSG_LEN(fd_size);
2659 cmsg->cmsg_level = SOL_SOCKET;
2660 cmsg->cmsg_type = SCM_RIGHTS;
2661 memcpy(CMSG_DATA(cmsg), s->write_msgfds, fd_size);
2663 do {
2664 r = sendmsg(s->fd, &msgh, 0);
2665 } while (r < 0 && errno == EINTR);
2667 /* free the written msgfds, no matter what */
2668 if (s->write_msgfds_num) {
2669 g_free(s->write_msgfds);
2670 s->write_msgfds = 0;
2671 s->write_msgfds_num = 0;
2674 return r;
2676 #endif
2678 /* Called with chr_write_lock held. */
2679 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2681 TCPCharDriver *s = chr->opaque;
2682 if (s->connected) {
2683 #ifndef _WIN32
2684 if (s->is_unix && s->write_msgfds_num) {
2685 return unix_send_msgfds(chr, buf, len);
2686 } else
2687 #endif
2689 return io_channel_send(s->chan, buf, len);
2691 } else {
2692 /* XXX: indicate an error ? */
2693 return len;
2697 static int tcp_chr_read_poll(void *opaque)
2699 CharDriverState *chr = opaque;
2700 TCPCharDriver *s = chr->opaque;
2701 if (!s->connected)
2702 return 0;
2703 s->max_size = qemu_chr_be_can_write(chr);
2704 return s->max_size;
2707 #define IAC 255
2708 #define IAC_BREAK 243
2709 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2710 TCPCharDriver *s,
2711 uint8_t *buf, int *size)
2713 /* Handle any telnet client's basic IAC options to satisfy char by
2714 * char mode with no echo. All IAC options will be removed from
2715 * the buf and the do_telnetopt variable will be used to track the
2716 * state of the width of the IAC information.
2718 * IAC commands come in sets of 3 bytes with the exception of the
2719 * "IAC BREAK" command and the double IAC.
2722 int i;
2723 int j = 0;
2725 for (i = 0; i < *size; i++) {
2726 if (s->do_telnetopt > 1) {
2727 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2728 /* Double IAC means send an IAC */
2729 if (j != i)
2730 buf[j] = buf[i];
2731 j++;
2732 s->do_telnetopt = 1;
2733 } else {
2734 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2735 /* Handle IAC break commands by sending a serial break */
2736 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2737 s->do_telnetopt++;
2739 s->do_telnetopt++;
2741 if (s->do_telnetopt >= 4) {
2742 s->do_telnetopt = 1;
2744 } else {
2745 if ((unsigned char)buf[i] == IAC) {
2746 s->do_telnetopt = 2;
2747 } else {
2748 if (j != i)
2749 buf[j] = buf[i];
2750 j++;
2754 *size = j;
2757 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2759 TCPCharDriver *s = chr->opaque;
2760 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2762 assert(num <= TCP_MAX_FDS);
2764 if (to_copy) {
2765 int i;
2767 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2769 /* Close unused fds */
2770 for (i = to_copy; i < s->read_msgfds_num; i++) {
2771 close(s->read_msgfds[i]);
2774 g_free(s->read_msgfds);
2775 s->read_msgfds = 0;
2776 s->read_msgfds_num = 0;
2779 return to_copy;
2782 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2784 TCPCharDriver *s = chr->opaque;
2786 /* clear old pending fd array */
2787 g_free(s->write_msgfds);
2789 if (num) {
2790 s->write_msgfds = g_new(int, num);
2791 memcpy(s->write_msgfds, fds, num * sizeof(int));
2794 s->write_msgfds_num = num;
2796 return 0;
2799 #ifndef _WIN32
2800 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2802 TCPCharDriver *s = chr->opaque;
2803 struct cmsghdr *cmsg;
2805 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2806 int fd_size, i;
2808 if (cmsg->cmsg_len < CMSG_LEN(sizeof(int)) ||
2809 cmsg->cmsg_level != SOL_SOCKET ||
2810 cmsg->cmsg_type != SCM_RIGHTS) {
2811 continue;
2814 fd_size = cmsg->cmsg_len - CMSG_LEN(0);
2816 if (!fd_size) {
2817 continue;
2820 /* close and clean read_msgfds */
2821 for (i = 0; i < s->read_msgfds_num; i++) {
2822 close(s->read_msgfds[i]);
2825 if (s->read_msgfds_num) {
2826 g_free(s->read_msgfds);
2829 s->read_msgfds_num = fd_size / sizeof(int);
2830 s->read_msgfds = g_malloc(fd_size);
2831 memcpy(s->read_msgfds, CMSG_DATA(cmsg), fd_size);
2833 for (i = 0; i < s->read_msgfds_num; i++) {
2834 int fd = s->read_msgfds[i];
2835 if (fd < 0) {
2836 continue;
2839 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2840 qemu_set_block(fd);
2842 #ifndef MSG_CMSG_CLOEXEC
2843 qemu_set_cloexec(fd);
2844 #endif
2849 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2851 TCPCharDriver *s = chr->opaque;
2852 struct msghdr msg = { NULL, };
2853 struct iovec iov[1];
2854 union {
2855 struct cmsghdr cmsg;
2856 char control[CMSG_SPACE(sizeof(int) * TCP_MAX_FDS)];
2857 } msg_control;
2858 int flags = 0;
2859 ssize_t ret;
2861 iov[0].iov_base = buf;
2862 iov[0].iov_len = len;
2864 msg.msg_iov = iov;
2865 msg.msg_iovlen = 1;
2866 msg.msg_control = &msg_control;
2867 msg.msg_controllen = sizeof(msg_control);
2869 #ifdef MSG_CMSG_CLOEXEC
2870 flags |= MSG_CMSG_CLOEXEC;
2871 #endif
2872 do {
2873 ret = recvmsg(s->fd, &msg, flags);
2874 } while (ret == -1 && errno == EINTR);
2876 if (ret > 0 && s->is_unix) {
2877 unix_process_msgfd(chr, &msg);
2880 return ret;
2882 #else
2883 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2885 TCPCharDriver *s = chr->opaque;
2886 ssize_t ret;
2888 do {
2889 ret = qemu_recv(s->fd, buf, len, 0);
2890 } while (ret == -1 && socket_error() == EINTR);
2892 return ret;
2894 #endif
2896 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2898 TCPCharDriver *s = chr->opaque;
2899 return g_io_create_watch(s->chan, cond);
2902 static void tcp_chr_disconnect(CharDriverState *chr)
2904 TCPCharDriver *s = chr->opaque;
2906 s->connected = 0;
2907 if (s->listen_chan) {
2908 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
2909 tcp_chr_accept, chr);
2911 remove_fd_in_watch(chr);
2912 g_io_channel_unref(s->chan);
2913 s->chan = NULL;
2914 closesocket(s->fd);
2915 s->fd = -1;
2916 SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
2917 "disconnected:", s->addr, s->is_listen, s->is_telnet);
2918 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2919 if (s->reconnect_time) {
2920 qemu_chr_socket_restart_timer(chr);
2924 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2926 CharDriverState *chr = opaque;
2927 TCPCharDriver *s = chr->opaque;
2928 uint8_t buf[READ_BUF_LEN];
2929 int len, size;
2931 if (!s->connected || s->max_size <= 0) {
2932 return TRUE;
2934 len = sizeof(buf);
2935 if (len > s->max_size)
2936 len = s->max_size;
2937 size = tcp_chr_recv(chr, (void *)buf, len);
2938 if (size == 0 ||
2939 (size < 0 &&
2940 socket_error() != EAGAIN && socket_error() != EWOULDBLOCK)) {
2941 /* connection closed */
2942 tcp_chr_disconnect(chr);
2943 } else if (size > 0) {
2944 if (s->do_telnetopt)
2945 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2946 if (size > 0)
2947 qemu_chr_be_write(chr, buf, size);
2950 return TRUE;
2953 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2955 TCPCharDriver *s = chr->opaque;
2956 int size;
2958 if (!s->connected) {
2959 return 0;
2962 size = tcp_chr_recv(chr, (void *) buf, len);
2963 if (size == 0) {
2964 /* connection closed */
2965 tcp_chr_disconnect(chr);
2968 return size;
2971 #ifndef _WIN32
2972 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2974 CharDriverState *chr = qemu_chr_open_fd(eventfd, eventfd, NULL, NULL);
2976 if (chr) {
2977 chr->avail_connections = 1;
2980 return chr;
2982 #endif
2984 static void tcp_chr_connect(void *opaque)
2986 CharDriverState *chr = opaque;
2987 TCPCharDriver *s = chr->opaque;
2988 struct sockaddr_storage ss, ps;
2989 socklen_t ss_len = sizeof(ss), ps_len = sizeof(ps);
2991 memset(&ss, 0, ss_len);
2992 if (getsockname(s->fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2993 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
2994 "Error in getsockname: %s\n", strerror(errno));
2995 } else if (getpeername(s->fd, (struct sockaddr *) &ps, &ps_len) != 0) {
2996 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
2997 "Error in getpeername: %s\n", strerror(errno));
2998 } else {
2999 sockaddr_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
3000 &ss, ss_len, &ps, ps_len,
3001 s->is_listen, s->is_telnet);
3004 s->connected = 1;
3005 if (s->chan) {
3006 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
3007 tcp_chr_read, chr);
3009 qemu_chr_be_generic_open(chr);
3012 static void tcp_chr_update_read_handler(CharDriverState *chr)
3014 TCPCharDriver *s = chr->opaque;
3016 remove_fd_in_watch(chr);
3017 if (s->chan) {
3018 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
3019 tcp_chr_read, chr);
3023 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3024 static void tcp_chr_telnet_init(int fd)
3026 char buf[3];
3027 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3028 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3029 send(fd, (char *)buf, 3, 0);
3030 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3031 send(fd, (char *)buf, 3, 0);
3032 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3033 send(fd, (char *)buf, 3, 0);
3034 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3035 send(fd, (char *)buf, 3, 0);
3038 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3040 TCPCharDriver *s = chr->opaque;
3041 if (s->fd != -1)
3042 return -1;
3044 qemu_set_nonblock(fd);
3045 if (s->do_nodelay)
3046 socket_set_nodelay(fd);
3047 s->fd = fd;
3048 s->chan = io_channel_from_socket(fd);
3049 if (s->listen_tag) {
3050 g_source_remove(s->listen_tag);
3051 s->listen_tag = 0;
3053 tcp_chr_connect(chr);
3055 return 0;
3058 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
3060 CharDriverState *chr = opaque;
3061 TCPCharDriver *s = chr->opaque;
3062 struct sockaddr_in saddr;
3063 #ifndef _WIN32
3064 struct sockaddr_un uaddr;
3065 #endif
3066 struct sockaddr *addr;
3067 socklen_t len;
3068 int fd;
3070 for(;;) {
3071 #ifndef _WIN32
3072 if (s->is_unix) {
3073 len = sizeof(uaddr);
3074 addr = (struct sockaddr *)&uaddr;
3075 } else
3076 #endif
3078 len = sizeof(saddr);
3079 addr = (struct sockaddr *)&saddr;
3081 fd = qemu_accept(s->listen_fd, addr, &len);
3082 if (fd < 0 && errno != EINTR) {
3083 s->listen_tag = 0;
3084 return FALSE;
3085 } else if (fd >= 0) {
3086 if (s->do_telnetopt)
3087 tcp_chr_telnet_init(fd);
3088 break;
3091 if (tcp_chr_add_client(chr, fd) < 0)
3092 close(fd);
3094 return TRUE;
3097 static void tcp_chr_close(CharDriverState *chr)
3099 TCPCharDriver *s = chr->opaque;
3100 int i;
3102 if (s->reconnect_timer) {
3103 g_source_remove(s->reconnect_timer);
3104 s->reconnect_timer = 0;
3106 qapi_free_SocketAddress(s->addr);
3107 if (s->fd >= 0) {
3108 remove_fd_in_watch(chr);
3109 if (s->chan) {
3110 g_io_channel_unref(s->chan);
3112 closesocket(s->fd);
3114 if (s->listen_fd >= 0) {
3115 if (s->listen_tag) {
3116 g_source_remove(s->listen_tag);
3117 s->listen_tag = 0;
3119 if (s->listen_chan) {
3120 g_io_channel_unref(s->listen_chan);
3122 closesocket(s->listen_fd);
3124 if (s->read_msgfds_num) {
3125 for (i = 0; i < s->read_msgfds_num; i++) {
3126 close(s->read_msgfds[i]);
3128 g_free(s->read_msgfds);
3130 if (s->write_msgfds_num) {
3131 g_free(s->write_msgfds);
3133 g_free(s);
3134 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3137 static void qemu_chr_finish_socket_connection(CharDriverState *chr, int fd)
3139 TCPCharDriver *s = chr->opaque;
3141 if (s->is_listen) {
3142 s->listen_fd = fd;
3143 s->listen_chan = io_channel_from_socket(s->listen_fd);
3144 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
3145 tcp_chr_accept, chr);
3146 } else {
3147 s->connected = 1;
3148 s->fd = fd;
3149 socket_set_nodelay(fd);
3150 s->chan = io_channel_from_socket(s->fd);
3151 tcp_chr_connect(chr);
3155 static void qemu_chr_socket_connected(int fd, Error *err, void *opaque)
3157 CharDriverState *chr = opaque;
3158 TCPCharDriver *s = chr->opaque;
3160 if (fd < 0) {
3161 check_report_connect_error(chr, err);
3162 return;
3165 s->connect_err_reported = false;
3166 qemu_chr_finish_socket_connection(chr, fd);
3169 static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp)
3171 TCPCharDriver *s = chr->opaque;
3172 int fd;
3174 if (s->is_listen) {
3175 fd = socket_listen(s->addr, errp);
3176 } else if (s->reconnect_time) {
3177 fd = socket_connect(s->addr, errp, qemu_chr_socket_connected, chr);
3178 return fd >= 0;
3179 } else {
3180 fd = socket_connect(s->addr, errp, NULL, NULL);
3182 if (fd < 0) {
3183 return false;
3186 qemu_chr_finish_socket_connection(chr, fd);
3187 return true;
3190 /*********************************************************/
3191 /* Ring buffer chardev */
3193 typedef struct {
3194 size_t size;
3195 size_t prod;
3196 size_t cons;
3197 uint8_t *cbuf;
3198 } RingBufCharDriver;
3200 static size_t ringbuf_count(const CharDriverState *chr)
3202 const RingBufCharDriver *d = chr->opaque;
3204 return d->prod - d->cons;
3207 /* Called with chr_write_lock held. */
3208 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3210 RingBufCharDriver *d = chr->opaque;
3211 int i;
3213 if (!buf || (len < 0)) {
3214 return -1;
3217 for (i = 0; i < len; i++ ) {
3218 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3219 if (d->prod - d->cons > d->size) {
3220 d->cons = d->prod - d->size;
3224 return 0;
3227 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3229 RingBufCharDriver *d = chr->opaque;
3230 int i;
3232 qemu_mutex_lock(&chr->chr_write_lock);
3233 for (i = 0; i < len && d->cons != d->prod; i++) {
3234 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3236 qemu_mutex_unlock(&chr->chr_write_lock);
3238 return i;
3241 static void ringbuf_chr_close(struct CharDriverState *chr)
3243 RingBufCharDriver *d = chr->opaque;
3245 g_free(d->cbuf);
3246 g_free(d);
3247 chr->opaque = NULL;
3250 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3251 ChardevBackend *backend,
3252 ChardevReturn *ret,
3253 Error **errp)
3255 ChardevRingbuf *opts = backend->u.ringbuf;
3256 ChardevCommon *common = qapi_ChardevRingbuf_base(backend->u.ringbuf);
3257 CharDriverState *chr;
3258 RingBufCharDriver *d;
3260 chr = qemu_chr_alloc(common, errp);
3261 if (!chr) {
3262 return NULL;
3264 d = g_malloc(sizeof(*d));
3266 d->size = opts->has_size ? opts->size : 65536;
3268 /* The size must be power of 2 */
3269 if (d->size & (d->size - 1)) {
3270 error_setg(errp, "size of ringbuf chardev must be power of two");
3271 goto fail;
3274 d->prod = 0;
3275 d->cons = 0;
3276 d->cbuf = g_malloc0(d->size);
3278 chr->opaque = d;
3279 chr->chr_write = ringbuf_chr_write;
3280 chr->chr_close = ringbuf_chr_close;
3282 return chr;
3284 fail:
3285 g_free(d);
3286 qemu_chr_free_common(chr);
3287 return NULL;
3290 bool chr_is_ringbuf(const CharDriverState *chr)
3292 return chr->chr_write == ringbuf_chr_write;
3295 void qmp_ringbuf_write(const char *device, const char *data,
3296 bool has_format, enum DataFormat format,
3297 Error **errp)
3299 CharDriverState *chr;
3300 const uint8_t *write_data;
3301 int ret;
3302 gsize write_count;
3304 chr = qemu_chr_find(device);
3305 if (!chr) {
3306 error_setg(errp, "Device '%s' not found", device);
3307 return;
3310 if (!chr_is_ringbuf(chr)) {
3311 error_setg(errp,"%s is not a ringbuf device", device);
3312 return;
3315 if (has_format && (format == DATA_FORMAT_BASE64)) {
3316 write_data = qbase64_decode(data, -1,
3317 &write_count,
3318 errp);
3319 if (!write_data) {
3320 return;
3322 } else {
3323 write_data = (uint8_t *)data;
3324 write_count = strlen(data);
3327 ret = ringbuf_chr_write(chr, write_data, write_count);
3329 if (write_data != (uint8_t *)data) {
3330 g_free((void *)write_data);
3333 if (ret < 0) {
3334 error_setg(errp, "Failed to write to device %s", device);
3335 return;
3339 char *qmp_ringbuf_read(const char *device, int64_t size,
3340 bool has_format, enum DataFormat format,
3341 Error **errp)
3343 CharDriverState *chr;
3344 uint8_t *read_data;
3345 size_t count;
3346 char *data;
3348 chr = qemu_chr_find(device);
3349 if (!chr) {
3350 error_setg(errp, "Device '%s' not found", device);
3351 return NULL;
3354 if (!chr_is_ringbuf(chr)) {
3355 error_setg(errp,"%s is not a ringbuf device", device);
3356 return NULL;
3359 if (size <= 0) {
3360 error_setg(errp, "size must be greater than zero");
3361 return NULL;
3364 count = ringbuf_count(chr);
3365 size = size > count ? count : size;
3366 read_data = g_malloc(size + 1);
3368 ringbuf_chr_read(chr, read_data, size);
3370 if (has_format && (format == DATA_FORMAT_BASE64)) {
3371 data = g_base64_encode(read_data, size);
3372 g_free(read_data);
3373 } else {
3375 * FIXME should read only complete, valid UTF-8 characters up
3376 * to @size bytes. Invalid sequences should be replaced by a
3377 * suitable replacement character. Except when (and only
3378 * when) ring buffer lost characters since last read, initial
3379 * continuation characters should be dropped.
3381 read_data[size] = 0;
3382 data = (char *)read_data;
3385 return data;
3388 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3390 char host[65], port[33], width[8], height[8];
3391 int pos;
3392 const char *p;
3393 QemuOpts *opts;
3394 Error *local_err = NULL;
3396 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3397 if (local_err) {
3398 error_report_err(local_err);
3399 return NULL;
3402 if (strstart(filename, "mon:", &p)) {
3403 filename = p;
3404 qemu_opt_set(opts, "mux", "on", &error_abort);
3405 if (strcmp(filename, "stdio") == 0) {
3406 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3407 * but pass it to the guest. Handle this only for compat syntax,
3408 * for -chardev syntax we have special option for this.
3409 * This is what -nographic did, redirecting+muxing serial+monitor
3410 * to stdio causing Ctrl+C to be passed to guest. */
3411 qemu_opt_set(opts, "signal", "off", &error_abort);
3415 if (strcmp(filename, "null") == 0 ||
3416 strcmp(filename, "pty") == 0 ||
3417 strcmp(filename, "msmouse") == 0 ||
3418 strcmp(filename, "braille") == 0 ||
3419 strcmp(filename, "testdev") == 0 ||
3420 strcmp(filename, "stdio") == 0) {
3421 qemu_opt_set(opts, "backend", filename, &error_abort);
3422 return opts;
3424 if (strstart(filename, "vc", &p)) {
3425 qemu_opt_set(opts, "backend", "vc", &error_abort);
3426 if (*p == ':') {
3427 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3428 /* pixels */
3429 qemu_opt_set(opts, "width", width, &error_abort);
3430 qemu_opt_set(opts, "height", height, &error_abort);
3431 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3432 /* chars */
3433 qemu_opt_set(opts, "cols", width, &error_abort);
3434 qemu_opt_set(opts, "rows", height, &error_abort);
3435 } else {
3436 goto fail;
3439 return opts;
3441 if (strcmp(filename, "con:") == 0) {
3442 qemu_opt_set(opts, "backend", "console", &error_abort);
3443 return opts;
3445 if (strstart(filename, "COM", NULL)) {
3446 qemu_opt_set(opts, "backend", "serial", &error_abort);
3447 qemu_opt_set(opts, "path", filename, &error_abort);
3448 return opts;
3450 if (strstart(filename, "file:", &p)) {
3451 qemu_opt_set(opts, "backend", "file", &error_abort);
3452 qemu_opt_set(opts, "path", p, &error_abort);
3453 return opts;
3455 if (strstart(filename, "pipe:", &p)) {
3456 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3457 qemu_opt_set(opts, "path", p, &error_abort);
3458 return opts;
3460 if (strstart(filename, "tcp:", &p) ||
3461 strstart(filename, "telnet:", &p)) {
3462 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3463 host[0] = 0;
3464 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3465 goto fail;
3467 qemu_opt_set(opts, "backend", "socket", &error_abort);
3468 qemu_opt_set(opts, "host", host, &error_abort);
3469 qemu_opt_set(opts, "port", port, &error_abort);
3470 if (p[pos] == ',') {
3471 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3472 if (local_err) {
3473 error_report_err(local_err);
3474 goto fail;
3477 if (strstart(filename, "telnet:", &p))
3478 qemu_opt_set(opts, "telnet", "on", &error_abort);
3479 return opts;
3481 if (strstart(filename, "udp:", &p)) {
3482 qemu_opt_set(opts, "backend", "udp", &error_abort);
3483 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3484 host[0] = 0;
3485 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3486 goto fail;
3489 qemu_opt_set(opts, "host", host, &error_abort);
3490 qemu_opt_set(opts, "port", port, &error_abort);
3491 if (p[pos] == '@') {
3492 p += pos + 1;
3493 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3494 host[0] = 0;
3495 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3496 goto fail;
3499 qemu_opt_set(opts, "localaddr", host, &error_abort);
3500 qemu_opt_set(opts, "localport", port, &error_abort);
3502 return opts;
3504 if (strstart(filename, "unix:", &p)) {
3505 qemu_opt_set(opts, "backend", "socket", &error_abort);
3506 qemu_opts_do_parse(opts, p, "path", &local_err);
3507 if (local_err) {
3508 error_report_err(local_err);
3509 goto fail;
3511 return opts;
3513 if (strstart(filename, "/dev/parport", NULL) ||
3514 strstart(filename, "/dev/ppi", NULL)) {
3515 qemu_opt_set(opts, "backend", "parport", &error_abort);
3516 qemu_opt_set(opts, "path", filename, &error_abort);
3517 return opts;
3519 if (strstart(filename, "/dev/", NULL)) {
3520 qemu_opt_set(opts, "backend", "tty", &error_abort);
3521 qemu_opt_set(opts, "path", filename, &error_abort);
3522 return opts;
3525 fail:
3526 qemu_opts_del(opts);
3527 return NULL;
3530 static void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3532 const char *logfile = qemu_opt_get(opts, "logfile");
3534 backend->has_logfile = logfile != NULL;
3535 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3537 backend->has_logappend = true;
3538 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3542 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3543 Error **errp)
3545 const char *path = qemu_opt_get(opts, "path");
3547 if (path == NULL) {
3548 error_setg(errp, "chardev: file: no filename given");
3549 return;
3551 backend->u.file = g_new0(ChardevFile, 1);
3552 qemu_chr_parse_common(opts, qapi_ChardevFile_base(backend->u.file));
3553 backend->u.file->out = g_strdup(path);
3555 backend->u.file->has_append = true;
3556 backend->u.file->append = qemu_opt_get_bool(opts, "append", false);
3559 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3560 Error **errp)
3562 backend->u.stdio = g_new0(ChardevStdio, 1);
3563 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(backend->u.stdio));
3564 backend->u.stdio->has_signal = true;
3565 backend->u.stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3568 #ifdef HAVE_CHARDEV_SERIAL
3569 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3570 Error **errp)
3572 const char *device = qemu_opt_get(opts, "path");
3574 if (device == NULL) {
3575 error_setg(errp, "chardev: serial/tty: no device path given");
3576 return;
3578 backend->u.serial = g_new0(ChardevHostdev, 1);
3579 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.serial));
3580 backend->u.serial->device = g_strdup(device);
3582 #endif
3584 #ifdef HAVE_CHARDEV_PARPORT
3585 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3586 Error **errp)
3588 const char *device = qemu_opt_get(opts, "path");
3590 if (device == NULL) {
3591 error_setg(errp, "chardev: parallel: no device path given");
3592 return;
3594 backend->u.parallel = g_new0(ChardevHostdev, 1);
3595 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.parallel));
3596 backend->u.parallel->device = g_strdup(device);
3598 #endif
3600 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3601 Error **errp)
3603 const char *device = qemu_opt_get(opts, "path");
3605 if (device == NULL) {
3606 error_setg(errp, "chardev: pipe: no device path given");
3607 return;
3609 backend->u.pipe = g_new0(ChardevHostdev, 1);
3610 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(backend->u.pipe));
3611 backend->u.pipe->device = g_strdup(device);
3614 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3615 Error **errp)
3617 int val;
3619 backend->u.ringbuf = g_new0(ChardevRingbuf, 1);
3620 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(backend->u.ringbuf));
3622 val = qemu_opt_get_size(opts, "size", 0);
3623 if (val != 0) {
3624 backend->u.ringbuf->has_size = true;
3625 backend->u.ringbuf->size = val;
3629 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3630 Error **errp)
3632 const char *chardev = qemu_opt_get(opts, "chardev");
3634 if (chardev == NULL) {
3635 error_setg(errp, "chardev: mux: no chardev given");
3636 return;
3638 backend->u.mux = g_new0(ChardevMux, 1);
3639 qemu_chr_parse_common(opts, qapi_ChardevMux_base(backend->u.mux));
3640 backend->u.mux->chardev = g_strdup(chardev);
3643 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3644 Error **errp)
3646 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3647 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3648 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3649 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3650 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3651 const char *path = qemu_opt_get(opts, "path");
3652 const char *host = qemu_opt_get(opts, "host");
3653 const char *port = qemu_opt_get(opts, "port");
3654 SocketAddress *addr;
3656 if (!path) {
3657 if (!host) {
3658 error_setg(errp, "chardev: socket: no host given");
3659 return;
3661 if (!port) {
3662 error_setg(errp, "chardev: socket: no port given");
3663 return;
3667 backend->u.socket = g_new0(ChardevSocket, 1);
3668 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(backend->u.socket));
3670 backend->u.socket->has_nodelay = true;
3671 backend->u.socket->nodelay = do_nodelay;
3672 backend->u.socket->has_server = true;
3673 backend->u.socket->server = is_listen;
3674 backend->u.socket->has_telnet = true;
3675 backend->u.socket->telnet = is_telnet;
3676 backend->u.socket->has_wait = true;
3677 backend->u.socket->wait = is_waitconnect;
3678 backend->u.socket->has_reconnect = true;
3679 backend->u.socket->reconnect = reconnect;
3681 addr = g_new0(SocketAddress, 1);
3682 if (path) {
3683 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3684 addr->u.q_unix = g_new0(UnixSocketAddress, 1);
3685 addr->u.q_unix->path = g_strdup(path);
3686 } else {
3687 addr->type = SOCKET_ADDRESS_KIND_INET;
3688 addr->u.inet = g_new0(InetSocketAddress, 1);
3689 addr->u.inet->host = g_strdup(host);
3690 addr->u.inet->port = g_strdup(port);
3691 addr->u.inet->has_to = qemu_opt_get(opts, "to");
3692 addr->u.inet->to = qemu_opt_get_number(opts, "to", 0);
3693 addr->u.inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3694 addr->u.inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3695 addr->u.inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3696 addr->u.inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3698 backend->u.socket->addr = addr;
3701 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3702 Error **errp)
3704 const char *host = qemu_opt_get(opts, "host");
3705 const char *port = qemu_opt_get(opts, "port");
3706 const char *localaddr = qemu_opt_get(opts, "localaddr");
3707 const char *localport = qemu_opt_get(opts, "localport");
3708 bool has_local = false;
3709 SocketAddress *addr;
3711 if (host == NULL || strlen(host) == 0) {
3712 host = "localhost";
3714 if (port == NULL || strlen(port) == 0) {
3715 error_setg(errp, "chardev: udp: remote port not specified");
3716 return;
3718 if (localport == NULL || strlen(localport) == 0) {
3719 localport = "0";
3720 } else {
3721 has_local = true;
3723 if (localaddr == NULL || strlen(localaddr) == 0) {
3724 localaddr = "";
3725 } else {
3726 has_local = true;
3729 backend->u.udp = g_new0(ChardevUdp, 1);
3730 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(backend->u.udp));
3732 addr = g_new0(SocketAddress, 1);
3733 addr->type = SOCKET_ADDRESS_KIND_INET;
3734 addr->u.inet = g_new0(InetSocketAddress, 1);
3735 addr->u.inet->host = g_strdup(host);
3736 addr->u.inet->port = g_strdup(port);
3737 addr->u.inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3738 addr->u.inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3739 addr->u.inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3740 addr->u.inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3741 backend->u.udp->remote = addr;
3743 if (has_local) {
3744 backend->u.udp->has_local = true;
3745 addr = g_new0(SocketAddress, 1);
3746 addr->type = SOCKET_ADDRESS_KIND_INET;
3747 addr->u.inet = g_new0(InetSocketAddress, 1);
3748 addr->u.inet->host = g_strdup(localaddr);
3749 addr->u.inet->port = g_strdup(localport);
3750 backend->u.udp->local = addr;
3754 typedef struct CharDriver {
3755 const char *name;
3756 ChardevBackendKind kind;
3757 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3758 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3759 ChardevReturn *ret, Error **errp);
3760 } CharDriver;
3762 static GSList *backends;
3764 void register_char_driver(const char *name, ChardevBackendKind kind,
3765 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3766 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3767 ChardevReturn *ret, Error **errp))
3769 CharDriver *s;
3771 s = g_malloc0(sizeof(*s));
3772 s->name = g_strdup(name);
3773 s->kind = kind;
3774 s->parse = parse;
3775 s->create = create;
3777 backends = g_slist_append(backends, s);
3780 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3781 void (*init)(struct CharDriverState *s),
3782 Error **errp)
3784 Error *local_err = NULL;
3785 CharDriver *cd;
3786 CharDriverState *chr;
3787 GSList *i;
3788 ChardevReturn *ret = NULL;
3789 ChardevBackend *backend;
3790 const char *id = qemu_opts_id(opts);
3791 char *bid = NULL;
3793 if (id == NULL) {
3794 error_setg(errp, "chardev: no id specified");
3795 goto err;
3798 if (qemu_opt_get(opts, "backend") == NULL) {
3799 error_setg(errp, "chardev: \"%s\" missing backend",
3800 qemu_opts_id(opts));
3801 goto err;
3803 for (i = backends; i; i = i->next) {
3804 cd = i->data;
3806 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3807 break;
3810 if (i == NULL) {
3811 error_setg(errp, "chardev: backend \"%s\" not found",
3812 qemu_opt_get(opts, "backend"));
3813 goto err;
3816 backend = g_new0(ChardevBackend, 1);
3818 if (qemu_opt_get_bool(opts, "mux", 0)) {
3819 bid = g_strdup_printf("%s-base", id);
3822 chr = NULL;
3823 backend->type = cd->kind;
3824 if (cd->parse) {
3825 cd->parse(opts, backend, &local_err);
3826 if (local_err) {
3827 error_propagate(errp, local_err);
3828 goto qapi_out;
3830 } else {
3831 ChardevCommon *cc = g_new0(ChardevCommon, 1);
3832 qemu_chr_parse_common(opts, cc);
3833 backend->u.data = cc;
3836 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3837 if (!ret) {
3838 goto qapi_out;
3841 if (bid) {
3842 qapi_free_ChardevBackend(backend);
3843 qapi_free_ChardevReturn(ret);
3844 backend = g_new0(ChardevBackend, 1);
3845 backend->u.mux = g_new0(ChardevMux, 1);
3846 backend->type = CHARDEV_BACKEND_KIND_MUX;
3847 backend->u.mux->chardev = g_strdup(bid);
3848 ret = qmp_chardev_add(id, backend, errp);
3849 if (!ret) {
3850 chr = qemu_chr_find(bid);
3851 qemu_chr_delete(chr);
3852 chr = NULL;
3853 goto qapi_out;
3857 chr = qemu_chr_find(id);
3858 chr->opts = opts;
3860 qapi_out:
3861 qapi_free_ChardevBackend(backend);
3862 qapi_free_ChardevReturn(ret);
3863 g_free(bid);
3864 return chr;
3866 err:
3867 qemu_opts_del(opts);
3868 return NULL;
3871 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3873 const char *p;
3874 CharDriverState *chr;
3875 QemuOpts *opts;
3876 Error *err = NULL;
3878 if (strstart(filename, "chardev:", &p)) {
3879 return qemu_chr_find(p);
3882 opts = qemu_chr_parse_compat(label, filename);
3883 if (!opts)
3884 return NULL;
3886 chr = qemu_chr_new_from_opts(opts, init, &err);
3887 if (err) {
3888 error_report_err(err);
3890 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3891 qemu_chr_fe_claim_no_fail(chr);
3892 monitor_init(chr, MONITOR_USE_READLINE);
3894 return chr;
3897 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3899 if (chr->chr_set_echo) {
3900 chr->chr_set_echo(chr, echo);
3904 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3906 if (chr->fe_open == fe_open) {
3907 return;
3909 chr->fe_open = fe_open;
3910 if (chr->chr_set_fe_open) {
3911 chr->chr_set_fe_open(chr, fe_open);
3915 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3917 if (chr->chr_fe_event) {
3918 chr->chr_fe_event(chr, event);
3922 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3923 GIOFunc func, void *user_data)
3925 GSource *src;
3926 guint tag;
3928 if (s->chr_add_watch == NULL) {
3929 return -ENOSYS;
3932 src = s->chr_add_watch(s, cond);
3933 if (!src) {
3934 return -EINVAL;
3937 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3938 tag = g_source_attach(src, NULL);
3939 g_source_unref(src);
3941 return tag;
3944 int qemu_chr_fe_claim(CharDriverState *s)
3946 if (s->avail_connections < 1) {
3947 return -1;
3949 s->avail_connections--;
3950 return 0;
3953 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3955 if (qemu_chr_fe_claim(s) != 0) {
3956 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3957 __func__, s->label);
3958 exit(1);
3962 void qemu_chr_fe_release(CharDriverState *s)
3964 s->avail_connections++;
3967 static void qemu_chr_free_common(CharDriverState *chr)
3969 g_free(chr->filename);
3970 g_free(chr->label);
3971 qemu_opts_del(chr->opts);
3972 if (chr->logfd != -1) {
3973 close(chr->logfd);
3975 qemu_mutex_destroy(&chr->chr_write_lock);
3976 g_free(chr);
3979 void qemu_chr_free(CharDriverState *chr)
3981 if (chr->chr_close) {
3982 chr->chr_close(chr);
3984 qemu_chr_free_common(chr);
3987 void qemu_chr_delete(CharDriverState *chr)
3989 QTAILQ_REMOVE(&chardevs, chr, next);
3990 qemu_chr_free(chr);
3993 ChardevInfoList *qmp_query_chardev(Error **errp)
3995 ChardevInfoList *chr_list = NULL;
3996 CharDriverState *chr;
3998 QTAILQ_FOREACH(chr, &chardevs, next) {
3999 ChardevInfoList *info = g_malloc0(sizeof(*info));
4000 info->value = g_malloc0(sizeof(*info->value));
4001 info->value->label = g_strdup(chr->label);
4002 info->value->filename = g_strdup(chr->filename);
4003 info->value->frontend_open = chr->fe_open;
4005 info->next = chr_list;
4006 chr_list = info;
4009 return chr_list;
4012 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4014 ChardevBackendInfoList *backend_list = NULL;
4015 CharDriver *c = NULL;
4016 GSList *i = NULL;
4018 for (i = backends; i; i = i->next) {
4019 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4020 c = i->data;
4021 info->value = g_malloc0(sizeof(*info->value));
4022 info->value->name = g_strdup(c->name);
4024 info->next = backend_list;
4025 backend_list = info;
4028 return backend_list;
4031 CharDriverState *qemu_chr_find(const char *name)
4033 CharDriverState *chr;
4035 QTAILQ_FOREACH(chr, &chardevs, next) {
4036 if (strcmp(chr->label, name) != 0)
4037 continue;
4038 return chr;
4040 return NULL;
4043 /* Get a character (serial) device interface. */
4044 CharDriverState *qemu_char_get_next_serial(void)
4046 static int next_serial;
4047 CharDriverState *chr;
4049 /* FIXME: This function needs to go away: use chardev properties! */
4051 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
4052 chr = serial_hds[next_serial++];
4053 qemu_chr_fe_claim_no_fail(chr);
4054 return chr;
4056 return NULL;
4059 QemuOptsList qemu_chardev_opts = {
4060 .name = "chardev",
4061 .implied_opt_name = "backend",
4062 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4063 .desc = {
4065 .name = "backend",
4066 .type = QEMU_OPT_STRING,
4068 .name = "path",
4069 .type = QEMU_OPT_STRING,
4071 .name = "host",
4072 .type = QEMU_OPT_STRING,
4074 .name = "port",
4075 .type = QEMU_OPT_STRING,
4077 .name = "localaddr",
4078 .type = QEMU_OPT_STRING,
4080 .name = "localport",
4081 .type = QEMU_OPT_STRING,
4083 .name = "to",
4084 .type = QEMU_OPT_NUMBER,
4086 .name = "ipv4",
4087 .type = QEMU_OPT_BOOL,
4089 .name = "ipv6",
4090 .type = QEMU_OPT_BOOL,
4092 .name = "wait",
4093 .type = QEMU_OPT_BOOL,
4095 .name = "server",
4096 .type = QEMU_OPT_BOOL,
4098 .name = "delay",
4099 .type = QEMU_OPT_BOOL,
4101 .name = "reconnect",
4102 .type = QEMU_OPT_NUMBER,
4104 .name = "telnet",
4105 .type = QEMU_OPT_BOOL,
4107 .name = "width",
4108 .type = QEMU_OPT_NUMBER,
4110 .name = "height",
4111 .type = QEMU_OPT_NUMBER,
4113 .name = "cols",
4114 .type = QEMU_OPT_NUMBER,
4116 .name = "rows",
4117 .type = QEMU_OPT_NUMBER,
4119 .name = "mux",
4120 .type = QEMU_OPT_BOOL,
4122 .name = "signal",
4123 .type = QEMU_OPT_BOOL,
4125 .name = "name",
4126 .type = QEMU_OPT_STRING,
4128 .name = "debug",
4129 .type = QEMU_OPT_NUMBER,
4131 .name = "size",
4132 .type = QEMU_OPT_SIZE,
4134 .name = "chardev",
4135 .type = QEMU_OPT_STRING,
4137 .name = "append",
4138 .type = QEMU_OPT_BOOL,
4140 .name = "logfile",
4141 .type = QEMU_OPT_STRING,
4143 .name = "logappend",
4144 .type = QEMU_OPT_BOOL,
4146 { /* end of list */ }
4150 #ifdef _WIN32
4152 static CharDriverState *qmp_chardev_open_file(const char *id,
4153 ChardevBackend *backend,
4154 ChardevReturn *ret,
4155 Error **errp)
4157 ChardevFile *file = backend->u.file;
4158 ChardevCommon *common = qapi_ChardevFile_base(backend->u.file);
4159 HANDLE out;
4161 if (file->has_in) {
4162 error_setg(errp, "input file not supported");
4163 return NULL;
4166 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
4167 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
4168 if (out == INVALID_HANDLE_VALUE) {
4169 error_setg(errp, "open %s failed", file->out);
4170 return NULL;
4172 return qemu_chr_open_win_file(out, common, errp);
4175 static CharDriverState *qmp_chardev_open_serial(const char *id,
4176 ChardevBackend *backend,
4177 ChardevReturn *ret,
4178 Error **errp)
4180 ChardevHostdev *serial = backend->u.serial;
4181 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.serial);
4182 return qemu_chr_open_win_path(serial->device, common, errp);
4185 #else /* WIN32 */
4187 static int qmp_chardev_open_file_source(char *src, int flags,
4188 Error **errp)
4190 int fd = -1;
4192 TFR(fd = qemu_open(src, flags, 0666));
4193 if (fd == -1) {
4194 error_setg_file_open(errp, errno, src);
4196 return fd;
4199 static CharDriverState *qmp_chardev_open_file(const char *id,
4200 ChardevBackend *backend,
4201 ChardevReturn *ret,
4202 Error **errp)
4204 ChardevFile *file = backend->u.file;
4205 ChardevCommon *common = qapi_ChardevFile_base(backend->u.file);
4206 int flags, in = -1, out;
4208 flags = O_WRONLY | O_CREAT | O_BINARY;
4209 if (file->has_append && file->append) {
4210 flags |= O_APPEND;
4211 } else {
4212 flags |= O_TRUNC;
4215 out = qmp_chardev_open_file_source(file->out, flags, errp);
4216 if (out < 0) {
4217 return NULL;
4220 if (file->has_in) {
4221 flags = O_RDONLY;
4222 in = qmp_chardev_open_file_source(file->in, flags, errp);
4223 if (in < 0) {
4224 qemu_close(out);
4225 return NULL;
4229 return qemu_chr_open_fd(in, out, common, errp);
4232 #ifdef HAVE_CHARDEV_SERIAL
4233 static CharDriverState *qmp_chardev_open_serial(const char *id,
4234 ChardevBackend *backend,
4235 ChardevReturn *ret,
4236 Error **errp)
4238 ChardevHostdev *serial = backend->u.serial;
4239 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.serial);
4240 int fd;
4242 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4243 if (fd < 0) {
4244 return NULL;
4246 qemu_set_nonblock(fd);
4247 return qemu_chr_open_tty_fd(fd, common, errp);
4249 #endif
4251 #ifdef HAVE_CHARDEV_PARPORT
4252 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4253 ChardevBackend *backend,
4254 ChardevReturn *ret,
4255 Error **errp)
4257 ChardevHostdev *parallel = backend->u.parallel;
4258 ChardevCommon *common = qapi_ChardevHostdev_base(backend->u.parallel);
4259 int fd;
4261 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4262 if (fd < 0) {
4263 return NULL;
4265 return qemu_chr_open_pp_fd(fd, common, errp);
4267 #endif
4269 #endif /* WIN32 */
4271 static void socket_try_connect(CharDriverState *chr)
4273 Error *err = NULL;
4275 if (!qemu_chr_open_socket_fd(chr, &err)) {
4276 check_report_connect_error(chr, err);
4280 static gboolean socket_reconnect_timeout(gpointer opaque)
4282 CharDriverState *chr = opaque;
4283 TCPCharDriver *s = chr->opaque;
4285 s->reconnect_timer = 0;
4287 if (chr->be_open) {
4288 return false;
4291 socket_try_connect(chr);
4293 return false;
4296 static CharDriverState *qmp_chardev_open_socket(const char *id,
4297 ChardevBackend *backend,
4298 ChardevReturn *ret,
4299 Error **errp)
4301 CharDriverState *chr;
4302 TCPCharDriver *s;
4303 ChardevSocket *sock = backend->u.socket;
4304 SocketAddress *addr = sock->addr;
4305 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4306 bool is_listen = sock->has_server ? sock->server : true;
4307 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4308 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4309 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4310 ChardevCommon *common = qapi_ChardevSocket_base(backend->u.socket);
4312 chr = qemu_chr_alloc(common, errp);
4313 if (!chr) {
4314 return NULL;
4316 s = g_new0(TCPCharDriver, 1);
4318 s->fd = -1;
4319 s->listen_fd = -1;
4320 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4321 s->is_listen = is_listen;
4322 s->is_telnet = is_telnet;
4323 s->do_nodelay = do_nodelay;
4324 qapi_copy_SocketAddress(&s->addr, sock->addr);
4326 chr->opaque = s;
4327 chr->chr_write = tcp_chr_write;
4328 chr->chr_sync_read = tcp_chr_sync_read;
4329 chr->chr_close = tcp_chr_close;
4330 chr->get_msgfds = tcp_get_msgfds;
4331 chr->set_msgfds = tcp_set_msgfds;
4332 chr->chr_add_client = tcp_chr_add_client;
4333 chr->chr_add_watch = tcp_chr_add_watch;
4334 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4335 /* be isn't opened until we get a connection */
4336 chr->explicit_be_open = true;
4338 chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
4339 SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, "disconnected:",
4340 addr, is_listen, is_telnet);
4342 if (is_listen) {
4343 if (is_telnet) {
4344 s->do_telnetopt = 1;
4346 } else if (reconnect > 0) {
4347 s->reconnect_time = reconnect;
4350 if (s->reconnect_time) {
4351 socket_try_connect(chr);
4352 } else if (!qemu_chr_open_socket_fd(chr, errp)) {
4353 g_free(s);
4354 qemu_chr_free_common(chr);
4355 return NULL;
4358 if (is_listen && is_waitconnect) {
4359 fprintf(stderr, "QEMU waiting for connection on: %s\n",
4360 chr->filename);
4361 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
4362 qemu_set_nonblock(s->listen_fd);
4365 return chr;
4368 static CharDriverState *qmp_chardev_open_udp(const char *id,
4369 ChardevBackend *backend,
4370 ChardevReturn *ret,
4371 Error **errp)
4373 ChardevUdp *udp = backend->u.udp;
4374 ChardevCommon *common = qapi_ChardevUdp_base(backend->u.udp);
4375 int fd;
4377 fd = socket_dgram(udp->remote, udp->local, errp);
4378 if (fd < 0) {
4379 return NULL;
4381 return qemu_chr_open_udp_fd(fd, common, errp);
4384 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4385 Error **errp)
4387 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4388 CharDriverState *chr = NULL;
4389 Error *local_err = NULL;
4390 GSList *i;
4391 CharDriver *cd;
4393 chr = qemu_chr_find(id);
4394 if (chr) {
4395 error_setg(errp, "Chardev '%s' already exists", id);
4396 g_free(ret);
4397 return NULL;
4400 for (i = backends; i; i = i->next) {
4401 cd = i->data;
4403 if (cd->kind == backend->type) {
4404 chr = cd->create(id, backend, ret, &local_err);
4405 if (local_err) {
4406 error_propagate(errp, local_err);
4407 goto out_error;
4409 break;
4413 if (chr == NULL) {
4414 assert(!i);
4415 error_setg(errp, "chardev backend not available");
4416 goto out_error;
4419 chr->label = g_strdup(id);
4420 chr->avail_connections =
4421 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4422 if (!chr->filename) {
4423 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4425 if (!chr->explicit_be_open) {
4426 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4428 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4429 return ret;
4431 out_error:
4432 g_free(ret);
4433 return NULL;
4436 void qmp_chardev_remove(const char *id, Error **errp)
4438 CharDriverState *chr;
4440 chr = qemu_chr_find(id);
4441 if (chr == NULL) {
4442 error_setg(errp, "Chardev '%s' not found", id);
4443 return;
4445 if (chr->chr_can_read || chr->chr_read ||
4446 chr->chr_event || chr->handler_opaque) {
4447 error_setg(errp, "Chardev '%s' is busy", id);
4448 return;
4450 qemu_chr_delete(chr);
4453 static void register_types(void)
4455 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4456 qemu_chr_open_null);
4457 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4458 qemu_chr_parse_socket, qmp_chardev_open_socket);
4459 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4460 qmp_chardev_open_udp);
4461 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4462 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4463 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4464 qemu_chr_parse_file_out, qmp_chardev_open_file);
4465 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4466 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4467 #if defined HAVE_CHARDEV_SERIAL
4468 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4469 qemu_chr_parse_serial, qmp_chardev_open_serial);
4470 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4471 qemu_chr_parse_serial, qmp_chardev_open_serial);
4472 #endif
4473 #ifdef HAVE_CHARDEV_PARPORT
4474 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4475 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4476 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4477 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4478 #endif
4479 #ifdef HAVE_CHARDEV_PTY
4480 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4481 qemu_chr_open_pty);
4482 #endif
4483 #ifdef _WIN32
4484 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4485 qemu_chr_open_win_con);
4486 #endif
4487 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4488 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4489 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4490 qemu_chr_open_mux);
4491 /* Bug-compatibility: */
4492 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4493 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4494 /* this must be done after machine init, since we register FEs with muxes
4495 * as part of realize functions like serial_isa_realizefn when -nographic
4496 * is specified
4498 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4501 type_init(register_types);