quorum: Emit QUORUM_REPORT_BAD for reads in fifo mode
[qemu/ar7.git] / qemu-char.c
blobbfcf80dd10918529760136de0350a6610d88d95d
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
25 #include "qemu-common.h"
26 #include "monitor/monitor.h"
27 #include "sysemu/sysemu.h"
28 #include "sysemu/block-backend.h"
29 #include "qemu/error-report.h"
30 #include "qemu/timer.h"
31 #include "sysemu/char.h"
32 #include "hw/usb.h"
33 #include "qmp-commands.h"
34 #include "qapi/qmp-input-visitor.h"
35 #include "qapi/qmp-output-visitor.h"
36 #include "qapi-visit.h"
37 #include "qemu/base64.h"
38 #include "io/channel-socket.h"
39 #include "io/channel-file.h"
40 #include "io/channel-tls.h"
41 #include "sysemu/replay.h"
43 #include <zlib.h>
45 #ifndef _WIN32
46 #include <sys/times.h>
47 #include <sys/wait.h>
48 #include <termios.h>
49 #include <sys/mman.h>
50 #include <sys/ioctl.h>
51 #include <sys/resource.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
54 #include <net/if.h>
55 #include <arpa/inet.h>
56 #include <netdb.h>
57 #include <sys/select.h>
58 #ifdef CONFIG_BSD
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/ethernet.h>
73 #include <sys/sockio.h>
74 #include <netinet/arp.h>
75 #include <netinet/in.h>
76 #include <netinet/in_systm.h>
77 #include <netinet/ip.h>
78 #include <netinet/ip_icmp.h> // must come after ip.h
79 #include <netinet/udp.h>
80 #include <netinet/tcp.h>
81 #endif
82 #endif
83 #endif
85 #include "qemu/sockets.h"
86 #include "ui/qemu-spice.h"
88 #define READ_BUF_LEN 4096
89 #define READ_RETRIES 10
90 #define TCP_MAX_FDS 16
92 /***********************************************************/
93 /* Socket address helpers */
95 static char *SocketAddress_to_str(const char *prefix, SocketAddress *addr,
96 bool is_listen, bool is_telnet)
98 switch (addr->type) {
99 case SOCKET_ADDRESS_KIND_INET:
100 return g_strdup_printf("%s%s:%s:%s%s", prefix,
101 is_telnet ? "telnet" : "tcp", addr->u.inet->host,
102 addr->u.inet->port, is_listen ? ",server" : "");
103 break;
104 case SOCKET_ADDRESS_KIND_UNIX:
105 return g_strdup_printf("%sunix:%s%s", prefix,
106 addr->u.q_unix->path,
107 is_listen ? ",server" : "");
108 break;
109 case SOCKET_ADDRESS_KIND_FD:
110 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd->str,
111 is_listen ? ",server" : "");
112 break;
113 default:
114 abort();
118 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
119 struct sockaddr_storage *ps, socklen_t ps_len,
120 bool is_listen, bool is_telnet)
122 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
123 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
124 const char *left = "", *right = "";
126 switch (ss->ss_family) {
127 #ifndef _WIN32
128 case AF_UNIX:
129 return g_strdup_printf("unix:%s%s",
130 ((struct sockaddr_un *)(ss))->sun_path,
131 is_listen ? ",server" : "");
132 #endif
133 case AF_INET6:
134 left = "[";
135 right = "]";
136 /* fall through */
137 case AF_INET:
138 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
139 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
140 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
141 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
142 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
143 is_telnet ? "telnet" : "tcp",
144 left, shost, right, sserv,
145 is_listen ? ",server" : "",
146 left, phost, right, pserv);
148 default:
149 return g_strdup_printf("unknown");
153 /***********************************************************/
154 /* character device */
156 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
157 QTAILQ_HEAD_INITIALIZER(chardevs);
159 static void qemu_chr_free_common(CharDriverState *chr);
161 CharDriverState *qemu_chr_alloc(ChardevCommon *backend, Error **errp)
163 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
164 qemu_mutex_init(&chr->chr_write_lock);
166 if (backend->has_logfile) {
167 int flags = O_WRONLY | O_CREAT;
168 if (backend->has_logappend &&
169 backend->logappend) {
170 flags |= O_APPEND;
171 } else {
172 flags |= O_TRUNC;
174 chr->logfd = qemu_open(backend->logfile, flags, 0666);
175 if (chr->logfd < 0) {
176 error_setg_errno(errp, errno,
177 "Unable to open logfile %s",
178 backend->logfile);
179 g_free(chr);
180 return NULL;
182 } else {
183 chr->logfd = -1;
186 return chr;
189 void qemu_chr_be_event(CharDriverState *s, int event)
191 /* Keep track if the char device is open */
192 switch (event) {
193 case CHR_EVENT_OPENED:
194 s->be_open = 1;
195 break;
196 case CHR_EVENT_CLOSED:
197 s->be_open = 0;
198 break;
201 if (!s->chr_event)
202 return;
203 s->chr_event(s->handler_opaque, event);
206 void qemu_chr_be_generic_open(CharDriverState *s)
208 qemu_chr_be_event(s, CHR_EVENT_OPENED);
212 /* Not reporting errors from writing to logfile, as logs are
213 * defined to be "best effort" only */
214 static void qemu_chr_fe_write_log(CharDriverState *s,
215 const uint8_t *buf, size_t len)
217 size_t done = 0;
218 ssize_t ret;
220 if (s->logfd < 0) {
221 return;
224 while (done < len) {
225 do {
226 ret = write(s->logfd, buf + done, len - done);
227 if (ret == -1 && errno == EAGAIN) {
228 g_usleep(100);
230 } while (ret == -1 && errno == EAGAIN);
232 if (ret <= 0) {
233 return;
235 done += ret;
239 static int qemu_chr_fe_write_buffer(CharDriverState *s, const uint8_t *buf, int len, int *offset)
241 int res = 0;
242 *offset = 0;
244 qemu_mutex_lock(&s->chr_write_lock);
245 while (*offset < len) {
246 do {
247 res = s->chr_write(s, buf + *offset, len - *offset);
248 if (res == -1 && errno == EAGAIN) {
249 g_usleep(100);
251 } while (res == -1 && errno == EAGAIN);
253 if (res <= 0) {
254 break;
257 *offset += res;
259 if (*offset > 0) {
260 qemu_chr_fe_write_log(s, buf, *offset);
262 qemu_mutex_unlock(&s->chr_write_lock);
264 return res;
267 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
269 int ret;
271 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
272 int offset;
273 replay_char_write_event_load(&ret, &offset);
274 assert(offset <= len);
275 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
276 return ret;
279 qemu_mutex_lock(&s->chr_write_lock);
280 ret = s->chr_write(s, buf, len);
282 if (ret > 0) {
283 qemu_chr_fe_write_log(s, buf, ret);
286 qemu_mutex_unlock(&s->chr_write_lock);
288 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
289 replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
292 return ret;
295 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
297 int offset;
298 int res;
300 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
301 replay_char_write_event_load(&res, &offset);
302 assert(offset <= len);
303 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
304 return res;
307 res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
309 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
310 replay_char_write_event_save(res, offset);
313 if (res < 0) {
314 return res;
316 return offset;
319 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
321 int offset = 0, counter = 10;
322 int res;
324 if (!s->chr_sync_read) {
325 return 0;
328 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
329 return replay_char_read_all_load(buf);
332 while (offset < len) {
333 do {
334 res = s->chr_sync_read(s, buf + offset, len - offset);
335 if (res == -1 && errno == EAGAIN) {
336 g_usleep(100);
338 } while (res == -1 && errno == EAGAIN);
340 if (res == 0) {
341 break;
344 if (res < 0) {
345 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
346 replay_char_read_all_save_error(res);
348 return res;
351 offset += res;
353 if (!counter--) {
354 break;
358 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
359 replay_char_read_all_save_buf(buf, offset);
361 return offset;
364 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
366 int res;
367 if (!s->chr_ioctl || s->replay) {
368 res = -ENOTSUP;
369 } else {
370 res = s->chr_ioctl(s, cmd, arg);
373 return res;
376 int qemu_chr_be_can_write(CharDriverState *s)
378 if (!s->chr_can_read)
379 return 0;
380 return s->chr_can_read(s->handler_opaque);
383 void qemu_chr_be_write_impl(CharDriverState *s, uint8_t *buf, int len)
385 if (s->chr_read) {
386 s->chr_read(s->handler_opaque, buf, len);
390 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
392 if (s->replay) {
393 if (replay_mode == REPLAY_MODE_PLAY) {
394 return;
396 replay_chr_be_write(s, buf, len);
397 } else {
398 qemu_chr_be_write_impl(s, buf, len);
402 int qemu_chr_fe_get_msgfd(CharDriverState *s)
404 int fd;
405 int res = (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
406 if (s->replay) {
407 fprintf(stderr,
408 "Replay: get msgfd is not supported for serial devices yet\n");
409 exit(1);
411 return res;
414 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
416 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
419 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
421 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
424 int qemu_chr_add_client(CharDriverState *s, int fd)
426 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
429 void qemu_chr_accept_input(CharDriverState *s)
431 if (s->chr_accept_input)
432 s->chr_accept_input(s);
433 qemu_notify_event();
436 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
438 char buf[READ_BUF_LEN];
439 va_list ap;
440 va_start(ap, fmt);
441 vsnprintf(buf, sizeof(buf), fmt, ap);
442 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
443 va_end(ap);
446 static void remove_fd_in_watch(CharDriverState *chr);
448 void qemu_chr_add_handlers(CharDriverState *s,
449 IOCanReadHandler *fd_can_read,
450 IOReadHandler *fd_read,
451 IOEventHandler *fd_event,
452 void *opaque)
454 int fe_open;
456 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
457 fe_open = 0;
458 remove_fd_in_watch(s);
459 } else {
460 fe_open = 1;
462 s->chr_can_read = fd_can_read;
463 s->chr_read = fd_read;
464 s->chr_event = fd_event;
465 s->handler_opaque = opaque;
466 if (fe_open && s->chr_update_read_handler)
467 s->chr_update_read_handler(s);
469 if (!s->explicit_fe_open) {
470 qemu_chr_fe_set_open(s, fe_open);
473 /* We're connecting to an already opened device, so let's make sure we
474 also get the open event */
475 if (fe_open && s->be_open) {
476 qemu_chr_be_generic_open(s);
480 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
482 return len;
485 static CharDriverState *qemu_chr_open_null(const char *id,
486 ChardevBackend *backend,
487 ChardevReturn *ret,
488 Error **errp)
490 CharDriverState *chr;
491 ChardevCommon *common = backend->u.null;
493 chr = qemu_chr_alloc(common, errp);
494 if (!chr) {
495 return NULL;
497 chr->chr_write = null_chr_write;
498 chr->explicit_be_open = true;
499 return chr;
502 /* MUX driver for serial I/O splitting */
503 #define MAX_MUX 4
504 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
505 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
506 typedef struct {
507 IOCanReadHandler *chr_can_read[MAX_MUX];
508 IOReadHandler *chr_read[MAX_MUX];
509 IOEventHandler *chr_event[MAX_MUX];
510 void *ext_opaque[MAX_MUX];
511 CharDriverState *drv;
512 int focus;
513 int mux_cnt;
514 int term_got_escape;
515 int max_size;
516 /* Intermediate input buffer allows to catch escape sequences even if the
517 currently active device is not accepting any input - but only until it
518 is full as well. */
519 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
520 int prod[MAX_MUX];
521 int cons[MAX_MUX];
522 int timestamps;
524 /* Protected by the CharDriverState chr_write_lock. */
525 int linestart;
526 int64_t timestamps_start;
527 } MuxDriver;
530 /* Called with chr_write_lock held. */
531 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
533 MuxDriver *d = chr->opaque;
534 int ret;
535 if (!d->timestamps) {
536 ret = qemu_chr_fe_write(d->drv, buf, len);
537 } else {
538 int i;
540 ret = 0;
541 for (i = 0; i < len; i++) {
542 if (d->linestart) {
543 char buf1[64];
544 int64_t ti;
545 int secs;
547 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
548 if (d->timestamps_start == -1)
549 d->timestamps_start = ti;
550 ti -= d->timestamps_start;
551 secs = ti / 1000;
552 snprintf(buf1, sizeof(buf1),
553 "[%02d:%02d:%02d.%03d] ",
554 secs / 3600,
555 (secs / 60) % 60,
556 secs % 60,
557 (int)(ti % 1000));
558 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
559 d->linestart = 0;
561 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
562 if (buf[i] == '\n') {
563 d->linestart = 1;
567 return ret;
570 static const char * const mux_help[] = {
571 "% h print this help\n\r",
572 "% x exit emulator\n\r",
573 "% s save disk data back to file (if -snapshot)\n\r",
574 "% t toggle console timestamps\n\r",
575 "% b send break (magic sysrq)\n\r",
576 "% c switch between console and monitor\n\r",
577 "% % sends %\n\r",
578 NULL
581 int term_escape_char = 0x01; /* ctrl-a is used for escape */
582 static void mux_print_help(CharDriverState *chr)
584 int i, j;
585 char ebuf[15] = "Escape-Char";
586 char cbuf[50] = "\n\r";
588 if (term_escape_char > 0 && term_escape_char < 26) {
589 snprintf(cbuf, sizeof(cbuf), "\n\r");
590 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
591 } else {
592 snprintf(cbuf, sizeof(cbuf),
593 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
594 term_escape_char);
596 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
597 for (i = 0; mux_help[i] != NULL; i++) {
598 for (j=0; mux_help[i][j] != '\0'; j++) {
599 if (mux_help[i][j] == '%')
600 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
601 else
602 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
607 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
609 if (d->chr_event[mux_nr])
610 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
613 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
615 if (d->term_got_escape) {
616 d->term_got_escape = 0;
617 if (ch == term_escape_char)
618 goto send_char;
619 switch(ch) {
620 case '?':
621 case 'h':
622 mux_print_help(chr);
623 break;
624 case 'x':
626 const char *term = "QEMU: Terminated\n\r";
627 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
628 exit(0);
629 break;
631 case 's':
632 blk_commit_all();
633 break;
634 case 'b':
635 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
636 break;
637 case 'c':
638 /* Switch to the next registered device */
639 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
640 d->focus++;
641 if (d->focus >= d->mux_cnt)
642 d->focus = 0;
643 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
644 break;
645 case 't':
646 d->timestamps = !d->timestamps;
647 d->timestamps_start = -1;
648 d->linestart = 0;
649 break;
651 } else if (ch == term_escape_char) {
652 d->term_got_escape = 1;
653 } else {
654 send_char:
655 return 1;
657 return 0;
660 static void mux_chr_accept_input(CharDriverState *chr)
662 MuxDriver *d = chr->opaque;
663 int m = d->focus;
665 while (d->prod[m] != d->cons[m] &&
666 d->chr_can_read[m] &&
667 d->chr_can_read[m](d->ext_opaque[m])) {
668 d->chr_read[m](d->ext_opaque[m],
669 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
673 static int mux_chr_can_read(void *opaque)
675 CharDriverState *chr = opaque;
676 MuxDriver *d = chr->opaque;
677 int m = d->focus;
679 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
680 return 1;
681 if (d->chr_can_read[m])
682 return d->chr_can_read[m](d->ext_opaque[m]);
683 return 0;
686 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
688 CharDriverState *chr = opaque;
689 MuxDriver *d = chr->opaque;
690 int m = d->focus;
691 int i;
693 mux_chr_accept_input (opaque);
695 for(i = 0; i < size; i++)
696 if (mux_proc_byte(chr, d, buf[i])) {
697 if (d->prod[m] == d->cons[m] &&
698 d->chr_can_read[m] &&
699 d->chr_can_read[m](d->ext_opaque[m]))
700 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
701 else
702 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
706 static void mux_chr_event(void *opaque, int event)
708 CharDriverState *chr = opaque;
709 MuxDriver *d = chr->opaque;
710 int i;
712 /* Send the event to all registered listeners */
713 for (i = 0; i < d->mux_cnt; i++)
714 mux_chr_send_event(d, i, event);
717 static void mux_chr_update_read_handler(CharDriverState *chr)
719 MuxDriver *d = chr->opaque;
721 if (d->mux_cnt >= MAX_MUX) {
722 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
723 return;
725 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
726 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
727 d->chr_read[d->mux_cnt] = chr->chr_read;
728 d->chr_event[d->mux_cnt] = chr->chr_event;
729 /* Fix up the real driver with mux routines */
730 if (d->mux_cnt == 0) {
731 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
732 mux_chr_event, chr);
734 if (d->focus != -1) {
735 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
737 d->focus = d->mux_cnt;
738 d->mux_cnt++;
739 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
742 static bool muxes_realized;
745 * Called after processing of default and command-line-specified
746 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
747 * to a mux chardev. This is done here to ensure that
748 * output/prompts/banners are only displayed for the FE that has
749 * focus when initial command-line processing/machine init is
750 * completed.
752 * After this point, any new FE attached to any new or existing
753 * mux will receive CHR_EVENT_OPENED notifications for the BE
754 * immediately.
756 static void muxes_realize_done(Notifier *notifier, void *unused)
758 CharDriverState *chr;
760 QTAILQ_FOREACH(chr, &chardevs, next) {
761 if (chr->is_mux) {
762 MuxDriver *d = chr->opaque;
763 int i;
765 /* send OPENED to all already-attached FEs */
766 for (i = 0; i < d->mux_cnt; i++) {
767 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
769 /* mark mux as OPENED so any new FEs will immediately receive
770 * OPENED event
772 qemu_chr_be_generic_open(chr);
775 muxes_realized = true;
778 static Notifier muxes_realize_notify = {
779 .notify = muxes_realize_done,
782 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
784 MuxDriver *d = s->opaque;
785 return d->drv->chr_add_watch(d->drv, cond);
788 static CharDriverState *qemu_chr_open_mux(const char *id,
789 ChardevBackend *backend,
790 ChardevReturn *ret, Error **errp)
792 ChardevMux *mux = backend->u.mux;
793 CharDriverState *chr, *drv;
794 MuxDriver *d;
795 ChardevCommon *common = qapi_ChardevMux_base(mux);
797 drv = qemu_chr_find(mux->chardev);
798 if (drv == NULL) {
799 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
800 return NULL;
803 chr = qemu_chr_alloc(common, errp);
804 if (!chr) {
805 return NULL;
807 d = g_new0(MuxDriver, 1);
809 chr->opaque = d;
810 d->drv = drv;
811 d->focus = -1;
812 chr->chr_write = mux_chr_write;
813 chr->chr_update_read_handler = mux_chr_update_read_handler;
814 chr->chr_accept_input = mux_chr_accept_input;
815 /* Frontend guest-open / -close notification is not support with muxes */
816 chr->chr_set_fe_open = NULL;
817 if (drv->chr_add_watch) {
818 chr->chr_add_watch = mux_chr_add_watch;
820 /* only default to opened state if we've realized the initial
821 * set of muxes
823 chr->explicit_be_open = muxes_realized ? 0 : 1;
824 chr->is_mux = 1;
826 return chr;
830 typedef struct IOWatchPoll
832 GSource parent;
834 QIOChannel *ioc;
835 GSource *src;
837 IOCanReadHandler *fd_can_read;
838 GSourceFunc fd_read;
839 void *opaque;
840 } IOWatchPoll;
842 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
844 return container_of(source, IOWatchPoll, parent);
847 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
849 IOWatchPoll *iwp = io_watch_poll_from_source(source);
850 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
851 bool was_active = iwp->src != NULL;
852 if (was_active == now_active) {
853 return FALSE;
856 if (now_active) {
857 iwp->src = qio_channel_create_watch(
858 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
859 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
860 g_source_attach(iwp->src, NULL);
861 } else {
862 g_source_destroy(iwp->src);
863 g_source_unref(iwp->src);
864 iwp->src = NULL;
866 return FALSE;
869 static gboolean io_watch_poll_check(GSource *source)
871 return FALSE;
874 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
875 gpointer user_data)
877 abort();
880 static void io_watch_poll_finalize(GSource *source)
882 /* Due to a glib bug, removing the last reference to a source
883 * inside a finalize callback causes recursive locking (and a
884 * deadlock). This is not a problem inside other callbacks,
885 * including dispatch callbacks, so we call io_remove_watch_poll
886 * to remove this source. At this point, iwp->src must
887 * be NULL, or we would leak it.
889 * This would be solved much more elegantly by child sources,
890 * but we support older glib versions that do not have them.
892 IOWatchPoll *iwp = io_watch_poll_from_source(source);
893 assert(iwp->src == NULL);
896 static GSourceFuncs io_watch_poll_funcs = {
897 .prepare = io_watch_poll_prepare,
898 .check = io_watch_poll_check,
899 .dispatch = io_watch_poll_dispatch,
900 .finalize = io_watch_poll_finalize,
903 /* Can only be used for read */
904 static guint io_add_watch_poll(QIOChannel *ioc,
905 IOCanReadHandler *fd_can_read,
906 QIOChannelFunc fd_read,
907 gpointer user_data)
909 IOWatchPoll *iwp;
910 int tag;
912 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
913 iwp->fd_can_read = fd_can_read;
914 iwp->opaque = user_data;
915 iwp->ioc = ioc;
916 iwp->fd_read = (GSourceFunc) fd_read;
917 iwp->src = NULL;
919 tag = g_source_attach(&iwp->parent, NULL);
920 g_source_unref(&iwp->parent);
921 return tag;
924 static void io_remove_watch_poll(guint tag)
926 GSource *source;
927 IOWatchPoll *iwp;
929 g_return_if_fail (tag > 0);
931 source = g_main_context_find_source_by_id(NULL, tag);
932 g_return_if_fail (source != NULL);
934 iwp = io_watch_poll_from_source(source);
935 if (iwp->src) {
936 g_source_destroy(iwp->src);
937 g_source_unref(iwp->src);
938 iwp->src = NULL;
940 g_source_destroy(&iwp->parent);
943 static void remove_fd_in_watch(CharDriverState *chr)
945 if (chr->fd_in_tag) {
946 io_remove_watch_poll(chr->fd_in_tag);
947 chr->fd_in_tag = 0;
952 static int io_channel_send_full(QIOChannel *ioc,
953 const void *buf, size_t len,
954 int *fds, size_t nfds)
956 size_t offset = 0;
958 while (offset < len) {
959 ssize_t ret = 0;
960 struct iovec iov = { .iov_base = (char *)buf + offset,
961 .iov_len = len - offset };
963 ret = qio_channel_writev_full(
964 ioc, &iov, 1,
965 fds, nfds, NULL);
966 if (ret == QIO_CHANNEL_ERR_BLOCK) {
967 if (offset) {
968 return offset;
971 errno = EAGAIN;
972 return -1;
973 } else if (ret < 0) {
974 errno = EINVAL;
975 return -1;
978 offset += ret;
981 return offset;
985 #ifndef _WIN32
986 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
988 return io_channel_send_full(ioc, buf, len, NULL, 0);
992 typedef struct FDCharDriver {
993 CharDriverState *chr;
994 QIOChannel *ioc_in, *ioc_out;
995 int max_size;
996 } FDCharDriver;
998 /* Called with chr_write_lock held. */
999 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1001 FDCharDriver *s = chr->opaque;
1003 return io_channel_send(s->ioc_out, buf, len);
1006 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1008 CharDriverState *chr = opaque;
1009 FDCharDriver *s = chr->opaque;
1010 int len;
1011 uint8_t buf[READ_BUF_LEN];
1012 ssize_t ret;
1014 len = sizeof(buf);
1015 if (len > s->max_size) {
1016 len = s->max_size;
1018 if (len == 0) {
1019 return TRUE;
1022 ret = qio_channel_read(
1023 chan, (gchar *)buf, len, NULL);
1024 if (ret == 0) {
1025 remove_fd_in_watch(chr);
1026 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1027 return FALSE;
1029 if (ret > 0) {
1030 qemu_chr_be_write(chr, buf, ret);
1033 return TRUE;
1036 static int fd_chr_read_poll(void *opaque)
1038 CharDriverState *chr = opaque;
1039 FDCharDriver *s = chr->opaque;
1041 s->max_size = qemu_chr_be_can_write(chr);
1042 return s->max_size;
1045 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1047 FDCharDriver *s = chr->opaque;
1048 return qio_channel_create_watch(s->ioc_out, cond);
1051 static void fd_chr_update_read_handler(CharDriverState *chr)
1053 FDCharDriver *s = chr->opaque;
1055 remove_fd_in_watch(chr);
1056 if (s->ioc_in) {
1057 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
1058 fd_chr_read_poll,
1059 fd_chr_read, chr);
1063 static void fd_chr_close(struct CharDriverState *chr)
1065 FDCharDriver *s = chr->opaque;
1067 remove_fd_in_watch(chr);
1068 if (s->ioc_in) {
1069 object_unref(OBJECT(s->ioc_in));
1071 if (s->ioc_out) {
1072 object_unref(OBJECT(s->ioc_out));
1075 g_free(s);
1076 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1079 /* open a character device to a unix fd */
1080 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1081 ChardevCommon *backend, Error **errp)
1083 CharDriverState *chr;
1084 FDCharDriver *s;
1086 chr = qemu_chr_alloc(backend, errp);
1087 if (!chr) {
1088 return NULL;
1090 s = g_new0(FDCharDriver, 1);
1091 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1092 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1093 qemu_set_nonblock(fd_out);
1094 s->chr = chr;
1095 chr->opaque = s;
1096 chr->chr_add_watch = fd_chr_add_watch;
1097 chr->chr_write = fd_chr_write;
1098 chr->chr_update_read_handler = fd_chr_update_read_handler;
1099 chr->chr_close = fd_chr_close;
1101 return chr;
1104 static CharDriverState *qemu_chr_open_pipe(const char *id,
1105 ChardevBackend *backend,
1106 ChardevReturn *ret,
1107 Error **errp)
1109 ChardevHostdev *opts = backend->u.pipe;
1110 int fd_in, fd_out;
1111 char *filename_in;
1112 char *filename_out;
1113 const char *filename = opts->device;
1114 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1117 filename_in = g_strdup_printf("%s.in", filename);
1118 filename_out = g_strdup_printf("%s.out", filename);
1119 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1120 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1121 g_free(filename_in);
1122 g_free(filename_out);
1123 if (fd_in < 0 || fd_out < 0) {
1124 if (fd_in >= 0)
1125 close(fd_in);
1126 if (fd_out >= 0)
1127 close(fd_out);
1128 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1129 if (fd_in < 0) {
1130 error_setg_file_open(errp, errno, filename);
1131 return NULL;
1134 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1137 /* init terminal so that we can grab keys */
1138 static struct termios oldtty;
1139 static int old_fd0_flags;
1140 static bool stdio_in_use;
1141 static bool stdio_allow_signal;
1142 static bool stdio_echo_state;
1144 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1146 static void term_exit(void)
1148 tcsetattr (0, TCSANOW, &oldtty);
1149 fcntl(0, F_SETFL, old_fd0_flags);
1152 static void term_stdio_handler(int sig)
1154 /* restore echo after resume from suspend. */
1155 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1158 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1160 struct termios tty;
1162 stdio_echo_state = echo;
1163 tty = oldtty;
1164 if (!echo) {
1165 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1166 |INLCR|IGNCR|ICRNL|IXON);
1167 tty.c_oflag |= OPOST;
1168 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1169 tty.c_cflag &= ~(CSIZE|PARENB);
1170 tty.c_cflag |= CS8;
1171 tty.c_cc[VMIN] = 1;
1172 tty.c_cc[VTIME] = 0;
1174 if (!stdio_allow_signal)
1175 tty.c_lflag &= ~ISIG;
1177 tcsetattr (0, TCSANOW, &tty);
1180 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1182 term_exit();
1183 fd_chr_close(chr);
1186 static CharDriverState *qemu_chr_open_stdio(const char *id,
1187 ChardevBackend *backend,
1188 ChardevReturn *ret,
1189 Error **errp)
1191 ChardevStdio *opts = backend->u.stdio;
1192 CharDriverState *chr;
1193 struct sigaction act;
1194 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1196 if (is_daemonized()) {
1197 error_setg(errp, "cannot use stdio with -daemonize");
1198 return NULL;
1201 if (stdio_in_use) {
1202 error_setg(errp, "cannot use stdio by multiple character devices");
1203 return NULL;
1206 stdio_in_use = true;
1207 old_fd0_flags = fcntl(0, F_GETFL);
1208 tcgetattr(0, &oldtty);
1209 qemu_set_nonblock(0);
1210 atexit(term_exit);
1212 memset(&act, 0, sizeof(act));
1213 act.sa_handler = term_stdio_handler;
1214 sigaction(SIGCONT, &act, NULL);
1216 chr = qemu_chr_open_fd(0, 1, common, errp);
1217 chr->chr_close = qemu_chr_close_stdio;
1218 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1219 if (opts->has_signal) {
1220 stdio_allow_signal = opts->signal;
1222 qemu_chr_fe_set_echo(chr, false);
1224 return chr;
1227 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1228 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1229 || defined(__GLIBC__)
1231 #define HAVE_CHARDEV_SERIAL 1
1232 #define HAVE_CHARDEV_PTY 1
1234 typedef struct {
1235 QIOChannel *ioc;
1236 int read_bytes;
1238 /* Protected by the CharDriverState chr_write_lock. */
1239 int connected;
1240 guint timer_tag;
1241 guint open_tag;
1242 } PtyCharDriver;
1244 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1245 static void pty_chr_state(CharDriverState *chr, int connected);
1247 static gboolean pty_chr_timer(gpointer opaque)
1249 struct CharDriverState *chr = opaque;
1250 PtyCharDriver *s = chr->opaque;
1252 qemu_mutex_lock(&chr->chr_write_lock);
1253 s->timer_tag = 0;
1254 s->open_tag = 0;
1255 if (!s->connected) {
1256 /* Next poll ... */
1257 pty_chr_update_read_handler_locked(chr);
1259 qemu_mutex_unlock(&chr->chr_write_lock);
1260 return FALSE;
1263 /* Called with chr_write_lock held. */
1264 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1266 PtyCharDriver *s = chr->opaque;
1268 if (s->timer_tag) {
1269 g_source_remove(s->timer_tag);
1270 s->timer_tag = 0;
1273 if (ms == 1000) {
1274 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1275 } else {
1276 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1280 /* Called with chr_write_lock held. */
1281 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1283 PtyCharDriver *s = chr->opaque;
1284 GPollFD pfd;
1285 int rc;
1286 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1288 pfd.fd = fioc->fd;
1289 pfd.events = G_IO_OUT;
1290 pfd.revents = 0;
1291 do {
1292 rc = g_poll(&pfd, 1, 0);
1293 } while (rc == -1 && errno == EINTR);
1294 assert(rc >= 0);
1296 if (pfd.revents & G_IO_HUP) {
1297 pty_chr_state(chr, 0);
1298 } else {
1299 pty_chr_state(chr, 1);
1303 static void pty_chr_update_read_handler(CharDriverState *chr)
1305 qemu_mutex_lock(&chr->chr_write_lock);
1306 pty_chr_update_read_handler_locked(chr);
1307 qemu_mutex_unlock(&chr->chr_write_lock);
1310 /* Called with chr_write_lock held. */
1311 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1313 PtyCharDriver *s = chr->opaque;
1315 if (!s->connected) {
1316 /* guest sends data, check for (re-)connect */
1317 pty_chr_update_read_handler_locked(chr);
1318 if (!s->connected) {
1319 return 0;
1322 return io_channel_send(s->ioc, buf, len);
1325 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1327 PtyCharDriver *s = chr->opaque;
1328 if (!s->connected) {
1329 return NULL;
1331 return qio_channel_create_watch(s->ioc, cond);
1334 static int pty_chr_read_poll(void *opaque)
1336 CharDriverState *chr = opaque;
1337 PtyCharDriver *s = chr->opaque;
1339 s->read_bytes = qemu_chr_be_can_write(chr);
1340 return s->read_bytes;
1343 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1345 CharDriverState *chr = opaque;
1346 PtyCharDriver *s = chr->opaque;
1347 gsize len;
1348 uint8_t buf[READ_BUF_LEN];
1349 ssize_t ret;
1351 len = sizeof(buf);
1352 if (len > s->read_bytes)
1353 len = s->read_bytes;
1354 if (len == 0) {
1355 return TRUE;
1357 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1358 if (ret <= 0) {
1359 pty_chr_state(chr, 0);
1360 return FALSE;
1361 } else {
1362 pty_chr_state(chr, 1);
1363 qemu_chr_be_write(chr, buf, ret);
1365 return TRUE;
1368 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1370 CharDriverState *chr = opaque;
1371 PtyCharDriver *s = chr->opaque;
1373 s->open_tag = 0;
1374 qemu_chr_be_generic_open(chr);
1375 return FALSE;
1378 /* Called with chr_write_lock held. */
1379 static void pty_chr_state(CharDriverState *chr, int connected)
1381 PtyCharDriver *s = chr->opaque;
1383 if (!connected) {
1384 if (s->open_tag) {
1385 g_source_remove(s->open_tag);
1386 s->open_tag = 0;
1388 remove_fd_in_watch(chr);
1389 s->connected = 0;
1390 /* (re-)connect poll interval for idle guests: once per second.
1391 * We check more frequently in case the guests sends data to
1392 * the virtual device linked to our pty. */
1393 pty_chr_rearm_timer(chr, 1000);
1394 } else {
1395 if (s->timer_tag) {
1396 g_source_remove(s->timer_tag);
1397 s->timer_tag = 0;
1399 if (!s->connected) {
1400 g_assert(s->open_tag == 0);
1401 s->connected = 1;
1402 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1404 if (!chr->fd_in_tag) {
1405 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1406 pty_chr_read_poll,
1407 pty_chr_read, chr);
1412 static void pty_chr_close(struct CharDriverState *chr)
1414 PtyCharDriver *s = chr->opaque;
1416 qemu_mutex_lock(&chr->chr_write_lock);
1417 pty_chr_state(chr, 0);
1418 object_unref(OBJECT(s->ioc));
1419 if (s->timer_tag) {
1420 g_source_remove(s->timer_tag);
1421 s->timer_tag = 0;
1423 qemu_mutex_unlock(&chr->chr_write_lock);
1424 g_free(s);
1425 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1428 static CharDriverState *qemu_chr_open_pty(const char *id,
1429 ChardevBackend *backend,
1430 ChardevReturn *ret,
1431 Error **errp)
1433 CharDriverState *chr;
1434 PtyCharDriver *s;
1435 int master_fd, slave_fd;
1436 char pty_name[PATH_MAX];
1437 ChardevCommon *common = backend->u.pty;
1439 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1440 if (master_fd < 0) {
1441 error_setg_errno(errp, errno, "Failed to create PTY");
1442 return NULL;
1445 close(slave_fd);
1446 qemu_set_nonblock(master_fd);
1448 chr = qemu_chr_alloc(common, errp);
1449 if (!chr) {
1450 close(master_fd);
1451 return NULL;
1454 chr->filename = g_strdup_printf("pty:%s", pty_name);
1455 ret->pty = g_strdup(pty_name);
1456 ret->has_pty = true;
1458 fprintf(stderr, "char device redirected to %s (label %s)\n",
1459 pty_name, id);
1461 s = g_new0(PtyCharDriver, 1);
1462 chr->opaque = s;
1463 chr->chr_write = pty_chr_write;
1464 chr->chr_update_read_handler = pty_chr_update_read_handler;
1465 chr->chr_close = pty_chr_close;
1466 chr->chr_add_watch = pty_chr_add_watch;
1467 chr->explicit_be_open = true;
1469 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1470 s->timer_tag = 0;
1472 return chr;
1475 static void tty_serial_init(int fd, int speed,
1476 int parity, int data_bits, int stop_bits)
1478 struct termios tty;
1479 speed_t spd;
1481 #if 0
1482 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1483 speed, parity, data_bits, stop_bits);
1484 #endif
1485 tcgetattr (fd, &tty);
1487 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1488 speed = speed * 10 / 11;
1489 do {
1490 check_speed(50);
1491 check_speed(75);
1492 check_speed(110);
1493 check_speed(134);
1494 check_speed(150);
1495 check_speed(200);
1496 check_speed(300);
1497 check_speed(600);
1498 check_speed(1200);
1499 check_speed(1800);
1500 check_speed(2400);
1501 check_speed(4800);
1502 check_speed(9600);
1503 check_speed(19200);
1504 check_speed(38400);
1505 /* Non-Posix values follow. They may be unsupported on some systems. */
1506 check_speed(57600);
1507 check_speed(115200);
1508 #ifdef B230400
1509 check_speed(230400);
1510 #endif
1511 #ifdef B460800
1512 check_speed(460800);
1513 #endif
1514 #ifdef B500000
1515 check_speed(500000);
1516 #endif
1517 #ifdef B576000
1518 check_speed(576000);
1519 #endif
1520 #ifdef B921600
1521 check_speed(921600);
1522 #endif
1523 #ifdef B1000000
1524 check_speed(1000000);
1525 #endif
1526 #ifdef B1152000
1527 check_speed(1152000);
1528 #endif
1529 #ifdef B1500000
1530 check_speed(1500000);
1531 #endif
1532 #ifdef B2000000
1533 check_speed(2000000);
1534 #endif
1535 #ifdef B2500000
1536 check_speed(2500000);
1537 #endif
1538 #ifdef B3000000
1539 check_speed(3000000);
1540 #endif
1541 #ifdef B3500000
1542 check_speed(3500000);
1543 #endif
1544 #ifdef B4000000
1545 check_speed(4000000);
1546 #endif
1547 spd = B115200;
1548 } while (0);
1550 cfsetispeed(&tty, spd);
1551 cfsetospeed(&tty, spd);
1553 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1554 |INLCR|IGNCR|ICRNL|IXON);
1555 tty.c_oflag |= OPOST;
1556 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1557 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1558 switch(data_bits) {
1559 default:
1560 case 8:
1561 tty.c_cflag |= CS8;
1562 break;
1563 case 7:
1564 tty.c_cflag |= CS7;
1565 break;
1566 case 6:
1567 tty.c_cflag |= CS6;
1568 break;
1569 case 5:
1570 tty.c_cflag |= CS5;
1571 break;
1573 switch(parity) {
1574 default:
1575 case 'N':
1576 break;
1577 case 'E':
1578 tty.c_cflag |= PARENB;
1579 break;
1580 case 'O':
1581 tty.c_cflag |= PARENB | PARODD;
1582 break;
1584 if (stop_bits == 2)
1585 tty.c_cflag |= CSTOPB;
1587 tcsetattr (fd, TCSANOW, &tty);
1590 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1592 FDCharDriver *s = chr->opaque;
1593 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1595 switch(cmd) {
1596 case CHR_IOCTL_SERIAL_SET_PARAMS:
1598 QEMUSerialSetParams *ssp = arg;
1599 tty_serial_init(fioc->fd,
1600 ssp->speed, ssp->parity,
1601 ssp->data_bits, ssp->stop_bits);
1603 break;
1604 case CHR_IOCTL_SERIAL_SET_BREAK:
1606 int enable = *(int *)arg;
1607 if (enable) {
1608 tcsendbreak(fioc->fd, 1);
1611 break;
1612 case CHR_IOCTL_SERIAL_GET_TIOCM:
1614 int sarg = 0;
1615 int *targ = (int *)arg;
1616 ioctl(fioc->fd, TIOCMGET, &sarg);
1617 *targ = 0;
1618 if (sarg & TIOCM_CTS)
1619 *targ |= CHR_TIOCM_CTS;
1620 if (sarg & TIOCM_CAR)
1621 *targ |= CHR_TIOCM_CAR;
1622 if (sarg & TIOCM_DSR)
1623 *targ |= CHR_TIOCM_DSR;
1624 if (sarg & TIOCM_RI)
1625 *targ |= CHR_TIOCM_RI;
1626 if (sarg & TIOCM_DTR)
1627 *targ |= CHR_TIOCM_DTR;
1628 if (sarg & TIOCM_RTS)
1629 *targ |= CHR_TIOCM_RTS;
1631 break;
1632 case CHR_IOCTL_SERIAL_SET_TIOCM:
1634 int sarg = *(int *)arg;
1635 int targ = 0;
1636 ioctl(fioc->fd, TIOCMGET, &targ);
1637 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1638 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1639 if (sarg & CHR_TIOCM_CTS)
1640 targ |= TIOCM_CTS;
1641 if (sarg & CHR_TIOCM_CAR)
1642 targ |= TIOCM_CAR;
1643 if (sarg & CHR_TIOCM_DSR)
1644 targ |= TIOCM_DSR;
1645 if (sarg & CHR_TIOCM_RI)
1646 targ |= TIOCM_RI;
1647 if (sarg & CHR_TIOCM_DTR)
1648 targ |= TIOCM_DTR;
1649 if (sarg & CHR_TIOCM_RTS)
1650 targ |= TIOCM_RTS;
1651 ioctl(fioc->fd, TIOCMSET, &targ);
1653 break;
1654 default:
1655 return -ENOTSUP;
1657 return 0;
1660 static void qemu_chr_close_tty(CharDriverState *chr)
1662 fd_chr_close(chr);
1665 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1666 ChardevCommon *backend,
1667 Error **errp)
1669 CharDriverState *chr;
1671 tty_serial_init(fd, 115200, 'N', 8, 1);
1672 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1673 chr->chr_ioctl = tty_serial_ioctl;
1674 chr->chr_close = qemu_chr_close_tty;
1675 return chr;
1677 #endif /* __linux__ || __sun__ */
1679 #if defined(__linux__)
1681 #define HAVE_CHARDEV_PARPORT 1
1683 typedef struct {
1684 int fd;
1685 int mode;
1686 } ParallelCharDriver;
1688 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1690 if (s->mode != mode) {
1691 int m = mode;
1692 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1693 return 0;
1694 s->mode = mode;
1696 return 1;
1699 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1701 ParallelCharDriver *drv = chr->opaque;
1702 int fd = drv->fd;
1703 uint8_t b;
1705 switch(cmd) {
1706 case CHR_IOCTL_PP_READ_DATA:
1707 if (ioctl(fd, PPRDATA, &b) < 0)
1708 return -ENOTSUP;
1709 *(uint8_t *)arg = b;
1710 break;
1711 case CHR_IOCTL_PP_WRITE_DATA:
1712 b = *(uint8_t *)arg;
1713 if (ioctl(fd, PPWDATA, &b) < 0)
1714 return -ENOTSUP;
1715 break;
1716 case CHR_IOCTL_PP_READ_CONTROL:
1717 if (ioctl(fd, PPRCONTROL, &b) < 0)
1718 return -ENOTSUP;
1719 /* Linux gives only the lowest bits, and no way to know data
1720 direction! For better compatibility set the fixed upper
1721 bits. */
1722 *(uint8_t *)arg = b | 0xc0;
1723 break;
1724 case CHR_IOCTL_PP_WRITE_CONTROL:
1725 b = *(uint8_t *)arg;
1726 if (ioctl(fd, PPWCONTROL, &b) < 0)
1727 return -ENOTSUP;
1728 break;
1729 case CHR_IOCTL_PP_READ_STATUS:
1730 if (ioctl(fd, PPRSTATUS, &b) < 0)
1731 return -ENOTSUP;
1732 *(uint8_t *)arg = b;
1733 break;
1734 case CHR_IOCTL_PP_DATA_DIR:
1735 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1736 return -ENOTSUP;
1737 break;
1738 case CHR_IOCTL_PP_EPP_READ_ADDR:
1739 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1740 struct ParallelIOArg *parg = arg;
1741 int n = read(fd, parg->buffer, parg->count);
1742 if (n != parg->count) {
1743 return -EIO;
1746 break;
1747 case CHR_IOCTL_PP_EPP_READ:
1748 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1749 struct ParallelIOArg *parg = arg;
1750 int n = read(fd, parg->buffer, parg->count);
1751 if (n != parg->count) {
1752 return -EIO;
1755 break;
1756 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1757 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1758 struct ParallelIOArg *parg = arg;
1759 int n = write(fd, parg->buffer, parg->count);
1760 if (n != parg->count) {
1761 return -EIO;
1764 break;
1765 case CHR_IOCTL_PP_EPP_WRITE:
1766 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1767 struct ParallelIOArg *parg = arg;
1768 int n = write(fd, parg->buffer, parg->count);
1769 if (n != parg->count) {
1770 return -EIO;
1773 break;
1774 default:
1775 return -ENOTSUP;
1777 return 0;
1780 static void pp_close(CharDriverState *chr)
1782 ParallelCharDriver *drv = chr->opaque;
1783 int fd = drv->fd;
1785 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1786 ioctl(fd, PPRELEASE);
1787 close(fd);
1788 g_free(drv);
1789 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1792 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1793 ChardevCommon *backend,
1794 Error **errp)
1796 CharDriverState *chr;
1797 ParallelCharDriver *drv;
1799 if (ioctl(fd, PPCLAIM) < 0) {
1800 error_setg_errno(errp, errno, "not a parallel port");
1801 close(fd);
1802 return NULL;
1805 chr = qemu_chr_alloc(backend, errp);
1806 if (!chr) {
1807 return NULL;
1810 drv = g_new0(ParallelCharDriver, 1);
1811 chr->opaque = drv;
1812 chr->chr_write = null_chr_write;
1813 chr->chr_ioctl = pp_ioctl;
1814 chr->chr_close = pp_close;
1816 drv->fd = fd;
1817 drv->mode = IEEE1284_MODE_COMPAT;
1819 return chr;
1821 #endif /* __linux__ */
1823 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1825 #define HAVE_CHARDEV_PARPORT 1
1827 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1829 int fd = (int)(intptr_t)chr->opaque;
1830 uint8_t b;
1832 switch(cmd) {
1833 case CHR_IOCTL_PP_READ_DATA:
1834 if (ioctl(fd, PPIGDATA, &b) < 0)
1835 return -ENOTSUP;
1836 *(uint8_t *)arg = b;
1837 break;
1838 case CHR_IOCTL_PP_WRITE_DATA:
1839 b = *(uint8_t *)arg;
1840 if (ioctl(fd, PPISDATA, &b) < 0)
1841 return -ENOTSUP;
1842 break;
1843 case CHR_IOCTL_PP_READ_CONTROL:
1844 if (ioctl(fd, PPIGCTRL, &b) < 0)
1845 return -ENOTSUP;
1846 *(uint8_t *)arg = b;
1847 break;
1848 case CHR_IOCTL_PP_WRITE_CONTROL:
1849 b = *(uint8_t *)arg;
1850 if (ioctl(fd, PPISCTRL, &b) < 0)
1851 return -ENOTSUP;
1852 break;
1853 case CHR_IOCTL_PP_READ_STATUS:
1854 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1855 return -ENOTSUP;
1856 *(uint8_t *)arg = b;
1857 break;
1858 default:
1859 return -ENOTSUP;
1861 return 0;
1864 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1865 ChardevCommon *backend,
1866 Error **errp)
1868 CharDriverState *chr;
1870 chr = qemu_chr_alloc(backend, errp);
1871 if (!chr) {
1872 return NULL;
1874 chr->opaque = (void *)(intptr_t)fd;
1875 chr->chr_write = null_chr_write;
1876 chr->chr_ioctl = pp_ioctl;
1877 chr->explicit_be_open = true;
1878 return chr;
1880 #endif
1882 #else /* _WIN32 */
1884 #define HAVE_CHARDEV_SERIAL 1
1886 typedef struct {
1887 int max_size;
1888 HANDLE hcom, hrecv, hsend;
1889 OVERLAPPED orecv;
1890 BOOL fpipe;
1891 DWORD len;
1893 /* Protected by the CharDriverState chr_write_lock. */
1894 OVERLAPPED osend;
1895 } WinCharState;
1897 typedef struct {
1898 HANDLE hStdIn;
1899 HANDLE hInputReadyEvent;
1900 HANDLE hInputDoneEvent;
1901 HANDLE hInputThread;
1902 uint8_t win_stdio_buf;
1903 } WinStdioCharState;
1905 #define NSENDBUF 2048
1906 #define NRECVBUF 2048
1907 #define MAXCONNECT 1
1908 #define NTIMEOUT 5000
1910 static int win_chr_poll(void *opaque);
1911 static int win_chr_pipe_poll(void *opaque);
1913 static void win_chr_close(CharDriverState *chr)
1915 WinCharState *s = chr->opaque;
1917 if (s->hsend) {
1918 CloseHandle(s->hsend);
1919 s->hsend = NULL;
1921 if (s->hrecv) {
1922 CloseHandle(s->hrecv);
1923 s->hrecv = NULL;
1925 if (s->hcom) {
1926 CloseHandle(s->hcom);
1927 s->hcom = NULL;
1929 if (s->fpipe)
1930 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1931 else
1932 qemu_del_polling_cb(win_chr_poll, chr);
1934 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1937 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1939 WinCharState *s = chr->opaque;
1940 COMMCONFIG comcfg;
1941 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1942 COMSTAT comstat;
1943 DWORD size;
1944 DWORD err;
1946 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1947 if (!s->hsend) {
1948 error_setg(errp, "Failed CreateEvent");
1949 goto fail;
1951 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1952 if (!s->hrecv) {
1953 error_setg(errp, "Failed CreateEvent");
1954 goto fail;
1957 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1958 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1959 if (s->hcom == INVALID_HANDLE_VALUE) {
1960 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1961 s->hcom = NULL;
1962 goto fail;
1965 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1966 error_setg(errp, "Failed SetupComm");
1967 goto fail;
1970 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1971 size = sizeof(COMMCONFIG);
1972 GetDefaultCommConfig(filename, &comcfg, &size);
1973 comcfg.dcb.DCBlength = sizeof(DCB);
1974 CommConfigDialog(filename, NULL, &comcfg);
1976 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1977 error_setg(errp, "Failed SetCommState");
1978 goto fail;
1981 if (!SetCommMask(s->hcom, EV_ERR)) {
1982 error_setg(errp, "Failed SetCommMask");
1983 goto fail;
1986 cto.ReadIntervalTimeout = MAXDWORD;
1987 if (!SetCommTimeouts(s->hcom, &cto)) {
1988 error_setg(errp, "Failed SetCommTimeouts");
1989 goto fail;
1992 if (!ClearCommError(s->hcom, &err, &comstat)) {
1993 error_setg(errp, "Failed ClearCommError");
1994 goto fail;
1996 qemu_add_polling_cb(win_chr_poll, chr);
1997 return 0;
1999 fail:
2000 win_chr_close(chr);
2001 return -1;
2004 /* Called with chr_write_lock held. */
2005 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2007 WinCharState *s = chr->opaque;
2008 DWORD len, ret, size, err;
2010 len = len1;
2011 ZeroMemory(&s->osend, sizeof(s->osend));
2012 s->osend.hEvent = s->hsend;
2013 while (len > 0) {
2014 if (s->hsend)
2015 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2016 else
2017 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2018 if (!ret) {
2019 err = GetLastError();
2020 if (err == ERROR_IO_PENDING) {
2021 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2022 if (ret) {
2023 buf += size;
2024 len -= size;
2025 } else {
2026 break;
2028 } else {
2029 break;
2031 } else {
2032 buf += size;
2033 len -= size;
2036 return len1 - len;
2039 static int win_chr_read_poll(CharDriverState *chr)
2041 WinCharState *s = chr->opaque;
2043 s->max_size = qemu_chr_be_can_write(chr);
2044 return s->max_size;
2047 static void win_chr_readfile(CharDriverState *chr)
2049 WinCharState *s = chr->opaque;
2050 int ret, err;
2051 uint8_t buf[READ_BUF_LEN];
2052 DWORD size;
2054 ZeroMemory(&s->orecv, sizeof(s->orecv));
2055 s->orecv.hEvent = s->hrecv;
2056 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2057 if (!ret) {
2058 err = GetLastError();
2059 if (err == ERROR_IO_PENDING) {
2060 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2064 if (size > 0) {
2065 qemu_chr_be_write(chr, buf, size);
2069 static void win_chr_read(CharDriverState *chr)
2071 WinCharState *s = chr->opaque;
2073 if (s->len > s->max_size)
2074 s->len = s->max_size;
2075 if (s->len == 0)
2076 return;
2078 win_chr_readfile(chr);
2081 static int win_chr_poll(void *opaque)
2083 CharDriverState *chr = opaque;
2084 WinCharState *s = chr->opaque;
2085 COMSTAT status;
2086 DWORD comerr;
2088 ClearCommError(s->hcom, &comerr, &status);
2089 if (status.cbInQue > 0) {
2090 s->len = status.cbInQue;
2091 win_chr_read_poll(chr);
2092 win_chr_read(chr);
2093 return 1;
2095 return 0;
2098 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2099 ChardevCommon *backend,
2100 Error **errp)
2102 CharDriverState *chr;
2103 WinCharState *s;
2105 chr = qemu_chr_alloc(backend, errp);
2106 if (!chr) {
2107 return NULL;
2109 s = g_new0(WinCharState, 1);
2110 chr->opaque = s;
2111 chr->chr_write = win_chr_write;
2112 chr->chr_close = win_chr_close;
2114 if (win_chr_init(chr, filename, errp) < 0) {
2115 g_free(s);
2116 qemu_chr_free_common(chr);
2117 return NULL;
2119 return chr;
2122 static int win_chr_pipe_poll(void *opaque)
2124 CharDriverState *chr = opaque;
2125 WinCharState *s = chr->opaque;
2126 DWORD size;
2128 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2129 if (size > 0) {
2130 s->len = size;
2131 win_chr_read_poll(chr);
2132 win_chr_read(chr);
2133 return 1;
2135 return 0;
2138 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2139 Error **errp)
2141 WinCharState *s = chr->opaque;
2142 OVERLAPPED ov;
2143 int ret;
2144 DWORD size;
2145 char *openname;
2147 s->fpipe = TRUE;
2149 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2150 if (!s->hsend) {
2151 error_setg(errp, "Failed CreateEvent");
2152 goto fail;
2154 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2155 if (!s->hrecv) {
2156 error_setg(errp, "Failed CreateEvent");
2157 goto fail;
2160 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2161 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2162 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2163 PIPE_WAIT,
2164 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2165 g_free(openname);
2166 if (s->hcom == INVALID_HANDLE_VALUE) {
2167 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2168 s->hcom = NULL;
2169 goto fail;
2172 ZeroMemory(&ov, sizeof(ov));
2173 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2174 ret = ConnectNamedPipe(s->hcom, &ov);
2175 if (ret) {
2176 error_setg(errp, "Failed ConnectNamedPipe");
2177 goto fail;
2180 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2181 if (!ret) {
2182 error_setg(errp, "Failed GetOverlappedResult");
2183 if (ov.hEvent) {
2184 CloseHandle(ov.hEvent);
2185 ov.hEvent = NULL;
2187 goto fail;
2190 if (ov.hEvent) {
2191 CloseHandle(ov.hEvent);
2192 ov.hEvent = NULL;
2194 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2195 return 0;
2197 fail:
2198 win_chr_close(chr);
2199 return -1;
2203 static CharDriverState *qemu_chr_open_pipe(const char *id,
2204 ChardevBackend *backend,
2205 ChardevReturn *ret,
2206 Error **errp)
2208 ChardevHostdev *opts = backend->u.pipe;
2209 const char *filename = opts->device;
2210 CharDriverState *chr;
2211 WinCharState *s;
2212 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2214 chr = qemu_chr_alloc(common, errp);
2215 if (!chr) {
2216 return NULL;
2218 s = g_new0(WinCharState, 1);
2219 chr->opaque = s;
2220 chr->chr_write = win_chr_write;
2221 chr->chr_close = win_chr_close;
2223 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2224 g_free(s);
2225 qemu_chr_free_common(chr);
2226 return NULL;
2228 return chr;
2231 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2232 ChardevCommon *backend,
2233 Error **errp)
2235 CharDriverState *chr;
2236 WinCharState *s;
2238 chr = qemu_chr_alloc(backend, errp);
2239 if (!chr) {
2240 return NULL;
2242 s = g_new0(WinCharState, 1);
2243 s->hcom = fd_out;
2244 chr->opaque = s;
2245 chr->chr_write = win_chr_write;
2246 return chr;
2249 static CharDriverState *qemu_chr_open_win_con(const char *id,
2250 ChardevBackend *backend,
2251 ChardevReturn *ret,
2252 Error **errp)
2254 ChardevCommon *common = backend->u.console;
2255 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2256 common, errp);
2259 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2261 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2262 DWORD dwSize;
2263 int len1;
2265 len1 = len;
2267 while (len1 > 0) {
2268 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2269 break;
2271 buf += dwSize;
2272 len1 -= dwSize;
2275 return len - len1;
2278 static void win_stdio_wait_func(void *opaque)
2280 CharDriverState *chr = opaque;
2281 WinStdioCharState *stdio = chr->opaque;
2282 INPUT_RECORD buf[4];
2283 int ret;
2284 DWORD dwSize;
2285 int i;
2287 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2289 if (!ret) {
2290 /* Avoid error storm */
2291 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2292 return;
2295 for (i = 0; i < dwSize; i++) {
2296 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2298 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2299 int j;
2300 if (kev->uChar.AsciiChar != 0) {
2301 for (j = 0; j < kev->wRepeatCount; j++) {
2302 if (qemu_chr_be_can_write(chr)) {
2303 uint8_t c = kev->uChar.AsciiChar;
2304 qemu_chr_be_write(chr, &c, 1);
2312 static DWORD WINAPI win_stdio_thread(LPVOID param)
2314 CharDriverState *chr = param;
2315 WinStdioCharState *stdio = chr->opaque;
2316 int ret;
2317 DWORD dwSize;
2319 while (1) {
2321 /* Wait for one byte */
2322 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2324 /* Exit in case of error, continue if nothing read */
2325 if (!ret) {
2326 break;
2328 if (!dwSize) {
2329 continue;
2332 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2333 if (stdio->win_stdio_buf == '\r') {
2334 continue;
2337 /* Signal the main thread and wait until the byte was eaten */
2338 if (!SetEvent(stdio->hInputReadyEvent)) {
2339 break;
2341 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2342 != WAIT_OBJECT_0) {
2343 break;
2347 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2348 return 0;
2351 static void win_stdio_thread_wait_func(void *opaque)
2353 CharDriverState *chr = opaque;
2354 WinStdioCharState *stdio = chr->opaque;
2356 if (qemu_chr_be_can_write(chr)) {
2357 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2360 SetEvent(stdio->hInputDoneEvent);
2363 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2365 WinStdioCharState *stdio = chr->opaque;
2366 DWORD dwMode = 0;
2368 GetConsoleMode(stdio->hStdIn, &dwMode);
2370 if (echo) {
2371 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2372 } else {
2373 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2377 static void win_stdio_close(CharDriverState *chr)
2379 WinStdioCharState *stdio = chr->opaque;
2381 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2382 CloseHandle(stdio->hInputReadyEvent);
2384 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2385 CloseHandle(stdio->hInputDoneEvent);
2387 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2388 TerminateThread(stdio->hInputThread, 0);
2391 g_free(chr->opaque);
2392 g_free(chr);
2395 static CharDriverState *qemu_chr_open_stdio(const char *id,
2396 ChardevBackend *backend,
2397 ChardevReturn *ret,
2398 Error **errp)
2400 CharDriverState *chr;
2401 WinStdioCharState *stdio;
2402 DWORD dwMode;
2403 int is_console = 0;
2404 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio);
2406 chr = qemu_chr_alloc(common, errp);
2407 if (!chr) {
2408 return NULL;
2410 stdio = g_new0(WinStdioCharState, 1);
2412 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2413 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2414 error_setg(errp, "cannot open stdio: invalid handle");
2415 return NULL;
2418 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2420 chr->opaque = stdio;
2421 chr->chr_write = win_stdio_write;
2422 chr->chr_close = win_stdio_close;
2424 if (is_console) {
2425 if (qemu_add_wait_object(stdio->hStdIn,
2426 win_stdio_wait_func, chr)) {
2427 error_setg(errp, "qemu_add_wait_object: failed");
2428 goto err1;
2430 } else {
2431 DWORD dwId;
2433 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2434 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2435 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2436 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2437 error_setg(errp, "cannot create event");
2438 goto err2;
2440 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2441 win_stdio_thread_wait_func, chr)) {
2442 error_setg(errp, "qemu_add_wait_object: failed");
2443 goto err2;
2445 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2446 chr, 0, &dwId);
2448 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2449 error_setg(errp, "cannot create stdio thread");
2450 goto err3;
2454 dwMode |= ENABLE_LINE_INPUT;
2456 if (is_console) {
2457 /* set the terminal in raw mode */
2458 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2459 dwMode |= ENABLE_PROCESSED_INPUT;
2462 SetConsoleMode(stdio->hStdIn, dwMode);
2464 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2465 qemu_chr_fe_set_echo(chr, false);
2467 return chr;
2469 err3:
2470 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2471 err2:
2472 CloseHandle(stdio->hInputReadyEvent);
2473 CloseHandle(stdio->hInputDoneEvent);
2474 err1:
2475 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2476 return NULL;
2478 #endif /* !_WIN32 */
2481 /***********************************************************/
2482 /* UDP Net console */
2484 typedef struct {
2485 QIOChannel *ioc;
2486 uint8_t buf[READ_BUF_LEN];
2487 int bufcnt;
2488 int bufptr;
2489 int max_size;
2490 } NetCharDriver;
2492 /* Called with chr_write_lock held. */
2493 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2495 NetCharDriver *s = chr->opaque;
2497 return qio_channel_write(
2498 s->ioc, (const char *)buf, len, NULL);
2501 static int udp_chr_read_poll(void *opaque)
2503 CharDriverState *chr = opaque;
2504 NetCharDriver *s = chr->opaque;
2506 s->max_size = qemu_chr_be_can_write(chr);
2508 /* If there were any stray characters in the queue process them
2509 * first
2511 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2512 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2513 s->bufptr++;
2514 s->max_size = qemu_chr_be_can_write(chr);
2516 return s->max_size;
2519 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2521 CharDriverState *chr = opaque;
2522 NetCharDriver *s = chr->opaque;
2523 ssize_t ret;
2525 if (s->max_size == 0) {
2526 return TRUE;
2528 ret = qio_channel_read(
2529 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2530 if (ret <= 0) {
2531 remove_fd_in_watch(chr);
2532 return FALSE;
2534 s->bufcnt = ret;
2536 s->bufptr = 0;
2537 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2538 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2539 s->bufptr++;
2540 s->max_size = qemu_chr_be_can_write(chr);
2543 return TRUE;
2546 static void udp_chr_update_read_handler(CharDriverState *chr)
2548 NetCharDriver *s = chr->opaque;
2550 remove_fd_in_watch(chr);
2551 if (s->ioc) {
2552 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2553 udp_chr_read_poll,
2554 udp_chr_read, chr);
2558 static void udp_chr_close(CharDriverState *chr)
2560 NetCharDriver *s = chr->opaque;
2562 remove_fd_in_watch(chr);
2563 if (s->ioc) {
2564 object_unref(OBJECT(s->ioc));
2566 g_free(s);
2567 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2570 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2571 ChardevCommon *backend,
2572 Error **errp)
2574 CharDriverState *chr = NULL;
2575 NetCharDriver *s = NULL;
2577 chr = qemu_chr_alloc(backend, errp);
2578 if (!chr) {
2579 return NULL;
2581 s = g_new0(NetCharDriver, 1);
2583 s->ioc = QIO_CHANNEL(sioc);
2584 s->bufcnt = 0;
2585 s->bufptr = 0;
2586 chr->opaque = s;
2587 chr->chr_write = udp_chr_write;
2588 chr->chr_update_read_handler = udp_chr_update_read_handler;
2589 chr->chr_close = udp_chr_close;
2590 /* be isn't opened until we get a connection */
2591 chr->explicit_be_open = true;
2592 return chr;
2595 /***********************************************************/
2596 /* TCP Net console */
2598 typedef struct {
2599 QIOChannel *ioc; /* Client I/O channel */
2600 QIOChannelSocket *sioc; /* Client master channel */
2601 QIOChannelSocket *listen_ioc;
2602 guint listen_tag;
2603 QCryptoTLSCreds *tls_creds;
2604 int connected;
2605 int max_size;
2606 int do_telnetopt;
2607 int do_nodelay;
2608 int is_unix;
2609 int *read_msgfds;
2610 size_t read_msgfds_num;
2611 int *write_msgfds;
2612 size_t write_msgfds_num;
2614 SocketAddress *addr;
2615 bool is_listen;
2616 bool is_telnet;
2618 guint reconnect_timer;
2619 int64_t reconnect_time;
2620 bool connect_err_reported;
2621 } TCPCharDriver;
2623 static gboolean socket_reconnect_timeout(gpointer opaque);
2625 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2627 TCPCharDriver *s = chr->opaque;
2628 assert(s->connected == 0);
2629 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2630 socket_reconnect_timeout, chr);
2633 static void check_report_connect_error(CharDriverState *chr,
2634 Error *err)
2636 TCPCharDriver *s = chr->opaque;
2638 if (!s->connect_err_reported) {
2639 error_report("Unable to connect character device %s: %s",
2640 chr->label, error_get_pretty(err));
2641 s->connect_err_reported = true;
2643 qemu_chr_socket_restart_timer(chr);
2646 static gboolean tcp_chr_accept(QIOChannel *chan,
2647 GIOCondition cond,
2648 void *opaque);
2650 /* Called with chr_write_lock held. */
2651 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2653 TCPCharDriver *s = chr->opaque;
2654 if (s->connected) {
2655 int ret = io_channel_send_full(s->ioc, buf, len,
2656 s->write_msgfds,
2657 s->write_msgfds_num);
2659 /* free the written msgfds, no matter what */
2660 if (s->write_msgfds_num) {
2661 g_free(s->write_msgfds);
2662 s->write_msgfds = 0;
2663 s->write_msgfds_num = 0;
2666 return ret;
2667 } else {
2668 /* XXX: indicate an error ? */
2669 return len;
2673 static int tcp_chr_read_poll(void *opaque)
2675 CharDriverState *chr = opaque;
2676 TCPCharDriver *s = chr->opaque;
2677 if (!s->connected)
2678 return 0;
2679 s->max_size = qemu_chr_be_can_write(chr);
2680 return s->max_size;
2683 #define IAC 255
2684 #define IAC_BREAK 243
2685 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2686 TCPCharDriver *s,
2687 uint8_t *buf, int *size)
2689 /* Handle any telnet client's basic IAC options to satisfy char by
2690 * char mode with no echo. All IAC options will be removed from
2691 * the buf and the do_telnetopt variable will be used to track the
2692 * state of the width of the IAC information.
2694 * IAC commands come in sets of 3 bytes with the exception of the
2695 * "IAC BREAK" command and the double IAC.
2698 int i;
2699 int j = 0;
2701 for (i = 0; i < *size; i++) {
2702 if (s->do_telnetopt > 1) {
2703 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2704 /* Double IAC means send an IAC */
2705 if (j != i)
2706 buf[j] = buf[i];
2707 j++;
2708 s->do_telnetopt = 1;
2709 } else {
2710 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2711 /* Handle IAC break commands by sending a serial break */
2712 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2713 s->do_telnetopt++;
2715 s->do_telnetopt++;
2717 if (s->do_telnetopt >= 4) {
2718 s->do_telnetopt = 1;
2720 } else {
2721 if ((unsigned char)buf[i] == IAC) {
2722 s->do_telnetopt = 2;
2723 } else {
2724 if (j != i)
2725 buf[j] = buf[i];
2726 j++;
2730 *size = j;
2733 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2735 TCPCharDriver *s = chr->opaque;
2736 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2738 assert(num <= TCP_MAX_FDS);
2740 if (to_copy) {
2741 int i;
2743 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2745 /* Close unused fds */
2746 for (i = to_copy; i < s->read_msgfds_num; i++) {
2747 close(s->read_msgfds[i]);
2750 g_free(s->read_msgfds);
2751 s->read_msgfds = 0;
2752 s->read_msgfds_num = 0;
2755 return to_copy;
2758 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2760 TCPCharDriver *s = chr->opaque;
2762 if (!qio_channel_has_feature(s->ioc,
2763 QIO_CHANNEL_FEATURE_FD_PASS)) {
2764 return -1;
2766 /* clear old pending fd array */
2767 g_free(s->write_msgfds);
2768 s->write_msgfds = NULL;
2770 if (num) {
2771 s->write_msgfds = g_new(int, num);
2772 memcpy(s->write_msgfds, fds, num * sizeof(int));
2775 s->write_msgfds_num = num;
2777 return 0;
2780 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2782 TCPCharDriver *s = chr->opaque;
2783 struct iovec iov = { .iov_base = buf, .iov_len = len };
2784 int ret;
2785 size_t i;
2786 int *msgfds = NULL;
2787 size_t msgfds_num = 0;
2789 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2790 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2791 &msgfds, &msgfds_num,
2792 NULL);
2793 } else {
2794 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2795 NULL, NULL,
2796 NULL);
2799 if (msgfds_num) {
2800 /* close and clean read_msgfds */
2801 for (i = 0; i < s->read_msgfds_num; i++) {
2802 close(s->read_msgfds[i]);
2805 if (s->read_msgfds_num) {
2806 g_free(s->read_msgfds);
2809 s->read_msgfds = msgfds;
2810 s->read_msgfds_num = msgfds_num;
2813 for (i = 0; i < s->read_msgfds_num; i++) {
2814 int fd = s->read_msgfds[i];
2815 if (fd < 0) {
2816 continue;
2819 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2820 qemu_set_block(fd);
2822 #ifndef MSG_CMSG_CLOEXEC
2823 qemu_set_cloexec(fd);
2824 #endif
2827 return ret;
2830 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2832 TCPCharDriver *s = chr->opaque;
2833 return qio_channel_create_watch(s->ioc, cond);
2836 static void tcp_chr_disconnect(CharDriverState *chr)
2838 TCPCharDriver *s = chr->opaque;
2840 if (!s->connected) {
2841 return;
2844 s->connected = 0;
2845 if (s->listen_ioc) {
2846 s->listen_tag = qio_channel_add_watch(
2847 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
2849 tcp_set_msgfds(chr, NULL, 0);
2850 remove_fd_in_watch(chr);
2851 object_unref(OBJECT(s->sioc));
2852 s->sioc = NULL;
2853 object_unref(OBJECT(s->ioc));
2854 s->ioc = NULL;
2855 g_free(chr->filename);
2856 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
2857 s->is_listen, s->is_telnet);
2858 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2859 if (s->reconnect_time) {
2860 qemu_chr_socket_restart_timer(chr);
2864 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2866 CharDriverState *chr = opaque;
2867 TCPCharDriver *s = chr->opaque;
2868 uint8_t buf[READ_BUF_LEN];
2869 int len, size;
2871 if (!s->connected || s->max_size <= 0) {
2872 return TRUE;
2874 len = sizeof(buf);
2875 if (len > s->max_size)
2876 len = s->max_size;
2877 size = tcp_chr_recv(chr, (void *)buf, len);
2878 if (size == 0 || size == -1) {
2879 /* connection closed */
2880 tcp_chr_disconnect(chr);
2881 } else if (size > 0) {
2882 if (s->do_telnetopt)
2883 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2884 if (size > 0)
2885 qemu_chr_be_write(chr, buf, size);
2888 return TRUE;
2891 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2893 TCPCharDriver *s = chr->opaque;
2894 int size;
2896 if (!s->connected) {
2897 return 0;
2900 size = tcp_chr_recv(chr, (void *) buf, len);
2901 if (size == 0) {
2902 /* connection closed */
2903 tcp_chr_disconnect(chr);
2906 return size;
2909 static void tcp_chr_connect(void *opaque)
2911 CharDriverState *chr = opaque;
2912 TCPCharDriver *s = chr->opaque;
2914 g_free(chr->filename);
2915 chr->filename = sockaddr_to_str(
2916 &s->sioc->localAddr, s->sioc->localAddrLen,
2917 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
2918 s->is_listen, s->is_telnet);
2920 s->connected = 1;
2921 if (s->ioc) {
2922 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2923 tcp_chr_read_poll,
2924 tcp_chr_read, chr);
2926 qemu_chr_be_generic_open(chr);
2929 static void tcp_chr_update_read_handler(CharDriverState *chr)
2931 TCPCharDriver *s = chr->opaque;
2933 if (!s->connected) {
2934 return;
2937 remove_fd_in_watch(chr);
2938 if (s->ioc) {
2939 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2940 tcp_chr_read_poll,
2941 tcp_chr_read, chr);
2945 typedef struct {
2946 CharDriverState *chr;
2947 char buf[12];
2948 size_t buflen;
2949 } TCPCharDriverTelnetInit;
2951 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
2952 GIOCondition cond G_GNUC_UNUSED,
2953 gpointer user_data)
2955 TCPCharDriverTelnetInit *init = user_data;
2956 ssize_t ret;
2958 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
2959 if (ret < 0) {
2960 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2961 ret = 0;
2962 } else {
2963 tcp_chr_disconnect(init->chr);
2964 return FALSE;
2967 init->buflen -= ret;
2969 if (init->buflen == 0) {
2970 tcp_chr_connect(init->chr);
2971 return FALSE;
2974 memmove(init->buf, init->buf + ret, init->buflen);
2976 return TRUE;
2979 static void tcp_chr_telnet_init(CharDriverState *chr)
2981 TCPCharDriver *s = chr->opaque;
2982 TCPCharDriverTelnetInit *init =
2983 g_new0(TCPCharDriverTelnetInit, 1);
2984 size_t n = 0;
2986 init->chr = chr;
2987 init->buflen = 12;
2989 #define IACSET(x, a, b, c) \
2990 do { \
2991 x[n++] = a; \
2992 x[n++] = b; \
2993 x[n++] = c; \
2994 } while (0)
2996 /* Prep the telnet negotion to put telnet in binary,
2997 * no echo, single char mode */
2998 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2999 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3000 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3001 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3003 #undef IACSET
3005 qio_channel_add_watch(
3006 s->ioc, G_IO_OUT,
3007 tcp_chr_telnet_init_io,
3008 init, NULL);
3012 static void tcp_chr_tls_handshake(Object *source,
3013 Error *err,
3014 gpointer user_data)
3016 CharDriverState *chr = user_data;
3017 TCPCharDriver *s = chr->opaque;
3019 if (err) {
3020 tcp_chr_disconnect(chr);
3021 } else {
3022 if (s->do_telnetopt) {
3023 tcp_chr_telnet_init(chr);
3024 } else {
3025 tcp_chr_connect(chr);
3031 static void tcp_chr_tls_init(CharDriverState *chr)
3033 TCPCharDriver *s = chr->opaque;
3034 QIOChannelTLS *tioc;
3035 Error *err = NULL;
3037 if (s->is_listen) {
3038 tioc = qio_channel_tls_new_server(
3039 s->ioc, s->tls_creds,
3040 NULL, /* XXX Use an ACL */
3041 &err);
3042 } else {
3043 tioc = qio_channel_tls_new_client(
3044 s->ioc, s->tls_creds,
3045 s->addr->u.inet->host,
3046 &err);
3048 if (tioc == NULL) {
3049 error_free(err);
3050 tcp_chr_disconnect(chr);
3052 object_unref(OBJECT(s->ioc));
3053 s->ioc = QIO_CHANNEL(tioc);
3055 qio_channel_tls_handshake(tioc,
3056 tcp_chr_tls_handshake,
3057 chr,
3058 NULL);
3062 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3064 TCPCharDriver *s = chr->opaque;
3065 if (s->ioc != NULL) {
3066 return -1;
3069 s->ioc = QIO_CHANNEL(sioc);
3070 object_ref(OBJECT(sioc));
3071 s->sioc = sioc;
3072 object_ref(OBJECT(sioc));
3074 if (s->do_nodelay) {
3075 qio_channel_set_delay(s->ioc, false);
3077 if (s->listen_tag) {
3078 g_source_remove(s->listen_tag);
3079 s->listen_tag = 0;
3082 if (s->tls_creds) {
3083 tcp_chr_tls_init(chr);
3084 } else {
3085 if (s->do_telnetopt) {
3086 tcp_chr_telnet_init(chr);
3087 } else {
3088 tcp_chr_connect(chr);
3092 return 0;
3096 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3098 int ret;
3099 QIOChannelSocket *sioc;
3101 sioc = qio_channel_socket_new_fd(fd, NULL);
3102 if (!sioc) {
3103 return -1;
3105 qio_channel_set_blocking(QIO_CHANNEL(sioc), false, NULL);
3106 ret = tcp_chr_new_client(chr, sioc);
3107 object_unref(OBJECT(sioc));
3108 return ret;
3111 static gboolean tcp_chr_accept(QIOChannel *channel,
3112 GIOCondition cond,
3113 void *opaque)
3115 CharDriverState *chr = opaque;
3116 QIOChannelSocket *sioc;
3118 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3119 NULL);
3120 if (!sioc) {
3121 return TRUE;
3124 tcp_chr_new_client(chr, sioc);
3126 object_unref(OBJECT(sioc));
3128 return TRUE;
3131 static void tcp_chr_close(CharDriverState *chr)
3133 TCPCharDriver *s = chr->opaque;
3134 int i;
3136 if (s->reconnect_timer) {
3137 g_source_remove(s->reconnect_timer);
3138 s->reconnect_timer = 0;
3140 qapi_free_SocketAddress(s->addr);
3141 remove_fd_in_watch(chr);
3142 if (s->ioc) {
3143 object_unref(OBJECT(s->ioc));
3145 if (s->listen_tag) {
3146 g_source_remove(s->listen_tag);
3147 s->listen_tag = 0;
3149 if (s->listen_ioc) {
3150 object_unref(OBJECT(s->listen_ioc));
3152 if (s->read_msgfds_num) {
3153 for (i = 0; i < s->read_msgfds_num; i++) {
3154 close(s->read_msgfds[i]);
3156 g_free(s->read_msgfds);
3158 if (s->tls_creds) {
3159 object_unref(OBJECT(s->tls_creds));
3161 if (s->write_msgfds_num) {
3162 g_free(s->write_msgfds);
3164 g_free(s);
3165 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3169 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3171 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3172 CharDriverState *chr = opaque;
3173 TCPCharDriver *s = chr->opaque;
3175 if (err) {
3176 check_report_connect_error(chr, err);
3177 object_unref(src);
3178 return;
3181 s->connect_err_reported = false;
3182 tcp_chr_new_client(chr, sioc);
3183 object_unref(OBJECT(sioc));
3187 /*********************************************************/
3188 /* Ring buffer chardev */
3190 typedef struct {
3191 size_t size;
3192 size_t prod;
3193 size_t cons;
3194 uint8_t *cbuf;
3195 } RingBufCharDriver;
3197 static size_t ringbuf_count(const CharDriverState *chr)
3199 const RingBufCharDriver *d = chr->opaque;
3201 return d->prod - d->cons;
3204 /* Called with chr_write_lock held. */
3205 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3207 RingBufCharDriver *d = chr->opaque;
3208 int i;
3210 if (!buf || (len < 0)) {
3211 return -1;
3214 for (i = 0; i < len; i++ ) {
3215 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3216 if (d->prod - d->cons > d->size) {
3217 d->cons = d->prod - d->size;
3221 return 0;
3224 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3226 RingBufCharDriver *d = chr->opaque;
3227 int i;
3229 qemu_mutex_lock(&chr->chr_write_lock);
3230 for (i = 0; i < len && d->cons != d->prod; i++) {
3231 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3233 qemu_mutex_unlock(&chr->chr_write_lock);
3235 return i;
3238 static void ringbuf_chr_close(struct CharDriverState *chr)
3240 RingBufCharDriver *d = chr->opaque;
3242 g_free(d->cbuf);
3243 g_free(d);
3244 chr->opaque = NULL;
3247 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3248 ChardevBackend *backend,
3249 ChardevReturn *ret,
3250 Error **errp)
3252 ChardevRingbuf *opts = backend->u.ringbuf;
3253 ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
3254 CharDriverState *chr;
3255 RingBufCharDriver *d;
3257 chr = qemu_chr_alloc(common, errp);
3258 if (!chr) {
3259 return NULL;
3261 d = g_malloc(sizeof(*d));
3263 d->size = opts->has_size ? opts->size : 65536;
3265 /* The size must be power of 2 */
3266 if (d->size & (d->size - 1)) {
3267 error_setg(errp, "size of ringbuf chardev must be power of two");
3268 goto fail;
3271 d->prod = 0;
3272 d->cons = 0;
3273 d->cbuf = g_malloc0(d->size);
3275 chr->opaque = d;
3276 chr->chr_write = ringbuf_chr_write;
3277 chr->chr_close = ringbuf_chr_close;
3279 return chr;
3281 fail:
3282 g_free(d);
3283 qemu_chr_free_common(chr);
3284 return NULL;
3287 bool chr_is_ringbuf(const CharDriverState *chr)
3289 return chr->chr_write == ringbuf_chr_write;
3292 void qmp_ringbuf_write(const char *device, const char *data,
3293 bool has_format, enum DataFormat format,
3294 Error **errp)
3296 CharDriverState *chr;
3297 const uint8_t *write_data;
3298 int ret;
3299 gsize write_count;
3301 chr = qemu_chr_find(device);
3302 if (!chr) {
3303 error_setg(errp, "Device '%s' not found", device);
3304 return;
3307 if (!chr_is_ringbuf(chr)) {
3308 error_setg(errp,"%s is not a ringbuf device", device);
3309 return;
3312 if (has_format && (format == DATA_FORMAT_BASE64)) {
3313 write_data = qbase64_decode(data, -1,
3314 &write_count,
3315 errp);
3316 if (!write_data) {
3317 return;
3319 } else {
3320 write_data = (uint8_t *)data;
3321 write_count = strlen(data);
3324 ret = ringbuf_chr_write(chr, write_data, write_count);
3326 if (write_data != (uint8_t *)data) {
3327 g_free((void *)write_data);
3330 if (ret < 0) {
3331 error_setg(errp, "Failed to write to device %s", device);
3332 return;
3336 char *qmp_ringbuf_read(const char *device, int64_t size,
3337 bool has_format, enum DataFormat format,
3338 Error **errp)
3340 CharDriverState *chr;
3341 uint8_t *read_data;
3342 size_t count;
3343 char *data;
3345 chr = qemu_chr_find(device);
3346 if (!chr) {
3347 error_setg(errp, "Device '%s' not found", device);
3348 return NULL;
3351 if (!chr_is_ringbuf(chr)) {
3352 error_setg(errp,"%s is not a ringbuf device", device);
3353 return NULL;
3356 if (size <= 0) {
3357 error_setg(errp, "size must be greater than zero");
3358 return NULL;
3361 count = ringbuf_count(chr);
3362 size = size > count ? count : size;
3363 read_data = g_malloc(size + 1);
3365 ringbuf_chr_read(chr, read_data, size);
3367 if (has_format && (format == DATA_FORMAT_BASE64)) {
3368 data = g_base64_encode(read_data, size);
3369 g_free(read_data);
3370 } else {
3372 * FIXME should read only complete, valid UTF-8 characters up
3373 * to @size bytes. Invalid sequences should be replaced by a
3374 * suitable replacement character. Except when (and only
3375 * when) ring buffer lost characters since last read, initial
3376 * continuation characters should be dropped.
3378 read_data[size] = 0;
3379 data = (char *)read_data;
3382 return data;
3385 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3387 char host[65], port[33], width[8], height[8];
3388 int pos;
3389 const char *p;
3390 QemuOpts *opts;
3391 Error *local_err = NULL;
3393 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3394 if (local_err) {
3395 error_report_err(local_err);
3396 return NULL;
3399 if (strstart(filename, "mon:", &p)) {
3400 filename = p;
3401 qemu_opt_set(opts, "mux", "on", &error_abort);
3402 if (strcmp(filename, "stdio") == 0) {
3403 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3404 * but pass it to the guest. Handle this only for compat syntax,
3405 * for -chardev syntax we have special option for this.
3406 * This is what -nographic did, redirecting+muxing serial+monitor
3407 * to stdio causing Ctrl+C to be passed to guest. */
3408 qemu_opt_set(opts, "signal", "off", &error_abort);
3412 if (strcmp(filename, "null") == 0 ||
3413 strcmp(filename, "pty") == 0 ||
3414 strcmp(filename, "msmouse") == 0 ||
3415 strcmp(filename, "braille") == 0 ||
3416 strcmp(filename, "testdev") == 0 ||
3417 strcmp(filename, "stdio") == 0) {
3418 qemu_opt_set(opts, "backend", filename, &error_abort);
3419 return opts;
3421 if (strstart(filename, "vc", &p)) {
3422 qemu_opt_set(opts, "backend", "vc", &error_abort);
3423 if (*p == ':') {
3424 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3425 /* pixels */
3426 qemu_opt_set(opts, "width", width, &error_abort);
3427 qemu_opt_set(opts, "height", height, &error_abort);
3428 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3429 /* chars */
3430 qemu_opt_set(opts, "cols", width, &error_abort);
3431 qemu_opt_set(opts, "rows", height, &error_abort);
3432 } else {
3433 goto fail;
3436 return opts;
3438 if (strcmp(filename, "con:") == 0) {
3439 qemu_opt_set(opts, "backend", "console", &error_abort);
3440 return opts;
3442 if (strstart(filename, "COM", NULL)) {
3443 qemu_opt_set(opts, "backend", "serial", &error_abort);
3444 qemu_opt_set(opts, "path", filename, &error_abort);
3445 return opts;
3447 if (strstart(filename, "file:", &p)) {
3448 qemu_opt_set(opts, "backend", "file", &error_abort);
3449 qemu_opt_set(opts, "path", p, &error_abort);
3450 return opts;
3452 if (strstart(filename, "pipe:", &p)) {
3453 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3454 qemu_opt_set(opts, "path", p, &error_abort);
3455 return opts;
3457 if (strstart(filename, "tcp:", &p) ||
3458 strstart(filename, "telnet:", &p)) {
3459 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3460 host[0] = 0;
3461 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3462 goto fail;
3464 qemu_opt_set(opts, "backend", "socket", &error_abort);
3465 qemu_opt_set(opts, "host", host, &error_abort);
3466 qemu_opt_set(opts, "port", port, &error_abort);
3467 if (p[pos] == ',') {
3468 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3469 if (local_err) {
3470 error_report_err(local_err);
3471 goto fail;
3474 if (strstart(filename, "telnet:", &p))
3475 qemu_opt_set(opts, "telnet", "on", &error_abort);
3476 return opts;
3478 if (strstart(filename, "udp:", &p)) {
3479 qemu_opt_set(opts, "backend", "udp", &error_abort);
3480 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3481 host[0] = 0;
3482 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3483 goto fail;
3486 qemu_opt_set(opts, "host", host, &error_abort);
3487 qemu_opt_set(opts, "port", port, &error_abort);
3488 if (p[pos] == '@') {
3489 p += pos + 1;
3490 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3491 host[0] = 0;
3492 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3493 goto fail;
3496 qemu_opt_set(opts, "localaddr", host, &error_abort);
3497 qemu_opt_set(opts, "localport", port, &error_abort);
3499 return opts;
3501 if (strstart(filename, "unix:", &p)) {
3502 qemu_opt_set(opts, "backend", "socket", &error_abort);
3503 qemu_opts_do_parse(opts, p, "path", &local_err);
3504 if (local_err) {
3505 error_report_err(local_err);
3506 goto fail;
3508 return opts;
3510 if (strstart(filename, "/dev/parport", NULL) ||
3511 strstart(filename, "/dev/ppi", NULL)) {
3512 qemu_opt_set(opts, "backend", "parport", &error_abort);
3513 qemu_opt_set(opts, "path", filename, &error_abort);
3514 return opts;
3516 if (strstart(filename, "/dev/", NULL)) {
3517 qemu_opt_set(opts, "backend", "tty", &error_abort);
3518 qemu_opt_set(opts, "path", filename, &error_abort);
3519 return opts;
3522 fail:
3523 qemu_opts_del(opts);
3524 return NULL;
3527 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3529 const char *logfile = qemu_opt_get(opts, "logfile");
3531 backend->has_logfile = logfile != NULL;
3532 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3534 backend->has_logappend = true;
3535 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3539 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3540 Error **errp)
3542 const char *path = qemu_opt_get(opts, "path");
3543 ChardevFile *file;
3545 if (path == NULL) {
3546 error_setg(errp, "chardev: file: no filename given");
3547 return;
3549 file = backend->u.file = g_new0(ChardevFile, 1);
3550 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3551 file->out = g_strdup(path);
3553 file->has_append = true;
3554 file->append = qemu_opt_get_bool(opts, "append", false);
3557 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3558 Error **errp)
3560 ChardevStdio *stdio;
3562 stdio = backend->u.stdio = g_new0(ChardevStdio, 1);
3563 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3564 stdio->has_signal = true;
3565 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");
3573 ChardevHostdev *serial;
3575 if (device == NULL) {
3576 error_setg(errp, "chardev: serial/tty: no device path given");
3577 return;
3579 serial = backend->u.serial = g_new0(ChardevHostdev, 1);
3580 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3581 serial->device = g_strdup(device);
3583 #endif
3585 #ifdef HAVE_CHARDEV_PARPORT
3586 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3587 Error **errp)
3589 const char *device = qemu_opt_get(opts, "path");
3590 ChardevHostdev *parallel;
3592 if (device == NULL) {
3593 error_setg(errp, "chardev: parallel: no device path given");
3594 return;
3596 parallel = backend->u.parallel = g_new0(ChardevHostdev, 1);
3597 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3598 parallel->device = g_strdup(device);
3600 #endif
3602 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3603 Error **errp)
3605 const char *device = qemu_opt_get(opts, "path");
3606 ChardevHostdev *dev;
3608 if (device == NULL) {
3609 error_setg(errp, "chardev: pipe: no device path given");
3610 return;
3612 dev = backend->u.pipe = g_new0(ChardevHostdev, 1);
3613 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3614 dev->device = g_strdup(device);
3617 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3618 Error **errp)
3620 int val;
3621 ChardevRingbuf *ringbuf;
3623 ringbuf = backend->u.ringbuf = g_new0(ChardevRingbuf, 1);
3624 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3626 val = qemu_opt_get_size(opts, "size", 0);
3627 if (val != 0) {
3628 ringbuf->has_size = true;
3629 ringbuf->size = val;
3633 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3634 Error **errp)
3636 const char *chardev = qemu_opt_get(opts, "chardev");
3637 ChardevMux *mux;
3639 if (chardev == NULL) {
3640 error_setg(errp, "chardev: mux: no chardev given");
3641 return;
3643 mux = backend->u.mux = g_new0(ChardevMux, 1);
3644 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
3645 mux->chardev = g_strdup(chardev);
3648 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3649 Error **errp)
3651 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3652 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3653 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3654 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3655 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3656 const char *path = qemu_opt_get(opts, "path");
3657 const char *host = qemu_opt_get(opts, "host");
3658 const char *port = qemu_opt_get(opts, "port");
3659 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3660 SocketAddress *addr;
3661 ChardevSocket *sock;
3663 if (!path) {
3664 if (!host) {
3665 error_setg(errp, "chardev: socket: no host given");
3666 return;
3668 if (!port) {
3669 error_setg(errp, "chardev: socket: no port given");
3670 return;
3672 } else {
3673 if (tls_creds) {
3674 error_setg(errp, "TLS can only be used over TCP socket");
3675 return;
3679 sock = backend->u.socket = g_new0(ChardevSocket, 1);
3680 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
3682 sock->has_nodelay = true;
3683 sock->nodelay = do_nodelay;
3684 sock->has_server = true;
3685 sock->server = is_listen;
3686 sock->has_telnet = true;
3687 sock->telnet = is_telnet;
3688 sock->has_wait = true;
3689 sock->wait = is_waitconnect;
3690 sock->has_reconnect = true;
3691 sock->reconnect = reconnect;
3692 sock->tls_creds = g_strdup(tls_creds);
3694 addr = g_new0(SocketAddress, 1);
3695 if (path) {
3696 UnixSocketAddress *q_unix;
3697 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3698 q_unix = addr->u.q_unix = g_new0(UnixSocketAddress, 1);
3699 q_unix->path = g_strdup(path);
3700 } else {
3701 addr->type = SOCKET_ADDRESS_KIND_INET;
3702 addr->u.inet = g_new(InetSocketAddress, 1);
3703 *addr->u.inet = (InetSocketAddress) {
3704 .host = g_strdup(host),
3705 .port = g_strdup(port),
3706 .has_to = qemu_opt_get(opts, "to"),
3707 .to = qemu_opt_get_number(opts, "to", 0),
3708 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3709 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3710 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3711 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3714 sock->addr = addr;
3717 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3718 Error **errp)
3720 const char *host = qemu_opt_get(opts, "host");
3721 const char *port = qemu_opt_get(opts, "port");
3722 const char *localaddr = qemu_opt_get(opts, "localaddr");
3723 const char *localport = qemu_opt_get(opts, "localport");
3724 bool has_local = false;
3725 SocketAddress *addr;
3726 ChardevUdp *udp;
3728 if (host == NULL || strlen(host) == 0) {
3729 host = "localhost";
3731 if (port == NULL || strlen(port) == 0) {
3732 error_setg(errp, "chardev: udp: remote port not specified");
3733 return;
3735 if (localport == NULL || strlen(localport) == 0) {
3736 localport = "0";
3737 } else {
3738 has_local = true;
3740 if (localaddr == NULL || strlen(localaddr) == 0) {
3741 localaddr = "";
3742 } else {
3743 has_local = true;
3746 udp = backend->u.udp = g_new0(ChardevUdp, 1);
3747 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
3749 addr = g_new0(SocketAddress, 1);
3750 addr->type = SOCKET_ADDRESS_KIND_INET;
3751 addr->u.inet = g_new(InetSocketAddress, 1);
3752 *addr->u.inet = (InetSocketAddress) {
3753 .host = g_strdup(host),
3754 .port = g_strdup(port),
3755 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3756 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3757 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3758 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3760 udp->remote = addr;
3762 if (has_local) {
3763 udp->has_local = true;
3764 addr = g_new0(SocketAddress, 1);
3765 addr->type = SOCKET_ADDRESS_KIND_INET;
3766 addr->u.inet = g_new(InetSocketAddress, 1);
3767 *addr->u.inet = (InetSocketAddress) {
3768 .host = g_strdup(localaddr),
3769 .port = g_strdup(localport),
3771 udp->local = addr;
3775 typedef struct CharDriver {
3776 const char *name;
3777 ChardevBackendKind kind;
3778 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3779 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3780 ChardevReturn *ret, Error **errp);
3781 } CharDriver;
3783 static GSList *backends;
3785 void register_char_driver(const char *name, ChardevBackendKind kind,
3786 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3787 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3788 ChardevReturn *ret, Error **errp))
3790 CharDriver *s;
3792 s = g_malloc0(sizeof(*s));
3793 s->name = g_strdup(name);
3794 s->kind = kind;
3795 s->parse = parse;
3796 s->create = create;
3798 backends = g_slist_append(backends, s);
3801 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3802 void (*init)(struct CharDriverState *s),
3803 Error **errp)
3805 Error *local_err = NULL;
3806 CharDriver *cd;
3807 CharDriverState *chr;
3808 GSList *i;
3809 ChardevReturn *ret = NULL;
3810 ChardevBackend *backend;
3811 const char *id = qemu_opts_id(opts);
3812 char *bid = NULL;
3814 if (id == NULL) {
3815 error_setg(errp, "chardev: no id specified");
3816 goto err;
3819 if (qemu_opt_get(opts, "backend") == NULL) {
3820 error_setg(errp, "chardev: \"%s\" missing backend",
3821 qemu_opts_id(opts));
3822 goto err;
3824 for (i = backends; i; i = i->next) {
3825 cd = i->data;
3827 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3828 break;
3831 if (i == NULL) {
3832 error_setg(errp, "chardev: backend \"%s\" not found",
3833 qemu_opt_get(opts, "backend"));
3834 goto err;
3837 backend = g_new0(ChardevBackend, 1);
3839 if (qemu_opt_get_bool(opts, "mux", 0)) {
3840 bid = g_strdup_printf("%s-base", id);
3843 chr = NULL;
3844 backend->type = cd->kind;
3845 if (cd->parse) {
3846 cd->parse(opts, backend, &local_err);
3847 if (local_err) {
3848 error_propagate(errp, local_err);
3849 goto qapi_out;
3851 } else {
3852 ChardevCommon *cc = g_new0(ChardevCommon, 1);
3853 qemu_chr_parse_common(opts, cc);
3854 backend->u.null = cc; /* Any ChardevCommon member would work */
3857 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3858 if (!ret) {
3859 goto qapi_out;
3862 if (bid) {
3863 qapi_free_ChardevBackend(backend);
3864 qapi_free_ChardevReturn(ret);
3865 backend = g_new0(ChardevBackend, 1);
3866 backend->u.mux = g_new0(ChardevMux, 1);
3867 backend->type = CHARDEV_BACKEND_KIND_MUX;
3868 backend->u.mux->chardev = g_strdup(bid);
3869 ret = qmp_chardev_add(id, backend, errp);
3870 if (!ret) {
3871 chr = qemu_chr_find(bid);
3872 qemu_chr_delete(chr);
3873 chr = NULL;
3874 goto qapi_out;
3878 chr = qemu_chr_find(id);
3879 chr->opts = opts;
3881 qapi_out:
3882 qapi_free_ChardevBackend(backend);
3883 qapi_free_ChardevReturn(ret);
3884 g_free(bid);
3885 return chr;
3887 err:
3888 qemu_opts_del(opts);
3889 return NULL;
3892 CharDriverState *qemu_chr_new_noreplay(const char *label, const char *filename,
3893 void (*init)(struct CharDriverState *s))
3895 const char *p;
3896 CharDriverState *chr;
3897 QemuOpts *opts;
3898 Error *err = NULL;
3900 if (strstart(filename, "chardev:", &p)) {
3901 return qemu_chr_find(p);
3904 opts = qemu_chr_parse_compat(label, filename);
3905 if (!opts)
3906 return NULL;
3908 chr = qemu_chr_new_from_opts(opts, init, &err);
3909 if (err) {
3910 error_report_err(err);
3912 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3913 qemu_chr_fe_claim_no_fail(chr);
3914 monitor_init(chr, MONITOR_USE_READLINE);
3916 return chr;
3919 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3921 CharDriverState *chr;
3922 chr = qemu_chr_new_noreplay(label, filename, init);
3923 if (chr) {
3924 chr->replay = replay_mode != REPLAY_MODE_NONE;
3925 if (chr->replay && chr->chr_ioctl) {
3926 fprintf(stderr,
3927 "Replay: ioctl is not supported for serial devices yet\n");
3929 replay_register_char_driver(chr);
3931 return chr;
3934 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3936 if (chr->chr_set_echo) {
3937 chr->chr_set_echo(chr, echo);
3941 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3943 if (chr->fe_open == fe_open) {
3944 return;
3946 chr->fe_open = fe_open;
3947 if (chr->chr_set_fe_open) {
3948 chr->chr_set_fe_open(chr, fe_open);
3952 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3954 if (chr->chr_fe_event) {
3955 chr->chr_fe_event(chr, event);
3959 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3960 GIOFunc func, void *user_data)
3962 GSource *src;
3963 guint tag;
3965 if (s->chr_add_watch == NULL) {
3966 return -ENOSYS;
3969 src = s->chr_add_watch(s, cond);
3970 if (!src) {
3971 return -EINVAL;
3974 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3975 tag = g_source_attach(src, NULL);
3976 g_source_unref(src);
3978 return tag;
3981 int qemu_chr_fe_claim(CharDriverState *s)
3983 if (s->avail_connections < 1) {
3984 return -1;
3986 s->avail_connections--;
3987 return 0;
3990 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3992 if (qemu_chr_fe_claim(s) != 0) {
3993 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3994 __func__, s->label);
3995 exit(1);
3999 void qemu_chr_fe_release(CharDriverState *s)
4001 s->avail_connections++;
4004 static void qemu_chr_free_common(CharDriverState *chr)
4006 g_free(chr->filename);
4007 g_free(chr->label);
4008 qemu_opts_del(chr->opts);
4009 if (chr->logfd != -1) {
4010 close(chr->logfd);
4012 qemu_mutex_destroy(&chr->chr_write_lock);
4013 g_free(chr);
4016 void qemu_chr_free(CharDriverState *chr)
4018 if (chr->chr_close) {
4019 chr->chr_close(chr);
4021 qemu_chr_free_common(chr);
4024 void qemu_chr_delete(CharDriverState *chr)
4026 QTAILQ_REMOVE(&chardevs, chr, next);
4027 qemu_chr_free(chr);
4030 ChardevInfoList *qmp_query_chardev(Error **errp)
4032 ChardevInfoList *chr_list = NULL;
4033 CharDriverState *chr;
4035 QTAILQ_FOREACH(chr, &chardevs, next) {
4036 ChardevInfoList *info = g_malloc0(sizeof(*info));
4037 info->value = g_malloc0(sizeof(*info->value));
4038 info->value->label = g_strdup(chr->label);
4039 info->value->filename = g_strdup(chr->filename);
4040 info->value->frontend_open = chr->fe_open;
4042 info->next = chr_list;
4043 chr_list = info;
4046 return chr_list;
4049 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4051 ChardevBackendInfoList *backend_list = NULL;
4052 CharDriver *c = NULL;
4053 GSList *i = NULL;
4055 for (i = backends; i; i = i->next) {
4056 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4057 c = i->data;
4058 info->value = g_malloc0(sizeof(*info->value));
4059 info->value->name = g_strdup(c->name);
4061 info->next = backend_list;
4062 backend_list = info;
4065 return backend_list;
4068 CharDriverState *qemu_chr_find(const char *name)
4070 CharDriverState *chr;
4072 QTAILQ_FOREACH(chr, &chardevs, next) {
4073 if (strcmp(chr->label, name) != 0)
4074 continue;
4075 return chr;
4077 return NULL;
4080 /* Get a character (serial) device interface. */
4081 CharDriverState *qemu_char_get_next_serial(void)
4083 static int next_serial;
4084 CharDriverState *chr;
4086 /* FIXME: This function needs to go away: use chardev properties! */
4088 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
4089 chr = serial_hds[next_serial++];
4090 qemu_chr_fe_claim_no_fail(chr);
4091 return chr;
4093 return NULL;
4096 QemuOptsList qemu_chardev_opts = {
4097 .name = "chardev",
4098 .implied_opt_name = "backend",
4099 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4100 .desc = {
4102 .name = "backend",
4103 .type = QEMU_OPT_STRING,
4105 .name = "path",
4106 .type = QEMU_OPT_STRING,
4108 .name = "host",
4109 .type = QEMU_OPT_STRING,
4111 .name = "port",
4112 .type = QEMU_OPT_STRING,
4114 .name = "localaddr",
4115 .type = QEMU_OPT_STRING,
4117 .name = "localport",
4118 .type = QEMU_OPT_STRING,
4120 .name = "to",
4121 .type = QEMU_OPT_NUMBER,
4123 .name = "ipv4",
4124 .type = QEMU_OPT_BOOL,
4126 .name = "ipv6",
4127 .type = QEMU_OPT_BOOL,
4129 .name = "wait",
4130 .type = QEMU_OPT_BOOL,
4132 .name = "server",
4133 .type = QEMU_OPT_BOOL,
4135 .name = "delay",
4136 .type = QEMU_OPT_BOOL,
4138 .name = "reconnect",
4139 .type = QEMU_OPT_NUMBER,
4141 .name = "telnet",
4142 .type = QEMU_OPT_BOOL,
4144 .name = "tls-creds",
4145 .type = QEMU_OPT_STRING,
4147 .name = "width",
4148 .type = QEMU_OPT_NUMBER,
4150 .name = "height",
4151 .type = QEMU_OPT_NUMBER,
4153 .name = "cols",
4154 .type = QEMU_OPT_NUMBER,
4156 .name = "rows",
4157 .type = QEMU_OPT_NUMBER,
4159 .name = "mux",
4160 .type = QEMU_OPT_BOOL,
4162 .name = "signal",
4163 .type = QEMU_OPT_BOOL,
4165 .name = "name",
4166 .type = QEMU_OPT_STRING,
4168 .name = "debug",
4169 .type = QEMU_OPT_NUMBER,
4171 .name = "size",
4172 .type = QEMU_OPT_SIZE,
4174 .name = "chardev",
4175 .type = QEMU_OPT_STRING,
4177 .name = "append",
4178 .type = QEMU_OPT_BOOL,
4180 .name = "logfile",
4181 .type = QEMU_OPT_STRING,
4183 .name = "logappend",
4184 .type = QEMU_OPT_BOOL,
4186 { /* end of list */ }
4190 #ifdef _WIN32
4192 static CharDriverState *qmp_chardev_open_file(const char *id,
4193 ChardevBackend *backend,
4194 ChardevReturn *ret,
4195 Error **errp)
4197 ChardevFile *file = backend->u.file;
4198 ChardevCommon *common = qapi_ChardevFile_base(file);
4199 HANDLE out;
4201 if (file->has_in) {
4202 error_setg(errp, "input file not supported");
4203 return NULL;
4206 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
4207 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
4208 if (out == INVALID_HANDLE_VALUE) {
4209 error_setg(errp, "open %s failed", file->out);
4210 return NULL;
4212 return qemu_chr_open_win_file(out, common, errp);
4215 static CharDriverState *qmp_chardev_open_serial(const char *id,
4216 ChardevBackend *backend,
4217 ChardevReturn *ret,
4218 Error **errp)
4220 ChardevHostdev *serial = backend->u.serial;
4221 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4222 return qemu_chr_open_win_path(serial->device, common, errp);
4225 #else /* WIN32 */
4227 static int qmp_chardev_open_file_source(char *src, int flags,
4228 Error **errp)
4230 int fd = -1;
4232 TFR(fd = qemu_open(src, flags, 0666));
4233 if (fd == -1) {
4234 error_setg_file_open(errp, errno, src);
4236 return fd;
4239 static CharDriverState *qmp_chardev_open_file(const char *id,
4240 ChardevBackend *backend,
4241 ChardevReturn *ret,
4242 Error **errp)
4244 ChardevFile *file = backend->u.file;
4245 ChardevCommon *common = qapi_ChardevFile_base(file);
4246 int flags, in = -1, out;
4248 flags = O_WRONLY | O_CREAT | O_BINARY;
4249 if (file->has_append && file->append) {
4250 flags |= O_APPEND;
4251 } else {
4252 flags |= O_TRUNC;
4255 out = qmp_chardev_open_file_source(file->out, flags, errp);
4256 if (out < 0) {
4257 return NULL;
4260 if (file->has_in) {
4261 flags = O_RDONLY;
4262 in = qmp_chardev_open_file_source(file->in, flags, errp);
4263 if (in < 0) {
4264 qemu_close(out);
4265 return NULL;
4269 return qemu_chr_open_fd(in, out, common, errp);
4272 #ifdef HAVE_CHARDEV_SERIAL
4273 static CharDriverState *qmp_chardev_open_serial(const char *id,
4274 ChardevBackend *backend,
4275 ChardevReturn *ret,
4276 Error **errp)
4278 ChardevHostdev *serial = backend->u.serial;
4279 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4280 int fd;
4282 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4283 if (fd < 0) {
4284 return NULL;
4286 qemu_set_nonblock(fd);
4287 return qemu_chr_open_tty_fd(fd, common, errp);
4289 #endif
4291 #ifdef HAVE_CHARDEV_PARPORT
4292 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4293 ChardevBackend *backend,
4294 ChardevReturn *ret,
4295 Error **errp)
4297 ChardevHostdev *parallel = backend->u.parallel;
4298 ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
4299 int fd;
4301 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4302 if (fd < 0) {
4303 return NULL;
4305 return qemu_chr_open_pp_fd(fd, common, errp);
4307 #endif
4309 #endif /* WIN32 */
4311 static gboolean socket_reconnect_timeout(gpointer opaque)
4313 CharDriverState *chr = opaque;
4314 TCPCharDriver *s = chr->opaque;
4315 QIOChannelSocket *sioc;
4317 s->reconnect_timer = 0;
4319 if (chr->be_open) {
4320 return false;
4323 sioc = qio_channel_socket_new();
4324 qio_channel_socket_connect_async(sioc, s->addr,
4325 qemu_chr_socket_connected,
4326 chr, NULL);
4328 return false;
4331 static CharDriverState *qmp_chardev_open_socket(const char *id,
4332 ChardevBackend *backend,
4333 ChardevReturn *ret,
4334 Error **errp)
4336 CharDriverState *chr;
4337 TCPCharDriver *s;
4338 ChardevSocket *sock = backend->u.socket;
4339 SocketAddress *addr = sock->addr;
4340 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4341 bool is_listen = sock->has_server ? sock->server : true;
4342 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4343 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4344 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4345 ChardevCommon *common = qapi_ChardevSocket_base(sock);
4346 QIOChannelSocket *sioc = NULL;
4348 chr = qemu_chr_alloc(common, errp);
4349 if (!chr) {
4350 return NULL;
4352 s = g_new0(TCPCharDriver, 1);
4354 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4355 s->is_listen = is_listen;
4356 s->is_telnet = is_telnet;
4357 s->do_nodelay = do_nodelay;
4358 if (sock->tls_creds) {
4359 Object *creds;
4360 creds = object_resolve_path_component(
4361 object_get_objects_root(), sock->tls_creds);
4362 if (!creds) {
4363 error_setg(errp, "No TLS credentials with id '%s'",
4364 sock->tls_creds);
4365 goto error;
4367 s->tls_creds = (QCryptoTLSCreds *)
4368 object_dynamic_cast(creds,
4369 TYPE_QCRYPTO_TLS_CREDS);
4370 if (!s->tls_creds) {
4371 error_setg(errp, "Object with id '%s' is not TLS credentials",
4372 sock->tls_creds);
4373 goto error;
4375 object_ref(OBJECT(s->tls_creds));
4376 if (is_listen) {
4377 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4378 error_setg(errp, "%s",
4379 "Expected TLS credentials for server endpoint");
4380 goto error;
4382 } else {
4383 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4384 error_setg(errp, "%s",
4385 "Expected TLS credentials for client endpoint");
4386 goto error;
4391 qapi_copy_SocketAddress(&s->addr, sock->addr);
4393 chr->opaque = s;
4394 chr->chr_write = tcp_chr_write;
4395 chr->chr_sync_read = tcp_chr_sync_read;
4396 chr->chr_close = tcp_chr_close;
4397 chr->get_msgfds = tcp_get_msgfds;
4398 chr->set_msgfds = tcp_set_msgfds;
4399 chr->chr_add_client = tcp_chr_add_client;
4400 chr->chr_add_watch = tcp_chr_add_watch;
4401 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4402 /* be isn't opened until we get a connection */
4403 chr->explicit_be_open = true;
4405 chr->filename = SocketAddress_to_str("disconnected:",
4406 addr, is_listen, is_telnet);
4408 if (is_listen) {
4409 if (is_telnet) {
4410 s->do_telnetopt = 1;
4412 } else if (reconnect > 0) {
4413 s->reconnect_time = reconnect;
4416 sioc = qio_channel_socket_new();
4417 if (s->reconnect_time) {
4418 qio_channel_socket_connect_async(sioc, s->addr,
4419 qemu_chr_socket_connected,
4420 chr, NULL);
4421 } else if (s->is_listen) {
4422 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4423 goto error;
4425 s->listen_ioc = sioc;
4426 if (is_waitconnect) {
4427 fprintf(stderr, "QEMU waiting for connection on: %s\n",
4428 chr->filename);
4429 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
4431 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
4432 if (!s->ioc) {
4433 s->listen_tag = qio_channel_add_watch(
4434 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
4436 } else {
4437 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
4438 goto error;
4440 tcp_chr_new_client(chr, sioc);
4441 object_unref(OBJECT(sioc));
4444 return chr;
4446 error:
4447 if (sioc) {
4448 object_unref(OBJECT(sioc));
4450 if (s->tls_creds) {
4451 object_unref(OBJECT(s->tls_creds));
4453 g_free(s);
4454 qemu_chr_free_common(chr);
4455 return NULL;
4458 static CharDriverState *qmp_chardev_open_udp(const char *id,
4459 ChardevBackend *backend,
4460 ChardevReturn *ret,
4461 Error **errp)
4463 ChardevUdp *udp = backend->u.udp;
4464 ChardevCommon *common = qapi_ChardevUdp_base(udp);
4465 QIOChannelSocket *sioc = qio_channel_socket_new();
4467 if (qio_channel_socket_dgram_sync(sioc,
4468 udp->local, udp->remote,
4469 errp) < 0) {
4470 object_unref(OBJECT(sioc));
4471 return NULL;
4473 return qemu_chr_open_udp(sioc, common, errp);
4476 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4477 Error **errp)
4479 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4480 CharDriverState *chr = NULL;
4481 Error *local_err = NULL;
4482 GSList *i;
4483 CharDriver *cd;
4485 chr = qemu_chr_find(id);
4486 if (chr) {
4487 error_setg(errp, "Chardev '%s' already exists", id);
4488 g_free(ret);
4489 return NULL;
4492 for (i = backends; i; i = i->next) {
4493 cd = i->data;
4495 if (cd->kind == backend->type) {
4496 chr = cd->create(id, backend, ret, &local_err);
4497 if (local_err) {
4498 error_propagate(errp, local_err);
4499 goto out_error;
4501 break;
4505 if (chr == NULL) {
4506 assert(!i);
4507 error_setg(errp, "chardev backend not available");
4508 goto out_error;
4511 chr->label = g_strdup(id);
4512 chr->avail_connections =
4513 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4514 if (!chr->filename) {
4515 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4517 if (!chr->explicit_be_open) {
4518 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4520 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4521 return ret;
4523 out_error:
4524 g_free(ret);
4525 return NULL;
4528 void qmp_chardev_remove(const char *id, Error **errp)
4530 CharDriverState *chr;
4532 chr = qemu_chr_find(id);
4533 if (chr == NULL) {
4534 error_setg(errp, "Chardev '%s' not found", id);
4535 return;
4537 if (chr->chr_can_read || chr->chr_read ||
4538 chr->chr_event || chr->handler_opaque) {
4539 error_setg(errp, "Chardev '%s' is busy", id);
4540 return;
4542 if (chr->replay) {
4543 error_setg(errp,
4544 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4545 return;
4547 qemu_chr_delete(chr);
4550 static void register_types(void)
4552 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4553 qemu_chr_open_null);
4554 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4555 qemu_chr_parse_socket, qmp_chardev_open_socket);
4556 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4557 qmp_chardev_open_udp);
4558 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4559 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4560 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4561 qemu_chr_parse_file_out, qmp_chardev_open_file);
4562 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4563 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4564 #if defined HAVE_CHARDEV_SERIAL
4565 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4566 qemu_chr_parse_serial, qmp_chardev_open_serial);
4567 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4568 qemu_chr_parse_serial, qmp_chardev_open_serial);
4569 #endif
4570 #ifdef HAVE_CHARDEV_PARPORT
4571 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4572 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4573 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4574 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4575 #endif
4576 #ifdef HAVE_CHARDEV_PTY
4577 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4578 qemu_chr_open_pty);
4579 #endif
4580 #ifdef _WIN32
4581 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4582 qemu_chr_open_win_con);
4583 #endif
4584 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4585 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4586 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4587 qemu_chr_open_mux);
4588 /* Bug-compatibility: */
4589 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4590 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4591 /* this must be done after machine init, since we register FEs with muxes
4592 * as part of realize functions like serial_isa_realizefn when -nographic
4593 * is specified
4595 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4598 type_init(register_types);