memory: don't sign-extend 32-bit writes
[qemu/kevin.git] / qemu-char.c
blob6b4a2997029338e22a6c1f4d737241824484832c
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 typedef struct MuxChardev MuxChardev;
94 /***********************************************************/
95 /* Socket address helpers */
97 static char *SocketAddress_to_str(const char *prefix, SocketAddress *addr,
98 bool is_listen, bool is_telnet)
100 switch (addr->type) {
101 case SOCKET_ADDRESS_KIND_INET:
102 return g_strdup_printf("%s%s:%s:%s%s", prefix,
103 is_telnet ? "telnet" : "tcp",
104 addr->u.inet.data->host,
105 addr->u.inet.data->port,
106 is_listen ? ",server" : "");
107 break;
108 case SOCKET_ADDRESS_KIND_UNIX:
109 return g_strdup_printf("%sunix:%s%s", prefix,
110 addr->u.q_unix.data->path,
111 is_listen ? ",server" : "");
112 break;
113 case SOCKET_ADDRESS_KIND_FD:
114 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd.data->str,
115 is_listen ? ",server" : "");
116 break;
117 default:
118 abort();
122 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
123 struct sockaddr_storage *ps, socklen_t ps_len,
124 bool is_listen, bool is_telnet)
126 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
127 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
128 const char *left = "", *right = "";
130 switch (ss->ss_family) {
131 #ifndef _WIN32
132 case AF_UNIX:
133 return g_strdup_printf("unix:%s%s",
134 ((struct sockaddr_un *)(ss))->sun_path,
135 is_listen ? ",server" : "");
136 #endif
137 case AF_INET6:
138 left = "[";
139 right = "]";
140 /* fall through */
141 case AF_INET:
142 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
143 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
144 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
145 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
146 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
147 is_telnet ? "telnet" : "tcp",
148 left, shost, right, sserv,
149 is_listen ? ",server" : "",
150 left, phost, right, pserv);
152 default:
153 return g_strdup_printf("unknown");
157 /***********************************************************/
158 /* character device */
160 static QTAILQ_HEAD(ChardevHead, Chardev) chardevs =
161 QTAILQ_HEAD_INITIALIZER(chardevs);
163 void qemu_chr_be_event(Chardev *s, int event)
165 CharBackend *be = s->be;
167 /* Keep track if the char device is open */
168 switch (event) {
169 case CHR_EVENT_OPENED:
170 s->be_open = 1;
171 break;
172 case CHR_EVENT_CLOSED:
173 s->be_open = 0;
174 break;
177 if (!be || !be->chr_event) {
178 return;
181 be->chr_event(be->opaque, event);
184 void qemu_chr_be_generic_open(Chardev *s)
186 qemu_chr_be_event(s, CHR_EVENT_OPENED);
190 /* Not reporting errors from writing to logfile, as logs are
191 * defined to be "best effort" only */
192 static void qemu_chr_fe_write_log(Chardev *s,
193 const uint8_t *buf, size_t len)
195 size_t done = 0;
196 ssize_t ret;
198 if (s->logfd < 0) {
199 return;
202 while (done < len) {
203 retry:
204 ret = write(s->logfd, buf + done, len - done);
205 if (ret == -1 && errno == EAGAIN) {
206 g_usleep(100);
207 goto retry;
210 if (ret <= 0) {
211 return;
213 done += ret;
217 static int qemu_chr_fe_write_buffer(Chardev *s,
218 const uint8_t *buf, int len, int *offset)
220 ChardevClass *cc = CHARDEV_GET_CLASS(s);
221 int res = 0;
222 *offset = 0;
224 qemu_mutex_lock(&s->chr_write_lock);
225 while (*offset < len) {
226 retry:
227 res = cc->chr_write(s, buf + *offset, len - *offset);
228 if (res < 0 && errno == EAGAIN) {
229 g_usleep(100);
230 goto retry;
233 if (res <= 0) {
234 break;
237 *offset += res;
239 if (*offset > 0) {
240 qemu_chr_fe_write_log(s, buf, *offset);
242 qemu_mutex_unlock(&s->chr_write_lock);
244 return res;
247 static bool qemu_chr_replay(Chardev *chr)
249 return qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_REPLAY);
252 int qemu_chr_fe_write(CharBackend *be, const uint8_t *buf, int len)
254 Chardev *s = be->chr;
255 ChardevClass *cc;
256 int ret;
258 if (!s) {
259 return 0;
262 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_PLAY) {
263 int offset;
264 replay_char_write_event_load(&ret, &offset);
265 assert(offset <= len);
266 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
267 return ret;
270 cc = CHARDEV_GET_CLASS(s);
271 qemu_mutex_lock(&s->chr_write_lock);
272 ret = cc->chr_write(s, buf, len);
274 if (ret > 0) {
275 qemu_chr_fe_write_log(s, buf, ret);
278 qemu_mutex_unlock(&s->chr_write_lock);
280 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
281 replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
284 return ret;
287 static int qemu_chr_write_all(Chardev *s, const uint8_t *buf, int len)
289 int offset;
290 int res;
292 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_PLAY) {
293 replay_char_write_event_load(&res, &offset);
294 assert(offset <= len);
295 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
296 return res;
299 res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
301 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
302 replay_char_write_event_save(res, offset);
305 if (res < 0) {
306 return res;
308 return offset;
311 int qemu_chr_fe_write_all(CharBackend *be, const uint8_t *buf, int len)
313 Chardev *s = be->chr;
315 if (!s) {
316 return 0;
319 return qemu_chr_write_all(s, buf, len);
322 int qemu_chr_fe_read_all(CharBackend *be, uint8_t *buf, int len)
324 Chardev *s = be->chr;
325 int offset = 0, counter = 10;
326 int res;
328 if (!s || !CHARDEV_GET_CLASS(s)->chr_sync_read) {
329 return 0;
332 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_PLAY) {
333 return replay_char_read_all_load(buf);
336 while (offset < len) {
337 retry:
338 res = CHARDEV_GET_CLASS(s)->chr_sync_read(s, buf + offset,
339 len - offset);
340 if (res == -1 && errno == EAGAIN) {
341 g_usleep(100);
342 goto retry;
345 if (res == 0) {
346 break;
349 if (res < 0) {
350 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
351 replay_char_read_all_save_error(res);
353 return res;
356 offset += res;
358 if (!counter--) {
359 break;
363 if (qemu_chr_replay(s) && replay_mode == REPLAY_MODE_RECORD) {
364 replay_char_read_all_save_buf(buf, offset);
366 return offset;
369 int qemu_chr_fe_ioctl(CharBackend *be, int cmd, void *arg)
371 Chardev *s = be->chr;
372 int res;
374 if (!s || !CHARDEV_GET_CLASS(s)->chr_ioctl || qemu_chr_replay(s)) {
375 res = -ENOTSUP;
376 } else {
377 res = CHARDEV_GET_CLASS(s)->chr_ioctl(s, cmd, arg);
380 return res;
383 int qemu_chr_be_can_write(Chardev *s)
385 CharBackend *be = s->be;
387 if (!be || !be->chr_can_read) {
388 return 0;
391 return be->chr_can_read(be->opaque);
394 void qemu_chr_be_write_impl(Chardev *s, uint8_t *buf, int len)
396 CharBackend *be = s->be;
398 if (be && be->chr_read) {
399 be->chr_read(be->opaque, buf, len);
403 void qemu_chr_be_write(Chardev *s, uint8_t *buf, int len)
405 if (qemu_chr_replay(s)) {
406 if (replay_mode == REPLAY_MODE_PLAY) {
407 return;
409 replay_chr_be_write(s, buf, len);
410 } else {
411 qemu_chr_be_write_impl(s, buf, len);
415 int qemu_chr_fe_get_msgfd(CharBackend *be)
417 Chardev *s = be->chr;
418 int fd;
419 int res = (qemu_chr_fe_get_msgfds(be, &fd, 1) == 1) ? fd : -1;
420 if (s && qemu_chr_replay(s)) {
421 error_report("Replay: get msgfd is not supported "
422 "for serial devices yet");
423 exit(1);
425 return res;
428 int qemu_chr_fe_get_msgfds(CharBackend *be, int *fds, int len)
430 Chardev *s = be->chr;
432 if (!s) {
433 return -1;
436 return CHARDEV_GET_CLASS(s)->get_msgfds ?
437 CHARDEV_GET_CLASS(s)->get_msgfds(s, fds, len) : -1;
440 int qemu_chr_fe_set_msgfds(CharBackend *be, int *fds, int num)
442 Chardev *s = be->chr;
444 if (!s) {
445 return -1;
448 return CHARDEV_GET_CLASS(s)->set_msgfds ?
449 CHARDEV_GET_CLASS(s)->set_msgfds(s, fds, num) : -1;
452 int qemu_chr_add_client(Chardev *s, int fd)
454 return CHARDEV_GET_CLASS(s)->chr_add_client ?
455 CHARDEV_GET_CLASS(s)->chr_add_client(s, fd) : -1;
458 void qemu_chr_fe_accept_input(CharBackend *be)
460 Chardev *s = be->chr;
462 if (!s) {
463 return;
466 if (CHARDEV_GET_CLASS(s)->chr_accept_input) {
467 CHARDEV_GET_CLASS(s)->chr_accept_input(s);
469 qemu_notify_event();
472 void qemu_chr_fe_printf(CharBackend *be, const char *fmt, ...)
474 char buf[READ_BUF_LEN];
475 va_list ap;
476 va_start(ap, fmt);
477 vsnprintf(buf, sizeof(buf), fmt, ap);
478 /* XXX this blocks entire thread. Rewrite to use
479 * qemu_chr_fe_write and background I/O callbacks */
480 qemu_chr_fe_write_all(be, (uint8_t *)buf, strlen(buf));
481 va_end(ap);
484 static void remove_fd_in_watch(Chardev *chr);
485 static void mux_chr_set_handlers(Chardev *chr, GMainContext *context);
486 static void mux_set_focus(Chardev *chr, int focus);
488 static void qemu_char_open(Chardev *chr, ChardevBackend *backend,
489 bool *be_opened, Error **errp)
491 ChardevClass *cc = CHARDEV_GET_CLASS(chr);
492 /* Any ChardevCommon member would work */
493 ChardevCommon *common = backend ? backend->u.null.data : NULL;
495 if (common && common->has_logfile) {
496 int flags = O_WRONLY | O_CREAT;
497 if (common->has_logappend &&
498 common->logappend) {
499 flags |= O_APPEND;
500 } else {
501 flags |= O_TRUNC;
503 chr->logfd = qemu_open(common->logfile, flags, 0666);
504 if (chr->logfd < 0) {
505 error_setg_errno(errp, errno,
506 "Unable to open logfile %s",
507 common->logfile);
508 return;
512 if (cc->open) {
513 cc->open(chr, backend, be_opened, errp);
517 static void char_init(Object *obj)
519 Chardev *chr = CHARDEV(obj);
521 chr->logfd = -1;
522 qemu_mutex_init(&chr->chr_write_lock);
525 static void char_finalize(Object *obj)
527 Chardev *chr = CHARDEV(obj);
529 if (chr->be) {
530 chr->be->chr = NULL;
532 g_free(chr->filename);
533 g_free(chr->label);
534 if (chr->logfd != -1) {
535 close(chr->logfd);
537 qemu_mutex_destroy(&chr->chr_write_lock);
540 static const TypeInfo char_type_info = {
541 .name = TYPE_CHARDEV,
542 .parent = TYPE_OBJECT,
543 .instance_size = sizeof(Chardev),
544 .instance_init = char_init,
545 .instance_finalize = char_finalize,
546 .abstract = true,
547 .class_size = sizeof(ChardevClass),
550 static int null_chr_write(Chardev *chr, const uint8_t *buf, int len)
552 return len;
555 static void null_chr_open(Chardev *chr,
556 ChardevBackend *backend,
557 bool *be_opened,
558 Error **errp)
560 *be_opened = false;
563 static const CharDriver null_driver = {
564 .kind = CHARDEV_BACKEND_KIND_NULL,
567 static void char_null_class_init(ObjectClass *oc, void *data)
569 ChardevClass *cc = CHARDEV_CLASS(oc);
571 cc->open = null_chr_open;
572 cc->chr_write = null_chr_write;
575 static const TypeInfo char_null_type_info = {
576 .name = TYPE_CHARDEV_NULL,
577 .parent = TYPE_CHARDEV,
578 .instance_size = sizeof(Chardev),
579 .class_init = char_null_class_init,
582 /* MUX driver for serial I/O splitting */
583 #define MAX_MUX 4
584 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
585 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
586 struct MuxChardev {
587 Chardev parent;
588 CharBackend *backends[MAX_MUX];
589 CharBackend chr;
590 int focus;
591 int mux_cnt;
592 int term_got_escape;
593 int max_size;
594 /* Intermediate input buffer allows to catch escape sequences even if the
595 currently active device is not accepting any input - but only until it
596 is full as well. */
597 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
598 int prod[MAX_MUX];
599 int cons[MAX_MUX];
600 int timestamps;
602 /* Protected by the Chardev chr_write_lock. */
603 int linestart;
604 int64_t timestamps_start;
607 #define MUX_CHARDEV(obj) OBJECT_CHECK(MuxChardev, (obj), TYPE_CHARDEV_MUX)
609 /* Called with chr_write_lock held. */
610 static int mux_chr_write(Chardev *chr, const uint8_t *buf, int len)
612 MuxChardev *d = MUX_CHARDEV(chr);
613 int ret;
614 if (!d->timestamps) {
615 ret = qemu_chr_fe_write(&d->chr, buf, len);
616 } else {
617 int i;
619 ret = 0;
620 for (i = 0; i < len; i++) {
621 if (d->linestart) {
622 char buf1[64];
623 int64_t ti;
624 int secs;
626 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
627 if (d->timestamps_start == -1)
628 d->timestamps_start = ti;
629 ti -= d->timestamps_start;
630 secs = ti / 1000;
631 snprintf(buf1, sizeof(buf1),
632 "[%02d:%02d:%02d.%03d] ",
633 secs / 3600,
634 (secs / 60) % 60,
635 secs % 60,
636 (int)(ti % 1000));
637 /* XXX this blocks entire thread. Rewrite to use
638 * qemu_chr_fe_write and background I/O callbacks */
639 qemu_chr_fe_write_all(&d->chr,
640 (uint8_t *)buf1, strlen(buf1));
641 d->linestart = 0;
643 ret += qemu_chr_fe_write(&d->chr, buf + i, 1);
644 if (buf[i] == '\n') {
645 d->linestart = 1;
649 return ret;
652 static const char * const mux_help[] = {
653 "% h print this help\n\r",
654 "% x exit emulator\n\r",
655 "% s save disk data back to file (if -snapshot)\n\r",
656 "% t toggle console timestamps\n\r",
657 "% b send break (magic sysrq)\n\r",
658 "% c switch between console and monitor\n\r",
659 "% % sends %\n\r",
660 NULL
663 int term_escape_char = 0x01; /* ctrl-a is used for escape */
664 static void mux_print_help(Chardev *chr)
666 int i, j;
667 char ebuf[15] = "Escape-Char";
668 char cbuf[50] = "\n\r";
670 if (term_escape_char > 0 && term_escape_char < 26) {
671 snprintf(cbuf, sizeof(cbuf), "\n\r");
672 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
673 } else {
674 snprintf(cbuf, sizeof(cbuf),
675 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
676 term_escape_char);
678 /* XXX this blocks entire thread. Rewrite to use
679 * qemu_chr_fe_write and background I/O callbacks */
680 qemu_chr_write_all(chr, (uint8_t *)cbuf, strlen(cbuf));
681 for (i = 0; mux_help[i] != NULL; i++) {
682 for (j=0; mux_help[i][j] != '\0'; j++) {
683 if (mux_help[i][j] == '%')
684 qemu_chr_write_all(chr, (uint8_t *)ebuf, strlen(ebuf));
685 else
686 qemu_chr_write_all(chr, (uint8_t *)&mux_help[i][j], 1);
691 static void mux_chr_send_event(MuxChardev *d, int mux_nr, int event)
693 CharBackend *be = d->backends[mux_nr];
695 if (be && be->chr_event) {
696 be->chr_event(be->opaque, event);
700 static int mux_proc_byte(Chardev *chr, MuxChardev *d, int ch)
702 if (d->term_got_escape) {
703 d->term_got_escape = 0;
704 if (ch == term_escape_char)
705 goto send_char;
706 switch(ch) {
707 case '?':
708 case 'h':
709 mux_print_help(chr);
710 break;
711 case 'x':
713 const char *term = "QEMU: Terminated\n\r";
714 qemu_chr_write_all(chr, (uint8_t *)term, strlen(term));
715 exit(0);
716 break;
718 case 's':
719 blk_commit_all();
720 break;
721 case 'b':
722 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
723 break;
724 case 'c':
725 assert(d->mux_cnt > 0); /* handler registered with first fe */
726 /* Switch to the next registered device */
727 mux_set_focus(chr, (d->focus + 1) % d->mux_cnt);
728 break;
729 case 't':
730 d->timestamps = !d->timestamps;
731 d->timestamps_start = -1;
732 d->linestart = 0;
733 break;
735 } else if (ch == term_escape_char) {
736 d->term_got_escape = 1;
737 } else {
738 send_char:
739 return 1;
741 return 0;
744 static void mux_chr_accept_input(Chardev *chr)
746 MuxChardev *d = MUX_CHARDEV(chr);
747 int m = d->focus;
748 CharBackend *be = d->backends[m];
750 while (be && d->prod[m] != d->cons[m] &&
751 be->chr_can_read && be->chr_can_read(be->opaque)) {
752 be->chr_read(be->opaque,
753 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
757 static int mux_chr_can_read(void *opaque)
759 MuxChardev *d = MUX_CHARDEV(opaque);
760 int m = d->focus;
761 CharBackend *be = d->backends[m];
763 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE) {
764 return 1;
767 if (be && be->chr_can_read) {
768 return be->chr_can_read(be->opaque);
771 return 0;
774 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
776 Chardev *chr = CHARDEV(opaque);
777 MuxChardev *d = MUX_CHARDEV(opaque);
778 int m = d->focus;
779 CharBackend *be = d->backends[m];
780 int i;
782 mux_chr_accept_input(opaque);
784 for (i = 0; i < size; i++)
785 if (mux_proc_byte(chr, d, buf[i])) {
786 if (d->prod[m] == d->cons[m] &&
787 be && be->chr_can_read &&
788 be->chr_can_read(be->opaque))
789 be->chr_read(be->opaque, &buf[i], 1);
790 else
791 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
795 static bool muxes_realized;
797 static void mux_chr_event(void *opaque, int event)
799 MuxChardev *d = MUX_CHARDEV(opaque);
800 int i;
802 if (!muxes_realized) {
803 return;
806 /* Send the event to all registered listeners */
807 for (i = 0; i < d->mux_cnt; i++)
808 mux_chr_send_event(d, i, event);
812 * Called after processing of default and command-line-specified
813 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
814 * to a mux chardev. This is done here to ensure that
815 * output/prompts/banners are only displayed for the FE that has
816 * focus when initial command-line processing/machine init is
817 * completed.
819 * After this point, any new FE attached to any new or existing
820 * mux will receive CHR_EVENT_OPENED notifications for the BE
821 * immediately.
823 static void muxes_realize_done(Notifier *notifier, void *unused)
825 Chardev *chr;
827 QTAILQ_FOREACH(chr, &chardevs, next) {
828 if (CHARDEV_IS_MUX(chr)) {
829 MuxChardev *d = MUX_CHARDEV(chr);
830 int i;
832 /* send OPENED to all already-attached FEs */
833 for (i = 0; i < d->mux_cnt; i++) {
834 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
836 /* mark mux as OPENED so any new FEs will immediately receive
837 * OPENED event
839 qemu_chr_be_generic_open(chr);
842 muxes_realized = true;
845 static Notifier muxes_realize_notify = {
846 .notify = muxes_realize_done,
849 static GSource *mux_chr_add_watch(Chardev *s, GIOCondition cond)
851 MuxChardev *d = MUX_CHARDEV(s);
852 Chardev *chr = qemu_chr_fe_get_driver(&d->chr);
853 ChardevClass *cc = CHARDEV_GET_CLASS(chr);
855 if (!cc->chr_add_watch) {
856 return NULL;
859 return cc->chr_add_watch(chr, cond);
862 static void mux_chr_free(struct Chardev *chr)
864 MuxChardev *d = MUX_CHARDEV(chr);
865 int i;
867 for (i = 0; i < d->mux_cnt; i++) {
868 CharBackend *be = d->backends[i];
869 if (be) {
870 be->chr = NULL;
873 qemu_chr_fe_deinit(&d->chr);
876 static void mux_chr_set_handlers(Chardev *chr, GMainContext *context)
878 MuxChardev *d = MUX_CHARDEV(chr);
880 /* Fix up the real driver with mux routines */
881 qemu_chr_fe_set_handlers(&d->chr,
882 mux_chr_can_read,
883 mux_chr_read,
884 mux_chr_event,
885 chr,
886 context, true);
889 static void mux_set_focus(Chardev *chr, int focus)
891 MuxChardev *d = MUX_CHARDEV(chr);
893 assert(focus >= 0);
894 assert(focus < d->mux_cnt);
896 if (d->focus != -1) {
897 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
900 d->focus = focus;
901 chr->be = d->backends[focus];
902 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
905 static void qemu_chr_open_mux(Chardev *chr,
906 ChardevBackend *backend,
907 bool *be_opened,
908 Error **errp)
910 ChardevMux *mux = backend->u.mux.data;
911 Chardev *drv;
912 MuxChardev *d = MUX_CHARDEV(chr);
914 drv = qemu_chr_find(mux->chardev);
915 if (drv == NULL) {
916 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
917 return;
920 d->focus = -1;
921 /* only default to opened state if we've realized the initial
922 * set of muxes
924 *be_opened = muxes_realized;
925 qemu_chr_fe_init(&d->chr, drv, errp);
928 Chardev *qemu_chr_fe_get_driver(CharBackend *be)
930 return be->chr;
933 bool qemu_chr_fe_init(CharBackend *b, Chardev *s, Error **errp)
935 int tag = 0;
937 if (CHARDEV_IS_MUX(s)) {
938 MuxChardev *d = MUX_CHARDEV(s);
940 if (d->mux_cnt >= MAX_MUX) {
941 goto unavailable;
944 d->backends[d->mux_cnt] = b;
945 tag = d->mux_cnt++;
946 } else if (s->be) {
947 goto unavailable;
948 } else {
949 s->be = b;
952 b->fe_open = false;
953 b->tag = tag;
954 b->chr = s;
955 return true;
957 unavailable:
958 error_setg(errp, QERR_DEVICE_IN_USE, s->label);
959 return false;
962 static bool qemu_chr_is_busy(Chardev *s)
964 if (CHARDEV_IS_MUX(s)) {
965 MuxChardev *d = MUX_CHARDEV(s);
966 return d->mux_cnt >= 0;
967 } else {
968 return s->be != NULL;
972 void qemu_chr_fe_deinit(CharBackend *b)
974 assert(b);
976 if (b->chr) {
977 qemu_chr_fe_set_handlers(b, NULL, NULL, NULL, NULL, NULL, true);
978 if (b->chr->be == b) {
979 b->chr->be = NULL;
981 if (CHARDEV_IS_MUX(b->chr)) {
982 MuxChardev *d = MUX_CHARDEV(b->chr);
983 d->backends[b->tag] = NULL;
985 b->chr = NULL;
989 void qemu_chr_fe_set_handlers(CharBackend *b,
990 IOCanReadHandler *fd_can_read,
991 IOReadHandler *fd_read,
992 IOEventHandler *fd_event,
993 void *opaque,
994 GMainContext *context,
995 bool set_open)
997 Chardev *s;
998 ChardevClass *cc;
999 int fe_open;
1001 s = b->chr;
1002 if (!s) {
1003 return;
1006 cc = CHARDEV_GET_CLASS(s);
1007 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
1008 fe_open = 0;
1009 remove_fd_in_watch(s);
1010 } else {
1011 fe_open = 1;
1013 b->chr_can_read = fd_can_read;
1014 b->chr_read = fd_read;
1015 b->chr_event = fd_event;
1016 b->opaque = opaque;
1017 if (cc->chr_update_read_handler) {
1018 cc->chr_update_read_handler(s, context);
1021 if (set_open) {
1022 qemu_chr_fe_set_open(b, fe_open);
1025 if (fe_open) {
1026 qemu_chr_fe_take_focus(b);
1027 /* We're connecting to an already opened device, so let's make sure we
1028 also get the open event */
1029 if (s->be_open) {
1030 qemu_chr_be_generic_open(s);
1034 if (CHARDEV_IS_MUX(s)) {
1035 mux_chr_set_handlers(s, context);
1039 void qemu_chr_fe_take_focus(CharBackend *b)
1041 if (!b->chr) {
1042 return;
1045 if (CHARDEV_IS_MUX(b->chr)) {
1046 mux_set_focus(b->chr, b->tag);
1050 typedef struct IOWatchPoll
1052 GSource parent;
1054 QIOChannel *ioc;
1055 GSource *src;
1057 IOCanReadHandler *fd_can_read;
1058 GSourceFunc fd_read;
1059 void *opaque;
1060 GMainContext *context;
1061 } IOWatchPoll;
1063 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
1065 return container_of(source, IOWatchPoll, parent);
1068 static gboolean io_watch_poll_prepare(GSource *source,
1069 gint *timeout_)
1071 IOWatchPoll *iwp = io_watch_poll_from_source(source);
1072 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
1073 bool was_active = iwp->src != NULL;
1074 if (was_active == now_active) {
1075 return FALSE;
1078 if (now_active) {
1079 iwp->src = qio_channel_create_watch(
1080 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
1081 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
1082 g_source_attach(iwp->src, iwp->context);
1083 } else {
1084 g_source_destroy(iwp->src);
1085 g_source_unref(iwp->src);
1086 iwp->src = NULL;
1088 return FALSE;
1091 static gboolean io_watch_poll_check(GSource *source)
1093 return FALSE;
1096 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
1097 gpointer user_data)
1099 abort();
1102 static void io_watch_poll_finalize(GSource *source)
1104 /* Due to a glib bug, removing the last reference to a source
1105 * inside a finalize callback causes recursive locking (and a
1106 * deadlock). This is not a problem inside other callbacks,
1107 * including dispatch callbacks, so we call io_remove_watch_poll
1108 * to remove this source. At this point, iwp->src must
1109 * be NULL, or we would leak it.
1111 * This would be solved much more elegantly by child sources,
1112 * but we support older glib versions that do not have them.
1114 IOWatchPoll *iwp = io_watch_poll_from_source(source);
1115 assert(iwp->src == NULL);
1118 static GSourceFuncs io_watch_poll_funcs = {
1119 .prepare = io_watch_poll_prepare,
1120 .check = io_watch_poll_check,
1121 .dispatch = io_watch_poll_dispatch,
1122 .finalize = io_watch_poll_finalize,
1125 /* Can only be used for read */
1126 static guint io_add_watch_poll(Chardev *chr,
1127 QIOChannel *ioc,
1128 IOCanReadHandler *fd_can_read,
1129 QIOChannelFunc fd_read,
1130 gpointer user_data,
1131 GMainContext *context)
1133 IOWatchPoll *iwp;
1134 int tag;
1135 char *name;
1137 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs,
1138 sizeof(IOWatchPoll));
1139 iwp->fd_can_read = fd_can_read;
1140 iwp->opaque = user_data;
1141 iwp->ioc = ioc;
1142 iwp->fd_read = (GSourceFunc) fd_read;
1143 iwp->src = NULL;
1144 iwp->context = context;
1146 name = g_strdup_printf("chardev-iowatch-%s", chr->label);
1147 g_source_set_name((GSource *)iwp, name);
1148 g_free(name);
1150 tag = g_source_attach(&iwp->parent, context);
1151 g_source_unref(&iwp->parent);
1152 return tag;
1155 static void io_remove_watch_poll(guint tag)
1157 GSource *source;
1158 IOWatchPoll *iwp;
1160 g_return_if_fail (tag > 0);
1162 source = g_main_context_find_source_by_id(NULL, tag);
1163 g_return_if_fail (source != NULL);
1165 iwp = io_watch_poll_from_source(source);
1166 if (iwp->src) {
1167 g_source_destroy(iwp->src);
1168 g_source_unref(iwp->src);
1169 iwp->src = NULL;
1171 g_source_destroy(&iwp->parent);
1174 static void remove_fd_in_watch(Chardev *chr)
1176 if (chr->fd_in_tag) {
1177 io_remove_watch_poll(chr->fd_in_tag);
1178 chr->fd_in_tag = 0;
1183 static int io_channel_send_full(QIOChannel *ioc,
1184 const void *buf, size_t len,
1185 int *fds, size_t nfds)
1187 size_t offset = 0;
1189 while (offset < len) {
1190 ssize_t ret = 0;
1191 struct iovec iov = { .iov_base = (char *)buf + offset,
1192 .iov_len = len - offset };
1194 ret = qio_channel_writev_full(
1195 ioc, &iov, 1,
1196 fds, nfds, NULL);
1197 if (ret == QIO_CHANNEL_ERR_BLOCK) {
1198 if (offset) {
1199 return offset;
1202 errno = EAGAIN;
1203 return -1;
1204 } else if (ret < 0) {
1205 errno = EINVAL;
1206 return -1;
1209 offset += ret;
1212 return offset;
1216 #ifndef _WIN32
1217 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
1219 return io_channel_send_full(ioc, buf, len, NULL, 0);
1222 typedef struct FDChardev {
1223 Chardev parent;
1224 Chardev *chr;
1225 QIOChannel *ioc_in, *ioc_out;
1226 int max_size;
1227 } FDChardev;
1229 #define TYPE_CHARDEV_FD "chardev-fd"
1230 #define FD_CHARDEV(obj) OBJECT_CHECK(FDChardev, (obj), TYPE_CHARDEV_FD)
1232 /* Called with chr_write_lock held. */
1233 static int fd_chr_write(Chardev *chr, const uint8_t *buf, int len)
1235 FDChardev *s = FD_CHARDEV(chr);
1237 return io_channel_send(s->ioc_out, buf, len);
1240 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1242 Chardev *chr = CHARDEV(opaque);
1243 FDChardev *s = FD_CHARDEV(opaque);
1244 int len;
1245 uint8_t buf[READ_BUF_LEN];
1246 ssize_t ret;
1248 len = sizeof(buf);
1249 if (len > s->max_size) {
1250 len = s->max_size;
1252 if (len == 0) {
1253 return TRUE;
1256 ret = qio_channel_read(
1257 chan, (gchar *)buf, len, NULL);
1258 if (ret == 0) {
1259 remove_fd_in_watch(chr);
1260 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1261 return FALSE;
1263 if (ret > 0) {
1264 qemu_chr_be_write(chr, buf, ret);
1267 return TRUE;
1270 static int fd_chr_read_poll(void *opaque)
1272 Chardev *chr = CHARDEV(opaque);
1273 FDChardev *s = FD_CHARDEV(opaque);
1275 s->max_size = qemu_chr_be_can_write(chr);
1276 return s->max_size;
1279 static GSource *fd_chr_add_watch(Chardev *chr, GIOCondition cond)
1281 FDChardev *s = FD_CHARDEV(chr);
1282 return qio_channel_create_watch(s->ioc_out, cond);
1285 static void fd_chr_update_read_handler(Chardev *chr,
1286 GMainContext *context)
1288 FDChardev *s = FD_CHARDEV(chr);
1290 remove_fd_in_watch(chr);
1291 if (s->ioc_in) {
1292 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc_in,
1293 fd_chr_read_poll,
1294 fd_chr_read, chr,
1295 context);
1299 static void fd_chr_free(struct Chardev *chr)
1301 FDChardev *s = FD_CHARDEV(chr);
1303 remove_fd_in_watch(chr);
1304 if (s->ioc_in) {
1305 object_unref(OBJECT(s->ioc_in));
1307 if (s->ioc_out) {
1308 object_unref(OBJECT(s->ioc_out));
1311 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1314 /* open a character device to a unix fd */
1315 static void qemu_chr_open_fd(Chardev *chr,
1316 int fd_in, int fd_out)
1318 FDChardev *s = FD_CHARDEV(chr);
1319 char *name;
1321 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1322 name = g_strdup_printf("chardev-file-in-%s", chr->label);
1323 qio_channel_set_name(QIO_CHANNEL(s->ioc_in), name);
1324 g_free(name);
1325 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1326 name = g_strdup_printf("chardev-file-out-%s", chr->label);
1327 qio_channel_set_name(QIO_CHANNEL(s->ioc_out), name);
1328 g_free(name);
1329 qemu_set_nonblock(fd_out);
1330 s->chr = chr;
1333 static void char_fd_class_init(ObjectClass *oc, void *data)
1335 ChardevClass *cc = CHARDEV_CLASS(oc);
1337 cc->chr_add_watch = fd_chr_add_watch;
1338 cc->chr_write = fd_chr_write;
1339 cc->chr_update_read_handler = fd_chr_update_read_handler;
1340 cc->chr_free = fd_chr_free;
1343 static const TypeInfo char_fd_type_info = {
1344 .name = TYPE_CHARDEV_FD,
1345 .parent = TYPE_CHARDEV,
1346 .instance_size = sizeof(FDChardev),
1347 .class_init = char_fd_class_init,
1348 .abstract = true,
1351 static void qemu_chr_open_pipe(Chardev *chr,
1352 ChardevBackend *backend,
1353 bool *be_opened,
1354 Error **errp)
1356 ChardevHostdev *opts = backend->u.pipe.data;
1357 int fd_in, fd_out;
1358 char *filename_in;
1359 char *filename_out;
1360 const char *filename = opts->device;
1362 filename_in = g_strdup_printf("%s.in", filename);
1363 filename_out = g_strdup_printf("%s.out", filename);
1364 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1365 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1366 g_free(filename_in);
1367 g_free(filename_out);
1368 if (fd_in < 0 || fd_out < 0) {
1369 if (fd_in >= 0)
1370 close(fd_in);
1371 if (fd_out >= 0)
1372 close(fd_out);
1373 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1374 if (fd_in < 0) {
1375 error_setg_file_open(errp, errno, filename);
1376 return;
1379 qemu_chr_open_fd(chr, fd_in, fd_out);
1382 /* init terminal so that we can grab keys */
1383 static struct termios oldtty;
1384 static int old_fd0_flags;
1385 static bool stdio_in_use;
1386 static bool stdio_allow_signal;
1387 static bool stdio_echo_state;
1389 static void qemu_chr_set_echo_stdio(Chardev *chr, bool echo);
1391 static void term_exit(void)
1393 tcsetattr (0, TCSANOW, &oldtty);
1394 fcntl(0, F_SETFL, old_fd0_flags);
1397 static void term_stdio_handler(int sig)
1399 /* restore echo after resume from suspend. */
1400 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1403 static void qemu_chr_set_echo_stdio(Chardev *chr, bool echo)
1405 struct termios tty;
1407 stdio_echo_state = echo;
1408 tty = oldtty;
1409 if (!echo) {
1410 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1411 |INLCR|IGNCR|ICRNL|IXON);
1412 tty.c_oflag |= OPOST;
1413 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1414 tty.c_cflag &= ~(CSIZE|PARENB);
1415 tty.c_cflag |= CS8;
1416 tty.c_cc[VMIN] = 1;
1417 tty.c_cc[VTIME] = 0;
1419 if (!stdio_allow_signal)
1420 tty.c_lflag &= ~ISIG;
1422 tcsetattr (0, TCSANOW, &tty);
1425 static void qemu_chr_free_stdio(struct Chardev *chr)
1427 term_exit();
1428 fd_chr_free(chr);
1431 static void qemu_chr_open_stdio(Chardev *chr,
1432 ChardevBackend *backend,
1433 bool *be_opened,
1434 Error **errp)
1436 ChardevStdio *opts = backend->u.stdio.data;
1437 struct sigaction act;
1439 if (is_daemonized()) {
1440 error_setg(errp, "cannot use stdio with -daemonize");
1441 return;
1444 if (stdio_in_use) {
1445 error_setg(errp, "cannot use stdio by multiple character devices");
1446 return;
1449 stdio_in_use = true;
1450 old_fd0_flags = fcntl(0, F_GETFL);
1451 tcgetattr(0, &oldtty);
1452 qemu_set_nonblock(0);
1453 atexit(term_exit);
1455 memset(&act, 0, sizeof(act));
1456 act.sa_handler = term_stdio_handler;
1457 sigaction(SIGCONT, &act, NULL);
1459 qemu_chr_open_fd(chr, 0, 1);
1461 if (opts->has_signal) {
1462 stdio_allow_signal = opts->signal;
1464 qemu_chr_set_echo_stdio(chr, false);
1467 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1468 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1469 || defined(__GLIBC__)
1471 #define HAVE_CHARDEV_SERIAL 1
1472 #define HAVE_CHARDEV_PTY 1
1474 typedef struct {
1475 Chardev parent;
1476 QIOChannel *ioc;
1477 int read_bytes;
1479 /* Protected by the Chardev chr_write_lock. */
1480 int connected;
1481 guint timer_tag;
1482 guint open_tag;
1483 } PtyChardev;
1485 #define PTY_CHARDEV(obj) OBJECT_CHECK(PtyChardev, (obj), TYPE_CHARDEV_PTY)
1487 static void pty_chr_update_read_handler_locked(Chardev *chr);
1488 static void pty_chr_state(Chardev *chr, int connected);
1490 static gboolean pty_chr_timer(gpointer opaque)
1492 struct Chardev *chr = CHARDEV(opaque);
1493 PtyChardev *s = PTY_CHARDEV(opaque);
1495 qemu_mutex_lock(&chr->chr_write_lock);
1496 s->timer_tag = 0;
1497 s->open_tag = 0;
1498 if (!s->connected) {
1499 /* Next poll ... */
1500 pty_chr_update_read_handler_locked(chr);
1502 qemu_mutex_unlock(&chr->chr_write_lock);
1503 return FALSE;
1506 /* Called with chr_write_lock held. */
1507 static void pty_chr_rearm_timer(Chardev *chr, int ms)
1509 PtyChardev *s = PTY_CHARDEV(chr);
1510 char *name;
1512 if (s->timer_tag) {
1513 g_source_remove(s->timer_tag);
1514 s->timer_tag = 0;
1517 if (ms == 1000) {
1518 name = g_strdup_printf("pty-timer-secs-%s", chr->label);
1519 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1520 } else {
1521 name = g_strdup_printf("pty-timer-ms-%s", chr->label);
1522 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1524 g_source_set_name_by_id(s->timer_tag, name);
1525 g_free(name);
1528 /* Called with chr_write_lock held. */
1529 static void pty_chr_update_read_handler_locked(Chardev *chr)
1531 PtyChardev *s = PTY_CHARDEV(chr);
1532 GPollFD pfd;
1533 int rc;
1534 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1536 pfd.fd = fioc->fd;
1537 pfd.events = G_IO_OUT;
1538 pfd.revents = 0;
1539 do {
1540 rc = g_poll(&pfd, 1, 0);
1541 } while (rc == -1 && errno == EINTR);
1542 assert(rc >= 0);
1544 if (pfd.revents & G_IO_HUP) {
1545 pty_chr_state(chr, 0);
1546 } else {
1547 pty_chr_state(chr, 1);
1551 static void pty_chr_update_read_handler(Chardev *chr,
1552 GMainContext *context)
1554 qemu_mutex_lock(&chr->chr_write_lock);
1555 pty_chr_update_read_handler_locked(chr);
1556 qemu_mutex_unlock(&chr->chr_write_lock);
1559 /* Called with chr_write_lock held. */
1560 static int char_pty_chr_write(Chardev *chr, const uint8_t *buf, int len)
1562 PtyChardev *s = PTY_CHARDEV(chr);
1564 if (!s->connected) {
1565 /* guest sends data, check for (re-)connect */
1566 pty_chr_update_read_handler_locked(chr);
1567 if (!s->connected) {
1568 return 0;
1571 return io_channel_send(s->ioc, buf, len);
1574 static GSource *pty_chr_add_watch(Chardev *chr, GIOCondition cond)
1576 PtyChardev *s = PTY_CHARDEV(chr);
1577 if (!s->connected) {
1578 return NULL;
1580 return qio_channel_create_watch(s->ioc, cond);
1583 static int pty_chr_read_poll(void *opaque)
1585 Chardev *chr = CHARDEV(opaque);
1586 PtyChardev *s = PTY_CHARDEV(opaque);
1588 s->read_bytes = qemu_chr_be_can_write(chr);
1589 return s->read_bytes;
1592 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1594 Chardev *chr = CHARDEV(opaque);
1595 PtyChardev *s = PTY_CHARDEV(opaque);
1596 gsize len;
1597 uint8_t buf[READ_BUF_LEN];
1598 ssize_t ret;
1600 len = sizeof(buf);
1601 if (len > s->read_bytes)
1602 len = s->read_bytes;
1603 if (len == 0) {
1604 return TRUE;
1606 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1607 if (ret <= 0) {
1608 pty_chr_state(chr, 0);
1609 return FALSE;
1610 } else {
1611 pty_chr_state(chr, 1);
1612 qemu_chr_be_write(chr, buf, ret);
1614 return TRUE;
1617 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1619 Chardev *chr = CHARDEV(opaque);
1620 PtyChardev *s = PTY_CHARDEV(opaque);
1622 s->open_tag = 0;
1623 qemu_chr_be_generic_open(chr);
1624 return FALSE;
1627 /* Called with chr_write_lock held. */
1628 static void pty_chr_state(Chardev *chr, int connected)
1630 PtyChardev *s = PTY_CHARDEV(chr);
1632 if (!connected) {
1633 if (s->open_tag) {
1634 g_source_remove(s->open_tag);
1635 s->open_tag = 0;
1637 remove_fd_in_watch(chr);
1638 s->connected = 0;
1639 /* (re-)connect poll interval for idle guests: once per second.
1640 * We check more frequently in case the guests sends data to
1641 * the virtual device linked to our pty. */
1642 pty_chr_rearm_timer(chr, 1000);
1643 } else {
1644 if (s->timer_tag) {
1645 g_source_remove(s->timer_tag);
1646 s->timer_tag = 0;
1648 if (!s->connected) {
1649 g_assert(s->open_tag == 0);
1650 s->connected = 1;
1651 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1653 if (!chr->fd_in_tag) {
1654 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
1655 pty_chr_read_poll,
1656 pty_chr_read,
1657 chr, NULL);
1662 static void pty_chr_free(struct Chardev *chr)
1664 PtyChardev *s = PTY_CHARDEV(chr);
1666 qemu_mutex_lock(&chr->chr_write_lock);
1667 pty_chr_state(chr, 0);
1668 object_unref(OBJECT(s->ioc));
1669 if (s->timer_tag) {
1670 g_source_remove(s->timer_tag);
1671 s->timer_tag = 0;
1673 qemu_mutex_unlock(&chr->chr_write_lock);
1674 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1677 static void char_pty_open(Chardev *chr,
1678 ChardevBackend *backend,
1679 bool *be_opened,
1680 Error **errp)
1682 PtyChardev *s;
1683 int master_fd, slave_fd;
1684 char pty_name[PATH_MAX];
1685 char *name;
1687 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1688 if (master_fd < 0) {
1689 error_setg_errno(errp, errno, "Failed to create PTY");
1690 return;
1693 close(slave_fd);
1694 qemu_set_nonblock(master_fd);
1696 chr->filename = g_strdup_printf("pty:%s", pty_name);
1697 error_report("char device redirected to %s (label %s)",
1698 pty_name, chr->label);
1700 s = PTY_CHARDEV(chr);
1701 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1702 name = g_strdup_printf("chardev-pty-%s", chr->label);
1703 qio_channel_set_name(QIO_CHANNEL(s->ioc), name);
1704 g_free(name);
1705 s->timer_tag = 0;
1706 *be_opened = false;
1709 static const CharDriver pty_driver = {
1710 .kind = CHARDEV_BACKEND_KIND_PTY,
1713 static void char_pty_class_init(ObjectClass *oc, void *data)
1715 ChardevClass *cc = CHARDEV_CLASS(oc);
1717 cc->open = char_pty_open;
1718 cc->chr_write = char_pty_chr_write;
1719 cc->chr_update_read_handler = pty_chr_update_read_handler;
1720 cc->chr_add_watch = pty_chr_add_watch;
1721 cc->chr_free = pty_chr_free;
1724 static const TypeInfo char_pty_type_info = {
1725 .name = TYPE_CHARDEV_PTY,
1726 .parent = TYPE_CHARDEV,
1727 .instance_size = sizeof(PtyChardev),
1728 .class_init = char_pty_class_init,
1731 static void tty_serial_init(int fd, int speed,
1732 int parity, int data_bits, int stop_bits)
1734 struct termios tty;
1735 speed_t spd;
1737 #if 0
1738 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1739 speed, parity, data_bits, stop_bits);
1740 #endif
1741 tcgetattr (fd, &tty);
1743 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1744 speed = speed * 10 / 11;
1745 do {
1746 check_speed(50);
1747 check_speed(75);
1748 check_speed(110);
1749 check_speed(134);
1750 check_speed(150);
1751 check_speed(200);
1752 check_speed(300);
1753 check_speed(600);
1754 check_speed(1200);
1755 check_speed(1800);
1756 check_speed(2400);
1757 check_speed(4800);
1758 check_speed(9600);
1759 check_speed(19200);
1760 check_speed(38400);
1761 /* Non-Posix values follow. They may be unsupported on some systems. */
1762 check_speed(57600);
1763 check_speed(115200);
1764 #ifdef B230400
1765 check_speed(230400);
1766 #endif
1767 #ifdef B460800
1768 check_speed(460800);
1769 #endif
1770 #ifdef B500000
1771 check_speed(500000);
1772 #endif
1773 #ifdef B576000
1774 check_speed(576000);
1775 #endif
1776 #ifdef B921600
1777 check_speed(921600);
1778 #endif
1779 #ifdef B1000000
1780 check_speed(1000000);
1781 #endif
1782 #ifdef B1152000
1783 check_speed(1152000);
1784 #endif
1785 #ifdef B1500000
1786 check_speed(1500000);
1787 #endif
1788 #ifdef B2000000
1789 check_speed(2000000);
1790 #endif
1791 #ifdef B2500000
1792 check_speed(2500000);
1793 #endif
1794 #ifdef B3000000
1795 check_speed(3000000);
1796 #endif
1797 #ifdef B3500000
1798 check_speed(3500000);
1799 #endif
1800 #ifdef B4000000
1801 check_speed(4000000);
1802 #endif
1803 spd = B115200;
1804 } while (0);
1806 cfsetispeed(&tty, spd);
1807 cfsetospeed(&tty, spd);
1809 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1810 |INLCR|IGNCR|ICRNL|IXON);
1811 tty.c_oflag |= OPOST;
1812 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1813 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1814 switch(data_bits) {
1815 default:
1816 case 8:
1817 tty.c_cflag |= CS8;
1818 break;
1819 case 7:
1820 tty.c_cflag |= CS7;
1821 break;
1822 case 6:
1823 tty.c_cflag |= CS6;
1824 break;
1825 case 5:
1826 tty.c_cflag |= CS5;
1827 break;
1829 switch(parity) {
1830 default:
1831 case 'N':
1832 break;
1833 case 'E':
1834 tty.c_cflag |= PARENB;
1835 break;
1836 case 'O':
1837 tty.c_cflag |= PARENB | PARODD;
1838 break;
1840 if (stop_bits == 2)
1841 tty.c_cflag |= CSTOPB;
1843 tcsetattr (fd, TCSANOW, &tty);
1846 static int tty_serial_ioctl(Chardev *chr, int cmd, void *arg)
1848 FDChardev *s = FD_CHARDEV(chr);
1849 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1851 switch(cmd) {
1852 case CHR_IOCTL_SERIAL_SET_PARAMS:
1854 QEMUSerialSetParams *ssp = arg;
1855 tty_serial_init(fioc->fd,
1856 ssp->speed, ssp->parity,
1857 ssp->data_bits, ssp->stop_bits);
1859 break;
1860 case CHR_IOCTL_SERIAL_SET_BREAK:
1862 int enable = *(int *)arg;
1863 if (enable) {
1864 tcsendbreak(fioc->fd, 1);
1867 break;
1868 case CHR_IOCTL_SERIAL_GET_TIOCM:
1870 int sarg = 0;
1871 int *targ = (int *)arg;
1872 ioctl(fioc->fd, TIOCMGET, &sarg);
1873 *targ = 0;
1874 if (sarg & TIOCM_CTS)
1875 *targ |= CHR_TIOCM_CTS;
1876 if (sarg & TIOCM_CAR)
1877 *targ |= CHR_TIOCM_CAR;
1878 if (sarg & TIOCM_DSR)
1879 *targ |= CHR_TIOCM_DSR;
1880 if (sarg & TIOCM_RI)
1881 *targ |= CHR_TIOCM_RI;
1882 if (sarg & TIOCM_DTR)
1883 *targ |= CHR_TIOCM_DTR;
1884 if (sarg & TIOCM_RTS)
1885 *targ |= CHR_TIOCM_RTS;
1887 break;
1888 case CHR_IOCTL_SERIAL_SET_TIOCM:
1890 int sarg = *(int *)arg;
1891 int targ = 0;
1892 ioctl(fioc->fd, TIOCMGET, &targ);
1893 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1894 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1895 if (sarg & CHR_TIOCM_CTS)
1896 targ |= TIOCM_CTS;
1897 if (sarg & CHR_TIOCM_CAR)
1898 targ |= TIOCM_CAR;
1899 if (sarg & CHR_TIOCM_DSR)
1900 targ |= TIOCM_DSR;
1901 if (sarg & CHR_TIOCM_RI)
1902 targ |= TIOCM_RI;
1903 if (sarg & CHR_TIOCM_DTR)
1904 targ |= TIOCM_DTR;
1905 if (sarg & CHR_TIOCM_RTS)
1906 targ |= TIOCM_RTS;
1907 ioctl(fioc->fd, TIOCMSET, &targ);
1909 break;
1910 default:
1911 return -ENOTSUP;
1913 return 0;
1916 static void qemu_chr_free_tty(Chardev *chr)
1918 fd_chr_free(chr);
1920 #endif /* __linux__ || __sun__ */
1922 #if defined(__linux__)
1924 #define HAVE_CHARDEV_PARPORT 1
1926 typedef struct {
1927 Chardev parent;
1928 int fd;
1929 int mode;
1930 } ParallelChardev;
1932 #define PARALLEL_CHARDEV(obj) \
1933 OBJECT_CHECK(ParallelChardev, (obj), TYPE_CHARDEV_PARALLEL)
1935 static int pp_hw_mode(ParallelChardev *s, uint16_t mode)
1937 if (s->mode != mode) {
1938 int m = mode;
1939 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1940 return 0;
1941 s->mode = mode;
1943 return 1;
1946 static int pp_ioctl(Chardev *chr, int cmd, void *arg)
1948 ParallelChardev *drv = PARALLEL_CHARDEV(chr);
1949 int fd = drv->fd;
1950 uint8_t b;
1952 switch(cmd) {
1953 case CHR_IOCTL_PP_READ_DATA:
1954 if (ioctl(fd, PPRDATA, &b) < 0)
1955 return -ENOTSUP;
1956 *(uint8_t *)arg = b;
1957 break;
1958 case CHR_IOCTL_PP_WRITE_DATA:
1959 b = *(uint8_t *)arg;
1960 if (ioctl(fd, PPWDATA, &b) < 0)
1961 return -ENOTSUP;
1962 break;
1963 case CHR_IOCTL_PP_READ_CONTROL:
1964 if (ioctl(fd, PPRCONTROL, &b) < 0)
1965 return -ENOTSUP;
1966 /* Linux gives only the lowest bits, and no way to know data
1967 direction! For better compatibility set the fixed upper
1968 bits. */
1969 *(uint8_t *)arg = b | 0xc0;
1970 break;
1971 case CHR_IOCTL_PP_WRITE_CONTROL:
1972 b = *(uint8_t *)arg;
1973 if (ioctl(fd, PPWCONTROL, &b) < 0)
1974 return -ENOTSUP;
1975 break;
1976 case CHR_IOCTL_PP_READ_STATUS:
1977 if (ioctl(fd, PPRSTATUS, &b) < 0)
1978 return -ENOTSUP;
1979 *(uint8_t *)arg = b;
1980 break;
1981 case CHR_IOCTL_PP_DATA_DIR:
1982 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1983 return -ENOTSUP;
1984 break;
1985 case CHR_IOCTL_PP_EPP_READ_ADDR:
1986 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1987 struct ParallelIOArg *parg = arg;
1988 int n = read(fd, parg->buffer, parg->count);
1989 if (n != parg->count) {
1990 return -EIO;
1993 break;
1994 case CHR_IOCTL_PP_EPP_READ:
1995 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1996 struct ParallelIOArg *parg = arg;
1997 int n = read(fd, parg->buffer, parg->count);
1998 if (n != parg->count) {
1999 return -EIO;
2002 break;
2003 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2004 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2005 struct ParallelIOArg *parg = arg;
2006 int n = write(fd, parg->buffer, parg->count);
2007 if (n != parg->count) {
2008 return -EIO;
2011 break;
2012 case CHR_IOCTL_PP_EPP_WRITE:
2013 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2014 struct ParallelIOArg *parg = arg;
2015 int n = write(fd, parg->buffer, parg->count);
2016 if (n != parg->count) {
2017 return -EIO;
2020 break;
2021 default:
2022 return -ENOTSUP;
2024 return 0;
2027 static void pp_free(Chardev *chr)
2029 ParallelChardev *drv = PARALLEL_CHARDEV(chr);
2030 int fd = drv->fd;
2032 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2033 ioctl(fd, PPRELEASE);
2034 close(fd);
2035 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2038 static void qemu_chr_open_pp_fd(Chardev *chr,
2039 int fd,
2040 bool *be_opened,
2041 Error **errp)
2043 ParallelChardev *drv = PARALLEL_CHARDEV(chr);
2045 if (ioctl(fd, PPCLAIM) < 0) {
2046 error_setg_errno(errp, errno, "not a parallel port");
2047 close(fd);
2048 return;
2051 drv->fd = fd;
2052 drv->mode = IEEE1284_MODE_COMPAT;
2054 #endif /* __linux__ */
2056 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
2058 #define HAVE_CHARDEV_PARPORT 1
2060 typedef struct {
2061 Chardev parent;
2062 int fd;
2063 } ParallelChardev;
2065 #define PARALLEL_CHARDEV(obj) \
2066 OBJECT_CHECK(ParallelChardev, (obj), TYPE_CHARDEV_PARALLEL)
2068 static int pp_ioctl(Chardev *chr, int cmd, void *arg)
2070 ParallelChardev *drv = PARALLEL_CHARDEV(chr);
2071 uint8_t b;
2073 switch (cmd) {
2074 case CHR_IOCTL_PP_READ_DATA:
2075 if (ioctl(drv->fd, PPIGDATA, &b) < 0) {
2076 return -ENOTSUP;
2078 *(uint8_t *)arg = b;
2079 break;
2080 case CHR_IOCTL_PP_WRITE_DATA:
2081 b = *(uint8_t *)arg;
2082 if (ioctl(drv->fd, PPISDATA, &b) < 0) {
2083 return -ENOTSUP;
2085 break;
2086 case CHR_IOCTL_PP_READ_CONTROL:
2087 if (ioctl(drv->fd, PPIGCTRL, &b) < 0) {
2088 return -ENOTSUP;
2090 *(uint8_t *)arg = b;
2091 break;
2092 case CHR_IOCTL_PP_WRITE_CONTROL:
2093 b = *(uint8_t *)arg;
2094 if (ioctl(drv->fd, PPISCTRL, &b) < 0) {
2095 return -ENOTSUP;
2097 break;
2098 case CHR_IOCTL_PP_READ_STATUS:
2099 if (ioctl(drv->fd, PPIGSTATUS, &b) < 0) {
2100 return -ENOTSUP;
2102 *(uint8_t *)arg = b;
2103 break;
2104 default:
2105 return -ENOTSUP;
2107 return 0;
2110 static void qemu_chr_open_pp_fd(Chardev *chr,
2111 int fd,
2112 bool *be_opened,
2113 Error **errp)
2115 ParallelChardev *drv = PARALLEL_CHARDEV(chr);
2116 drv->fd = fd;
2117 *be_opened = false;
2119 #endif
2121 #else /* _WIN32 */
2123 #define HAVE_CHARDEV_SERIAL 1
2125 typedef struct {
2126 Chardev parent;
2127 int max_size;
2128 HANDLE hcom, hrecv, hsend;
2129 OVERLAPPED orecv;
2130 BOOL fpipe;
2131 DWORD len;
2133 /* Protected by the Chardev chr_write_lock. */
2134 OVERLAPPED osend;
2135 } WinChardev;
2137 #define TYPE_CHARDEV_WIN "chardev-win"
2138 #define WIN_CHARDEV(obj) OBJECT_CHECK(WinChardev, (obj), TYPE_CHARDEV_WIN)
2140 typedef struct {
2141 Chardev parent;
2142 HANDLE hStdIn;
2143 HANDLE hInputReadyEvent;
2144 HANDLE hInputDoneEvent;
2145 HANDLE hInputThread;
2146 uint8_t win_stdio_buf;
2147 } WinStdioChardev;
2149 #define TYPE_CHARDEV_WIN_STDIO "chardev-win-stdio"
2150 #define WIN_STDIO_CHARDEV(obj) \
2151 OBJECT_CHECK(WinStdioChardev, (obj), TYPE_CHARDEV_WIN_STDIO)
2153 #define NSENDBUF 2048
2154 #define NRECVBUF 2048
2155 #define MAXCONNECT 1
2156 #define NTIMEOUT 5000
2158 static int win_chr_poll(void *opaque);
2159 static int win_chr_pipe_poll(void *opaque);
2161 static void win_chr_free(Chardev *chr)
2163 WinChardev *s = WIN_CHARDEV(chr);
2165 if (s->hsend) {
2166 CloseHandle(s->hsend);
2167 s->hsend = NULL;
2169 if (s->hrecv) {
2170 CloseHandle(s->hrecv);
2171 s->hrecv = NULL;
2173 if (s->hcom) {
2174 CloseHandle(s->hcom);
2175 s->hcom = NULL;
2177 if (s->fpipe)
2178 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2179 else
2180 qemu_del_polling_cb(win_chr_poll, chr);
2182 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2185 static int win_chr_init(Chardev *chr, const char *filename, Error **errp)
2187 WinChardev *s = WIN_CHARDEV(chr);
2188 COMMCONFIG comcfg;
2189 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2190 COMSTAT comstat;
2191 DWORD size;
2192 DWORD err;
2194 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2195 if (!s->hsend) {
2196 error_setg(errp, "Failed CreateEvent");
2197 goto fail;
2199 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2200 if (!s->hrecv) {
2201 error_setg(errp, "Failed CreateEvent");
2202 goto fail;
2205 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2206 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2207 if (s->hcom == INVALID_HANDLE_VALUE) {
2208 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
2209 s->hcom = NULL;
2210 goto fail;
2213 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2214 error_setg(errp, "Failed SetupComm");
2215 goto fail;
2218 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2219 size = sizeof(COMMCONFIG);
2220 GetDefaultCommConfig(filename, &comcfg, &size);
2221 comcfg.dcb.DCBlength = sizeof(DCB);
2222 CommConfigDialog(filename, NULL, &comcfg);
2224 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2225 error_setg(errp, "Failed SetCommState");
2226 goto fail;
2229 if (!SetCommMask(s->hcom, EV_ERR)) {
2230 error_setg(errp, "Failed SetCommMask");
2231 goto fail;
2234 cto.ReadIntervalTimeout = MAXDWORD;
2235 if (!SetCommTimeouts(s->hcom, &cto)) {
2236 error_setg(errp, "Failed SetCommTimeouts");
2237 goto fail;
2240 if (!ClearCommError(s->hcom, &err, &comstat)) {
2241 error_setg(errp, "Failed ClearCommError");
2242 goto fail;
2244 qemu_add_polling_cb(win_chr_poll, chr);
2245 return 0;
2247 fail:
2248 win_chr_free(chr);
2249 return -1;
2252 /* Called with chr_write_lock held. */
2253 static int win_chr_write(Chardev *chr, const uint8_t *buf, int len1)
2255 WinChardev *s = WIN_CHARDEV(chr);
2256 DWORD len, ret, size, err;
2258 len = len1;
2259 ZeroMemory(&s->osend, sizeof(s->osend));
2260 s->osend.hEvent = s->hsend;
2261 while (len > 0) {
2262 if (s->hsend)
2263 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2264 else
2265 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2266 if (!ret) {
2267 err = GetLastError();
2268 if (err == ERROR_IO_PENDING) {
2269 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2270 if (ret) {
2271 buf += size;
2272 len -= size;
2273 } else {
2274 break;
2276 } else {
2277 break;
2279 } else {
2280 buf += size;
2281 len -= size;
2284 return len1 - len;
2287 static int win_chr_read_poll(Chardev *chr)
2289 WinChardev *s = WIN_CHARDEV(chr);
2291 s->max_size = qemu_chr_be_can_write(chr);
2292 return s->max_size;
2295 static void win_chr_readfile(Chardev *chr)
2297 WinChardev *s = WIN_CHARDEV(chr);
2299 int ret, err;
2300 uint8_t buf[READ_BUF_LEN];
2301 DWORD size;
2303 ZeroMemory(&s->orecv, sizeof(s->orecv));
2304 s->orecv.hEvent = s->hrecv;
2305 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2306 if (!ret) {
2307 err = GetLastError();
2308 if (err == ERROR_IO_PENDING) {
2309 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2313 if (size > 0) {
2314 qemu_chr_be_write(chr, buf, size);
2318 static void win_chr_read(Chardev *chr)
2320 WinChardev *s = WIN_CHARDEV(chr);
2322 if (s->len > s->max_size)
2323 s->len = s->max_size;
2324 if (s->len == 0)
2325 return;
2327 win_chr_readfile(chr);
2330 static int win_chr_poll(void *opaque)
2332 Chardev *chr = CHARDEV(opaque);
2333 WinChardev *s = WIN_CHARDEV(opaque);
2334 COMSTAT status;
2335 DWORD comerr;
2337 ClearCommError(s->hcom, &comerr, &status);
2338 if (status.cbInQue > 0) {
2339 s->len = status.cbInQue;
2340 win_chr_read_poll(chr);
2341 win_chr_read(chr);
2342 return 1;
2344 return 0;
2347 static int win_chr_pipe_poll(void *opaque)
2349 Chardev *chr = CHARDEV(opaque);
2350 WinChardev *s = WIN_CHARDEV(opaque);
2351 DWORD size;
2353 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2354 if (size > 0) {
2355 s->len = size;
2356 win_chr_read_poll(chr);
2357 win_chr_read(chr);
2358 return 1;
2360 return 0;
2363 static int win_chr_pipe_init(Chardev *chr, const char *filename,
2364 Error **errp)
2366 WinChardev *s = WIN_CHARDEV(chr);
2367 OVERLAPPED ov;
2368 int ret;
2369 DWORD size;
2370 char *openname;
2372 s->fpipe = TRUE;
2374 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2375 if (!s->hsend) {
2376 error_setg(errp, "Failed CreateEvent");
2377 goto fail;
2379 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2380 if (!s->hrecv) {
2381 error_setg(errp, "Failed CreateEvent");
2382 goto fail;
2385 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2386 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2387 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2388 PIPE_WAIT,
2389 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2390 g_free(openname);
2391 if (s->hcom == INVALID_HANDLE_VALUE) {
2392 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2393 s->hcom = NULL;
2394 goto fail;
2397 ZeroMemory(&ov, sizeof(ov));
2398 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2399 ret = ConnectNamedPipe(s->hcom, &ov);
2400 if (ret) {
2401 error_setg(errp, "Failed ConnectNamedPipe");
2402 goto fail;
2405 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2406 if (!ret) {
2407 error_setg(errp, "Failed GetOverlappedResult");
2408 if (ov.hEvent) {
2409 CloseHandle(ov.hEvent);
2410 ov.hEvent = NULL;
2412 goto fail;
2415 if (ov.hEvent) {
2416 CloseHandle(ov.hEvent);
2417 ov.hEvent = NULL;
2419 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2420 return 0;
2422 fail:
2423 win_chr_free(chr);
2424 return -1;
2428 static void qemu_chr_open_pipe(Chardev *chr,
2429 ChardevBackend *backend,
2430 bool *be_opened,
2431 Error **errp)
2433 ChardevHostdev *opts = backend->u.pipe.data;
2434 const char *filename = opts->device;
2436 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2437 return;
2441 static void qemu_chr_open_win_file(Chardev *chr, HANDLE fd_out)
2443 WinChardev *s = WIN_CHARDEV(chr);
2445 s->hcom = fd_out;
2448 static void char_win_class_init(ObjectClass *oc, void *data)
2450 ChardevClass *cc = CHARDEV_CLASS(oc);
2452 cc->chr_write = win_chr_write;
2453 cc->chr_free = win_chr_free;
2456 static const TypeInfo char_win_type_info = {
2457 .name = TYPE_CHARDEV_WIN,
2458 .parent = TYPE_CHARDEV,
2459 .instance_size = sizeof(WinChardev),
2460 .class_init = char_win_class_init,
2461 .abstract = true,
2464 static void qemu_chr_open_win_con(Chardev *chr,
2465 ChardevBackend *backend,
2466 bool *be_opened,
2467 Error **errp)
2469 qemu_chr_open_win_file(chr, GetStdHandle(STD_OUTPUT_HANDLE));
2472 static const CharDriver console_driver = {
2473 .kind = CHARDEV_BACKEND_KIND_CONSOLE,
2476 static void char_console_class_init(ObjectClass *oc, void *data)
2478 ChardevClass *cc = CHARDEV_CLASS(oc);
2480 cc->open = qemu_chr_open_win_con;
2481 cc->chr_free = NULL;
2484 static const TypeInfo char_console_type_info = {
2485 .name = TYPE_CHARDEV_CONSOLE,
2486 .parent = TYPE_CHARDEV_WIN,
2487 .class_init = char_console_class_init,
2490 static int win_stdio_write(Chardev *chr, const uint8_t *buf, int len)
2492 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2493 DWORD dwSize;
2494 int len1;
2496 len1 = len;
2498 while (len1 > 0) {
2499 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2500 break;
2502 buf += dwSize;
2503 len1 -= dwSize;
2506 return len - len1;
2509 static void win_stdio_wait_func(void *opaque)
2511 Chardev *chr = CHARDEV(opaque);
2512 WinStdioChardev *stdio = WIN_STDIO_CHARDEV(opaque);
2513 INPUT_RECORD buf[4];
2514 int ret;
2515 DWORD dwSize;
2516 int i;
2518 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2520 if (!ret) {
2521 /* Avoid error storm */
2522 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2523 return;
2526 for (i = 0; i < dwSize; i++) {
2527 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2529 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2530 int j;
2531 if (kev->uChar.AsciiChar != 0) {
2532 for (j = 0; j < kev->wRepeatCount; j++) {
2533 if (qemu_chr_be_can_write(chr)) {
2534 uint8_t c = kev->uChar.AsciiChar;
2535 qemu_chr_be_write(chr, &c, 1);
2543 static DWORD WINAPI win_stdio_thread(LPVOID param)
2545 WinStdioChardev *stdio = WIN_STDIO_CHARDEV(param);
2546 int ret;
2547 DWORD dwSize;
2549 while (1) {
2551 /* Wait for one byte */
2552 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2554 /* Exit in case of error, continue if nothing read */
2555 if (!ret) {
2556 break;
2558 if (!dwSize) {
2559 continue;
2562 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2563 if (stdio->win_stdio_buf == '\r') {
2564 continue;
2567 /* Signal the main thread and wait until the byte was eaten */
2568 if (!SetEvent(stdio->hInputReadyEvent)) {
2569 break;
2571 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2572 != WAIT_OBJECT_0) {
2573 break;
2577 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2578 return 0;
2581 static void win_stdio_thread_wait_func(void *opaque)
2583 Chardev *chr = CHARDEV(opaque);
2584 WinStdioChardev *stdio = WIN_STDIO_CHARDEV(opaque);
2586 if (qemu_chr_be_can_write(chr)) {
2587 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2590 SetEvent(stdio->hInputDoneEvent);
2593 static void qemu_chr_set_echo_win_stdio(Chardev *chr, bool echo)
2595 WinStdioChardev *stdio = WIN_STDIO_CHARDEV(chr);
2596 DWORD dwMode = 0;
2598 GetConsoleMode(stdio->hStdIn, &dwMode);
2600 if (echo) {
2601 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2602 } else {
2603 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2607 static void win_stdio_free(Chardev *chr)
2609 WinStdioChardev *stdio = WIN_STDIO_CHARDEV(chr);
2611 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2612 CloseHandle(stdio->hInputReadyEvent);
2614 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2615 CloseHandle(stdio->hInputDoneEvent);
2617 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2618 TerminateThread(stdio->hInputThread, 0);
2622 static const TypeInfo char_win_stdio_type_info = {
2623 .name = TYPE_CHARDEV_WIN_STDIO,
2624 .parent = TYPE_CHARDEV,
2625 .instance_size = sizeof(WinStdioChardev),
2626 .abstract = true,
2629 static void qemu_chr_open_stdio(Chardev *chr,
2630 ChardevBackend *backend,
2631 bool *be_opened,
2632 Error **errp)
2634 WinStdioChardev *stdio = WIN_STDIO_CHARDEV(chr);
2635 DWORD dwMode;
2636 int is_console = 0;
2638 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2639 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2640 error_setg(errp, "cannot open stdio: invalid handle");
2641 return;
2644 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2646 if (is_console) {
2647 if (qemu_add_wait_object(stdio->hStdIn,
2648 win_stdio_wait_func, chr)) {
2649 error_setg(errp, "qemu_add_wait_object: failed");
2650 goto err1;
2652 } else {
2653 DWORD dwId;
2655 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2656 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2657 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2658 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2659 error_setg(errp, "cannot create event");
2660 goto err2;
2662 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2663 win_stdio_thread_wait_func, chr)) {
2664 error_setg(errp, "qemu_add_wait_object: failed");
2665 goto err2;
2667 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2668 chr, 0, &dwId);
2670 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2671 error_setg(errp, "cannot create stdio thread");
2672 goto err3;
2676 dwMode |= ENABLE_LINE_INPUT;
2678 if (is_console) {
2679 /* set the terminal in raw mode */
2680 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2681 dwMode |= ENABLE_PROCESSED_INPUT;
2684 SetConsoleMode(stdio->hStdIn, dwMode);
2686 qemu_chr_set_echo_win_stdio(chr, false);
2688 return;
2690 err3:
2691 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2692 err2:
2693 CloseHandle(stdio->hInputReadyEvent);
2694 CloseHandle(stdio->hInputDoneEvent);
2695 err1:
2696 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2698 #endif /* !_WIN32 */
2700 /***********************************************************/
2701 /* UDP Net console */
2703 typedef struct {
2704 Chardev parent;
2705 QIOChannel *ioc;
2706 uint8_t buf[READ_BUF_LEN];
2707 int bufcnt;
2708 int bufptr;
2709 int max_size;
2710 } UdpChardev;
2712 #define UDP_CHARDEV(obj) OBJECT_CHECK(UdpChardev, (obj), TYPE_CHARDEV_UDP)
2714 /* Called with chr_write_lock held. */
2715 static int udp_chr_write(Chardev *chr, const uint8_t *buf, int len)
2717 UdpChardev *s = UDP_CHARDEV(chr);
2719 return qio_channel_write(
2720 s->ioc, (const char *)buf, len, NULL);
2723 static int udp_chr_read_poll(void *opaque)
2725 Chardev *chr = CHARDEV(opaque);
2726 UdpChardev *s = UDP_CHARDEV(opaque);
2728 s->max_size = qemu_chr_be_can_write(chr);
2730 /* If there were any stray characters in the queue process them
2731 * first
2733 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2734 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2735 s->bufptr++;
2736 s->max_size = qemu_chr_be_can_write(chr);
2738 return s->max_size;
2741 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2743 Chardev *chr = CHARDEV(opaque);
2744 UdpChardev *s = UDP_CHARDEV(opaque);
2745 ssize_t ret;
2747 if (s->max_size == 0) {
2748 return TRUE;
2750 ret = qio_channel_read(
2751 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2752 if (ret <= 0) {
2753 remove_fd_in_watch(chr);
2754 return FALSE;
2756 s->bufcnt = ret;
2758 s->bufptr = 0;
2759 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2760 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2761 s->bufptr++;
2762 s->max_size = qemu_chr_be_can_write(chr);
2765 return TRUE;
2768 static void udp_chr_update_read_handler(Chardev *chr,
2769 GMainContext *context)
2771 UdpChardev *s = UDP_CHARDEV(chr);
2773 remove_fd_in_watch(chr);
2774 if (s->ioc) {
2775 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
2776 udp_chr_read_poll,
2777 udp_chr_read, chr,
2778 context);
2782 static void udp_chr_free(Chardev *chr)
2784 UdpChardev *s = UDP_CHARDEV(chr);
2786 remove_fd_in_watch(chr);
2787 if (s->ioc) {
2788 object_unref(OBJECT(s->ioc));
2790 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2793 /***********************************************************/
2794 /* TCP Net console */
2796 typedef struct {
2797 Chardev parent;
2798 QIOChannel *ioc; /* Client I/O channel */
2799 QIOChannelSocket *sioc; /* Client master channel */
2800 QIOChannelSocket *listen_ioc;
2801 guint listen_tag;
2802 QCryptoTLSCreds *tls_creds;
2803 int connected;
2804 int max_size;
2805 int do_telnetopt;
2806 int do_nodelay;
2807 int is_unix;
2808 int *read_msgfds;
2809 size_t read_msgfds_num;
2810 int *write_msgfds;
2811 size_t write_msgfds_num;
2813 SocketAddress *addr;
2814 bool is_listen;
2815 bool is_telnet;
2817 guint reconnect_timer;
2818 int64_t reconnect_time;
2819 bool connect_err_reported;
2820 } SocketChardev;
2822 #define SOCKET_CHARDEV(obj) \
2823 OBJECT_CHECK(SocketChardev, (obj), TYPE_CHARDEV_SOCKET)
2825 static gboolean socket_reconnect_timeout(gpointer opaque);
2827 static void qemu_chr_socket_restart_timer(Chardev *chr)
2829 SocketChardev *s = SOCKET_CHARDEV(chr);
2830 char *name;
2832 assert(s->connected == 0);
2833 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2834 socket_reconnect_timeout, chr);
2835 name = g_strdup_printf("chardev-socket-reconnect-%s", chr->label);
2836 g_source_set_name_by_id(s->reconnect_timer, name);
2837 g_free(name);
2840 static void check_report_connect_error(Chardev *chr,
2841 Error *err)
2843 SocketChardev *s = SOCKET_CHARDEV(chr);
2845 if (!s->connect_err_reported) {
2846 error_report("Unable to connect character device %s: %s",
2847 chr->label, error_get_pretty(err));
2848 s->connect_err_reported = true;
2850 qemu_chr_socket_restart_timer(chr);
2853 static gboolean tcp_chr_accept(QIOChannel *chan,
2854 GIOCondition cond,
2855 void *opaque);
2857 /* Called with chr_write_lock held. */
2858 static int tcp_chr_write(Chardev *chr, const uint8_t *buf, int len)
2860 SocketChardev *s = SOCKET_CHARDEV(chr);
2862 if (s->connected) {
2863 int ret = io_channel_send_full(s->ioc, buf, len,
2864 s->write_msgfds,
2865 s->write_msgfds_num);
2867 /* free the written msgfds, no matter what */
2868 if (s->write_msgfds_num) {
2869 g_free(s->write_msgfds);
2870 s->write_msgfds = 0;
2871 s->write_msgfds_num = 0;
2874 return ret;
2875 } else {
2876 /* XXX: indicate an error ? */
2877 return len;
2881 static int tcp_chr_read_poll(void *opaque)
2883 Chardev *chr = CHARDEV(opaque);
2884 SocketChardev *s = SOCKET_CHARDEV(opaque);
2885 if (!s->connected)
2886 return 0;
2887 s->max_size = qemu_chr_be_can_write(chr);
2888 return s->max_size;
2891 #define IAC 255
2892 #define IAC_BREAK 243
2893 static void tcp_chr_process_IAC_bytes(Chardev *chr,
2894 SocketChardev *s,
2895 uint8_t *buf, int *size)
2897 /* Handle any telnet client's basic IAC options to satisfy char by
2898 * char mode with no echo. All IAC options will be removed from
2899 * the buf and the do_telnetopt variable will be used to track the
2900 * state of the width of the IAC information.
2902 * IAC commands come in sets of 3 bytes with the exception of the
2903 * "IAC BREAK" command and the double IAC.
2906 int i;
2907 int j = 0;
2909 for (i = 0; i < *size; i++) {
2910 if (s->do_telnetopt > 1) {
2911 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2912 /* Double IAC means send an IAC */
2913 if (j != i)
2914 buf[j] = buf[i];
2915 j++;
2916 s->do_telnetopt = 1;
2917 } else {
2918 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2919 /* Handle IAC break commands by sending a serial break */
2920 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2921 s->do_telnetopt++;
2923 s->do_telnetopt++;
2925 if (s->do_telnetopt >= 4) {
2926 s->do_telnetopt = 1;
2928 } else {
2929 if ((unsigned char)buf[i] == IAC) {
2930 s->do_telnetopt = 2;
2931 } else {
2932 if (j != i)
2933 buf[j] = buf[i];
2934 j++;
2938 *size = j;
2941 static int tcp_get_msgfds(Chardev *chr, int *fds, int num)
2943 SocketChardev *s = SOCKET_CHARDEV(chr);
2945 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2947 assert(num <= TCP_MAX_FDS);
2949 if (to_copy) {
2950 int i;
2952 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2954 /* Close unused fds */
2955 for (i = to_copy; i < s->read_msgfds_num; i++) {
2956 close(s->read_msgfds[i]);
2959 g_free(s->read_msgfds);
2960 s->read_msgfds = 0;
2961 s->read_msgfds_num = 0;
2964 return to_copy;
2967 static int tcp_set_msgfds(Chardev *chr, int *fds, int num)
2969 SocketChardev *s = SOCKET_CHARDEV(chr);
2971 /* clear old pending fd array */
2972 g_free(s->write_msgfds);
2973 s->write_msgfds = NULL;
2974 s->write_msgfds_num = 0;
2976 if (!s->connected ||
2977 !qio_channel_has_feature(s->ioc,
2978 QIO_CHANNEL_FEATURE_FD_PASS)) {
2979 return -1;
2982 if (num) {
2983 s->write_msgfds = g_new(int, num);
2984 memcpy(s->write_msgfds, fds, num * sizeof(int));
2987 s->write_msgfds_num = num;
2989 return 0;
2992 static ssize_t tcp_chr_recv(Chardev *chr, char *buf, size_t len)
2994 SocketChardev *s = SOCKET_CHARDEV(chr);
2995 struct iovec iov = { .iov_base = buf, .iov_len = len };
2996 int ret;
2997 size_t i;
2998 int *msgfds = NULL;
2999 size_t msgfds_num = 0;
3001 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
3002 ret = qio_channel_readv_full(s->ioc, &iov, 1,
3003 &msgfds, &msgfds_num,
3004 NULL);
3005 } else {
3006 ret = qio_channel_readv_full(s->ioc, &iov, 1,
3007 NULL, NULL,
3008 NULL);
3011 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3012 errno = EAGAIN;
3013 ret = -1;
3014 } else if (ret == -1) {
3015 errno = EIO;
3018 if (msgfds_num) {
3019 /* close and clean read_msgfds */
3020 for (i = 0; i < s->read_msgfds_num; i++) {
3021 close(s->read_msgfds[i]);
3024 if (s->read_msgfds_num) {
3025 g_free(s->read_msgfds);
3028 s->read_msgfds = msgfds;
3029 s->read_msgfds_num = msgfds_num;
3032 for (i = 0; i < s->read_msgfds_num; i++) {
3033 int fd = s->read_msgfds[i];
3034 if (fd < 0) {
3035 continue;
3038 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
3039 qemu_set_block(fd);
3041 #ifndef MSG_CMSG_CLOEXEC
3042 qemu_set_cloexec(fd);
3043 #endif
3046 return ret;
3049 static GSource *tcp_chr_add_watch(Chardev *chr, GIOCondition cond)
3051 SocketChardev *s = SOCKET_CHARDEV(chr);
3052 return qio_channel_create_watch(s->ioc, cond);
3055 static void tcp_chr_free_connection(Chardev *chr)
3057 SocketChardev *s = SOCKET_CHARDEV(chr);
3058 int i;
3060 if (!s->connected) {
3061 return;
3064 if (s->read_msgfds_num) {
3065 for (i = 0; i < s->read_msgfds_num; i++) {
3066 close(s->read_msgfds[i]);
3068 g_free(s->read_msgfds);
3069 s->read_msgfds = NULL;
3070 s->read_msgfds_num = 0;
3073 tcp_set_msgfds(chr, NULL, 0);
3074 remove_fd_in_watch(chr);
3075 object_unref(OBJECT(s->sioc));
3076 s->sioc = NULL;
3077 object_unref(OBJECT(s->ioc));
3078 s->ioc = NULL;
3079 g_free(chr->filename);
3080 chr->filename = NULL;
3081 s->connected = 0;
3084 static void tcp_chr_disconnect(Chardev *chr)
3086 SocketChardev *s = SOCKET_CHARDEV(chr);
3088 if (!s->connected) {
3089 return;
3092 tcp_chr_free_connection(chr);
3094 if (s->listen_ioc) {
3095 s->listen_tag = qio_channel_add_watch(
3096 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
3098 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
3099 s->is_listen, s->is_telnet);
3100 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3101 if (s->reconnect_time) {
3102 qemu_chr_socket_restart_timer(chr);
3106 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
3108 Chardev *chr = CHARDEV(opaque);
3109 SocketChardev *s = SOCKET_CHARDEV(opaque);
3110 uint8_t buf[READ_BUF_LEN];
3111 int len, size;
3113 if (!s->connected || s->max_size <= 0) {
3114 return TRUE;
3116 len = sizeof(buf);
3117 if (len > s->max_size)
3118 len = s->max_size;
3119 size = tcp_chr_recv(chr, (void *)buf, len);
3120 if (size == 0 || size == -1) {
3121 /* connection closed */
3122 tcp_chr_disconnect(chr);
3123 } else if (size > 0) {
3124 if (s->do_telnetopt)
3125 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3126 if (size > 0)
3127 qemu_chr_be_write(chr, buf, size);
3130 return TRUE;
3133 static int tcp_chr_sync_read(Chardev *chr, const uint8_t *buf, int len)
3135 SocketChardev *s = SOCKET_CHARDEV(chr);
3136 int size;
3138 if (!s->connected) {
3139 return 0;
3142 size = tcp_chr_recv(chr, (void *) buf, len);
3143 if (size == 0) {
3144 /* connection closed */
3145 tcp_chr_disconnect(chr);
3148 return size;
3151 static void tcp_chr_connect(void *opaque)
3153 Chardev *chr = CHARDEV(opaque);
3154 SocketChardev *s = SOCKET_CHARDEV(opaque);
3156 g_free(chr->filename);
3157 chr->filename = sockaddr_to_str(
3158 &s->sioc->localAddr, s->sioc->localAddrLen,
3159 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
3160 s->is_listen, s->is_telnet);
3162 s->connected = 1;
3163 if (s->ioc) {
3164 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
3165 tcp_chr_read_poll,
3166 tcp_chr_read,
3167 chr, NULL);
3169 qemu_chr_be_generic_open(chr);
3172 static void tcp_chr_update_read_handler(Chardev *chr,
3173 GMainContext *context)
3175 SocketChardev *s = SOCKET_CHARDEV(chr);
3177 if (!s->connected) {
3178 return;
3181 remove_fd_in_watch(chr);
3182 if (s->ioc) {
3183 chr->fd_in_tag = io_add_watch_poll(chr, s->ioc,
3184 tcp_chr_read_poll,
3185 tcp_chr_read, chr,
3186 context);
3190 typedef struct {
3191 Chardev *chr;
3192 char buf[12];
3193 size_t buflen;
3194 } TCPCharDriverTelnetInit;
3196 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
3197 GIOCondition cond G_GNUC_UNUSED,
3198 gpointer user_data)
3200 TCPCharDriverTelnetInit *init = user_data;
3201 ssize_t ret;
3203 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
3204 if (ret < 0) {
3205 if (ret == QIO_CHANNEL_ERR_BLOCK) {
3206 ret = 0;
3207 } else {
3208 tcp_chr_disconnect(init->chr);
3209 return FALSE;
3212 init->buflen -= ret;
3214 if (init->buflen == 0) {
3215 tcp_chr_connect(init->chr);
3216 return FALSE;
3219 memmove(init->buf, init->buf + ret, init->buflen);
3221 return TRUE;
3224 static void tcp_chr_telnet_init(Chardev *chr)
3226 SocketChardev *s = SOCKET_CHARDEV(chr);
3227 TCPCharDriverTelnetInit *init =
3228 g_new0(TCPCharDriverTelnetInit, 1);
3229 size_t n = 0;
3231 init->chr = chr;
3232 init->buflen = 12;
3234 #define IACSET(x, a, b, c) \
3235 do { \
3236 x[n++] = a; \
3237 x[n++] = b; \
3238 x[n++] = c; \
3239 } while (0)
3241 /* Prep the telnet negotion to put telnet in binary,
3242 * no echo, single char mode */
3243 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3244 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3245 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3246 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3248 #undef IACSET
3250 qio_channel_add_watch(
3251 s->ioc, G_IO_OUT,
3252 tcp_chr_telnet_init_io,
3253 init, NULL);
3257 static void tcp_chr_tls_handshake(QIOTask *task,
3258 gpointer user_data)
3260 Chardev *chr = user_data;
3261 SocketChardev *s = user_data;
3263 if (qio_task_propagate_error(task, NULL)) {
3264 tcp_chr_disconnect(chr);
3265 } else {
3266 if (s->do_telnetopt) {
3267 tcp_chr_telnet_init(chr);
3268 } else {
3269 tcp_chr_connect(chr);
3275 static void tcp_chr_tls_init(Chardev *chr)
3277 SocketChardev *s = SOCKET_CHARDEV(chr);
3278 QIOChannelTLS *tioc;
3279 Error *err = NULL;
3280 gchar *name;
3282 if (s->is_listen) {
3283 tioc = qio_channel_tls_new_server(
3284 s->ioc, s->tls_creds,
3285 NULL, /* XXX Use an ACL */
3286 &err);
3287 } else {
3288 tioc = qio_channel_tls_new_client(
3289 s->ioc, s->tls_creds,
3290 s->addr->u.inet.data->host,
3291 &err);
3293 if (tioc == NULL) {
3294 error_free(err);
3295 tcp_chr_disconnect(chr);
3296 return;
3298 name = g_strdup_printf("chardev-tls-%s-%s",
3299 s->is_listen ? "server" : "client",
3300 chr->label);
3301 qio_channel_set_name(QIO_CHANNEL(tioc), name);
3302 g_free(name);
3303 object_unref(OBJECT(s->ioc));
3304 s->ioc = QIO_CHANNEL(tioc);
3306 qio_channel_tls_handshake(tioc,
3307 tcp_chr_tls_handshake,
3308 chr,
3309 NULL);
3313 static void tcp_chr_set_client_ioc_name(Chardev *chr,
3314 QIOChannelSocket *sioc)
3316 SocketChardev *s = SOCKET_CHARDEV(chr);
3317 char *name;
3318 name = g_strdup_printf("chardev-tcp-%s-%s",
3319 s->is_listen ? "server" : "client",
3320 chr->label);
3321 qio_channel_set_name(QIO_CHANNEL(sioc), name);
3322 g_free(name);
3326 static int tcp_chr_new_client(Chardev *chr, QIOChannelSocket *sioc)
3328 SocketChardev *s = SOCKET_CHARDEV(chr);
3330 if (s->ioc != NULL) {
3331 return -1;
3334 s->ioc = QIO_CHANNEL(sioc);
3335 object_ref(OBJECT(sioc));
3336 s->sioc = sioc;
3337 object_ref(OBJECT(sioc));
3339 qio_channel_set_blocking(s->ioc, false, NULL);
3341 if (s->do_nodelay) {
3342 qio_channel_set_delay(s->ioc, false);
3344 if (s->listen_tag) {
3345 g_source_remove(s->listen_tag);
3346 s->listen_tag = 0;
3349 if (s->tls_creds) {
3350 tcp_chr_tls_init(chr);
3351 } else {
3352 if (s->do_telnetopt) {
3353 tcp_chr_telnet_init(chr);
3354 } else {
3355 tcp_chr_connect(chr);
3359 return 0;
3363 static int tcp_chr_add_client(Chardev *chr, int fd)
3365 int ret;
3366 QIOChannelSocket *sioc;
3368 sioc = qio_channel_socket_new_fd(fd, NULL);
3369 if (!sioc) {
3370 return -1;
3372 tcp_chr_set_client_ioc_name(chr, sioc);
3373 ret = tcp_chr_new_client(chr, sioc);
3374 object_unref(OBJECT(sioc));
3375 return ret;
3378 static gboolean tcp_chr_accept(QIOChannel *channel,
3379 GIOCondition cond,
3380 void *opaque)
3382 Chardev *chr = CHARDEV(opaque);
3383 QIOChannelSocket *sioc;
3385 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3386 NULL);
3387 if (!sioc) {
3388 return TRUE;
3391 tcp_chr_new_client(chr, sioc);
3393 object_unref(OBJECT(sioc));
3395 return TRUE;
3398 static int tcp_chr_wait_connected(Chardev *chr, Error **errp)
3400 SocketChardev *s = SOCKET_CHARDEV(chr);
3401 QIOChannelSocket *sioc;
3403 /* It can't wait on s->connected, since it is set asynchronously
3404 * in TLS and telnet cases, only wait for an accepted socket */
3405 while (!s->ioc) {
3406 if (s->is_listen) {
3407 error_report("QEMU waiting for connection on: %s",
3408 chr->filename);
3409 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), true, NULL);
3410 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
3411 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
3412 } else {
3413 sioc = qio_channel_socket_new();
3414 tcp_chr_set_client_ioc_name(chr, sioc);
3415 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
3416 object_unref(OBJECT(sioc));
3417 return -1;
3419 tcp_chr_new_client(chr, sioc);
3420 object_unref(OBJECT(sioc));
3424 return 0;
3427 static int qemu_chr_wait_connected(Chardev *chr, Error **errp)
3429 ChardevClass *cc = CHARDEV_GET_CLASS(chr);
3431 if (cc->chr_wait_connected) {
3432 return cc->chr_wait_connected(chr, errp);
3435 return 0;
3438 int qemu_chr_fe_wait_connected(CharBackend *be, Error **errp)
3440 if (!be->chr) {
3441 error_setg(errp, "missing associated backend");
3442 return -1;
3445 return qemu_chr_wait_connected(be->chr, errp);
3448 static void tcp_chr_free(Chardev *chr)
3450 SocketChardev *s = SOCKET_CHARDEV(chr);
3452 tcp_chr_free_connection(chr);
3454 if (s->reconnect_timer) {
3455 g_source_remove(s->reconnect_timer);
3456 s->reconnect_timer = 0;
3458 qapi_free_SocketAddress(s->addr);
3459 if (s->listen_tag) {
3460 g_source_remove(s->listen_tag);
3461 s->listen_tag = 0;
3463 if (s->listen_ioc) {
3464 object_unref(OBJECT(s->listen_ioc));
3466 if (s->tls_creds) {
3467 object_unref(OBJECT(s->tls_creds));
3470 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3474 static void qemu_chr_socket_connected(QIOTask *task, void *opaque)
3476 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(qio_task_get_source(task));
3477 Chardev *chr = CHARDEV(opaque);
3478 SocketChardev *s = SOCKET_CHARDEV(chr);
3479 Error *err = NULL;
3481 if (qio_task_propagate_error(task, &err)) {
3482 check_report_connect_error(chr, err);
3483 error_free(err);
3484 goto cleanup;
3487 s->connect_err_reported = false;
3488 tcp_chr_new_client(chr, sioc);
3490 cleanup:
3491 object_unref(OBJECT(sioc));
3495 /*********************************************************/
3496 /* Ring buffer chardev */
3498 typedef struct {
3499 Chardev parent;
3500 size_t size;
3501 size_t prod;
3502 size_t cons;
3503 uint8_t *cbuf;
3504 } RingBufChardev;
3506 #define RINGBUF_CHARDEV(obj) \
3507 OBJECT_CHECK(RingBufChardev, (obj), TYPE_CHARDEV_RINGBUF)
3509 static size_t ringbuf_count(const Chardev *chr)
3511 const RingBufChardev *d = RINGBUF_CHARDEV(chr);
3513 return d->prod - d->cons;
3516 /* Called with chr_write_lock held. */
3517 static int ringbuf_chr_write(Chardev *chr, const uint8_t *buf, int len)
3519 RingBufChardev *d = RINGBUF_CHARDEV(chr);
3520 int i;
3522 if (!buf || (len < 0)) {
3523 return -1;
3526 for (i = 0; i < len; i++ ) {
3527 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3528 if (d->prod - d->cons > d->size) {
3529 d->cons = d->prod - d->size;
3533 return len;
3536 static int ringbuf_chr_read(Chardev *chr, uint8_t *buf, int len)
3538 RingBufChardev *d = RINGBUF_CHARDEV(chr);
3539 int i;
3541 qemu_mutex_lock(&chr->chr_write_lock);
3542 for (i = 0; i < len && d->cons != d->prod; i++) {
3543 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3545 qemu_mutex_unlock(&chr->chr_write_lock);
3547 return i;
3550 static void ringbuf_chr_free(struct Chardev *chr)
3552 RingBufChardev *d = RINGBUF_CHARDEV(chr);
3554 g_free(d->cbuf);
3557 static void qemu_chr_open_ringbuf(Chardev *chr,
3558 ChardevBackend *backend,
3559 bool *be_opened,
3560 Error **errp)
3562 ChardevRingbuf *opts = backend->u.ringbuf.data;
3563 RingBufChardev *d = RINGBUF_CHARDEV(chr);
3565 d->size = opts->has_size ? opts->size : 65536;
3567 /* The size must be power of 2 */
3568 if (d->size & (d->size - 1)) {
3569 error_setg(errp, "size of ringbuf chardev must be power of two");
3570 return;
3573 d->prod = 0;
3574 d->cons = 0;
3575 d->cbuf = g_malloc0(d->size);
3578 void qmp_ringbuf_write(const char *device, const char *data,
3579 bool has_format, enum DataFormat format,
3580 Error **errp)
3582 Chardev *chr;
3583 const uint8_t *write_data;
3584 int ret;
3585 gsize write_count;
3587 chr = qemu_chr_find(device);
3588 if (!chr) {
3589 error_setg(errp, "Device '%s' not found", device);
3590 return;
3593 if (!CHARDEV_IS_RINGBUF(chr)) {
3594 error_setg(errp,"%s is not a ringbuf device", device);
3595 return;
3598 if (has_format && (format == DATA_FORMAT_BASE64)) {
3599 write_data = qbase64_decode(data, -1,
3600 &write_count,
3601 errp);
3602 if (!write_data) {
3603 return;
3605 } else {
3606 write_data = (uint8_t *)data;
3607 write_count = strlen(data);
3610 ret = ringbuf_chr_write(chr, write_data, write_count);
3612 if (write_data != (uint8_t *)data) {
3613 g_free((void *)write_data);
3616 if (ret < 0) {
3617 error_setg(errp, "Failed to write to device %s", device);
3618 return;
3622 char *qmp_ringbuf_read(const char *device, int64_t size,
3623 bool has_format, enum DataFormat format,
3624 Error **errp)
3626 Chardev *chr;
3627 uint8_t *read_data;
3628 size_t count;
3629 char *data;
3631 chr = qemu_chr_find(device);
3632 if (!chr) {
3633 error_setg(errp, "Device '%s' not found", device);
3634 return NULL;
3637 if (!CHARDEV_IS_RINGBUF(chr)) {
3638 error_setg(errp,"%s is not a ringbuf device", device);
3639 return NULL;
3642 if (size <= 0) {
3643 error_setg(errp, "size must be greater than zero");
3644 return NULL;
3647 count = ringbuf_count(chr);
3648 size = size > count ? count : size;
3649 read_data = g_malloc(size + 1);
3651 ringbuf_chr_read(chr, read_data, size);
3653 if (has_format && (format == DATA_FORMAT_BASE64)) {
3654 data = g_base64_encode(read_data, size);
3655 g_free(read_data);
3656 } else {
3658 * FIXME should read only complete, valid UTF-8 characters up
3659 * to @size bytes. Invalid sequences should be replaced by a
3660 * suitable replacement character. Except when (and only
3661 * when) ring buffer lost characters since last read, initial
3662 * continuation characters should be dropped.
3664 read_data[size] = 0;
3665 data = (char *)read_data;
3668 return data;
3671 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3673 char host[65], port[33], width[8], height[8];
3674 int pos;
3675 const char *p;
3676 QemuOpts *opts;
3677 Error *local_err = NULL;
3679 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3680 if (local_err) {
3681 error_report_err(local_err);
3682 return NULL;
3685 if (strstart(filename, "mon:", &p)) {
3686 filename = p;
3687 qemu_opt_set(opts, "mux", "on", &error_abort);
3688 if (strcmp(filename, "stdio") == 0) {
3689 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3690 * but pass it to the guest. Handle this only for compat syntax,
3691 * for -chardev syntax we have special option for this.
3692 * This is what -nographic did, redirecting+muxing serial+monitor
3693 * to stdio causing Ctrl+C to be passed to guest. */
3694 qemu_opt_set(opts, "signal", "off", &error_abort);
3698 if (strcmp(filename, "null") == 0 ||
3699 strcmp(filename, "pty") == 0 ||
3700 strcmp(filename, "msmouse") == 0 ||
3701 strcmp(filename, "braille") == 0 ||
3702 strcmp(filename, "testdev") == 0 ||
3703 strcmp(filename, "stdio") == 0) {
3704 qemu_opt_set(opts, "backend", filename, &error_abort);
3705 return opts;
3707 if (strstart(filename, "vc", &p)) {
3708 qemu_opt_set(opts, "backend", "vc", &error_abort);
3709 if (*p == ':') {
3710 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3711 /* pixels */
3712 qemu_opt_set(opts, "width", width, &error_abort);
3713 qemu_opt_set(opts, "height", height, &error_abort);
3714 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3715 /* chars */
3716 qemu_opt_set(opts, "cols", width, &error_abort);
3717 qemu_opt_set(opts, "rows", height, &error_abort);
3718 } else {
3719 goto fail;
3722 return opts;
3724 if (strcmp(filename, "con:") == 0) {
3725 qemu_opt_set(opts, "backend", "console", &error_abort);
3726 return opts;
3728 if (strstart(filename, "COM", NULL)) {
3729 qemu_opt_set(opts, "backend", "serial", &error_abort);
3730 qemu_opt_set(opts, "path", filename, &error_abort);
3731 return opts;
3733 if (strstart(filename, "file:", &p)) {
3734 qemu_opt_set(opts, "backend", "file", &error_abort);
3735 qemu_opt_set(opts, "path", p, &error_abort);
3736 return opts;
3738 if (strstart(filename, "pipe:", &p)) {
3739 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3740 qemu_opt_set(opts, "path", p, &error_abort);
3741 return opts;
3743 if (strstart(filename, "tcp:", &p) ||
3744 strstart(filename, "telnet:", &p)) {
3745 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3746 host[0] = 0;
3747 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3748 goto fail;
3750 qemu_opt_set(opts, "backend", "socket", &error_abort);
3751 qemu_opt_set(opts, "host", host, &error_abort);
3752 qemu_opt_set(opts, "port", port, &error_abort);
3753 if (p[pos] == ',') {
3754 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3755 if (local_err) {
3756 error_report_err(local_err);
3757 goto fail;
3760 if (strstart(filename, "telnet:", &p))
3761 qemu_opt_set(opts, "telnet", "on", &error_abort);
3762 return opts;
3764 if (strstart(filename, "udp:", &p)) {
3765 qemu_opt_set(opts, "backend", "udp", &error_abort);
3766 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3767 host[0] = 0;
3768 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3769 goto fail;
3772 qemu_opt_set(opts, "host", host, &error_abort);
3773 qemu_opt_set(opts, "port", port, &error_abort);
3774 if (p[pos] == '@') {
3775 p += pos + 1;
3776 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3777 host[0] = 0;
3778 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3779 goto fail;
3782 qemu_opt_set(opts, "localaddr", host, &error_abort);
3783 qemu_opt_set(opts, "localport", port, &error_abort);
3785 return opts;
3787 if (strstart(filename, "unix:", &p)) {
3788 qemu_opt_set(opts, "backend", "socket", &error_abort);
3789 qemu_opts_do_parse(opts, p, "path", &local_err);
3790 if (local_err) {
3791 error_report_err(local_err);
3792 goto fail;
3794 return opts;
3796 if (strstart(filename, "/dev/parport", NULL) ||
3797 strstart(filename, "/dev/ppi", NULL)) {
3798 qemu_opt_set(opts, "backend", "parport", &error_abort);
3799 qemu_opt_set(opts, "path", filename, &error_abort);
3800 return opts;
3802 if (strstart(filename, "/dev/", NULL)) {
3803 qemu_opt_set(opts, "backend", "tty", &error_abort);
3804 qemu_opt_set(opts, "path", filename, &error_abort);
3805 return opts;
3808 fail:
3809 qemu_opts_del(opts);
3810 return NULL;
3813 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3815 const char *logfile = qemu_opt_get(opts, "logfile");
3817 backend->has_logfile = logfile != NULL;
3818 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3820 backend->has_logappend = true;
3821 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3825 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3826 Error **errp)
3828 const char *path = qemu_opt_get(opts, "path");
3829 ChardevFile *file;
3831 if (path == NULL) {
3832 error_setg(errp, "chardev: file: no filename given");
3833 return;
3835 file = backend->u.file.data = g_new0(ChardevFile, 1);
3836 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3837 file->out = g_strdup(path);
3839 file->has_append = true;
3840 file->append = qemu_opt_get_bool(opts, "append", false);
3843 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3844 Error **errp)
3846 ChardevStdio *stdio;
3848 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3849 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3850 stdio->has_signal = true;
3851 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3854 static const CharDriver stdio_driver = {
3855 .kind = CHARDEV_BACKEND_KIND_STDIO,
3856 .parse = qemu_chr_parse_stdio,
3859 static void char_stdio_class_init(ObjectClass *oc, void *data)
3861 ChardevClass *cc = CHARDEV_CLASS(oc);
3863 cc->open = qemu_chr_open_stdio;
3864 #ifdef _WIN32
3865 cc->chr_write = win_stdio_write;
3866 cc->chr_set_echo = qemu_chr_set_echo_win_stdio;
3867 cc->chr_free = win_stdio_free;
3868 #else
3869 cc->chr_set_echo = qemu_chr_set_echo_stdio;
3870 cc->chr_free = qemu_chr_free_stdio;
3871 #endif
3874 static const TypeInfo char_stdio_type_info = {
3875 .name = TYPE_CHARDEV_STDIO,
3876 #ifdef _WIN32
3877 .parent = TYPE_CHARDEV_WIN_STDIO,
3878 #else
3879 .parent = TYPE_CHARDEV_FD,
3880 #endif
3881 .class_init = char_stdio_class_init,
3884 #ifdef HAVE_CHARDEV_SERIAL
3885 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3886 Error **errp)
3888 const char *device = qemu_opt_get(opts, "path");
3889 ChardevHostdev *serial;
3891 if (device == NULL) {
3892 error_setg(errp, "chardev: serial/tty: no device path given");
3893 return;
3895 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3896 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3897 serial->device = g_strdup(device);
3899 #endif
3901 #ifdef HAVE_CHARDEV_PARPORT
3902 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3903 Error **errp)
3905 const char *device = qemu_opt_get(opts, "path");
3906 ChardevHostdev *parallel;
3908 if (device == NULL) {
3909 error_setg(errp, "chardev: parallel: no device path given");
3910 return;
3912 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3913 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3914 parallel->device = g_strdup(device);
3916 #endif
3918 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3919 Error **errp)
3921 const char *device = qemu_opt_get(opts, "path");
3922 ChardevHostdev *dev;
3924 if (device == NULL) {
3925 error_setg(errp, "chardev: pipe: no device path given");
3926 return;
3928 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3929 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3930 dev->device = g_strdup(device);
3933 static const CharDriver pipe_driver = {
3934 .kind = CHARDEV_BACKEND_KIND_PIPE,
3935 .parse = qemu_chr_parse_pipe,
3938 static void char_pipe_class_init(ObjectClass *oc, void *data)
3940 ChardevClass *cc = CHARDEV_CLASS(oc);
3942 cc->open = qemu_chr_open_pipe;
3945 static const TypeInfo char_pipe_type_info = {
3946 .name = TYPE_CHARDEV_PIPE,
3947 #ifdef _WIN32
3948 .parent = TYPE_CHARDEV_WIN,
3949 #else
3950 .parent = TYPE_CHARDEV_FD,
3951 #endif
3952 .class_init = char_pipe_class_init,
3955 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3956 Error **errp)
3958 int val;
3959 ChardevRingbuf *ringbuf;
3961 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3962 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3964 val = qemu_opt_get_size(opts, "size", 0);
3965 if (val != 0) {
3966 ringbuf->has_size = true;
3967 ringbuf->size = val;
3971 static const CharDriver ringbuf_driver = {
3972 .kind = CHARDEV_BACKEND_KIND_RINGBUF,
3973 .parse = qemu_chr_parse_ringbuf,
3976 static void char_ringbuf_class_init(ObjectClass *oc, void *data)
3978 ChardevClass *cc = CHARDEV_CLASS(oc);
3980 cc->open = qemu_chr_open_ringbuf;
3981 cc->chr_write = ringbuf_chr_write;
3982 cc->chr_free = ringbuf_chr_free;
3985 static const TypeInfo char_ringbuf_type_info = {
3986 .name = TYPE_CHARDEV_RINGBUF,
3987 .parent = TYPE_CHARDEV,
3988 .class_init = char_ringbuf_class_init,
3989 .instance_size = sizeof(RingBufChardev),
3992 /* Bug-compatibility: */
3993 static const CharDriver memory_driver = {
3994 .kind = CHARDEV_BACKEND_KIND_MEMORY,
3995 .parse = qemu_chr_parse_ringbuf,
3998 static const TypeInfo char_memory_type_info = {
3999 .name = TYPE_CHARDEV_MEMORY,
4000 .parent = TYPE_CHARDEV_RINGBUF,
4003 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
4004 Error **errp)
4006 const char *chardev = qemu_opt_get(opts, "chardev");
4007 ChardevMux *mux;
4009 if (chardev == NULL) {
4010 error_setg(errp, "chardev: mux: no chardev given");
4011 return;
4013 mux = backend->u.mux.data = g_new0(ChardevMux, 1);
4014 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
4015 mux->chardev = g_strdup(chardev);
4018 static const CharDriver mux_driver = {
4019 .kind = CHARDEV_BACKEND_KIND_MUX,
4020 .parse = qemu_chr_parse_mux,
4023 static void char_mux_class_init(ObjectClass *oc, void *data)
4025 ChardevClass *cc = CHARDEV_CLASS(oc);
4027 cc->open = qemu_chr_open_mux;
4028 cc->chr_free = mux_chr_free;
4029 cc->chr_write = mux_chr_write;
4030 cc->chr_accept_input = mux_chr_accept_input;
4031 cc->chr_add_watch = mux_chr_add_watch;
4034 static const TypeInfo char_mux_type_info = {
4035 .name = TYPE_CHARDEV_MUX,
4036 .parent = TYPE_CHARDEV,
4037 .class_init = char_mux_class_init,
4038 .instance_size = sizeof(MuxChardev),
4041 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
4042 Error **errp)
4044 bool is_listen = qemu_opt_get_bool(opts, "server", false);
4045 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
4046 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
4047 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
4048 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
4049 const char *path = qemu_opt_get(opts, "path");
4050 const char *host = qemu_opt_get(opts, "host");
4051 const char *port = qemu_opt_get(opts, "port");
4052 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
4053 SocketAddress *addr;
4054 ChardevSocket *sock;
4056 if (!path) {
4057 if (!host) {
4058 error_setg(errp, "chardev: socket: no host given");
4059 return;
4061 if (!port) {
4062 error_setg(errp, "chardev: socket: no port given");
4063 return;
4065 } else {
4066 if (tls_creds) {
4067 error_setg(errp, "TLS can only be used over TCP socket");
4068 return;
4072 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
4073 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
4075 sock->has_nodelay = true;
4076 sock->nodelay = do_nodelay;
4077 sock->has_server = true;
4078 sock->server = is_listen;
4079 sock->has_telnet = true;
4080 sock->telnet = is_telnet;
4081 sock->has_wait = true;
4082 sock->wait = is_waitconnect;
4083 sock->has_reconnect = true;
4084 sock->reconnect = reconnect;
4085 sock->tls_creds = g_strdup(tls_creds);
4087 addr = g_new0(SocketAddress, 1);
4088 if (path) {
4089 UnixSocketAddress *q_unix;
4090 addr->type = SOCKET_ADDRESS_KIND_UNIX;
4091 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
4092 q_unix->path = g_strdup(path);
4093 } else {
4094 addr->type = SOCKET_ADDRESS_KIND_INET;
4095 addr->u.inet.data = g_new(InetSocketAddress, 1);
4096 *addr->u.inet.data = (InetSocketAddress) {
4097 .host = g_strdup(host),
4098 .port = g_strdup(port),
4099 .has_to = qemu_opt_get(opts, "to"),
4100 .to = qemu_opt_get_number(opts, "to", 0),
4101 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
4102 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
4103 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
4104 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
4107 sock->addr = addr;
4110 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
4111 Error **errp)
4113 const char *host = qemu_opt_get(opts, "host");
4114 const char *port = qemu_opt_get(opts, "port");
4115 const char *localaddr = qemu_opt_get(opts, "localaddr");
4116 const char *localport = qemu_opt_get(opts, "localport");
4117 bool has_local = false;
4118 SocketAddress *addr;
4119 ChardevUdp *udp;
4121 if (host == NULL || strlen(host) == 0) {
4122 host = "localhost";
4124 if (port == NULL || strlen(port) == 0) {
4125 error_setg(errp, "chardev: udp: remote port not specified");
4126 return;
4128 if (localport == NULL || strlen(localport) == 0) {
4129 localport = "0";
4130 } else {
4131 has_local = true;
4133 if (localaddr == NULL || strlen(localaddr) == 0) {
4134 localaddr = "";
4135 } else {
4136 has_local = true;
4139 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
4140 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
4142 addr = g_new0(SocketAddress, 1);
4143 addr->type = SOCKET_ADDRESS_KIND_INET;
4144 addr->u.inet.data = g_new(InetSocketAddress, 1);
4145 *addr->u.inet.data = (InetSocketAddress) {
4146 .host = g_strdup(host),
4147 .port = g_strdup(port),
4148 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
4149 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
4150 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
4151 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
4153 udp->remote = addr;
4155 if (has_local) {
4156 udp->has_local = true;
4157 addr = g_new0(SocketAddress, 1);
4158 addr->type = SOCKET_ADDRESS_KIND_INET;
4159 addr->u.inet.data = g_new(InetSocketAddress, 1);
4160 *addr->u.inet.data = (InetSocketAddress) {
4161 .host = g_strdup(localaddr),
4162 .port = g_strdup(localport),
4164 udp->local = addr;
4168 static const CharDriver *backends[CHARDEV_BACKEND_KIND__MAX];
4170 void register_char_driver(const CharDriver *driver)
4172 backends[driver->kind] = driver;
4175 Chardev *qemu_chr_new_from_opts(QemuOpts *opts,
4176 Error **errp)
4178 Error *local_err = NULL;
4179 const CharDriver *cd = NULL;
4180 Chardev *chr;
4181 int i;
4182 ChardevReturn *ret = NULL;
4183 ChardevBackend *backend;
4184 const char *name = qemu_opt_get(opts, "backend");
4185 const char *id = qemu_opts_id(opts);
4186 char *bid = NULL;
4188 if (name == NULL) {
4189 error_setg(errp, "chardev: \"%s\" missing backend",
4190 qemu_opts_id(opts));
4191 goto err;
4194 if (is_help_option(name)) {
4195 GString *str = g_string_new("");
4196 for (i = 0; i < ARRAY_SIZE(backends); i++) {
4197 cd = backends[i];
4198 if (cd) {
4199 g_string_append_printf(str, "\n%s", ChardevBackendKind_lookup[cd->kind]);
4200 if (cd->alias) {
4201 g_string_append_printf(str, "\n%s", cd->alias);
4206 error_report("Available chardev backend types: %s", str->str);
4207 g_string_free(str, true);
4208 exit(0);
4211 if (id == NULL) {
4212 error_setg(errp, "chardev: no id specified");
4213 goto err;
4216 for (i = 0; i < ARRAY_SIZE(backends); i++) {
4217 cd = backends[i];
4218 if (!cd) {
4219 continue;
4221 if (g_strcmp0(ChardevBackendKind_lookup[cd->kind], name) == 0 ||
4222 g_strcmp0(cd->alias, name) == 0) {
4223 break;
4226 if (i == ARRAY_SIZE(backends)) {
4227 error_setg(errp, "chardev: backend \"%s\" not found", name);
4228 goto err;
4231 backend = g_new0(ChardevBackend, 1);
4233 if (qemu_opt_get_bool(opts, "mux", 0)) {
4234 bid = g_strdup_printf("%s-base", id);
4237 chr = NULL;
4238 backend->type = cd->kind;
4239 if (cd->parse) {
4240 cd->parse(opts, backend, &local_err);
4241 if (local_err) {
4242 error_propagate(errp, local_err);
4243 goto qapi_out;
4245 } else {
4246 ChardevCommon *cc = g_new0(ChardevCommon, 1);
4247 qemu_chr_parse_common(opts, cc);
4248 backend->u.null.data = cc; /* Any ChardevCommon member would work */
4251 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
4252 if (!ret) {
4253 goto qapi_out;
4256 if (bid) {
4257 qapi_free_ChardevBackend(backend);
4258 qapi_free_ChardevReturn(ret);
4259 backend = g_new0(ChardevBackend, 1);
4260 backend->u.mux.data = g_new0(ChardevMux, 1);
4261 backend->type = CHARDEV_BACKEND_KIND_MUX;
4262 backend->u.mux.data->chardev = g_strdup(bid);
4263 ret = qmp_chardev_add(id, backend, errp);
4264 if (!ret) {
4265 chr = qemu_chr_find(bid);
4266 qemu_chr_delete(chr);
4267 chr = NULL;
4268 goto qapi_out;
4272 chr = qemu_chr_find(id);
4274 qapi_out:
4275 qapi_free_ChardevBackend(backend);
4276 qapi_free_ChardevReturn(ret);
4277 g_free(bid);
4278 return chr;
4280 err:
4281 return NULL;
4284 Chardev *qemu_chr_new_noreplay(const char *label, const char *filename)
4286 const char *p;
4287 Chardev *chr;
4288 QemuOpts *opts;
4289 Error *err = NULL;
4291 if (strstart(filename, "chardev:", &p)) {
4292 return qemu_chr_find(p);
4295 opts = qemu_chr_parse_compat(label, filename);
4296 if (!opts)
4297 return NULL;
4299 chr = qemu_chr_new_from_opts(opts, &err);
4300 if (err) {
4301 error_report_err(err);
4303 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
4304 monitor_init(chr, MONITOR_USE_READLINE);
4306 qemu_opts_del(opts);
4307 return chr;
4310 Chardev *qemu_chr_new(const char *label, const char *filename)
4312 Chardev *chr;
4313 chr = qemu_chr_new_noreplay(label, filename);
4314 if (chr) {
4315 if (replay_mode != REPLAY_MODE_NONE) {
4316 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_REPLAY);
4318 if (qemu_chr_replay(chr) && CHARDEV_GET_CLASS(chr)->chr_ioctl) {
4319 error_report("Replay: ioctl is not supported "
4320 "for serial devices yet");
4322 replay_register_char_driver(chr);
4324 return chr;
4327 void qemu_chr_fe_set_echo(CharBackend *be, bool echo)
4329 Chardev *chr = be->chr;
4331 if (chr && CHARDEV_GET_CLASS(chr)->chr_set_echo) {
4332 CHARDEV_GET_CLASS(chr)->chr_set_echo(chr, echo);
4336 void qemu_chr_fe_set_open(CharBackend *be, int fe_open)
4338 Chardev *chr = be->chr;
4340 if (!chr) {
4341 return;
4344 if (be->fe_open == fe_open) {
4345 return;
4347 be->fe_open = fe_open;
4348 if (CHARDEV_GET_CLASS(chr)->chr_set_fe_open) {
4349 CHARDEV_GET_CLASS(chr)->chr_set_fe_open(chr, fe_open);
4353 guint qemu_chr_fe_add_watch(CharBackend *be, GIOCondition cond,
4354 GIOFunc func, void *user_data)
4356 Chardev *s = be->chr;
4357 GSource *src;
4358 guint tag;
4360 if (!s || CHARDEV_GET_CLASS(s)->chr_add_watch == NULL) {
4361 return 0;
4364 src = CHARDEV_GET_CLASS(s)->chr_add_watch(s, cond);
4365 if (!src) {
4366 return 0;
4369 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
4370 tag = g_source_attach(src, NULL);
4371 g_source_unref(src);
4373 return tag;
4376 void qemu_chr_fe_disconnect(CharBackend *be)
4378 Chardev *chr = be->chr;
4380 if (chr && CHARDEV_GET_CLASS(chr)->chr_disconnect) {
4381 CHARDEV_GET_CLASS(chr)->chr_disconnect(chr);
4385 void qemu_chr_free(Chardev *chr)
4387 if (CHARDEV_GET_CLASS(chr)->chr_free) {
4388 CHARDEV_GET_CLASS(chr)->chr_free(chr);
4390 object_unref(OBJECT(chr));
4393 void qemu_chr_delete(Chardev *chr)
4395 QTAILQ_REMOVE(&chardevs, chr, next);
4396 qemu_chr_free(chr);
4399 ChardevInfoList *qmp_query_chardev(Error **errp)
4401 ChardevInfoList *chr_list = NULL;
4402 Chardev *chr;
4404 QTAILQ_FOREACH(chr, &chardevs, next) {
4405 ChardevInfoList *info = g_malloc0(sizeof(*info));
4406 info->value = g_malloc0(sizeof(*info->value));
4407 info->value->label = g_strdup(chr->label);
4408 info->value->filename = g_strdup(chr->filename);
4409 info->value->frontend_open = chr->be && chr->be->fe_open;
4411 info->next = chr_list;
4412 chr_list = info;
4415 return chr_list;
4418 static ChardevBackendInfoList *
4419 qmp_prepend_backend(ChardevBackendInfoList *list, const char *name)
4421 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4422 info->value = g_malloc0(sizeof(*info->value));
4423 info->value->name = g_strdup(name);
4424 info->next = list;
4425 return info;
4428 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4430 ChardevBackendInfoList *backend_list = NULL;
4431 const CharDriver *c;
4432 int i;
4434 for (i = 0; i < ARRAY_SIZE(backends); i++) {
4435 c = backends[i];
4436 if (!c) {
4437 continue;
4440 backend_list = qmp_prepend_backend(backend_list,
4441 ChardevBackendKind_lookup[c->kind]);
4442 if (c->alias) {
4443 backend_list = qmp_prepend_backend(backend_list, c->alias);
4447 return backend_list;
4450 Chardev *qemu_chr_find(const char *name)
4452 Chardev *chr;
4454 QTAILQ_FOREACH(chr, &chardevs, next) {
4455 if (strcmp(chr->label, name) != 0)
4456 continue;
4457 return chr;
4459 return NULL;
4462 QemuOptsList qemu_chardev_opts = {
4463 .name = "chardev",
4464 .implied_opt_name = "backend",
4465 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4466 .desc = {
4468 .name = "backend",
4469 .type = QEMU_OPT_STRING,
4471 .name = "path",
4472 .type = QEMU_OPT_STRING,
4474 .name = "host",
4475 .type = QEMU_OPT_STRING,
4477 .name = "port",
4478 .type = QEMU_OPT_STRING,
4480 .name = "localaddr",
4481 .type = QEMU_OPT_STRING,
4483 .name = "localport",
4484 .type = QEMU_OPT_STRING,
4486 .name = "to",
4487 .type = QEMU_OPT_NUMBER,
4489 .name = "ipv4",
4490 .type = QEMU_OPT_BOOL,
4492 .name = "ipv6",
4493 .type = QEMU_OPT_BOOL,
4495 .name = "wait",
4496 .type = QEMU_OPT_BOOL,
4498 .name = "server",
4499 .type = QEMU_OPT_BOOL,
4501 .name = "delay",
4502 .type = QEMU_OPT_BOOL,
4504 .name = "reconnect",
4505 .type = QEMU_OPT_NUMBER,
4507 .name = "telnet",
4508 .type = QEMU_OPT_BOOL,
4510 .name = "tls-creds",
4511 .type = QEMU_OPT_STRING,
4513 .name = "width",
4514 .type = QEMU_OPT_NUMBER,
4516 .name = "height",
4517 .type = QEMU_OPT_NUMBER,
4519 .name = "cols",
4520 .type = QEMU_OPT_NUMBER,
4522 .name = "rows",
4523 .type = QEMU_OPT_NUMBER,
4525 .name = "mux",
4526 .type = QEMU_OPT_BOOL,
4528 .name = "signal",
4529 .type = QEMU_OPT_BOOL,
4531 .name = "name",
4532 .type = QEMU_OPT_STRING,
4534 .name = "debug",
4535 .type = QEMU_OPT_NUMBER,
4537 .name = "size",
4538 .type = QEMU_OPT_SIZE,
4540 .name = "chardev",
4541 .type = QEMU_OPT_STRING,
4543 .name = "append",
4544 .type = QEMU_OPT_BOOL,
4546 .name = "logfile",
4547 .type = QEMU_OPT_STRING,
4549 .name = "logappend",
4550 .type = QEMU_OPT_BOOL,
4552 { /* end of list */ }
4556 #ifdef _WIN32
4558 static void qmp_chardev_open_file(Chardev *chr,
4559 ChardevBackend *backend,
4560 bool *be_opened,
4561 Error **errp)
4563 ChardevFile *file = backend->u.file.data;
4564 HANDLE out;
4565 DWORD accessmode;
4566 DWORD flags;
4568 if (file->has_in) {
4569 error_setg(errp, "input file not supported");
4570 return;
4573 if (file->has_append && file->append) {
4574 /* Append to file if it already exists. */
4575 accessmode = FILE_GENERIC_WRITE & ~FILE_WRITE_DATA;
4576 flags = OPEN_ALWAYS;
4577 } else {
4578 /* Truncate file if it already exists. */
4579 accessmode = GENERIC_WRITE;
4580 flags = CREATE_ALWAYS;
4583 out = CreateFile(file->out, accessmode, FILE_SHARE_READ, NULL, flags,
4584 FILE_ATTRIBUTE_NORMAL, NULL);
4585 if (out == INVALID_HANDLE_VALUE) {
4586 error_setg(errp, "open %s failed", file->out);
4587 return;
4590 qemu_chr_open_win_file(chr, out);
4593 static void qmp_chardev_open_serial(Chardev *chr,
4594 ChardevBackend *backend,
4595 bool *be_opened,
4596 Error **errp)
4598 ChardevHostdev *serial = backend->u.serial.data;
4600 win_chr_init(chr, serial->device, errp);
4603 #else /* WIN32 */
4605 static int qmp_chardev_open_file_source(char *src, int flags,
4606 Error **errp)
4608 int fd = -1;
4610 TFR(fd = qemu_open(src, flags, 0666));
4611 if (fd == -1) {
4612 error_setg_file_open(errp, errno, src);
4614 return fd;
4617 static void qmp_chardev_open_file(Chardev *chr,
4618 ChardevBackend *backend,
4619 bool *be_opened,
4620 Error **errp)
4622 ChardevFile *file = backend->u.file.data;
4623 int flags, in = -1, out;
4625 flags = O_WRONLY | O_CREAT | O_BINARY;
4626 if (file->has_append && file->append) {
4627 flags |= O_APPEND;
4628 } else {
4629 flags |= O_TRUNC;
4632 out = qmp_chardev_open_file_source(file->out, flags, errp);
4633 if (out < 0) {
4634 return;
4637 if (file->has_in) {
4638 flags = O_RDONLY;
4639 in = qmp_chardev_open_file_source(file->in, flags, errp);
4640 if (in < 0) {
4641 qemu_close(out);
4642 return;
4646 qemu_chr_open_fd(chr, in, out);
4649 #ifdef HAVE_CHARDEV_SERIAL
4650 static void qmp_chardev_open_serial(Chardev *chr,
4651 ChardevBackend *backend,
4652 bool *be_opened,
4653 Error **errp)
4655 ChardevHostdev *serial = backend->u.serial.data;
4656 int fd;
4658 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4659 if (fd < 0) {
4660 return;
4662 qemu_set_nonblock(fd);
4663 tty_serial_init(fd, 115200, 'N', 8, 1);
4665 qemu_chr_open_fd(chr, fd, fd);
4667 #endif
4669 #ifdef HAVE_CHARDEV_PARPORT
4670 static void qmp_chardev_open_parallel(Chardev *chr,
4671 ChardevBackend *backend,
4672 bool *be_opened,
4673 Error **errp)
4675 ChardevHostdev *parallel = backend->u.parallel.data;
4676 int fd;
4678 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4679 if (fd < 0) {
4680 return;
4682 qemu_chr_open_pp_fd(chr, fd, be_opened, errp);
4685 static const CharDriver parallel_driver = {
4686 .kind = CHARDEV_BACKEND_KIND_PARALLEL,
4687 .alias = "parport",
4688 .parse = qemu_chr_parse_parallel,
4691 static void char_parallel_class_init(ObjectClass *oc, void *data)
4693 ChardevClass *cc = CHARDEV_CLASS(oc);
4695 cc->open = qmp_chardev_open_parallel;
4696 #if defined(__linux__)
4697 cc->chr_write = null_chr_write;
4698 cc->chr_ioctl = pp_ioctl;
4699 cc->chr_free = pp_free;
4700 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
4701 /* FIXME: no chr_free */
4702 cc->chr_write = null_chr_write;
4703 cc->chr_ioctl = pp_ioctl;
4704 #endif
4707 static const TypeInfo char_parallel_type_info = {
4708 .name = TYPE_CHARDEV_PARALLEL,
4709 .parent = TYPE_CHARDEV,
4710 .instance_size = sizeof(ParallelChardev),
4711 .class_init = char_parallel_class_init,
4713 #endif
4715 #endif /* WIN32 */
4717 static const CharDriver file_driver = {
4718 .kind = CHARDEV_BACKEND_KIND_FILE,
4719 .parse = qemu_chr_parse_file_out,
4722 static void char_file_class_init(ObjectClass *oc, void *data)
4724 ChardevClass *cc = CHARDEV_CLASS(oc);
4726 cc->open = qmp_chardev_open_file;
4727 #ifdef _WIN32
4728 /* FIXME: no chr_free */
4729 cc->chr_free = NULL;
4730 #endif
4733 static const TypeInfo char_file_type_info = {
4734 .name = TYPE_CHARDEV_FILE,
4735 #ifdef _WIN32
4736 .parent = TYPE_CHARDEV_WIN,
4737 #else
4738 .parent = TYPE_CHARDEV_FD,
4739 #endif
4740 .class_init = char_file_class_init,
4743 #ifdef HAVE_CHARDEV_SERIAL
4745 static const CharDriver serial_driver = {
4746 .kind = CHARDEV_BACKEND_KIND_SERIAL,
4747 .alias = "tty",
4748 .parse = qemu_chr_parse_serial,
4751 static void char_serial_class_init(ObjectClass *oc, void *data)
4753 ChardevClass *cc = CHARDEV_CLASS(oc);
4755 cc->open = qmp_chardev_open_serial;
4756 #ifndef _WIN32
4757 cc->chr_ioctl = tty_serial_ioctl;
4758 cc->chr_free = qemu_chr_free_tty;
4759 #endif
4762 static const TypeInfo char_serial_type_info = {
4763 .name = TYPE_CHARDEV_SERIAL,
4764 #ifdef _WIN32
4765 .parent = TYPE_CHARDEV_WIN,
4766 #else
4767 .parent = TYPE_CHARDEV_FD,
4768 #endif
4769 .class_init = char_serial_class_init,
4771 #endif
4773 static gboolean socket_reconnect_timeout(gpointer opaque)
4775 Chardev *chr = CHARDEV(opaque);
4776 SocketChardev *s = SOCKET_CHARDEV(opaque);
4777 QIOChannelSocket *sioc;
4779 s->reconnect_timer = 0;
4781 if (chr->be_open) {
4782 return false;
4785 sioc = qio_channel_socket_new();
4786 tcp_chr_set_client_ioc_name(chr, sioc);
4787 qio_channel_socket_connect_async(sioc, s->addr,
4788 qemu_chr_socket_connected,
4789 chr, NULL);
4791 return false;
4794 static void qmp_chardev_open_socket(Chardev *chr,
4795 ChardevBackend *backend,
4796 bool *be_opened,
4797 Error **errp)
4799 SocketChardev *s = SOCKET_CHARDEV(chr);
4800 ChardevSocket *sock = backend->u.socket.data;
4801 SocketAddress *addr = sock->addr;
4802 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4803 bool is_listen = sock->has_server ? sock->server : true;
4804 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4805 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4806 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4807 QIOChannelSocket *sioc = NULL;
4809 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4810 s->is_listen = is_listen;
4811 s->is_telnet = is_telnet;
4812 s->do_nodelay = do_nodelay;
4813 if (sock->tls_creds) {
4814 Object *creds;
4815 creds = object_resolve_path_component(
4816 object_get_objects_root(), sock->tls_creds);
4817 if (!creds) {
4818 error_setg(errp, "No TLS credentials with id '%s'",
4819 sock->tls_creds);
4820 goto error;
4822 s->tls_creds = (QCryptoTLSCreds *)
4823 object_dynamic_cast(creds,
4824 TYPE_QCRYPTO_TLS_CREDS);
4825 if (!s->tls_creds) {
4826 error_setg(errp, "Object with id '%s' is not TLS credentials",
4827 sock->tls_creds);
4828 goto error;
4830 object_ref(OBJECT(s->tls_creds));
4831 if (is_listen) {
4832 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4833 error_setg(errp, "%s",
4834 "Expected TLS credentials for server endpoint");
4835 goto error;
4837 } else {
4838 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4839 error_setg(errp, "%s",
4840 "Expected TLS credentials for client endpoint");
4841 goto error;
4846 s->addr = QAPI_CLONE(SocketAddress, sock->addr);
4848 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_RECONNECTABLE);
4849 if (s->is_unix) {
4850 qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_FD_PASS);
4853 /* be isn't opened until we get a connection */
4854 *be_opened = false;
4856 chr->filename = SocketAddress_to_str("disconnected:",
4857 addr, is_listen, is_telnet);
4859 if (is_listen) {
4860 if (is_telnet) {
4861 s->do_telnetopt = 1;
4863 } else if (reconnect > 0) {
4864 s->reconnect_time = reconnect;
4867 if (s->reconnect_time) {
4868 sioc = qio_channel_socket_new();
4869 tcp_chr_set_client_ioc_name(chr, sioc);
4870 qio_channel_socket_connect_async(sioc, s->addr,
4871 qemu_chr_socket_connected,
4872 chr, NULL);
4873 } else {
4874 if (s->is_listen) {
4875 char *name;
4876 sioc = qio_channel_socket_new();
4878 name = g_strdup_printf("chardev-tcp-listener-%s", chr->label);
4879 qio_channel_set_name(QIO_CHANNEL(sioc), name);
4880 g_free(name);
4882 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4883 goto error;
4885 s->listen_ioc = sioc;
4886 if (is_waitconnect &&
4887 qemu_chr_wait_connected(chr, errp) < 0) {
4888 goto error;
4890 if (!s->ioc) {
4891 s->listen_tag = qio_channel_add_watch(
4892 QIO_CHANNEL(s->listen_ioc), G_IO_IN,
4893 tcp_chr_accept, chr, NULL);
4895 } else if (qemu_chr_wait_connected(chr, errp) < 0) {
4896 goto error;
4900 return;
4902 error:
4903 if (sioc) {
4904 object_unref(OBJECT(sioc));
4906 if (s->tls_creds) {
4907 object_unref(OBJECT(s->tls_creds));
4911 static const CharDriver socket_driver = {
4912 .kind = CHARDEV_BACKEND_KIND_SOCKET,
4913 .parse = qemu_chr_parse_socket,
4916 static void char_socket_class_init(ObjectClass *oc, void *data)
4918 ChardevClass *cc = CHARDEV_CLASS(oc);
4920 cc->open = qmp_chardev_open_socket;
4921 cc->chr_wait_connected = tcp_chr_wait_connected;
4922 cc->chr_write = tcp_chr_write;
4923 cc->chr_sync_read = tcp_chr_sync_read;
4924 cc->chr_disconnect = tcp_chr_disconnect;
4925 cc->get_msgfds = tcp_get_msgfds;
4926 cc->set_msgfds = tcp_set_msgfds;
4927 cc->chr_add_client = tcp_chr_add_client;
4928 cc->chr_add_watch = tcp_chr_add_watch;
4929 cc->chr_update_read_handler = tcp_chr_update_read_handler;
4930 cc->chr_free = tcp_chr_free;
4933 static const TypeInfo char_socket_type_info = {
4934 .name = TYPE_CHARDEV_SOCKET,
4935 .parent = TYPE_CHARDEV,
4936 .instance_size = sizeof(SocketChardev),
4937 .class_init = char_socket_class_init,
4940 static void qmp_chardev_open_udp(Chardev *chr,
4941 ChardevBackend *backend,
4942 bool *be_opened,
4943 Error **errp)
4945 ChardevUdp *udp = backend->u.udp.data;
4946 QIOChannelSocket *sioc = qio_channel_socket_new();
4947 char *name;
4948 UdpChardev *s = UDP_CHARDEV(chr);
4950 if (qio_channel_socket_dgram_sync(sioc,
4951 udp->local, udp->remote,
4952 errp) < 0) {
4953 object_unref(OBJECT(sioc));
4954 return;
4957 name = g_strdup_printf("chardev-udp-%s", chr->label);
4958 qio_channel_set_name(QIO_CHANNEL(sioc), name);
4959 g_free(name);
4961 s->ioc = QIO_CHANNEL(sioc);
4962 /* be isn't opened until we get a connection */
4963 *be_opened = false;
4966 static const CharDriver udp_driver = {
4967 .kind = CHARDEV_BACKEND_KIND_UDP,
4968 .parse = qemu_chr_parse_udp,
4971 static void char_udp_class_init(ObjectClass *oc, void *data)
4973 ChardevClass *cc = CHARDEV_CLASS(oc);
4975 cc->open = qmp_chardev_open_udp;
4976 cc->chr_write = udp_chr_write;
4977 cc->chr_update_read_handler = udp_chr_update_read_handler;
4978 cc->chr_free = udp_chr_free;
4981 static const TypeInfo char_udp_type_info = {
4982 .name = TYPE_CHARDEV_UDP,
4983 .parent = TYPE_CHARDEV,
4984 .instance_size = sizeof(UdpChardev),
4985 .class_init = char_udp_class_init,
4988 bool qemu_chr_has_feature(Chardev *chr,
4989 CharDriverFeature feature)
4991 return test_bit(feature, chr->features);
4994 void qemu_chr_set_feature(Chardev *chr,
4995 CharDriverFeature feature)
4997 return set_bit(feature, chr->features);
5000 static const ChardevClass *char_get_class(const char *driver, Error **errp)
5002 ObjectClass *oc;
5003 const ChardevClass *cc;
5004 char *typename = g_strdup_printf("chardev-%s", driver);
5006 oc = object_class_by_name(typename);
5007 g_free(typename);
5009 if (!object_class_dynamic_cast(oc, TYPE_CHARDEV)) {
5010 error_setg(errp, "'%s' is not a valid char driver name", driver);
5011 return NULL;
5014 if (object_class_is_abstract(oc)) {
5015 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "driver",
5016 "abstract device type");
5017 return NULL;
5020 cc = CHARDEV_CLASS(oc);
5021 if (cc->internal) {
5022 error_setg(errp, "'%s' is not a valid char driver name", driver);
5023 return NULL;
5026 return cc;
5029 Chardev *qemu_chardev_new(const char *id, const char *typename,
5030 ChardevBackend *backend, Error **errp)
5032 Chardev *chr = NULL;
5033 Error *local_err = NULL;
5034 bool be_opened = true;
5036 assert(g_str_has_prefix(typename, "chardev-"));
5038 chr = CHARDEV(object_new(typename));
5039 chr->label = g_strdup(id);
5041 qemu_char_open(chr, backend, &be_opened, &local_err);
5042 if (local_err) {
5043 error_propagate(errp, local_err);
5044 object_unref(OBJECT(chr));
5045 return NULL;
5048 if (!chr->filename) {
5049 chr->filename = g_strdup(typename + 8);
5051 if (be_opened) {
5052 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
5055 return chr;
5058 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
5059 Error **errp)
5061 const ChardevClass *cc;
5062 ChardevReturn *ret;
5063 Chardev *chr;
5065 chr = qemu_chr_find(id);
5066 if (chr) {
5067 error_setg(errp, "Chardev '%s' already exists", id);
5068 return NULL;
5071 cc = char_get_class(ChardevBackendKind_lookup[backend->type], errp);
5072 if (!cc) {
5073 return NULL;
5076 chr = qemu_chardev_new(id, object_class_get_name(OBJECT_CLASS(cc)),
5077 backend, errp);
5078 if (!chr) {
5079 return NULL;
5082 ret = g_new0(ChardevReturn, 1);
5083 if (CHARDEV_IS_PTY(chr)) {
5084 ret->pty = g_strdup(chr->filename + 4);
5085 ret->has_pty = true;
5088 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
5089 return ret;
5092 void qmp_chardev_remove(const char *id, Error **errp)
5094 Chardev *chr;
5096 chr = qemu_chr_find(id);
5097 if (chr == NULL) {
5098 error_setg(errp, "Chardev '%s' not found", id);
5099 return;
5101 if (qemu_chr_is_busy(chr)) {
5102 error_setg(errp, "Chardev '%s' is busy", id);
5103 return;
5105 if (qemu_chr_replay(chr)) {
5106 error_setg(errp,
5107 "Chardev '%s' cannot be unplugged in record/replay mode", id);
5108 return;
5110 qemu_chr_delete(chr);
5113 void qemu_chr_cleanup(void)
5115 Chardev *chr, *tmp;
5117 QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
5118 qemu_chr_delete(chr);
5122 static void register_types(void)
5124 static const struct {
5125 const CharDriver *driver;
5126 const TypeInfo *type;
5127 } chardevs[] = {
5128 { &null_driver, &char_null_type_info },
5129 { &socket_driver, &char_socket_type_info },
5130 { &udp_driver, &char_udp_type_info },
5131 { &ringbuf_driver, &char_ringbuf_type_info },
5132 { &file_driver, &char_file_type_info },
5133 { &stdio_driver, &char_stdio_type_info },
5134 #ifdef HAVE_CHARDEV_SERIAL
5135 { &serial_driver, &char_serial_type_info },
5136 #endif
5137 #ifdef HAVE_CHARDEV_PARPORT
5138 { &parallel_driver, &char_parallel_type_info },
5139 #endif
5140 #ifdef HAVE_CHARDEV_PTY
5141 { &pty_driver, &char_pty_type_info },
5142 #endif
5143 #ifdef _WIN32
5144 { &console_driver, &char_console_type_info },
5145 #endif
5146 { &pipe_driver, &char_pipe_type_info },
5147 { &mux_driver, &char_mux_type_info },
5148 { &memory_driver, &char_memory_type_info }
5150 int i;
5152 type_register_static(&char_type_info);
5153 #ifndef _WIN32
5154 type_register_static(&char_fd_type_info);
5155 #else
5156 type_register_static(&char_win_type_info);
5157 type_register_static(&char_win_stdio_type_info);
5158 #endif
5159 for (i = 0; i < ARRAY_SIZE(chardevs); i++) {
5160 type_register_static(chardevs[i].type);
5161 register_char_driver(chardevs[i].driver);
5164 /* this must be done after machine init, since we register FEs with muxes
5165 * as part of realize functions like serial_isa_realizefn when -nographic
5166 * is specified
5168 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
5171 type_init(register_types);