qapi: Allow anonymous base for flat union
[qemu/cris-port.git] / qemu-char.c
blobf90e4c1208aa9dcb7bafc2d1539de6d5b022599b
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",
102 addr->u.inet.data->host,
103 addr->u.inet.data->port,
104 is_listen ? ",server" : "");
105 break;
106 case SOCKET_ADDRESS_KIND_UNIX:
107 return g_strdup_printf("%sunix:%s%s", prefix,
108 addr->u.q_unix.data->path,
109 is_listen ? ",server" : "");
110 break;
111 case SOCKET_ADDRESS_KIND_FD:
112 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd.data->str,
113 is_listen ? ",server" : "");
114 break;
115 default:
116 abort();
120 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
121 struct sockaddr_storage *ps, socklen_t ps_len,
122 bool is_listen, bool is_telnet)
124 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
125 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
126 const char *left = "", *right = "";
128 switch (ss->ss_family) {
129 #ifndef _WIN32
130 case AF_UNIX:
131 return g_strdup_printf("unix:%s%s",
132 ((struct sockaddr_un *)(ss))->sun_path,
133 is_listen ? ",server" : "");
134 #endif
135 case AF_INET6:
136 left = "[";
137 right = "]";
138 /* fall through */
139 case AF_INET:
140 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
141 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
142 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
143 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
144 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
145 is_telnet ? "telnet" : "tcp",
146 left, shost, right, sserv,
147 is_listen ? ",server" : "",
148 left, phost, right, pserv);
150 default:
151 return g_strdup_printf("unknown");
155 /***********************************************************/
156 /* character device */
158 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
159 QTAILQ_HEAD_INITIALIZER(chardevs);
161 static void qemu_chr_free_common(CharDriverState *chr);
163 CharDriverState *qemu_chr_alloc(ChardevCommon *backend, Error **errp)
165 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
166 qemu_mutex_init(&chr->chr_write_lock);
168 if (backend->has_logfile) {
169 int flags = O_WRONLY | O_CREAT;
170 if (backend->has_logappend &&
171 backend->logappend) {
172 flags |= O_APPEND;
173 } else {
174 flags |= O_TRUNC;
176 chr->logfd = qemu_open(backend->logfile, flags, 0666);
177 if (chr->logfd < 0) {
178 error_setg_errno(errp, errno,
179 "Unable to open logfile %s",
180 backend->logfile);
181 g_free(chr);
182 return NULL;
184 } else {
185 chr->logfd = -1;
188 return chr;
191 void qemu_chr_be_event(CharDriverState *s, int event)
193 /* Keep track if the char device is open */
194 switch (event) {
195 case CHR_EVENT_OPENED:
196 s->be_open = 1;
197 break;
198 case CHR_EVENT_CLOSED:
199 s->be_open = 0;
200 break;
203 if (!s->chr_event)
204 return;
205 s->chr_event(s->handler_opaque, event);
208 void qemu_chr_be_generic_open(CharDriverState *s)
210 qemu_chr_be_event(s, CHR_EVENT_OPENED);
214 /* Not reporting errors from writing to logfile, as logs are
215 * defined to be "best effort" only */
216 static void qemu_chr_fe_write_log(CharDriverState *s,
217 const uint8_t *buf, size_t len)
219 size_t done = 0;
220 ssize_t ret;
222 if (s->logfd < 0) {
223 return;
226 while (done < len) {
227 do {
228 ret = write(s->logfd, buf + done, len - done);
229 if (ret == -1 && errno == EAGAIN) {
230 g_usleep(100);
232 } while (ret == -1 && errno == EAGAIN);
234 if (ret <= 0) {
235 return;
237 done += ret;
241 static int qemu_chr_fe_write_buffer(CharDriverState *s, const uint8_t *buf, int len, int *offset)
243 int res = 0;
244 *offset = 0;
246 qemu_mutex_lock(&s->chr_write_lock);
247 while (*offset < len) {
248 do {
249 res = s->chr_write(s, buf + *offset, len - *offset);
250 if (res == -1 && errno == EAGAIN) {
251 g_usleep(100);
253 } while (res == -1 && errno == EAGAIN);
255 if (res <= 0) {
256 break;
259 *offset += res;
261 if (*offset > 0) {
262 qemu_chr_fe_write_log(s, buf, *offset);
264 qemu_mutex_unlock(&s->chr_write_lock);
266 return res;
269 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
271 int ret;
273 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
274 int offset;
275 replay_char_write_event_load(&ret, &offset);
276 assert(offset <= len);
277 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
278 return ret;
281 qemu_mutex_lock(&s->chr_write_lock);
282 ret = s->chr_write(s, buf, len);
284 if (ret > 0) {
285 qemu_chr_fe_write_log(s, buf, ret);
288 qemu_mutex_unlock(&s->chr_write_lock);
290 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
291 replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
294 return ret;
297 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
299 int offset;
300 int res;
302 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
303 replay_char_write_event_load(&res, &offset);
304 assert(offset <= len);
305 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
306 return res;
309 res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
311 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
312 replay_char_write_event_save(res, offset);
315 if (res < 0) {
316 return res;
318 return offset;
321 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
323 int offset = 0, counter = 10;
324 int res;
326 if (!s->chr_sync_read) {
327 return 0;
330 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
331 return replay_char_read_all_load(buf);
334 while (offset < len) {
335 do {
336 res = s->chr_sync_read(s, buf + offset, len - offset);
337 if (res == -1 && errno == EAGAIN) {
338 g_usleep(100);
340 } while (res == -1 && errno == EAGAIN);
342 if (res == 0) {
343 break;
346 if (res < 0) {
347 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
348 replay_char_read_all_save_error(res);
350 return res;
353 offset += res;
355 if (!counter--) {
356 break;
360 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
361 replay_char_read_all_save_buf(buf, offset);
363 return offset;
366 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
368 int res;
369 if (!s->chr_ioctl || s->replay) {
370 res = -ENOTSUP;
371 } else {
372 res = s->chr_ioctl(s, cmd, arg);
375 return res;
378 int qemu_chr_be_can_write(CharDriverState *s)
380 if (!s->chr_can_read)
381 return 0;
382 return s->chr_can_read(s->handler_opaque);
385 void qemu_chr_be_write_impl(CharDriverState *s, uint8_t *buf, int len)
387 if (s->chr_read) {
388 s->chr_read(s->handler_opaque, buf, len);
392 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
394 if (s->replay) {
395 if (replay_mode == REPLAY_MODE_PLAY) {
396 return;
398 replay_chr_be_write(s, buf, len);
399 } else {
400 qemu_chr_be_write_impl(s, buf, len);
404 int qemu_chr_fe_get_msgfd(CharDriverState *s)
406 int fd;
407 int res = (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
408 if (s->replay) {
409 fprintf(stderr,
410 "Replay: get msgfd is not supported for serial devices yet\n");
411 exit(1);
413 return res;
416 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
418 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
421 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
423 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
426 int qemu_chr_add_client(CharDriverState *s, int fd)
428 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
431 void qemu_chr_accept_input(CharDriverState *s)
433 if (s->chr_accept_input)
434 s->chr_accept_input(s);
435 qemu_notify_event();
438 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
440 char buf[READ_BUF_LEN];
441 va_list ap;
442 va_start(ap, fmt);
443 vsnprintf(buf, sizeof(buf), fmt, ap);
444 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
445 va_end(ap);
448 static void remove_fd_in_watch(CharDriverState *chr);
450 void qemu_chr_add_handlers(CharDriverState *s,
451 IOCanReadHandler *fd_can_read,
452 IOReadHandler *fd_read,
453 IOEventHandler *fd_event,
454 void *opaque)
456 int fe_open;
458 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
459 fe_open = 0;
460 remove_fd_in_watch(s);
461 } else {
462 fe_open = 1;
464 s->chr_can_read = fd_can_read;
465 s->chr_read = fd_read;
466 s->chr_event = fd_event;
467 s->handler_opaque = opaque;
468 if (fe_open && s->chr_update_read_handler)
469 s->chr_update_read_handler(s);
471 if (!s->explicit_fe_open) {
472 qemu_chr_fe_set_open(s, fe_open);
475 /* We're connecting to an already opened device, so let's make sure we
476 also get the open event */
477 if (fe_open && s->be_open) {
478 qemu_chr_be_generic_open(s);
482 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
484 return len;
487 static CharDriverState *qemu_chr_open_null(const char *id,
488 ChardevBackend *backend,
489 ChardevReturn *ret,
490 Error **errp)
492 CharDriverState *chr;
493 ChardevCommon *common = backend->u.null.data;
495 chr = qemu_chr_alloc(common, errp);
496 if (!chr) {
497 return NULL;
499 chr->chr_write = null_chr_write;
500 chr->explicit_be_open = true;
501 return chr;
504 /* MUX driver for serial I/O splitting */
505 #define MAX_MUX 4
506 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
507 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
508 typedef struct {
509 IOCanReadHandler *chr_can_read[MAX_MUX];
510 IOReadHandler *chr_read[MAX_MUX];
511 IOEventHandler *chr_event[MAX_MUX];
512 void *ext_opaque[MAX_MUX];
513 CharDriverState *drv;
514 int focus;
515 int mux_cnt;
516 int term_got_escape;
517 int max_size;
518 /* Intermediate input buffer allows to catch escape sequences even if the
519 currently active device is not accepting any input - but only until it
520 is full as well. */
521 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
522 int prod[MAX_MUX];
523 int cons[MAX_MUX];
524 int timestamps;
526 /* Protected by the CharDriverState chr_write_lock. */
527 int linestart;
528 int64_t timestamps_start;
529 } MuxDriver;
532 /* Called with chr_write_lock held. */
533 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
535 MuxDriver *d = chr->opaque;
536 int ret;
537 if (!d->timestamps) {
538 ret = qemu_chr_fe_write(d->drv, buf, len);
539 } else {
540 int i;
542 ret = 0;
543 for (i = 0; i < len; i++) {
544 if (d->linestart) {
545 char buf1[64];
546 int64_t ti;
547 int secs;
549 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
550 if (d->timestamps_start == -1)
551 d->timestamps_start = ti;
552 ti -= d->timestamps_start;
553 secs = ti / 1000;
554 snprintf(buf1, sizeof(buf1),
555 "[%02d:%02d:%02d.%03d] ",
556 secs / 3600,
557 (secs / 60) % 60,
558 secs % 60,
559 (int)(ti % 1000));
560 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
561 d->linestart = 0;
563 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
564 if (buf[i] == '\n') {
565 d->linestart = 1;
569 return ret;
572 static const char * const mux_help[] = {
573 "% h print this help\n\r",
574 "% x exit emulator\n\r",
575 "% s save disk data back to file (if -snapshot)\n\r",
576 "% t toggle console timestamps\n\r",
577 "% b send break (magic sysrq)\n\r",
578 "% c switch between console and monitor\n\r",
579 "% % sends %\n\r",
580 NULL
583 int term_escape_char = 0x01; /* ctrl-a is used for escape */
584 static void mux_print_help(CharDriverState *chr)
586 int i, j;
587 char ebuf[15] = "Escape-Char";
588 char cbuf[50] = "\n\r";
590 if (term_escape_char > 0 && term_escape_char < 26) {
591 snprintf(cbuf, sizeof(cbuf), "\n\r");
592 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
593 } else {
594 snprintf(cbuf, sizeof(cbuf),
595 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
596 term_escape_char);
598 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
599 for (i = 0; mux_help[i] != NULL; i++) {
600 for (j=0; mux_help[i][j] != '\0'; j++) {
601 if (mux_help[i][j] == '%')
602 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
603 else
604 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
609 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
611 if (d->chr_event[mux_nr])
612 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
615 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
617 if (d->term_got_escape) {
618 d->term_got_escape = 0;
619 if (ch == term_escape_char)
620 goto send_char;
621 switch(ch) {
622 case '?':
623 case 'h':
624 mux_print_help(chr);
625 break;
626 case 'x':
628 const char *term = "QEMU: Terminated\n\r";
629 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
630 exit(0);
631 break;
633 case 's':
634 blk_commit_all();
635 break;
636 case 'b':
637 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
638 break;
639 case 'c':
640 /* Switch to the next registered device */
641 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
642 d->focus++;
643 if (d->focus >= d->mux_cnt)
644 d->focus = 0;
645 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
646 break;
647 case 't':
648 d->timestamps = !d->timestamps;
649 d->timestamps_start = -1;
650 d->linestart = 0;
651 break;
653 } else if (ch == term_escape_char) {
654 d->term_got_escape = 1;
655 } else {
656 send_char:
657 return 1;
659 return 0;
662 static void mux_chr_accept_input(CharDriverState *chr)
664 MuxDriver *d = chr->opaque;
665 int m = d->focus;
667 while (d->prod[m] != d->cons[m] &&
668 d->chr_can_read[m] &&
669 d->chr_can_read[m](d->ext_opaque[m])) {
670 d->chr_read[m](d->ext_opaque[m],
671 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
675 static int mux_chr_can_read(void *opaque)
677 CharDriverState *chr = opaque;
678 MuxDriver *d = chr->opaque;
679 int m = d->focus;
681 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
682 return 1;
683 if (d->chr_can_read[m])
684 return d->chr_can_read[m](d->ext_opaque[m]);
685 return 0;
688 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
690 CharDriverState *chr = opaque;
691 MuxDriver *d = chr->opaque;
692 int m = d->focus;
693 int i;
695 mux_chr_accept_input (opaque);
697 for(i = 0; i < size; i++)
698 if (mux_proc_byte(chr, d, buf[i])) {
699 if (d->prod[m] == d->cons[m] &&
700 d->chr_can_read[m] &&
701 d->chr_can_read[m](d->ext_opaque[m]))
702 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
703 else
704 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
708 static void mux_chr_event(void *opaque, int event)
710 CharDriverState *chr = opaque;
711 MuxDriver *d = chr->opaque;
712 int i;
714 /* Send the event to all registered listeners */
715 for (i = 0; i < d->mux_cnt; i++)
716 mux_chr_send_event(d, i, event);
719 static void mux_chr_update_read_handler(CharDriverState *chr)
721 MuxDriver *d = chr->opaque;
723 if (d->mux_cnt >= MAX_MUX) {
724 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
725 return;
727 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
728 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
729 d->chr_read[d->mux_cnt] = chr->chr_read;
730 d->chr_event[d->mux_cnt] = chr->chr_event;
731 /* Fix up the real driver with mux routines */
732 if (d->mux_cnt == 0) {
733 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
734 mux_chr_event, chr);
736 if (d->focus != -1) {
737 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
739 d->focus = d->mux_cnt;
740 d->mux_cnt++;
741 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
744 static bool muxes_realized;
747 * Called after processing of default and command-line-specified
748 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
749 * to a mux chardev. This is done here to ensure that
750 * output/prompts/banners are only displayed for the FE that has
751 * focus when initial command-line processing/machine init is
752 * completed.
754 * After this point, any new FE attached to any new or existing
755 * mux will receive CHR_EVENT_OPENED notifications for the BE
756 * immediately.
758 static void muxes_realize_done(Notifier *notifier, void *unused)
760 CharDriverState *chr;
762 QTAILQ_FOREACH(chr, &chardevs, next) {
763 if (chr->is_mux) {
764 MuxDriver *d = chr->opaque;
765 int i;
767 /* send OPENED to all already-attached FEs */
768 for (i = 0; i < d->mux_cnt; i++) {
769 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
771 /* mark mux as OPENED so any new FEs will immediately receive
772 * OPENED event
774 qemu_chr_be_generic_open(chr);
777 muxes_realized = true;
780 static Notifier muxes_realize_notify = {
781 .notify = muxes_realize_done,
784 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
786 MuxDriver *d = s->opaque;
787 return d->drv->chr_add_watch(d->drv, cond);
790 static CharDriverState *qemu_chr_open_mux(const char *id,
791 ChardevBackend *backend,
792 ChardevReturn *ret, Error **errp)
794 ChardevMux *mux = backend->u.mux.data;
795 CharDriverState *chr, *drv;
796 MuxDriver *d;
797 ChardevCommon *common = qapi_ChardevMux_base(mux);
799 drv = qemu_chr_find(mux->chardev);
800 if (drv == NULL) {
801 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
802 return NULL;
805 chr = qemu_chr_alloc(common, errp);
806 if (!chr) {
807 return NULL;
809 d = g_new0(MuxDriver, 1);
811 chr->opaque = d;
812 d->drv = drv;
813 d->focus = -1;
814 chr->chr_write = mux_chr_write;
815 chr->chr_update_read_handler = mux_chr_update_read_handler;
816 chr->chr_accept_input = mux_chr_accept_input;
817 /* Frontend guest-open / -close notification is not support with muxes */
818 chr->chr_set_fe_open = NULL;
819 if (drv->chr_add_watch) {
820 chr->chr_add_watch = mux_chr_add_watch;
822 /* only default to opened state if we've realized the initial
823 * set of muxes
825 chr->explicit_be_open = muxes_realized ? 0 : 1;
826 chr->is_mux = 1;
828 return chr;
832 typedef struct IOWatchPoll
834 GSource parent;
836 QIOChannel *ioc;
837 GSource *src;
839 IOCanReadHandler *fd_can_read;
840 GSourceFunc fd_read;
841 void *opaque;
842 } IOWatchPoll;
844 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
846 return container_of(source, IOWatchPoll, parent);
849 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
851 IOWatchPoll *iwp = io_watch_poll_from_source(source);
852 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
853 bool was_active = iwp->src != NULL;
854 if (was_active == now_active) {
855 return FALSE;
858 if (now_active) {
859 iwp->src = qio_channel_create_watch(
860 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
861 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
862 g_source_attach(iwp->src, NULL);
863 } else {
864 g_source_destroy(iwp->src);
865 g_source_unref(iwp->src);
866 iwp->src = NULL;
868 return FALSE;
871 static gboolean io_watch_poll_check(GSource *source)
873 return FALSE;
876 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
877 gpointer user_data)
879 abort();
882 static void io_watch_poll_finalize(GSource *source)
884 /* Due to a glib bug, removing the last reference to a source
885 * inside a finalize callback causes recursive locking (and a
886 * deadlock). This is not a problem inside other callbacks,
887 * including dispatch callbacks, so we call io_remove_watch_poll
888 * to remove this source. At this point, iwp->src must
889 * be NULL, or we would leak it.
891 * This would be solved much more elegantly by child sources,
892 * but we support older glib versions that do not have them.
894 IOWatchPoll *iwp = io_watch_poll_from_source(source);
895 assert(iwp->src == NULL);
898 static GSourceFuncs io_watch_poll_funcs = {
899 .prepare = io_watch_poll_prepare,
900 .check = io_watch_poll_check,
901 .dispatch = io_watch_poll_dispatch,
902 .finalize = io_watch_poll_finalize,
905 /* Can only be used for read */
906 static guint io_add_watch_poll(QIOChannel *ioc,
907 IOCanReadHandler *fd_can_read,
908 QIOChannelFunc fd_read,
909 gpointer user_data)
911 IOWatchPoll *iwp;
912 int tag;
914 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
915 iwp->fd_can_read = fd_can_read;
916 iwp->opaque = user_data;
917 iwp->ioc = ioc;
918 iwp->fd_read = (GSourceFunc) fd_read;
919 iwp->src = NULL;
921 tag = g_source_attach(&iwp->parent, NULL);
922 g_source_unref(&iwp->parent);
923 return tag;
926 static void io_remove_watch_poll(guint tag)
928 GSource *source;
929 IOWatchPoll *iwp;
931 g_return_if_fail (tag > 0);
933 source = g_main_context_find_source_by_id(NULL, tag);
934 g_return_if_fail (source != NULL);
936 iwp = io_watch_poll_from_source(source);
937 if (iwp->src) {
938 g_source_destroy(iwp->src);
939 g_source_unref(iwp->src);
940 iwp->src = NULL;
942 g_source_destroy(&iwp->parent);
945 static void remove_fd_in_watch(CharDriverState *chr)
947 if (chr->fd_in_tag) {
948 io_remove_watch_poll(chr->fd_in_tag);
949 chr->fd_in_tag = 0;
954 static int io_channel_send_full(QIOChannel *ioc,
955 const void *buf, size_t len,
956 int *fds, size_t nfds)
958 size_t offset = 0;
960 while (offset < len) {
961 ssize_t ret = 0;
962 struct iovec iov = { .iov_base = (char *)buf + offset,
963 .iov_len = len - offset };
965 ret = qio_channel_writev_full(
966 ioc, &iov, 1,
967 fds, nfds, NULL);
968 if (ret == QIO_CHANNEL_ERR_BLOCK) {
969 if (offset) {
970 return offset;
973 errno = EAGAIN;
974 return -1;
975 } else if (ret < 0) {
976 errno = EINVAL;
977 return -1;
980 offset += ret;
983 return offset;
987 #ifndef _WIN32
988 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
990 return io_channel_send_full(ioc, buf, len, NULL, 0);
994 typedef struct FDCharDriver {
995 CharDriverState *chr;
996 QIOChannel *ioc_in, *ioc_out;
997 int max_size;
998 } FDCharDriver;
1000 /* Called with chr_write_lock held. */
1001 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1003 FDCharDriver *s = chr->opaque;
1005 return io_channel_send(s->ioc_out, buf, len);
1008 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1010 CharDriverState *chr = opaque;
1011 FDCharDriver *s = chr->opaque;
1012 int len;
1013 uint8_t buf[READ_BUF_LEN];
1014 ssize_t ret;
1016 len = sizeof(buf);
1017 if (len > s->max_size) {
1018 len = s->max_size;
1020 if (len == 0) {
1021 return TRUE;
1024 ret = qio_channel_read(
1025 chan, (gchar *)buf, len, NULL);
1026 if (ret == 0) {
1027 remove_fd_in_watch(chr);
1028 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1029 return FALSE;
1031 if (ret > 0) {
1032 qemu_chr_be_write(chr, buf, ret);
1035 return TRUE;
1038 static int fd_chr_read_poll(void *opaque)
1040 CharDriverState *chr = opaque;
1041 FDCharDriver *s = chr->opaque;
1043 s->max_size = qemu_chr_be_can_write(chr);
1044 return s->max_size;
1047 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1049 FDCharDriver *s = chr->opaque;
1050 return qio_channel_create_watch(s->ioc_out, cond);
1053 static void fd_chr_update_read_handler(CharDriverState *chr)
1055 FDCharDriver *s = chr->opaque;
1057 remove_fd_in_watch(chr);
1058 if (s->ioc_in) {
1059 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
1060 fd_chr_read_poll,
1061 fd_chr_read, chr);
1065 static void fd_chr_close(struct CharDriverState *chr)
1067 FDCharDriver *s = chr->opaque;
1069 remove_fd_in_watch(chr);
1070 if (s->ioc_in) {
1071 object_unref(OBJECT(s->ioc_in));
1073 if (s->ioc_out) {
1074 object_unref(OBJECT(s->ioc_out));
1077 g_free(s);
1078 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1081 /* open a character device to a unix fd */
1082 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1083 ChardevCommon *backend, Error **errp)
1085 CharDriverState *chr;
1086 FDCharDriver *s;
1088 chr = qemu_chr_alloc(backend, errp);
1089 if (!chr) {
1090 return NULL;
1092 s = g_new0(FDCharDriver, 1);
1093 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1094 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1095 qemu_set_nonblock(fd_out);
1096 s->chr = chr;
1097 chr->opaque = s;
1098 chr->chr_add_watch = fd_chr_add_watch;
1099 chr->chr_write = fd_chr_write;
1100 chr->chr_update_read_handler = fd_chr_update_read_handler;
1101 chr->chr_close = fd_chr_close;
1103 return chr;
1106 static CharDriverState *qemu_chr_open_pipe(const char *id,
1107 ChardevBackend *backend,
1108 ChardevReturn *ret,
1109 Error **errp)
1111 ChardevHostdev *opts = backend->u.pipe.data;
1112 int fd_in, fd_out;
1113 char *filename_in;
1114 char *filename_out;
1115 const char *filename = opts->device;
1116 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1119 filename_in = g_strdup_printf("%s.in", filename);
1120 filename_out = g_strdup_printf("%s.out", filename);
1121 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1122 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1123 g_free(filename_in);
1124 g_free(filename_out);
1125 if (fd_in < 0 || fd_out < 0) {
1126 if (fd_in >= 0)
1127 close(fd_in);
1128 if (fd_out >= 0)
1129 close(fd_out);
1130 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1131 if (fd_in < 0) {
1132 error_setg_file_open(errp, errno, filename);
1133 return NULL;
1136 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1139 /* init terminal so that we can grab keys */
1140 static struct termios oldtty;
1141 static int old_fd0_flags;
1142 static bool stdio_in_use;
1143 static bool stdio_allow_signal;
1144 static bool stdio_echo_state;
1146 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1148 static void term_exit(void)
1150 tcsetattr (0, TCSANOW, &oldtty);
1151 fcntl(0, F_SETFL, old_fd0_flags);
1154 static void term_stdio_handler(int sig)
1156 /* restore echo after resume from suspend. */
1157 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1160 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1162 struct termios tty;
1164 stdio_echo_state = echo;
1165 tty = oldtty;
1166 if (!echo) {
1167 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1168 |INLCR|IGNCR|ICRNL|IXON);
1169 tty.c_oflag |= OPOST;
1170 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1171 tty.c_cflag &= ~(CSIZE|PARENB);
1172 tty.c_cflag |= CS8;
1173 tty.c_cc[VMIN] = 1;
1174 tty.c_cc[VTIME] = 0;
1176 if (!stdio_allow_signal)
1177 tty.c_lflag &= ~ISIG;
1179 tcsetattr (0, TCSANOW, &tty);
1182 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1184 term_exit();
1185 fd_chr_close(chr);
1188 static CharDriverState *qemu_chr_open_stdio(const char *id,
1189 ChardevBackend *backend,
1190 ChardevReturn *ret,
1191 Error **errp)
1193 ChardevStdio *opts = backend->u.stdio.data;
1194 CharDriverState *chr;
1195 struct sigaction act;
1196 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1198 if (is_daemonized()) {
1199 error_setg(errp, "cannot use stdio with -daemonize");
1200 return NULL;
1203 if (stdio_in_use) {
1204 error_setg(errp, "cannot use stdio by multiple character devices");
1205 return NULL;
1208 stdio_in_use = true;
1209 old_fd0_flags = fcntl(0, F_GETFL);
1210 tcgetattr(0, &oldtty);
1211 qemu_set_nonblock(0);
1212 atexit(term_exit);
1214 memset(&act, 0, sizeof(act));
1215 act.sa_handler = term_stdio_handler;
1216 sigaction(SIGCONT, &act, NULL);
1218 chr = qemu_chr_open_fd(0, 1, common, errp);
1219 chr->chr_close = qemu_chr_close_stdio;
1220 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1221 if (opts->has_signal) {
1222 stdio_allow_signal = opts->signal;
1224 qemu_chr_fe_set_echo(chr, false);
1226 return chr;
1229 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1230 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1231 || defined(__GLIBC__)
1233 #define HAVE_CHARDEV_SERIAL 1
1234 #define HAVE_CHARDEV_PTY 1
1236 typedef struct {
1237 QIOChannel *ioc;
1238 int read_bytes;
1240 /* Protected by the CharDriverState chr_write_lock. */
1241 int connected;
1242 guint timer_tag;
1243 guint open_tag;
1244 } PtyCharDriver;
1246 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1247 static void pty_chr_state(CharDriverState *chr, int connected);
1249 static gboolean pty_chr_timer(gpointer opaque)
1251 struct CharDriverState *chr = opaque;
1252 PtyCharDriver *s = chr->opaque;
1254 qemu_mutex_lock(&chr->chr_write_lock);
1255 s->timer_tag = 0;
1256 s->open_tag = 0;
1257 if (!s->connected) {
1258 /* Next poll ... */
1259 pty_chr_update_read_handler_locked(chr);
1261 qemu_mutex_unlock(&chr->chr_write_lock);
1262 return FALSE;
1265 /* Called with chr_write_lock held. */
1266 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1268 PtyCharDriver *s = chr->opaque;
1270 if (s->timer_tag) {
1271 g_source_remove(s->timer_tag);
1272 s->timer_tag = 0;
1275 if (ms == 1000) {
1276 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1277 } else {
1278 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1282 /* Called with chr_write_lock held. */
1283 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1285 PtyCharDriver *s = chr->opaque;
1286 GPollFD pfd;
1287 int rc;
1288 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1290 pfd.fd = fioc->fd;
1291 pfd.events = G_IO_OUT;
1292 pfd.revents = 0;
1293 do {
1294 rc = g_poll(&pfd, 1, 0);
1295 } while (rc == -1 && errno == EINTR);
1296 assert(rc >= 0);
1298 if (pfd.revents & G_IO_HUP) {
1299 pty_chr_state(chr, 0);
1300 } else {
1301 pty_chr_state(chr, 1);
1305 static void pty_chr_update_read_handler(CharDriverState *chr)
1307 qemu_mutex_lock(&chr->chr_write_lock);
1308 pty_chr_update_read_handler_locked(chr);
1309 qemu_mutex_unlock(&chr->chr_write_lock);
1312 /* Called with chr_write_lock held. */
1313 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1315 PtyCharDriver *s = chr->opaque;
1317 if (!s->connected) {
1318 /* guest sends data, check for (re-)connect */
1319 pty_chr_update_read_handler_locked(chr);
1320 if (!s->connected) {
1321 return 0;
1324 return io_channel_send(s->ioc, buf, len);
1327 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1329 PtyCharDriver *s = chr->opaque;
1330 if (!s->connected) {
1331 return NULL;
1333 return qio_channel_create_watch(s->ioc, cond);
1336 static int pty_chr_read_poll(void *opaque)
1338 CharDriverState *chr = opaque;
1339 PtyCharDriver *s = chr->opaque;
1341 s->read_bytes = qemu_chr_be_can_write(chr);
1342 return s->read_bytes;
1345 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1347 CharDriverState *chr = opaque;
1348 PtyCharDriver *s = chr->opaque;
1349 gsize len;
1350 uint8_t buf[READ_BUF_LEN];
1351 ssize_t ret;
1353 len = sizeof(buf);
1354 if (len > s->read_bytes)
1355 len = s->read_bytes;
1356 if (len == 0) {
1357 return TRUE;
1359 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1360 if (ret <= 0) {
1361 pty_chr_state(chr, 0);
1362 return FALSE;
1363 } else {
1364 pty_chr_state(chr, 1);
1365 qemu_chr_be_write(chr, buf, ret);
1367 return TRUE;
1370 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1372 CharDriverState *chr = opaque;
1373 PtyCharDriver *s = chr->opaque;
1375 s->open_tag = 0;
1376 qemu_chr_be_generic_open(chr);
1377 return FALSE;
1380 /* Called with chr_write_lock held. */
1381 static void pty_chr_state(CharDriverState *chr, int connected)
1383 PtyCharDriver *s = chr->opaque;
1385 if (!connected) {
1386 if (s->open_tag) {
1387 g_source_remove(s->open_tag);
1388 s->open_tag = 0;
1390 remove_fd_in_watch(chr);
1391 s->connected = 0;
1392 /* (re-)connect poll interval for idle guests: once per second.
1393 * We check more frequently in case the guests sends data to
1394 * the virtual device linked to our pty. */
1395 pty_chr_rearm_timer(chr, 1000);
1396 } else {
1397 if (s->timer_tag) {
1398 g_source_remove(s->timer_tag);
1399 s->timer_tag = 0;
1401 if (!s->connected) {
1402 g_assert(s->open_tag == 0);
1403 s->connected = 1;
1404 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1406 if (!chr->fd_in_tag) {
1407 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1408 pty_chr_read_poll,
1409 pty_chr_read, chr);
1414 static void pty_chr_close(struct CharDriverState *chr)
1416 PtyCharDriver *s = chr->opaque;
1418 qemu_mutex_lock(&chr->chr_write_lock);
1419 pty_chr_state(chr, 0);
1420 object_unref(OBJECT(s->ioc));
1421 if (s->timer_tag) {
1422 g_source_remove(s->timer_tag);
1423 s->timer_tag = 0;
1425 qemu_mutex_unlock(&chr->chr_write_lock);
1426 g_free(s);
1427 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1430 static CharDriverState *qemu_chr_open_pty(const char *id,
1431 ChardevBackend *backend,
1432 ChardevReturn *ret,
1433 Error **errp)
1435 CharDriverState *chr;
1436 PtyCharDriver *s;
1437 int master_fd, slave_fd;
1438 char pty_name[PATH_MAX];
1439 ChardevCommon *common = backend->u.pty.data;
1441 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1442 if (master_fd < 0) {
1443 error_setg_errno(errp, errno, "Failed to create PTY");
1444 return NULL;
1447 close(slave_fd);
1448 qemu_set_nonblock(master_fd);
1450 chr = qemu_chr_alloc(common, errp);
1451 if (!chr) {
1452 close(master_fd);
1453 return NULL;
1456 chr->filename = g_strdup_printf("pty:%s", pty_name);
1457 ret->pty = g_strdup(pty_name);
1458 ret->has_pty = true;
1460 fprintf(stderr, "char device redirected to %s (label %s)\n",
1461 pty_name, id);
1463 s = g_new0(PtyCharDriver, 1);
1464 chr->opaque = s;
1465 chr->chr_write = pty_chr_write;
1466 chr->chr_update_read_handler = pty_chr_update_read_handler;
1467 chr->chr_close = pty_chr_close;
1468 chr->chr_add_watch = pty_chr_add_watch;
1469 chr->explicit_be_open = true;
1471 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1472 s->timer_tag = 0;
1474 return chr;
1477 static void tty_serial_init(int fd, int speed,
1478 int parity, int data_bits, int stop_bits)
1480 struct termios tty;
1481 speed_t spd;
1483 #if 0
1484 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1485 speed, parity, data_bits, stop_bits);
1486 #endif
1487 tcgetattr (fd, &tty);
1489 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1490 speed = speed * 10 / 11;
1491 do {
1492 check_speed(50);
1493 check_speed(75);
1494 check_speed(110);
1495 check_speed(134);
1496 check_speed(150);
1497 check_speed(200);
1498 check_speed(300);
1499 check_speed(600);
1500 check_speed(1200);
1501 check_speed(1800);
1502 check_speed(2400);
1503 check_speed(4800);
1504 check_speed(9600);
1505 check_speed(19200);
1506 check_speed(38400);
1507 /* Non-Posix values follow. They may be unsupported on some systems. */
1508 check_speed(57600);
1509 check_speed(115200);
1510 #ifdef B230400
1511 check_speed(230400);
1512 #endif
1513 #ifdef B460800
1514 check_speed(460800);
1515 #endif
1516 #ifdef B500000
1517 check_speed(500000);
1518 #endif
1519 #ifdef B576000
1520 check_speed(576000);
1521 #endif
1522 #ifdef B921600
1523 check_speed(921600);
1524 #endif
1525 #ifdef B1000000
1526 check_speed(1000000);
1527 #endif
1528 #ifdef B1152000
1529 check_speed(1152000);
1530 #endif
1531 #ifdef B1500000
1532 check_speed(1500000);
1533 #endif
1534 #ifdef B2000000
1535 check_speed(2000000);
1536 #endif
1537 #ifdef B2500000
1538 check_speed(2500000);
1539 #endif
1540 #ifdef B3000000
1541 check_speed(3000000);
1542 #endif
1543 #ifdef B3500000
1544 check_speed(3500000);
1545 #endif
1546 #ifdef B4000000
1547 check_speed(4000000);
1548 #endif
1549 spd = B115200;
1550 } while (0);
1552 cfsetispeed(&tty, spd);
1553 cfsetospeed(&tty, spd);
1555 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1556 |INLCR|IGNCR|ICRNL|IXON);
1557 tty.c_oflag |= OPOST;
1558 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1559 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1560 switch(data_bits) {
1561 default:
1562 case 8:
1563 tty.c_cflag |= CS8;
1564 break;
1565 case 7:
1566 tty.c_cflag |= CS7;
1567 break;
1568 case 6:
1569 tty.c_cflag |= CS6;
1570 break;
1571 case 5:
1572 tty.c_cflag |= CS5;
1573 break;
1575 switch(parity) {
1576 default:
1577 case 'N':
1578 break;
1579 case 'E':
1580 tty.c_cflag |= PARENB;
1581 break;
1582 case 'O':
1583 tty.c_cflag |= PARENB | PARODD;
1584 break;
1586 if (stop_bits == 2)
1587 tty.c_cflag |= CSTOPB;
1589 tcsetattr (fd, TCSANOW, &tty);
1592 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1594 FDCharDriver *s = chr->opaque;
1595 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1597 switch(cmd) {
1598 case CHR_IOCTL_SERIAL_SET_PARAMS:
1600 QEMUSerialSetParams *ssp = arg;
1601 tty_serial_init(fioc->fd,
1602 ssp->speed, ssp->parity,
1603 ssp->data_bits, ssp->stop_bits);
1605 break;
1606 case CHR_IOCTL_SERIAL_SET_BREAK:
1608 int enable = *(int *)arg;
1609 if (enable) {
1610 tcsendbreak(fioc->fd, 1);
1613 break;
1614 case CHR_IOCTL_SERIAL_GET_TIOCM:
1616 int sarg = 0;
1617 int *targ = (int *)arg;
1618 ioctl(fioc->fd, TIOCMGET, &sarg);
1619 *targ = 0;
1620 if (sarg & TIOCM_CTS)
1621 *targ |= CHR_TIOCM_CTS;
1622 if (sarg & TIOCM_CAR)
1623 *targ |= CHR_TIOCM_CAR;
1624 if (sarg & TIOCM_DSR)
1625 *targ |= CHR_TIOCM_DSR;
1626 if (sarg & TIOCM_RI)
1627 *targ |= CHR_TIOCM_RI;
1628 if (sarg & TIOCM_DTR)
1629 *targ |= CHR_TIOCM_DTR;
1630 if (sarg & TIOCM_RTS)
1631 *targ |= CHR_TIOCM_RTS;
1633 break;
1634 case CHR_IOCTL_SERIAL_SET_TIOCM:
1636 int sarg = *(int *)arg;
1637 int targ = 0;
1638 ioctl(fioc->fd, TIOCMGET, &targ);
1639 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1640 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1641 if (sarg & CHR_TIOCM_CTS)
1642 targ |= TIOCM_CTS;
1643 if (sarg & CHR_TIOCM_CAR)
1644 targ |= TIOCM_CAR;
1645 if (sarg & CHR_TIOCM_DSR)
1646 targ |= TIOCM_DSR;
1647 if (sarg & CHR_TIOCM_RI)
1648 targ |= TIOCM_RI;
1649 if (sarg & CHR_TIOCM_DTR)
1650 targ |= TIOCM_DTR;
1651 if (sarg & CHR_TIOCM_RTS)
1652 targ |= TIOCM_RTS;
1653 ioctl(fioc->fd, TIOCMSET, &targ);
1655 break;
1656 default:
1657 return -ENOTSUP;
1659 return 0;
1662 static void qemu_chr_close_tty(CharDriverState *chr)
1664 fd_chr_close(chr);
1667 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1668 ChardevCommon *backend,
1669 Error **errp)
1671 CharDriverState *chr;
1673 tty_serial_init(fd, 115200, 'N', 8, 1);
1674 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1675 chr->chr_ioctl = tty_serial_ioctl;
1676 chr->chr_close = qemu_chr_close_tty;
1677 return chr;
1679 #endif /* __linux__ || __sun__ */
1681 #if defined(__linux__)
1683 #define HAVE_CHARDEV_PARPORT 1
1685 typedef struct {
1686 int fd;
1687 int mode;
1688 } ParallelCharDriver;
1690 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1692 if (s->mode != mode) {
1693 int m = mode;
1694 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1695 return 0;
1696 s->mode = mode;
1698 return 1;
1701 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1703 ParallelCharDriver *drv = chr->opaque;
1704 int fd = drv->fd;
1705 uint8_t b;
1707 switch(cmd) {
1708 case CHR_IOCTL_PP_READ_DATA:
1709 if (ioctl(fd, PPRDATA, &b) < 0)
1710 return -ENOTSUP;
1711 *(uint8_t *)arg = b;
1712 break;
1713 case CHR_IOCTL_PP_WRITE_DATA:
1714 b = *(uint8_t *)arg;
1715 if (ioctl(fd, PPWDATA, &b) < 0)
1716 return -ENOTSUP;
1717 break;
1718 case CHR_IOCTL_PP_READ_CONTROL:
1719 if (ioctl(fd, PPRCONTROL, &b) < 0)
1720 return -ENOTSUP;
1721 /* Linux gives only the lowest bits, and no way to know data
1722 direction! For better compatibility set the fixed upper
1723 bits. */
1724 *(uint8_t *)arg = b | 0xc0;
1725 break;
1726 case CHR_IOCTL_PP_WRITE_CONTROL:
1727 b = *(uint8_t *)arg;
1728 if (ioctl(fd, PPWCONTROL, &b) < 0)
1729 return -ENOTSUP;
1730 break;
1731 case CHR_IOCTL_PP_READ_STATUS:
1732 if (ioctl(fd, PPRSTATUS, &b) < 0)
1733 return -ENOTSUP;
1734 *(uint8_t *)arg = b;
1735 break;
1736 case CHR_IOCTL_PP_DATA_DIR:
1737 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1738 return -ENOTSUP;
1739 break;
1740 case CHR_IOCTL_PP_EPP_READ_ADDR:
1741 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1742 struct ParallelIOArg *parg = arg;
1743 int n = read(fd, parg->buffer, parg->count);
1744 if (n != parg->count) {
1745 return -EIO;
1748 break;
1749 case CHR_IOCTL_PP_EPP_READ:
1750 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1751 struct ParallelIOArg *parg = arg;
1752 int n = read(fd, parg->buffer, parg->count);
1753 if (n != parg->count) {
1754 return -EIO;
1757 break;
1758 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1759 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1760 struct ParallelIOArg *parg = arg;
1761 int n = write(fd, parg->buffer, parg->count);
1762 if (n != parg->count) {
1763 return -EIO;
1766 break;
1767 case CHR_IOCTL_PP_EPP_WRITE:
1768 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1769 struct ParallelIOArg *parg = arg;
1770 int n = write(fd, parg->buffer, parg->count);
1771 if (n != parg->count) {
1772 return -EIO;
1775 break;
1776 default:
1777 return -ENOTSUP;
1779 return 0;
1782 static void pp_close(CharDriverState *chr)
1784 ParallelCharDriver *drv = chr->opaque;
1785 int fd = drv->fd;
1787 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1788 ioctl(fd, PPRELEASE);
1789 close(fd);
1790 g_free(drv);
1791 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1794 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1795 ChardevCommon *backend,
1796 Error **errp)
1798 CharDriverState *chr;
1799 ParallelCharDriver *drv;
1801 if (ioctl(fd, PPCLAIM) < 0) {
1802 error_setg_errno(errp, errno, "not a parallel port");
1803 close(fd);
1804 return NULL;
1807 chr = qemu_chr_alloc(backend, errp);
1808 if (!chr) {
1809 return NULL;
1812 drv = g_new0(ParallelCharDriver, 1);
1813 chr->opaque = drv;
1814 chr->chr_write = null_chr_write;
1815 chr->chr_ioctl = pp_ioctl;
1816 chr->chr_close = pp_close;
1818 drv->fd = fd;
1819 drv->mode = IEEE1284_MODE_COMPAT;
1821 return chr;
1823 #endif /* __linux__ */
1825 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1827 #define HAVE_CHARDEV_PARPORT 1
1829 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1831 int fd = (int)(intptr_t)chr->opaque;
1832 uint8_t b;
1834 switch(cmd) {
1835 case CHR_IOCTL_PP_READ_DATA:
1836 if (ioctl(fd, PPIGDATA, &b) < 0)
1837 return -ENOTSUP;
1838 *(uint8_t *)arg = b;
1839 break;
1840 case CHR_IOCTL_PP_WRITE_DATA:
1841 b = *(uint8_t *)arg;
1842 if (ioctl(fd, PPISDATA, &b) < 0)
1843 return -ENOTSUP;
1844 break;
1845 case CHR_IOCTL_PP_READ_CONTROL:
1846 if (ioctl(fd, PPIGCTRL, &b) < 0)
1847 return -ENOTSUP;
1848 *(uint8_t *)arg = b;
1849 break;
1850 case CHR_IOCTL_PP_WRITE_CONTROL:
1851 b = *(uint8_t *)arg;
1852 if (ioctl(fd, PPISCTRL, &b) < 0)
1853 return -ENOTSUP;
1854 break;
1855 case CHR_IOCTL_PP_READ_STATUS:
1856 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1857 return -ENOTSUP;
1858 *(uint8_t *)arg = b;
1859 break;
1860 default:
1861 return -ENOTSUP;
1863 return 0;
1866 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1867 ChardevCommon *backend,
1868 Error **errp)
1870 CharDriverState *chr;
1872 chr = qemu_chr_alloc(backend, errp);
1873 if (!chr) {
1874 return NULL;
1876 chr->opaque = (void *)(intptr_t)fd;
1877 chr->chr_write = null_chr_write;
1878 chr->chr_ioctl = pp_ioctl;
1879 chr->explicit_be_open = true;
1880 return chr;
1882 #endif
1884 #else /* _WIN32 */
1886 #define HAVE_CHARDEV_SERIAL 1
1888 typedef struct {
1889 int max_size;
1890 HANDLE hcom, hrecv, hsend;
1891 OVERLAPPED orecv;
1892 BOOL fpipe;
1893 DWORD len;
1895 /* Protected by the CharDriverState chr_write_lock. */
1896 OVERLAPPED osend;
1897 } WinCharState;
1899 typedef struct {
1900 HANDLE hStdIn;
1901 HANDLE hInputReadyEvent;
1902 HANDLE hInputDoneEvent;
1903 HANDLE hInputThread;
1904 uint8_t win_stdio_buf;
1905 } WinStdioCharState;
1907 #define NSENDBUF 2048
1908 #define NRECVBUF 2048
1909 #define MAXCONNECT 1
1910 #define NTIMEOUT 5000
1912 static int win_chr_poll(void *opaque);
1913 static int win_chr_pipe_poll(void *opaque);
1915 static void win_chr_close(CharDriverState *chr)
1917 WinCharState *s = chr->opaque;
1919 if (s->hsend) {
1920 CloseHandle(s->hsend);
1921 s->hsend = NULL;
1923 if (s->hrecv) {
1924 CloseHandle(s->hrecv);
1925 s->hrecv = NULL;
1927 if (s->hcom) {
1928 CloseHandle(s->hcom);
1929 s->hcom = NULL;
1931 if (s->fpipe)
1932 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1933 else
1934 qemu_del_polling_cb(win_chr_poll, chr);
1936 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1939 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1941 WinCharState *s = chr->opaque;
1942 COMMCONFIG comcfg;
1943 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1944 COMSTAT comstat;
1945 DWORD size;
1946 DWORD err;
1948 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1949 if (!s->hsend) {
1950 error_setg(errp, "Failed CreateEvent");
1951 goto fail;
1953 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1954 if (!s->hrecv) {
1955 error_setg(errp, "Failed CreateEvent");
1956 goto fail;
1959 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1960 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1961 if (s->hcom == INVALID_HANDLE_VALUE) {
1962 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1963 s->hcom = NULL;
1964 goto fail;
1967 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1968 error_setg(errp, "Failed SetupComm");
1969 goto fail;
1972 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1973 size = sizeof(COMMCONFIG);
1974 GetDefaultCommConfig(filename, &comcfg, &size);
1975 comcfg.dcb.DCBlength = sizeof(DCB);
1976 CommConfigDialog(filename, NULL, &comcfg);
1978 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1979 error_setg(errp, "Failed SetCommState");
1980 goto fail;
1983 if (!SetCommMask(s->hcom, EV_ERR)) {
1984 error_setg(errp, "Failed SetCommMask");
1985 goto fail;
1988 cto.ReadIntervalTimeout = MAXDWORD;
1989 if (!SetCommTimeouts(s->hcom, &cto)) {
1990 error_setg(errp, "Failed SetCommTimeouts");
1991 goto fail;
1994 if (!ClearCommError(s->hcom, &err, &comstat)) {
1995 error_setg(errp, "Failed ClearCommError");
1996 goto fail;
1998 qemu_add_polling_cb(win_chr_poll, chr);
1999 return 0;
2001 fail:
2002 win_chr_close(chr);
2003 return -1;
2006 /* Called with chr_write_lock held. */
2007 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2009 WinCharState *s = chr->opaque;
2010 DWORD len, ret, size, err;
2012 len = len1;
2013 ZeroMemory(&s->osend, sizeof(s->osend));
2014 s->osend.hEvent = s->hsend;
2015 while (len > 0) {
2016 if (s->hsend)
2017 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2018 else
2019 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2020 if (!ret) {
2021 err = GetLastError();
2022 if (err == ERROR_IO_PENDING) {
2023 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2024 if (ret) {
2025 buf += size;
2026 len -= size;
2027 } else {
2028 break;
2030 } else {
2031 break;
2033 } else {
2034 buf += size;
2035 len -= size;
2038 return len1 - len;
2041 static int win_chr_read_poll(CharDriverState *chr)
2043 WinCharState *s = chr->opaque;
2045 s->max_size = qemu_chr_be_can_write(chr);
2046 return s->max_size;
2049 static void win_chr_readfile(CharDriverState *chr)
2051 WinCharState *s = chr->opaque;
2052 int ret, err;
2053 uint8_t buf[READ_BUF_LEN];
2054 DWORD size;
2056 ZeroMemory(&s->orecv, sizeof(s->orecv));
2057 s->orecv.hEvent = s->hrecv;
2058 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2059 if (!ret) {
2060 err = GetLastError();
2061 if (err == ERROR_IO_PENDING) {
2062 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2066 if (size > 0) {
2067 qemu_chr_be_write(chr, buf, size);
2071 static void win_chr_read(CharDriverState *chr)
2073 WinCharState *s = chr->opaque;
2075 if (s->len > s->max_size)
2076 s->len = s->max_size;
2077 if (s->len == 0)
2078 return;
2080 win_chr_readfile(chr);
2083 static int win_chr_poll(void *opaque)
2085 CharDriverState *chr = opaque;
2086 WinCharState *s = chr->opaque;
2087 COMSTAT status;
2088 DWORD comerr;
2090 ClearCommError(s->hcom, &comerr, &status);
2091 if (status.cbInQue > 0) {
2092 s->len = status.cbInQue;
2093 win_chr_read_poll(chr);
2094 win_chr_read(chr);
2095 return 1;
2097 return 0;
2100 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2101 ChardevCommon *backend,
2102 Error **errp)
2104 CharDriverState *chr;
2105 WinCharState *s;
2107 chr = qemu_chr_alloc(backend, errp);
2108 if (!chr) {
2109 return NULL;
2111 s = g_new0(WinCharState, 1);
2112 chr->opaque = s;
2113 chr->chr_write = win_chr_write;
2114 chr->chr_close = win_chr_close;
2116 if (win_chr_init(chr, filename, errp) < 0) {
2117 g_free(s);
2118 qemu_chr_free_common(chr);
2119 return NULL;
2121 return chr;
2124 static int win_chr_pipe_poll(void *opaque)
2126 CharDriverState *chr = opaque;
2127 WinCharState *s = chr->opaque;
2128 DWORD size;
2130 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2131 if (size > 0) {
2132 s->len = size;
2133 win_chr_read_poll(chr);
2134 win_chr_read(chr);
2135 return 1;
2137 return 0;
2140 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2141 Error **errp)
2143 WinCharState *s = chr->opaque;
2144 OVERLAPPED ov;
2145 int ret;
2146 DWORD size;
2147 char *openname;
2149 s->fpipe = TRUE;
2151 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2152 if (!s->hsend) {
2153 error_setg(errp, "Failed CreateEvent");
2154 goto fail;
2156 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2157 if (!s->hrecv) {
2158 error_setg(errp, "Failed CreateEvent");
2159 goto fail;
2162 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2163 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2164 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2165 PIPE_WAIT,
2166 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2167 g_free(openname);
2168 if (s->hcom == INVALID_HANDLE_VALUE) {
2169 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2170 s->hcom = NULL;
2171 goto fail;
2174 ZeroMemory(&ov, sizeof(ov));
2175 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2176 ret = ConnectNamedPipe(s->hcom, &ov);
2177 if (ret) {
2178 error_setg(errp, "Failed ConnectNamedPipe");
2179 goto fail;
2182 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2183 if (!ret) {
2184 error_setg(errp, "Failed GetOverlappedResult");
2185 if (ov.hEvent) {
2186 CloseHandle(ov.hEvent);
2187 ov.hEvent = NULL;
2189 goto fail;
2192 if (ov.hEvent) {
2193 CloseHandle(ov.hEvent);
2194 ov.hEvent = NULL;
2196 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2197 return 0;
2199 fail:
2200 win_chr_close(chr);
2201 return -1;
2205 static CharDriverState *qemu_chr_open_pipe(const char *id,
2206 ChardevBackend *backend,
2207 ChardevReturn *ret,
2208 Error **errp)
2210 ChardevHostdev *opts = backend->u.pipe.data;
2211 const char *filename = opts->device;
2212 CharDriverState *chr;
2213 WinCharState *s;
2214 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2216 chr = qemu_chr_alloc(common, errp);
2217 if (!chr) {
2218 return NULL;
2220 s = g_new0(WinCharState, 1);
2221 chr->opaque = s;
2222 chr->chr_write = win_chr_write;
2223 chr->chr_close = win_chr_close;
2225 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2226 g_free(s);
2227 qemu_chr_free_common(chr);
2228 return NULL;
2230 return chr;
2233 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2234 ChardevCommon *backend,
2235 Error **errp)
2237 CharDriverState *chr;
2238 WinCharState *s;
2240 chr = qemu_chr_alloc(backend, errp);
2241 if (!chr) {
2242 return NULL;
2244 s = g_new0(WinCharState, 1);
2245 s->hcom = fd_out;
2246 chr->opaque = s;
2247 chr->chr_write = win_chr_write;
2248 return chr;
2251 static CharDriverState *qemu_chr_open_win_con(const char *id,
2252 ChardevBackend *backend,
2253 ChardevReturn *ret,
2254 Error **errp)
2256 ChardevCommon *common = backend->u.console.data;
2257 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2258 common, errp);
2261 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2263 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2264 DWORD dwSize;
2265 int len1;
2267 len1 = len;
2269 while (len1 > 0) {
2270 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2271 break;
2273 buf += dwSize;
2274 len1 -= dwSize;
2277 return len - len1;
2280 static void win_stdio_wait_func(void *opaque)
2282 CharDriverState *chr = opaque;
2283 WinStdioCharState *stdio = chr->opaque;
2284 INPUT_RECORD buf[4];
2285 int ret;
2286 DWORD dwSize;
2287 int i;
2289 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2291 if (!ret) {
2292 /* Avoid error storm */
2293 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2294 return;
2297 for (i = 0; i < dwSize; i++) {
2298 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2300 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2301 int j;
2302 if (kev->uChar.AsciiChar != 0) {
2303 for (j = 0; j < kev->wRepeatCount; j++) {
2304 if (qemu_chr_be_can_write(chr)) {
2305 uint8_t c = kev->uChar.AsciiChar;
2306 qemu_chr_be_write(chr, &c, 1);
2314 static DWORD WINAPI win_stdio_thread(LPVOID param)
2316 CharDriverState *chr = param;
2317 WinStdioCharState *stdio = chr->opaque;
2318 int ret;
2319 DWORD dwSize;
2321 while (1) {
2323 /* Wait for one byte */
2324 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2326 /* Exit in case of error, continue if nothing read */
2327 if (!ret) {
2328 break;
2330 if (!dwSize) {
2331 continue;
2334 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2335 if (stdio->win_stdio_buf == '\r') {
2336 continue;
2339 /* Signal the main thread and wait until the byte was eaten */
2340 if (!SetEvent(stdio->hInputReadyEvent)) {
2341 break;
2343 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2344 != WAIT_OBJECT_0) {
2345 break;
2349 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2350 return 0;
2353 static void win_stdio_thread_wait_func(void *opaque)
2355 CharDriverState *chr = opaque;
2356 WinStdioCharState *stdio = chr->opaque;
2358 if (qemu_chr_be_can_write(chr)) {
2359 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2362 SetEvent(stdio->hInputDoneEvent);
2365 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2367 WinStdioCharState *stdio = chr->opaque;
2368 DWORD dwMode = 0;
2370 GetConsoleMode(stdio->hStdIn, &dwMode);
2372 if (echo) {
2373 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2374 } else {
2375 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2379 static void win_stdio_close(CharDriverState *chr)
2381 WinStdioCharState *stdio = chr->opaque;
2383 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2384 CloseHandle(stdio->hInputReadyEvent);
2386 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2387 CloseHandle(stdio->hInputDoneEvent);
2389 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2390 TerminateThread(stdio->hInputThread, 0);
2393 g_free(chr->opaque);
2394 g_free(chr);
2397 static CharDriverState *qemu_chr_open_stdio(const char *id,
2398 ChardevBackend *backend,
2399 ChardevReturn *ret,
2400 Error **errp)
2402 CharDriverState *chr;
2403 WinStdioCharState *stdio;
2404 DWORD dwMode;
2405 int is_console = 0;
2406 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio.data);
2408 chr = qemu_chr_alloc(common, errp);
2409 if (!chr) {
2410 return NULL;
2412 stdio = g_new0(WinStdioCharState, 1);
2414 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2415 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2416 error_setg(errp, "cannot open stdio: invalid handle");
2417 return NULL;
2420 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2422 chr->opaque = stdio;
2423 chr->chr_write = win_stdio_write;
2424 chr->chr_close = win_stdio_close;
2426 if (is_console) {
2427 if (qemu_add_wait_object(stdio->hStdIn,
2428 win_stdio_wait_func, chr)) {
2429 error_setg(errp, "qemu_add_wait_object: failed");
2430 goto err1;
2432 } else {
2433 DWORD dwId;
2435 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2436 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2437 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2438 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2439 error_setg(errp, "cannot create event");
2440 goto err2;
2442 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2443 win_stdio_thread_wait_func, chr)) {
2444 error_setg(errp, "qemu_add_wait_object: failed");
2445 goto err2;
2447 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2448 chr, 0, &dwId);
2450 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2451 error_setg(errp, "cannot create stdio thread");
2452 goto err3;
2456 dwMode |= ENABLE_LINE_INPUT;
2458 if (is_console) {
2459 /* set the terminal in raw mode */
2460 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2461 dwMode |= ENABLE_PROCESSED_INPUT;
2464 SetConsoleMode(stdio->hStdIn, dwMode);
2466 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2467 qemu_chr_fe_set_echo(chr, false);
2469 return chr;
2471 err3:
2472 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2473 err2:
2474 CloseHandle(stdio->hInputReadyEvent);
2475 CloseHandle(stdio->hInputDoneEvent);
2476 err1:
2477 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2478 return NULL;
2480 #endif /* !_WIN32 */
2483 /***********************************************************/
2484 /* UDP Net console */
2486 typedef struct {
2487 QIOChannel *ioc;
2488 uint8_t buf[READ_BUF_LEN];
2489 int bufcnt;
2490 int bufptr;
2491 int max_size;
2492 } NetCharDriver;
2494 /* Called with chr_write_lock held. */
2495 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2497 NetCharDriver *s = chr->opaque;
2499 return qio_channel_write(
2500 s->ioc, (const char *)buf, len, NULL);
2503 static int udp_chr_read_poll(void *opaque)
2505 CharDriverState *chr = opaque;
2506 NetCharDriver *s = chr->opaque;
2508 s->max_size = qemu_chr_be_can_write(chr);
2510 /* If there were any stray characters in the queue process them
2511 * first
2513 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2514 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2515 s->bufptr++;
2516 s->max_size = qemu_chr_be_can_write(chr);
2518 return s->max_size;
2521 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2523 CharDriverState *chr = opaque;
2524 NetCharDriver *s = chr->opaque;
2525 ssize_t ret;
2527 if (s->max_size == 0) {
2528 return TRUE;
2530 ret = qio_channel_read(
2531 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2532 if (ret <= 0) {
2533 remove_fd_in_watch(chr);
2534 return FALSE;
2536 s->bufcnt = ret;
2538 s->bufptr = 0;
2539 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2540 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2541 s->bufptr++;
2542 s->max_size = qemu_chr_be_can_write(chr);
2545 return TRUE;
2548 static void udp_chr_update_read_handler(CharDriverState *chr)
2550 NetCharDriver *s = chr->opaque;
2552 remove_fd_in_watch(chr);
2553 if (s->ioc) {
2554 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2555 udp_chr_read_poll,
2556 udp_chr_read, chr);
2560 static void udp_chr_close(CharDriverState *chr)
2562 NetCharDriver *s = chr->opaque;
2564 remove_fd_in_watch(chr);
2565 if (s->ioc) {
2566 object_unref(OBJECT(s->ioc));
2568 g_free(s);
2569 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2572 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2573 ChardevCommon *backend,
2574 Error **errp)
2576 CharDriverState *chr = NULL;
2577 NetCharDriver *s = NULL;
2579 chr = qemu_chr_alloc(backend, errp);
2580 if (!chr) {
2581 return NULL;
2583 s = g_new0(NetCharDriver, 1);
2585 s->ioc = QIO_CHANNEL(sioc);
2586 s->bufcnt = 0;
2587 s->bufptr = 0;
2588 chr->opaque = s;
2589 chr->chr_write = udp_chr_write;
2590 chr->chr_update_read_handler = udp_chr_update_read_handler;
2591 chr->chr_close = udp_chr_close;
2592 /* be isn't opened until we get a connection */
2593 chr->explicit_be_open = true;
2594 return chr;
2597 /***********************************************************/
2598 /* TCP Net console */
2600 typedef struct {
2601 QIOChannel *ioc; /* Client I/O channel */
2602 QIOChannelSocket *sioc; /* Client master channel */
2603 QIOChannelSocket *listen_ioc;
2604 guint listen_tag;
2605 QCryptoTLSCreds *tls_creds;
2606 int connected;
2607 int max_size;
2608 int do_telnetopt;
2609 int do_nodelay;
2610 int is_unix;
2611 int *read_msgfds;
2612 size_t read_msgfds_num;
2613 int *write_msgfds;
2614 size_t write_msgfds_num;
2616 SocketAddress *addr;
2617 bool is_listen;
2618 bool is_telnet;
2620 guint reconnect_timer;
2621 int64_t reconnect_time;
2622 bool connect_err_reported;
2623 } TCPCharDriver;
2625 static gboolean socket_reconnect_timeout(gpointer opaque);
2627 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2629 TCPCharDriver *s = chr->opaque;
2630 assert(s->connected == 0);
2631 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2632 socket_reconnect_timeout, chr);
2635 static void check_report_connect_error(CharDriverState *chr,
2636 Error *err)
2638 TCPCharDriver *s = chr->opaque;
2640 if (!s->connect_err_reported) {
2641 error_report("Unable to connect character device %s: %s",
2642 chr->label, error_get_pretty(err));
2643 s->connect_err_reported = true;
2645 qemu_chr_socket_restart_timer(chr);
2648 static gboolean tcp_chr_accept(QIOChannel *chan,
2649 GIOCondition cond,
2650 void *opaque);
2652 /* Called with chr_write_lock held. */
2653 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2655 TCPCharDriver *s = chr->opaque;
2656 if (s->connected) {
2657 int ret = io_channel_send_full(s->ioc, buf, len,
2658 s->write_msgfds,
2659 s->write_msgfds_num);
2661 /* free the written msgfds, no matter what */
2662 if (s->write_msgfds_num) {
2663 g_free(s->write_msgfds);
2664 s->write_msgfds = 0;
2665 s->write_msgfds_num = 0;
2668 return ret;
2669 } else {
2670 /* XXX: indicate an error ? */
2671 return len;
2675 static int tcp_chr_read_poll(void *opaque)
2677 CharDriverState *chr = opaque;
2678 TCPCharDriver *s = chr->opaque;
2679 if (!s->connected)
2680 return 0;
2681 s->max_size = qemu_chr_be_can_write(chr);
2682 return s->max_size;
2685 #define IAC 255
2686 #define IAC_BREAK 243
2687 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2688 TCPCharDriver *s,
2689 uint8_t *buf, int *size)
2691 /* Handle any telnet client's basic IAC options to satisfy char by
2692 * char mode with no echo. All IAC options will be removed from
2693 * the buf and the do_telnetopt variable will be used to track the
2694 * state of the width of the IAC information.
2696 * IAC commands come in sets of 3 bytes with the exception of the
2697 * "IAC BREAK" command and the double IAC.
2700 int i;
2701 int j = 0;
2703 for (i = 0; i < *size; i++) {
2704 if (s->do_telnetopt > 1) {
2705 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2706 /* Double IAC means send an IAC */
2707 if (j != i)
2708 buf[j] = buf[i];
2709 j++;
2710 s->do_telnetopt = 1;
2711 } else {
2712 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2713 /* Handle IAC break commands by sending a serial break */
2714 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2715 s->do_telnetopt++;
2717 s->do_telnetopt++;
2719 if (s->do_telnetopt >= 4) {
2720 s->do_telnetopt = 1;
2722 } else {
2723 if ((unsigned char)buf[i] == IAC) {
2724 s->do_telnetopt = 2;
2725 } else {
2726 if (j != i)
2727 buf[j] = buf[i];
2728 j++;
2732 *size = j;
2735 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2737 TCPCharDriver *s = chr->opaque;
2738 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2740 assert(num <= TCP_MAX_FDS);
2742 if (to_copy) {
2743 int i;
2745 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2747 /* Close unused fds */
2748 for (i = to_copy; i < s->read_msgfds_num; i++) {
2749 close(s->read_msgfds[i]);
2752 g_free(s->read_msgfds);
2753 s->read_msgfds = 0;
2754 s->read_msgfds_num = 0;
2757 return to_copy;
2760 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2762 TCPCharDriver *s = chr->opaque;
2764 if (!qio_channel_has_feature(s->ioc,
2765 QIO_CHANNEL_FEATURE_FD_PASS)) {
2766 return -1;
2768 /* clear old pending fd array */
2769 g_free(s->write_msgfds);
2770 s->write_msgfds = NULL;
2772 if (num) {
2773 s->write_msgfds = g_new(int, num);
2774 memcpy(s->write_msgfds, fds, num * sizeof(int));
2777 s->write_msgfds_num = num;
2779 return 0;
2782 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2784 TCPCharDriver *s = chr->opaque;
2785 struct iovec iov = { .iov_base = buf, .iov_len = len };
2786 int ret;
2787 size_t i;
2788 int *msgfds = NULL;
2789 size_t msgfds_num = 0;
2791 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2792 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2793 &msgfds, &msgfds_num,
2794 NULL);
2795 } else {
2796 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2797 NULL, NULL,
2798 NULL);
2801 if (msgfds_num) {
2802 /* close and clean read_msgfds */
2803 for (i = 0; i < s->read_msgfds_num; i++) {
2804 close(s->read_msgfds[i]);
2807 if (s->read_msgfds_num) {
2808 g_free(s->read_msgfds);
2811 s->read_msgfds = msgfds;
2812 s->read_msgfds_num = msgfds_num;
2815 for (i = 0; i < s->read_msgfds_num; i++) {
2816 int fd = s->read_msgfds[i];
2817 if (fd < 0) {
2818 continue;
2821 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2822 qemu_set_block(fd);
2824 #ifndef MSG_CMSG_CLOEXEC
2825 qemu_set_cloexec(fd);
2826 #endif
2829 return ret;
2832 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2834 TCPCharDriver *s = chr->opaque;
2835 return qio_channel_create_watch(s->ioc, cond);
2838 static void tcp_chr_disconnect(CharDriverState *chr)
2840 TCPCharDriver *s = chr->opaque;
2842 if (!s->connected) {
2843 return;
2846 s->connected = 0;
2847 if (s->listen_ioc) {
2848 s->listen_tag = qio_channel_add_watch(
2849 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
2851 tcp_set_msgfds(chr, NULL, 0);
2852 remove_fd_in_watch(chr);
2853 object_unref(OBJECT(s->sioc));
2854 s->sioc = NULL;
2855 object_unref(OBJECT(s->ioc));
2856 s->ioc = NULL;
2857 g_free(chr->filename);
2858 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
2859 s->is_listen, s->is_telnet);
2860 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2861 if (s->reconnect_time) {
2862 qemu_chr_socket_restart_timer(chr);
2866 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2868 CharDriverState *chr = opaque;
2869 TCPCharDriver *s = chr->opaque;
2870 uint8_t buf[READ_BUF_LEN];
2871 int len, size;
2873 if (!s->connected || s->max_size <= 0) {
2874 return TRUE;
2876 len = sizeof(buf);
2877 if (len > s->max_size)
2878 len = s->max_size;
2879 size = tcp_chr_recv(chr, (void *)buf, len);
2880 if (size == 0 || size == -1) {
2881 /* connection closed */
2882 tcp_chr_disconnect(chr);
2883 } else if (size > 0) {
2884 if (s->do_telnetopt)
2885 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2886 if (size > 0)
2887 qemu_chr_be_write(chr, buf, size);
2890 return TRUE;
2893 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2895 TCPCharDriver *s = chr->opaque;
2896 int size;
2898 if (!s->connected) {
2899 return 0;
2902 size = tcp_chr_recv(chr, (void *) buf, len);
2903 if (size == 0) {
2904 /* connection closed */
2905 tcp_chr_disconnect(chr);
2908 return size;
2911 static void tcp_chr_connect(void *opaque)
2913 CharDriverState *chr = opaque;
2914 TCPCharDriver *s = chr->opaque;
2916 g_free(chr->filename);
2917 chr->filename = sockaddr_to_str(
2918 &s->sioc->localAddr, s->sioc->localAddrLen,
2919 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
2920 s->is_listen, s->is_telnet);
2922 s->connected = 1;
2923 if (s->ioc) {
2924 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2925 tcp_chr_read_poll,
2926 tcp_chr_read, chr);
2928 qemu_chr_be_generic_open(chr);
2931 static void tcp_chr_update_read_handler(CharDriverState *chr)
2933 TCPCharDriver *s = chr->opaque;
2935 if (!s->connected) {
2936 return;
2939 remove_fd_in_watch(chr);
2940 if (s->ioc) {
2941 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2942 tcp_chr_read_poll,
2943 tcp_chr_read, chr);
2947 typedef struct {
2948 CharDriverState *chr;
2949 char buf[12];
2950 size_t buflen;
2951 } TCPCharDriverTelnetInit;
2953 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
2954 GIOCondition cond G_GNUC_UNUSED,
2955 gpointer user_data)
2957 TCPCharDriverTelnetInit *init = user_data;
2958 ssize_t ret;
2960 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
2961 if (ret < 0) {
2962 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2963 ret = 0;
2964 } else {
2965 tcp_chr_disconnect(init->chr);
2966 return FALSE;
2969 init->buflen -= ret;
2971 if (init->buflen == 0) {
2972 tcp_chr_connect(init->chr);
2973 return FALSE;
2976 memmove(init->buf, init->buf + ret, init->buflen);
2978 return TRUE;
2981 static void tcp_chr_telnet_init(CharDriverState *chr)
2983 TCPCharDriver *s = chr->opaque;
2984 TCPCharDriverTelnetInit *init =
2985 g_new0(TCPCharDriverTelnetInit, 1);
2986 size_t n = 0;
2988 init->chr = chr;
2989 init->buflen = 12;
2991 #define IACSET(x, a, b, c) \
2992 do { \
2993 x[n++] = a; \
2994 x[n++] = b; \
2995 x[n++] = c; \
2996 } while (0)
2998 /* Prep the telnet negotion to put telnet in binary,
2999 * no echo, single char mode */
3000 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3001 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3002 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3003 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3005 #undef IACSET
3007 qio_channel_add_watch(
3008 s->ioc, G_IO_OUT,
3009 tcp_chr_telnet_init_io,
3010 init, NULL);
3014 static void tcp_chr_tls_handshake(Object *source,
3015 Error *err,
3016 gpointer user_data)
3018 CharDriverState *chr = user_data;
3019 TCPCharDriver *s = chr->opaque;
3021 if (err) {
3022 tcp_chr_disconnect(chr);
3023 } else {
3024 if (s->do_telnetopt) {
3025 tcp_chr_telnet_init(chr);
3026 } else {
3027 tcp_chr_connect(chr);
3033 static void tcp_chr_tls_init(CharDriverState *chr)
3035 TCPCharDriver *s = chr->opaque;
3036 QIOChannelTLS *tioc;
3037 Error *err = NULL;
3039 if (s->is_listen) {
3040 tioc = qio_channel_tls_new_server(
3041 s->ioc, s->tls_creds,
3042 NULL, /* XXX Use an ACL */
3043 &err);
3044 } else {
3045 tioc = qio_channel_tls_new_client(
3046 s->ioc, s->tls_creds,
3047 s->addr->u.inet.data->host,
3048 &err);
3050 if (tioc == NULL) {
3051 error_free(err);
3052 tcp_chr_disconnect(chr);
3054 object_unref(OBJECT(s->ioc));
3055 s->ioc = QIO_CHANNEL(tioc);
3057 qio_channel_tls_handshake(tioc,
3058 tcp_chr_tls_handshake,
3059 chr,
3060 NULL);
3064 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3066 TCPCharDriver *s = chr->opaque;
3067 if (s->ioc != NULL) {
3068 return -1;
3071 s->ioc = QIO_CHANNEL(sioc);
3072 object_ref(OBJECT(sioc));
3073 s->sioc = sioc;
3074 object_ref(OBJECT(sioc));
3076 if (s->do_nodelay) {
3077 qio_channel_set_delay(s->ioc, false);
3079 if (s->listen_tag) {
3080 g_source_remove(s->listen_tag);
3081 s->listen_tag = 0;
3084 if (s->tls_creds) {
3085 tcp_chr_tls_init(chr);
3086 } else {
3087 if (s->do_telnetopt) {
3088 tcp_chr_telnet_init(chr);
3089 } else {
3090 tcp_chr_connect(chr);
3094 return 0;
3098 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3100 int ret;
3101 QIOChannelSocket *sioc;
3103 sioc = qio_channel_socket_new_fd(fd, NULL);
3104 if (!sioc) {
3105 return -1;
3107 qio_channel_set_blocking(QIO_CHANNEL(sioc), false, NULL);
3108 ret = tcp_chr_new_client(chr, sioc);
3109 object_unref(OBJECT(sioc));
3110 return ret;
3113 static gboolean tcp_chr_accept(QIOChannel *channel,
3114 GIOCondition cond,
3115 void *opaque)
3117 CharDriverState *chr = opaque;
3118 QIOChannelSocket *sioc;
3120 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3121 NULL);
3122 if (!sioc) {
3123 return TRUE;
3126 tcp_chr_new_client(chr, sioc);
3128 object_unref(OBJECT(sioc));
3130 return TRUE;
3133 static void tcp_chr_close(CharDriverState *chr)
3135 TCPCharDriver *s = chr->opaque;
3136 int i;
3138 if (s->reconnect_timer) {
3139 g_source_remove(s->reconnect_timer);
3140 s->reconnect_timer = 0;
3142 qapi_free_SocketAddress(s->addr);
3143 remove_fd_in_watch(chr);
3144 if (s->ioc) {
3145 object_unref(OBJECT(s->ioc));
3147 if (s->listen_tag) {
3148 g_source_remove(s->listen_tag);
3149 s->listen_tag = 0;
3151 if (s->listen_ioc) {
3152 object_unref(OBJECT(s->listen_ioc));
3154 if (s->read_msgfds_num) {
3155 for (i = 0; i < s->read_msgfds_num; i++) {
3156 close(s->read_msgfds[i]);
3158 g_free(s->read_msgfds);
3160 if (s->tls_creds) {
3161 object_unref(OBJECT(s->tls_creds));
3163 if (s->write_msgfds_num) {
3164 g_free(s->write_msgfds);
3166 g_free(s);
3167 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3171 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3173 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3174 CharDriverState *chr = opaque;
3175 TCPCharDriver *s = chr->opaque;
3177 if (err) {
3178 check_report_connect_error(chr, err);
3179 object_unref(src);
3180 return;
3183 s->connect_err_reported = false;
3184 tcp_chr_new_client(chr, sioc);
3185 object_unref(OBJECT(sioc));
3189 /*********************************************************/
3190 /* Ring buffer chardev */
3192 typedef struct {
3193 size_t size;
3194 size_t prod;
3195 size_t cons;
3196 uint8_t *cbuf;
3197 } RingBufCharDriver;
3199 static size_t ringbuf_count(const CharDriverState *chr)
3201 const RingBufCharDriver *d = chr->opaque;
3203 return d->prod - d->cons;
3206 /* Called with chr_write_lock held. */
3207 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3209 RingBufCharDriver *d = chr->opaque;
3210 int i;
3212 if (!buf || (len < 0)) {
3213 return -1;
3216 for (i = 0; i < len; i++ ) {
3217 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3218 if (d->prod - d->cons > d->size) {
3219 d->cons = d->prod - d->size;
3223 return 0;
3226 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3228 RingBufCharDriver *d = chr->opaque;
3229 int i;
3231 qemu_mutex_lock(&chr->chr_write_lock);
3232 for (i = 0; i < len && d->cons != d->prod; i++) {
3233 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3235 qemu_mutex_unlock(&chr->chr_write_lock);
3237 return i;
3240 static void ringbuf_chr_close(struct CharDriverState *chr)
3242 RingBufCharDriver *d = chr->opaque;
3244 g_free(d->cbuf);
3245 g_free(d);
3246 chr->opaque = NULL;
3249 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3250 ChardevBackend *backend,
3251 ChardevReturn *ret,
3252 Error **errp)
3254 ChardevRingbuf *opts = backend->u.ringbuf.data;
3255 ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
3256 CharDriverState *chr;
3257 RingBufCharDriver *d;
3259 chr = qemu_chr_alloc(common, errp);
3260 if (!chr) {
3261 return NULL;
3263 d = g_malloc(sizeof(*d));
3265 d->size = opts->has_size ? opts->size : 65536;
3267 /* The size must be power of 2 */
3268 if (d->size & (d->size - 1)) {
3269 error_setg(errp, "size of ringbuf chardev must be power of two");
3270 goto fail;
3273 d->prod = 0;
3274 d->cons = 0;
3275 d->cbuf = g_malloc0(d->size);
3277 chr->opaque = d;
3278 chr->chr_write = ringbuf_chr_write;
3279 chr->chr_close = ringbuf_chr_close;
3281 return chr;
3283 fail:
3284 g_free(d);
3285 qemu_chr_free_common(chr);
3286 return NULL;
3289 bool chr_is_ringbuf(const CharDriverState *chr)
3291 return chr->chr_write == ringbuf_chr_write;
3294 void qmp_ringbuf_write(const char *device, const char *data,
3295 bool has_format, enum DataFormat format,
3296 Error **errp)
3298 CharDriverState *chr;
3299 const uint8_t *write_data;
3300 int ret;
3301 gsize write_count;
3303 chr = qemu_chr_find(device);
3304 if (!chr) {
3305 error_setg(errp, "Device '%s' not found", device);
3306 return;
3309 if (!chr_is_ringbuf(chr)) {
3310 error_setg(errp,"%s is not a ringbuf device", device);
3311 return;
3314 if (has_format && (format == DATA_FORMAT_BASE64)) {
3315 write_data = qbase64_decode(data, -1,
3316 &write_count,
3317 errp);
3318 if (!write_data) {
3319 return;
3321 } else {
3322 write_data = (uint8_t *)data;
3323 write_count = strlen(data);
3326 ret = ringbuf_chr_write(chr, write_data, write_count);
3328 if (write_data != (uint8_t *)data) {
3329 g_free((void *)write_data);
3332 if (ret < 0) {
3333 error_setg(errp, "Failed to write to device %s", device);
3334 return;
3338 char *qmp_ringbuf_read(const char *device, int64_t size,
3339 bool has_format, enum DataFormat format,
3340 Error **errp)
3342 CharDriverState *chr;
3343 uint8_t *read_data;
3344 size_t count;
3345 char *data;
3347 chr = qemu_chr_find(device);
3348 if (!chr) {
3349 error_setg(errp, "Device '%s' not found", device);
3350 return NULL;
3353 if (!chr_is_ringbuf(chr)) {
3354 error_setg(errp,"%s is not a ringbuf device", device);
3355 return NULL;
3358 if (size <= 0) {
3359 error_setg(errp, "size must be greater than zero");
3360 return NULL;
3363 count = ringbuf_count(chr);
3364 size = size > count ? count : size;
3365 read_data = g_malloc(size + 1);
3367 ringbuf_chr_read(chr, read_data, size);
3369 if (has_format && (format == DATA_FORMAT_BASE64)) {
3370 data = g_base64_encode(read_data, size);
3371 g_free(read_data);
3372 } else {
3374 * FIXME should read only complete, valid UTF-8 characters up
3375 * to @size bytes. Invalid sequences should be replaced by a
3376 * suitable replacement character. Except when (and only
3377 * when) ring buffer lost characters since last read, initial
3378 * continuation characters should be dropped.
3380 read_data[size] = 0;
3381 data = (char *)read_data;
3384 return data;
3387 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3389 char host[65], port[33], width[8], height[8];
3390 int pos;
3391 const char *p;
3392 QemuOpts *opts;
3393 Error *local_err = NULL;
3395 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3396 if (local_err) {
3397 error_report_err(local_err);
3398 return NULL;
3401 if (strstart(filename, "mon:", &p)) {
3402 filename = p;
3403 qemu_opt_set(opts, "mux", "on", &error_abort);
3404 if (strcmp(filename, "stdio") == 0) {
3405 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3406 * but pass it to the guest. Handle this only for compat syntax,
3407 * for -chardev syntax we have special option for this.
3408 * This is what -nographic did, redirecting+muxing serial+monitor
3409 * to stdio causing Ctrl+C to be passed to guest. */
3410 qemu_opt_set(opts, "signal", "off", &error_abort);
3414 if (strcmp(filename, "null") == 0 ||
3415 strcmp(filename, "pty") == 0 ||
3416 strcmp(filename, "msmouse") == 0 ||
3417 strcmp(filename, "braille") == 0 ||
3418 strcmp(filename, "testdev") == 0 ||
3419 strcmp(filename, "stdio") == 0) {
3420 qemu_opt_set(opts, "backend", filename, &error_abort);
3421 return opts;
3423 if (strstart(filename, "vc", &p)) {
3424 qemu_opt_set(opts, "backend", "vc", &error_abort);
3425 if (*p == ':') {
3426 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3427 /* pixels */
3428 qemu_opt_set(opts, "width", width, &error_abort);
3429 qemu_opt_set(opts, "height", height, &error_abort);
3430 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3431 /* chars */
3432 qemu_opt_set(opts, "cols", width, &error_abort);
3433 qemu_opt_set(opts, "rows", height, &error_abort);
3434 } else {
3435 goto fail;
3438 return opts;
3440 if (strcmp(filename, "con:") == 0) {
3441 qemu_opt_set(opts, "backend", "console", &error_abort);
3442 return opts;
3444 if (strstart(filename, "COM", NULL)) {
3445 qemu_opt_set(opts, "backend", "serial", &error_abort);
3446 qemu_opt_set(opts, "path", filename, &error_abort);
3447 return opts;
3449 if (strstart(filename, "file:", &p)) {
3450 qemu_opt_set(opts, "backend", "file", &error_abort);
3451 qemu_opt_set(opts, "path", p, &error_abort);
3452 return opts;
3454 if (strstart(filename, "pipe:", &p)) {
3455 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3456 qemu_opt_set(opts, "path", p, &error_abort);
3457 return opts;
3459 if (strstart(filename, "tcp:", &p) ||
3460 strstart(filename, "telnet:", &p)) {
3461 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3462 host[0] = 0;
3463 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3464 goto fail;
3466 qemu_opt_set(opts, "backend", "socket", &error_abort);
3467 qemu_opt_set(opts, "host", host, &error_abort);
3468 qemu_opt_set(opts, "port", port, &error_abort);
3469 if (p[pos] == ',') {
3470 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3471 if (local_err) {
3472 error_report_err(local_err);
3473 goto fail;
3476 if (strstart(filename, "telnet:", &p))
3477 qemu_opt_set(opts, "telnet", "on", &error_abort);
3478 return opts;
3480 if (strstart(filename, "udp:", &p)) {
3481 qemu_opt_set(opts, "backend", "udp", &error_abort);
3482 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3483 host[0] = 0;
3484 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3485 goto fail;
3488 qemu_opt_set(opts, "host", host, &error_abort);
3489 qemu_opt_set(opts, "port", port, &error_abort);
3490 if (p[pos] == '@') {
3491 p += pos + 1;
3492 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3493 host[0] = 0;
3494 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3495 goto fail;
3498 qemu_opt_set(opts, "localaddr", host, &error_abort);
3499 qemu_opt_set(opts, "localport", port, &error_abort);
3501 return opts;
3503 if (strstart(filename, "unix:", &p)) {
3504 qemu_opt_set(opts, "backend", "socket", &error_abort);
3505 qemu_opts_do_parse(opts, p, "path", &local_err);
3506 if (local_err) {
3507 error_report_err(local_err);
3508 goto fail;
3510 return opts;
3512 if (strstart(filename, "/dev/parport", NULL) ||
3513 strstart(filename, "/dev/ppi", NULL)) {
3514 qemu_opt_set(opts, "backend", "parport", &error_abort);
3515 qemu_opt_set(opts, "path", filename, &error_abort);
3516 return opts;
3518 if (strstart(filename, "/dev/", NULL)) {
3519 qemu_opt_set(opts, "backend", "tty", &error_abort);
3520 qemu_opt_set(opts, "path", filename, &error_abort);
3521 return opts;
3524 fail:
3525 qemu_opts_del(opts);
3526 return NULL;
3529 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3531 const char *logfile = qemu_opt_get(opts, "logfile");
3533 backend->has_logfile = logfile != NULL;
3534 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3536 backend->has_logappend = true;
3537 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3541 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3542 Error **errp)
3544 const char *path = qemu_opt_get(opts, "path");
3545 ChardevFile *file;
3547 if (path == NULL) {
3548 error_setg(errp, "chardev: file: no filename given");
3549 return;
3551 file = backend->u.file.data = g_new0(ChardevFile, 1);
3552 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3553 file->out = g_strdup(path);
3555 file->has_append = true;
3556 file->append = qemu_opt_get_bool(opts, "append", false);
3559 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3560 Error **errp)
3562 ChardevStdio *stdio;
3564 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3565 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3566 stdio->has_signal = true;
3567 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3570 #ifdef HAVE_CHARDEV_SERIAL
3571 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3572 Error **errp)
3574 const char *device = qemu_opt_get(opts, "path");
3575 ChardevHostdev *serial;
3577 if (device == NULL) {
3578 error_setg(errp, "chardev: serial/tty: no device path given");
3579 return;
3581 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3582 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3583 serial->device = g_strdup(device);
3585 #endif
3587 #ifdef HAVE_CHARDEV_PARPORT
3588 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3589 Error **errp)
3591 const char *device = qemu_opt_get(opts, "path");
3592 ChardevHostdev *parallel;
3594 if (device == NULL) {
3595 error_setg(errp, "chardev: parallel: no device path given");
3596 return;
3598 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3599 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3600 parallel->device = g_strdup(device);
3602 #endif
3604 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3605 Error **errp)
3607 const char *device = qemu_opt_get(opts, "path");
3608 ChardevHostdev *dev;
3610 if (device == NULL) {
3611 error_setg(errp, "chardev: pipe: no device path given");
3612 return;
3614 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3615 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3616 dev->device = g_strdup(device);
3619 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3620 Error **errp)
3622 int val;
3623 ChardevRingbuf *ringbuf;
3625 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3626 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3628 val = qemu_opt_get_size(opts, "size", 0);
3629 if (val != 0) {
3630 ringbuf->has_size = true;
3631 ringbuf->size = val;
3635 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3636 Error **errp)
3638 const char *chardev = qemu_opt_get(opts, "chardev");
3639 ChardevMux *mux;
3641 if (chardev == NULL) {
3642 error_setg(errp, "chardev: mux: no chardev given");
3643 return;
3645 mux = backend->u.mux.data = g_new0(ChardevMux, 1);
3646 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
3647 mux->chardev = g_strdup(chardev);
3650 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3651 Error **errp)
3653 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3654 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3655 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3656 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3657 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3658 const char *path = qemu_opt_get(opts, "path");
3659 const char *host = qemu_opt_get(opts, "host");
3660 const char *port = qemu_opt_get(opts, "port");
3661 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3662 SocketAddress *addr;
3663 ChardevSocket *sock;
3665 if (!path) {
3666 if (!host) {
3667 error_setg(errp, "chardev: socket: no host given");
3668 return;
3670 if (!port) {
3671 error_setg(errp, "chardev: socket: no port given");
3672 return;
3674 } else {
3675 if (tls_creds) {
3676 error_setg(errp, "TLS can only be used over TCP socket");
3677 return;
3681 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
3682 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
3684 sock->has_nodelay = true;
3685 sock->nodelay = do_nodelay;
3686 sock->has_server = true;
3687 sock->server = is_listen;
3688 sock->has_telnet = true;
3689 sock->telnet = is_telnet;
3690 sock->has_wait = true;
3691 sock->wait = is_waitconnect;
3692 sock->has_reconnect = true;
3693 sock->reconnect = reconnect;
3694 sock->tls_creds = g_strdup(tls_creds);
3696 addr = g_new0(SocketAddress, 1);
3697 if (path) {
3698 UnixSocketAddress *q_unix;
3699 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3700 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
3701 q_unix->path = g_strdup(path);
3702 } else {
3703 addr->type = SOCKET_ADDRESS_KIND_INET;
3704 addr->u.inet.data = g_new(InetSocketAddress, 1);
3705 *addr->u.inet.data = (InetSocketAddress) {
3706 .host = g_strdup(host),
3707 .port = g_strdup(port),
3708 .has_to = qemu_opt_get(opts, "to"),
3709 .to = qemu_opt_get_number(opts, "to", 0),
3710 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3711 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3712 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3713 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3716 sock->addr = addr;
3719 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3720 Error **errp)
3722 const char *host = qemu_opt_get(opts, "host");
3723 const char *port = qemu_opt_get(opts, "port");
3724 const char *localaddr = qemu_opt_get(opts, "localaddr");
3725 const char *localport = qemu_opt_get(opts, "localport");
3726 bool has_local = false;
3727 SocketAddress *addr;
3728 ChardevUdp *udp;
3730 if (host == NULL || strlen(host) == 0) {
3731 host = "localhost";
3733 if (port == NULL || strlen(port) == 0) {
3734 error_setg(errp, "chardev: udp: remote port not specified");
3735 return;
3737 if (localport == NULL || strlen(localport) == 0) {
3738 localport = "0";
3739 } else {
3740 has_local = true;
3742 if (localaddr == NULL || strlen(localaddr) == 0) {
3743 localaddr = "";
3744 } else {
3745 has_local = true;
3748 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
3749 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
3751 addr = g_new0(SocketAddress, 1);
3752 addr->type = SOCKET_ADDRESS_KIND_INET;
3753 addr->u.inet.data = g_new(InetSocketAddress, 1);
3754 *addr->u.inet.data = (InetSocketAddress) {
3755 .host = g_strdup(host),
3756 .port = g_strdup(port),
3757 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3758 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3759 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3760 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3762 udp->remote = addr;
3764 if (has_local) {
3765 udp->has_local = true;
3766 addr = g_new0(SocketAddress, 1);
3767 addr->type = SOCKET_ADDRESS_KIND_INET;
3768 addr->u.inet.data = g_new(InetSocketAddress, 1);
3769 *addr->u.inet.data = (InetSocketAddress) {
3770 .host = g_strdup(localaddr),
3771 .port = g_strdup(localport),
3773 udp->local = addr;
3777 typedef struct CharDriver {
3778 const char *name;
3779 ChardevBackendKind kind;
3780 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3781 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3782 ChardevReturn *ret, Error **errp);
3783 } CharDriver;
3785 static GSList *backends;
3787 void register_char_driver(const char *name, ChardevBackendKind kind,
3788 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3789 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3790 ChardevReturn *ret, Error **errp))
3792 CharDriver *s;
3794 s = g_malloc0(sizeof(*s));
3795 s->name = g_strdup(name);
3796 s->kind = kind;
3797 s->parse = parse;
3798 s->create = create;
3800 backends = g_slist_append(backends, s);
3803 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3804 void (*init)(struct CharDriverState *s),
3805 Error **errp)
3807 Error *local_err = NULL;
3808 CharDriver *cd;
3809 CharDriverState *chr;
3810 GSList *i;
3811 ChardevReturn *ret = NULL;
3812 ChardevBackend *backend;
3813 const char *id = qemu_opts_id(opts);
3814 char *bid = NULL;
3816 if (id == NULL) {
3817 error_setg(errp, "chardev: no id specified");
3818 goto err;
3821 if (qemu_opt_get(opts, "backend") == NULL) {
3822 error_setg(errp, "chardev: \"%s\" missing backend",
3823 qemu_opts_id(opts));
3824 goto err;
3826 for (i = backends; i; i = i->next) {
3827 cd = i->data;
3829 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3830 break;
3833 if (i == NULL) {
3834 error_setg(errp, "chardev: backend \"%s\" not found",
3835 qemu_opt_get(opts, "backend"));
3836 goto err;
3839 backend = g_new0(ChardevBackend, 1);
3841 if (qemu_opt_get_bool(opts, "mux", 0)) {
3842 bid = g_strdup_printf("%s-base", id);
3845 chr = NULL;
3846 backend->type = cd->kind;
3847 if (cd->parse) {
3848 cd->parse(opts, backend, &local_err);
3849 if (local_err) {
3850 error_propagate(errp, local_err);
3851 goto qapi_out;
3853 } else {
3854 ChardevCommon *cc = g_new0(ChardevCommon, 1);
3855 qemu_chr_parse_common(opts, cc);
3856 backend->u.null.data = cc; /* Any ChardevCommon member would work */
3859 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3860 if (!ret) {
3861 goto qapi_out;
3864 if (bid) {
3865 qapi_free_ChardevBackend(backend);
3866 qapi_free_ChardevReturn(ret);
3867 backend = g_new0(ChardevBackend, 1);
3868 backend->u.mux.data = g_new0(ChardevMux, 1);
3869 backend->type = CHARDEV_BACKEND_KIND_MUX;
3870 backend->u.mux.data->chardev = g_strdup(bid);
3871 ret = qmp_chardev_add(id, backend, errp);
3872 if (!ret) {
3873 chr = qemu_chr_find(bid);
3874 qemu_chr_delete(chr);
3875 chr = NULL;
3876 goto qapi_out;
3880 chr = qemu_chr_find(id);
3881 chr->opts = opts;
3883 qapi_out:
3884 qapi_free_ChardevBackend(backend);
3885 qapi_free_ChardevReturn(ret);
3886 g_free(bid);
3887 return chr;
3889 err:
3890 qemu_opts_del(opts);
3891 return NULL;
3894 CharDriverState *qemu_chr_new_noreplay(const char *label, const char *filename,
3895 void (*init)(struct CharDriverState *s))
3897 const char *p;
3898 CharDriverState *chr;
3899 QemuOpts *opts;
3900 Error *err = NULL;
3902 if (strstart(filename, "chardev:", &p)) {
3903 return qemu_chr_find(p);
3906 opts = qemu_chr_parse_compat(label, filename);
3907 if (!opts)
3908 return NULL;
3910 chr = qemu_chr_new_from_opts(opts, init, &err);
3911 if (err) {
3912 error_report_err(err);
3914 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3915 qemu_chr_fe_claim_no_fail(chr);
3916 monitor_init(chr, MONITOR_USE_READLINE);
3918 return chr;
3921 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3923 CharDriverState *chr;
3924 chr = qemu_chr_new_noreplay(label, filename, init);
3925 if (chr) {
3926 chr->replay = replay_mode != REPLAY_MODE_NONE;
3927 if (chr->replay && chr->chr_ioctl) {
3928 fprintf(stderr,
3929 "Replay: ioctl is not supported for serial devices yet\n");
3931 replay_register_char_driver(chr);
3933 return chr;
3936 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3938 if (chr->chr_set_echo) {
3939 chr->chr_set_echo(chr, echo);
3943 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3945 if (chr->fe_open == fe_open) {
3946 return;
3948 chr->fe_open = fe_open;
3949 if (chr->chr_set_fe_open) {
3950 chr->chr_set_fe_open(chr, fe_open);
3954 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3956 if (chr->chr_fe_event) {
3957 chr->chr_fe_event(chr, event);
3961 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3962 GIOFunc func, void *user_data)
3964 GSource *src;
3965 guint tag;
3967 if (s->chr_add_watch == NULL) {
3968 return -ENOSYS;
3971 src = s->chr_add_watch(s, cond);
3972 if (!src) {
3973 return -EINVAL;
3976 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3977 tag = g_source_attach(src, NULL);
3978 g_source_unref(src);
3980 return tag;
3983 int qemu_chr_fe_claim(CharDriverState *s)
3985 if (s->avail_connections < 1) {
3986 return -1;
3988 s->avail_connections--;
3989 return 0;
3992 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3994 if (qemu_chr_fe_claim(s) != 0) {
3995 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3996 __func__, s->label);
3997 exit(1);
4001 void qemu_chr_fe_release(CharDriverState *s)
4003 s->avail_connections++;
4006 static void qemu_chr_free_common(CharDriverState *chr)
4008 g_free(chr->filename);
4009 g_free(chr->label);
4010 qemu_opts_del(chr->opts);
4011 if (chr->logfd != -1) {
4012 close(chr->logfd);
4014 qemu_mutex_destroy(&chr->chr_write_lock);
4015 g_free(chr);
4018 void qemu_chr_free(CharDriverState *chr)
4020 if (chr->chr_close) {
4021 chr->chr_close(chr);
4023 qemu_chr_free_common(chr);
4026 void qemu_chr_delete(CharDriverState *chr)
4028 QTAILQ_REMOVE(&chardevs, chr, next);
4029 qemu_chr_free(chr);
4032 ChardevInfoList *qmp_query_chardev(Error **errp)
4034 ChardevInfoList *chr_list = NULL;
4035 CharDriverState *chr;
4037 QTAILQ_FOREACH(chr, &chardevs, next) {
4038 ChardevInfoList *info = g_malloc0(sizeof(*info));
4039 info->value = g_malloc0(sizeof(*info->value));
4040 info->value->label = g_strdup(chr->label);
4041 info->value->filename = g_strdup(chr->filename);
4042 info->value->frontend_open = chr->fe_open;
4044 info->next = chr_list;
4045 chr_list = info;
4048 return chr_list;
4051 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4053 ChardevBackendInfoList *backend_list = NULL;
4054 CharDriver *c = NULL;
4055 GSList *i = NULL;
4057 for (i = backends; i; i = i->next) {
4058 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4059 c = i->data;
4060 info->value = g_malloc0(sizeof(*info->value));
4061 info->value->name = g_strdup(c->name);
4063 info->next = backend_list;
4064 backend_list = info;
4067 return backend_list;
4070 CharDriverState *qemu_chr_find(const char *name)
4072 CharDriverState *chr;
4074 QTAILQ_FOREACH(chr, &chardevs, next) {
4075 if (strcmp(chr->label, name) != 0)
4076 continue;
4077 return chr;
4079 return NULL;
4082 /* Get a character (serial) device interface. */
4083 CharDriverState *qemu_char_get_next_serial(void)
4085 static int next_serial;
4086 CharDriverState *chr;
4088 /* FIXME: This function needs to go away: use chardev properties! */
4090 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
4091 chr = serial_hds[next_serial++];
4092 qemu_chr_fe_claim_no_fail(chr);
4093 return chr;
4095 return NULL;
4098 QemuOptsList qemu_chardev_opts = {
4099 .name = "chardev",
4100 .implied_opt_name = "backend",
4101 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4102 .desc = {
4104 .name = "backend",
4105 .type = QEMU_OPT_STRING,
4107 .name = "path",
4108 .type = QEMU_OPT_STRING,
4110 .name = "host",
4111 .type = QEMU_OPT_STRING,
4113 .name = "port",
4114 .type = QEMU_OPT_STRING,
4116 .name = "localaddr",
4117 .type = QEMU_OPT_STRING,
4119 .name = "localport",
4120 .type = QEMU_OPT_STRING,
4122 .name = "to",
4123 .type = QEMU_OPT_NUMBER,
4125 .name = "ipv4",
4126 .type = QEMU_OPT_BOOL,
4128 .name = "ipv6",
4129 .type = QEMU_OPT_BOOL,
4131 .name = "wait",
4132 .type = QEMU_OPT_BOOL,
4134 .name = "server",
4135 .type = QEMU_OPT_BOOL,
4137 .name = "delay",
4138 .type = QEMU_OPT_BOOL,
4140 .name = "reconnect",
4141 .type = QEMU_OPT_NUMBER,
4143 .name = "telnet",
4144 .type = QEMU_OPT_BOOL,
4146 .name = "tls-creds",
4147 .type = QEMU_OPT_STRING,
4149 .name = "width",
4150 .type = QEMU_OPT_NUMBER,
4152 .name = "height",
4153 .type = QEMU_OPT_NUMBER,
4155 .name = "cols",
4156 .type = QEMU_OPT_NUMBER,
4158 .name = "rows",
4159 .type = QEMU_OPT_NUMBER,
4161 .name = "mux",
4162 .type = QEMU_OPT_BOOL,
4164 .name = "signal",
4165 .type = QEMU_OPT_BOOL,
4167 .name = "name",
4168 .type = QEMU_OPT_STRING,
4170 .name = "debug",
4171 .type = QEMU_OPT_NUMBER,
4173 .name = "size",
4174 .type = QEMU_OPT_SIZE,
4176 .name = "chardev",
4177 .type = QEMU_OPT_STRING,
4179 .name = "append",
4180 .type = QEMU_OPT_BOOL,
4182 .name = "logfile",
4183 .type = QEMU_OPT_STRING,
4185 .name = "logappend",
4186 .type = QEMU_OPT_BOOL,
4188 { /* end of list */ }
4192 #ifdef _WIN32
4194 static CharDriverState *qmp_chardev_open_file(const char *id,
4195 ChardevBackend *backend,
4196 ChardevReturn *ret,
4197 Error **errp)
4199 ChardevFile *file = backend->u.file.data;
4200 ChardevCommon *common = qapi_ChardevFile_base(file);
4201 HANDLE out;
4203 if (file->has_in) {
4204 error_setg(errp, "input file not supported");
4205 return NULL;
4208 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
4209 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
4210 if (out == INVALID_HANDLE_VALUE) {
4211 error_setg(errp, "open %s failed", file->out);
4212 return NULL;
4214 return qemu_chr_open_win_file(out, common, errp);
4217 static CharDriverState *qmp_chardev_open_serial(const char *id,
4218 ChardevBackend *backend,
4219 ChardevReturn *ret,
4220 Error **errp)
4222 ChardevHostdev *serial = backend->u.serial.data;
4223 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4224 return qemu_chr_open_win_path(serial->device, common, errp);
4227 #else /* WIN32 */
4229 static int qmp_chardev_open_file_source(char *src, int flags,
4230 Error **errp)
4232 int fd = -1;
4234 TFR(fd = qemu_open(src, flags, 0666));
4235 if (fd == -1) {
4236 error_setg_file_open(errp, errno, src);
4238 return fd;
4241 static CharDriverState *qmp_chardev_open_file(const char *id,
4242 ChardevBackend *backend,
4243 ChardevReturn *ret,
4244 Error **errp)
4246 ChardevFile *file = backend->u.file.data;
4247 ChardevCommon *common = qapi_ChardevFile_base(file);
4248 int flags, in = -1, out;
4250 flags = O_WRONLY | O_CREAT | O_BINARY;
4251 if (file->has_append && file->append) {
4252 flags |= O_APPEND;
4253 } else {
4254 flags |= O_TRUNC;
4257 out = qmp_chardev_open_file_source(file->out, flags, errp);
4258 if (out < 0) {
4259 return NULL;
4262 if (file->has_in) {
4263 flags = O_RDONLY;
4264 in = qmp_chardev_open_file_source(file->in, flags, errp);
4265 if (in < 0) {
4266 qemu_close(out);
4267 return NULL;
4271 return qemu_chr_open_fd(in, out, common, errp);
4274 #ifdef HAVE_CHARDEV_SERIAL
4275 static CharDriverState *qmp_chardev_open_serial(const char *id,
4276 ChardevBackend *backend,
4277 ChardevReturn *ret,
4278 Error **errp)
4280 ChardevHostdev *serial = backend->u.serial.data;
4281 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4282 int fd;
4284 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4285 if (fd < 0) {
4286 return NULL;
4288 qemu_set_nonblock(fd);
4289 return qemu_chr_open_tty_fd(fd, common, errp);
4291 #endif
4293 #ifdef HAVE_CHARDEV_PARPORT
4294 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4295 ChardevBackend *backend,
4296 ChardevReturn *ret,
4297 Error **errp)
4299 ChardevHostdev *parallel = backend->u.parallel.data;
4300 ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
4301 int fd;
4303 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4304 if (fd < 0) {
4305 return NULL;
4307 return qemu_chr_open_pp_fd(fd, common, errp);
4309 #endif
4311 #endif /* WIN32 */
4313 static gboolean socket_reconnect_timeout(gpointer opaque)
4315 CharDriverState *chr = opaque;
4316 TCPCharDriver *s = chr->opaque;
4317 QIOChannelSocket *sioc;
4319 s->reconnect_timer = 0;
4321 if (chr->be_open) {
4322 return false;
4325 sioc = qio_channel_socket_new();
4326 qio_channel_socket_connect_async(sioc, s->addr,
4327 qemu_chr_socket_connected,
4328 chr, NULL);
4330 return false;
4333 static CharDriverState *qmp_chardev_open_socket(const char *id,
4334 ChardevBackend *backend,
4335 ChardevReturn *ret,
4336 Error **errp)
4338 CharDriverState *chr;
4339 TCPCharDriver *s;
4340 ChardevSocket *sock = backend->u.socket.data;
4341 SocketAddress *addr = sock->addr;
4342 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4343 bool is_listen = sock->has_server ? sock->server : true;
4344 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4345 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4346 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4347 ChardevCommon *common = qapi_ChardevSocket_base(sock);
4348 QIOChannelSocket *sioc = NULL;
4350 chr = qemu_chr_alloc(common, errp);
4351 if (!chr) {
4352 return NULL;
4354 s = g_new0(TCPCharDriver, 1);
4356 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4357 s->is_listen = is_listen;
4358 s->is_telnet = is_telnet;
4359 s->do_nodelay = do_nodelay;
4360 if (sock->tls_creds) {
4361 Object *creds;
4362 creds = object_resolve_path_component(
4363 object_get_objects_root(), sock->tls_creds);
4364 if (!creds) {
4365 error_setg(errp, "No TLS credentials with id '%s'",
4366 sock->tls_creds);
4367 goto error;
4369 s->tls_creds = (QCryptoTLSCreds *)
4370 object_dynamic_cast(creds,
4371 TYPE_QCRYPTO_TLS_CREDS);
4372 if (!s->tls_creds) {
4373 error_setg(errp, "Object with id '%s' is not TLS credentials",
4374 sock->tls_creds);
4375 goto error;
4377 object_ref(OBJECT(s->tls_creds));
4378 if (is_listen) {
4379 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4380 error_setg(errp, "%s",
4381 "Expected TLS credentials for server endpoint");
4382 goto error;
4384 } else {
4385 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4386 error_setg(errp, "%s",
4387 "Expected TLS credentials for client endpoint");
4388 goto error;
4393 qapi_copy_SocketAddress(&s->addr, sock->addr);
4395 chr->opaque = s;
4396 chr->chr_write = tcp_chr_write;
4397 chr->chr_sync_read = tcp_chr_sync_read;
4398 chr->chr_close = tcp_chr_close;
4399 chr->get_msgfds = tcp_get_msgfds;
4400 chr->set_msgfds = tcp_set_msgfds;
4401 chr->chr_add_client = tcp_chr_add_client;
4402 chr->chr_add_watch = tcp_chr_add_watch;
4403 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4404 /* be isn't opened until we get a connection */
4405 chr->explicit_be_open = true;
4407 chr->filename = SocketAddress_to_str("disconnected:",
4408 addr, is_listen, is_telnet);
4410 if (is_listen) {
4411 if (is_telnet) {
4412 s->do_telnetopt = 1;
4414 } else if (reconnect > 0) {
4415 s->reconnect_time = reconnect;
4418 sioc = qio_channel_socket_new();
4419 if (s->reconnect_time) {
4420 qio_channel_socket_connect_async(sioc, s->addr,
4421 qemu_chr_socket_connected,
4422 chr, NULL);
4423 } else if (s->is_listen) {
4424 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4425 goto error;
4427 s->listen_ioc = sioc;
4428 if (is_waitconnect) {
4429 fprintf(stderr, "QEMU waiting for connection on: %s\n",
4430 chr->filename);
4431 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
4433 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
4434 if (!s->ioc) {
4435 s->listen_tag = qio_channel_add_watch(
4436 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
4438 } else {
4439 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
4440 goto error;
4442 tcp_chr_new_client(chr, sioc);
4443 object_unref(OBJECT(sioc));
4446 return chr;
4448 error:
4449 if (sioc) {
4450 object_unref(OBJECT(sioc));
4452 if (s->tls_creds) {
4453 object_unref(OBJECT(s->tls_creds));
4455 g_free(s);
4456 qemu_chr_free_common(chr);
4457 return NULL;
4460 static CharDriverState *qmp_chardev_open_udp(const char *id,
4461 ChardevBackend *backend,
4462 ChardevReturn *ret,
4463 Error **errp)
4465 ChardevUdp *udp = backend->u.udp.data;
4466 ChardevCommon *common = qapi_ChardevUdp_base(udp);
4467 QIOChannelSocket *sioc = qio_channel_socket_new();
4469 if (qio_channel_socket_dgram_sync(sioc,
4470 udp->local, udp->remote,
4471 errp) < 0) {
4472 object_unref(OBJECT(sioc));
4473 return NULL;
4475 return qemu_chr_open_udp(sioc, common, errp);
4478 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4479 Error **errp)
4481 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4482 CharDriverState *chr = NULL;
4483 Error *local_err = NULL;
4484 GSList *i;
4485 CharDriver *cd;
4487 chr = qemu_chr_find(id);
4488 if (chr) {
4489 error_setg(errp, "Chardev '%s' already exists", id);
4490 g_free(ret);
4491 return NULL;
4494 for (i = backends; i; i = i->next) {
4495 cd = i->data;
4497 if (cd->kind == backend->type) {
4498 chr = cd->create(id, backend, ret, &local_err);
4499 if (local_err) {
4500 error_propagate(errp, local_err);
4501 goto out_error;
4503 break;
4507 if (chr == NULL) {
4508 assert(!i);
4509 error_setg(errp, "chardev backend not available");
4510 goto out_error;
4513 chr->label = g_strdup(id);
4514 chr->avail_connections =
4515 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4516 if (!chr->filename) {
4517 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4519 if (!chr->explicit_be_open) {
4520 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4522 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4523 return ret;
4525 out_error:
4526 g_free(ret);
4527 return NULL;
4530 void qmp_chardev_remove(const char *id, Error **errp)
4532 CharDriverState *chr;
4534 chr = qemu_chr_find(id);
4535 if (chr == NULL) {
4536 error_setg(errp, "Chardev '%s' not found", id);
4537 return;
4539 if (chr->chr_can_read || chr->chr_read ||
4540 chr->chr_event || chr->handler_opaque) {
4541 error_setg(errp, "Chardev '%s' is busy", id);
4542 return;
4544 if (chr->replay) {
4545 error_setg(errp,
4546 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4547 return;
4549 qemu_chr_delete(chr);
4552 static void register_types(void)
4554 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4555 qemu_chr_open_null);
4556 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4557 qemu_chr_parse_socket, qmp_chardev_open_socket);
4558 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4559 qmp_chardev_open_udp);
4560 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4561 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4562 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4563 qemu_chr_parse_file_out, qmp_chardev_open_file);
4564 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4565 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4566 #if defined HAVE_CHARDEV_SERIAL
4567 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4568 qemu_chr_parse_serial, qmp_chardev_open_serial);
4569 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4570 qemu_chr_parse_serial, qmp_chardev_open_serial);
4571 #endif
4572 #ifdef HAVE_CHARDEV_PARPORT
4573 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4574 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4575 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4576 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4577 #endif
4578 #ifdef HAVE_CHARDEV_PTY
4579 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4580 qemu_chr_open_pty);
4581 #endif
4582 #ifdef _WIN32
4583 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4584 qemu_chr_open_win_con);
4585 #endif
4586 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4587 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4588 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4589 qemu_chr_open_mux);
4590 /* Bug-compatibility: */
4591 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4592 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4593 /* this must be done after machine init, since we register FEs with muxes
4594 * as part of realize functions like serial_isa_realizefn when -nographic
4595 * is specified
4597 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4600 type_init(register_types);