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