nbd: Switch .bdrv_co_discard() to byte-based
[qemu/ar7.git] / qemu-char.c
blobe4b8448422918ded183a28b2a7b9671b5d421989
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
25 #include "qemu-common.h"
26 #include "qemu/cutils.h"
27 #include "monitor/monitor.h"
28 #include "sysemu/sysemu.h"
29 #include "sysemu/block-backend.h"
30 #include "qemu/error-report.h"
31 #include "qemu/timer.h"
32 #include "sysemu/char.h"
33 #include "hw/usb.h"
34 #include "qmp-commands.h"
35 #include "qapi/clone-visitor.h"
36 #include "qapi-visit.h"
37 #include "qemu/base64.h"
38 #include "io/channel-socket.h"
39 #include "io/channel-file.h"
40 #include "io/channel-tls.h"
41 #include "sysemu/replay.h"
43 #include <zlib.h>
45 #ifndef _WIN32
46 #include <sys/times.h>
47 #include <sys/wait.h>
48 #include <termios.h>
49 #include <sys/ioctl.h>
50 #include <sys/resource.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <net/if.h>
54 #include <arpa/inet.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef CONFIG_BSD
58 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
59 #include <dev/ppbus/ppi.h>
60 #include <dev/ppbus/ppbconf.h>
61 #elif defined(__DragonFly__)
62 #include <dev/misc/ppi/ppi.h>
63 #include <bus/ppbus/ppbconf.h>
64 #endif
65 #else
66 #ifdef __linux__
67 #include <linux/ppdev.h>
68 #include <linux/parport.h>
69 #endif
70 #ifdef __sun__
71 #include <sys/ethernet.h>
72 #include <sys/sockio.h>
73 #include <netinet/arp.h>
74 #include <netinet/in.h>
75 #include <netinet/in_systm.h>
76 #include <netinet/ip.h>
77 #include <netinet/ip_icmp.h> // must come after ip.h
78 #include <netinet/udp.h>
79 #include <netinet/tcp.h>
80 #endif
81 #endif
82 #endif
84 #include "qemu/sockets.h"
85 #include "ui/qemu-spice.h"
87 #define READ_BUF_LEN 4096
88 #define READ_RETRIES 10
89 #define TCP_MAX_FDS 16
91 /***********************************************************/
92 /* Socket address helpers */
94 static char *SocketAddress_to_str(const char *prefix, SocketAddress *addr,
95 bool is_listen, bool is_telnet)
97 switch (addr->type) {
98 case SOCKET_ADDRESS_KIND_INET:
99 return g_strdup_printf("%s%s:%s:%s%s", prefix,
100 is_telnet ? "telnet" : "tcp",
101 addr->u.inet.data->host,
102 addr->u.inet.data->port,
103 is_listen ? ",server" : "");
104 break;
105 case SOCKET_ADDRESS_KIND_UNIX:
106 return g_strdup_printf("%sunix:%s%s", prefix,
107 addr->u.q_unix.data->path,
108 is_listen ? ",server" : "");
109 break;
110 case SOCKET_ADDRESS_KIND_FD:
111 return g_strdup_printf("%sfd:%s%s", prefix, addr->u.fd.data->str,
112 is_listen ? ",server" : "");
113 break;
114 default:
115 abort();
119 static char *sockaddr_to_str(struct sockaddr_storage *ss, socklen_t ss_len,
120 struct sockaddr_storage *ps, socklen_t ps_len,
121 bool is_listen, bool is_telnet)
123 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
124 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
125 const char *left = "", *right = "";
127 switch (ss->ss_family) {
128 #ifndef _WIN32
129 case AF_UNIX:
130 return g_strdup_printf("unix:%s%s",
131 ((struct sockaddr_un *)(ss))->sun_path,
132 is_listen ? ",server" : "");
133 #endif
134 case AF_INET6:
135 left = "[";
136 right = "]";
137 /* fall through */
138 case AF_INET:
139 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
140 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
141 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
142 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
143 return g_strdup_printf("%s:%s%s%s:%s%s <-> %s%s%s:%s",
144 is_telnet ? "telnet" : "tcp",
145 left, shost, right, sserv,
146 is_listen ? ",server" : "",
147 left, phost, right, pserv);
149 default:
150 return g_strdup_printf("unknown");
154 /***********************************************************/
155 /* character device */
157 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
158 QTAILQ_HEAD_INITIALIZER(chardevs);
160 static void qemu_chr_free_common(CharDriverState *chr);
162 CharDriverState *qemu_chr_alloc(ChardevCommon *backend, Error **errp)
164 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
165 qemu_mutex_init(&chr->chr_write_lock);
167 if (backend->has_logfile) {
168 int flags = O_WRONLY | O_CREAT;
169 if (backend->has_logappend &&
170 backend->logappend) {
171 flags |= O_APPEND;
172 } else {
173 flags |= O_TRUNC;
175 chr->logfd = qemu_open(backend->logfile, flags, 0666);
176 if (chr->logfd < 0) {
177 error_setg_errno(errp, errno,
178 "Unable to open logfile %s",
179 backend->logfile);
180 g_free(chr);
181 return NULL;
183 } else {
184 chr->logfd = -1;
187 return chr;
190 void qemu_chr_be_event(CharDriverState *s, int event)
192 /* Keep track if the char device is open */
193 switch (event) {
194 case CHR_EVENT_OPENED:
195 s->be_open = 1;
196 break;
197 case CHR_EVENT_CLOSED:
198 s->be_open = 0;
199 break;
202 if (!s->chr_event)
203 return;
204 s->chr_event(s->handler_opaque, event);
207 void qemu_chr_be_generic_open(CharDriverState *s)
209 qemu_chr_be_event(s, CHR_EVENT_OPENED);
213 /* Not reporting errors from writing to logfile, as logs are
214 * defined to be "best effort" only */
215 static void qemu_chr_fe_write_log(CharDriverState *s,
216 const uint8_t *buf, size_t len)
218 size_t done = 0;
219 ssize_t ret;
221 if (s->logfd < 0) {
222 return;
225 while (done < len) {
226 retry:
227 ret = write(s->logfd, buf + done, len - done);
228 if (ret == -1 && errno == EAGAIN) {
229 g_usleep(100);
230 goto retry;
233 if (ret <= 0) {
234 return;
236 done += ret;
240 static int qemu_chr_fe_write_buffer(CharDriverState *s, const uint8_t *buf, int len, int *offset)
242 int res = 0;
243 *offset = 0;
245 qemu_mutex_lock(&s->chr_write_lock);
246 while (*offset < len) {
247 retry:
248 res = s->chr_write(s, buf + *offset, len - *offset);
249 if (res < 0 && errno == EAGAIN) {
250 g_usleep(100);
251 goto retry;
254 if (res <= 0) {
255 break;
258 *offset += res;
260 if (*offset > 0) {
261 qemu_chr_fe_write_log(s, buf, *offset);
263 qemu_mutex_unlock(&s->chr_write_lock);
265 return res;
268 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
270 int ret;
272 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
273 int offset;
274 replay_char_write_event_load(&ret, &offset);
275 assert(offset <= len);
276 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
277 return ret;
280 qemu_mutex_lock(&s->chr_write_lock);
281 ret = s->chr_write(s, buf, len);
283 if (ret > 0) {
284 qemu_chr_fe_write_log(s, buf, ret);
287 qemu_mutex_unlock(&s->chr_write_lock);
289 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
290 replay_char_write_event_save(ret, ret < 0 ? 0 : ret);
293 return ret;
296 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
298 int offset;
299 int res;
301 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
302 replay_char_write_event_load(&res, &offset);
303 assert(offset <= len);
304 qemu_chr_fe_write_buffer(s, buf, offset, &offset);
305 return res;
308 res = qemu_chr_fe_write_buffer(s, buf, len, &offset);
310 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
311 replay_char_write_event_save(res, offset);
314 if (res < 0) {
315 return res;
317 return offset;
320 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
322 int offset = 0, counter = 10;
323 int res;
325 if (!s->chr_sync_read) {
326 return 0;
329 if (s->replay && replay_mode == REPLAY_MODE_PLAY) {
330 return replay_char_read_all_load(buf);
333 while (offset < len) {
334 retry:
335 res = s->chr_sync_read(s, buf + offset, len - offset);
336 if (res == -1 && errno == EAGAIN) {
337 g_usleep(100);
338 goto retry;
341 if (res == 0) {
342 break;
345 if (res < 0) {
346 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
347 replay_char_read_all_save_error(res);
349 return res;
352 offset += res;
354 if (!counter--) {
355 break;
359 if (s->replay && replay_mode == REPLAY_MODE_RECORD) {
360 replay_char_read_all_save_buf(buf, offset);
362 return offset;
365 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
367 int res;
368 if (!s->chr_ioctl || s->replay) {
369 res = -ENOTSUP;
370 } else {
371 res = s->chr_ioctl(s, cmd, arg);
374 return res;
377 int qemu_chr_be_can_write(CharDriverState *s)
379 if (!s->chr_can_read)
380 return 0;
381 return s->chr_can_read(s->handler_opaque);
384 void qemu_chr_be_write_impl(CharDriverState *s, uint8_t *buf, int len)
386 if (s->chr_read) {
387 s->chr_read(s->handler_opaque, buf, len);
391 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
393 if (s->replay) {
394 if (replay_mode == REPLAY_MODE_PLAY) {
395 return;
397 replay_chr_be_write(s, buf, len);
398 } else {
399 qemu_chr_be_write_impl(s, buf, len);
403 int qemu_chr_fe_get_msgfd(CharDriverState *s)
405 int fd;
406 int res = (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
407 if (s->replay) {
408 fprintf(stderr,
409 "Replay: get msgfd is not supported for serial devices yet\n");
410 exit(1);
412 return res;
415 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
417 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
420 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
422 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
425 int qemu_chr_add_client(CharDriverState *s, int fd)
427 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
430 void qemu_chr_accept_input(CharDriverState *s)
432 if (s->chr_accept_input)
433 s->chr_accept_input(s);
434 qemu_notify_event();
437 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
439 char buf[READ_BUF_LEN];
440 va_list ap;
441 va_start(ap, fmt);
442 vsnprintf(buf, sizeof(buf), fmt, ap);
443 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
444 va_end(ap);
447 static void remove_fd_in_watch(CharDriverState *chr);
449 void qemu_chr_add_handlers(CharDriverState *s,
450 IOCanReadHandler *fd_can_read,
451 IOReadHandler *fd_read,
452 IOEventHandler *fd_event,
453 void *opaque)
455 int fe_open;
457 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
458 fe_open = 0;
459 remove_fd_in_watch(s);
460 } else {
461 fe_open = 1;
463 s->chr_can_read = fd_can_read;
464 s->chr_read = fd_read;
465 s->chr_event = fd_event;
466 s->handler_opaque = opaque;
467 if (fe_open && s->chr_update_read_handler)
468 s->chr_update_read_handler(s);
470 if (!s->explicit_fe_open) {
471 qemu_chr_fe_set_open(s, fe_open);
474 /* We're connecting to an already opened device, so let's make sure we
475 also get the open event */
476 if (fe_open && s->be_open) {
477 qemu_chr_be_generic_open(s);
481 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
483 return len;
486 static CharDriverState *qemu_chr_open_null(const char *id,
487 ChardevBackend *backend,
488 ChardevReturn *ret,
489 Error **errp)
491 CharDriverState *chr;
492 ChardevCommon *common = backend->u.null.data;
494 chr = qemu_chr_alloc(common, errp);
495 if (!chr) {
496 return NULL;
498 chr->chr_write = null_chr_write;
499 chr->explicit_be_open = true;
500 return chr;
503 /* MUX driver for serial I/O splitting */
504 #define MAX_MUX 4
505 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
506 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
507 typedef struct {
508 IOCanReadHandler *chr_can_read[MAX_MUX];
509 IOReadHandler *chr_read[MAX_MUX];
510 IOEventHandler *chr_event[MAX_MUX];
511 void *ext_opaque[MAX_MUX];
512 CharDriverState *drv;
513 int focus;
514 int mux_cnt;
515 int term_got_escape;
516 int max_size;
517 /* Intermediate input buffer allows to catch escape sequences even if the
518 currently active device is not accepting any input - but only until it
519 is full as well. */
520 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
521 int prod[MAX_MUX];
522 int cons[MAX_MUX];
523 int timestamps;
525 /* Protected by the CharDriverState chr_write_lock. */
526 int linestart;
527 int64_t timestamps_start;
528 } MuxDriver;
531 /* Called with chr_write_lock held. */
532 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
534 MuxDriver *d = chr->opaque;
535 int ret;
536 if (!d->timestamps) {
537 ret = qemu_chr_fe_write(d->drv, buf, len);
538 } else {
539 int i;
541 ret = 0;
542 for (i = 0; i < len; i++) {
543 if (d->linestart) {
544 char buf1[64];
545 int64_t ti;
546 int secs;
548 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
549 if (d->timestamps_start == -1)
550 d->timestamps_start = ti;
551 ti -= d->timestamps_start;
552 secs = ti / 1000;
553 snprintf(buf1, sizeof(buf1),
554 "[%02d:%02d:%02d.%03d] ",
555 secs / 3600,
556 (secs / 60) % 60,
557 secs % 60,
558 (int)(ti % 1000));
559 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
560 d->linestart = 0;
562 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
563 if (buf[i] == '\n') {
564 d->linestart = 1;
568 return ret;
571 static const char * const mux_help[] = {
572 "% h print this help\n\r",
573 "% x exit emulator\n\r",
574 "% s save disk data back to file (if -snapshot)\n\r",
575 "% t toggle console timestamps\n\r",
576 "% b send break (magic sysrq)\n\r",
577 "% c switch between console and monitor\n\r",
578 "% % sends %\n\r",
579 NULL
582 int term_escape_char = 0x01; /* ctrl-a is used for escape */
583 static void mux_print_help(CharDriverState *chr)
585 int i, j;
586 char ebuf[15] = "Escape-Char";
587 char cbuf[50] = "\n\r";
589 if (term_escape_char > 0 && term_escape_char < 26) {
590 snprintf(cbuf, sizeof(cbuf), "\n\r");
591 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
592 } else {
593 snprintf(cbuf, sizeof(cbuf),
594 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
595 term_escape_char);
597 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
598 for (i = 0; mux_help[i] != NULL; i++) {
599 for (j=0; mux_help[i][j] != '\0'; j++) {
600 if (mux_help[i][j] == '%')
601 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
602 else
603 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
608 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
610 if (d->chr_event[mux_nr])
611 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
614 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
616 if (d->term_got_escape) {
617 d->term_got_escape = 0;
618 if (ch == term_escape_char)
619 goto send_char;
620 switch(ch) {
621 case '?':
622 case 'h':
623 mux_print_help(chr);
624 break;
625 case 'x':
627 const char *term = "QEMU: Terminated\n\r";
628 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
629 exit(0);
630 break;
632 case 's':
633 blk_commit_all();
634 break;
635 case 'b':
636 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
637 break;
638 case 'c':
639 /* Switch to the next registered device */
640 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
641 d->focus++;
642 if (d->focus >= d->mux_cnt)
643 d->focus = 0;
644 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
645 break;
646 case 't':
647 d->timestamps = !d->timestamps;
648 d->timestamps_start = -1;
649 d->linestart = 0;
650 break;
652 } else if (ch == term_escape_char) {
653 d->term_got_escape = 1;
654 } else {
655 send_char:
656 return 1;
658 return 0;
661 static void mux_chr_accept_input(CharDriverState *chr)
663 MuxDriver *d = chr->opaque;
664 int m = d->focus;
666 while (d->prod[m] != d->cons[m] &&
667 d->chr_can_read[m] &&
668 d->chr_can_read[m](d->ext_opaque[m])) {
669 d->chr_read[m](d->ext_opaque[m],
670 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
674 static int mux_chr_can_read(void *opaque)
676 CharDriverState *chr = opaque;
677 MuxDriver *d = chr->opaque;
678 int m = d->focus;
680 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
681 return 1;
682 if (d->chr_can_read[m])
683 return d->chr_can_read[m](d->ext_opaque[m]);
684 return 0;
687 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
689 CharDriverState *chr = opaque;
690 MuxDriver *d = chr->opaque;
691 int m = d->focus;
692 int i;
694 mux_chr_accept_input (opaque);
696 for(i = 0; i < size; i++)
697 if (mux_proc_byte(chr, d, buf[i])) {
698 if (d->prod[m] == d->cons[m] &&
699 d->chr_can_read[m] &&
700 d->chr_can_read[m](d->ext_opaque[m]))
701 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
702 else
703 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
707 static void mux_chr_event(void *opaque, int event)
709 CharDriverState *chr = opaque;
710 MuxDriver *d = chr->opaque;
711 int i;
713 /* Send the event to all registered listeners */
714 for (i = 0; i < d->mux_cnt; i++)
715 mux_chr_send_event(d, i, event);
718 static void mux_chr_update_read_handler(CharDriverState *chr)
720 MuxDriver *d = chr->opaque;
722 if (d->mux_cnt >= MAX_MUX) {
723 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
724 return;
726 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
727 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
728 d->chr_read[d->mux_cnt] = chr->chr_read;
729 d->chr_event[d->mux_cnt] = chr->chr_event;
730 /* Fix up the real driver with mux routines */
731 if (d->mux_cnt == 0) {
732 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
733 mux_chr_event, chr);
735 if (d->focus != -1) {
736 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
738 d->focus = d->mux_cnt;
739 d->mux_cnt++;
740 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
743 static bool muxes_realized;
746 * Called after processing of default and command-line-specified
747 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
748 * to a mux chardev. This is done here to ensure that
749 * output/prompts/banners are only displayed for the FE that has
750 * focus when initial command-line processing/machine init is
751 * completed.
753 * After this point, any new FE attached to any new or existing
754 * mux will receive CHR_EVENT_OPENED notifications for the BE
755 * immediately.
757 static void muxes_realize_done(Notifier *notifier, void *unused)
759 CharDriverState *chr;
761 QTAILQ_FOREACH(chr, &chardevs, next) {
762 if (chr->is_mux) {
763 MuxDriver *d = chr->opaque;
764 int i;
766 /* send OPENED to all already-attached FEs */
767 for (i = 0; i < d->mux_cnt; i++) {
768 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
770 /* mark mux as OPENED so any new FEs will immediately receive
771 * OPENED event
773 qemu_chr_be_generic_open(chr);
776 muxes_realized = true;
779 static Notifier muxes_realize_notify = {
780 .notify = muxes_realize_done,
783 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
785 MuxDriver *d = s->opaque;
786 return d->drv->chr_add_watch(d->drv, cond);
789 static CharDriverState *qemu_chr_open_mux(const char *id,
790 ChardevBackend *backend,
791 ChardevReturn *ret, Error **errp)
793 ChardevMux *mux = backend->u.mux.data;
794 CharDriverState *chr, *drv;
795 MuxDriver *d;
796 ChardevCommon *common = qapi_ChardevMux_base(mux);
798 drv = qemu_chr_find(mux->chardev);
799 if (drv == NULL) {
800 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
801 return NULL;
804 chr = qemu_chr_alloc(common, errp);
805 if (!chr) {
806 return NULL;
808 d = g_new0(MuxDriver, 1);
810 chr->opaque = d;
811 d->drv = drv;
812 d->focus = -1;
813 chr->chr_write = mux_chr_write;
814 chr->chr_update_read_handler = mux_chr_update_read_handler;
815 chr->chr_accept_input = mux_chr_accept_input;
816 /* Frontend guest-open / -close notification is not support with muxes */
817 chr->chr_set_fe_open = NULL;
818 if (drv->chr_add_watch) {
819 chr->chr_add_watch = mux_chr_add_watch;
821 /* only default to opened state if we've realized the initial
822 * set of muxes
824 chr->explicit_be_open = muxes_realized ? 0 : 1;
825 chr->is_mux = 1;
827 return chr;
831 typedef struct IOWatchPoll
833 GSource parent;
835 QIOChannel *ioc;
836 GSource *src;
838 IOCanReadHandler *fd_can_read;
839 GSourceFunc fd_read;
840 void *opaque;
841 } IOWatchPoll;
843 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
845 return container_of(source, IOWatchPoll, parent);
848 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
850 IOWatchPoll *iwp = io_watch_poll_from_source(source);
851 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
852 bool was_active = iwp->src != NULL;
853 if (was_active == now_active) {
854 return FALSE;
857 if (now_active) {
858 iwp->src = qio_channel_create_watch(
859 iwp->ioc, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
860 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
861 g_source_attach(iwp->src, NULL);
862 } else {
863 g_source_destroy(iwp->src);
864 g_source_unref(iwp->src);
865 iwp->src = NULL;
867 return FALSE;
870 static gboolean io_watch_poll_check(GSource *source)
872 return FALSE;
875 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
876 gpointer user_data)
878 abort();
881 static void io_watch_poll_finalize(GSource *source)
883 /* Due to a glib bug, removing the last reference to a source
884 * inside a finalize callback causes recursive locking (and a
885 * deadlock). This is not a problem inside other callbacks,
886 * including dispatch callbacks, so we call io_remove_watch_poll
887 * to remove this source. At this point, iwp->src must
888 * be NULL, or we would leak it.
890 * This would be solved much more elegantly by child sources,
891 * but we support older glib versions that do not have them.
893 IOWatchPoll *iwp = io_watch_poll_from_source(source);
894 assert(iwp->src == NULL);
897 static GSourceFuncs io_watch_poll_funcs = {
898 .prepare = io_watch_poll_prepare,
899 .check = io_watch_poll_check,
900 .dispatch = io_watch_poll_dispatch,
901 .finalize = io_watch_poll_finalize,
904 /* Can only be used for read */
905 static guint io_add_watch_poll(QIOChannel *ioc,
906 IOCanReadHandler *fd_can_read,
907 QIOChannelFunc fd_read,
908 gpointer user_data)
910 IOWatchPoll *iwp;
911 int tag;
913 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
914 iwp->fd_can_read = fd_can_read;
915 iwp->opaque = user_data;
916 iwp->ioc = ioc;
917 iwp->fd_read = (GSourceFunc) fd_read;
918 iwp->src = NULL;
920 tag = g_source_attach(&iwp->parent, NULL);
921 g_source_unref(&iwp->parent);
922 return tag;
925 static void io_remove_watch_poll(guint tag)
927 GSource *source;
928 IOWatchPoll *iwp;
930 g_return_if_fail (tag > 0);
932 source = g_main_context_find_source_by_id(NULL, tag);
933 g_return_if_fail (source != NULL);
935 iwp = io_watch_poll_from_source(source);
936 if (iwp->src) {
937 g_source_destroy(iwp->src);
938 g_source_unref(iwp->src);
939 iwp->src = NULL;
941 g_source_destroy(&iwp->parent);
944 static void remove_fd_in_watch(CharDriverState *chr)
946 if (chr->fd_in_tag) {
947 io_remove_watch_poll(chr->fd_in_tag);
948 chr->fd_in_tag = 0;
953 static int io_channel_send_full(QIOChannel *ioc,
954 const void *buf, size_t len,
955 int *fds, size_t nfds)
957 size_t offset = 0;
959 while (offset < len) {
960 ssize_t ret = 0;
961 struct iovec iov = { .iov_base = (char *)buf + offset,
962 .iov_len = len - offset };
964 ret = qio_channel_writev_full(
965 ioc, &iov, 1,
966 fds, nfds, NULL);
967 if (ret == QIO_CHANNEL_ERR_BLOCK) {
968 if (offset) {
969 return offset;
972 errno = EAGAIN;
973 return -1;
974 } else if (ret < 0) {
975 errno = EINVAL;
976 return -1;
979 offset += ret;
982 return offset;
986 #ifndef _WIN32
987 static int io_channel_send(QIOChannel *ioc, const void *buf, size_t len)
989 return io_channel_send_full(ioc, buf, len, NULL, 0);
993 typedef struct FDCharDriver {
994 CharDriverState *chr;
995 QIOChannel *ioc_in, *ioc_out;
996 int max_size;
997 } FDCharDriver;
999 /* Called with chr_write_lock held. */
1000 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1002 FDCharDriver *s = chr->opaque;
1004 return io_channel_send(s->ioc_out, buf, len);
1007 static gboolean fd_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1009 CharDriverState *chr = opaque;
1010 FDCharDriver *s = chr->opaque;
1011 int len;
1012 uint8_t buf[READ_BUF_LEN];
1013 ssize_t ret;
1015 len = sizeof(buf);
1016 if (len > s->max_size) {
1017 len = s->max_size;
1019 if (len == 0) {
1020 return TRUE;
1023 ret = qio_channel_read(
1024 chan, (gchar *)buf, len, NULL);
1025 if (ret == 0) {
1026 remove_fd_in_watch(chr);
1027 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1028 return FALSE;
1030 if (ret > 0) {
1031 qemu_chr_be_write(chr, buf, ret);
1034 return TRUE;
1037 static int fd_chr_read_poll(void *opaque)
1039 CharDriverState *chr = opaque;
1040 FDCharDriver *s = chr->opaque;
1042 s->max_size = qemu_chr_be_can_write(chr);
1043 return s->max_size;
1046 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1048 FDCharDriver *s = chr->opaque;
1049 return qio_channel_create_watch(s->ioc_out, cond);
1052 static void fd_chr_update_read_handler(CharDriverState *chr)
1054 FDCharDriver *s = chr->opaque;
1056 remove_fd_in_watch(chr);
1057 if (s->ioc_in) {
1058 chr->fd_in_tag = io_add_watch_poll(s->ioc_in,
1059 fd_chr_read_poll,
1060 fd_chr_read, chr);
1064 static void fd_chr_close(struct CharDriverState *chr)
1066 FDCharDriver *s = chr->opaque;
1068 remove_fd_in_watch(chr);
1069 if (s->ioc_in) {
1070 object_unref(OBJECT(s->ioc_in));
1072 if (s->ioc_out) {
1073 object_unref(OBJECT(s->ioc_out));
1076 g_free(s);
1077 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1080 /* open a character device to a unix fd */
1081 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out,
1082 ChardevCommon *backend, Error **errp)
1084 CharDriverState *chr;
1085 FDCharDriver *s;
1087 chr = qemu_chr_alloc(backend, errp);
1088 if (!chr) {
1089 return NULL;
1091 s = g_new0(FDCharDriver, 1);
1092 s->ioc_in = QIO_CHANNEL(qio_channel_file_new_fd(fd_in));
1093 s->ioc_out = QIO_CHANNEL(qio_channel_file_new_fd(fd_out));
1094 qemu_set_nonblock(fd_out);
1095 s->chr = chr;
1096 chr->opaque = s;
1097 chr->chr_add_watch = fd_chr_add_watch;
1098 chr->chr_write = fd_chr_write;
1099 chr->chr_update_read_handler = fd_chr_update_read_handler;
1100 chr->chr_close = fd_chr_close;
1102 return chr;
1105 static CharDriverState *qemu_chr_open_pipe(const char *id,
1106 ChardevBackend *backend,
1107 ChardevReturn *ret,
1108 Error **errp)
1110 ChardevHostdev *opts = backend->u.pipe.data;
1111 int fd_in, fd_out;
1112 char *filename_in;
1113 char *filename_out;
1114 const char *filename = opts->device;
1115 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
1118 filename_in = g_strdup_printf("%s.in", filename);
1119 filename_out = g_strdup_printf("%s.out", filename);
1120 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1121 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1122 g_free(filename_in);
1123 g_free(filename_out);
1124 if (fd_in < 0 || fd_out < 0) {
1125 if (fd_in >= 0)
1126 close(fd_in);
1127 if (fd_out >= 0)
1128 close(fd_out);
1129 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1130 if (fd_in < 0) {
1131 error_setg_file_open(errp, errno, filename);
1132 return NULL;
1135 return qemu_chr_open_fd(fd_in, fd_out, common, errp);
1138 /* init terminal so that we can grab keys */
1139 static struct termios oldtty;
1140 static int old_fd0_flags;
1141 static bool stdio_in_use;
1142 static bool stdio_allow_signal;
1143 static bool stdio_echo_state;
1145 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1147 static void term_exit(void)
1149 tcsetattr (0, TCSANOW, &oldtty);
1150 fcntl(0, F_SETFL, old_fd0_flags);
1153 static void term_stdio_handler(int sig)
1155 /* restore echo after resume from suspend. */
1156 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1159 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1161 struct termios tty;
1163 stdio_echo_state = echo;
1164 tty = oldtty;
1165 if (!echo) {
1166 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1167 |INLCR|IGNCR|ICRNL|IXON);
1168 tty.c_oflag |= OPOST;
1169 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1170 tty.c_cflag &= ~(CSIZE|PARENB);
1171 tty.c_cflag |= CS8;
1172 tty.c_cc[VMIN] = 1;
1173 tty.c_cc[VTIME] = 0;
1175 if (!stdio_allow_signal)
1176 tty.c_lflag &= ~ISIG;
1178 tcsetattr (0, TCSANOW, &tty);
1181 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1183 term_exit();
1184 fd_chr_close(chr);
1187 static CharDriverState *qemu_chr_open_stdio(const char *id,
1188 ChardevBackend *backend,
1189 ChardevReturn *ret,
1190 Error **errp)
1192 ChardevStdio *opts = backend->u.stdio.data;
1193 CharDriverState *chr;
1194 struct sigaction act;
1195 ChardevCommon *common = qapi_ChardevStdio_base(opts);
1197 if (is_daemonized()) {
1198 error_setg(errp, "cannot use stdio with -daemonize");
1199 return NULL;
1202 if (stdio_in_use) {
1203 error_setg(errp, "cannot use stdio by multiple character devices");
1204 return NULL;
1207 stdio_in_use = true;
1208 old_fd0_flags = fcntl(0, F_GETFL);
1209 tcgetattr(0, &oldtty);
1210 qemu_set_nonblock(0);
1211 atexit(term_exit);
1213 memset(&act, 0, sizeof(act));
1214 act.sa_handler = term_stdio_handler;
1215 sigaction(SIGCONT, &act, NULL);
1217 chr = qemu_chr_open_fd(0, 1, common, errp);
1218 chr->chr_close = qemu_chr_close_stdio;
1219 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1220 if (opts->has_signal) {
1221 stdio_allow_signal = opts->signal;
1223 qemu_chr_fe_set_echo(chr, false);
1225 return chr;
1228 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1229 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1230 || defined(__GLIBC__)
1232 #define HAVE_CHARDEV_SERIAL 1
1233 #define HAVE_CHARDEV_PTY 1
1235 typedef struct {
1236 QIOChannel *ioc;
1237 int read_bytes;
1239 /* Protected by the CharDriverState chr_write_lock. */
1240 int connected;
1241 guint timer_tag;
1242 guint open_tag;
1243 } PtyCharDriver;
1245 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1246 static void pty_chr_state(CharDriverState *chr, int connected);
1248 static gboolean pty_chr_timer(gpointer opaque)
1250 struct CharDriverState *chr = opaque;
1251 PtyCharDriver *s = chr->opaque;
1253 qemu_mutex_lock(&chr->chr_write_lock);
1254 s->timer_tag = 0;
1255 s->open_tag = 0;
1256 if (!s->connected) {
1257 /* Next poll ... */
1258 pty_chr_update_read_handler_locked(chr);
1260 qemu_mutex_unlock(&chr->chr_write_lock);
1261 return FALSE;
1264 /* Called with chr_write_lock held. */
1265 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1267 PtyCharDriver *s = chr->opaque;
1269 if (s->timer_tag) {
1270 g_source_remove(s->timer_tag);
1271 s->timer_tag = 0;
1274 if (ms == 1000) {
1275 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1276 } else {
1277 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1281 /* Called with chr_write_lock held. */
1282 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1284 PtyCharDriver *s = chr->opaque;
1285 GPollFD pfd;
1286 int rc;
1287 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
1289 pfd.fd = fioc->fd;
1290 pfd.events = G_IO_OUT;
1291 pfd.revents = 0;
1292 do {
1293 rc = g_poll(&pfd, 1, 0);
1294 } while (rc == -1 && errno == EINTR);
1295 assert(rc >= 0);
1297 if (pfd.revents & G_IO_HUP) {
1298 pty_chr_state(chr, 0);
1299 } else {
1300 pty_chr_state(chr, 1);
1304 static void pty_chr_update_read_handler(CharDriverState *chr)
1306 qemu_mutex_lock(&chr->chr_write_lock);
1307 pty_chr_update_read_handler_locked(chr);
1308 qemu_mutex_unlock(&chr->chr_write_lock);
1311 /* Called with chr_write_lock held. */
1312 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1314 PtyCharDriver *s = chr->opaque;
1316 if (!s->connected) {
1317 /* guest sends data, check for (re-)connect */
1318 pty_chr_update_read_handler_locked(chr);
1319 if (!s->connected) {
1320 return 0;
1323 return io_channel_send(s->ioc, buf, len);
1326 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1328 PtyCharDriver *s = chr->opaque;
1329 if (!s->connected) {
1330 return NULL;
1332 return qio_channel_create_watch(s->ioc, cond);
1335 static int pty_chr_read_poll(void *opaque)
1337 CharDriverState *chr = opaque;
1338 PtyCharDriver *s = chr->opaque;
1340 s->read_bytes = qemu_chr_be_can_write(chr);
1341 return s->read_bytes;
1344 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
1346 CharDriverState *chr = opaque;
1347 PtyCharDriver *s = chr->opaque;
1348 gsize len;
1349 uint8_t buf[READ_BUF_LEN];
1350 ssize_t ret;
1352 len = sizeof(buf);
1353 if (len > s->read_bytes)
1354 len = s->read_bytes;
1355 if (len == 0) {
1356 return TRUE;
1358 ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
1359 if (ret <= 0) {
1360 pty_chr_state(chr, 0);
1361 return FALSE;
1362 } else {
1363 pty_chr_state(chr, 1);
1364 qemu_chr_be_write(chr, buf, ret);
1366 return TRUE;
1369 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1371 CharDriverState *chr = opaque;
1372 PtyCharDriver *s = chr->opaque;
1374 s->open_tag = 0;
1375 qemu_chr_be_generic_open(chr);
1376 return FALSE;
1379 /* Called with chr_write_lock held. */
1380 static void pty_chr_state(CharDriverState *chr, int connected)
1382 PtyCharDriver *s = chr->opaque;
1384 if (!connected) {
1385 if (s->open_tag) {
1386 g_source_remove(s->open_tag);
1387 s->open_tag = 0;
1389 remove_fd_in_watch(chr);
1390 s->connected = 0;
1391 /* (re-)connect poll interval for idle guests: once per second.
1392 * We check more frequently in case the guests sends data to
1393 * the virtual device linked to our pty. */
1394 pty_chr_rearm_timer(chr, 1000);
1395 } else {
1396 if (s->timer_tag) {
1397 g_source_remove(s->timer_tag);
1398 s->timer_tag = 0;
1400 if (!s->connected) {
1401 g_assert(s->open_tag == 0);
1402 s->connected = 1;
1403 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1405 if (!chr->fd_in_tag) {
1406 chr->fd_in_tag = io_add_watch_poll(s->ioc,
1407 pty_chr_read_poll,
1408 pty_chr_read, chr);
1413 static void pty_chr_close(struct CharDriverState *chr)
1415 PtyCharDriver *s = chr->opaque;
1417 qemu_mutex_lock(&chr->chr_write_lock);
1418 pty_chr_state(chr, 0);
1419 object_unref(OBJECT(s->ioc));
1420 if (s->timer_tag) {
1421 g_source_remove(s->timer_tag);
1422 s->timer_tag = 0;
1424 qemu_mutex_unlock(&chr->chr_write_lock);
1425 g_free(s);
1426 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1429 static CharDriverState *qemu_chr_open_pty(const char *id,
1430 ChardevBackend *backend,
1431 ChardevReturn *ret,
1432 Error **errp)
1434 CharDriverState *chr;
1435 PtyCharDriver *s;
1436 int master_fd, slave_fd;
1437 char pty_name[PATH_MAX];
1438 ChardevCommon *common = backend->u.pty.data;
1440 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1441 if (master_fd < 0) {
1442 error_setg_errno(errp, errno, "Failed to create PTY");
1443 return NULL;
1446 close(slave_fd);
1447 qemu_set_nonblock(master_fd);
1449 chr = qemu_chr_alloc(common, errp);
1450 if (!chr) {
1451 close(master_fd);
1452 return NULL;
1455 chr->filename = g_strdup_printf("pty:%s", pty_name);
1456 ret->pty = g_strdup(pty_name);
1457 ret->has_pty = true;
1459 fprintf(stderr, "char device redirected to %s (label %s)\n",
1460 pty_name, id);
1462 s = g_new0(PtyCharDriver, 1);
1463 chr->opaque = s;
1464 chr->chr_write = pty_chr_write;
1465 chr->chr_update_read_handler = pty_chr_update_read_handler;
1466 chr->chr_close = pty_chr_close;
1467 chr->chr_add_watch = pty_chr_add_watch;
1468 chr->explicit_be_open = true;
1470 s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
1471 s->timer_tag = 0;
1473 return chr;
1476 static void tty_serial_init(int fd, int speed,
1477 int parity, int data_bits, int stop_bits)
1479 struct termios tty;
1480 speed_t spd;
1482 #if 0
1483 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1484 speed, parity, data_bits, stop_bits);
1485 #endif
1486 tcgetattr (fd, &tty);
1488 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1489 speed = speed * 10 / 11;
1490 do {
1491 check_speed(50);
1492 check_speed(75);
1493 check_speed(110);
1494 check_speed(134);
1495 check_speed(150);
1496 check_speed(200);
1497 check_speed(300);
1498 check_speed(600);
1499 check_speed(1200);
1500 check_speed(1800);
1501 check_speed(2400);
1502 check_speed(4800);
1503 check_speed(9600);
1504 check_speed(19200);
1505 check_speed(38400);
1506 /* Non-Posix values follow. They may be unsupported on some systems. */
1507 check_speed(57600);
1508 check_speed(115200);
1509 #ifdef B230400
1510 check_speed(230400);
1511 #endif
1512 #ifdef B460800
1513 check_speed(460800);
1514 #endif
1515 #ifdef B500000
1516 check_speed(500000);
1517 #endif
1518 #ifdef B576000
1519 check_speed(576000);
1520 #endif
1521 #ifdef B921600
1522 check_speed(921600);
1523 #endif
1524 #ifdef B1000000
1525 check_speed(1000000);
1526 #endif
1527 #ifdef B1152000
1528 check_speed(1152000);
1529 #endif
1530 #ifdef B1500000
1531 check_speed(1500000);
1532 #endif
1533 #ifdef B2000000
1534 check_speed(2000000);
1535 #endif
1536 #ifdef B2500000
1537 check_speed(2500000);
1538 #endif
1539 #ifdef B3000000
1540 check_speed(3000000);
1541 #endif
1542 #ifdef B3500000
1543 check_speed(3500000);
1544 #endif
1545 #ifdef B4000000
1546 check_speed(4000000);
1547 #endif
1548 spd = B115200;
1549 } while (0);
1551 cfsetispeed(&tty, spd);
1552 cfsetospeed(&tty, spd);
1554 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1555 |INLCR|IGNCR|ICRNL|IXON);
1556 tty.c_oflag |= OPOST;
1557 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1558 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1559 switch(data_bits) {
1560 default:
1561 case 8:
1562 tty.c_cflag |= CS8;
1563 break;
1564 case 7:
1565 tty.c_cflag |= CS7;
1566 break;
1567 case 6:
1568 tty.c_cflag |= CS6;
1569 break;
1570 case 5:
1571 tty.c_cflag |= CS5;
1572 break;
1574 switch(parity) {
1575 default:
1576 case 'N':
1577 break;
1578 case 'E':
1579 tty.c_cflag |= PARENB;
1580 break;
1581 case 'O':
1582 tty.c_cflag |= PARENB | PARODD;
1583 break;
1585 if (stop_bits == 2)
1586 tty.c_cflag |= CSTOPB;
1588 tcsetattr (fd, TCSANOW, &tty);
1591 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1593 FDCharDriver *s = chr->opaque;
1594 QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc_in);
1596 switch(cmd) {
1597 case CHR_IOCTL_SERIAL_SET_PARAMS:
1599 QEMUSerialSetParams *ssp = arg;
1600 tty_serial_init(fioc->fd,
1601 ssp->speed, ssp->parity,
1602 ssp->data_bits, ssp->stop_bits);
1604 break;
1605 case CHR_IOCTL_SERIAL_SET_BREAK:
1607 int enable = *(int *)arg;
1608 if (enable) {
1609 tcsendbreak(fioc->fd, 1);
1612 break;
1613 case CHR_IOCTL_SERIAL_GET_TIOCM:
1615 int sarg = 0;
1616 int *targ = (int *)arg;
1617 ioctl(fioc->fd, TIOCMGET, &sarg);
1618 *targ = 0;
1619 if (sarg & TIOCM_CTS)
1620 *targ |= CHR_TIOCM_CTS;
1621 if (sarg & TIOCM_CAR)
1622 *targ |= CHR_TIOCM_CAR;
1623 if (sarg & TIOCM_DSR)
1624 *targ |= CHR_TIOCM_DSR;
1625 if (sarg & TIOCM_RI)
1626 *targ |= CHR_TIOCM_RI;
1627 if (sarg & TIOCM_DTR)
1628 *targ |= CHR_TIOCM_DTR;
1629 if (sarg & TIOCM_RTS)
1630 *targ |= CHR_TIOCM_RTS;
1632 break;
1633 case CHR_IOCTL_SERIAL_SET_TIOCM:
1635 int sarg = *(int *)arg;
1636 int targ = 0;
1637 ioctl(fioc->fd, TIOCMGET, &targ);
1638 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1639 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1640 if (sarg & CHR_TIOCM_CTS)
1641 targ |= TIOCM_CTS;
1642 if (sarg & CHR_TIOCM_CAR)
1643 targ |= TIOCM_CAR;
1644 if (sarg & CHR_TIOCM_DSR)
1645 targ |= TIOCM_DSR;
1646 if (sarg & CHR_TIOCM_RI)
1647 targ |= TIOCM_RI;
1648 if (sarg & CHR_TIOCM_DTR)
1649 targ |= TIOCM_DTR;
1650 if (sarg & CHR_TIOCM_RTS)
1651 targ |= TIOCM_RTS;
1652 ioctl(fioc->fd, TIOCMSET, &targ);
1654 break;
1655 default:
1656 return -ENOTSUP;
1658 return 0;
1661 static void qemu_chr_close_tty(CharDriverState *chr)
1663 fd_chr_close(chr);
1666 static CharDriverState *qemu_chr_open_tty_fd(int fd,
1667 ChardevCommon *backend,
1668 Error **errp)
1670 CharDriverState *chr;
1672 tty_serial_init(fd, 115200, 'N', 8, 1);
1673 chr = qemu_chr_open_fd(fd, fd, backend, errp);
1674 chr->chr_ioctl = tty_serial_ioctl;
1675 chr->chr_close = qemu_chr_close_tty;
1676 return chr;
1678 #endif /* __linux__ || __sun__ */
1680 #if defined(__linux__)
1682 #define HAVE_CHARDEV_PARPORT 1
1684 typedef struct {
1685 int fd;
1686 int mode;
1687 } ParallelCharDriver;
1689 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1691 if (s->mode != mode) {
1692 int m = mode;
1693 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1694 return 0;
1695 s->mode = mode;
1697 return 1;
1700 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1702 ParallelCharDriver *drv = chr->opaque;
1703 int fd = drv->fd;
1704 uint8_t b;
1706 switch(cmd) {
1707 case CHR_IOCTL_PP_READ_DATA:
1708 if (ioctl(fd, PPRDATA, &b) < 0)
1709 return -ENOTSUP;
1710 *(uint8_t *)arg = b;
1711 break;
1712 case CHR_IOCTL_PP_WRITE_DATA:
1713 b = *(uint8_t *)arg;
1714 if (ioctl(fd, PPWDATA, &b) < 0)
1715 return -ENOTSUP;
1716 break;
1717 case CHR_IOCTL_PP_READ_CONTROL:
1718 if (ioctl(fd, PPRCONTROL, &b) < 0)
1719 return -ENOTSUP;
1720 /* Linux gives only the lowest bits, and no way to know data
1721 direction! For better compatibility set the fixed upper
1722 bits. */
1723 *(uint8_t *)arg = b | 0xc0;
1724 break;
1725 case CHR_IOCTL_PP_WRITE_CONTROL:
1726 b = *(uint8_t *)arg;
1727 if (ioctl(fd, PPWCONTROL, &b) < 0)
1728 return -ENOTSUP;
1729 break;
1730 case CHR_IOCTL_PP_READ_STATUS:
1731 if (ioctl(fd, PPRSTATUS, &b) < 0)
1732 return -ENOTSUP;
1733 *(uint8_t *)arg = b;
1734 break;
1735 case CHR_IOCTL_PP_DATA_DIR:
1736 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1737 return -ENOTSUP;
1738 break;
1739 case CHR_IOCTL_PP_EPP_READ_ADDR:
1740 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1741 struct ParallelIOArg *parg = arg;
1742 int n = read(fd, parg->buffer, parg->count);
1743 if (n != parg->count) {
1744 return -EIO;
1747 break;
1748 case CHR_IOCTL_PP_EPP_READ:
1749 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1750 struct ParallelIOArg *parg = arg;
1751 int n = read(fd, parg->buffer, parg->count);
1752 if (n != parg->count) {
1753 return -EIO;
1756 break;
1757 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1758 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1759 struct ParallelIOArg *parg = arg;
1760 int n = write(fd, parg->buffer, parg->count);
1761 if (n != parg->count) {
1762 return -EIO;
1765 break;
1766 case CHR_IOCTL_PP_EPP_WRITE:
1767 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1768 struct ParallelIOArg *parg = arg;
1769 int n = write(fd, parg->buffer, parg->count);
1770 if (n != parg->count) {
1771 return -EIO;
1774 break;
1775 default:
1776 return -ENOTSUP;
1778 return 0;
1781 static void pp_close(CharDriverState *chr)
1783 ParallelCharDriver *drv = chr->opaque;
1784 int fd = drv->fd;
1786 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1787 ioctl(fd, PPRELEASE);
1788 close(fd);
1789 g_free(drv);
1790 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1793 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1794 ChardevCommon *backend,
1795 Error **errp)
1797 CharDriverState *chr;
1798 ParallelCharDriver *drv;
1800 if (ioctl(fd, PPCLAIM) < 0) {
1801 error_setg_errno(errp, errno, "not a parallel port");
1802 close(fd);
1803 return NULL;
1806 chr = qemu_chr_alloc(backend, errp);
1807 if (!chr) {
1808 return NULL;
1811 drv = g_new0(ParallelCharDriver, 1);
1812 chr->opaque = drv;
1813 chr->chr_write = null_chr_write;
1814 chr->chr_ioctl = pp_ioctl;
1815 chr->chr_close = pp_close;
1817 drv->fd = fd;
1818 drv->mode = IEEE1284_MODE_COMPAT;
1820 return chr;
1822 #endif /* __linux__ */
1824 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1826 #define HAVE_CHARDEV_PARPORT 1
1828 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1830 int fd = (int)(intptr_t)chr->opaque;
1831 uint8_t b;
1833 switch(cmd) {
1834 case CHR_IOCTL_PP_READ_DATA:
1835 if (ioctl(fd, PPIGDATA, &b) < 0)
1836 return -ENOTSUP;
1837 *(uint8_t *)arg = b;
1838 break;
1839 case CHR_IOCTL_PP_WRITE_DATA:
1840 b = *(uint8_t *)arg;
1841 if (ioctl(fd, PPISDATA, &b) < 0)
1842 return -ENOTSUP;
1843 break;
1844 case CHR_IOCTL_PP_READ_CONTROL:
1845 if (ioctl(fd, PPIGCTRL, &b) < 0)
1846 return -ENOTSUP;
1847 *(uint8_t *)arg = b;
1848 break;
1849 case CHR_IOCTL_PP_WRITE_CONTROL:
1850 b = *(uint8_t *)arg;
1851 if (ioctl(fd, PPISCTRL, &b) < 0)
1852 return -ENOTSUP;
1853 break;
1854 case CHR_IOCTL_PP_READ_STATUS:
1855 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1856 return -ENOTSUP;
1857 *(uint8_t *)arg = b;
1858 break;
1859 default:
1860 return -ENOTSUP;
1862 return 0;
1865 static CharDriverState *qemu_chr_open_pp_fd(int fd,
1866 ChardevCommon *backend,
1867 Error **errp)
1869 CharDriverState *chr;
1871 chr = qemu_chr_alloc(backend, errp);
1872 if (!chr) {
1873 return NULL;
1875 chr->opaque = (void *)(intptr_t)fd;
1876 chr->chr_write = null_chr_write;
1877 chr->chr_ioctl = pp_ioctl;
1878 chr->explicit_be_open = true;
1879 return chr;
1881 #endif
1883 #else /* _WIN32 */
1885 #define HAVE_CHARDEV_SERIAL 1
1887 typedef struct {
1888 int max_size;
1889 HANDLE hcom, hrecv, hsend;
1890 OVERLAPPED orecv;
1891 BOOL fpipe;
1892 DWORD len;
1894 /* Protected by the CharDriverState chr_write_lock. */
1895 OVERLAPPED osend;
1896 } WinCharState;
1898 typedef struct {
1899 HANDLE hStdIn;
1900 HANDLE hInputReadyEvent;
1901 HANDLE hInputDoneEvent;
1902 HANDLE hInputThread;
1903 uint8_t win_stdio_buf;
1904 } WinStdioCharState;
1906 #define NSENDBUF 2048
1907 #define NRECVBUF 2048
1908 #define MAXCONNECT 1
1909 #define NTIMEOUT 5000
1911 static int win_chr_poll(void *opaque);
1912 static int win_chr_pipe_poll(void *opaque);
1914 static void win_chr_close(CharDriverState *chr)
1916 WinCharState *s = chr->opaque;
1918 if (s->hsend) {
1919 CloseHandle(s->hsend);
1920 s->hsend = NULL;
1922 if (s->hrecv) {
1923 CloseHandle(s->hrecv);
1924 s->hrecv = NULL;
1926 if (s->hcom) {
1927 CloseHandle(s->hcom);
1928 s->hcom = NULL;
1930 if (s->fpipe)
1931 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1932 else
1933 qemu_del_polling_cb(win_chr_poll, chr);
1935 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1938 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1940 WinCharState *s = chr->opaque;
1941 COMMCONFIG comcfg;
1942 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1943 COMSTAT comstat;
1944 DWORD size;
1945 DWORD err;
1947 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1948 if (!s->hsend) {
1949 error_setg(errp, "Failed CreateEvent");
1950 goto fail;
1952 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1953 if (!s->hrecv) {
1954 error_setg(errp, "Failed CreateEvent");
1955 goto fail;
1958 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1959 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1960 if (s->hcom == INVALID_HANDLE_VALUE) {
1961 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1962 s->hcom = NULL;
1963 goto fail;
1966 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1967 error_setg(errp, "Failed SetupComm");
1968 goto fail;
1971 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1972 size = sizeof(COMMCONFIG);
1973 GetDefaultCommConfig(filename, &comcfg, &size);
1974 comcfg.dcb.DCBlength = sizeof(DCB);
1975 CommConfigDialog(filename, NULL, &comcfg);
1977 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1978 error_setg(errp, "Failed SetCommState");
1979 goto fail;
1982 if (!SetCommMask(s->hcom, EV_ERR)) {
1983 error_setg(errp, "Failed SetCommMask");
1984 goto fail;
1987 cto.ReadIntervalTimeout = MAXDWORD;
1988 if (!SetCommTimeouts(s->hcom, &cto)) {
1989 error_setg(errp, "Failed SetCommTimeouts");
1990 goto fail;
1993 if (!ClearCommError(s->hcom, &err, &comstat)) {
1994 error_setg(errp, "Failed ClearCommError");
1995 goto fail;
1997 qemu_add_polling_cb(win_chr_poll, chr);
1998 return 0;
2000 fail:
2001 win_chr_close(chr);
2002 return -1;
2005 /* Called with chr_write_lock held. */
2006 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2008 WinCharState *s = chr->opaque;
2009 DWORD len, ret, size, err;
2011 len = len1;
2012 ZeroMemory(&s->osend, sizeof(s->osend));
2013 s->osend.hEvent = s->hsend;
2014 while (len > 0) {
2015 if (s->hsend)
2016 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2017 else
2018 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2019 if (!ret) {
2020 err = GetLastError();
2021 if (err == ERROR_IO_PENDING) {
2022 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2023 if (ret) {
2024 buf += size;
2025 len -= size;
2026 } else {
2027 break;
2029 } else {
2030 break;
2032 } else {
2033 buf += size;
2034 len -= size;
2037 return len1 - len;
2040 static int win_chr_read_poll(CharDriverState *chr)
2042 WinCharState *s = chr->opaque;
2044 s->max_size = qemu_chr_be_can_write(chr);
2045 return s->max_size;
2048 static void win_chr_readfile(CharDriverState *chr)
2050 WinCharState *s = chr->opaque;
2051 int ret, err;
2052 uint8_t buf[READ_BUF_LEN];
2053 DWORD size;
2055 ZeroMemory(&s->orecv, sizeof(s->orecv));
2056 s->orecv.hEvent = s->hrecv;
2057 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2058 if (!ret) {
2059 err = GetLastError();
2060 if (err == ERROR_IO_PENDING) {
2061 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2065 if (size > 0) {
2066 qemu_chr_be_write(chr, buf, size);
2070 static void win_chr_read(CharDriverState *chr)
2072 WinCharState *s = chr->opaque;
2074 if (s->len > s->max_size)
2075 s->len = s->max_size;
2076 if (s->len == 0)
2077 return;
2079 win_chr_readfile(chr);
2082 static int win_chr_poll(void *opaque)
2084 CharDriverState *chr = opaque;
2085 WinCharState *s = chr->opaque;
2086 COMSTAT status;
2087 DWORD comerr;
2089 ClearCommError(s->hcom, &comerr, &status);
2090 if (status.cbInQue > 0) {
2091 s->len = status.cbInQue;
2092 win_chr_read_poll(chr);
2093 win_chr_read(chr);
2094 return 1;
2096 return 0;
2099 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2100 ChardevCommon *backend,
2101 Error **errp)
2103 CharDriverState *chr;
2104 WinCharState *s;
2106 chr = qemu_chr_alloc(backend, errp);
2107 if (!chr) {
2108 return NULL;
2110 s = g_new0(WinCharState, 1);
2111 chr->opaque = s;
2112 chr->chr_write = win_chr_write;
2113 chr->chr_close = win_chr_close;
2115 if (win_chr_init(chr, filename, errp) < 0) {
2116 g_free(s);
2117 qemu_chr_free_common(chr);
2118 return NULL;
2120 return chr;
2123 static int win_chr_pipe_poll(void *opaque)
2125 CharDriverState *chr = opaque;
2126 WinCharState *s = chr->opaque;
2127 DWORD size;
2129 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2130 if (size > 0) {
2131 s->len = size;
2132 win_chr_read_poll(chr);
2133 win_chr_read(chr);
2134 return 1;
2136 return 0;
2139 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2140 Error **errp)
2142 WinCharState *s = chr->opaque;
2143 OVERLAPPED ov;
2144 int ret;
2145 DWORD size;
2146 char *openname;
2148 s->fpipe = TRUE;
2150 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2151 if (!s->hsend) {
2152 error_setg(errp, "Failed CreateEvent");
2153 goto fail;
2155 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2156 if (!s->hrecv) {
2157 error_setg(errp, "Failed CreateEvent");
2158 goto fail;
2161 openname = g_strdup_printf("\\\\.\\pipe\\%s", filename);
2162 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2163 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2164 PIPE_WAIT,
2165 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2166 g_free(openname);
2167 if (s->hcom == INVALID_HANDLE_VALUE) {
2168 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2169 s->hcom = NULL;
2170 goto fail;
2173 ZeroMemory(&ov, sizeof(ov));
2174 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2175 ret = ConnectNamedPipe(s->hcom, &ov);
2176 if (ret) {
2177 error_setg(errp, "Failed ConnectNamedPipe");
2178 goto fail;
2181 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2182 if (!ret) {
2183 error_setg(errp, "Failed GetOverlappedResult");
2184 if (ov.hEvent) {
2185 CloseHandle(ov.hEvent);
2186 ov.hEvent = NULL;
2188 goto fail;
2191 if (ov.hEvent) {
2192 CloseHandle(ov.hEvent);
2193 ov.hEvent = NULL;
2195 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2196 return 0;
2198 fail:
2199 win_chr_close(chr);
2200 return -1;
2204 static CharDriverState *qemu_chr_open_pipe(const char *id,
2205 ChardevBackend *backend,
2206 ChardevReturn *ret,
2207 Error **errp)
2209 ChardevHostdev *opts = backend->u.pipe.data;
2210 const char *filename = opts->device;
2211 CharDriverState *chr;
2212 WinCharState *s;
2213 ChardevCommon *common = qapi_ChardevHostdev_base(opts);
2215 chr = qemu_chr_alloc(common, errp);
2216 if (!chr) {
2217 return NULL;
2219 s = g_new0(WinCharState, 1);
2220 chr->opaque = s;
2221 chr->chr_write = win_chr_write;
2222 chr->chr_close = win_chr_close;
2224 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2225 g_free(s);
2226 qemu_chr_free_common(chr);
2227 return NULL;
2229 return chr;
2232 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out,
2233 ChardevCommon *backend,
2234 Error **errp)
2236 CharDriverState *chr;
2237 WinCharState *s;
2239 chr = qemu_chr_alloc(backend, errp);
2240 if (!chr) {
2241 return NULL;
2243 s = g_new0(WinCharState, 1);
2244 s->hcom = fd_out;
2245 chr->opaque = s;
2246 chr->chr_write = win_chr_write;
2247 return chr;
2250 static CharDriverState *qemu_chr_open_win_con(const char *id,
2251 ChardevBackend *backend,
2252 ChardevReturn *ret,
2253 Error **errp)
2255 ChardevCommon *common = backend->u.console.data;
2256 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE),
2257 common, errp);
2260 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2262 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2263 DWORD dwSize;
2264 int len1;
2266 len1 = len;
2268 while (len1 > 0) {
2269 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2270 break;
2272 buf += dwSize;
2273 len1 -= dwSize;
2276 return len - len1;
2279 static void win_stdio_wait_func(void *opaque)
2281 CharDriverState *chr = opaque;
2282 WinStdioCharState *stdio = chr->opaque;
2283 INPUT_RECORD buf[4];
2284 int ret;
2285 DWORD dwSize;
2286 int i;
2288 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2290 if (!ret) {
2291 /* Avoid error storm */
2292 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2293 return;
2296 for (i = 0; i < dwSize; i++) {
2297 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2299 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2300 int j;
2301 if (kev->uChar.AsciiChar != 0) {
2302 for (j = 0; j < kev->wRepeatCount; j++) {
2303 if (qemu_chr_be_can_write(chr)) {
2304 uint8_t c = kev->uChar.AsciiChar;
2305 qemu_chr_be_write(chr, &c, 1);
2313 static DWORD WINAPI win_stdio_thread(LPVOID param)
2315 CharDriverState *chr = param;
2316 WinStdioCharState *stdio = chr->opaque;
2317 int ret;
2318 DWORD dwSize;
2320 while (1) {
2322 /* Wait for one byte */
2323 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2325 /* Exit in case of error, continue if nothing read */
2326 if (!ret) {
2327 break;
2329 if (!dwSize) {
2330 continue;
2333 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2334 if (stdio->win_stdio_buf == '\r') {
2335 continue;
2338 /* Signal the main thread and wait until the byte was eaten */
2339 if (!SetEvent(stdio->hInputReadyEvent)) {
2340 break;
2342 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2343 != WAIT_OBJECT_0) {
2344 break;
2348 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2349 return 0;
2352 static void win_stdio_thread_wait_func(void *opaque)
2354 CharDriverState *chr = opaque;
2355 WinStdioCharState *stdio = chr->opaque;
2357 if (qemu_chr_be_can_write(chr)) {
2358 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2361 SetEvent(stdio->hInputDoneEvent);
2364 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2366 WinStdioCharState *stdio = chr->opaque;
2367 DWORD dwMode = 0;
2369 GetConsoleMode(stdio->hStdIn, &dwMode);
2371 if (echo) {
2372 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2373 } else {
2374 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2378 static void win_stdio_close(CharDriverState *chr)
2380 WinStdioCharState *stdio = chr->opaque;
2382 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2383 CloseHandle(stdio->hInputReadyEvent);
2385 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2386 CloseHandle(stdio->hInputDoneEvent);
2388 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2389 TerminateThread(stdio->hInputThread, 0);
2392 g_free(chr->opaque);
2393 g_free(chr);
2396 static CharDriverState *qemu_chr_open_stdio(const char *id,
2397 ChardevBackend *backend,
2398 ChardevReturn *ret,
2399 Error **errp)
2401 CharDriverState *chr;
2402 WinStdioCharState *stdio;
2403 DWORD dwMode;
2404 int is_console = 0;
2405 ChardevCommon *common = qapi_ChardevStdio_base(backend->u.stdio.data);
2407 chr = qemu_chr_alloc(common, errp);
2408 if (!chr) {
2409 return NULL;
2411 stdio = g_new0(WinStdioCharState, 1);
2413 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2414 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2415 error_setg(errp, "cannot open stdio: invalid handle");
2416 return NULL;
2419 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2421 chr->opaque = stdio;
2422 chr->chr_write = win_stdio_write;
2423 chr->chr_close = win_stdio_close;
2425 if (is_console) {
2426 if (qemu_add_wait_object(stdio->hStdIn,
2427 win_stdio_wait_func, chr)) {
2428 error_setg(errp, "qemu_add_wait_object: failed");
2429 goto err1;
2431 } else {
2432 DWORD dwId;
2434 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2435 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2436 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2437 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2438 error_setg(errp, "cannot create event");
2439 goto err2;
2441 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2442 win_stdio_thread_wait_func, chr)) {
2443 error_setg(errp, "qemu_add_wait_object: failed");
2444 goto err2;
2446 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2447 chr, 0, &dwId);
2449 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2450 error_setg(errp, "cannot create stdio thread");
2451 goto err3;
2455 dwMode |= ENABLE_LINE_INPUT;
2457 if (is_console) {
2458 /* set the terminal in raw mode */
2459 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2460 dwMode |= ENABLE_PROCESSED_INPUT;
2463 SetConsoleMode(stdio->hStdIn, dwMode);
2465 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2466 qemu_chr_fe_set_echo(chr, false);
2468 return chr;
2470 err3:
2471 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2472 err2:
2473 CloseHandle(stdio->hInputReadyEvent);
2474 CloseHandle(stdio->hInputDoneEvent);
2475 err1:
2476 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2477 return NULL;
2479 #endif /* !_WIN32 */
2482 /***********************************************************/
2483 /* UDP Net console */
2485 typedef struct {
2486 QIOChannel *ioc;
2487 uint8_t buf[READ_BUF_LEN];
2488 int bufcnt;
2489 int bufptr;
2490 int max_size;
2491 } NetCharDriver;
2493 /* Called with chr_write_lock held. */
2494 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2496 NetCharDriver *s = chr->opaque;
2498 return qio_channel_write(
2499 s->ioc, (const char *)buf, len, NULL);
2502 static int udp_chr_read_poll(void *opaque)
2504 CharDriverState *chr = opaque;
2505 NetCharDriver *s = chr->opaque;
2507 s->max_size = qemu_chr_be_can_write(chr);
2509 /* If there were any stray characters in the queue process them
2510 * first
2512 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2513 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2514 s->bufptr++;
2515 s->max_size = qemu_chr_be_can_write(chr);
2517 return s->max_size;
2520 static gboolean udp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2522 CharDriverState *chr = opaque;
2523 NetCharDriver *s = chr->opaque;
2524 ssize_t ret;
2526 if (s->max_size == 0) {
2527 return TRUE;
2529 ret = qio_channel_read(
2530 s->ioc, (char *)s->buf, sizeof(s->buf), NULL);
2531 if (ret <= 0) {
2532 remove_fd_in_watch(chr);
2533 return FALSE;
2535 s->bufcnt = ret;
2537 s->bufptr = 0;
2538 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2539 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2540 s->bufptr++;
2541 s->max_size = qemu_chr_be_can_write(chr);
2544 return TRUE;
2547 static void udp_chr_update_read_handler(CharDriverState *chr)
2549 NetCharDriver *s = chr->opaque;
2551 remove_fd_in_watch(chr);
2552 if (s->ioc) {
2553 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2554 udp_chr_read_poll,
2555 udp_chr_read, chr);
2559 static void udp_chr_close(CharDriverState *chr)
2561 NetCharDriver *s = chr->opaque;
2563 remove_fd_in_watch(chr);
2564 if (s->ioc) {
2565 object_unref(OBJECT(s->ioc));
2567 g_free(s);
2568 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2571 static CharDriverState *qemu_chr_open_udp(QIOChannelSocket *sioc,
2572 ChardevCommon *backend,
2573 Error **errp)
2575 CharDriverState *chr = NULL;
2576 NetCharDriver *s = NULL;
2578 chr = qemu_chr_alloc(backend, errp);
2579 if (!chr) {
2580 return NULL;
2582 s = g_new0(NetCharDriver, 1);
2584 s->ioc = QIO_CHANNEL(sioc);
2585 s->bufcnt = 0;
2586 s->bufptr = 0;
2587 chr->opaque = s;
2588 chr->chr_write = udp_chr_write;
2589 chr->chr_update_read_handler = udp_chr_update_read_handler;
2590 chr->chr_close = udp_chr_close;
2591 /* be isn't opened until we get a connection */
2592 chr->explicit_be_open = true;
2593 return chr;
2596 /***********************************************************/
2597 /* TCP Net console */
2599 typedef struct {
2600 QIOChannel *ioc; /* Client I/O channel */
2601 QIOChannelSocket *sioc; /* Client master channel */
2602 QIOChannelSocket *listen_ioc;
2603 guint listen_tag;
2604 QCryptoTLSCreds *tls_creds;
2605 int connected;
2606 int max_size;
2607 int do_telnetopt;
2608 int do_nodelay;
2609 int is_unix;
2610 int *read_msgfds;
2611 size_t read_msgfds_num;
2612 int *write_msgfds;
2613 size_t write_msgfds_num;
2615 SocketAddress *addr;
2616 bool is_listen;
2617 bool is_telnet;
2619 guint reconnect_timer;
2620 int64_t reconnect_time;
2621 bool connect_err_reported;
2622 } TCPCharDriver;
2624 static gboolean socket_reconnect_timeout(gpointer opaque);
2626 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2628 TCPCharDriver *s = chr->opaque;
2629 assert(s->connected == 0);
2630 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2631 socket_reconnect_timeout, chr);
2634 static void check_report_connect_error(CharDriverState *chr,
2635 Error *err)
2637 TCPCharDriver *s = chr->opaque;
2639 if (!s->connect_err_reported) {
2640 error_report("Unable to connect character device %s: %s",
2641 chr->label, error_get_pretty(err));
2642 s->connect_err_reported = true;
2644 qemu_chr_socket_restart_timer(chr);
2647 static gboolean tcp_chr_accept(QIOChannel *chan,
2648 GIOCondition cond,
2649 void *opaque);
2651 /* Called with chr_write_lock held. */
2652 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2654 TCPCharDriver *s = chr->opaque;
2655 if (s->connected) {
2656 int ret = io_channel_send_full(s->ioc, buf, len,
2657 s->write_msgfds,
2658 s->write_msgfds_num);
2660 /* free the written msgfds, no matter what */
2661 if (s->write_msgfds_num) {
2662 g_free(s->write_msgfds);
2663 s->write_msgfds = 0;
2664 s->write_msgfds_num = 0;
2667 return ret;
2668 } else {
2669 /* XXX: indicate an error ? */
2670 return len;
2674 static int tcp_chr_read_poll(void *opaque)
2676 CharDriverState *chr = opaque;
2677 TCPCharDriver *s = chr->opaque;
2678 if (!s->connected)
2679 return 0;
2680 s->max_size = qemu_chr_be_can_write(chr);
2681 return s->max_size;
2684 #define IAC 255
2685 #define IAC_BREAK 243
2686 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2687 TCPCharDriver *s,
2688 uint8_t *buf, int *size)
2690 /* Handle any telnet client's basic IAC options to satisfy char by
2691 * char mode with no echo. All IAC options will be removed from
2692 * the buf and the do_telnetopt variable will be used to track the
2693 * state of the width of the IAC information.
2695 * IAC commands come in sets of 3 bytes with the exception of the
2696 * "IAC BREAK" command and the double IAC.
2699 int i;
2700 int j = 0;
2702 for (i = 0; i < *size; i++) {
2703 if (s->do_telnetopt > 1) {
2704 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2705 /* Double IAC means send an IAC */
2706 if (j != i)
2707 buf[j] = buf[i];
2708 j++;
2709 s->do_telnetopt = 1;
2710 } else {
2711 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2712 /* Handle IAC break commands by sending a serial break */
2713 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2714 s->do_telnetopt++;
2716 s->do_telnetopt++;
2718 if (s->do_telnetopt >= 4) {
2719 s->do_telnetopt = 1;
2721 } else {
2722 if ((unsigned char)buf[i] == IAC) {
2723 s->do_telnetopt = 2;
2724 } else {
2725 if (j != i)
2726 buf[j] = buf[i];
2727 j++;
2731 *size = j;
2734 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2736 TCPCharDriver *s = chr->opaque;
2737 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2739 assert(num <= TCP_MAX_FDS);
2741 if (to_copy) {
2742 int i;
2744 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2746 /* Close unused fds */
2747 for (i = to_copy; i < s->read_msgfds_num; i++) {
2748 close(s->read_msgfds[i]);
2751 g_free(s->read_msgfds);
2752 s->read_msgfds = 0;
2753 s->read_msgfds_num = 0;
2756 return to_copy;
2759 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2761 TCPCharDriver *s = chr->opaque;
2763 if (!qio_channel_has_feature(s->ioc,
2764 QIO_CHANNEL_FEATURE_FD_PASS)) {
2765 return -1;
2767 /* clear old pending fd array */
2768 g_free(s->write_msgfds);
2769 s->write_msgfds = NULL;
2771 if (num) {
2772 s->write_msgfds = g_new(int, num);
2773 memcpy(s->write_msgfds, fds, num * sizeof(int));
2776 s->write_msgfds_num = num;
2778 return 0;
2781 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2783 TCPCharDriver *s = chr->opaque;
2784 struct iovec iov = { .iov_base = buf, .iov_len = len };
2785 int ret;
2786 size_t i;
2787 int *msgfds = NULL;
2788 size_t msgfds_num = 0;
2790 if (qio_channel_has_feature(s->ioc, QIO_CHANNEL_FEATURE_FD_PASS)) {
2791 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2792 &msgfds, &msgfds_num,
2793 NULL);
2794 } else {
2795 ret = qio_channel_readv_full(s->ioc, &iov, 1,
2796 NULL, NULL,
2797 NULL);
2800 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2801 errno = EAGAIN;
2802 ret = -1;
2803 } else if (ret == -1) {
2804 errno = EIO;
2807 if (msgfds_num) {
2808 /* close and clean read_msgfds */
2809 for (i = 0; i < s->read_msgfds_num; i++) {
2810 close(s->read_msgfds[i]);
2813 if (s->read_msgfds_num) {
2814 g_free(s->read_msgfds);
2817 s->read_msgfds = msgfds;
2818 s->read_msgfds_num = msgfds_num;
2821 for (i = 0; i < s->read_msgfds_num; i++) {
2822 int fd = s->read_msgfds[i];
2823 if (fd < 0) {
2824 continue;
2827 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2828 qemu_set_block(fd);
2830 #ifndef MSG_CMSG_CLOEXEC
2831 qemu_set_cloexec(fd);
2832 #endif
2835 return ret;
2838 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2840 TCPCharDriver *s = chr->opaque;
2841 return qio_channel_create_watch(s->ioc, cond);
2844 static void tcp_chr_disconnect(CharDriverState *chr)
2846 TCPCharDriver *s = chr->opaque;
2848 if (!s->connected) {
2849 return;
2852 s->connected = 0;
2853 if (s->listen_ioc) {
2854 s->listen_tag = qio_channel_add_watch(
2855 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
2857 tcp_set_msgfds(chr, NULL, 0);
2858 remove_fd_in_watch(chr);
2859 object_unref(OBJECT(s->sioc));
2860 s->sioc = NULL;
2861 object_unref(OBJECT(s->ioc));
2862 s->ioc = NULL;
2863 g_free(chr->filename);
2864 chr->filename = SocketAddress_to_str("disconnected:", s->addr,
2865 s->is_listen, s->is_telnet);
2866 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2867 if (s->reconnect_time) {
2868 qemu_chr_socket_restart_timer(chr);
2872 static gboolean tcp_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
2874 CharDriverState *chr = opaque;
2875 TCPCharDriver *s = chr->opaque;
2876 uint8_t buf[READ_BUF_LEN];
2877 int len, size;
2879 if (!s->connected || s->max_size <= 0) {
2880 return TRUE;
2882 len = sizeof(buf);
2883 if (len > s->max_size)
2884 len = s->max_size;
2885 size = tcp_chr_recv(chr, (void *)buf, len);
2886 if (size == 0 || size == -1) {
2887 /* connection closed */
2888 tcp_chr_disconnect(chr);
2889 } else if (size > 0) {
2890 if (s->do_telnetopt)
2891 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2892 if (size > 0)
2893 qemu_chr_be_write(chr, buf, size);
2896 return TRUE;
2899 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2901 TCPCharDriver *s = chr->opaque;
2902 int size;
2904 if (!s->connected) {
2905 return 0;
2908 size = tcp_chr_recv(chr, (void *) buf, len);
2909 if (size == 0) {
2910 /* connection closed */
2911 tcp_chr_disconnect(chr);
2914 return size;
2917 static void tcp_chr_connect(void *opaque)
2919 CharDriverState *chr = opaque;
2920 TCPCharDriver *s = chr->opaque;
2922 g_free(chr->filename);
2923 chr->filename = sockaddr_to_str(
2924 &s->sioc->localAddr, s->sioc->localAddrLen,
2925 &s->sioc->remoteAddr, s->sioc->remoteAddrLen,
2926 s->is_listen, s->is_telnet);
2928 s->connected = 1;
2929 if (s->ioc) {
2930 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2931 tcp_chr_read_poll,
2932 tcp_chr_read, chr);
2934 qemu_chr_be_generic_open(chr);
2937 static void tcp_chr_update_read_handler(CharDriverState *chr)
2939 TCPCharDriver *s = chr->opaque;
2941 if (!s->connected) {
2942 return;
2945 remove_fd_in_watch(chr);
2946 if (s->ioc) {
2947 chr->fd_in_tag = io_add_watch_poll(s->ioc,
2948 tcp_chr_read_poll,
2949 tcp_chr_read, chr);
2953 typedef struct {
2954 CharDriverState *chr;
2955 char buf[12];
2956 size_t buflen;
2957 } TCPCharDriverTelnetInit;
2959 static gboolean tcp_chr_telnet_init_io(QIOChannel *ioc,
2960 GIOCondition cond G_GNUC_UNUSED,
2961 gpointer user_data)
2963 TCPCharDriverTelnetInit *init = user_data;
2964 ssize_t ret;
2966 ret = qio_channel_write(ioc, init->buf, init->buflen, NULL);
2967 if (ret < 0) {
2968 if (ret == QIO_CHANNEL_ERR_BLOCK) {
2969 ret = 0;
2970 } else {
2971 tcp_chr_disconnect(init->chr);
2972 return FALSE;
2975 init->buflen -= ret;
2977 if (init->buflen == 0) {
2978 tcp_chr_connect(init->chr);
2979 return FALSE;
2982 memmove(init->buf, init->buf + ret, init->buflen);
2984 return TRUE;
2987 static void tcp_chr_telnet_init(CharDriverState *chr)
2989 TCPCharDriver *s = chr->opaque;
2990 TCPCharDriverTelnetInit *init =
2991 g_new0(TCPCharDriverTelnetInit, 1);
2992 size_t n = 0;
2994 init->chr = chr;
2995 init->buflen = 12;
2997 #define IACSET(x, a, b, c) \
2998 do { \
2999 x[n++] = a; \
3000 x[n++] = b; \
3001 x[n++] = c; \
3002 } while (0)
3004 /* Prep the telnet negotion to put telnet in binary,
3005 * no echo, single char mode */
3006 IACSET(init->buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3007 IACSET(init->buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3008 IACSET(init->buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3009 IACSET(init->buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3011 #undef IACSET
3013 qio_channel_add_watch(
3014 s->ioc, G_IO_OUT,
3015 tcp_chr_telnet_init_io,
3016 init, NULL);
3020 static void tcp_chr_tls_handshake(Object *source,
3021 Error *err,
3022 gpointer user_data)
3024 CharDriverState *chr = user_data;
3025 TCPCharDriver *s = chr->opaque;
3027 if (err) {
3028 tcp_chr_disconnect(chr);
3029 } else {
3030 if (s->do_telnetopt) {
3031 tcp_chr_telnet_init(chr);
3032 } else {
3033 tcp_chr_connect(chr);
3039 static void tcp_chr_tls_init(CharDriverState *chr)
3041 TCPCharDriver *s = chr->opaque;
3042 QIOChannelTLS *tioc;
3043 Error *err = NULL;
3045 if (s->is_listen) {
3046 tioc = qio_channel_tls_new_server(
3047 s->ioc, s->tls_creds,
3048 NULL, /* XXX Use an ACL */
3049 &err);
3050 } else {
3051 tioc = qio_channel_tls_new_client(
3052 s->ioc, s->tls_creds,
3053 s->addr->u.inet.data->host,
3054 &err);
3056 if (tioc == NULL) {
3057 error_free(err);
3058 tcp_chr_disconnect(chr);
3060 object_unref(OBJECT(s->ioc));
3061 s->ioc = QIO_CHANNEL(tioc);
3063 qio_channel_tls_handshake(tioc,
3064 tcp_chr_tls_handshake,
3065 chr,
3066 NULL);
3070 static int tcp_chr_new_client(CharDriverState *chr, QIOChannelSocket *sioc)
3072 TCPCharDriver *s = chr->opaque;
3073 if (s->ioc != NULL) {
3074 return -1;
3077 s->ioc = QIO_CHANNEL(sioc);
3078 object_ref(OBJECT(sioc));
3079 s->sioc = sioc;
3080 object_ref(OBJECT(sioc));
3082 qio_channel_set_blocking(s->ioc, false, NULL);
3084 if (s->do_nodelay) {
3085 qio_channel_set_delay(s->ioc, false);
3087 if (s->listen_tag) {
3088 g_source_remove(s->listen_tag);
3089 s->listen_tag = 0;
3092 if (s->tls_creds) {
3093 tcp_chr_tls_init(chr);
3094 } else {
3095 if (s->do_telnetopt) {
3096 tcp_chr_telnet_init(chr);
3097 } else {
3098 tcp_chr_connect(chr);
3102 return 0;
3106 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3108 int ret;
3109 QIOChannelSocket *sioc;
3111 sioc = qio_channel_socket_new_fd(fd, NULL);
3112 if (!sioc) {
3113 return -1;
3115 ret = tcp_chr_new_client(chr, sioc);
3116 object_unref(OBJECT(sioc));
3117 return ret;
3120 static gboolean tcp_chr_accept(QIOChannel *channel,
3121 GIOCondition cond,
3122 void *opaque)
3124 CharDriverState *chr = opaque;
3125 QIOChannelSocket *sioc;
3127 sioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(channel),
3128 NULL);
3129 if (!sioc) {
3130 return TRUE;
3133 tcp_chr_new_client(chr, sioc);
3135 object_unref(OBJECT(sioc));
3137 return TRUE;
3140 static void tcp_chr_close(CharDriverState *chr)
3142 TCPCharDriver *s = chr->opaque;
3143 int i;
3145 if (s->reconnect_timer) {
3146 g_source_remove(s->reconnect_timer);
3147 s->reconnect_timer = 0;
3149 qapi_free_SocketAddress(s->addr);
3150 remove_fd_in_watch(chr);
3151 if (s->ioc) {
3152 object_unref(OBJECT(s->ioc));
3154 if (s->listen_tag) {
3155 g_source_remove(s->listen_tag);
3156 s->listen_tag = 0;
3158 if (s->listen_ioc) {
3159 object_unref(OBJECT(s->listen_ioc));
3161 if (s->read_msgfds_num) {
3162 for (i = 0; i < s->read_msgfds_num; i++) {
3163 close(s->read_msgfds[i]);
3165 g_free(s->read_msgfds);
3167 if (s->tls_creds) {
3168 object_unref(OBJECT(s->tls_creds));
3170 if (s->write_msgfds_num) {
3171 g_free(s->write_msgfds);
3173 g_free(s);
3174 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3178 static void qemu_chr_socket_connected(Object *src, Error *err, void *opaque)
3180 QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(src);
3181 CharDriverState *chr = opaque;
3182 TCPCharDriver *s = chr->opaque;
3184 if (err) {
3185 check_report_connect_error(chr, err);
3186 object_unref(src);
3187 return;
3190 s->connect_err_reported = false;
3191 tcp_chr_new_client(chr, sioc);
3192 object_unref(OBJECT(sioc));
3196 /*********************************************************/
3197 /* Ring buffer chardev */
3199 typedef struct {
3200 size_t size;
3201 size_t prod;
3202 size_t cons;
3203 uint8_t *cbuf;
3204 } RingBufCharDriver;
3206 static size_t ringbuf_count(const CharDriverState *chr)
3208 const RingBufCharDriver *d = chr->opaque;
3210 return d->prod - d->cons;
3213 /* Called with chr_write_lock held. */
3214 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3216 RingBufCharDriver *d = chr->opaque;
3217 int i;
3219 if (!buf || (len < 0)) {
3220 return -1;
3223 for (i = 0; i < len; i++ ) {
3224 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3225 if (d->prod - d->cons > d->size) {
3226 d->cons = d->prod - d->size;
3230 return 0;
3233 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3235 RingBufCharDriver *d = chr->opaque;
3236 int i;
3238 qemu_mutex_lock(&chr->chr_write_lock);
3239 for (i = 0; i < len && d->cons != d->prod; i++) {
3240 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3242 qemu_mutex_unlock(&chr->chr_write_lock);
3244 return i;
3247 static void ringbuf_chr_close(struct CharDriverState *chr)
3249 RingBufCharDriver *d = chr->opaque;
3251 g_free(d->cbuf);
3252 g_free(d);
3253 chr->opaque = NULL;
3256 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3257 ChardevBackend *backend,
3258 ChardevReturn *ret,
3259 Error **errp)
3261 ChardevRingbuf *opts = backend->u.ringbuf.data;
3262 ChardevCommon *common = qapi_ChardevRingbuf_base(opts);
3263 CharDriverState *chr;
3264 RingBufCharDriver *d;
3266 chr = qemu_chr_alloc(common, errp);
3267 if (!chr) {
3268 return NULL;
3270 d = g_malloc(sizeof(*d));
3272 d->size = opts->has_size ? opts->size : 65536;
3274 /* The size must be power of 2 */
3275 if (d->size & (d->size - 1)) {
3276 error_setg(errp, "size of ringbuf chardev must be power of two");
3277 goto fail;
3280 d->prod = 0;
3281 d->cons = 0;
3282 d->cbuf = g_malloc0(d->size);
3284 chr->opaque = d;
3285 chr->chr_write = ringbuf_chr_write;
3286 chr->chr_close = ringbuf_chr_close;
3288 return chr;
3290 fail:
3291 g_free(d);
3292 qemu_chr_free_common(chr);
3293 return NULL;
3296 bool chr_is_ringbuf(const CharDriverState *chr)
3298 return chr->chr_write == ringbuf_chr_write;
3301 void qmp_ringbuf_write(const char *device, const char *data,
3302 bool has_format, enum DataFormat format,
3303 Error **errp)
3305 CharDriverState *chr;
3306 const uint8_t *write_data;
3307 int ret;
3308 gsize write_count;
3310 chr = qemu_chr_find(device);
3311 if (!chr) {
3312 error_setg(errp, "Device '%s' not found", device);
3313 return;
3316 if (!chr_is_ringbuf(chr)) {
3317 error_setg(errp,"%s is not a ringbuf device", device);
3318 return;
3321 if (has_format && (format == DATA_FORMAT_BASE64)) {
3322 write_data = qbase64_decode(data, -1,
3323 &write_count,
3324 errp);
3325 if (!write_data) {
3326 return;
3328 } else {
3329 write_data = (uint8_t *)data;
3330 write_count = strlen(data);
3333 ret = ringbuf_chr_write(chr, write_data, write_count);
3335 if (write_data != (uint8_t *)data) {
3336 g_free((void *)write_data);
3339 if (ret < 0) {
3340 error_setg(errp, "Failed to write to device %s", device);
3341 return;
3345 char *qmp_ringbuf_read(const char *device, int64_t size,
3346 bool has_format, enum DataFormat format,
3347 Error **errp)
3349 CharDriverState *chr;
3350 uint8_t *read_data;
3351 size_t count;
3352 char *data;
3354 chr = qemu_chr_find(device);
3355 if (!chr) {
3356 error_setg(errp, "Device '%s' not found", device);
3357 return NULL;
3360 if (!chr_is_ringbuf(chr)) {
3361 error_setg(errp,"%s is not a ringbuf device", device);
3362 return NULL;
3365 if (size <= 0) {
3366 error_setg(errp, "size must be greater than zero");
3367 return NULL;
3370 count = ringbuf_count(chr);
3371 size = size > count ? count : size;
3372 read_data = g_malloc(size + 1);
3374 ringbuf_chr_read(chr, read_data, size);
3376 if (has_format && (format == DATA_FORMAT_BASE64)) {
3377 data = g_base64_encode(read_data, size);
3378 g_free(read_data);
3379 } else {
3381 * FIXME should read only complete, valid UTF-8 characters up
3382 * to @size bytes. Invalid sequences should be replaced by a
3383 * suitable replacement character. Except when (and only
3384 * when) ring buffer lost characters since last read, initial
3385 * continuation characters should be dropped.
3387 read_data[size] = 0;
3388 data = (char *)read_data;
3391 return data;
3394 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3396 char host[65], port[33], width[8], height[8];
3397 int pos;
3398 const char *p;
3399 QemuOpts *opts;
3400 Error *local_err = NULL;
3402 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3403 if (local_err) {
3404 error_report_err(local_err);
3405 return NULL;
3408 if (strstart(filename, "mon:", &p)) {
3409 filename = p;
3410 qemu_opt_set(opts, "mux", "on", &error_abort);
3411 if (strcmp(filename, "stdio") == 0) {
3412 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3413 * but pass it to the guest. Handle this only for compat syntax,
3414 * for -chardev syntax we have special option for this.
3415 * This is what -nographic did, redirecting+muxing serial+monitor
3416 * to stdio causing Ctrl+C to be passed to guest. */
3417 qemu_opt_set(opts, "signal", "off", &error_abort);
3421 if (strcmp(filename, "null") == 0 ||
3422 strcmp(filename, "pty") == 0 ||
3423 strcmp(filename, "msmouse") == 0 ||
3424 strcmp(filename, "braille") == 0 ||
3425 strcmp(filename, "testdev") == 0 ||
3426 strcmp(filename, "stdio") == 0) {
3427 qemu_opt_set(opts, "backend", filename, &error_abort);
3428 return opts;
3430 if (strstart(filename, "vc", &p)) {
3431 qemu_opt_set(opts, "backend", "vc", &error_abort);
3432 if (*p == ':') {
3433 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3434 /* pixels */
3435 qemu_opt_set(opts, "width", width, &error_abort);
3436 qemu_opt_set(opts, "height", height, &error_abort);
3437 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3438 /* chars */
3439 qemu_opt_set(opts, "cols", width, &error_abort);
3440 qemu_opt_set(opts, "rows", height, &error_abort);
3441 } else {
3442 goto fail;
3445 return opts;
3447 if (strcmp(filename, "con:") == 0) {
3448 qemu_opt_set(opts, "backend", "console", &error_abort);
3449 return opts;
3451 if (strstart(filename, "COM", NULL)) {
3452 qemu_opt_set(opts, "backend", "serial", &error_abort);
3453 qemu_opt_set(opts, "path", filename, &error_abort);
3454 return opts;
3456 if (strstart(filename, "file:", &p)) {
3457 qemu_opt_set(opts, "backend", "file", &error_abort);
3458 qemu_opt_set(opts, "path", p, &error_abort);
3459 return opts;
3461 if (strstart(filename, "pipe:", &p)) {
3462 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3463 qemu_opt_set(opts, "path", p, &error_abort);
3464 return opts;
3466 if (strstart(filename, "tcp:", &p) ||
3467 strstart(filename, "telnet:", &p)) {
3468 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3469 host[0] = 0;
3470 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3471 goto fail;
3473 qemu_opt_set(opts, "backend", "socket", &error_abort);
3474 qemu_opt_set(opts, "host", host, &error_abort);
3475 qemu_opt_set(opts, "port", port, &error_abort);
3476 if (p[pos] == ',') {
3477 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3478 if (local_err) {
3479 error_report_err(local_err);
3480 goto fail;
3483 if (strstart(filename, "telnet:", &p))
3484 qemu_opt_set(opts, "telnet", "on", &error_abort);
3485 return opts;
3487 if (strstart(filename, "udp:", &p)) {
3488 qemu_opt_set(opts, "backend", "udp", &error_abort);
3489 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3490 host[0] = 0;
3491 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3492 goto fail;
3495 qemu_opt_set(opts, "host", host, &error_abort);
3496 qemu_opt_set(opts, "port", port, &error_abort);
3497 if (p[pos] == '@') {
3498 p += pos + 1;
3499 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3500 host[0] = 0;
3501 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3502 goto fail;
3505 qemu_opt_set(opts, "localaddr", host, &error_abort);
3506 qemu_opt_set(opts, "localport", port, &error_abort);
3508 return opts;
3510 if (strstart(filename, "unix:", &p)) {
3511 qemu_opt_set(opts, "backend", "socket", &error_abort);
3512 qemu_opts_do_parse(opts, p, "path", &local_err);
3513 if (local_err) {
3514 error_report_err(local_err);
3515 goto fail;
3517 return opts;
3519 if (strstart(filename, "/dev/parport", NULL) ||
3520 strstart(filename, "/dev/ppi", NULL)) {
3521 qemu_opt_set(opts, "backend", "parport", &error_abort);
3522 qemu_opt_set(opts, "path", filename, &error_abort);
3523 return opts;
3525 if (strstart(filename, "/dev/", NULL)) {
3526 qemu_opt_set(opts, "backend", "tty", &error_abort);
3527 qemu_opt_set(opts, "path", filename, &error_abort);
3528 return opts;
3531 fail:
3532 qemu_opts_del(opts);
3533 return NULL;
3536 void qemu_chr_parse_common(QemuOpts *opts, ChardevCommon *backend)
3538 const char *logfile = qemu_opt_get(opts, "logfile");
3540 backend->has_logfile = logfile != NULL;
3541 backend->logfile = logfile ? g_strdup(logfile) : NULL;
3543 backend->has_logappend = true;
3544 backend->logappend = qemu_opt_get_bool(opts, "logappend", false);
3548 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3549 Error **errp)
3551 const char *path = qemu_opt_get(opts, "path");
3552 ChardevFile *file;
3554 if (path == NULL) {
3555 error_setg(errp, "chardev: file: no filename given");
3556 return;
3558 file = backend->u.file.data = g_new0(ChardevFile, 1);
3559 qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));
3560 file->out = g_strdup(path);
3562 file->has_append = true;
3563 file->append = qemu_opt_get_bool(opts, "append", false);
3566 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3567 Error **errp)
3569 ChardevStdio *stdio;
3571 stdio = backend->u.stdio.data = g_new0(ChardevStdio, 1);
3572 qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));
3573 stdio->has_signal = true;
3574 stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3577 #ifdef HAVE_CHARDEV_SERIAL
3578 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3579 Error **errp)
3581 const char *device = qemu_opt_get(opts, "path");
3582 ChardevHostdev *serial;
3584 if (device == NULL) {
3585 error_setg(errp, "chardev: serial/tty: no device path given");
3586 return;
3588 serial = backend->u.serial.data = g_new0(ChardevHostdev, 1);
3589 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(serial));
3590 serial->device = g_strdup(device);
3592 #endif
3594 #ifdef HAVE_CHARDEV_PARPORT
3595 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3596 Error **errp)
3598 const char *device = qemu_opt_get(opts, "path");
3599 ChardevHostdev *parallel;
3601 if (device == NULL) {
3602 error_setg(errp, "chardev: parallel: no device path given");
3603 return;
3605 parallel = backend->u.parallel.data = g_new0(ChardevHostdev, 1);
3606 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(parallel));
3607 parallel->device = g_strdup(device);
3609 #endif
3611 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3612 Error **errp)
3614 const char *device = qemu_opt_get(opts, "path");
3615 ChardevHostdev *dev;
3617 if (device == NULL) {
3618 error_setg(errp, "chardev: pipe: no device path given");
3619 return;
3621 dev = backend->u.pipe.data = g_new0(ChardevHostdev, 1);
3622 qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));
3623 dev->device = g_strdup(device);
3626 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3627 Error **errp)
3629 int val;
3630 ChardevRingbuf *ringbuf;
3632 ringbuf = backend->u.ringbuf.data = g_new0(ChardevRingbuf, 1);
3633 qemu_chr_parse_common(opts, qapi_ChardevRingbuf_base(ringbuf));
3635 val = qemu_opt_get_size(opts, "size", 0);
3636 if (val != 0) {
3637 ringbuf->has_size = true;
3638 ringbuf->size = val;
3642 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3643 Error **errp)
3645 const char *chardev = qemu_opt_get(opts, "chardev");
3646 ChardevMux *mux;
3648 if (chardev == NULL) {
3649 error_setg(errp, "chardev: mux: no chardev given");
3650 return;
3652 mux = backend->u.mux.data = g_new0(ChardevMux, 1);
3653 qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));
3654 mux->chardev = g_strdup(chardev);
3657 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3658 Error **errp)
3660 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3661 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3662 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3663 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3664 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3665 const char *path = qemu_opt_get(opts, "path");
3666 const char *host = qemu_opt_get(opts, "host");
3667 const char *port = qemu_opt_get(opts, "port");
3668 const char *tls_creds = qemu_opt_get(opts, "tls-creds");
3669 SocketAddress *addr;
3670 ChardevSocket *sock;
3672 if (!path) {
3673 if (!host) {
3674 error_setg(errp, "chardev: socket: no host given");
3675 return;
3677 if (!port) {
3678 error_setg(errp, "chardev: socket: no port given");
3679 return;
3681 } else {
3682 if (tls_creds) {
3683 error_setg(errp, "TLS can only be used over TCP socket");
3684 return;
3688 sock = backend->u.socket.data = g_new0(ChardevSocket, 1);
3689 qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));
3691 sock->has_nodelay = true;
3692 sock->nodelay = do_nodelay;
3693 sock->has_server = true;
3694 sock->server = is_listen;
3695 sock->has_telnet = true;
3696 sock->telnet = is_telnet;
3697 sock->has_wait = true;
3698 sock->wait = is_waitconnect;
3699 sock->has_reconnect = true;
3700 sock->reconnect = reconnect;
3701 sock->tls_creds = g_strdup(tls_creds);
3703 addr = g_new0(SocketAddress, 1);
3704 if (path) {
3705 UnixSocketAddress *q_unix;
3706 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3707 q_unix = addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
3708 q_unix->path = g_strdup(path);
3709 } else {
3710 addr->type = SOCKET_ADDRESS_KIND_INET;
3711 addr->u.inet.data = g_new(InetSocketAddress, 1);
3712 *addr->u.inet.data = (InetSocketAddress) {
3713 .host = g_strdup(host),
3714 .port = g_strdup(port),
3715 .has_to = qemu_opt_get(opts, "to"),
3716 .to = qemu_opt_get_number(opts, "to", 0),
3717 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3718 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3719 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3720 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3723 sock->addr = addr;
3726 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3727 Error **errp)
3729 const char *host = qemu_opt_get(opts, "host");
3730 const char *port = qemu_opt_get(opts, "port");
3731 const char *localaddr = qemu_opt_get(opts, "localaddr");
3732 const char *localport = qemu_opt_get(opts, "localport");
3733 bool has_local = false;
3734 SocketAddress *addr;
3735 ChardevUdp *udp;
3737 if (host == NULL || strlen(host) == 0) {
3738 host = "localhost";
3740 if (port == NULL || strlen(port) == 0) {
3741 error_setg(errp, "chardev: udp: remote port not specified");
3742 return;
3744 if (localport == NULL || strlen(localport) == 0) {
3745 localport = "0";
3746 } else {
3747 has_local = true;
3749 if (localaddr == NULL || strlen(localaddr) == 0) {
3750 localaddr = "";
3751 } else {
3752 has_local = true;
3755 udp = backend->u.udp.data = g_new0(ChardevUdp, 1);
3756 qemu_chr_parse_common(opts, qapi_ChardevUdp_base(udp));
3758 addr = g_new0(SocketAddress, 1);
3759 addr->type = SOCKET_ADDRESS_KIND_INET;
3760 addr->u.inet.data = g_new(InetSocketAddress, 1);
3761 *addr->u.inet.data = (InetSocketAddress) {
3762 .host = g_strdup(host),
3763 .port = g_strdup(port),
3764 .has_ipv4 = qemu_opt_get(opts, "ipv4"),
3765 .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),
3766 .has_ipv6 = qemu_opt_get(opts, "ipv6"),
3767 .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),
3769 udp->remote = addr;
3771 if (has_local) {
3772 udp->has_local = true;
3773 addr = g_new0(SocketAddress, 1);
3774 addr->type = SOCKET_ADDRESS_KIND_INET;
3775 addr->u.inet.data = g_new(InetSocketAddress, 1);
3776 *addr->u.inet.data = (InetSocketAddress) {
3777 .host = g_strdup(localaddr),
3778 .port = g_strdup(localport),
3780 udp->local = addr;
3784 typedef struct CharDriver {
3785 const char *name;
3786 ChardevBackendKind kind;
3787 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3788 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3789 ChardevReturn *ret, Error **errp);
3790 } CharDriver;
3792 static GSList *backends;
3794 void register_char_driver(const char *name, ChardevBackendKind kind,
3795 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3796 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3797 ChardevReturn *ret, Error **errp))
3799 CharDriver *s;
3801 s = g_malloc0(sizeof(*s));
3802 s->name = g_strdup(name);
3803 s->kind = kind;
3804 s->parse = parse;
3805 s->create = create;
3807 backends = g_slist_append(backends, s);
3810 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3811 void (*init)(struct CharDriverState *s),
3812 Error **errp)
3814 Error *local_err = NULL;
3815 CharDriver *cd;
3816 CharDriverState *chr;
3817 GSList *i;
3818 ChardevReturn *ret = NULL;
3819 ChardevBackend *backend;
3820 const char *id = qemu_opts_id(opts);
3821 char *bid = NULL;
3823 if (id == NULL) {
3824 error_setg(errp, "chardev: no id specified");
3825 goto err;
3828 if (qemu_opt_get(opts, "backend") == NULL) {
3829 error_setg(errp, "chardev: \"%s\" missing backend",
3830 qemu_opts_id(opts));
3831 goto err;
3833 for (i = backends; i; i = i->next) {
3834 cd = i->data;
3836 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3837 break;
3840 if (i == NULL) {
3841 error_setg(errp, "chardev: backend \"%s\" not found",
3842 qemu_opt_get(opts, "backend"));
3843 goto err;
3846 backend = g_new0(ChardevBackend, 1);
3848 if (qemu_opt_get_bool(opts, "mux", 0)) {
3849 bid = g_strdup_printf("%s-base", id);
3852 chr = NULL;
3853 backend->type = cd->kind;
3854 if (cd->parse) {
3855 cd->parse(opts, backend, &local_err);
3856 if (local_err) {
3857 error_propagate(errp, local_err);
3858 goto qapi_out;
3860 } else {
3861 ChardevCommon *cc = g_new0(ChardevCommon, 1);
3862 qemu_chr_parse_common(opts, cc);
3863 backend->u.null.data = cc; /* Any ChardevCommon member would work */
3866 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3867 if (!ret) {
3868 goto qapi_out;
3871 if (bid) {
3872 qapi_free_ChardevBackend(backend);
3873 qapi_free_ChardevReturn(ret);
3874 backend = g_new0(ChardevBackend, 1);
3875 backend->u.mux.data = g_new0(ChardevMux, 1);
3876 backend->type = CHARDEV_BACKEND_KIND_MUX;
3877 backend->u.mux.data->chardev = g_strdup(bid);
3878 ret = qmp_chardev_add(id, backend, errp);
3879 if (!ret) {
3880 chr = qemu_chr_find(bid);
3881 qemu_chr_delete(chr);
3882 chr = NULL;
3883 goto qapi_out;
3887 chr = qemu_chr_find(id);
3888 chr->opts = opts;
3890 qapi_out:
3891 qapi_free_ChardevBackend(backend);
3892 qapi_free_ChardevReturn(ret);
3893 g_free(bid);
3894 return chr;
3896 err:
3897 qemu_opts_del(opts);
3898 return NULL;
3901 CharDriverState *qemu_chr_new_noreplay(const char *label, const char *filename,
3902 void (*init)(struct CharDriverState *s))
3904 const char *p;
3905 CharDriverState *chr;
3906 QemuOpts *opts;
3907 Error *err = NULL;
3909 if (strstart(filename, "chardev:", &p)) {
3910 return qemu_chr_find(p);
3913 opts = qemu_chr_parse_compat(label, filename);
3914 if (!opts)
3915 return NULL;
3917 chr = qemu_chr_new_from_opts(opts, init, &err);
3918 if (err) {
3919 error_report_err(err);
3921 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3922 qemu_chr_fe_claim_no_fail(chr);
3923 monitor_init(chr, MONITOR_USE_READLINE);
3925 return chr;
3928 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3930 CharDriverState *chr;
3931 chr = qemu_chr_new_noreplay(label, filename, init);
3932 if (chr) {
3933 chr->replay = replay_mode != REPLAY_MODE_NONE;
3934 if (chr->replay && chr->chr_ioctl) {
3935 fprintf(stderr,
3936 "Replay: ioctl is not supported for serial devices yet\n");
3938 replay_register_char_driver(chr);
3940 return chr;
3943 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3945 if (chr->chr_set_echo) {
3946 chr->chr_set_echo(chr, echo);
3950 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3952 if (chr->fe_open == fe_open) {
3953 return;
3955 chr->fe_open = fe_open;
3956 if (chr->chr_set_fe_open) {
3957 chr->chr_set_fe_open(chr, fe_open);
3961 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3963 if (chr->chr_fe_event) {
3964 chr->chr_fe_event(chr, event);
3968 guint qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3969 GIOFunc func, void *user_data)
3971 GSource *src;
3972 guint tag;
3974 if (s->chr_add_watch == NULL) {
3975 return 0;
3978 src = s->chr_add_watch(s, cond);
3979 if (!src) {
3980 return 0;
3983 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3984 tag = g_source_attach(src, NULL);
3985 g_source_unref(src);
3987 return tag;
3990 int qemu_chr_fe_claim(CharDriverState *s)
3992 if (s->avail_connections < 1) {
3993 return -1;
3995 s->avail_connections--;
3996 return 0;
3999 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
4001 if (qemu_chr_fe_claim(s) != 0) {
4002 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
4003 __func__, s->label);
4004 exit(1);
4008 void qemu_chr_fe_release(CharDriverState *s)
4010 s->avail_connections++;
4013 void qemu_chr_disconnect(CharDriverState *chr)
4015 if (chr->chr_disconnect) {
4016 chr->chr_disconnect(chr);
4020 static void qemu_chr_free_common(CharDriverState *chr)
4022 g_free(chr->filename);
4023 g_free(chr->label);
4024 qemu_opts_del(chr->opts);
4025 if (chr->logfd != -1) {
4026 close(chr->logfd);
4028 qemu_mutex_destroy(&chr->chr_write_lock);
4029 g_free(chr);
4032 void qemu_chr_free(CharDriverState *chr)
4034 if (chr->chr_close) {
4035 chr->chr_close(chr);
4037 qemu_chr_free_common(chr);
4040 void qemu_chr_delete(CharDriverState *chr)
4042 QTAILQ_REMOVE(&chardevs, chr, next);
4043 qemu_chr_free(chr);
4046 ChardevInfoList *qmp_query_chardev(Error **errp)
4048 ChardevInfoList *chr_list = NULL;
4049 CharDriverState *chr;
4051 QTAILQ_FOREACH(chr, &chardevs, next) {
4052 ChardevInfoList *info = g_malloc0(sizeof(*info));
4053 info->value = g_malloc0(sizeof(*info->value));
4054 info->value->label = g_strdup(chr->label);
4055 info->value->filename = g_strdup(chr->filename);
4056 info->value->frontend_open = chr->fe_open;
4058 info->next = chr_list;
4059 chr_list = info;
4062 return chr_list;
4065 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
4067 ChardevBackendInfoList *backend_list = NULL;
4068 CharDriver *c = NULL;
4069 GSList *i = NULL;
4071 for (i = backends; i; i = i->next) {
4072 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
4073 c = i->data;
4074 info->value = g_malloc0(sizeof(*info->value));
4075 info->value->name = g_strdup(c->name);
4077 info->next = backend_list;
4078 backend_list = info;
4081 return backend_list;
4084 CharDriverState *qemu_chr_find(const char *name)
4086 CharDriverState *chr;
4088 QTAILQ_FOREACH(chr, &chardevs, next) {
4089 if (strcmp(chr->label, name) != 0)
4090 continue;
4091 return chr;
4093 return NULL;
4096 QemuOptsList qemu_chardev_opts = {
4097 .name = "chardev",
4098 .implied_opt_name = "backend",
4099 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
4100 .desc = {
4102 .name = "backend",
4103 .type = QEMU_OPT_STRING,
4105 .name = "path",
4106 .type = QEMU_OPT_STRING,
4108 .name = "host",
4109 .type = QEMU_OPT_STRING,
4111 .name = "port",
4112 .type = QEMU_OPT_STRING,
4114 .name = "localaddr",
4115 .type = QEMU_OPT_STRING,
4117 .name = "localport",
4118 .type = QEMU_OPT_STRING,
4120 .name = "to",
4121 .type = QEMU_OPT_NUMBER,
4123 .name = "ipv4",
4124 .type = QEMU_OPT_BOOL,
4126 .name = "ipv6",
4127 .type = QEMU_OPT_BOOL,
4129 .name = "wait",
4130 .type = QEMU_OPT_BOOL,
4132 .name = "server",
4133 .type = QEMU_OPT_BOOL,
4135 .name = "delay",
4136 .type = QEMU_OPT_BOOL,
4138 .name = "reconnect",
4139 .type = QEMU_OPT_NUMBER,
4141 .name = "telnet",
4142 .type = QEMU_OPT_BOOL,
4144 .name = "tls-creds",
4145 .type = QEMU_OPT_STRING,
4147 .name = "width",
4148 .type = QEMU_OPT_NUMBER,
4150 .name = "height",
4151 .type = QEMU_OPT_NUMBER,
4153 .name = "cols",
4154 .type = QEMU_OPT_NUMBER,
4156 .name = "rows",
4157 .type = QEMU_OPT_NUMBER,
4159 .name = "mux",
4160 .type = QEMU_OPT_BOOL,
4162 .name = "signal",
4163 .type = QEMU_OPT_BOOL,
4165 .name = "name",
4166 .type = QEMU_OPT_STRING,
4168 .name = "debug",
4169 .type = QEMU_OPT_NUMBER,
4171 .name = "size",
4172 .type = QEMU_OPT_SIZE,
4174 .name = "chardev",
4175 .type = QEMU_OPT_STRING,
4177 .name = "append",
4178 .type = QEMU_OPT_BOOL,
4180 .name = "logfile",
4181 .type = QEMU_OPT_STRING,
4183 .name = "logappend",
4184 .type = QEMU_OPT_BOOL,
4186 { /* end of list */ }
4190 #ifdef _WIN32
4192 static CharDriverState *qmp_chardev_open_file(const char *id,
4193 ChardevBackend *backend,
4194 ChardevReturn *ret,
4195 Error **errp)
4197 ChardevFile *file = backend->u.file.data;
4198 ChardevCommon *common = qapi_ChardevFile_base(file);
4199 HANDLE out;
4201 if (file->has_in) {
4202 error_setg(errp, "input file not supported");
4203 return NULL;
4206 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
4207 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
4208 if (out == INVALID_HANDLE_VALUE) {
4209 error_setg(errp, "open %s failed", file->out);
4210 return NULL;
4212 return qemu_chr_open_win_file(out, common, errp);
4215 static CharDriverState *qmp_chardev_open_serial(const char *id,
4216 ChardevBackend *backend,
4217 ChardevReturn *ret,
4218 Error **errp)
4220 ChardevHostdev *serial = backend->u.serial.data;
4221 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4222 return qemu_chr_open_win_path(serial->device, common, errp);
4225 #else /* WIN32 */
4227 static int qmp_chardev_open_file_source(char *src, int flags,
4228 Error **errp)
4230 int fd = -1;
4232 TFR(fd = qemu_open(src, flags, 0666));
4233 if (fd == -1) {
4234 error_setg_file_open(errp, errno, src);
4236 return fd;
4239 static CharDriverState *qmp_chardev_open_file(const char *id,
4240 ChardevBackend *backend,
4241 ChardevReturn *ret,
4242 Error **errp)
4244 ChardevFile *file = backend->u.file.data;
4245 ChardevCommon *common = qapi_ChardevFile_base(file);
4246 int flags, in = -1, out;
4248 flags = O_WRONLY | O_CREAT | O_BINARY;
4249 if (file->has_append && file->append) {
4250 flags |= O_APPEND;
4251 } else {
4252 flags |= O_TRUNC;
4255 out = qmp_chardev_open_file_source(file->out, flags, errp);
4256 if (out < 0) {
4257 return NULL;
4260 if (file->has_in) {
4261 flags = O_RDONLY;
4262 in = qmp_chardev_open_file_source(file->in, flags, errp);
4263 if (in < 0) {
4264 qemu_close(out);
4265 return NULL;
4269 return qemu_chr_open_fd(in, out, common, errp);
4272 #ifdef HAVE_CHARDEV_SERIAL
4273 static CharDriverState *qmp_chardev_open_serial(const char *id,
4274 ChardevBackend *backend,
4275 ChardevReturn *ret,
4276 Error **errp)
4278 ChardevHostdev *serial = backend->u.serial.data;
4279 ChardevCommon *common = qapi_ChardevHostdev_base(serial);
4280 int fd;
4282 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4283 if (fd < 0) {
4284 return NULL;
4286 qemu_set_nonblock(fd);
4287 return qemu_chr_open_tty_fd(fd, common, errp);
4289 #endif
4291 #ifdef HAVE_CHARDEV_PARPORT
4292 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4293 ChardevBackend *backend,
4294 ChardevReturn *ret,
4295 Error **errp)
4297 ChardevHostdev *parallel = backend->u.parallel.data;
4298 ChardevCommon *common = qapi_ChardevHostdev_base(parallel);
4299 int fd;
4301 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4302 if (fd < 0) {
4303 return NULL;
4305 return qemu_chr_open_pp_fd(fd, common, errp);
4307 #endif
4309 #endif /* WIN32 */
4311 static gboolean socket_reconnect_timeout(gpointer opaque)
4313 CharDriverState *chr = opaque;
4314 TCPCharDriver *s = chr->opaque;
4315 QIOChannelSocket *sioc;
4317 s->reconnect_timer = 0;
4319 if (chr->be_open) {
4320 return false;
4323 sioc = qio_channel_socket_new();
4324 qio_channel_socket_connect_async(sioc, s->addr,
4325 qemu_chr_socket_connected,
4326 chr, NULL);
4328 return false;
4331 static CharDriverState *qmp_chardev_open_socket(const char *id,
4332 ChardevBackend *backend,
4333 ChardevReturn *ret,
4334 Error **errp)
4336 CharDriverState *chr;
4337 TCPCharDriver *s;
4338 ChardevSocket *sock = backend->u.socket.data;
4339 SocketAddress *addr = sock->addr;
4340 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4341 bool is_listen = sock->has_server ? sock->server : true;
4342 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4343 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4344 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4345 ChardevCommon *common = qapi_ChardevSocket_base(sock);
4346 QIOChannelSocket *sioc = NULL;
4348 chr = qemu_chr_alloc(common, errp);
4349 if (!chr) {
4350 return NULL;
4352 s = g_new0(TCPCharDriver, 1);
4354 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4355 s->is_listen = is_listen;
4356 s->is_telnet = is_telnet;
4357 s->do_nodelay = do_nodelay;
4358 if (sock->tls_creds) {
4359 Object *creds;
4360 creds = object_resolve_path_component(
4361 object_get_objects_root(), sock->tls_creds);
4362 if (!creds) {
4363 error_setg(errp, "No TLS credentials with id '%s'",
4364 sock->tls_creds);
4365 goto error;
4367 s->tls_creds = (QCryptoTLSCreds *)
4368 object_dynamic_cast(creds,
4369 TYPE_QCRYPTO_TLS_CREDS);
4370 if (!s->tls_creds) {
4371 error_setg(errp, "Object with id '%s' is not TLS credentials",
4372 sock->tls_creds);
4373 goto error;
4375 object_ref(OBJECT(s->tls_creds));
4376 if (is_listen) {
4377 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
4378 error_setg(errp, "%s",
4379 "Expected TLS credentials for server endpoint");
4380 goto error;
4382 } else {
4383 if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
4384 error_setg(errp, "%s",
4385 "Expected TLS credentials for client endpoint");
4386 goto error;
4391 s->addr = QAPI_CLONE(SocketAddress, sock->addr);
4393 chr->opaque = s;
4394 chr->chr_write = tcp_chr_write;
4395 chr->chr_sync_read = tcp_chr_sync_read;
4396 chr->chr_close = tcp_chr_close;
4397 chr->chr_disconnect = tcp_chr_disconnect;
4398 chr->get_msgfds = tcp_get_msgfds;
4399 chr->set_msgfds = tcp_set_msgfds;
4400 chr->chr_add_client = tcp_chr_add_client;
4401 chr->chr_add_watch = tcp_chr_add_watch;
4402 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4403 /* be isn't opened until we get a connection */
4404 chr->explicit_be_open = true;
4406 chr->filename = SocketAddress_to_str("disconnected:",
4407 addr, is_listen, is_telnet);
4409 if (is_listen) {
4410 if (is_telnet) {
4411 s->do_telnetopt = 1;
4413 } else if (reconnect > 0) {
4414 s->reconnect_time = reconnect;
4417 sioc = qio_channel_socket_new();
4418 if (s->reconnect_time) {
4419 qio_channel_socket_connect_async(sioc, s->addr,
4420 qemu_chr_socket_connected,
4421 chr, NULL);
4422 } else if (s->is_listen) {
4423 if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {
4424 goto error;
4426 s->listen_ioc = sioc;
4427 if (is_waitconnect) {
4428 fprintf(stderr, "QEMU waiting for connection on: %s\n",
4429 chr->filename);
4430 tcp_chr_accept(QIO_CHANNEL(s->listen_ioc), G_IO_IN, chr);
4432 qio_channel_set_blocking(QIO_CHANNEL(s->listen_ioc), false, NULL);
4433 if (!s->ioc) {
4434 s->listen_tag = qio_channel_add_watch(
4435 QIO_CHANNEL(s->listen_ioc), G_IO_IN, tcp_chr_accept, chr, NULL);
4437 } else {
4438 if (qio_channel_socket_connect_sync(sioc, s->addr, errp) < 0) {
4439 goto error;
4441 tcp_chr_new_client(chr, sioc);
4442 object_unref(OBJECT(sioc));
4445 return chr;
4447 error:
4448 if (sioc) {
4449 object_unref(OBJECT(sioc));
4451 if (s->tls_creds) {
4452 object_unref(OBJECT(s->tls_creds));
4454 g_free(s);
4455 qemu_chr_free_common(chr);
4456 return NULL;
4459 static CharDriverState *qmp_chardev_open_udp(const char *id,
4460 ChardevBackend *backend,
4461 ChardevReturn *ret,
4462 Error **errp)
4464 ChardevUdp *udp = backend->u.udp.data;
4465 ChardevCommon *common = qapi_ChardevUdp_base(udp);
4466 QIOChannelSocket *sioc = qio_channel_socket_new();
4468 if (qio_channel_socket_dgram_sync(sioc,
4469 udp->local, udp->remote,
4470 errp) < 0) {
4471 object_unref(OBJECT(sioc));
4472 return NULL;
4474 return qemu_chr_open_udp(sioc, common, errp);
4477 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4478 Error **errp)
4480 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4481 CharDriverState *chr = NULL;
4482 Error *local_err = NULL;
4483 GSList *i;
4484 CharDriver *cd;
4486 chr = qemu_chr_find(id);
4487 if (chr) {
4488 error_setg(errp, "Chardev '%s' already exists", id);
4489 g_free(ret);
4490 return NULL;
4493 for (i = backends; i; i = i->next) {
4494 cd = i->data;
4496 if (cd->kind == backend->type) {
4497 chr = cd->create(id, backend, ret, &local_err);
4498 if (local_err) {
4499 error_propagate(errp, local_err);
4500 goto out_error;
4502 break;
4506 if (chr == NULL) {
4507 assert(!i);
4508 error_setg(errp, "chardev backend not available");
4509 goto out_error;
4512 chr->label = g_strdup(id);
4513 chr->avail_connections =
4514 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4515 if (!chr->filename) {
4516 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4518 if (!chr->explicit_be_open) {
4519 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4521 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4522 return ret;
4524 out_error:
4525 g_free(ret);
4526 return NULL;
4529 void qmp_chardev_remove(const char *id, Error **errp)
4531 CharDriverState *chr;
4533 chr = qemu_chr_find(id);
4534 if (chr == NULL) {
4535 error_setg(errp, "Chardev '%s' not found", id);
4536 return;
4538 if (chr->chr_can_read || chr->chr_read ||
4539 chr->chr_event || chr->handler_opaque) {
4540 error_setg(errp, "Chardev '%s' is busy", id);
4541 return;
4543 if (chr->replay) {
4544 error_setg(errp,
4545 "Chardev '%s' cannot be unplugged in record/replay mode", id);
4546 return;
4548 qemu_chr_delete(chr);
4551 void qemu_chr_cleanup(void)
4553 CharDriverState *chr, *tmp;
4555 QTAILQ_FOREACH_SAFE(chr, &chardevs, next, tmp) {
4556 qemu_chr_delete(chr);
4560 static void register_types(void)
4562 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4563 qemu_chr_open_null);
4564 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4565 qemu_chr_parse_socket, qmp_chardev_open_socket);
4566 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4567 qmp_chardev_open_udp);
4568 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4569 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4570 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4571 qemu_chr_parse_file_out, qmp_chardev_open_file);
4572 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4573 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4574 #if defined HAVE_CHARDEV_SERIAL
4575 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4576 qemu_chr_parse_serial, qmp_chardev_open_serial);
4577 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4578 qemu_chr_parse_serial, qmp_chardev_open_serial);
4579 #endif
4580 #ifdef HAVE_CHARDEV_PARPORT
4581 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4582 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4583 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4584 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4585 #endif
4586 #ifdef HAVE_CHARDEV_PTY
4587 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4588 qemu_chr_open_pty);
4589 #endif
4590 #ifdef _WIN32
4591 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4592 qemu_chr_open_win_con);
4593 #endif
4594 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4595 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4596 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4597 qemu_chr_open_mux);
4598 /* Bug-compatibility: */
4599 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4600 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4601 /* this must be done after machine init, since we register FEs with muxes
4602 * as part of realize functions like serial_isa_realizefn when -nographic
4603 * is specified
4605 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4608 type_init(register_types);