Merge remote-tracking branch 'remotes/mst/tags/for_upstream' into staging
[qemu/kevin.git] / qemu-char.c
blob721ce21ea2ae8de9a842b9a22d4b498ff981ff7c
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 "qemu/cutils.h"
27 #include "monitor/monitor.h"
28 #include "sysemu/sysemu.h"
29 #include "sysemu/block-backend.h"
30 #include "qemu/error-report.h"
31 #include "qemu/timer.h"
32 #include "sysemu/char.h"
33 #include "hw/usb.h"
34 #include "qmp-commands.h"
35 #include "qapi/clone-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"
42 #include "qemu/help_option.h"
44 #include <zlib.h>
46 #ifndef _WIN32
47 #include <sys/times.h>
48 #include <sys/wait.h>
49 #include <termios.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 chr->mux_idx = -1;
169 if (backend->has_logfile) {
170 int flags = O_WRONLY | O_CREAT;
171 if (backend->has_logappend &&
172 backend->logappend) {
173 flags |= O_APPEND;
174 } else {
175 flags |= O_TRUNC;
177 chr->logfd = qemu_open(backend->logfile, flags, 0666);
178 if (chr->logfd < 0) {
179 error_setg_errno(errp, errno,
180 "Unable to open logfile %s",
181 backend->logfile);
182 g_free(chr);
183 return NULL;
185 } else {
186 chr->logfd = -1;
189 return chr;
192 void qemu_chr_be_event(CharDriverState *s, int event)
194 /* Keep track if the char device is open */
195 switch (event) {
196 case CHR_EVENT_OPENED:
197 s->be_open = 1;
198 break;
199 case CHR_EVENT_CLOSED:
200 s->be_open = 0;
201 break;
204 if (!s->chr_event)
205 return;
206 s->chr_event(s->handler_opaque, event);
209 void qemu_chr_be_generic_open(CharDriverState *s)
211 qemu_chr_be_event(s, CHR_EVENT_OPENED);
215 /* Not reporting errors from writing to logfile, as logs are
216 * defined to be "best effort" only */
217 static void qemu_chr_fe_write_log(CharDriverState *s,
218 const uint8_t *buf, size_t len)
220 size_t done = 0;
221 ssize_t ret;
223 if (s->logfd < 0) {
224 return;
227 while (done < len) {
228 retry:
229 ret = write(s->logfd, buf + done, len - done);
230 if (ret == -1 && errno == EAGAIN) {
231 g_usleep(100);
232 goto retry;
235 if (ret <= 0) {
236 return;
238 done += ret;
242 static int qemu_chr_fe_write_buffer(CharDriverState *s, const uint8_t *buf, int len, int *offset)
244 int res = 0;
245 *offset = 0;
247 qemu_mutex_lock(&s->chr_write_lock);
248 while (*offset < len) {
249 retry:
250 res = s->chr_write(s, buf + *offset, len - *offset);
251 if (res < 0 && errno == EAGAIN) {
252 g_usleep(100);
253 goto retry;
256 if (res <= 0) {
257 break;
260 *offset += res;
262 if (*offset > 0) {
263 qemu_chr_fe_write_log(s, buf, *offset);
265 qemu_mutex_unlock(&s->chr_write_lock);
267 return res;
270 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
272 int ret;
274 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
275 int offset;
276 replay_char_write_event_load(&ret, &offset);
277 assert(offset <= len);
278 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
279 return ret;
282 qemu_mutex_lock(&s->chr_write_lock);
283 ret = s->chr_write(s, buf, len);
285 if (ret > 0) {
286 qemu_chr_fe_write_log(s, buf, ret);
289 qemu_mutex_unlock(&s->chr_write_lock);
291 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
292 replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
295 return ret;
298 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
300 int offset;
301 int res;
303 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
304 replay_char_write_event_load(&res, &offset);
305 assert(offset <= len);
306 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
307 return res;
310 res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
312 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
313 replay_char_write_event_save(res, offset);
316 if (res < 0) {
317 return res;
319 return offset;
322 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
324 int offset = 0, counter = 10;
325 int res;
327 if (!s->chr_sync_read) {
328 return 0;
331 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
332 return replay_char_read_all_load(buf);
335 while (offset < len) {
336 retry:
337 res = s->chr_sync_read(s, buf + offset, len - offset);
338 if (res == -1 && errno == EAGAIN) {
339 g_usleep(100);
340 goto retry;
343 if (res == 0) {
344 break;
347 if (res < 0) {
348 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
349 replay_char_read_all_save_error(res);
351 return res;
354 offset += res;
356 if (!counter--) {
357 break;
361 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
362 replay_char_read_all_save_buf(buf, offset);
364 return offset;
367 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
369 int res;
370 if (!s->chr_ioctl || s->replay) {
371 res = -ENOTSUP;
372 } else {
373 res = s->chr_ioctl(s, cmd, arg);
376 return res;
379 int qemu_chr_be_can_write(CharDriverState *s)
381 if (!s->chr_can_read)
382 return 0;
383 return s->chr_can_read(s->handler_opaque);
386 void qemu_chr_be_write_impl(CharDriverState *s, uint8_t *buf, int len)
388 if (s->chr_read) {
389 s->chr_read(s->handler_opaque, buf, len);
393 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
395 if (s->replay) {
396 if (replay_mode == REPLAY_MODE_PLAY) {
397 return;
399 replay_chr_be_write(s, buf, len);
400 } else {
401 qemu_chr_be_write_impl(s, buf, len);
405 int qemu_chr_fe_get_msgfd(CharDriverState *s)
407 int fd;
408 int res = (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
409 if (s->replay) {
410 fprintf(stderr,
411 "Replay: get msgfd is not supported for serial devices yet\n");
412 exit(1);
414 return res;
417 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
419 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
422 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
424 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
427 int qemu_chr_add_client(CharDriverState *s, int fd)
429 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
432 void qemu_chr_accept_input(CharDriverState *s)
434 if (s->chr_accept_input)
435 s->chr_accept_input(s);
436 qemu_notify_event();
439 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
441 char buf[READ_BUF_LEN];
442 va_list ap;
443 va_start(ap, fmt);
444 vsnprintf(buf, sizeof(buf), fmt, ap);
445 /* XXX this blocks entire thread. Rewrite to use
446 * qemu_chr_fe_write and background I/O callbacks */
447 qemu_chr_fe_write_all(s, (uint8_t *)buf, strlen(buf));
448 va_end(ap);
451 static void remove_fd_in_watch(CharDriverState *chr);
453 void qemu_chr_add_handlers_full(CharDriverState *s,
454 IOCanReadHandler *fd_can_read,
455 IOReadHandler *fd_read,
456 IOEventHandler *fd_event,
457 void *opaque,
458 GMainContext *context)
460 int fe_open;
462 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
463 fe_open = 0;
464 remove_fd_in_watch(s);
465 } else {
466 fe_open = 1;
468 s->chr_can_read = fd_can_read;
469 s->chr_read = fd_read;
470 s->chr_event = fd_event;
471 s->handler_opaque = opaque;
472 if (s->chr_update_read_handler) {
473 s->chr_update_read_handler(s, context);
476 if (!s->explicit_fe_open) {
477 qemu_chr_fe_set_open(s, fe_open);
480 /* We're connecting to an already opened device, so let's make sure we
481 also get the open event */
482 if (fe_open && s->be_open) {
483 qemu_chr_be_generic_open(s);
487 void qemu_chr_add_handlers(CharDriverState *s,
488 IOCanReadHandler *fd_can_read,
489 IOReadHandler *fd_read,
490 IOEventHandler *fd_event,
491 void *opaque)
493 qemu_chr_add_handlers_full(s, fd_can_read, fd_read,
494 fd_event, opaque, NULL);
497 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
499 return len;
502 static CharDriverState *qemu_chr_open_null(const char *id,
503 ChardevBackend *backend,
504 ChardevReturn *ret,
505 Error **errp)
507 CharDriverState *chr;
508 ChardevCommon *common = backend->u.null.data;
510 chr = qemu_chr_alloc(common, errp);
511 if (!chr) {
512 return NULL;
514 chr->chr_write = null_chr_write;
515 chr->explicit_be_open = true;
516 return chr;
519 /* MUX driver for serial I/O splitting */
520 #define MAX_MUX 4
521 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
522 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
523 typedef struct {
524 IOCanReadHandler *chr_can_read[MAX_MUX];
525 IOReadHandler *chr_read[MAX_MUX];
526 IOEventHandler *chr_event[MAX_MUX];
527 void *ext_opaque[MAX_MUX];
528 CharDriverState *drv;
529 int focus;
530 int mux_cnt;
531 int term_got_escape;
532 int max_size;
533 /* Intermediate input buffer allows to catch escape sequences even if the
534 currently active device is not accepting any input - but only until it
535 is full as well. */
536 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
537 int prod[MAX_MUX];
538 int cons[MAX_MUX];
539 int timestamps;
541 /* Protected by the CharDriverState chr_write_lock. */
542 int linestart;
543 int64_t timestamps_start;
544 } MuxDriver;
547 /* Called with chr_write_lock held. */
548 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
550 MuxDriver *d = chr->opaque;
551 int ret;
552 if (!d->timestamps) {
553 ret = qemu_chr_fe_write(d->drv, buf, len);
554 } else {
555 int i;
557 ret = 0;
558 for (i = 0; i < len; i++) {
559 if (d->linestart) {
560 char buf1[64];
561 int64_t ti;
562 int secs;
564 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
565 if (d->timestamps_start == -1)
566 d->timestamps_start = ti;
567 ti -= d->timestamps_start;
568 secs = ti / 1000;
569 snprintf(buf1, sizeof(buf1),
570 "[%02d:%02d:%02d.%03d] ",
571 secs / 3600,
572 (secs / 60) % 60,
573 secs % 60,
574 (int)(ti % 1000));
575 /* XXX this blocks entire thread. Rewrite to use
576 * qemu_chr_fe_write and background I/O callbacks */
577 qemu_chr_fe_write_all(d->drv, (uint8_t *)buf1, strlen(buf1));
578 d->linestart = 0;
580 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
581 if (buf[i] == '\n') {
582 d->linestart = 1;
586 return ret;
589 static const char * const mux_help[] = {
590 "% h print this help\n\r",
591 "% x exit emulator\n\r",
592 "% s save disk data back to file (if -snapshot)\n\r",
593 "% t toggle console timestamps\n\r",
594 "% b send break (magic sysrq)\n\r",
595 "% c switch between console and monitor\n\r",
596 "% % sends %\n\r",
597 NULL
600 int term_escape_char = 0x01; /* ctrl-a is used for escape */
601 static void mux_print_help(CharDriverState *chr)
603 int i, j;
604 char ebuf[15] = "Escape-Char";
605 char cbuf[50] = "\n\r";
607 if (term_escape_char > 0 && term_escape_char < 26) {
608 snprintf(cbuf, sizeof(cbuf), "\n\r");
609 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
610 } else {
611 snprintf(cbuf, sizeof(cbuf),
612 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
613 term_escape_char);
615 /* XXX this blocks entire thread. Rewrite to use
616 * qemu_chr_fe_write and background I/O callbacks */
617 qemu_chr_fe_write_all(chr, (uint8_t *)cbuf, strlen(cbuf));
618 for (i = 0; mux_help[i] != NULL; i++) {
619 for (j=0; mux_help[i][j] != '\0'; j++) {
620 if (mux_help[i][j] == '%')
621 qemu_chr_fe_write_all(chr, (uint8_t *)ebuf, strlen(ebuf));
622 else
623 qemu_chr_fe_write_all(chr, (uint8_t *)&mux_help[i][j], 1);
628 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
630 if (d->chr_event[mux_nr])
631 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
634 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
636 if (d->term_got_escape) {
637 d->term_got_escape = 0;
638 if (ch == term_escape_char)
639 goto send_char;
640 switch(ch) {
641 case '?':
642 case 'h':
643 mux_print_help(chr);
644 break;
645 case 'x':
647 const char *term = "QEMU: Terminated\n\r";
648 qemu_chr_fe_write_all(chr, (uint8_t *)term, strlen(term));
649 exit(0);
650 break;
652 case 's':
653 blk_commit_all();
654 break;
655 case 'b':
656 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
657 break;
658 case 'c':
659 /* Switch to the next registered device */
660 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
661 d->focus++;
662 if (d->focus >= d->mux_cnt)
663 d->focus = 0;
664 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
665 break;
666 case 't':
667 d->timestamps = !d->timestamps;
668 d->timestamps_start = -1;
669 d->linestart = 0;
670 break;
672 } else if (ch == term_escape_char) {
673 d->term_got_escape = 1;
674 } else {
675 send_char:
676 return 1;
678 return 0;
681 static void mux_chr_accept_input(CharDriverState *chr)
683 MuxDriver *d = chr->opaque;
684 int m = d->focus;
686 while (d->prod[m] != d->cons[m] &&
687 d->chr_can_read[m] &&
688 d->chr_can_read[m](d->ext_opaque[m])) {
689 d->chr_read[m](d->ext_opaque[m],
690 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
694 static int mux_chr_can_read(void *opaque)
696 CharDriverState *chr = opaque;
697 MuxDriver *d = chr->opaque;
698 int m = d->focus;
700 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
701 return 1;
702 if (d->chr_can_read[m])
703 return d->chr_can_read[m](d->ext_opaque[m]);
704 return 0;
707 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
709 CharDriverState *chr = opaque;
710 MuxDriver *d = chr->opaque;
711 int m = d->focus;
712 int i;
714 mux_chr_accept_input (opaque);
716 for(i = 0; i < size; i++)
717 if (mux_proc_byte(chr, d, buf[i])) {
718 if (d->prod[m] == d->cons[m] &&
719 d->chr_can_read[m] &&
720 d->chr_can_read[m](d->ext_opaque[m]))
721 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
722 else
723 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
727 static void mux_chr_event(void *opaque, int event)
729 CharDriverState *chr = opaque;
730 MuxDriver *d = chr->opaque;
731 int i;
733 /* Send the event to all registered listeners */
734 for (i = 0; i < d->mux_cnt; i++)
735 mux_chr_send_event(d, i, event);
738 static void mux_chr_update_read_handler(CharDriverState *chr,
739 GMainContext *context)
741 MuxDriver *d = chr->opaque;
742 int idx;
744 if (d->mux_cnt >= MAX_MUX) {
745 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
746 return;
749 if (chr->mux_idx == -1) {
750 chr->mux_idx = d->mux_cnt++;
753 idx = chr->mux_idx;
754 d->ext_opaque[idx] = chr->handler_opaque;
755 d->chr_can_read[idx] = chr->chr_can_read;
756 d->chr_read[idx] = chr->chr_read;
757 d->chr_event[idx] = chr->chr_event;
759 /* Fix up the real driver with mux routines */
760 if (d->mux_cnt == 1) {
761 qemu_chr_add_handlers_full(d->drv, mux_chr_can_read,
762 mux_chr_read,
763 mux_chr_event,
764 chr, context);
766 if (d->focus != -1) {
767 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
769 d->focus = idx;
770 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
773 static bool muxes_realized;
776 * Called after processing of default and command-line-specified
777 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
778 * to a mux chardev. This is done here to ensure that
779 * output/prompts/banners are only displayed for the FE that has
780 * focus when initial command-line processing/machine init is
781 * completed.
783 * After this point, any new FE attached to any new or existing
784 * mux will receive CHR_EVENT_OPENED notifications for the BE
785 * immediately.
787 static void muxes_realize_done(Notifier *notifier, void *unused)
789 CharDriverState *chr;
791 QTAILQ_FOREACH(chr, &chardevs, next) {
792 if (chr->is_mux) {
793 MuxDriver *d = chr->opaque;
794 int i;
796 /* send OPENED to all already-attached FEs */
797 for (i = 0; i < d->mux_cnt; i++) {
798 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
800 /* mark mux as OPENED so any new FEs will immediately receive
801 * OPENED event
803 qemu_chr_be_generic_open(chr);
806 muxes_realized = true;
809 static Notifier muxes_realize_notify = {
810 .notify = muxes_realize_done,
813 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
815 MuxDriver *d = s->opaque;
816 return d->drv->chr_add_watch(d->drv, cond);
819 static void mux_chr_close(struct CharDriverState *chr)
821 MuxDriver *d = chr->opaque;
823 g_free(d);
826 static CharDriverState *qemu_chr_open_mux(const char *id,
827 ChardevBackend *backend,
828 ChardevReturn *ret, Error **errp)
830 ChardevMux *mux = backend->u.mux.data;
831 CharDriverState *chr, *drv;
832 MuxDriver *d;
833 ChardevCommon *common = qapi_ChardevMux_base(mux);
835 drv = qemu_chr_find(mux->chardev);
836 if (drv == NULL) {
837 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
838 return NULL;
841 chr = qemu_chr_alloc(common, errp);
842 if (!chr) {
843 return NULL;
845 d = g_new0(MuxDriver, 1);
847 chr->opaque = d;
848 d->drv = drv;
849 d->focus = -1;
850 chr->chr_close = mux_chr_close;
851 chr->chr_write = mux_chr_write;
852 chr->chr_update_read_handler = mux_chr_update_read_handler;
853 chr->chr_accept_input = mux_chr_accept_input;
854 /* Frontend guest-open / -close notification is not support with muxes */
855 chr->chr_set_fe_open = NULL;
856 if (drv->chr_add_watch) {
857 chr->chr_add_watch = mux_chr_add_watch;
859 /* only default to opened state if we've realized the initial
860 * set of muxes
862 chr->explicit_be_open = muxes_realized ? 0 : 1;
863 chr->is_mux = 1;
865 return chr;
869 typedef struct IOWatchPoll
871 GSource parent;
873 QIOChannel *ioc;
874 GSource *src;
876 IOCanReadHandler *fd_can_read;
877 GSourceFunc fd_read;
878 void *opaque;
879 GMainContext *context;
880 } IOWatchPoll;
882 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
884 return container_of(source, IOWatchPoll, parent);
887 static gboolean io_watch_poll_prepare(GSource *source,
888 gint *timeout_)
890 IOWatchPoll *iwp = io_watch_poll_from_source(source);
891 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
892 bool was_active = iwp->src != NULL;
893 if (was_active == now_active) {
894 return FALSE;
897 if (now_active) {
898 iwp->src = qio_channel_create_watch(
899 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
900 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
901 g_source_attach(iwp->src, iwp->context);
902 } else {
903 g_source_destroy(iwp->src);
904 g_source_unref(iwp->src);
905 iwp->src = NULL;
907 return FALSE;
910 static gboolean io_watch_poll_check(GSource *source)
912 return FALSE;
915 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
916 gpointer user_data)
918 abort();
921 static void io_watch_poll_finalize(GSource *source)
923 /* Due to a glib bug, removing the last reference to a source
924 * inside a finalize callback causes recursive locking (and a
925 * deadlock). This is not a problem inside other callbacks,
926 * including dispatch callbacks, so we call io_remove_watch_poll
927 * to remove this source. At this point, iwp->src must
928 * be NULL, or we would leak it.
930 * This would be solved much more elegantly by child sources,
931 * but we support older glib versions that do not have them.
933 IOWatchPoll *iwp = io_watch_poll_from_source(source);
934 assert(iwp->src == NULL);
937 static GSourceFuncs io_watch_poll_funcs = {
938 .prepare = io_watch_poll_prepare,
939 .check = io_watch_poll_check,
940 .dispatch = io_watch_poll_dispatch,
941 .finalize = io_watch_poll_finalize,
944 /* Can only be used for read */
945 static guint io_add_watch_poll(QIOChannel *ioc,
946 IOCanReadHandler *fd_can_read,
947 QIOChannelFunc fd_read,
948 gpointer user_data,
949 GMainContext *context)
951 IOWatchPoll *iwp;
952 int tag;
954 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs,
955 sizeof(IOWatchPoll));
956 iwp->fd_can_read = fd_can_read;
957 iwp->opaque = user_data;
958 iwp->ioc = ioc;
959 iwp->fd_read = (GSourceFunc) fd_read;
960 iwp->src = NULL;
961 iwp->context = context;
963 tag = g_source_attach(&iwp->parent, context);
964 g_source_unref(&iwp->parent);
965 return tag;
968 static void io_remove_watch_poll(guint tag)
970 GSource *source;
971 IOWatchPoll *iwp;
973 g_return_if_fail (tag > 0);
975 source = g_main_context_find_source_by_id(NULL, tag);
976 g_return_if_fail (source != NULL);
978 iwp = io_watch_poll_from_source(source);
979 if (iwp->src) {
980 g_source_destroy(iwp->src);
981 g_source_unref(iwp->src);
982 iwp->src = NULL;
984 g_source_destroy(&iwp->parent);
987 static void remove_fd_in_watch(CharDriverState *chr)
989 if (chr->fd_in_tag) {
990 io_remove_watch_poll(chr->fd_in_tag);
991 chr->fd_in_tag = 0;
996 static int io_channel_send_full(QIOChannel *ioc,
997 const void *buf, size_t len,
998 int *fds, size_t nfds)
1000 size_t offset = 0;
1002 while (offset < len) {
1003 ssize_t ret = 0;
1004 struct iovec iov = { .iov_base = (char *)buf + offset,
1005 .iov_len = len - offset };
1007 ret = qio_channel_writev_full(
1008 ioc, &iov, 1,
1009 fds, nfds, NULL);
1010 if (ret == QIO_CHANNEL_ERR_BLOCK) {
1011 if (offset) {
1012 return offset;
1015 errno = EAGAIN;
1016 return -1;
1017 } else if (ret < 0) {
1018 errno = EINVAL;
1019 return -1;
1022 offset += ret;
1025 return offset;
1029 #ifndef _WIN32
1030 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
1032 return io_channel_send_full(ioc, buf, len, NULL, 0);
1036 typedef struct FDCharDriver {
1037 CharDriverState *chr;
1038 QIOChannel *ioc_in, *ioc_out;
1039 int max_size;
1040 } FDCharDriver;
1042 /* Called with chr_write_lock held. */
1043 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1045 FDCharDriver *s = chr->opaque;
1047 return io_channel_send(s->ioc_out, buf, len);
1050 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1052 CharDriverState *chr = opaque;
1053 FDCharDriver *s = chr->opaque;
1054 int len;
1055 uint8_t buf[READ_BUF_LEN];
1056 ssize_t ret;
1058 len = sizeof(buf);
1059 if (len > s->max_size) {
1060 len = s->max_size;
1062 if (len == 0) {
1063 return TRUE;
1066 ret = qio_channel_read(
1067 chan, (gchar *)buf, len, NULL);
1068 if (ret == 0) {
1069 remove_fd_in_watch(chr);
1070 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1071 return FALSE;
1073 if (ret > 0) {
1074 qemu_chr_be_write(chr, buf, ret);
1077 return TRUE;
1080 static int fd_chr_read_poll(void *opaque)
1082 CharDriverState *chr = opaque;
1083 FDCharDriver *s = chr->opaque;
1085 s->max_size = qemu_chr_be_can_write(chr);
1086 return s->max_size;
1089 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1091 FDCharDriver *s = chr->opaque;
1092 return qio_channel_create_watch(s->ioc_out, cond);
1095 static void fd_chr_update_read_handler(CharDriverState *chr,
1096 GMainContext *context)
1098 FDCharDriver *s = chr->opaque;
1100 remove_fd_in_watch(chr);
1101 if (s->ioc_in) {
1102 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
1103 fd_chr_read_poll,
1104 fd_chr_read, chr,
1105 context);
1109 static void fd_chr_close(struct CharDriverState *chr)
1111 FDCharDriver *s = chr->opaque;
1113 remove_fd_in_watch(chr);
1114 if (s->ioc_in) {
1115 object_unref(OBJECT(s->ioc_in));
1117 if (s->ioc_out) {
1118 object_unref(OBJECT(s->ioc_out));
1121 g_free(s);
1122 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1125 /* open a character device to a unix fd */
1126 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1127 ChardevCommon *backend, Error **errp)
1129 CharDriverState *chr;
1130 FDCharDriver *s;
1132 chr = qemu_chr_alloc(backend, errp);
1133 if (!chr) {
1134 return NULL;
1136 s = g_new0(FDCharDriver, 1);
1137 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1138 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1139 qemu_set_nonblock(fd_out);
1140 s->chr = chr;
1141 chr->opaque = s;
1142 chr->chr_add_watch = fd_chr_add_watch;
1143 chr->chr_write = fd_chr_write;
1144 chr->chr_update_read_handler = fd_chr_update_read_handler;
1145 chr->chr_close = fd_chr_close;
1147 return chr;
1150 static CharDriverState *qemu_chr_open_pipe(const char *id,
1151 ChardevBackend *backend,
1152 ChardevReturn *ret,
1153 Error **errp)
1155 ChardevHostdev *opts = backend->u.pipe.data;
1156 int fd_in, fd_out;
1157 char *filename_in;
1158 char *filename_out;
1159 const char *filename = opts->device;
1160 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1163 filename_in = g_strdup_printf("%s.in", filename);
1164 filename_out = g_strdup_printf("%s.out", filename);
1165 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1166 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1167 g_free(filename_in);
1168 g_free(filename_out);
1169 if (fd_in < 0 || fd_out < 0) {
1170 if (fd_in >= 0)
1171 close(fd_in);
1172 if (fd_out >= 0)
1173 close(fd_out);
1174 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1175 if (fd_in < 0) {
1176 error_setg_file_open(errp, errno, filename);
1177 return NULL;
1180 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1183 /* init terminal so that we can grab keys */
1184 static struct termios oldtty;
1185 static int old_fd0_flags;
1186 static bool stdio_in_use;
1187 static bool stdio_allow_signal;
1188 static bool stdio_echo_state;
1190 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1192 static void term_exit(void)
1194 tcsetattr (0, TCSANOW, &oldtty);
1195 fcntl(0, F_SETFL, old_fd0_flags);
1198 static void term_stdio_handler(int sig)
1200 /* restore echo after resume from suspend. */
1201 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1204 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1206 struct termios tty;
1208 stdio_echo_state = echo;
1209 tty = oldtty;
1210 if (!echo) {
1211 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1212 |INLCR|IGNCR|ICRNL|IXON);
1213 tty.c_oflag |= OPOST;
1214 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1215 tty.c_cflag &= ~(CSIZE|PARENB);
1216 tty.c_cflag |= CS8;
1217 tty.c_cc[VMIN] = 1;
1218 tty.c_cc[VTIME] = 0;
1220 if (!stdio_allow_signal)
1221 tty.c_lflag &= ~ISIG;
1223 tcsetattr (0, TCSANOW, &tty);
1226 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1228 term_exit();
1229 fd_chr_close(chr);
1232 static CharDriverState *qemu_chr_open_stdio(const char *id,
1233 ChardevBackend *backend,
1234 ChardevReturn *ret,
1235 Error **errp)
1237 ChardevStdio *opts = backend->u.stdio.data;
1238 CharDriverState *chr;
1239 struct sigaction act;
1240 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1242 if (is_daemonized()) {
1243 error_setg(errp, "cannot use stdio with -daemonize");
1244 return NULL;
1247 if (stdio_in_use) {
1248 error_setg(errp, "cannot use stdio by multiple character devices");
1249 return NULL;
1252 stdio_in_use = true;
1253 old_fd0_flags = fcntl(0, F_GETFL);
1254 tcgetattr(0, &oldtty);
1255 qemu_set_nonblock(0);
1256 atexit(term_exit);
1258 memset(&act, 0, sizeof(act));
1259 act.sa_handler = term_stdio_handler;
1260 sigaction(SIGCONT, &act, NULL);
1262 chr = qemu_chr_open_fd(0, 1, common, errp);
1263 if (!chr) {
1264 return NULL;
1266 chr->chr_close = qemu_chr_close_stdio;
1267 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1268 if (opts->has_signal) {
1269 stdio_allow_signal = opts->signal;
1271 qemu_chr_fe_set_echo(chr, false);
1273 return chr;
1276 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1277 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1278 || defined(__GLIBC__)
1280 #define HAVE_CHARDEV_SERIAL 1
1281 #define HAVE_CHARDEV_PTY 1
1283 typedef struct {
1284 QIOChannel *ioc;
1285 int read_bytes;
1287 /* Protected by the CharDriverState chr_write_lock. */
1288 int connected;
1289 guint timer_tag;
1290 guint open_tag;
1291 } PtyCharDriver;
1293 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1294 static void pty_chr_state(CharDriverState *chr, int connected);
1296 static gboolean pty_chr_timer(gpointer opaque)
1298 struct CharDriverState *chr = opaque;
1299 PtyCharDriver *s = chr->opaque;
1301 qemu_mutex_lock(&chr->chr_write_lock);
1302 s->timer_tag = 0;
1303 s->open_tag = 0;
1304 if (!s->connected) {
1305 /* Next poll ... */
1306 pty_chr_update_read_handler_locked(chr);
1308 qemu_mutex_unlock(&chr->chr_write_lock);
1309 return FALSE;
1312 /* Called with chr_write_lock held. */
1313 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1315 PtyCharDriver *s = chr->opaque;
1317 if (s->timer_tag) {
1318 g_source_remove(s->timer_tag);
1319 s->timer_tag = 0;
1322 if (ms == 1000) {
1323 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1324 } else {
1325 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1329 /* Called with chr_write_lock held. */
1330 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1332 PtyCharDriver *s = chr->opaque;
1333 GPollFD pfd;
1334 int rc;
1335 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1337 pfd.fd = fioc->fd;
1338 pfd.events = G_IO_OUT;
1339 pfd.revents = 0;
1340 do {
1341 rc = g_poll(&pfd, 1, 0);
1342 } while (rc == -1 && errno == EINTR);
1343 assert(rc >= 0);
1345 if (pfd.revents & G_IO_HUP) {
1346 pty_chr_state(chr, 0);
1347 } else {
1348 pty_chr_state(chr, 1);
1352 static void pty_chr_update_read_handler(CharDriverState *chr,
1353 GMainContext *context)
1355 qemu_mutex_lock(&chr->chr_write_lock);
1356 pty_chr_update_read_handler_locked(chr);
1357 qemu_mutex_unlock(&chr->chr_write_lock);
1360 /* Called with chr_write_lock held. */
1361 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1363 PtyCharDriver *s = chr->opaque;
1365 if (!s->connected) {
1366 /* guest sends data, check for (re-)connect */
1367 pty_chr_update_read_handler_locked(chr);
1368 if (!s->connected) {
1369 return 0;
1372 return io_channel_send(s->ioc, buf, len);
1375 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1377 PtyCharDriver *s = chr->opaque;
1378 if (!s->connected) {
1379 return NULL;
1381 return qio_channel_create_watch(s->ioc, cond);
1384 static int pty_chr_read_poll(void *opaque)
1386 CharDriverState *chr = opaque;
1387 PtyCharDriver *s = chr->opaque;
1389 s->read_bytes = qemu_chr_be_can_write(chr);
1390 return s->read_bytes;
1393 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1395 CharDriverState *chr = opaque;
1396 PtyCharDriver *s = chr->opaque;
1397 gsize len;
1398 uint8_t buf[READ_BUF_LEN];
1399 ssize_t ret;
1401 len = sizeof(buf);
1402 if (len > s->read_bytes)
1403 len = s->read_bytes;
1404 if (len == 0) {
1405 return TRUE;
1407 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1408 if (ret <= 0) {
1409 pty_chr_state(chr, 0);
1410 return FALSE;
1411 } else {
1412 pty_chr_state(chr, 1);
1413 qemu_chr_be_write(chr, buf, ret);
1415 return TRUE;
1418 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1420 CharDriverState *chr = opaque;
1421 PtyCharDriver *s = chr->opaque;
1423 s->open_tag = 0;
1424 qemu_chr_be_generic_open(chr);
1425 return FALSE;
1428 /* Called with chr_write_lock held. */
1429 static void pty_chr_state(CharDriverState *chr, int connected)
1431 PtyCharDriver *s = chr->opaque;
1433 if (!connected) {
1434 if (s->open_tag) {
1435 g_source_remove(s->open_tag);
1436 s->open_tag = 0;
1438 remove_fd_in_watch(chr);
1439 s->connected = 0;
1440 /* (re-)connect poll interval for idle guests: once per second.
1441 * We check more frequently in case the guests sends data to
1442 * the virtual device linked to our pty. */
1443 pty_chr_rearm_timer(chr, 1000);
1444 } else {
1445 if (s->timer_tag) {
1446 g_source_remove(s->timer_tag);
1447 s->timer_tag = 0;
1449 if (!s->connected) {
1450 g_assert(s->open_tag == 0);
1451 s->connected = 1;
1452 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1454 if (!chr->fd_in_tag) {
1455 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1456 pty_chr_read_poll,
1457 pty_chr_read,
1458 chr, NULL);
1463 static void pty_chr_close(struct CharDriverState *chr)
1465 PtyCharDriver *s = chr->opaque;
1467 qemu_mutex_lock(&chr->chr_write_lock);
1468 pty_chr_state(chr, 0);
1469 object_unref(OBJECT(s->ioc));
1470 if (s->timer_tag) {
1471 g_source_remove(s->timer_tag);
1472 s->timer_tag = 0;
1474 qemu_mutex_unlock(&chr->chr_write_lock);
1475 g_free(s);
1476 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1479 static CharDriverState *qemu_chr_open_pty(const char *id,
1480 ChardevBackend *backend,
1481 ChardevReturn *ret,
1482 Error **errp)
1484 CharDriverState *chr;
1485 PtyCharDriver *s;
1486 int master_fd, slave_fd;
1487 char pty_name[PATH_MAX];
1488 ChardevCommon *common = backend->u.pty.data;
1490 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1491 if (master_fd < 0) {
1492 error_setg_errno(errp, errno, "Failed to create PTY");
1493 return NULL;
1496 close(slave_fd);
1497 qemu_set_nonblock(master_fd);
1499 chr = qemu_chr_alloc(common, errp);
1500 if (!chr) {
1501 close(master_fd);
1502 return NULL;
1505 chr->filename = g_strdup_printf("pty:%s", pty_name);
1506 ret->pty = g_strdup(pty_name);
1507 ret->has_pty = true;
1509 fprintf(stderr, "char device redirected to %s (label %s)\n",
1510 pty_name, id);
1512 s = g_new0(PtyCharDriver, 1);
1513 chr->opaque = s;
1514 chr->chr_write = pty_chr_write;
1515 chr->chr_update_read_handler = pty_chr_update_read_handler;
1516 chr->chr_close = pty_chr_close;
1517 chr->chr_add_watch = pty_chr_add_watch;
1518 chr->explicit_be_open = true;
1520 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1521 s->timer_tag = 0;
1523 return chr;
1526 static void tty_serial_init(int fd, int speed,
1527 int parity, int data_bits, int stop_bits)
1529 struct termios tty;
1530 speed_t spd;
1532 #if 0
1533 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1534 speed, parity, data_bits, stop_bits);
1535 #endif
1536 tcgetattr (fd, &tty);
1538 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1539 speed = speed * 10 / 11;
1540 do {
1541 check_speed(50);
1542 check_speed(75);
1543 check_speed(110);
1544 check_speed(134);
1545 check_speed(150);
1546 check_speed(200);
1547 check_speed(300);
1548 check_speed(600);
1549 check_speed(1200);
1550 check_speed(1800);
1551 check_speed(2400);
1552 check_speed(4800);
1553 check_speed(9600);
1554 check_speed(19200);
1555 check_speed(38400);
1556 /* Non-Posix values follow. They may be unsupported on some systems. */
1557 check_speed(57600);
1558 check_speed(115200);
1559 #ifdef B230400
1560 check_speed(230400);
1561 #endif
1562 #ifdef B460800
1563 check_speed(460800);
1564 #endif
1565 #ifdef B500000
1566 check_speed(500000);
1567 #endif
1568 #ifdef B576000
1569 check_speed(576000);
1570 #endif
1571 #ifdef B921600
1572 check_speed(921600);
1573 #endif
1574 #ifdef B1000000
1575 check_speed(1000000);
1576 #endif
1577 #ifdef B1152000
1578 check_speed(1152000);
1579 #endif
1580 #ifdef B1500000
1581 check_speed(1500000);
1582 #endif
1583 #ifdef B2000000
1584 check_speed(2000000);
1585 #endif
1586 #ifdef B2500000
1587 check_speed(2500000);
1588 #endif
1589 #ifdef B3000000
1590 check_speed(3000000);
1591 #endif
1592 #ifdef B3500000
1593 check_speed(3500000);
1594 #endif
1595 #ifdef B4000000
1596 check_speed(4000000);
1597 #endif
1598 spd = B115200;
1599 } while (0);
1601 cfsetispeed(&tty, spd);
1602 cfsetospeed(&tty, spd);
1604 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1605 |INLCR|IGNCR|ICRNL|IXON);
1606 tty.c_oflag |= OPOST;
1607 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1608 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1609 switch(data_bits) {
1610 default:
1611 case 8:
1612 tty.c_cflag |= CS8;
1613 break;
1614 case 7:
1615 tty.c_cflag |= CS7;
1616 break;
1617 case 6:
1618 tty.c_cflag |= CS6;
1619 break;
1620 case 5:
1621 tty.c_cflag |= CS5;
1622 break;
1624 switch(parity) {
1625 default:
1626 case 'N':
1627 break;
1628 case 'E':
1629 tty.c_cflag |= PARENB;
1630 break;
1631 case 'O':
1632 tty.c_cflag |= PARENB | PARODD;
1633 break;
1635 if (stop_bits == 2)
1636 tty.c_cflag |= CSTOPB;
1638 tcsetattr (fd, TCSANOW, &tty);
1641 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1643 FDCharDriver *s = chr->opaque;
1644 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1646 switch(cmd) {
1647 case CHR_IOCTL_SERIAL_SET_PARAMS:
1649 QEMUSerialSetParams *ssp = arg;
1650 tty_serial_init(fioc->fd,
1651 ssp->speed, ssp->parity,
1652 ssp->data_bits, ssp->stop_bits);
1654 break;
1655 case CHR_IOCTL_SERIAL_SET_BREAK:
1657 int enable = *(int *)arg;
1658 if (enable) {
1659 tcsendbreak(fioc->fd, 1);
1662 break;
1663 case CHR_IOCTL_SERIAL_GET_TIOCM:
1665 int sarg = 0;
1666 int *targ = (int *)arg;
1667 ioctl(fioc->fd, TIOCMGET, &sarg);
1668 *targ = 0;
1669 if (sarg & TIOCM_CTS)
1670 *targ |= CHR_TIOCM_CTS;
1671 if (sarg & TIOCM_CAR)
1672 *targ |= CHR_TIOCM_CAR;
1673 if (sarg & TIOCM_DSR)
1674 *targ |= CHR_TIOCM_DSR;
1675 if (sarg & TIOCM_RI)
1676 *targ |= CHR_TIOCM_RI;
1677 if (sarg & TIOCM_DTR)
1678 *targ |= CHR_TIOCM_DTR;
1679 if (sarg & TIOCM_RTS)
1680 *targ |= CHR_TIOCM_RTS;
1682 break;
1683 case CHR_IOCTL_SERIAL_SET_TIOCM:
1685 int sarg = *(int *)arg;
1686 int targ = 0;
1687 ioctl(fioc->fd, TIOCMGET, &targ);
1688 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1689 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1690 if (sarg & CHR_TIOCM_CTS)
1691 targ |= TIOCM_CTS;
1692 if (sarg & CHR_TIOCM_CAR)
1693 targ |= TIOCM_CAR;
1694 if (sarg & CHR_TIOCM_DSR)
1695 targ |= TIOCM_DSR;
1696 if (sarg & CHR_TIOCM_RI)
1697 targ |= TIOCM_RI;
1698 if (sarg & CHR_TIOCM_DTR)
1699 targ |= TIOCM_DTR;
1700 if (sarg & CHR_TIOCM_RTS)
1701 targ |= TIOCM_RTS;
1702 ioctl(fioc->fd, TIOCMSET, &targ);
1704 break;
1705 default:
1706 return -ENOTSUP;
1708 return 0;
1711 static void qemu_chr_close_tty(CharDriverState *chr)
1713 fd_chr_close(chr);
1716 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1717 ChardevCommon *backend,
1718 Error **errp)
1720 CharDriverState *chr;
1722 tty_serial_init(fd, 115200, 'N', 8, 1);
1723 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1724 if (!chr) {
1725 return NULL;
1727 chr->chr_ioctl = tty_serial_ioctl;
1728 chr->chr_close = qemu_chr_close_tty;
1729 return chr;
1731 #endif /* __linux__ || __sun__ */
1733 #if defined(__linux__)
1735 #define HAVE_CHARDEV_PARPORT 1
1737 typedef struct {
1738 int fd;
1739 int mode;
1740 } ParallelCharDriver;
1742 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1744 if (s->mode != mode) {
1745 int m = mode;
1746 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1747 return 0;
1748 s->mode = mode;
1750 return 1;
1753 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1755 ParallelCharDriver *drv = chr->opaque;
1756 int fd = drv->fd;
1757 uint8_t b;
1759 switch(cmd) {
1760 case CHR_IOCTL_PP_READ_DATA:
1761 if (ioctl(fd, PPRDATA, &b) < 0)
1762 return -ENOTSUP;
1763 *(uint8_t *)arg = b;
1764 break;
1765 case CHR_IOCTL_PP_WRITE_DATA:
1766 b = *(uint8_t *)arg;
1767 if (ioctl(fd, PPWDATA, &b) < 0)
1768 return -ENOTSUP;
1769 break;
1770 case CHR_IOCTL_PP_READ_CONTROL:
1771 if (ioctl(fd, PPRCONTROL, &b) < 0)
1772 return -ENOTSUP;
1773 /* Linux gives only the lowest bits, and no way to know data
1774 direction! For better compatibility set the fixed upper
1775 bits. */
1776 *(uint8_t *)arg = b | 0xc0;
1777 break;
1778 case CHR_IOCTL_PP_WRITE_CONTROL:
1779 b = *(uint8_t *)arg;
1780 if (ioctl(fd, PPWCONTROL, &b) < 0)
1781 return -ENOTSUP;
1782 break;
1783 case CHR_IOCTL_PP_READ_STATUS:
1784 if (ioctl(fd, PPRSTATUS, &b) < 0)
1785 return -ENOTSUP;
1786 *(uint8_t *)arg = b;
1787 break;
1788 case CHR_IOCTL_PP_DATA_DIR:
1789 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1790 return -ENOTSUP;
1791 break;
1792 case CHR_IOCTL_PP_EPP_READ_ADDR:
1793 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1794 struct ParallelIOArg *parg = arg;
1795 int n = read(fd, parg->buffer, parg->count);
1796 if (n != parg->count) {
1797 return -EIO;
1800 break;
1801 case CHR_IOCTL_PP_EPP_READ:
1802 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1803 struct ParallelIOArg *parg = arg;
1804 int n = read(fd, parg->buffer, parg->count);
1805 if (n != parg->count) {
1806 return -EIO;
1809 break;
1810 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1811 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1812 struct ParallelIOArg *parg = arg;
1813 int n = write(fd, parg->buffer, parg->count);
1814 if (n != parg->count) {
1815 return -EIO;
1818 break;
1819 case CHR_IOCTL_PP_EPP_WRITE:
1820 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1821 struct ParallelIOArg *parg = arg;
1822 int n = write(fd, parg->buffer, parg->count);
1823 if (n != parg->count) {
1824 return -EIO;
1827 break;
1828 default:
1829 return -ENOTSUP;
1831 return 0;
1834 static void pp_close(CharDriverState *chr)
1836 ParallelCharDriver *drv = chr->opaque;
1837 int fd = drv->fd;
1839 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1840 ioctl(fd, PPRELEASE);
1841 close(fd);
1842 g_free(drv);
1843 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1846 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1847 ChardevCommon *backend,
1848 Error **errp)
1850 CharDriverState *chr;
1851 ParallelCharDriver *drv;
1853 if (ioctl(fd, PPCLAIM) < 0) {
1854 error_setg_errno(errp, errno, "not a parallel port");
1855 close(fd);
1856 return NULL;
1859 chr = qemu_chr_alloc(backend, errp);
1860 if (!chr) {
1861 return NULL;
1864 drv = g_new0(ParallelCharDriver, 1);
1865 chr->opaque = drv;
1866 chr->chr_write = null_chr_write;
1867 chr->chr_ioctl = pp_ioctl;
1868 chr->chr_close = pp_close;
1870 drv->fd = fd;
1871 drv->mode = IEEE1284_MODE_COMPAT;
1873 return chr;
1875 #endif /* __linux__ */
1877 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1879 #define HAVE_CHARDEV_PARPORT 1
1881 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1883 int fd = (int)(intptr_t)chr->opaque;
1884 uint8_t b;
1886 switch(cmd) {
1887 case CHR_IOCTL_PP_READ_DATA:
1888 if (ioctl(fd, PPIGDATA, &b) < 0)
1889 return -ENOTSUP;
1890 *(uint8_t *)arg = b;
1891 break;
1892 case CHR_IOCTL_PP_WRITE_DATA:
1893 b = *(uint8_t *)arg;
1894 if (ioctl(fd, PPISDATA, &b) < 0)
1895 return -ENOTSUP;
1896 break;
1897 case CHR_IOCTL_PP_READ_CONTROL:
1898 if (ioctl(fd, PPIGCTRL, &b) < 0)
1899 return -ENOTSUP;
1900 *(uint8_t *)arg = b;
1901 break;
1902 case CHR_IOCTL_PP_WRITE_CONTROL:
1903 b = *(uint8_t *)arg;
1904 if (ioctl(fd, PPISCTRL, &b) < 0)
1905 return -ENOTSUP;
1906 break;
1907 case CHR_IOCTL_PP_READ_STATUS:
1908 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1909 return -ENOTSUP;
1910 *(uint8_t *)arg = b;
1911 break;
1912 default:
1913 return -ENOTSUP;
1915 return 0;
1918 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1919 ChardevCommon *backend,
1920 Error **errp)
1922 CharDriverState *chr;
1924 chr = qemu_chr_alloc(backend, errp);
1925 if (!chr) {
1926 return NULL;
1928 chr->opaque = (void *)(intptr_t)fd;
1929 chr->chr_write = null_chr_write;
1930 chr->chr_ioctl = pp_ioctl;
1931 chr->explicit_be_open = true;
1932 return chr;
1934 #endif
1936 #else /* _WIN32 */
1938 #define HAVE_CHARDEV_SERIAL 1
1940 typedef struct {
1941 int max_size;
1942 HANDLE hcom, hrecv, hsend;
1943 OVERLAPPED orecv;
1944 BOOL fpipe;
1945 DWORD len;
1947 /* Protected by the CharDriverState chr_write_lock. */
1948 OVERLAPPED osend;
1949 } WinCharState;
1951 typedef struct {
1952 HANDLE hStdIn;
1953 HANDLE hInputReadyEvent;
1954 HANDLE hInputDoneEvent;
1955 HANDLE hInputThread;
1956 uint8_t win_stdio_buf;
1957 } WinStdioCharState;
1959 #define NSENDBUF 2048
1960 #define NRECVBUF 2048
1961 #define MAXCONNECT 1
1962 #define NTIMEOUT 5000
1964 static int win_chr_poll(void *opaque);
1965 static int win_chr_pipe_poll(void *opaque);
1967 static void win_chr_close(CharDriverState *chr)
1969 WinCharState *s = chr->opaque;
1971 if (s->hsend) {
1972 CloseHandle(s->hsend);
1973 s->hsend = NULL;
1975 if (s->hrecv) {
1976 CloseHandle(s->hrecv);
1977 s->hrecv = NULL;
1979 if (s->hcom) {
1980 CloseHandle(s->hcom);
1981 s->hcom = NULL;
1983 if (s->fpipe)
1984 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1985 else
1986 qemu_del_polling_cb(win_chr_poll, chr);
1988 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1991 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1993 WinCharState *s = chr->opaque;
1994 COMMCONFIG comcfg;
1995 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1996 COMSTAT comstat;
1997 DWORD size;
1998 DWORD err;
2000 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2001 if (!s->hsend) {
2002 error_setg(errp, "Failed CreateEvent");
2003 goto fail;
2005 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2006 if (!s->hrecv) {
2007 error_setg(errp, "Failed CreateEvent");
2008 goto fail;
2011 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2012 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2013 if (s->hcom == INVALID_HANDLE_VALUE) {
2014 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
2015 s->hcom = NULL;
2016 goto fail;
2019 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2020 error_setg(errp, "Failed SetupComm");
2021 goto fail;
2024 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2025 size = sizeof(COMMCONFIG);
2026 GetDefaultCommConfig(filename, &comcfg, &size);
2027 comcfg.dcb.DCBlength = sizeof(DCB);
2028 CommConfigDialog(filename, NULL, &comcfg);
2030 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2031 error_setg(errp, "Failed SetCommState");
2032 goto fail;
2035 if (!SetCommMask(s->hcom, EV_ERR)) {
2036 error_setg(errp, "Failed SetCommMask");
2037 goto fail;
2040 cto.ReadIntervalTimeout = MAXDWORD;
2041 if (!SetCommTimeouts(s->hcom, &cto)) {
2042 error_setg(errp, "Failed SetCommTimeouts");
2043 goto fail;
2046 if (!ClearCommError(s->hcom, &err, &comstat)) {
2047 error_setg(errp, "Failed ClearCommError");
2048 goto fail;
2050 qemu_add_polling_cb(win_chr_poll, chr);
2051 return 0;
2053 fail:
2054 win_chr_close(chr);
2055 return -1;
2058 /* Called with chr_write_lock held. */
2059 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2061 WinCharState *s = chr->opaque;
2062 DWORD len, ret, size, err;
2064 len = len1;
2065 ZeroMemory(&s->osend, sizeof(s->osend));
2066 s->osend.hEvent = s->hsend;
2067 while (len > 0) {
2068 if (s->hsend)
2069 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2070 else
2071 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2072 if (!ret) {
2073 err = GetLastError();
2074 if (err == ERROR_IO_PENDING) {
2075 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2076 if (ret) {
2077 buf += size;
2078 len -= size;
2079 } else {
2080 break;
2082 } else {
2083 break;
2085 } else {
2086 buf += size;
2087 len -= size;
2090 return len1 - len;
2093 static int win_chr_read_poll(CharDriverState *chr)
2095 WinCharState *s = chr->opaque;
2097 s->max_size = qemu_chr_be_can_write(chr);
2098 return s->max_size;
2101 static void win_chr_readfile(CharDriverState *chr)
2103 WinCharState *s = chr->opaque;
2104 int ret, err;
2105 uint8_t buf[READ_BUF_LEN];
2106 DWORD size;
2108 ZeroMemory(&s->orecv, sizeof(s->orecv));
2109 s->orecv.hEvent = s->hrecv;
2110 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2111 if (!ret) {
2112 err = GetLastError();
2113 if (err == ERROR_IO_PENDING) {
2114 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2118 if (size > 0) {
2119 qemu_chr_be_write(chr, buf, size);
2123 static void win_chr_read(CharDriverState *chr)
2125 WinCharState *s = chr->opaque;
2127 if (s->len > s->max_size)
2128 s->len = s->max_size;
2129 if (s->len == 0)
2130 return;
2132 win_chr_readfile(chr);
2135 static int win_chr_poll(void *opaque)
2137 CharDriverState *chr = opaque;
2138 WinCharState *s = chr->opaque;
2139 COMSTAT status;
2140 DWORD comerr;
2142 ClearCommError(s->hcom, &comerr, &status);
2143 if (status.cbInQue > 0) {
2144 s->len = status.cbInQue;
2145 win_chr_read_poll(chr);
2146 win_chr_read(chr);
2147 return 1;
2149 return 0;
2152 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2153 ChardevCommon *backend,
2154 Error **errp)
2156 CharDriverState *chr;
2157 WinCharState *s;
2159 chr = qemu_chr_alloc(backend, errp);
2160 if (!chr) {
2161 return NULL;
2163 s = g_new0(WinCharState, 1);
2164 chr->opaque = s;
2165 chr->chr_write = win_chr_write;
2166 chr->chr_close = win_chr_close;
2168 if (win_chr_init(chr, filename, errp) < 0) {
2169 g_free(s);
2170 qemu_chr_free_common(chr);
2171 return NULL;
2173 return chr;
2176 static int win_chr_pipe_poll(void *opaque)
2178 CharDriverState *chr = opaque;
2179 WinCharState *s = chr->opaque;
2180 DWORD size;
2182 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2183 if (size > 0) {
2184 s->len = size;
2185 win_chr_read_poll(chr);
2186 win_chr_read(chr);
2187 return 1;
2189 return 0;
2192 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2193 Error **errp)
2195 WinCharState *s = chr->opaque;
2196 OVERLAPPED ov;
2197 int ret;
2198 DWORD size;
2199 char *openname;
2201 s->fpipe = TRUE;
2203 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2204 if (!s->hsend) {
2205 error_setg(errp, "Failed CreateEvent");
2206 goto fail;
2208 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2209 if (!s->hrecv) {
2210 error_setg(errp, "Failed CreateEvent");
2211 goto fail;
2214 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2215 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2216 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2217 PIPE_WAIT,
2218 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2219 g_free(openname);
2220 if (s->hcom == INVALID_HANDLE_VALUE) {
2221 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2222 s->hcom = NULL;
2223 goto fail;
2226 ZeroMemory(&ov, sizeof(ov));
2227 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2228 ret = ConnectNamedPipe(s->hcom, &ov);
2229 if (ret) {
2230 error_setg(errp, "Failed ConnectNamedPipe");
2231 goto fail;
2234 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2235 if (!ret) {
2236 error_setg(errp, "Failed GetOverlappedResult");
2237 if (ov.hEvent) {
2238 CloseHandle(ov.hEvent);
2239 ov.hEvent = NULL;
2241 goto fail;
2244 if (ov.hEvent) {
2245 CloseHandle(ov.hEvent);
2246 ov.hEvent = NULL;
2248 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2249 return 0;
2251 fail:
2252 win_chr_close(chr);
2253 return -1;
2257 static CharDriverState *qemu_chr_open_pipe(const char *id,
2258 ChardevBackend *backend,
2259 ChardevReturn *ret,
2260 Error **errp)
2262 ChardevHostdev *opts = backend->u.pipe.data;
2263 const char *filename = opts->device;
2264 CharDriverState *chr;
2265 WinCharState *s;
2266 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2268 chr = qemu_chr_alloc(common, errp);
2269 if (!chr) {
2270 return NULL;
2272 s = g_new0(WinCharState, 1);
2273 chr->opaque = s;
2274 chr->chr_write = win_chr_write;
2275 chr->chr_close = win_chr_close;
2277 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2278 g_free(s);
2279 qemu_chr_free_common(chr);
2280 return NULL;
2282 return chr;
2285 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2286 ChardevCommon *backend,
2287 Error **errp)
2289 CharDriverState *chr;
2290 WinCharState *s;
2292 chr = qemu_chr_alloc(backend, errp);
2293 if (!chr) {
2294 return NULL;
2296 s = g_new0(WinCharState, 1);
2297 s->hcom = fd_out;
2298 chr->opaque = s;
2299 chr->chr_write = win_chr_write;
2300 return chr;
2303 static CharDriverState *qemu_chr_open_win_con(const char *id,
2304 ChardevBackend *backend,
2305 ChardevReturn *ret,
2306 Error **errp)
2308 ChardevCommon *common = backend->u.console.data;
2309 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2310 common, errp);
2313 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2315 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2316 DWORD dwSize;
2317 int len1;
2319 len1 = len;
2321 while (len1 > 0) {
2322 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2323 break;
2325 buf += dwSize;
2326 len1 -= dwSize;
2329 return len - len1;
2332 static void win_stdio_wait_func(void *opaque)
2334 CharDriverState *chr = opaque;
2335 WinStdioCharState *stdio = chr->opaque;
2336 INPUT_RECORD buf[4];
2337 int ret;
2338 DWORD dwSize;
2339 int i;
2341 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2343 if (!ret) {
2344 /* Avoid error storm */
2345 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2346 return;
2349 for (i = 0; i < dwSize; i++) {
2350 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2352 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2353 int j;
2354 if (kev->uChar.AsciiChar != 0) {
2355 for (j = 0; j < kev->wRepeatCount; j++) {
2356 if (qemu_chr_be_can_write(chr)) {
2357 uint8_t c = kev->uChar.AsciiChar;
2358 qemu_chr_be_write(chr, &c, 1);
2366 static DWORD WINAPI win_stdio_thread(LPVOID param)
2368 CharDriverState *chr = param;
2369 WinStdioCharState *stdio = chr->opaque;
2370 int ret;
2371 DWORD dwSize;
2373 while (1) {
2375 /* Wait for one byte */
2376 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2378 /* Exit in case of error, continue if nothing read */
2379 if (!ret) {
2380 break;
2382 if (!dwSize) {
2383 continue;
2386 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2387 if (stdio->win_stdio_buf == '\r') {
2388 continue;
2391 /* Signal the main thread and wait until the byte was eaten */
2392 if (!SetEvent(stdio->hInputReadyEvent)) {
2393 break;
2395 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2396 != WAIT_OBJECT_0) {
2397 break;
2401 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2402 return 0;
2405 static void win_stdio_thread_wait_func(void *opaque)
2407 CharDriverState *chr = opaque;
2408 WinStdioCharState *stdio = chr->opaque;
2410 if (qemu_chr_be_can_write(chr)) {
2411 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2414 SetEvent(stdio->hInputDoneEvent);
2417 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2419 WinStdioCharState *stdio = chr->opaque;
2420 DWORD dwMode = 0;
2422 GetConsoleMode(stdio->hStdIn, &dwMode);
2424 if (echo) {
2425 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2426 } else {
2427 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2431 static void win_stdio_close(CharDriverState *chr)
2433 WinStdioCharState *stdio = chr->opaque;
2435 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2436 CloseHandle(stdio->hInputReadyEvent);
2438 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2439 CloseHandle(stdio->hInputDoneEvent);
2441 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2442 TerminateThread(stdio->hInputThread, 0);
2445 g_free(chr->opaque);
2446 g_free(chr);
2449 static CharDriverState *qemu_chr_open_stdio(const char *id,
2450 ChardevBackend *backend,
2451 ChardevReturn *ret,
2452 Error **errp)
2454 CharDriverState *chr;
2455 WinStdioCharState *stdio;
2456 DWORD dwMode;
2457 int is_console = 0;
2458 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio.data);
2460 chr = qemu_chr_alloc(common, errp);
2461 if (!chr) {
2462 return NULL;
2464 stdio = g_new0(WinStdioCharState, 1);
2466 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2467 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2468 error_setg(errp, "cannot open stdio: invalid handle");
2469 return NULL;
2472 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2474 chr->opaque = stdio;
2475 chr->chr_write = win_stdio_write;
2476 chr->chr_close = win_stdio_close;
2478 if (is_console) {
2479 if (qemu_add_wait_object(stdio->hStdIn,
2480 win_stdio_wait_func, chr)) {
2481 error_setg(errp, "qemu_add_wait_object: failed");
2482 goto err1;
2484 } else {
2485 DWORD dwId;
2487 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2488 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2489 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2490 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2491 error_setg(errp, "cannot create event");
2492 goto err2;
2494 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2495 win_stdio_thread_wait_func, chr)) {
2496 error_setg(errp, "qemu_add_wait_object: failed");
2497 goto err2;
2499 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2500 chr, 0, &dwId);
2502 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2503 error_setg(errp, "cannot create stdio thread");
2504 goto err3;
2508 dwMode |= ENABLE_LINE_INPUT;
2510 if (is_console) {
2511 /* set the terminal in raw mode */
2512 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2513 dwMode |= ENABLE_PROCESSED_INPUT;
2516 SetConsoleMode(stdio->hStdIn, dwMode);
2518 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2519 qemu_chr_fe_set_echo(chr, false);
2521 return chr;
2523 err3:
2524 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2525 err2:
2526 CloseHandle(stdio->hInputReadyEvent);
2527 CloseHandle(stdio->hInputDoneEvent);
2528 err1:
2529 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2530 return NULL;
2532 #endif /* !_WIN32 */
2535 /***********************************************************/
2536 /* UDP Net console */
2538 typedef struct {
2539 QIOChannel *ioc;
2540 uint8_t buf[READ_BUF_LEN];
2541 int bufcnt;
2542 int bufptr;
2543 int max_size;
2544 } NetCharDriver;
2546 /* Called with chr_write_lock held. */
2547 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2549 NetCharDriver *s = chr->opaque;
2551 return qio_channel_write(
2552 s->ioc, (const char *)buf, len, NULL);
2555 static int udp_chr_read_poll(void *opaque)
2557 CharDriverState *chr = opaque;
2558 NetCharDriver *s = chr->opaque;
2560 s->max_size = qemu_chr_be_can_write(chr);
2562 /* If there were any stray characters in the queue process them
2563 * first
2565 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2566 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2567 s->bufptr++;
2568 s->max_size = qemu_chr_be_can_write(chr);
2570 return s->max_size;
2573 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2575 CharDriverState *chr = opaque;
2576 NetCharDriver *s = chr->opaque;
2577 ssize_t ret;
2579 if (s->max_size == 0) {
2580 return TRUE;
2582 ret = qio_channel_read(
2583 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2584 if (ret <= 0) {
2585 remove_fd_in_watch(chr);
2586 return FALSE;
2588 s->bufcnt = ret;
2590 s->bufptr = 0;
2591 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2592 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2593 s->bufptr++;
2594 s->max_size = qemu_chr_be_can_write(chr);
2597 return TRUE;
2600 static void udp_chr_update_read_handler(CharDriverState *chr,
2601 GMainContext *context)
2603 NetCharDriver *s = chr->opaque;
2605 remove_fd_in_watch(chr);
2606 if (s->ioc) {
2607 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2608 udp_chr_read_poll,
2609 udp_chr_read, chr,
2610 context);
2614 static void udp_chr_close(CharDriverState *chr)
2616 NetCharDriver *s = chr->opaque;
2618 remove_fd_in_watch(chr);
2619 if (s->ioc) {
2620 object_unref(OBJECT(s->ioc));
2622 g_free(s);
2623 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2626 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2627 ChardevCommon *backend,
2628 Error **errp)
2630 CharDriverState *chr = NULL;
2631 NetCharDriver *s = NULL;
2633 chr = qemu_chr_alloc(backend, errp);
2634 if (!chr) {
2635 return NULL;
2637 s = g_new0(NetCharDriver, 1);
2639 s->ioc = QIO_CHANNEL(sioc);
2640 s->bufcnt = 0;
2641 s->bufptr = 0;
2642 chr->opaque = s;
2643 chr->chr_write = udp_chr_write;
2644 chr->chr_update_read_handler = udp_chr_update_read_handler;
2645 chr->chr_close = udp_chr_close;
2646 /* be isn't opened until we get a connection */
2647 chr->explicit_be_open = true;
2648 return chr;
2651 /***********************************************************/
2652 /* TCP Net console */
2654 typedef struct {
2655 QIOChannel *ioc; /* Client I/O channel */
2656 QIOChannelSocket *sioc; /* Client master channel */
2657 QIOChannelSocket *listen_ioc;
2658 guint listen_tag;
2659 QCryptoTLSCreds *tls_creds;
2660 int connected;
2661 int max_size;
2662 int do_telnetopt;
2663 int do_nodelay;
2664 int is_unix;
2665 int *read_msgfds;
2666 size_t read_msgfds_num;
2667 int *write_msgfds;
2668 size_t write_msgfds_num;
2670 SocketAddress *addr;
2671 bool is_listen;
2672 bool is_telnet;
2674 guint reconnect_timer;
2675 int64_t reconnect_time;
2676 bool connect_err_reported;
2677 } TCPCharDriver;
2679 static gboolean socket_reconnect_timeout(gpointer opaque);
2681 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2683 TCPCharDriver *s = chr->opaque;
2684 assert(s->connected == 0);
2685 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2686 socket_reconnect_timeout, chr);
2689 static void check_report_connect_error(CharDriverState *chr,
2690 Error *err)
2692 TCPCharDriver *s = chr->opaque;
2694 if (!s->connect_err_reported) {
2695 error_report("Unable to connect character device %s: %s",
2696 chr->label, error_get_pretty(err));
2697 s->connect_err_reported = true;
2699 qemu_chr_socket_restart_timer(chr);
2702 static gboolean tcp_chr_accept(QIOChannel *chan,
2703 GIOCondition cond,
2704 void *opaque);
2706 /* Called with chr_write_lock held. */
2707 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2709 TCPCharDriver *s = chr->opaque;
2710 if (s->connected) {
2711 int ret = io_channel_send_full(s->ioc, buf, len,
2712 s->write_msgfds,
2713 s->write_msgfds_num);
2715 /* free the written msgfds, no matter what */
2716 if (s->write_msgfds_num) {
2717 g_free(s->write_msgfds);
2718 s->write_msgfds = 0;
2719 s->write_msgfds_num = 0;
2722 return ret;
2723 } else {
2724 /* XXX: indicate an error ? */
2725 return len;
2729 static int tcp_chr_read_poll(void *opaque)
2731 CharDriverState *chr = opaque;
2732 TCPCharDriver *s = chr->opaque;
2733 if (!s->connected)
2734 return 0;
2735 s->max_size = qemu_chr_be_can_write(chr);
2736 return s->max_size;
2739 #define IAC 255
2740 #define IAC_BREAK 243
2741 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2742 TCPCharDriver *s,
2743 uint8_t *buf, int *size)
2745 /* Handle any telnet client's basic IAC options to satisfy char by
2746 * char mode with no echo. All IAC options will be removed from
2747 * the buf and the do_telnetopt variable will be used to track the
2748 * state of the width of the IAC information.
2750 * IAC commands come in sets of 3 bytes with the exception of the
2751 * "IAC BREAK" command and the double IAC.
2754 int i;
2755 int j = 0;
2757 for (i = 0; i < *size; i++) {
2758 if (s->do_telnetopt > 1) {
2759 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2760 /* Double IAC means send an IAC */
2761 if (j != i)
2762 buf[j] = buf[i];
2763 j++;
2764 s->do_telnetopt = 1;
2765 } else {
2766 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2767 /* Handle IAC break commands by sending a serial break */
2768 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2769 s->do_telnetopt++;
2771 s->do_telnetopt++;
2773 if (s->do_telnetopt >= 4) {
2774 s->do_telnetopt = 1;
2776 } else {
2777 if ((unsigned char)buf[i] == IAC) {
2778 s->do_telnetopt = 2;
2779 } else {
2780 if (j != i)
2781 buf[j] = buf[i];
2782 j++;
2786 *size = j;
2789 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2791 TCPCharDriver *s = chr->opaque;
2792 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2794 assert(num <= TCP_MAX_FDS);
2796 if (to_copy) {
2797 int i;
2799 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2801 /* Close unused fds */
2802 for (i = to_copy; i < s->read_msgfds_num; i++) {
2803 close(s->read_msgfds[i]);
2806 g_free(s->read_msgfds);
2807 s->read_msgfds = 0;
2808 s->read_msgfds_num = 0;
2811 return to_copy;
2814 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2816 TCPCharDriver *s = chr->opaque;
2818 /* clear old pending fd array */
2819 g_free(s->write_msgfds);
2820 s->write_msgfds = NULL;
2821 s->write_msgfds_num = 0;
2823 if (!s->connected ||
2824 !qio_channel_has_feature(s->ioc,
2825 QIO_CHANNEL_FEATURE_FD_PASS)) {
2826 return -1;
2829 if (num) {
2830 s->write_msgfds = g_new(int, num);
2831 memcpy(s->write_msgfds, fds, num * sizeof(int));
2834 s->write_msgfds_num = num;
2836 return 0;
2839 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2841 TCPCharDriver *s = chr->opaque;
2842 struct iovec iov = { .iov_base = buf, .iov_len = len };
2843 int ret;
2844 size_t i;
2845 int *msgfds = NULL;
2846 size_t msgfds_num = 0;
2848 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2849 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2850 &msgfds, &msgfds_num,
2851 NULL);
2852 } else {
2853 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2854 NULL, NULL,
2855 NULL);
2858 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2859 errno = EAGAIN;
2860 ret = -1;
2861 } else if (ret == -1) {
2862 errno = EIO;
2865 if (msgfds_num) {
2866 /* close and clean read_msgfds */
2867 for (i = 0; i < s->read_msgfds_num; i++) {
2868 close(s->read_msgfds[i]);
2871 if (s->read_msgfds_num) {
2872 g_free(s->read_msgfds);
2875 s->read_msgfds = msgfds;
2876 s->read_msgfds_num = msgfds_num;
2879 for (i = 0; i < s->read_msgfds_num; i++) {
2880 int fd = s->read_msgfds[i];
2881 if (fd < 0) {
2882 continue;
2885 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2886 qemu_set_block(fd);
2888 #ifndef MSG_CMSG_CLOEXEC
2889 qemu_set_cloexec(fd);
2890 #endif
2893 return ret;
2896 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2898 TCPCharDriver *s = chr->opaque;
2899 return qio_channel_create_watch(s->ioc, cond);
2902 static void tcp_chr_free_connection(CharDriverState *chr)
2904 TCPCharDriver *s = chr->opaque;
2905 int i;
2907 if (!s->connected) {
2908 return;
2911 if (s->read_msgfds_num) {
2912 for (i = 0; i < s->read_msgfds_num; i++) {
2913 close(s->read_msgfds[i]);
2915 g_free(s->read_msgfds);
2916 s->read_msgfds = NULL;
2917 s->read_msgfds_num = 0;
2920 tcp_set_msgfds(chr, NULL, 0);
2921 remove_fd_in_watch(chr);
2922 object_unref(OBJECT(s->sioc));
2923 s->sioc = NULL;
2924 object_unref(OBJECT(s->ioc));
2925 s->ioc = NULL;
2926 g_free(chr->filename);
2927 chr->filename = NULL;
2928 s->connected = 0;
2931 static void tcp_chr_disconnect(CharDriverState *chr)
2933 TCPCharDriver *s = chr->opaque;
2935 if (!s->connected) {
2936 return;
2939 tcp_chr_free_connection(chr);
2941 if (s->listen_ioc) {
2942 s->listen_tag = qio_channel_add_watch(
2943 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
2945 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
2946 s->is_listen, s->is_telnet);
2947 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2948 if (s->reconnect_time) {
2949 qemu_chr_socket_restart_timer(chr);
2953 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2955 CharDriverState *chr = opaque;
2956 TCPCharDriver *s = chr->opaque;
2957 uint8_t buf[READ_BUF_LEN];
2958 int len, size;
2960 if (!s->connected || s->max_size <= 0) {
2961 return TRUE;
2963 len = sizeof(buf);
2964 if (len > s->max_size)
2965 len = s->max_size;
2966 size = tcp_chr_recv(chr, (void *)buf, len);
2967 if (size == 0 || size == -1) {
2968 /* connection closed */
2969 tcp_chr_disconnect(chr);
2970 } else if (size > 0) {
2971 if (s->do_telnetopt)
2972 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2973 if (size > 0)
2974 qemu_chr_be_write(chr, buf, size);
2977 return TRUE;
2980 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2982 TCPCharDriver *s = chr->opaque;
2983 int size;
2985 if (!s->connected) {
2986 return 0;
2989 size = tcp_chr_recv(chr, (void *) buf, len);
2990 if (size == 0) {
2991 /* connection closed */
2992 tcp_chr_disconnect(chr);
2995 return size;
2998 static void tcp_chr_connect(void *opaque)
3000 CharDriverState *chr = opaque;
3001 TCPCharDriver *s = chr->opaque;
3003 g_free(chr->filename);
3004 chr->filename = sockaddr_to_str(
3005 &s->sioc->localAddr, s->sioc->localAddrLen,
3006 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
3007 s->is_listen, s->is_telnet);
3009 s->connected = 1;
3010 if (s->ioc) {
3011 chr->fd_in_tag = io_add_watch_poll(s->ioc,
3012 tcp_chr_read_poll,
3013 tcp_chr_read,
3014 chr, NULL);
3016 qemu_chr_be_generic_open(chr);
3019 static void tcp_chr_update_read_handler(CharDriverState *chr,
3020 GMainContext *context)
3022 TCPCharDriver *s = chr->opaque;
3024 if (!s->connected) {
3025 return;
3028 remove_fd_in_watch(chr);
3029 if (s->ioc) {
3030 chr->fd_in_tag = io_add_watch_poll(s->ioc,
3031 tcp_chr_read_poll,
3032 tcp_chr_read, chr,
3033 context);
3037 typedef struct {
3038 CharDriverState *chr;
3039 char buf[12];
3040 size_t buflen;
3041 } TCPCharDriverTelnetInit;
3043 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
3044 GIOCondition cond G_GNUC_UNUSED,
3045 gpointer user_data)
3047 TCPCharDriverTelnetInit *init = user_data;
3048 ssize_t ret;
3050 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
3051 if (ret < 0) {
3052 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3053 ret = 0;
3054 } else {
3055 tcp_chr_disconnect(init->chr);
3056 return FALSE;
3059 init->buflen -= ret;
3061 if (init->buflen == 0) {
3062 tcp_chr_connect(init->chr);
3063 return FALSE;
3066 memmove(init->buf, init->buf + ret, init->buflen);
3068 return TRUE;
3071 static void tcp_chr_telnet_init(CharDriverState *chr)
3073 TCPCharDriver *s = chr->opaque;
3074 TCPCharDriverTelnetInit *init =
3075 g_new0(TCPCharDriverTelnetInit, 1);
3076 size_t n = 0;
3078 init->chr = chr;
3079 init->buflen = 12;
3081 #define IACSET(x, a, b, c) \
3082 do { \
3083 x[n++] = a; \
3084 x[n++] = b; \
3085 x[n++] = c; \
3086 } while (0)
3088 /* Prep the telnet negotion to put telnet in binary,
3089 * no echo, single char mode */
3090 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3091 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3092 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3093 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3095 #undef IACSET
3097 qio_channel_add_watch(
3098 s->ioc, G_IO_OUT,
3099 tcp_chr_telnet_init_io,
3100 init, NULL);
3104 static void tcp_chr_tls_handshake(Object *source,
3105 Error *err,
3106 gpointer user_data)
3108 CharDriverState *chr = user_data;
3109 TCPCharDriver *s = chr->opaque;
3111 if (err) {
3112 tcp_chr_disconnect(chr);
3113 } else {
3114 if (s->do_telnetopt) {
3115 tcp_chr_telnet_init(chr);
3116 } else {
3117 tcp_chr_connect(chr);
3123 static void tcp_chr_tls_init(CharDriverState *chr)
3125 TCPCharDriver *s = chr->opaque;
3126 QIOChannelTLS *tioc;
3127 Error *err = NULL;
3129 if (s->is_listen) {
3130 tioc = qio_channel_tls_new_server(
3131 s->ioc, s->tls_creds,
3132 NULL, /* XXX Use an ACL */
3133 &err);
3134 } else {
3135 tioc = qio_channel_tls_new_client(
3136 s->ioc, s->tls_creds,
3137 s->addr->u.inet.data->host,
3138 &err);
3140 if (tioc == NULL) {
3141 error_free(err);
3142 tcp_chr_disconnect(chr);
3143 return;
3145 object_unref(OBJECT(s->ioc));
3146 s->ioc = QIO_CHANNEL(tioc);
3148 qio_channel_tls_handshake(tioc,
3149 tcp_chr_tls_handshake,
3150 chr,
3151 NULL);
3155 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3157 TCPCharDriver *s = chr->opaque;
3158 if (s->ioc != NULL) {
3159 return -1;
3162 s->ioc = QIO_CHANNEL(sioc);
3163 object_ref(OBJECT(sioc));
3164 s->sioc = sioc;
3165 object_ref(OBJECT(sioc));
3167 qio_channel_set_blocking(s->ioc, false, NULL);
3169 if (s->do_nodelay) {
3170 qio_channel_set_delay(s->ioc, false);
3172 if (s->listen_tag) {
3173 g_source_remove(s->listen_tag);
3174 s->listen_tag = 0;
3177 if (s->tls_creds) {
3178 tcp_chr_tls_init(chr);
3179 } else {
3180 if (s->do_telnetopt) {
3181 tcp_chr_telnet_init(chr);
3182 } else {
3183 tcp_chr_connect(chr);
3187 return 0;
3191 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3193 int ret;
3194 QIOChannelSocket *sioc;
3196 sioc = qio_channel_socket_new_fd(fd, NULL);
3197 if (!sioc) {
3198 return -1;
3200 ret = tcp_chr_new_client(chr, sioc);
3201 object_unref(OBJECT(sioc));
3202 return ret;
3205 static gboolean tcp_chr_accept(QIOChannel *channel,
3206 GIOCondition cond,
3207 void *opaque)
3209 CharDriverState *chr = opaque;
3210 QIOChannelSocket *sioc;
3212 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3213 NULL);
3214 if (!sioc) {
3215 return TRUE;
3218 tcp_chr_new_client(chr, sioc);
3220 object_unref(OBJECT(sioc));
3222 return TRUE;
3225 static int tcp_chr_wait_connected(CharDriverState *chr, Error **errp)
3227 TCPCharDriver *s = chr->opaque;
3228 QIOChannelSocket *sioc;
3230 /* It can't wait on s->connected, since it is set asynchronously
3231 * in TLS and telnet cases, only wait for an accepted socket */
3232 while (!s->ioc) {
3233 if (s->is_listen) {
3234 fprintf(stderr, "QEMU waiting for connection on: %s\n",
3235 chr->filename);
3236 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), true, NULL);
3237 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
3238 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
3239 } else {
3240 sioc = qio_channel_socket_new();
3241 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3242 object_unref(OBJECT(sioc));
3243 return -1;
3245 tcp_chr_new_client(chr, sioc);
3246 object_unref(OBJECT(sioc));
3250 return 0;
3253 int qemu_chr_wait_connected(CharDriverState *chr, Error **errp)
3255 if (chr->chr_wait_connected) {
3256 return chr->chr_wait_connected(chr, errp);
3259 return 0;
3262 static void tcp_chr_close(CharDriverState *chr)
3264 TCPCharDriver *s = chr->opaque;
3266 tcp_chr_free_connection(chr);
3268 if (s->reconnect_timer) {
3269 g_source_remove(s->reconnect_timer);
3270 s->reconnect_timer = 0;
3272 qapi_free_SocketAddress(s->addr);
3273 if (s->listen_tag) {
3274 g_source_remove(s->listen_tag);
3275 s->listen_tag = 0;
3277 if (s->listen_ioc) {
3278 object_unref(OBJECT(s->listen_ioc));
3280 if (s->tls_creds) {
3281 object_unref(OBJECT(s->tls_creds));
3283 g_free(s);
3284 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3288 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3290 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3291 CharDriverState *chr = opaque;
3292 TCPCharDriver *s = chr->opaque;
3294 if (err) {
3295 check_report_connect_error(chr, err);
3296 object_unref(src);
3297 return;
3300 s->connect_err_reported = false;
3301 tcp_chr_new_client(chr, sioc);
3302 object_unref(OBJECT(sioc));
3306 /*********************************************************/
3307 /* Ring buffer chardev */
3309 typedef struct {
3310 size_t size;
3311 size_t prod;
3312 size_t cons;
3313 uint8_t *cbuf;
3314 } RingBufCharDriver;
3316 static size_t ringbuf_count(const CharDriverState *chr)
3318 const RingBufCharDriver *d = chr->opaque;
3320 return d->prod - d->cons;
3323 /* Called with chr_write_lock held. */
3324 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3326 RingBufCharDriver *d = chr->opaque;
3327 int i;
3329 if (!buf || (len < 0)) {
3330 return -1;
3333 for (i = 0; i < len; i++ ) {
3334 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3335 if (d->prod - d->cons > d->size) {
3336 d->cons = d->prod - d->size;
3340 return 0;
3343 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3345 RingBufCharDriver *d = chr->opaque;
3346 int i;
3348 qemu_mutex_lock(&chr->chr_write_lock);
3349 for (i = 0; i < len && d->cons != d->prod; i++) {
3350 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3352 qemu_mutex_unlock(&chr->chr_write_lock);
3354 return i;
3357 static void ringbuf_chr_close(struct CharDriverState *chr)
3359 RingBufCharDriver *d = chr->opaque;
3361 g_free(d->cbuf);
3362 g_free(d);
3363 chr->opaque = NULL;
3366 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3367 ChardevBackend *backend,
3368 ChardevReturn *ret,
3369 Error **errp)
3371 ChardevRingbuf *opts = backend->u.ringbuf.data;
3372 ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
3373 CharDriverState *chr;
3374 RingBufCharDriver *d;
3376 chr = qemu_chr_alloc(common, errp);
3377 if (!chr) {
3378 return NULL;
3380 d = g_malloc(sizeof(*d));
3382 d->size = opts->has_size ? opts->size : 65536;
3384 /* The size must be power of 2 */
3385 if (d->size & (d->size - 1)) {
3386 error_setg(errp, "size of ringbuf chardev must be power of two");
3387 goto fail;
3390 d->prod = 0;
3391 d->cons = 0;
3392 d->cbuf = g_malloc0(d->size);
3394 chr->opaque = d;
3395 chr->chr_write = ringbuf_chr_write;
3396 chr->chr_close = ringbuf_chr_close;
3398 return chr;
3400 fail:
3401 g_free(d);
3402 qemu_chr_free_common(chr);
3403 return NULL;
3406 bool chr_is_ringbuf(const CharDriverState *chr)
3408 return chr->chr_write == ringbuf_chr_write;
3411 void qmp_ringbuf_write(const char *device, const char *data,
3412 bool has_format, enum DataFormat format,
3413 Error **errp)
3415 CharDriverState *chr;
3416 const uint8_t *write_data;
3417 int ret;
3418 gsize write_count;
3420 chr = qemu_chr_find(device);
3421 if (!chr) {
3422 error_setg(errp, "Device '%s' not found", device);
3423 return;
3426 if (!chr_is_ringbuf(chr)) {
3427 error_setg(errp,"%s is not a ringbuf device", device);
3428 return;
3431 if (has_format && (format == DATA_FORMAT_BASE64)) {
3432 write_data = qbase64_decode(data, -1,
3433 &write_count,
3434 errp);
3435 if (!write_data) {
3436 return;
3438 } else {
3439 write_data = (uint8_t *)data;
3440 write_count = strlen(data);
3443 ret = ringbuf_chr_write(chr, write_data, write_count);
3445 if (write_data != (uint8_t *)data) {
3446 g_free((void *)write_data);
3449 if (ret < 0) {
3450 error_setg(errp, "Failed to write to device %s", device);
3451 return;
3455 char *qmp_ringbuf_read(const char *device, int64_t size,
3456 bool has_format, enum DataFormat format,
3457 Error **errp)
3459 CharDriverState *chr;
3460 uint8_t *read_data;
3461 size_t count;
3462 char *data;
3464 chr = qemu_chr_find(device);
3465 if (!chr) {
3466 error_setg(errp, "Device '%s' not found", device);
3467 return NULL;
3470 if (!chr_is_ringbuf(chr)) {
3471 error_setg(errp,"%s is not a ringbuf device", device);
3472 return NULL;
3475 if (size <= 0) {
3476 error_setg(errp, "size must be greater than zero");
3477 return NULL;
3480 count = ringbuf_count(chr);
3481 size = size > count ? count : size;
3482 read_data = g_malloc(size + 1);
3484 ringbuf_chr_read(chr, read_data, size);
3486 if (has_format && (format == DATA_FORMAT_BASE64)) {
3487 data = g_base64_encode(read_data, size);
3488 g_free(read_data);
3489 } else {
3491 * FIXME should read only complete, valid UTF-8 characters up
3492 * to @size bytes. Invalid sequences should be replaced by a
3493 * suitable replacement character. Except when (and only
3494 * when) ring buffer lost characters since last read, initial
3495 * continuation characters should be dropped.
3497 read_data[size] = 0;
3498 data = (char *)read_data;
3501 return data;
3504 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3506 char host[65], port[33], width[8], height[8];
3507 int pos;
3508 const char *p;
3509 QemuOpts *opts;
3510 Error *local_err = NULL;
3512 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3513 if (local_err) {
3514 error_report_err(local_err);
3515 return NULL;
3518 if (strstart(filename, "mon:", &p)) {
3519 filename = p;
3520 qemu_opt_set(opts, "mux", "on", &error_abort);
3521 if (strcmp(filename, "stdio") == 0) {
3522 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3523 * but pass it to the guest. Handle this only for compat syntax,
3524 * for -chardev syntax we have special option for this.
3525 * This is what -nographic did, redirecting+muxing serial+monitor
3526 * to stdio causing Ctrl+C to be passed to guest. */
3527 qemu_opt_set(opts, "signal", "off", &error_abort);
3531 if (strcmp(filename, "null") == 0 ||
3532 strcmp(filename, "pty") == 0 ||
3533 strcmp(filename, "msmouse") == 0 ||
3534 strcmp(filename, "braille") == 0 ||
3535 strcmp(filename, "testdev") == 0 ||
3536 strcmp(filename, "stdio") == 0) {
3537 qemu_opt_set(opts, "backend", filename, &error_abort);
3538 return opts;
3540 if (strstart(filename, "vc", &p)) {
3541 qemu_opt_set(opts, "backend", "vc", &error_abort);
3542 if (*p == ':') {
3543 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3544 /* pixels */
3545 qemu_opt_set(opts, "width", width, &error_abort);
3546 qemu_opt_set(opts, "height", height, &error_abort);
3547 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3548 /* chars */
3549 qemu_opt_set(opts, "cols", width, &error_abort);
3550 qemu_opt_set(opts, "rows", height, &error_abort);
3551 } else {
3552 goto fail;
3555 return opts;
3557 if (strcmp(filename, "con:") == 0) {
3558 qemu_opt_set(opts, "backend", "console", &error_abort);
3559 return opts;
3561 if (strstart(filename, "COM", NULL)) {
3562 qemu_opt_set(opts, "backend", "serial", &error_abort);
3563 qemu_opt_set(opts, "path", filename, &error_abort);
3564 return opts;
3566 if (strstart(filename, "file:", &p)) {
3567 qemu_opt_set(opts, "backend", "file", &error_abort);
3568 qemu_opt_set(opts, "path", p, &error_abort);
3569 return opts;
3571 if (strstart(filename, "pipe:", &p)) {
3572 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3573 qemu_opt_set(opts, "path", p, &error_abort);
3574 return opts;
3576 if (strstart(filename, "tcp:", &p) ||
3577 strstart(filename, "telnet:", &p)) {
3578 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3579 host[0] = 0;
3580 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3581 goto fail;
3583 qemu_opt_set(opts, "backend", "socket", &error_abort);
3584 qemu_opt_set(opts, "host", host, &error_abort);
3585 qemu_opt_set(opts, "port", port, &error_abort);
3586 if (p[pos] == ',') {
3587 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3588 if (local_err) {
3589 error_report_err(local_err);
3590 goto fail;
3593 if (strstart(filename, "telnet:", &p))
3594 qemu_opt_set(opts, "telnet", "on", &error_abort);
3595 return opts;
3597 if (strstart(filename, "udp:", &p)) {
3598 qemu_opt_set(opts, "backend", "udp", &error_abort);
3599 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3600 host[0] = 0;
3601 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3602 goto fail;
3605 qemu_opt_set(opts, "host", host, &error_abort);
3606 qemu_opt_set(opts, "port", port, &error_abort);
3607 if (p[pos] == '@') {
3608 p += pos + 1;
3609 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3610 host[0] = 0;
3611 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3612 goto fail;
3615 qemu_opt_set(opts, "localaddr", host, &error_abort);
3616 qemu_opt_set(opts, "localport", port, &error_abort);
3618 return opts;
3620 if (strstart(filename, "unix:", &p)) {
3621 qemu_opt_set(opts, "backend", "socket", &error_abort);
3622 qemu_opts_do_parse(opts, p, "path", &local_err);
3623 if (local_err) {
3624 error_report_err(local_err);
3625 goto fail;
3627 return opts;
3629 if (strstart(filename, "/dev/parport", NULL) ||
3630 strstart(filename, "/dev/ppi", NULL)) {
3631 qemu_opt_set(opts, "backend", "parport", &error_abort);
3632 qemu_opt_set(opts, "path", filename, &error_abort);
3633 return opts;
3635 if (strstart(filename, "/dev/", NULL)) {
3636 qemu_opt_set(opts, "backend", "tty", &error_abort);
3637 qemu_opt_set(opts, "path", filename, &error_abort);
3638 return opts;
3641 fail:
3642 qemu_opts_del(opts);
3643 return NULL;
3646 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3648 const char *logfile = qemu_opt_get(opts, "logfile");
3650 backend->has_logfile = logfile != NULL;
3651 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3653 backend->has_logappend = true;
3654 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3658 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3659 Error **errp)
3661 const char *path = qemu_opt_get(opts, "path");
3662 ChardevFile *file;
3664 if (path == NULL) {
3665 error_setg(errp, "chardev: file: no filename given");
3666 return;
3668 file = backend->u.file.data = g_new0(ChardevFile, 1);
3669 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3670 file->out = g_strdup(path);
3672 file->has_append = true;
3673 file->append = qemu_opt_get_bool(opts, "append", false);
3676 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3677 Error **errp)
3679 ChardevStdio *stdio;
3681 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3682 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3683 stdio->has_signal = true;
3684 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3687 #ifdef HAVE_CHARDEV_SERIAL
3688 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3689 Error **errp)
3691 const char *device = qemu_opt_get(opts, "path");
3692 ChardevHostdev *serial;
3694 if (device == NULL) {
3695 error_setg(errp, "chardev: serial/tty: no device path given");
3696 return;
3698 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3699 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3700 serial->device = g_strdup(device);
3702 #endif
3704 #ifdef HAVE_CHARDEV_PARPORT
3705 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3706 Error **errp)
3708 const char *device = qemu_opt_get(opts, "path");
3709 ChardevHostdev *parallel;
3711 if (device == NULL) {
3712 error_setg(errp, "chardev: parallel: no device path given");
3713 return;
3715 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3716 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3717 parallel->device = g_strdup(device);
3719 #endif
3721 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3722 Error **errp)
3724 const char *device = qemu_opt_get(opts, "path");
3725 ChardevHostdev *dev;
3727 if (device == NULL) {
3728 error_setg(errp, "chardev: pipe: no device path given");
3729 return;
3731 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3732 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3733 dev->device = g_strdup(device);
3736 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3737 Error **errp)
3739 int val;
3740 ChardevRingbuf *ringbuf;
3742 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3743 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3745 val = qemu_opt_get_size(opts, "size", 0);
3746 if (val != 0) {
3747 ringbuf->has_size = true;
3748 ringbuf->size = val;
3752 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3753 Error **errp)
3755 const char *chardev = qemu_opt_get(opts, "chardev");
3756 ChardevMux *mux;
3758 if (chardev == NULL) {
3759 error_setg(errp, "chardev: mux: no chardev given");
3760 return;
3762 mux = backend->u.mux.data = g_new0(ChardevMux, 1);
3763 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
3764 mux->chardev = g_strdup(chardev);
3767 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3768 Error **errp)
3770 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3771 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3772 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3773 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3774 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3775 const char *path = qemu_opt_get(opts, "path");
3776 const char *host = qemu_opt_get(opts, "host");
3777 const char *port = qemu_opt_get(opts, "port");
3778 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3779 SocketAddress *addr;
3780 ChardevSocket *sock;
3782 if (!path) {
3783 if (!host) {
3784 error_setg(errp, "chardev: socket: no host given");
3785 return;
3787 if (!port) {
3788 error_setg(errp, "chardev: socket: no port given");
3789 return;
3791 } else {
3792 if (tls_creds) {
3793 error_setg(errp, "TLS can only be used over TCP socket");
3794 return;
3798 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
3799 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
3801 sock->has_nodelay = true;
3802 sock->nodelay = do_nodelay;
3803 sock->has_server = true;
3804 sock->server = is_listen;
3805 sock->has_telnet = true;
3806 sock->telnet = is_telnet;
3807 sock->has_wait = true;
3808 sock->wait = is_waitconnect;
3809 sock->has_reconnect = true;
3810 sock->reconnect = reconnect;
3811 sock->tls_creds = g_strdup(tls_creds);
3813 addr = g_new0(SocketAddress, 1);
3814 if (path) {
3815 UnixSocketAddress *q_unix;
3816 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3817 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
3818 q_unix->path = g_strdup(path);
3819 } else {
3820 addr->type = SOCKET_ADDRESS_KIND_INET;
3821 addr->u.inet.data = g_new(InetSocketAddress, 1);
3822 *addr->u.inet.data = (InetSocketAddress) {
3823 .host = g_strdup(host),
3824 .port = g_strdup(port),
3825 .has_to = qemu_opt_get(opts, "to"),
3826 .to = qemu_opt_get_number(opts, "to", 0),
3827 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3828 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3829 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3830 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3833 sock->addr = addr;
3836 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3837 Error **errp)
3839 const char *host = qemu_opt_get(opts, "host");
3840 const char *port = qemu_opt_get(opts, "port");
3841 const char *localaddr = qemu_opt_get(opts, "localaddr");
3842 const char *localport = qemu_opt_get(opts, "localport");
3843 bool has_local = false;
3844 SocketAddress *addr;
3845 ChardevUdp *udp;
3847 if (host == NULL || strlen(host) == 0) {
3848 host = "localhost";
3850 if (port == NULL || strlen(port) == 0) {
3851 error_setg(errp, "chardev: udp: remote port not specified");
3852 return;
3854 if (localport == NULL || strlen(localport) == 0) {
3855 localport = "0";
3856 } else {
3857 has_local = true;
3859 if (localaddr == NULL || strlen(localaddr) == 0) {
3860 localaddr = "";
3861 } else {
3862 has_local = true;
3865 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
3866 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
3868 addr = g_new0(SocketAddress, 1);
3869 addr->type = SOCKET_ADDRESS_KIND_INET;
3870 addr->u.inet.data = g_new(InetSocketAddress, 1);
3871 *addr->u.inet.data = (InetSocketAddress) {
3872 .host = g_strdup(host),
3873 .port = g_strdup(port),
3874 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3875 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3876 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3877 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3879 udp->remote = addr;
3881 if (has_local) {
3882 udp->has_local = true;
3883 addr = g_new0(SocketAddress, 1);
3884 addr->type = SOCKET_ADDRESS_KIND_INET;
3885 addr->u.inet.data = g_new(InetSocketAddress, 1);
3886 *addr->u.inet.data = (InetSocketAddress) {
3887 .host = g_strdup(localaddr),
3888 .port = g_strdup(localport),
3890 udp->local = addr;
3894 typedef struct CharDriver {
3895 const char *name;
3896 ChardevBackendKind kind;
3897 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3898 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3899 ChardevReturn *ret, Error **errp);
3900 } CharDriver;
3902 static GSList *backends;
3904 void register_char_driver(const char *name, ChardevBackendKind kind,
3905 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3906 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3907 ChardevReturn *ret, Error **errp))
3909 CharDriver *s;
3911 s = g_malloc0(sizeof(*s));
3912 s->name = g_strdup(name);
3913 s->kind = kind;
3914 s->parse = parse;
3915 s->create = create;
3917 backends = g_slist_append(backends, s);
3920 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3921 void (*init)(struct CharDriverState *s),
3922 Error **errp)
3924 Error *local_err = NULL;
3925 CharDriver *cd;
3926 CharDriverState *chr;
3927 GSList *i;
3928 ChardevReturn *ret = NULL;
3929 ChardevBackend *backend;
3930 const char *id = qemu_opts_id(opts);
3931 char *bid = NULL;
3933 if (qemu_opt_get(opts, "backend") == NULL) {
3934 error_setg(errp, "chardev: \"%s\" missing backend",
3935 qemu_opts_id(opts));
3936 goto err;
3939 if (is_help_option(qemu_opt_get(opts, "backend"))) {
3940 fprintf(stderr, "Available chardev backend types:\n");
3941 for (i = backends; i; i = i->next) {
3942 cd = i->data;
3943 fprintf(stderr, "%s\n", cd->name);
3945 exit(!is_help_option(qemu_opt_get(opts, "backend")));
3948 if (id == NULL) {
3949 error_setg(errp, "chardev: no id specified");
3950 goto err;
3953 for (i = backends; i; i = i->next) {
3954 cd = i->data;
3956 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3957 break;
3960 if (i == NULL) {
3961 error_setg(errp, "chardev: backend \"%s\" not found",
3962 qemu_opt_get(opts, "backend"));
3963 goto err;
3966 backend = g_new0(ChardevBackend, 1);
3968 if (qemu_opt_get_bool(opts, "mux", 0)) {
3969 bid = g_strdup_printf("%s-base", id);
3972 chr = NULL;
3973 backend->type = cd->kind;
3974 if (cd->parse) {
3975 cd->parse(opts, backend, &local_err);
3976 if (local_err) {
3977 error_propagate(errp, local_err);
3978 goto qapi_out;
3980 } else {
3981 ChardevCommon *cc = g_new0(ChardevCommon, 1);
3982 qemu_chr_parse_common(opts, cc);
3983 backend->u.null.data = cc; /* Any ChardevCommon member would work */
3986 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3987 if (!ret) {
3988 goto qapi_out;
3991 if (bid) {
3992 qapi_free_ChardevBackend(backend);
3993 qapi_free_ChardevReturn(ret);
3994 backend = g_new0(ChardevBackend, 1);
3995 backend->u.mux.data = g_new0(ChardevMux, 1);
3996 backend->type = CHARDEV_BACKEND_KIND_MUX;
3997 backend->u.mux.data->chardev = g_strdup(bid);
3998 ret = qmp_chardev_add(id, backend, errp);
3999 if (!ret) {
4000 chr = qemu_chr_find(bid);
4001 qemu_chr_delete(chr);
4002 chr = NULL;
4003 goto qapi_out;
4007 chr = qemu_chr_find(id);
4009 qapi_out:
4010 qapi_free_ChardevBackend(backend);
4011 qapi_free_ChardevReturn(ret);
4012 g_free(bid);
4013 return chr;
4015 err:
4016 return NULL;
4019 CharDriverState *qemu_chr_new_noreplay(const char *label, const char *filename,
4020 void (*init)(struct CharDriverState *s))
4022 const char *p;
4023 CharDriverState *chr;
4024 QemuOpts *opts;
4025 Error *err = NULL;
4027 if (strstart(filename, "chardev:", &p)) {
4028 return qemu_chr_find(p);
4031 opts = qemu_chr_parse_compat(label, filename);
4032 if (!opts)
4033 return NULL;
4035 chr = qemu_chr_new_from_opts(opts, init, &err);
4036 if (err) {
4037 error_report_err(err);
4039 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
4040 qemu_chr_fe_claim_no_fail(chr);
4041 monitor_init(chr, MONITOR_USE_READLINE);
4043 qemu_opts_del(opts);
4044 return chr;
4047 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
4049 CharDriverState *chr;
4050 chr = qemu_chr_new_noreplay(label, filename, init);
4051 if (chr) {
4052 chr->replay = replay_mode != REPLAY_MODE_NONE;
4053 if (chr->replay && chr->chr_ioctl) {
4054 fprintf(stderr,
4055 "Replay: ioctl is not supported for serial devices yet\n");
4057 replay_register_char_driver(chr);
4059 return chr;
4062 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
4064 if (chr->chr_set_echo) {
4065 chr->chr_set_echo(chr, echo);
4069 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
4071 if (chr->fe_open == fe_open) {
4072 return;
4074 chr->fe_open = fe_open;
4075 if (chr->chr_set_fe_open) {
4076 chr->chr_set_fe_open(chr, fe_open);
4080 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
4082 if (chr->chr_fe_event) {
4083 chr->chr_fe_event(chr, event);
4087 guint qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
4088 GIOFunc func, void *user_data)
4090 GSource *src;
4091 guint tag;
4093 if (s->chr_add_watch == NULL) {
4094 return 0;
4097 src = s->chr_add_watch(s, cond);
4098 if (!src) {
4099 return 0;
4102 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
4103 tag = g_source_attach(src, NULL);
4104 g_source_unref(src);
4106 return tag;
4109 int qemu_chr_fe_claim(CharDriverState *s)
4111 if (s->avail_connections < 1) {
4112 return -1;
4114 s->avail_connections--;
4115 return 0;
4118 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
4120 if (qemu_chr_fe_claim(s) != 0) {
4121 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
4122 __func__, s->label);
4123 exit(1);
4127 void qemu_chr_fe_release(CharDriverState *s)
4129 s->avail_connections++;
4132 void qemu_chr_disconnect(CharDriverState *chr)
4134 if (chr->chr_disconnect) {
4135 chr->chr_disconnect(chr);
4139 static void qemu_chr_free_common(CharDriverState *chr)
4141 g_free(chr->filename);
4142 g_free(chr->label);
4143 if (chr->logfd != -1) {
4144 close(chr->logfd);
4146 qemu_mutex_destroy(&chr->chr_write_lock);
4147 g_free(chr);
4150 void qemu_chr_free(CharDriverState *chr)
4152 if (chr->chr_close) {
4153 chr->chr_close(chr);
4155 qemu_chr_free_common(chr);
4158 void qemu_chr_delete(CharDriverState *chr)
4160 QTAILQ_REMOVE(&chardevs, chr, next);
4161 qemu_chr_free(chr);
4164 ChardevInfoList *qmp_query_chardev(Error **errp)
4166 ChardevInfoList *chr_list = NULL;
4167 CharDriverState *chr;
4169 QTAILQ_FOREACH(chr, &chardevs, next) {
4170 ChardevInfoList *info = g_malloc0(sizeof(*info));
4171 info->value = g_malloc0(sizeof(*info->value));
4172 info->value->label = g_strdup(chr->label);
4173 info->value->filename = g_strdup(chr->filename);
4174 info->value->frontend_open = chr->fe_open;
4176 info->next = chr_list;
4177 chr_list = info;
4180 return chr_list;
4183 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4185 ChardevBackendInfoList *backend_list = NULL;
4186 CharDriver *c = NULL;
4187 GSList *i = NULL;
4189 for (i = backends; i; i = i->next) {
4190 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4191 c = i->data;
4192 info->value = g_malloc0(sizeof(*info->value));
4193 info->value->name = g_strdup(c->name);
4195 info->next = backend_list;
4196 backend_list = info;
4199 return backend_list;
4202 CharDriverState *qemu_chr_find(const char *name)
4204 CharDriverState *chr;
4206 QTAILQ_FOREACH(chr, &chardevs, next) {
4207 if (strcmp(chr->label, name) != 0)
4208 continue;
4209 return chr;
4211 return NULL;
4214 QemuOptsList qemu_chardev_opts = {
4215 .name = "chardev",
4216 .implied_opt_name = "backend",
4217 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4218 .desc = {
4220 .name = "backend",
4221 .type = QEMU_OPT_STRING,
4223 .name = "path",
4224 .type = QEMU_OPT_STRING,
4226 .name = "host",
4227 .type = QEMU_OPT_STRING,
4229 .name = "port",
4230 .type = QEMU_OPT_STRING,
4232 .name = "localaddr",
4233 .type = QEMU_OPT_STRING,
4235 .name = "localport",
4236 .type = QEMU_OPT_STRING,
4238 .name = "to",
4239 .type = QEMU_OPT_NUMBER,
4241 .name = "ipv4",
4242 .type = QEMU_OPT_BOOL,
4244 .name = "ipv6",
4245 .type = QEMU_OPT_BOOL,
4247 .name = "wait",
4248 .type = QEMU_OPT_BOOL,
4250 .name = "server",
4251 .type = QEMU_OPT_BOOL,
4253 .name = "delay",
4254 .type = QEMU_OPT_BOOL,
4256 .name = "reconnect",
4257 .type = QEMU_OPT_NUMBER,
4259 .name = "telnet",
4260 .type = QEMU_OPT_BOOL,
4262 .name = "tls-creds",
4263 .type = QEMU_OPT_STRING,
4265 .name = "width",
4266 .type = QEMU_OPT_NUMBER,
4268 .name = "height",
4269 .type = QEMU_OPT_NUMBER,
4271 .name = "cols",
4272 .type = QEMU_OPT_NUMBER,
4274 .name = "rows",
4275 .type = QEMU_OPT_NUMBER,
4277 .name = "mux",
4278 .type = QEMU_OPT_BOOL,
4280 .name = "signal",
4281 .type = QEMU_OPT_BOOL,
4283 .name = "name",
4284 .type = QEMU_OPT_STRING,
4286 .name = "debug",
4287 .type = QEMU_OPT_NUMBER,
4289 .name = "size",
4290 .type = QEMU_OPT_SIZE,
4292 .name = "chardev",
4293 .type = QEMU_OPT_STRING,
4295 .name = "append",
4296 .type = QEMU_OPT_BOOL,
4298 .name = "logfile",
4299 .type = QEMU_OPT_STRING,
4301 .name = "logappend",
4302 .type = QEMU_OPT_BOOL,
4304 { /* end of list */ }
4308 #ifdef _WIN32
4310 static CharDriverState *qmp_chardev_open_file(const char *id,
4311 ChardevBackend *backend,
4312 ChardevReturn *ret,
4313 Error **errp)
4315 ChardevFile *file = backend->u.file.data;
4316 ChardevCommon *common = qapi_ChardevFile_base(file);
4317 HANDLE out;
4318 DWORD accessmode;
4319 DWORD flags;
4321 if (file->has_in) {
4322 error_setg(errp, "input file not supported");
4323 return NULL;
4326 if (file->has_append && file->append) {
4327 /* Append to file if it already exists. */
4328 accessmode = FILE_GENERIC_WRITE & ~FILE_WRITE_DATA;
4329 flags = OPEN_ALWAYS;
4330 } else {
4331 /* Truncate file if it already exists. */
4332 accessmode = GENERIC_WRITE;
4333 flags = CREATE_ALWAYS;
4336 out = CreateFile(file->out, accessmode, FILE_SHARE_READ, NULL, flags,
4337 FILE_ATTRIBUTE_NORMAL, NULL);
4338 if (out == INVALID_HANDLE_VALUE) {
4339 error_setg(errp, "open %s failed", file->out);
4340 return NULL;
4342 return qemu_chr_open_win_file(out, common, errp);
4345 static CharDriverState *qmp_chardev_open_serial(const char *id,
4346 ChardevBackend *backend,
4347 ChardevReturn *ret,
4348 Error **errp)
4350 ChardevHostdev *serial = backend->u.serial.data;
4351 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4352 return qemu_chr_open_win_path(serial->device, common, errp);
4355 #else /* WIN32 */
4357 static int qmp_chardev_open_file_source(char *src, int flags,
4358 Error **errp)
4360 int fd = -1;
4362 TFR(fd = qemu_open(src, flags, 0666));
4363 if (fd == -1) {
4364 error_setg_file_open(errp, errno, src);
4366 return fd;
4369 static CharDriverState *qmp_chardev_open_file(const char *id,
4370 ChardevBackend *backend,
4371 ChardevReturn *ret,
4372 Error **errp)
4374 ChardevFile *file = backend->u.file.data;
4375 ChardevCommon *common = qapi_ChardevFile_base(file);
4376 int flags, in = -1, out;
4378 flags = O_WRONLY | O_CREAT | O_BINARY;
4379 if (file->has_append && file->append) {
4380 flags |= O_APPEND;
4381 } else {
4382 flags |= O_TRUNC;
4385 out = qmp_chardev_open_file_source(file->out, flags, errp);
4386 if (out < 0) {
4387 return NULL;
4390 if (file->has_in) {
4391 flags = O_RDONLY;
4392 in = qmp_chardev_open_file_source(file->in, flags, errp);
4393 if (in < 0) {
4394 qemu_close(out);
4395 return NULL;
4399 return qemu_chr_open_fd(in, out, common, errp);
4402 #ifdef HAVE_CHARDEV_SERIAL
4403 static CharDriverState *qmp_chardev_open_serial(const char *id,
4404 ChardevBackend *backend,
4405 ChardevReturn *ret,
4406 Error **errp)
4408 ChardevHostdev *serial = backend->u.serial.data;
4409 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4410 int fd;
4412 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4413 if (fd < 0) {
4414 return NULL;
4416 qemu_set_nonblock(fd);
4417 return qemu_chr_open_tty_fd(fd, common, errp);
4419 #endif
4421 #ifdef HAVE_CHARDEV_PARPORT
4422 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4423 ChardevBackend *backend,
4424 ChardevReturn *ret,
4425 Error **errp)
4427 ChardevHostdev *parallel = backend->u.parallel.data;
4428 ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
4429 int fd;
4431 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4432 if (fd < 0) {
4433 return NULL;
4435 return qemu_chr_open_pp_fd(fd, common, errp);
4437 #endif
4439 #endif /* WIN32 */
4441 static gboolean socket_reconnect_timeout(gpointer opaque)
4443 CharDriverState *chr = opaque;
4444 TCPCharDriver *s = chr->opaque;
4445 QIOChannelSocket *sioc;
4447 s->reconnect_timer = 0;
4449 if (chr->be_open) {
4450 return false;
4453 sioc = qio_channel_socket_new();
4454 qio_channel_socket_connect_async(sioc, s->addr,
4455 qemu_chr_socket_connected,
4456 chr, NULL);
4458 return false;
4461 static CharDriverState *qmp_chardev_open_socket(const char *id,
4462 ChardevBackend *backend,
4463 ChardevReturn *ret,
4464 Error **errp)
4466 CharDriverState *chr;
4467 TCPCharDriver *s;
4468 ChardevSocket *sock = backend->u.socket.data;
4469 SocketAddress *addr = sock->addr;
4470 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4471 bool is_listen = sock->has_server ? sock->server : true;
4472 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4473 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4474 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4475 ChardevCommon *common = qapi_ChardevSocket_base(sock);
4476 QIOChannelSocket *sioc = NULL;
4478 chr = qemu_chr_alloc(common, errp);
4479 if (!chr) {
4480 return NULL;
4482 s = g_new0(TCPCharDriver, 1);
4484 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4485 s->is_listen = is_listen;
4486 s->is_telnet = is_telnet;
4487 s->do_nodelay = do_nodelay;
4488 if (sock->tls_creds) {
4489 Object *creds;
4490 creds = object_resolve_path_component(
4491 object_get_objects_root(), sock->tls_creds);
4492 if (!creds) {
4493 error_setg(errp, "No TLS credentials with id '%s'",
4494 sock->tls_creds);
4495 goto error;
4497 s->tls_creds = (QCryptoTLSCreds *)
4498 object_dynamic_cast(creds,
4499 TYPE_QCRYPTO_TLS_CREDS);
4500 if (!s->tls_creds) {
4501 error_setg(errp, "Object with id '%s' is not TLS credentials",
4502 sock->tls_creds);
4503 goto error;
4505 object_ref(OBJECT(s->tls_creds));
4506 if (is_listen) {
4507 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4508 error_setg(errp, "%s",
4509 "Expected TLS credentials for server endpoint");
4510 goto error;
4512 } else {
4513 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4514 error_setg(errp, "%s",
4515 "Expected TLS credentials for client endpoint");
4516 goto error;
4521 s->addr = QAPI_CLONE(SocketAddress, sock->addr);
4523 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_RECONNECTABLE);
4524 if (s->is_unix) {
4525 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_FD_PASS);
4528 chr->opaque = s;
4529 chr->chr_wait_connected = tcp_chr_wait_connected;
4530 chr->chr_write = tcp_chr_write;
4531 chr->chr_sync_read = tcp_chr_sync_read;
4532 chr->chr_close = tcp_chr_close;
4533 chr->chr_disconnect = tcp_chr_disconnect;
4534 chr->get_msgfds = tcp_get_msgfds;
4535 chr->set_msgfds = tcp_set_msgfds;
4536 chr->chr_add_client = tcp_chr_add_client;
4537 chr->chr_add_watch = tcp_chr_add_watch;
4538 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4539 /* be isn't opened until we get a connection */
4540 chr->explicit_be_open = true;
4542 chr->filename = SocketAddress_to_str("disconnected:",
4543 addr, is_listen, is_telnet);
4545 if (is_listen) {
4546 if (is_telnet) {
4547 s->do_telnetopt = 1;
4549 } else if (reconnect > 0) {
4550 s->reconnect_time = reconnect;
4553 if (s->reconnect_time) {
4554 sioc = qio_channel_socket_new();
4555 qio_channel_socket_connect_async(sioc, s->addr,
4556 qemu_chr_socket_connected,
4557 chr, NULL);
4558 } else {
4559 if (s->is_listen) {
4560 sioc = qio_channel_socket_new();
4561 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4562 goto error;
4564 s->listen_ioc = sioc;
4565 if (is_waitconnect &&
4566 qemu_chr_wait_connected(chr, errp) < 0) {
4567 goto error;
4569 if (!s->ioc) {
4570 s->listen_tag = qio_channel_add_watch(
4571 QIO_CHANNEL(s->listen_ioc), G_IO_IN,
4572 tcp_chr_accept, chr, NULL);
4574 } else if (qemu_chr_wait_connected(chr, errp) < 0) {
4575 goto error;
4579 return chr;
4581 error:
4582 if (sioc) {
4583 object_unref(OBJECT(sioc));
4585 if (s->tls_creds) {
4586 object_unref(OBJECT(s->tls_creds));
4588 g_free(s);
4589 qemu_chr_free_common(chr);
4590 return NULL;
4593 static CharDriverState *qmp_chardev_open_udp(const char *id,
4594 ChardevBackend *backend,
4595 ChardevReturn *ret,
4596 Error **errp)
4598 ChardevUdp *udp = backend->u.udp.data;
4599 ChardevCommon *common = qapi_ChardevUdp_base(udp);
4600 QIOChannelSocket *sioc = qio_channel_socket_new();
4602 if (qio_channel_socket_dgram_sync(sioc,
4603 udp->local, udp->remote,
4604 errp) < 0) {
4605 object_unref(OBJECT(sioc));
4606 return NULL;
4608 return qemu_chr_open_udp(sioc, common, errp);
4612 bool qemu_chr_has_feature(CharDriverState *chr,
4613 CharDriverFeature feature)
4615 return test_bit(feature, chr->features);
4618 void qemu_chr_set_feature(CharDriverState *chr,
4619 CharDriverFeature feature)
4621 return set_bit(feature, chr->features);
4624 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4625 Error **errp)
4627 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4628 CharDriverState *chr = NULL;
4629 Error *local_err = NULL;
4630 GSList *i;
4631 CharDriver *cd;
4633 chr = qemu_chr_find(id);
4634 if (chr) {
4635 error_setg(errp, "Chardev '%s' already exists", id);
4636 g_free(ret);
4637 return NULL;
4640 for (i = backends; i; i = i->next) {
4641 cd = i->data;
4643 if (cd->kind == backend->type) {
4644 chr = cd->create(id, backend, ret, &local_err);
4645 if (local_err) {
4646 error_propagate(errp, local_err);
4647 goto out_error;
4649 break;
4653 if (chr == NULL) {
4654 assert(!i);
4655 error_setg(errp, "chardev backend not available");
4656 goto out_error;
4659 chr->label = g_strdup(id);
4660 chr->avail_connections =
4661 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4662 if (!chr->filename) {
4663 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4665 if (!chr->explicit_be_open) {
4666 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4668 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4669 return ret;
4671 out_error:
4672 g_free(ret);
4673 return NULL;
4676 void qmp_chardev_remove(const char *id, Error **errp)
4678 CharDriverState *chr;
4680 chr = qemu_chr_find(id);
4681 if (chr == NULL) {
4682 error_setg(errp, "Chardev '%s' not found", id);
4683 return;
4685 if (chr->chr_can_read || chr->chr_read ||
4686 chr->chr_event || chr->handler_opaque) {
4687 error_setg(errp, "Chardev '%s' is busy", id);
4688 return;
4690 if (chr->replay) {
4691 error_setg(errp,
4692 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4693 return;
4695 qemu_chr_delete(chr);
4698 void qemu_chr_cleanup(void)
4700 CharDriverState *chr, *tmp;
4702 QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
4703 qemu_chr_delete(chr);
4707 static void register_types(void)
4709 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4710 qemu_chr_open_null);
4711 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4712 qemu_chr_parse_socket, qmp_chardev_open_socket);
4713 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4714 qmp_chardev_open_udp);
4715 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4716 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4717 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4718 qemu_chr_parse_file_out, qmp_chardev_open_file);
4719 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4720 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4721 #if defined HAVE_CHARDEV_SERIAL
4722 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4723 qemu_chr_parse_serial, qmp_chardev_open_serial);
4724 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4725 qemu_chr_parse_serial, qmp_chardev_open_serial);
4726 #endif
4727 #ifdef HAVE_CHARDEV_PARPORT
4728 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4729 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4730 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4731 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4732 #endif
4733 #ifdef HAVE_CHARDEV_PTY
4734 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4735 qemu_chr_open_pty);
4736 #endif
4737 #ifdef _WIN32
4738 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4739 qemu_chr_open_win_con);
4740 #endif
4741 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4742 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4743 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4744 qemu_chr_open_mux);
4745 /* Bug-compatibility: */
4746 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4747 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4748 /* this must be done after machine init, since we register FEs with muxes
4749 * as part of realize functions like serial_isa_realizefn when -nographic
4750 * is specified
4752 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4755 type_init(register_types);