9pfs: merge hw/virtio/virtio-9p.h into hw/9pfs/virtio-9p.h
[qemu/ar7.git] / qemu-char.c
blob00a7526761b3c7f190f4e0021a49954e2ffb4aa1
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-common.h"
25 #include "monitor/monitor.h"
26 #include "sysemu/sysemu.h"
27 #include "qemu/error-report.h"
28 #include "qemu/timer.h"
29 #include "sysemu/char.h"
30 #include "hw/usb.h"
31 #include "qmp-commands.h"
32 #include "qapi/qmp-input-visitor.h"
33 #include "qapi/qmp-output-visitor.h"
34 #include "qapi-visit.h"
35 #include "qemu/base64.h"
37 #include <unistd.h>
38 #include <fcntl.h>
39 #include <time.h>
40 #include <errno.h>
41 #include <sys/time.h>
42 #include <zlib.h>
44 #ifndef _WIN32
45 #include <sys/times.h>
46 #include <sys/wait.h>
47 #include <termios.h>
48 #include <sys/mman.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 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
60 #include <dev/ppbus/ppi.h>
61 #include <dev/ppbus/ppbconf.h>
62 #elif defined(__DragonFly__)
63 #include <dev/misc/ppi/ppi.h>
64 #include <bus/ppbus/ppbconf.h>
65 #endif
66 #else
67 #ifdef __linux__
68 #include <linux/ppdev.h>
69 #include <linux/parport.h>
70 #endif
71 #ifdef __sun__
72 #include <sys/stat.h>
73 #include <sys/ethernet.h>
74 #include <sys/sockio.h>
75 #include <netinet/arp.h>
76 #include <netinet/in.h>
77 #include <netinet/in_systm.h>
78 #include <netinet/ip.h>
79 #include <netinet/ip_icmp.h> // must come after ip.h
80 #include <netinet/udp.h>
81 #include <netinet/tcp.h>
82 #endif
83 #endif
84 #endif
86 #include "qemu/sockets.h"
87 #include "ui/qemu-spice.h"
89 #define READ_BUF_LEN 4096
90 #define READ_RETRIES 10
91 #define CHR_MAX_FILENAME_SIZE 256
92 #define TCP_MAX_FDS 16
94 /***********************************************************/
95 /* Socket address helpers */
97 static int SocketAddress_to_str(char *dest, int max_len,
98 const char *prefix, SocketAddress *addr,
99 bool is_listen, bool is_telnet)
101 switch (addr->type) {
102 case SOCKET_ADDRESS_KIND_INET:
103 return snprintf(dest, max_len, "%s%s:%s:%s%s", prefix,
104 is_telnet ? "telnet" : "tcp", addr->u.inet->host,
105 addr->u.inet->port, is_listen ? ",server" : "");
106 break;
107 case SOCKET_ADDRESS_KIND_UNIX:
108 return snprintf(dest, max_len, "%sunix:%s%s", prefix,
109 addr->u.q_unix->path, is_listen ? ",server" : "");
110 break;
111 case SOCKET_ADDRESS_KIND_FD:
112 return snprintf(dest, max_len, "%sfd:%s%s", prefix, addr->u.fd->str,
113 is_listen ? ",server" : "");
114 break;
115 default:
116 abort();
120 static int sockaddr_to_str(char *dest, int max_len,
121 struct sockaddr_storage *ss, socklen_t ss_len,
122 struct sockaddr_storage *ps, socklen_t ps_len,
123 bool is_listen, bool is_telnet)
125 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
126 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
127 const char *left = "", *right = "";
129 switch (ss->ss_family) {
130 #ifndef _WIN32
131 case AF_UNIX:
132 return snprintf(dest, max_len, "unix:%s%s",
133 ((struct sockaddr_un *)(ss))->sun_path,
134 is_listen ? ",server" : "");
135 #endif
136 case AF_INET6:
137 left = "[";
138 right = "]";
139 /* fall through */
140 case AF_INET:
141 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
142 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
143 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
144 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
145 return snprintf(dest, max_len, "%s:%s%s%s:%s%s <-> %s%s%s:%s",
146 is_telnet ? "telnet" : "tcp",
147 left, shost, right, sserv,
148 is_listen ? ",server" : "",
149 left, phost, right, pserv);
151 default:
152 return snprintf(dest, max_len, "unknown");
156 /***********************************************************/
157 /* character device */
159 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
160 QTAILQ_HEAD_INITIALIZER(chardevs);
162 CharDriverState *qemu_chr_alloc(void)
164 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
165 qemu_mutex_init(&chr->chr_write_lock);
166 return chr;
169 void qemu_chr_be_event(CharDriverState *s, int event)
171 /* Keep track if the char device is open */
172 switch (event) {
173 case CHR_EVENT_OPENED:
174 s->be_open = 1;
175 break;
176 case CHR_EVENT_CLOSED:
177 s->be_open = 0;
178 break;
181 if (!s->chr_event)
182 return;
183 s->chr_event(s->handler_opaque, event);
186 void qemu_chr_be_generic_open(CharDriverState *s)
188 qemu_chr_be_event(s, CHR_EVENT_OPENED);
191 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
193 int ret;
195 qemu_mutex_lock(&s->chr_write_lock);
196 ret = s->chr_write(s, buf, len);
197 qemu_mutex_unlock(&s->chr_write_lock);
198 return ret;
201 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
203 int offset = 0;
204 int res = 0;
206 qemu_mutex_lock(&s->chr_write_lock);
207 while (offset < len) {
208 do {
209 res = s->chr_write(s, buf + offset, len - offset);
210 if (res == -1 && errno == EAGAIN) {
211 g_usleep(100);
213 } while (res == -1 && errno == EAGAIN);
215 if (res <= 0) {
216 break;
219 offset += res;
221 qemu_mutex_unlock(&s->chr_write_lock);
223 if (res < 0) {
224 return res;
226 return offset;
229 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
231 int offset = 0, counter = 10;
232 int res;
234 if (!s->chr_sync_read) {
235 return 0;
238 while (offset < len) {
239 do {
240 res = s->chr_sync_read(s, buf + offset, len - offset);
241 if (res == -1 && errno == EAGAIN) {
242 g_usleep(100);
244 } while (res == -1 && errno == EAGAIN);
246 if (res == 0) {
247 break;
250 if (res < 0) {
251 return res;
254 offset += res;
256 if (!counter--) {
257 break;
261 return offset;
264 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
266 if (!s->chr_ioctl)
267 return -ENOTSUP;
268 return s->chr_ioctl(s, cmd, arg);
271 int qemu_chr_be_can_write(CharDriverState *s)
273 if (!s->chr_can_read)
274 return 0;
275 return s->chr_can_read(s->handler_opaque);
278 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
280 if (s->chr_read) {
281 s->chr_read(s->handler_opaque, buf, len);
285 int qemu_chr_fe_get_msgfd(CharDriverState *s)
287 int fd;
288 return (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
291 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
293 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
296 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
298 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
301 int qemu_chr_add_client(CharDriverState *s, int fd)
303 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
306 void qemu_chr_accept_input(CharDriverState *s)
308 if (s->chr_accept_input)
309 s->chr_accept_input(s);
310 qemu_notify_event();
313 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
315 char buf[READ_BUF_LEN];
316 va_list ap;
317 va_start(ap, fmt);
318 vsnprintf(buf, sizeof(buf), fmt, ap);
319 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
320 va_end(ap);
323 static void remove_fd_in_watch(CharDriverState *chr);
325 void qemu_chr_add_handlers(CharDriverState *s,
326 IOCanReadHandler *fd_can_read,
327 IOReadHandler *fd_read,
328 IOEventHandler *fd_event,
329 void *opaque)
331 int fe_open;
333 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
334 fe_open = 0;
335 remove_fd_in_watch(s);
336 } else {
337 fe_open = 1;
339 s->chr_can_read = fd_can_read;
340 s->chr_read = fd_read;
341 s->chr_event = fd_event;
342 s->handler_opaque = opaque;
343 if (fe_open && s->chr_update_read_handler)
344 s->chr_update_read_handler(s);
346 if (!s->explicit_fe_open) {
347 qemu_chr_fe_set_open(s, fe_open);
350 /* We're connecting to an already opened device, so let's make sure we
351 also get the open event */
352 if (fe_open && s->be_open) {
353 qemu_chr_be_generic_open(s);
357 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
359 return len;
362 static CharDriverState *qemu_chr_open_null(const char *id,
363 ChardevBackend *backend,
364 ChardevReturn *ret,
365 Error **errp)
367 CharDriverState *chr;
369 chr = qemu_chr_alloc();
370 chr->chr_write = null_chr_write;
371 chr->explicit_be_open = true;
372 return chr;
375 /* MUX driver for serial I/O splitting */
376 #define MAX_MUX 4
377 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
378 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
379 typedef struct {
380 IOCanReadHandler *chr_can_read[MAX_MUX];
381 IOReadHandler *chr_read[MAX_MUX];
382 IOEventHandler *chr_event[MAX_MUX];
383 void *ext_opaque[MAX_MUX];
384 CharDriverState *drv;
385 int focus;
386 int mux_cnt;
387 int term_got_escape;
388 int max_size;
389 /* Intermediate input buffer allows to catch escape sequences even if the
390 currently active device is not accepting any input - but only until it
391 is full as well. */
392 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
393 int prod[MAX_MUX];
394 int cons[MAX_MUX];
395 int timestamps;
397 /* Protected by the CharDriverState chr_write_lock. */
398 int linestart;
399 int64_t timestamps_start;
400 } MuxDriver;
403 /* Called with chr_write_lock held. */
404 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
406 MuxDriver *d = chr->opaque;
407 int ret;
408 if (!d->timestamps) {
409 ret = qemu_chr_fe_write(d->drv, buf, len);
410 } else {
411 int i;
413 ret = 0;
414 for (i = 0; i < len; i++) {
415 if (d->linestart) {
416 char buf1[64];
417 int64_t ti;
418 int secs;
420 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
421 if (d->timestamps_start == -1)
422 d->timestamps_start = ti;
423 ti -= d->timestamps_start;
424 secs = ti / 1000;
425 snprintf(buf1, sizeof(buf1),
426 "[%02d:%02d:%02d.%03d] ",
427 secs / 3600,
428 (secs / 60) % 60,
429 secs % 60,
430 (int)(ti % 1000));
431 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
432 d->linestart = 0;
434 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
435 if (buf[i] == '\n') {
436 d->linestart = 1;
440 return ret;
443 static const char * const mux_help[] = {
444 "% h print this help\n\r",
445 "% x exit emulator\n\r",
446 "% s save disk data back to file (if -snapshot)\n\r",
447 "% t toggle console timestamps\n\r",
448 "% b send break (magic sysrq)\n\r",
449 "% c switch between console and monitor\n\r",
450 "% % sends %\n\r",
451 NULL
454 int term_escape_char = 0x01; /* ctrl-a is used for escape */
455 static void mux_print_help(CharDriverState *chr)
457 int i, j;
458 char ebuf[15] = "Escape-Char";
459 char cbuf[50] = "\n\r";
461 if (term_escape_char > 0 && term_escape_char < 26) {
462 snprintf(cbuf, sizeof(cbuf), "\n\r");
463 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
464 } else {
465 snprintf(cbuf, sizeof(cbuf),
466 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
467 term_escape_char);
469 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
470 for (i = 0; mux_help[i] != NULL; i++) {
471 for (j=0; mux_help[i][j] != '\0'; j++) {
472 if (mux_help[i][j] == '%')
473 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
474 else
475 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
480 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
482 if (d->chr_event[mux_nr])
483 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
486 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
488 if (d->term_got_escape) {
489 d->term_got_escape = 0;
490 if (ch == term_escape_char)
491 goto send_char;
492 switch(ch) {
493 case '?':
494 case 'h':
495 mux_print_help(chr);
496 break;
497 case 'x':
499 const char *term = "QEMU: Terminated\n\r";
500 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
501 exit(0);
502 break;
504 case 's':
505 bdrv_commit_all();
506 break;
507 case 'b':
508 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
509 break;
510 case 'c':
511 /* Switch to the next registered device */
512 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
513 d->focus++;
514 if (d->focus >= d->mux_cnt)
515 d->focus = 0;
516 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
517 break;
518 case 't':
519 d->timestamps = !d->timestamps;
520 d->timestamps_start = -1;
521 d->linestart = 0;
522 break;
524 } else if (ch == term_escape_char) {
525 d->term_got_escape = 1;
526 } else {
527 send_char:
528 return 1;
530 return 0;
533 static void mux_chr_accept_input(CharDriverState *chr)
535 MuxDriver *d = chr->opaque;
536 int m = d->focus;
538 while (d->prod[m] != d->cons[m] &&
539 d->chr_can_read[m] &&
540 d->chr_can_read[m](d->ext_opaque[m])) {
541 d->chr_read[m](d->ext_opaque[m],
542 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
546 static int mux_chr_can_read(void *opaque)
548 CharDriverState *chr = opaque;
549 MuxDriver *d = chr->opaque;
550 int m = d->focus;
552 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
553 return 1;
554 if (d->chr_can_read[m])
555 return d->chr_can_read[m](d->ext_opaque[m]);
556 return 0;
559 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
561 CharDriverState *chr = opaque;
562 MuxDriver *d = chr->opaque;
563 int m = d->focus;
564 int i;
566 mux_chr_accept_input (opaque);
568 for(i = 0; i < size; i++)
569 if (mux_proc_byte(chr, d, buf[i])) {
570 if (d->prod[m] == d->cons[m] &&
571 d->chr_can_read[m] &&
572 d->chr_can_read[m](d->ext_opaque[m]))
573 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
574 else
575 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
579 static void mux_chr_event(void *opaque, int event)
581 CharDriverState *chr = opaque;
582 MuxDriver *d = chr->opaque;
583 int i;
585 /* Send the event to all registered listeners */
586 for (i = 0; i < d->mux_cnt; i++)
587 mux_chr_send_event(d, i, event);
590 static void mux_chr_update_read_handler(CharDriverState *chr)
592 MuxDriver *d = chr->opaque;
594 if (d->mux_cnt >= MAX_MUX) {
595 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
596 return;
598 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
599 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
600 d->chr_read[d->mux_cnt] = chr->chr_read;
601 d->chr_event[d->mux_cnt] = chr->chr_event;
602 /* Fix up the real driver with mux routines */
603 if (d->mux_cnt == 0) {
604 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
605 mux_chr_event, chr);
607 if (d->focus != -1) {
608 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
610 d->focus = d->mux_cnt;
611 d->mux_cnt++;
612 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
615 static bool muxes_realized;
618 * Called after processing of default and command-line-specified
619 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
620 * to a mux chardev. This is done here to ensure that
621 * output/prompts/banners are only displayed for the FE that has
622 * focus when initial command-line processing/machine init is
623 * completed.
625 * After this point, any new FE attached to any new or existing
626 * mux will receive CHR_EVENT_OPENED notifications for the BE
627 * immediately.
629 static void muxes_realize_done(Notifier *notifier, void *unused)
631 CharDriverState *chr;
633 QTAILQ_FOREACH(chr, &chardevs, next) {
634 if (chr->is_mux) {
635 MuxDriver *d = chr->opaque;
636 int i;
638 /* send OPENED to all already-attached FEs */
639 for (i = 0; i < d->mux_cnt; i++) {
640 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
642 /* mark mux as OPENED so any new FEs will immediately receive
643 * OPENED event
645 qemu_chr_be_generic_open(chr);
648 muxes_realized = true;
651 static Notifier muxes_realize_notify = {
652 .notify = muxes_realize_done,
655 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
657 MuxDriver *d = s->opaque;
658 return d->drv->chr_add_watch(d->drv, cond);
661 static CharDriverState *qemu_chr_open_mux(const char *id,
662 ChardevBackend *backend,
663 ChardevReturn *ret, Error **errp)
665 ChardevMux *mux = backend->u.mux;
666 CharDriverState *chr, *drv;
667 MuxDriver *d;
669 drv = qemu_chr_find(mux->chardev);
670 if (drv == NULL) {
671 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
672 return NULL;
675 chr = qemu_chr_alloc();
676 d = g_new0(MuxDriver, 1);
678 chr->opaque = d;
679 d->drv = drv;
680 d->focus = -1;
681 chr->chr_write = mux_chr_write;
682 chr->chr_update_read_handler = mux_chr_update_read_handler;
683 chr->chr_accept_input = mux_chr_accept_input;
684 /* Frontend guest-open / -close notification is not support with muxes */
685 chr->chr_set_fe_open = NULL;
686 if (drv->chr_add_watch) {
687 chr->chr_add_watch = mux_chr_add_watch;
689 /* only default to opened state if we've realized the initial
690 * set of muxes
692 chr->explicit_be_open = muxes_realized ? 0 : 1;
693 chr->is_mux = 1;
695 return chr;
699 #ifdef _WIN32
700 int send_all(int fd, const void *buf, int len1)
702 int ret, len;
704 len = len1;
705 while (len > 0) {
706 ret = send(fd, buf, len, 0);
707 if (ret < 0) {
708 errno = WSAGetLastError();
709 if (errno != WSAEWOULDBLOCK) {
710 return -1;
712 } else if (ret == 0) {
713 break;
714 } else {
715 buf += ret;
716 len -= ret;
719 return len1 - len;
722 #else
724 int send_all(int fd, const void *_buf, int len1)
726 int ret, len;
727 const uint8_t *buf = _buf;
729 len = len1;
730 while (len > 0) {
731 ret = write(fd, buf, len);
732 if (ret < 0) {
733 if (errno != EINTR && errno != EAGAIN)
734 return -1;
735 } else if (ret == 0) {
736 break;
737 } else {
738 buf += ret;
739 len -= ret;
742 return len1 - len;
745 int recv_all(int fd, void *_buf, int len1, bool single_read)
747 int ret, len;
748 uint8_t *buf = _buf;
750 len = len1;
751 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
752 if (ret < 0) {
753 if (errno != EINTR && errno != EAGAIN) {
754 return -1;
756 continue;
757 } else {
758 if (single_read) {
759 return ret;
761 buf += ret;
762 len -= ret;
765 return len1 - len;
768 #endif /* !_WIN32 */
770 typedef struct IOWatchPoll
772 GSource parent;
774 GIOChannel *channel;
775 GSource *src;
777 IOCanReadHandler *fd_can_read;
778 GSourceFunc fd_read;
779 void *opaque;
780 } IOWatchPoll;
782 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
784 return container_of(source, IOWatchPoll, parent);
787 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
789 IOWatchPoll *iwp = io_watch_poll_from_source(source);
790 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
791 bool was_active = iwp->src != NULL;
792 if (was_active == now_active) {
793 return FALSE;
796 if (now_active) {
797 iwp->src = g_io_create_watch(iwp->channel,
798 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
799 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
800 g_source_attach(iwp->src, NULL);
801 } else {
802 g_source_destroy(iwp->src);
803 g_source_unref(iwp->src);
804 iwp->src = NULL;
806 return FALSE;
809 static gboolean io_watch_poll_check(GSource *source)
811 return FALSE;
814 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
815 gpointer user_data)
817 abort();
820 static void io_watch_poll_finalize(GSource *source)
822 /* Due to a glib bug, removing the last reference to a source
823 * inside a finalize callback causes recursive locking (and a
824 * deadlock). This is not a problem inside other callbacks,
825 * including dispatch callbacks, so we call io_remove_watch_poll
826 * to remove this source. At this point, iwp->src must
827 * be NULL, or we would leak it.
829 * This would be solved much more elegantly by child sources,
830 * but we support older glib versions that do not have them.
832 IOWatchPoll *iwp = io_watch_poll_from_source(source);
833 assert(iwp->src == NULL);
836 static GSourceFuncs io_watch_poll_funcs = {
837 .prepare = io_watch_poll_prepare,
838 .check = io_watch_poll_check,
839 .dispatch = io_watch_poll_dispatch,
840 .finalize = io_watch_poll_finalize,
843 /* Can only be used for read */
844 static guint io_add_watch_poll(GIOChannel *channel,
845 IOCanReadHandler *fd_can_read,
846 GIOFunc fd_read,
847 gpointer user_data)
849 IOWatchPoll *iwp;
850 int tag;
852 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
853 iwp->fd_can_read = fd_can_read;
854 iwp->opaque = user_data;
855 iwp->channel = channel;
856 iwp->fd_read = (GSourceFunc) fd_read;
857 iwp->src = NULL;
859 tag = g_source_attach(&iwp->parent, NULL);
860 g_source_unref(&iwp->parent);
861 return tag;
864 static void io_remove_watch_poll(guint tag)
866 GSource *source;
867 IOWatchPoll *iwp;
869 g_return_if_fail (tag > 0);
871 source = g_main_context_find_source_by_id(NULL, tag);
872 g_return_if_fail (source != NULL);
874 iwp = io_watch_poll_from_source(source);
875 if (iwp->src) {
876 g_source_destroy(iwp->src);
877 g_source_unref(iwp->src);
878 iwp->src = NULL;
880 g_source_destroy(&iwp->parent);
883 static void remove_fd_in_watch(CharDriverState *chr)
885 if (chr->fd_in_tag) {
886 io_remove_watch_poll(chr->fd_in_tag);
887 chr->fd_in_tag = 0;
891 #ifndef _WIN32
892 static GIOChannel *io_channel_from_fd(int fd)
894 GIOChannel *chan;
896 if (fd == -1) {
897 return NULL;
900 chan = g_io_channel_unix_new(fd);
902 g_io_channel_set_encoding(chan, NULL, NULL);
903 g_io_channel_set_buffered(chan, FALSE);
905 return chan;
907 #endif
909 static GIOChannel *io_channel_from_socket(int fd)
911 GIOChannel *chan;
913 if (fd == -1) {
914 return NULL;
917 #ifdef _WIN32
918 chan = g_io_channel_win32_new_socket(fd);
919 #else
920 chan = g_io_channel_unix_new(fd);
921 #endif
923 g_io_channel_set_encoding(chan, NULL, NULL);
924 g_io_channel_set_buffered(chan, FALSE);
926 return chan;
929 static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
931 size_t offset = 0;
932 GIOStatus status = G_IO_STATUS_NORMAL;
934 while (offset < len && status == G_IO_STATUS_NORMAL) {
935 gsize bytes_written = 0;
937 status = g_io_channel_write_chars(fd, buf + offset, len - offset,
938 &bytes_written, NULL);
939 offset += bytes_written;
942 if (offset > 0) {
943 return offset;
945 switch (status) {
946 case G_IO_STATUS_NORMAL:
947 g_assert(len == 0);
948 return 0;
949 case G_IO_STATUS_AGAIN:
950 errno = EAGAIN;
951 return -1;
952 default:
953 break;
955 errno = EINVAL;
956 return -1;
959 #ifndef _WIN32
961 typedef struct FDCharDriver {
962 CharDriverState *chr;
963 GIOChannel *fd_in, *fd_out;
964 int max_size;
965 } FDCharDriver;
967 /* Called with chr_write_lock held. */
968 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
970 FDCharDriver *s = chr->opaque;
972 return io_channel_send(s->fd_out, buf, len);
975 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
977 CharDriverState *chr = opaque;
978 FDCharDriver *s = chr->opaque;
979 int len;
980 uint8_t buf[READ_BUF_LEN];
981 GIOStatus status;
982 gsize bytes_read;
984 len = sizeof(buf);
985 if (len > s->max_size) {
986 len = s->max_size;
988 if (len == 0) {
989 return TRUE;
992 status = g_io_channel_read_chars(chan, (gchar *)buf,
993 len, &bytes_read, NULL);
994 if (status == G_IO_STATUS_EOF) {
995 remove_fd_in_watch(chr);
996 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
997 return FALSE;
999 if (status == G_IO_STATUS_NORMAL) {
1000 qemu_chr_be_write(chr, buf, bytes_read);
1003 return TRUE;
1006 static int fd_chr_read_poll(void *opaque)
1008 CharDriverState *chr = opaque;
1009 FDCharDriver *s = chr->opaque;
1011 s->max_size = qemu_chr_be_can_write(chr);
1012 return s->max_size;
1015 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1017 FDCharDriver *s = chr->opaque;
1018 return g_io_create_watch(s->fd_out, cond);
1021 static void fd_chr_update_read_handler(CharDriverState *chr)
1023 FDCharDriver *s = chr->opaque;
1025 remove_fd_in_watch(chr);
1026 if (s->fd_in) {
1027 chr->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll,
1028 fd_chr_read, chr);
1032 static void fd_chr_close(struct CharDriverState *chr)
1034 FDCharDriver *s = chr->opaque;
1036 remove_fd_in_watch(chr);
1037 if (s->fd_in) {
1038 g_io_channel_unref(s->fd_in);
1040 if (s->fd_out) {
1041 g_io_channel_unref(s->fd_out);
1044 g_free(s);
1045 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1048 /* open a character device to a unix fd */
1049 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1051 CharDriverState *chr;
1052 FDCharDriver *s;
1054 chr = qemu_chr_alloc();
1055 s = g_new0(FDCharDriver, 1);
1056 s->fd_in = io_channel_from_fd(fd_in);
1057 s->fd_out = io_channel_from_fd(fd_out);
1058 qemu_set_nonblock(fd_out);
1059 s->chr = chr;
1060 chr->opaque = s;
1061 chr->chr_add_watch = fd_chr_add_watch;
1062 chr->chr_write = fd_chr_write;
1063 chr->chr_update_read_handler = fd_chr_update_read_handler;
1064 chr->chr_close = fd_chr_close;
1066 return chr;
1069 static CharDriverState *qemu_chr_open_pipe(const char *id,
1070 ChardevBackend *backend,
1071 ChardevReturn *ret,
1072 Error **errp)
1074 ChardevHostdev *opts = backend->u.pipe;
1075 int fd_in, fd_out;
1076 char filename_in[CHR_MAX_FILENAME_SIZE];
1077 char filename_out[CHR_MAX_FILENAME_SIZE];
1078 const char *filename = opts->device;
1080 snprintf(filename_in, CHR_MAX_FILENAME_SIZE, "%s.in", filename);
1081 snprintf(filename_out, CHR_MAX_FILENAME_SIZE, "%s.out", filename);
1082 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1083 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1084 if (fd_in < 0 || fd_out < 0) {
1085 if (fd_in >= 0)
1086 close(fd_in);
1087 if (fd_out >= 0)
1088 close(fd_out);
1089 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1090 if (fd_in < 0) {
1091 error_setg_file_open(errp, errno, filename);
1092 return NULL;
1095 return qemu_chr_open_fd(fd_in, fd_out);
1098 /* init terminal so that we can grab keys */
1099 static struct termios oldtty;
1100 static int old_fd0_flags;
1101 static bool stdio_in_use;
1102 static bool stdio_allow_signal;
1103 static bool stdio_echo_state;
1105 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1107 static void term_exit(void)
1109 tcsetattr (0, TCSANOW, &oldtty);
1110 fcntl(0, F_SETFL, old_fd0_flags);
1113 static void term_stdio_handler(int sig)
1115 /* restore echo after resume from suspend. */
1116 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1119 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1121 struct termios tty;
1123 stdio_echo_state = echo;
1124 tty = oldtty;
1125 if (!echo) {
1126 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1127 |INLCR|IGNCR|ICRNL|IXON);
1128 tty.c_oflag |= OPOST;
1129 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1130 tty.c_cflag &= ~(CSIZE|PARENB);
1131 tty.c_cflag |= CS8;
1132 tty.c_cc[VMIN] = 1;
1133 tty.c_cc[VTIME] = 0;
1135 if (!stdio_allow_signal)
1136 tty.c_lflag &= ~ISIG;
1138 tcsetattr (0, TCSANOW, &tty);
1141 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1143 term_exit();
1144 fd_chr_close(chr);
1147 static CharDriverState *qemu_chr_open_stdio(const char *id,
1148 ChardevBackend *backend,
1149 ChardevReturn *ret,
1150 Error **errp)
1152 ChardevStdio *opts = backend->u.stdio;
1153 CharDriverState *chr;
1154 struct sigaction act;
1156 if (is_daemonized()) {
1157 error_setg(errp, "cannot use stdio with -daemonize");
1158 return NULL;
1161 if (stdio_in_use) {
1162 error_setg(errp, "cannot use stdio by multiple character devices");
1163 return NULL;
1166 stdio_in_use = true;
1167 old_fd0_flags = fcntl(0, F_GETFL);
1168 tcgetattr(0, &oldtty);
1169 qemu_set_nonblock(0);
1170 atexit(term_exit);
1172 memset(&act, 0, sizeof(act));
1173 act.sa_handler = term_stdio_handler;
1174 sigaction(SIGCONT, &act, NULL);
1176 chr = qemu_chr_open_fd(0, 1);
1177 chr->chr_close = qemu_chr_close_stdio;
1178 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1179 if (opts->has_signal) {
1180 stdio_allow_signal = opts->signal;
1182 qemu_chr_fe_set_echo(chr, false);
1184 return chr;
1187 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1188 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1189 || defined(__GLIBC__)
1191 #define HAVE_CHARDEV_SERIAL 1
1192 #define HAVE_CHARDEV_PTY 1
1194 typedef struct {
1195 GIOChannel *fd;
1196 int read_bytes;
1198 /* Protected by the CharDriverState chr_write_lock. */
1199 int connected;
1200 guint timer_tag;
1201 guint open_tag;
1202 } PtyCharDriver;
1204 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1205 static void pty_chr_state(CharDriverState *chr, int connected);
1207 static gboolean pty_chr_timer(gpointer opaque)
1209 struct CharDriverState *chr = opaque;
1210 PtyCharDriver *s = chr->opaque;
1212 qemu_mutex_lock(&chr->chr_write_lock);
1213 s->timer_tag = 0;
1214 s->open_tag = 0;
1215 if (!s->connected) {
1216 /* Next poll ... */
1217 pty_chr_update_read_handler_locked(chr);
1219 qemu_mutex_unlock(&chr->chr_write_lock);
1220 return FALSE;
1223 /* Called with chr_write_lock held. */
1224 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1226 PtyCharDriver *s = chr->opaque;
1228 if (s->timer_tag) {
1229 g_source_remove(s->timer_tag);
1230 s->timer_tag = 0;
1233 if (ms == 1000) {
1234 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1235 } else {
1236 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1240 /* Called with chr_write_lock held. */
1241 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1243 PtyCharDriver *s = chr->opaque;
1244 GPollFD pfd;
1245 int rc;
1247 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1248 pfd.events = G_IO_OUT;
1249 pfd.revents = 0;
1250 do {
1251 rc = g_poll(&pfd, 1, 0);
1252 } while (rc == -1 && errno == EINTR);
1253 assert(rc >= 0);
1255 if (pfd.revents & G_IO_HUP) {
1256 pty_chr_state(chr, 0);
1257 } else {
1258 pty_chr_state(chr, 1);
1262 static void pty_chr_update_read_handler(CharDriverState *chr)
1264 qemu_mutex_lock(&chr->chr_write_lock);
1265 pty_chr_update_read_handler_locked(chr);
1266 qemu_mutex_unlock(&chr->chr_write_lock);
1269 /* Called with chr_write_lock held. */
1270 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1272 PtyCharDriver *s = chr->opaque;
1274 if (!s->connected) {
1275 /* guest sends data, check for (re-)connect */
1276 pty_chr_update_read_handler_locked(chr);
1277 if (!s->connected) {
1278 return 0;
1281 return io_channel_send(s->fd, buf, len);
1284 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1286 PtyCharDriver *s = chr->opaque;
1287 if (!s->connected) {
1288 return NULL;
1290 return g_io_create_watch(s->fd, cond);
1293 static int pty_chr_read_poll(void *opaque)
1295 CharDriverState *chr = opaque;
1296 PtyCharDriver *s = chr->opaque;
1298 s->read_bytes = qemu_chr_be_can_write(chr);
1299 return s->read_bytes;
1302 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1304 CharDriverState *chr = opaque;
1305 PtyCharDriver *s = chr->opaque;
1306 gsize size, len;
1307 uint8_t buf[READ_BUF_LEN];
1308 GIOStatus status;
1310 len = sizeof(buf);
1311 if (len > s->read_bytes)
1312 len = s->read_bytes;
1313 if (len == 0) {
1314 return TRUE;
1316 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1317 if (status != G_IO_STATUS_NORMAL) {
1318 pty_chr_state(chr, 0);
1319 return FALSE;
1320 } else {
1321 pty_chr_state(chr, 1);
1322 qemu_chr_be_write(chr, buf, size);
1324 return TRUE;
1327 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1329 CharDriverState *chr = opaque;
1330 PtyCharDriver *s = chr->opaque;
1332 s->open_tag = 0;
1333 qemu_chr_be_generic_open(chr);
1334 return FALSE;
1337 /* Called with chr_write_lock held. */
1338 static void pty_chr_state(CharDriverState *chr, int connected)
1340 PtyCharDriver *s = chr->opaque;
1342 if (!connected) {
1343 if (s->open_tag) {
1344 g_source_remove(s->open_tag);
1345 s->open_tag = 0;
1347 remove_fd_in_watch(chr);
1348 s->connected = 0;
1349 /* (re-)connect poll interval for idle guests: once per second.
1350 * We check more frequently in case the guests sends data to
1351 * the virtual device linked to our pty. */
1352 pty_chr_rearm_timer(chr, 1000);
1353 } else {
1354 if (s->timer_tag) {
1355 g_source_remove(s->timer_tag);
1356 s->timer_tag = 0;
1358 if (!s->connected) {
1359 g_assert(s->open_tag == 0);
1360 s->connected = 1;
1361 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1363 if (!chr->fd_in_tag) {
1364 chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
1365 pty_chr_read, chr);
1370 static void pty_chr_close(struct CharDriverState *chr)
1372 PtyCharDriver *s = chr->opaque;
1373 int fd;
1375 qemu_mutex_lock(&chr->chr_write_lock);
1376 pty_chr_state(chr, 0);
1377 fd = g_io_channel_unix_get_fd(s->fd);
1378 g_io_channel_unref(s->fd);
1379 close(fd);
1380 if (s->timer_tag) {
1381 g_source_remove(s->timer_tag);
1382 s->timer_tag = 0;
1384 qemu_mutex_unlock(&chr->chr_write_lock);
1385 g_free(s);
1386 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1389 static CharDriverState *qemu_chr_open_pty(const char *id,
1390 ChardevBackend *backend,
1391 ChardevReturn *ret,
1392 Error **errp)
1394 CharDriverState *chr;
1395 PtyCharDriver *s;
1396 int master_fd, slave_fd;
1397 char pty_name[PATH_MAX];
1399 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1400 if (master_fd < 0) {
1401 error_setg_errno(errp, errno, "Failed to create PTY");
1402 return NULL;
1405 close(slave_fd);
1406 qemu_set_nonblock(master_fd);
1408 chr = qemu_chr_alloc();
1410 chr->filename = g_strdup_printf("pty:%s", pty_name);
1411 ret->pty = g_strdup(pty_name);
1412 ret->has_pty = true;
1414 fprintf(stderr, "char device redirected to %s (label %s)\n",
1415 pty_name, id);
1417 s = g_new0(PtyCharDriver, 1);
1418 chr->opaque = s;
1419 chr->chr_write = pty_chr_write;
1420 chr->chr_update_read_handler = pty_chr_update_read_handler;
1421 chr->chr_close = pty_chr_close;
1422 chr->chr_add_watch = pty_chr_add_watch;
1423 chr->explicit_be_open = true;
1425 s->fd = io_channel_from_fd(master_fd);
1426 s->timer_tag = 0;
1428 return chr;
1431 static void tty_serial_init(int fd, int speed,
1432 int parity, int data_bits, int stop_bits)
1434 struct termios tty;
1435 speed_t spd;
1437 #if 0
1438 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1439 speed, parity, data_bits, stop_bits);
1440 #endif
1441 tcgetattr (fd, &tty);
1443 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1444 speed = speed * 10 / 11;
1445 do {
1446 check_speed(50);
1447 check_speed(75);
1448 check_speed(110);
1449 check_speed(134);
1450 check_speed(150);
1451 check_speed(200);
1452 check_speed(300);
1453 check_speed(600);
1454 check_speed(1200);
1455 check_speed(1800);
1456 check_speed(2400);
1457 check_speed(4800);
1458 check_speed(9600);
1459 check_speed(19200);
1460 check_speed(38400);
1461 /* Non-Posix values follow. They may be unsupported on some systems. */
1462 check_speed(57600);
1463 check_speed(115200);
1464 #ifdef B230400
1465 check_speed(230400);
1466 #endif
1467 #ifdef B460800
1468 check_speed(460800);
1469 #endif
1470 #ifdef B500000
1471 check_speed(500000);
1472 #endif
1473 #ifdef B576000
1474 check_speed(576000);
1475 #endif
1476 #ifdef B921600
1477 check_speed(921600);
1478 #endif
1479 #ifdef B1000000
1480 check_speed(1000000);
1481 #endif
1482 #ifdef B1152000
1483 check_speed(1152000);
1484 #endif
1485 #ifdef B1500000
1486 check_speed(1500000);
1487 #endif
1488 #ifdef B2000000
1489 check_speed(2000000);
1490 #endif
1491 #ifdef B2500000
1492 check_speed(2500000);
1493 #endif
1494 #ifdef B3000000
1495 check_speed(3000000);
1496 #endif
1497 #ifdef B3500000
1498 check_speed(3500000);
1499 #endif
1500 #ifdef B4000000
1501 check_speed(4000000);
1502 #endif
1503 spd = B115200;
1504 } while (0);
1506 cfsetispeed(&tty, spd);
1507 cfsetospeed(&tty, spd);
1509 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1510 |INLCR|IGNCR|ICRNL|IXON);
1511 tty.c_oflag |= OPOST;
1512 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1513 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1514 switch(data_bits) {
1515 default:
1516 case 8:
1517 tty.c_cflag |= CS8;
1518 break;
1519 case 7:
1520 tty.c_cflag |= CS7;
1521 break;
1522 case 6:
1523 tty.c_cflag |= CS6;
1524 break;
1525 case 5:
1526 tty.c_cflag |= CS5;
1527 break;
1529 switch(parity) {
1530 default:
1531 case 'N':
1532 break;
1533 case 'E':
1534 tty.c_cflag |= PARENB;
1535 break;
1536 case 'O':
1537 tty.c_cflag |= PARENB | PARODD;
1538 break;
1540 if (stop_bits == 2)
1541 tty.c_cflag |= CSTOPB;
1543 tcsetattr (fd, TCSANOW, &tty);
1546 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1548 FDCharDriver *s = chr->opaque;
1550 switch(cmd) {
1551 case CHR_IOCTL_SERIAL_SET_PARAMS:
1553 QEMUSerialSetParams *ssp = arg;
1554 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1555 ssp->speed, ssp->parity,
1556 ssp->data_bits, ssp->stop_bits);
1558 break;
1559 case CHR_IOCTL_SERIAL_SET_BREAK:
1561 int enable = *(int *)arg;
1562 if (enable) {
1563 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1566 break;
1567 case CHR_IOCTL_SERIAL_GET_TIOCM:
1569 int sarg = 0;
1570 int *targ = (int *)arg;
1571 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1572 *targ = 0;
1573 if (sarg & TIOCM_CTS)
1574 *targ |= CHR_TIOCM_CTS;
1575 if (sarg & TIOCM_CAR)
1576 *targ |= CHR_TIOCM_CAR;
1577 if (sarg & TIOCM_DSR)
1578 *targ |= CHR_TIOCM_DSR;
1579 if (sarg & TIOCM_RI)
1580 *targ |= CHR_TIOCM_RI;
1581 if (sarg & TIOCM_DTR)
1582 *targ |= CHR_TIOCM_DTR;
1583 if (sarg & TIOCM_RTS)
1584 *targ |= CHR_TIOCM_RTS;
1586 break;
1587 case CHR_IOCTL_SERIAL_SET_TIOCM:
1589 int sarg = *(int *)arg;
1590 int targ = 0;
1591 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1592 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1593 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1594 if (sarg & CHR_TIOCM_CTS)
1595 targ |= TIOCM_CTS;
1596 if (sarg & CHR_TIOCM_CAR)
1597 targ |= TIOCM_CAR;
1598 if (sarg & CHR_TIOCM_DSR)
1599 targ |= TIOCM_DSR;
1600 if (sarg & CHR_TIOCM_RI)
1601 targ |= TIOCM_RI;
1602 if (sarg & CHR_TIOCM_DTR)
1603 targ |= TIOCM_DTR;
1604 if (sarg & CHR_TIOCM_RTS)
1605 targ |= TIOCM_RTS;
1606 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1608 break;
1609 default:
1610 return -ENOTSUP;
1612 return 0;
1615 static void qemu_chr_close_tty(CharDriverState *chr)
1617 FDCharDriver *s = chr->opaque;
1618 int fd = -1;
1620 if (s) {
1621 fd = g_io_channel_unix_get_fd(s->fd_in);
1624 fd_chr_close(chr);
1626 if (fd >= 0) {
1627 close(fd);
1631 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1633 CharDriverState *chr;
1635 tty_serial_init(fd, 115200, 'N', 8, 1);
1636 chr = qemu_chr_open_fd(fd, fd);
1637 chr->chr_ioctl = tty_serial_ioctl;
1638 chr->chr_close = qemu_chr_close_tty;
1639 return chr;
1641 #endif /* __linux__ || __sun__ */
1643 #if defined(__linux__)
1645 #define HAVE_CHARDEV_PARPORT 1
1647 typedef struct {
1648 int fd;
1649 int mode;
1650 } ParallelCharDriver;
1652 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1654 if (s->mode != mode) {
1655 int m = mode;
1656 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1657 return 0;
1658 s->mode = mode;
1660 return 1;
1663 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1665 ParallelCharDriver *drv = chr->opaque;
1666 int fd = drv->fd;
1667 uint8_t b;
1669 switch(cmd) {
1670 case CHR_IOCTL_PP_READ_DATA:
1671 if (ioctl(fd, PPRDATA, &b) < 0)
1672 return -ENOTSUP;
1673 *(uint8_t *)arg = b;
1674 break;
1675 case CHR_IOCTL_PP_WRITE_DATA:
1676 b = *(uint8_t *)arg;
1677 if (ioctl(fd, PPWDATA, &b) < 0)
1678 return -ENOTSUP;
1679 break;
1680 case CHR_IOCTL_PP_READ_CONTROL:
1681 if (ioctl(fd, PPRCONTROL, &b) < 0)
1682 return -ENOTSUP;
1683 /* Linux gives only the lowest bits, and no way to know data
1684 direction! For better compatibility set the fixed upper
1685 bits. */
1686 *(uint8_t *)arg = b | 0xc0;
1687 break;
1688 case CHR_IOCTL_PP_WRITE_CONTROL:
1689 b = *(uint8_t *)arg;
1690 if (ioctl(fd, PPWCONTROL, &b) < 0)
1691 return -ENOTSUP;
1692 break;
1693 case CHR_IOCTL_PP_READ_STATUS:
1694 if (ioctl(fd, PPRSTATUS, &b) < 0)
1695 return -ENOTSUP;
1696 *(uint8_t *)arg = b;
1697 break;
1698 case CHR_IOCTL_PP_DATA_DIR:
1699 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1700 return -ENOTSUP;
1701 break;
1702 case CHR_IOCTL_PP_EPP_READ_ADDR:
1703 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1704 struct ParallelIOArg *parg = arg;
1705 int n = read(fd, parg->buffer, parg->count);
1706 if (n != parg->count) {
1707 return -EIO;
1710 break;
1711 case CHR_IOCTL_PP_EPP_READ:
1712 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1713 struct ParallelIOArg *parg = arg;
1714 int n = read(fd, parg->buffer, parg->count);
1715 if (n != parg->count) {
1716 return -EIO;
1719 break;
1720 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1721 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1722 struct ParallelIOArg *parg = arg;
1723 int n = write(fd, parg->buffer, parg->count);
1724 if (n != parg->count) {
1725 return -EIO;
1728 break;
1729 case CHR_IOCTL_PP_EPP_WRITE:
1730 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1731 struct ParallelIOArg *parg = arg;
1732 int n = write(fd, parg->buffer, parg->count);
1733 if (n != parg->count) {
1734 return -EIO;
1737 break;
1738 default:
1739 return -ENOTSUP;
1741 return 0;
1744 static void pp_close(CharDriverState *chr)
1746 ParallelCharDriver *drv = chr->opaque;
1747 int fd = drv->fd;
1749 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1750 ioctl(fd, PPRELEASE);
1751 close(fd);
1752 g_free(drv);
1753 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1756 static CharDriverState *qemu_chr_open_pp_fd(int fd, Error **errp)
1758 CharDriverState *chr;
1759 ParallelCharDriver *drv;
1761 if (ioctl(fd, PPCLAIM) < 0) {
1762 error_setg_errno(errp, errno, "not a parallel port");
1763 close(fd);
1764 return NULL;
1767 drv = g_new0(ParallelCharDriver, 1);
1768 drv->fd = fd;
1769 drv->mode = IEEE1284_MODE_COMPAT;
1771 chr = qemu_chr_alloc();
1772 chr->chr_write = null_chr_write;
1773 chr->chr_ioctl = pp_ioctl;
1774 chr->chr_close = pp_close;
1775 chr->opaque = drv;
1777 return chr;
1779 #endif /* __linux__ */
1781 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1783 #define HAVE_CHARDEV_PARPORT 1
1785 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1787 int fd = (int)(intptr_t)chr->opaque;
1788 uint8_t b;
1790 switch(cmd) {
1791 case CHR_IOCTL_PP_READ_DATA:
1792 if (ioctl(fd, PPIGDATA, &b) < 0)
1793 return -ENOTSUP;
1794 *(uint8_t *)arg = b;
1795 break;
1796 case CHR_IOCTL_PP_WRITE_DATA:
1797 b = *(uint8_t *)arg;
1798 if (ioctl(fd, PPISDATA, &b) < 0)
1799 return -ENOTSUP;
1800 break;
1801 case CHR_IOCTL_PP_READ_CONTROL:
1802 if (ioctl(fd, PPIGCTRL, &b) < 0)
1803 return -ENOTSUP;
1804 *(uint8_t *)arg = b;
1805 break;
1806 case CHR_IOCTL_PP_WRITE_CONTROL:
1807 b = *(uint8_t *)arg;
1808 if (ioctl(fd, PPISCTRL, &b) < 0)
1809 return -ENOTSUP;
1810 break;
1811 case CHR_IOCTL_PP_READ_STATUS:
1812 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1813 return -ENOTSUP;
1814 *(uint8_t *)arg = b;
1815 break;
1816 default:
1817 return -ENOTSUP;
1819 return 0;
1822 static CharDriverState *qemu_chr_open_pp_fd(int fd, Error **errp)
1824 CharDriverState *chr;
1826 chr = qemu_chr_alloc();
1827 chr->opaque = (void *)(intptr_t)fd;
1828 chr->chr_write = null_chr_write;
1829 chr->chr_ioctl = pp_ioctl;
1830 chr->explicit_be_open = true;
1831 return chr;
1833 #endif
1835 #else /* _WIN32 */
1837 #define HAVE_CHARDEV_SERIAL 1
1839 typedef struct {
1840 int max_size;
1841 HANDLE hcom, hrecv, hsend;
1842 OVERLAPPED orecv;
1843 BOOL fpipe;
1844 DWORD len;
1846 /* Protected by the CharDriverState chr_write_lock. */
1847 OVERLAPPED osend;
1848 } WinCharState;
1850 typedef struct {
1851 HANDLE hStdIn;
1852 HANDLE hInputReadyEvent;
1853 HANDLE hInputDoneEvent;
1854 HANDLE hInputThread;
1855 uint8_t win_stdio_buf;
1856 } WinStdioCharState;
1858 #define NSENDBUF 2048
1859 #define NRECVBUF 2048
1860 #define MAXCONNECT 1
1861 #define NTIMEOUT 5000
1863 static int win_chr_poll(void *opaque);
1864 static int win_chr_pipe_poll(void *opaque);
1866 static void win_chr_close(CharDriverState *chr)
1868 WinCharState *s = chr->opaque;
1870 if (s->hsend) {
1871 CloseHandle(s->hsend);
1872 s->hsend = NULL;
1874 if (s->hrecv) {
1875 CloseHandle(s->hrecv);
1876 s->hrecv = NULL;
1878 if (s->hcom) {
1879 CloseHandle(s->hcom);
1880 s->hcom = NULL;
1882 if (s->fpipe)
1883 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1884 else
1885 qemu_del_polling_cb(win_chr_poll, chr);
1887 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1890 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1892 WinCharState *s = chr->opaque;
1893 COMMCONFIG comcfg;
1894 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1895 COMSTAT comstat;
1896 DWORD size;
1897 DWORD err;
1899 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1900 if (!s->hsend) {
1901 error_setg(errp, "Failed CreateEvent");
1902 goto fail;
1904 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1905 if (!s->hrecv) {
1906 error_setg(errp, "Failed CreateEvent");
1907 goto fail;
1910 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1911 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1912 if (s->hcom == INVALID_HANDLE_VALUE) {
1913 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1914 s->hcom = NULL;
1915 goto fail;
1918 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1919 error_setg(errp, "Failed SetupComm");
1920 goto fail;
1923 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1924 size = sizeof(COMMCONFIG);
1925 GetDefaultCommConfig(filename, &comcfg, &size);
1926 comcfg.dcb.DCBlength = sizeof(DCB);
1927 CommConfigDialog(filename, NULL, &comcfg);
1929 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1930 error_setg(errp, "Failed SetCommState");
1931 goto fail;
1934 if (!SetCommMask(s->hcom, EV_ERR)) {
1935 error_setg(errp, "Failed SetCommMask");
1936 goto fail;
1939 cto.ReadIntervalTimeout = MAXDWORD;
1940 if (!SetCommTimeouts(s->hcom, &cto)) {
1941 error_setg(errp, "Failed SetCommTimeouts");
1942 goto fail;
1945 if (!ClearCommError(s->hcom, &err, &comstat)) {
1946 error_setg(errp, "Failed ClearCommError");
1947 goto fail;
1949 qemu_add_polling_cb(win_chr_poll, chr);
1950 return 0;
1952 fail:
1953 win_chr_close(chr);
1954 return -1;
1957 /* Called with chr_write_lock held. */
1958 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1960 WinCharState *s = chr->opaque;
1961 DWORD len, ret, size, err;
1963 len = len1;
1964 ZeroMemory(&s->osend, sizeof(s->osend));
1965 s->osend.hEvent = s->hsend;
1966 while (len > 0) {
1967 if (s->hsend)
1968 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1969 else
1970 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1971 if (!ret) {
1972 err = GetLastError();
1973 if (err == ERROR_IO_PENDING) {
1974 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1975 if (ret) {
1976 buf += size;
1977 len -= size;
1978 } else {
1979 break;
1981 } else {
1982 break;
1984 } else {
1985 buf += size;
1986 len -= size;
1989 return len1 - len;
1992 static int win_chr_read_poll(CharDriverState *chr)
1994 WinCharState *s = chr->opaque;
1996 s->max_size = qemu_chr_be_can_write(chr);
1997 return s->max_size;
2000 static void win_chr_readfile(CharDriverState *chr)
2002 WinCharState *s = chr->opaque;
2003 int ret, err;
2004 uint8_t buf[READ_BUF_LEN];
2005 DWORD size;
2007 ZeroMemory(&s->orecv, sizeof(s->orecv));
2008 s->orecv.hEvent = s->hrecv;
2009 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2010 if (!ret) {
2011 err = GetLastError();
2012 if (err == ERROR_IO_PENDING) {
2013 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2017 if (size > 0) {
2018 qemu_chr_be_write(chr, buf, size);
2022 static void win_chr_read(CharDriverState *chr)
2024 WinCharState *s = chr->opaque;
2026 if (s->len > s->max_size)
2027 s->len = s->max_size;
2028 if (s->len == 0)
2029 return;
2031 win_chr_readfile(chr);
2034 static int win_chr_poll(void *opaque)
2036 CharDriverState *chr = opaque;
2037 WinCharState *s = chr->opaque;
2038 COMSTAT status;
2039 DWORD comerr;
2041 ClearCommError(s->hcom, &comerr, &status);
2042 if (status.cbInQue > 0) {
2043 s->len = status.cbInQue;
2044 win_chr_read_poll(chr);
2045 win_chr_read(chr);
2046 return 1;
2048 return 0;
2051 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2052 Error **errp)
2054 CharDriverState *chr;
2055 WinCharState *s;
2057 chr = qemu_chr_alloc();
2058 s = g_new0(WinCharState, 1);
2059 chr->opaque = s;
2060 chr->chr_write = win_chr_write;
2061 chr->chr_close = win_chr_close;
2063 if (win_chr_init(chr, filename, errp) < 0) {
2064 g_free(s);
2065 g_free(chr);
2066 return NULL;
2068 return chr;
2071 static int win_chr_pipe_poll(void *opaque)
2073 CharDriverState *chr = opaque;
2074 WinCharState *s = chr->opaque;
2075 DWORD size;
2077 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2078 if (size > 0) {
2079 s->len = size;
2080 win_chr_read_poll(chr);
2081 win_chr_read(chr);
2082 return 1;
2084 return 0;
2087 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2088 Error **errp)
2090 WinCharState *s = chr->opaque;
2091 OVERLAPPED ov;
2092 int ret;
2093 DWORD size;
2094 char openname[CHR_MAX_FILENAME_SIZE];
2096 s->fpipe = TRUE;
2098 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2099 if (!s->hsend) {
2100 error_setg(errp, "Failed CreateEvent");
2101 goto fail;
2103 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2104 if (!s->hrecv) {
2105 error_setg(errp, "Failed CreateEvent");
2106 goto fail;
2109 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2110 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2111 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2112 PIPE_WAIT,
2113 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2114 if (s->hcom == INVALID_HANDLE_VALUE) {
2115 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2116 s->hcom = NULL;
2117 goto fail;
2120 ZeroMemory(&ov, sizeof(ov));
2121 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2122 ret = ConnectNamedPipe(s->hcom, &ov);
2123 if (ret) {
2124 error_setg(errp, "Failed ConnectNamedPipe");
2125 goto fail;
2128 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2129 if (!ret) {
2130 error_setg(errp, "Failed GetOverlappedResult");
2131 if (ov.hEvent) {
2132 CloseHandle(ov.hEvent);
2133 ov.hEvent = NULL;
2135 goto fail;
2138 if (ov.hEvent) {
2139 CloseHandle(ov.hEvent);
2140 ov.hEvent = NULL;
2142 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2143 return 0;
2145 fail:
2146 win_chr_close(chr);
2147 return -1;
2151 static CharDriverState *qemu_chr_open_pipe(const char *id,
2152 ChardevBackend *backend,
2153 ChardevReturn *ret,
2154 Error **errp)
2156 ChardevHostdev *opts = backend->u.pipe;
2157 const char *filename = opts->device;
2158 CharDriverState *chr;
2159 WinCharState *s;
2161 chr = qemu_chr_alloc();
2162 s = g_new0(WinCharState, 1);
2163 chr->opaque = s;
2164 chr->chr_write = win_chr_write;
2165 chr->chr_close = win_chr_close;
2167 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2168 g_free(s);
2169 g_free(chr);
2170 return NULL;
2172 return chr;
2175 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2177 CharDriverState *chr;
2178 WinCharState *s;
2180 chr = qemu_chr_alloc();
2181 s = g_new0(WinCharState, 1);
2182 s->hcom = fd_out;
2183 chr->opaque = s;
2184 chr->chr_write = win_chr_write;
2185 return chr;
2188 static CharDriverState *qemu_chr_open_win_con(const char *id,
2189 ChardevBackend *backend,
2190 ChardevReturn *ret,
2191 Error **errp)
2193 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2196 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2198 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2199 DWORD dwSize;
2200 int len1;
2202 len1 = len;
2204 while (len1 > 0) {
2205 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2206 break;
2208 buf += dwSize;
2209 len1 -= dwSize;
2212 return len - len1;
2215 static void win_stdio_wait_func(void *opaque)
2217 CharDriverState *chr = opaque;
2218 WinStdioCharState *stdio = chr->opaque;
2219 INPUT_RECORD buf[4];
2220 int ret;
2221 DWORD dwSize;
2222 int i;
2224 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2226 if (!ret) {
2227 /* Avoid error storm */
2228 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2229 return;
2232 for (i = 0; i < dwSize; i++) {
2233 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2235 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2236 int j;
2237 if (kev->uChar.AsciiChar != 0) {
2238 for (j = 0; j < kev->wRepeatCount; j++) {
2239 if (qemu_chr_be_can_write(chr)) {
2240 uint8_t c = kev->uChar.AsciiChar;
2241 qemu_chr_be_write(chr, &c, 1);
2249 static DWORD WINAPI win_stdio_thread(LPVOID param)
2251 CharDriverState *chr = param;
2252 WinStdioCharState *stdio = chr->opaque;
2253 int ret;
2254 DWORD dwSize;
2256 while (1) {
2258 /* Wait for one byte */
2259 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2261 /* Exit in case of error, continue if nothing read */
2262 if (!ret) {
2263 break;
2265 if (!dwSize) {
2266 continue;
2269 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2270 if (stdio->win_stdio_buf == '\r') {
2271 continue;
2274 /* Signal the main thread and wait until the byte was eaten */
2275 if (!SetEvent(stdio->hInputReadyEvent)) {
2276 break;
2278 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2279 != WAIT_OBJECT_0) {
2280 break;
2284 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2285 return 0;
2288 static void win_stdio_thread_wait_func(void *opaque)
2290 CharDriverState *chr = opaque;
2291 WinStdioCharState *stdio = chr->opaque;
2293 if (qemu_chr_be_can_write(chr)) {
2294 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2297 SetEvent(stdio->hInputDoneEvent);
2300 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2302 WinStdioCharState *stdio = chr->opaque;
2303 DWORD dwMode = 0;
2305 GetConsoleMode(stdio->hStdIn, &dwMode);
2307 if (echo) {
2308 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2309 } else {
2310 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2314 static void win_stdio_close(CharDriverState *chr)
2316 WinStdioCharState *stdio = chr->opaque;
2318 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2319 CloseHandle(stdio->hInputReadyEvent);
2321 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2322 CloseHandle(stdio->hInputDoneEvent);
2324 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2325 TerminateThread(stdio->hInputThread, 0);
2328 g_free(chr->opaque);
2329 g_free(chr);
2332 static CharDriverState *qemu_chr_open_stdio(const char *id,
2333 ChardevBackend *backend,
2334 ChardevReturn *ret,
2335 Error **errp)
2337 CharDriverState *chr;
2338 WinStdioCharState *stdio;
2339 DWORD dwMode;
2340 int is_console = 0;
2342 chr = qemu_chr_alloc();
2343 stdio = g_new0(WinStdioCharState, 1);
2345 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2346 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2347 error_setg(errp, "cannot open stdio: invalid handle");
2348 return NULL;
2351 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2353 chr->opaque = stdio;
2354 chr->chr_write = win_stdio_write;
2355 chr->chr_close = win_stdio_close;
2357 if (is_console) {
2358 if (qemu_add_wait_object(stdio->hStdIn,
2359 win_stdio_wait_func, chr)) {
2360 error_setg(errp, "qemu_add_wait_object: failed");
2361 goto err1;
2363 } else {
2364 DWORD dwId;
2366 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2367 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2368 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2369 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2370 error_setg(errp, "cannot create event");
2371 goto err2;
2373 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2374 win_stdio_thread_wait_func, chr)) {
2375 error_setg(errp, "qemu_add_wait_object: failed");
2376 goto err2;
2378 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2379 chr, 0, &dwId);
2381 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2382 error_setg(errp, "cannot create stdio thread");
2383 goto err3;
2387 dwMode |= ENABLE_LINE_INPUT;
2389 if (is_console) {
2390 /* set the terminal in raw mode */
2391 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2392 dwMode |= ENABLE_PROCESSED_INPUT;
2395 SetConsoleMode(stdio->hStdIn, dwMode);
2397 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2398 qemu_chr_fe_set_echo(chr, false);
2400 return chr;
2402 err3:
2403 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2404 err2:
2405 CloseHandle(stdio->hInputReadyEvent);
2406 CloseHandle(stdio->hInputDoneEvent);
2407 err1:
2408 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2409 return NULL;
2411 #endif /* !_WIN32 */
2414 /***********************************************************/
2415 /* UDP Net console */
2417 typedef struct {
2418 int fd;
2419 GIOChannel *chan;
2420 uint8_t buf[READ_BUF_LEN];
2421 int bufcnt;
2422 int bufptr;
2423 int max_size;
2424 } NetCharDriver;
2426 /* Called with chr_write_lock held. */
2427 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2429 NetCharDriver *s = chr->opaque;
2430 gsize bytes_written;
2431 GIOStatus status;
2433 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2434 if (status == G_IO_STATUS_EOF) {
2435 return 0;
2436 } else if (status != G_IO_STATUS_NORMAL) {
2437 return -1;
2440 return bytes_written;
2443 static int udp_chr_read_poll(void *opaque)
2445 CharDriverState *chr = opaque;
2446 NetCharDriver *s = chr->opaque;
2448 s->max_size = qemu_chr_be_can_write(chr);
2450 /* If there were any stray characters in the queue process them
2451 * first
2453 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2454 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2455 s->bufptr++;
2456 s->max_size = qemu_chr_be_can_write(chr);
2458 return s->max_size;
2461 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2463 CharDriverState *chr = opaque;
2464 NetCharDriver *s = chr->opaque;
2465 gsize bytes_read = 0;
2466 GIOStatus status;
2468 if (s->max_size == 0) {
2469 return TRUE;
2471 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2472 &bytes_read, NULL);
2473 s->bufcnt = bytes_read;
2474 s->bufptr = s->bufcnt;
2475 if (status != G_IO_STATUS_NORMAL) {
2476 remove_fd_in_watch(chr);
2477 return FALSE;
2480 s->bufptr = 0;
2481 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2482 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2483 s->bufptr++;
2484 s->max_size = qemu_chr_be_can_write(chr);
2487 return TRUE;
2490 static void udp_chr_update_read_handler(CharDriverState *chr)
2492 NetCharDriver *s = chr->opaque;
2494 remove_fd_in_watch(chr);
2495 if (s->chan) {
2496 chr->fd_in_tag = io_add_watch_poll(s->chan, udp_chr_read_poll,
2497 udp_chr_read, chr);
2501 static void udp_chr_close(CharDriverState *chr)
2503 NetCharDriver *s = chr->opaque;
2505 remove_fd_in_watch(chr);
2506 if (s->chan) {
2507 g_io_channel_unref(s->chan);
2508 closesocket(s->fd);
2510 g_free(s);
2511 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2514 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2516 CharDriverState *chr = NULL;
2517 NetCharDriver *s = NULL;
2519 chr = qemu_chr_alloc();
2520 s = g_new0(NetCharDriver, 1);
2522 s->fd = fd;
2523 s->chan = io_channel_from_socket(s->fd);
2524 s->bufcnt = 0;
2525 s->bufptr = 0;
2526 chr->opaque = s;
2527 chr->chr_write = udp_chr_write;
2528 chr->chr_update_read_handler = udp_chr_update_read_handler;
2529 chr->chr_close = udp_chr_close;
2530 /* be isn't opened until we get a connection */
2531 chr->explicit_be_open = true;
2532 return chr;
2535 /***********************************************************/
2536 /* TCP Net console */
2538 typedef struct {
2540 GIOChannel *chan, *listen_chan;
2541 guint listen_tag;
2542 int fd, listen_fd;
2543 int connected;
2544 int max_size;
2545 int do_telnetopt;
2546 int do_nodelay;
2547 int is_unix;
2548 int *read_msgfds;
2549 int read_msgfds_num;
2550 int *write_msgfds;
2551 int write_msgfds_num;
2553 SocketAddress *addr;
2554 bool is_listen;
2555 bool is_telnet;
2557 guint reconnect_timer;
2558 int64_t reconnect_time;
2559 bool connect_err_reported;
2560 } TCPCharDriver;
2562 static gboolean socket_reconnect_timeout(gpointer opaque);
2564 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2566 TCPCharDriver *s = chr->opaque;
2567 assert(s->connected == 0);
2568 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2569 socket_reconnect_timeout, chr);
2572 static void check_report_connect_error(CharDriverState *chr,
2573 Error *err)
2575 TCPCharDriver *s = chr->opaque;
2577 if (!s->connect_err_reported) {
2578 error_report("Unable to connect character device %s: %s",
2579 chr->label, error_get_pretty(err));
2580 s->connect_err_reported = true;
2582 qemu_chr_socket_restart_timer(chr);
2585 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2587 #ifndef _WIN32
2588 static int unix_send_msgfds(CharDriverState *chr, const uint8_t *buf, int len)
2590 TCPCharDriver *s = chr->opaque;
2591 struct msghdr msgh;
2592 struct iovec iov;
2593 int r;
2595 size_t fd_size = s->write_msgfds_num * sizeof(int);
2596 char control[CMSG_SPACE(fd_size)];
2597 struct cmsghdr *cmsg;
2599 memset(&msgh, 0, sizeof(msgh));
2600 memset(control, 0, sizeof(control));
2602 /* set the payload */
2603 iov.iov_base = (uint8_t *) buf;
2604 iov.iov_len = len;
2606 msgh.msg_iov = &iov;
2607 msgh.msg_iovlen = 1;
2609 msgh.msg_control = control;
2610 msgh.msg_controllen = sizeof(control);
2612 cmsg = CMSG_FIRSTHDR(&msgh);
2614 cmsg->cmsg_len = CMSG_LEN(fd_size);
2615 cmsg->cmsg_level = SOL_SOCKET;
2616 cmsg->cmsg_type = SCM_RIGHTS;
2617 memcpy(CMSG_DATA(cmsg), s->write_msgfds, fd_size);
2619 do {
2620 r = sendmsg(s->fd, &msgh, 0);
2621 } while (r < 0 && errno == EINTR);
2623 /* free the written msgfds, no matter what */
2624 if (s->write_msgfds_num) {
2625 g_free(s->write_msgfds);
2626 s->write_msgfds = 0;
2627 s->write_msgfds_num = 0;
2630 return r;
2632 #endif
2634 /* Called with chr_write_lock held. */
2635 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2637 TCPCharDriver *s = chr->opaque;
2638 if (s->connected) {
2639 #ifndef _WIN32
2640 if (s->is_unix && s->write_msgfds_num) {
2641 return unix_send_msgfds(chr, buf, len);
2642 } else
2643 #endif
2645 return io_channel_send(s->chan, buf, len);
2647 } else {
2648 /* XXX: indicate an error ? */
2649 return len;
2653 static int tcp_chr_read_poll(void *opaque)
2655 CharDriverState *chr = opaque;
2656 TCPCharDriver *s = chr->opaque;
2657 if (!s->connected)
2658 return 0;
2659 s->max_size = qemu_chr_be_can_write(chr);
2660 return s->max_size;
2663 #define IAC 255
2664 #define IAC_BREAK 243
2665 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2666 TCPCharDriver *s,
2667 uint8_t *buf, int *size)
2669 /* Handle any telnet client's basic IAC options to satisfy char by
2670 * char mode with no echo. All IAC options will be removed from
2671 * the buf and the do_telnetopt variable will be used to track the
2672 * state of the width of the IAC information.
2674 * IAC commands come in sets of 3 bytes with the exception of the
2675 * "IAC BREAK" command and the double IAC.
2678 int i;
2679 int j = 0;
2681 for (i = 0; i < *size; i++) {
2682 if (s->do_telnetopt > 1) {
2683 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2684 /* Double IAC means send an IAC */
2685 if (j != i)
2686 buf[j] = buf[i];
2687 j++;
2688 s->do_telnetopt = 1;
2689 } else {
2690 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2691 /* Handle IAC break commands by sending a serial break */
2692 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2693 s->do_telnetopt++;
2695 s->do_telnetopt++;
2697 if (s->do_telnetopt >= 4) {
2698 s->do_telnetopt = 1;
2700 } else {
2701 if ((unsigned char)buf[i] == IAC) {
2702 s->do_telnetopt = 2;
2703 } else {
2704 if (j != i)
2705 buf[j] = buf[i];
2706 j++;
2710 *size = j;
2713 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2715 TCPCharDriver *s = chr->opaque;
2716 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2718 assert(num <= TCP_MAX_FDS);
2720 if (to_copy) {
2721 int i;
2723 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2725 /* Close unused fds */
2726 for (i = to_copy; i < s->read_msgfds_num; i++) {
2727 close(s->read_msgfds[i]);
2730 g_free(s->read_msgfds);
2731 s->read_msgfds = 0;
2732 s->read_msgfds_num = 0;
2735 return to_copy;
2738 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2740 TCPCharDriver *s = chr->opaque;
2742 /* clear old pending fd array */
2743 g_free(s->write_msgfds);
2745 if (num) {
2746 s->write_msgfds = g_new(int, num);
2747 memcpy(s->write_msgfds, fds, num * sizeof(int));
2750 s->write_msgfds_num = num;
2752 return 0;
2755 #ifndef _WIN32
2756 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2758 TCPCharDriver *s = chr->opaque;
2759 struct cmsghdr *cmsg;
2761 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2762 int fd_size, i;
2764 if (cmsg->cmsg_len < CMSG_LEN(sizeof(int)) ||
2765 cmsg->cmsg_level != SOL_SOCKET ||
2766 cmsg->cmsg_type != SCM_RIGHTS) {
2767 continue;
2770 fd_size = cmsg->cmsg_len - CMSG_LEN(0);
2772 if (!fd_size) {
2773 continue;
2776 /* close and clean read_msgfds */
2777 for (i = 0; i < s->read_msgfds_num; i++) {
2778 close(s->read_msgfds[i]);
2781 if (s->read_msgfds_num) {
2782 g_free(s->read_msgfds);
2785 s->read_msgfds_num = fd_size / sizeof(int);
2786 s->read_msgfds = g_malloc(fd_size);
2787 memcpy(s->read_msgfds, CMSG_DATA(cmsg), fd_size);
2789 for (i = 0; i < s->read_msgfds_num; i++) {
2790 int fd = s->read_msgfds[i];
2791 if (fd < 0) {
2792 continue;
2795 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2796 qemu_set_block(fd);
2798 #ifndef MSG_CMSG_CLOEXEC
2799 qemu_set_cloexec(fd);
2800 #endif
2805 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2807 TCPCharDriver *s = chr->opaque;
2808 struct msghdr msg = { NULL, };
2809 struct iovec iov[1];
2810 union {
2811 struct cmsghdr cmsg;
2812 char control[CMSG_SPACE(sizeof(int) * TCP_MAX_FDS)];
2813 } msg_control;
2814 int flags = 0;
2815 ssize_t ret;
2817 iov[0].iov_base = buf;
2818 iov[0].iov_len = len;
2820 msg.msg_iov = iov;
2821 msg.msg_iovlen = 1;
2822 msg.msg_control = &msg_control;
2823 msg.msg_controllen = sizeof(msg_control);
2825 #ifdef MSG_CMSG_CLOEXEC
2826 flags |= MSG_CMSG_CLOEXEC;
2827 #endif
2828 do {
2829 ret = recvmsg(s->fd, &msg, flags);
2830 } while (ret == -1 && errno == EINTR);
2832 if (ret > 0 && s->is_unix) {
2833 unix_process_msgfd(chr, &msg);
2836 return ret;
2838 #else
2839 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2841 TCPCharDriver *s = chr->opaque;
2842 ssize_t ret;
2844 do {
2845 ret = qemu_recv(s->fd, buf, len, 0);
2846 } while (ret == -1 && socket_error() == EINTR);
2848 return ret;
2850 #endif
2852 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2854 TCPCharDriver *s = chr->opaque;
2855 return g_io_create_watch(s->chan, cond);
2858 static void tcp_chr_disconnect(CharDriverState *chr)
2860 TCPCharDriver *s = chr->opaque;
2862 s->connected = 0;
2863 if (s->listen_chan) {
2864 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
2865 tcp_chr_accept, chr);
2867 remove_fd_in_watch(chr);
2868 g_io_channel_unref(s->chan);
2869 s->chan = NULL;
2870 closesocket(s->fd);
2871 s->fd = -1;
2872 SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
2873 "disconnected:", s->addr, s->is_listen, s->is_telnet);
2874 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2875 if (s->reconnect_time) {
2876 qemu_chr_socket_restart_timer(chr);
2880 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2882 CharDriverState *chr = opaque;
2883 TCPCharDriver *s = chr->opaque;
2884 uint8_t buf[READ_BUF_LEN];
2885 int len, size;
2887 if (!s->connected || s->max_size <= 0) {
2888 return TRUE;
2890 len = sizeof(buf);
2891 if (len > s->max_size)
2892 len = s->max_size;
2893 size = tcp_chr_recv(chr, (void *)buf, len);
2894 if (size == 0 ||
2895 (size < 0 &&
2896 socket_error() != EAGAIN && socket_error() != EWOULDBLOCK)) {
2897 /* connection closed */
2898 tcp_chr_disconnect(chr);
2899 } else if (size > 0) {
2900 if (s->do_telnetopt)
2901 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2902 if (size > 0)
2903 qemu_chr_be_write(chr, buf, size);
2906 return TRUE;
2909 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2911 TCPCharDriver *s = chr->opaque;
2912 int size;
2914 if (!s->connected) {
2915 return 0;
2918 size = tcp_chr_recv(chr, (void *) buf, len);
2919 if (size == 0) {
2920 /* connection closed */
2921 tcp_chr_disconnect(chr);
2924 return size;
2927 #ifndef _WIN32
2928 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2930 CharDriverState *chr = qemu_chr_open_fd(eventfd, eventfd);
2932 if (chr) {
2933 chr->avail_connections = 1;
2936 return chr;
2938 #endif
2940 static void tcp_chr_connect(void *opaque)
2942 CharDriverState *chr = opaque;
2943 TCPCharDriver *s = chr->opaque;
2944 struct sockaddr_storage ss, ps;
2945 socklen_t ss_len = sizeof(ss), ps_len = sizeof(ps);
2947 memset(&ss, 0, ss_len);
2948 if (getsockname(s->fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2949 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
2950 "Error in getsockname: %s\n", strerror(errno));
2951 } else if (getpeername(s->fd, (struct sockaddr *) &ps, &ps_len) != 0) {
2952 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
2953 "Error in getpeername: %s\n", strerror(errno));
2954 } else {
2955 sockaddr_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
2956 &ss, ss_len, &ps, ps_len,
2957 s->is_listen, s->is_telnet);
2960 s->connected = 1;
2961 if (s->chan) {
2962 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2963 tcp_chr_read, chr);
2965 qemu_chr_be_generic_open(chr);
2968 static void tcp_chr_update_read_handler(CharDriverState *chr)
2970 TCPCharDriver *s = chr->opaque;
2972 remove_fd_in_watch(chr);
2973 if (s->chan) {
2974 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2975 tcp_chr_read, chr);
2979 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2980 static void tcp_chr_telnet_init(int fd)
2982 char buf[3];
2983 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2984 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2985 send(fd, (char *)buf, 3, 0);
2986 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2987 send(fd, (char *)buf, 3, 0);
2988 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2989 send(fd, (char *)buf, 3, 0);
2990 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2991 send(fd, (char *)buf, 3, 0);
2994 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2996 TCPCharDriver *s = chr->opaque;
2997 if (s->fd != -1)
2998 return -1;
3000 qemu_set_nonblock(fd);
3001 if (s->do_nodelay)
3002 socket_set_nodelay(fd);
3003 s->fd = fd;
3004 s->chan = io_channel_from_socket(fd);
3005 if (s->listen_tag) {
3006 g_source_remove(s->listen_tag);
3007 s->listen_tag = 0;
3009 tcp_chr_connect(chr);
3011 return 0;
3014 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
3016 CharDriverState *chr = opaque;
3017 TCPCharDriver *s = chr->opaque;
3018 struct sockaddr_in saddr;
3019 #ifndef _WIN32
3020 struct sockaddr_un uaddr;
3021 #endif
3022 struct sockaddr *addr;
3023 socklen_t len;
3024 int fd;
3026 for(;;) {
3027 #ifndef _WIN32
3028 if (s->is_unix) {
3029 len = sizeof(uaddr);
3030 addr = (struct sockaddr *)&uaddr;
3031 } else
3032 #endif
3034 len = sizeof(saddr);
3035 addr = (struct sockaddr *)&saddr;
3037 fd = qemu_accept(s->listen_fd, addr, &len);
3038 if (fd < 0 && errno != EINTR) {
3039 s->listen_tag = 0;
3040 return FALSE;
3041 } else if (fd >= 0) {
3042 if (s->do_telnetopt)
3043 tcp_chr_telnet_init(fd);
3044 break;
3047 if (tcp_chr_add_client(chr, fd) < 0)
3048 close(fd);
3050 return TRUE;
3053 static void tcp_chr_close(CharDriverState *chr)
3055 TCPCharDriver *s = chr->opaque;
3056 int i;
3058 if (s->reconnect_timer) {
3059 g_source_remove(s->reconnect_timer);
3060 s->reconnect_timer = 0;
3062 qapi_free_SocketAddress(s->addr);
3063 if (s->fd >= 0) {
3064 remove_fd_in_watch(chr);
3065 if (s->chan) {
3066 g_io_channel_unref(s->chan);
3068 closesocket(s->fd);
3070 if (s->listen_fd >= 0) {
3071 if (s->listen_tag) {
3072 g_source_remove(s->listen_tag);
3073 s->listen_tag = 0;
3075 if (s->listen_chan) {
3076 g_io_channel_unref(s->listen_chan);
3078 closesocket(s->listen_fd);
3080 if (s->read_msgfds_num) {
3081 for (i = 0; i < s->read_msgfds_num; i++) {
3082 close(s->read_msgfds[i]);
3084 g_free(s->read_msgfds);
3086 if (s->write_msgfds_num) {
3087 g_free(s->write_msgfds);
3089 g_free(s);
3090 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3093 static void qemu_chr_finish_socket_connection(CharDriverState *chr, int fd)
3095 TCPCharDriver *s = chr->opaque;
3097 if (s->is_listen) {
3098 s->listen_fd = fd;
3099 s->listen_chan = io_channel_from_socket(s->listen_fd);
3100 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
3101 tcp_chr_accept, chr);
3102 } else {
3103 s->connected = 1;
3104 s->fd = fd;
3105 socket_set_nodelay(fd);
3106 s->chan = io_channel_from_socket(s->fd);
3107 tcp_chr_connect(chr);
3111 static void qemu_chr_socket_connected(int fd, Error *err, void *opaque)
3113 CharDriverState *chr = opaque;
3114 TCPCharDriver *s = chr->opaque;
3116 if (fd < 0) {
3117 check_report_connect_error(chr, err);
3118 return;
3121 s->connect_err_reported = false;
3122 qemu_chr_finish_socket_connection(chr, fd);
3125 static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp)
3127 TCPCharDriver *s = chr->opaque;
3128 int fd;
3130 if (s->is_listen) {
3131 fd = socket_listen(s->addr, errp);
3132 } else if (s->reconnect_time) {
3133 fd = socket_connect(s->addr, errp, qemu_chr_socket_connected, chr);
3134 return fd >= 0;
3135 } else {
3136 fd = socket_connect(s->addr, errp, NULL, NULL);
3138 if (fd < 0) {
3139 return false;
3142 qemu_chr_finish_socket_connection(chr, fd);
3143 return true;
3146 /*********************************************************/
3147 /* Ring buffer chardev */
3149 typedef struct {
3150 size_t size;
3151 size_t prod;
3152 size_t cons;
3153 uint8_t *cbuf;
3154 } RingBufCharDriver;
3156 static size_t ringbuf_count(const CharDriverState *chr)
3158 const RingBufCharDriver *d = chr->opaque;
3160 return d->prod - d->cons;
3163 /* Called with chr_write_lock held. */
3164 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3166 RingBufCharDriver *d = chr->opaque;
3167 int i;
3169 if (!buf || (len < 0)) {
3170 return -1;
3173 for (i = 0; i < len; i++ ) {
3174 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3175 if (d->prod - d->cons > d->size) {
3176 d->cons = d->prod - d->size;
3180 return 0;
3183 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3185 RingBufCharDriver *d = chr->opaque;
3186 int i;
3188 qemu_mutex_lock(&chr->chr_write_lock);
3189 for (i = 0; i < len && d->cons != d->prod; i++) {
3190 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3192 qemu_mutex_unlock(&chr->chr_write_lock);
3194 return i;
3197 static void ringbuf_chr_close(struct CharDriverState *chr)
3199 RingBufCharDriver *d = chr->opaque;
3201 g_free(d->cbuf);
3202 g_free(d);
3203 chr->opaque = NULL;
3206 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3207 ChardevBackend *backend,
3208 ChardevReturn *ret,
3209 Error **errp)
3211 ChardevRingbuf *opts = backend->u.ringbuf;
3212 CharDriverState *chr;
3213 RingBufCharDriver *d;
3215 chr = qemu_chr_alloc();
3216 d = g_malloc(sizeof(*d));
3218 d->size = opts->has_size ? opts->size : 65536;
3220 /* The size must be power of 2 */
3221 if (d->size & (d->size - 1)) {
3222 error_setg(errp, "size of ringbuf chardev must be power of two");
3223 goto fail;
3226 d->prod = 0;
3227 d->cons = 0;
3228 d->cbuf = g_malloc0(d->size);
3230 chr->opaque = d;
3231 chr->chr_write = ringbuf_chr_write;
3232 chr->chr_close = ringbuf_chr_close;
3234 return chr;
3236 fail:
3237 g_free(d);
3238 g_free(chr);
3239 return NULL;
3242 bool chr_is_ringbuf(const CharDriverState *chr)
3244 return chr->chr_write == ringbuf_chr_write;
3247 void qmp_ringbuf_write(const char *device, const char *data,
3248 bool has_format, enum DataFormat format,
3249 Error **errp)
3251 CharDriverState *chr;
3252 const uint8_t *write_data;
3253 int ret;
3254 gsize write_count;
3256 chr = qemu_chr_find(device);
3257 if (!chr) {
3258 error_setg(errp, "Device '%s' not found", device);
3259 return;
3262 if (!chr_is_ringbuf(chr)) {
3263 error_setg(errp,"%s is not a ringbuf device", device);
3264 return;
3267 if (has_format && (format == DATA_FORMAT_BASE64)) {
3268 write_data = qbase64_decode(data, -1,
3269 &write_count,
3270 errp);
3271 if (!write_data) {
3272 return;
3274 } else {
3275 write_data = (uint8_t *)data;
3276 write_count = strlen(data);
3279 ret = ringbuf_chr_write(chr, write_data, write_count);
3281 if (write_data != (uint8_t *)data) {
3282 g_free((void *)write_data);
3285 if (ret < 0) {
3286 error_setg(errp, "Failed to write to device %s", device);
3287 return;
3291 char *qmp_ringbuf_read(const char *device, int64_t size,
3292 bool has_format, enum DataFormat format,
3293 Error **errp)
3295 CharDriverState *chr;
3296 uint8_t *read_data;
3297 size_t count;
3298 char *data;
3300 chr = qemu_chr_find(device);
3301 if (!chr) {
3302 error_setg(errp, "Device '%s' not found", device);
3303 return NULL;
3306 if (!chr_is_ringbuf(chr)) {
3307 error_setg(errp,"%s is not a ringbuf device", device);
3308 return NULL;
3311 if (size <= 0) {
3312 error_setg(errp, "size must be greater than zero");
3313 return NULL;
3316 count = ringbuf_count(chr);
3317 size = size > count ? count : size;
3318 read_data = g_malloc(size + 1);
3320 ringbuf_chr_read(chr, read_data, size);
3322 if (has_format && (format == DATA_FORMAT_BASE64)) {
3323 data = g_base64_encode(read_data, size);
3324 g_free(read_data);
3325 } else {
3327 * FIXME should read only complete, valid UTF-8 characters up
3328 * to @size bytes. Invalid sequences should be replaced by a
3329 * suitable replacement character. Except when (and only
3330 * when) ring buffer lost characters since last read, initial
3331 * continuation characters should be dropped.
3333 read_data[size] = 0;
3334 data = (char *)read_data;
3337 return data;
3340 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3342 char host[65], port[33], width[8], height[8];
3343 int pos;
3344 const char *p;
3345 QemuOpts *opts;
3346 Error *local_err = NULL;
3348 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3349 if (local_err) {
3350 error_report_err(local_err);
3351 return NULL;
3354 if (strstart(filename, "mon:", &p)) {
3355 filename = p;
3356 qemu_opt_set(opts, "mux", "on", &error_abort);
3357 if (strcmp(filename, "stdio") == 0) {
3358 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3359 * but pass it to the guest. Handle this only for compat syntax,
3360 * for -chardev syntax we have special option for this.
3361 * This is what -nographic did, redirecting+muxing serial+monitor
3362 * to stdio causing Ctrl+C to be passed to guest. */
3363 qemu_opt_set(opts, "signal", "off", &error_abort);
3367 if (strcmp(filename, "null") == 0 ||
3368 strcmp(filename, "pty") == 0 ||
3369 strcmp(filename, "msmouse") == 0 ||
3370 strcmp(filename, "braille") == 0 ||
3371 strcmp(filename, "testdev") == 0 ||
3372 strcmp(filename, "stdio") == 0) {
3373 qemu_opt_set(opts, "backend", filename, &error_abort);
3374 return opts;
3376 if (strstart(filename, "vc", &p)) {
3377 qemu_opt_set(opts, "backend", "vc", &error_abort);
3378 if (*p == ':') {
3379 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3380 /* pixels */
3381 qemu_opt_set(opts, "width", width, &error_abort);
3382 qemu_opt_set(opts, "height", height, &error_abort);
3383 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3384 /* chars */
3385 qemu_opt_set(opts, "cols", width, &error_abort);
3386 qemu_opt_set(opts, "rows", height, &error_abort);
3387 } else {
3388 goto fail;
3391 return opts;
3393 if (strcmp(filename, "con:") == 0) {
3394 qemu_opt_set(opts, "backend", "console", &error_abort);
3395 return opts;
3397 if (strstart(filename, "COM", NULL)) {
3398 qemu_opt_set(opts, "backend", "serial", &error_abort);
3399 qemu_opt_set(opts, "path", filename, &error_abort);
3400 return opts;
3402 if (strstart(filename, "file:", &p)) {
3403 qemu_opt_set(opts, "backend", "file", &error_abort);
3404 qemu_opt_set(opts, "path", p, &error_abort);
3405 return opts;
3407 if (strstart(filename, "pipe:", &p)) {
3408 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3409 qemu_opt_set(opts, "path", p, &error_abort);
3410 return opts;
3412 if (strstart(filename, "tcp:", &p) ||
3413 strstart(filename, "telnet:", &p)) {
3414 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3415 host[0] = 0;
3416 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3417 goto fail;
3419 qemu_opt_set(opts, "backend", "socket", &error_abort);
3420 qemu_opt_set(opts, "host", host, &error_abort);
3421 qemu_opt_set(opts, "port", port, &error_abort);
3422 if (p[pos] == ',') {
3423 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3424 if (local_err) {
3425 error_report_err(local_err);
3426 goto fail;
3429 if (strstart(filename, "telnet:", &p))
3430 qemu_opt_set(opts, "telnet", "on", &error_abort);
3431 return opts;
3433 if (strstart(filename, "udp:", &p)) {
3434 qemu_opt_set(opts, "backend", "udp", &error_abort);
3435 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3436 host[0] = 0;
3437 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3438 goto fail;
3441 qemu_opt_set(opts, "host", host, &error_abort);
3442 qemu_opt_set(opts, "port", port, &error_abort);
3443 if (p[pos] == '@') {
3444 p += pos + 1;
3445 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3446 host[0] = 0;
3447 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3448 goto fail;
3451 qemu_opt_set(opts, "localaddr", host, &error_abort);
3452 qemu_opt_set(opts, "localport", port, &error_abort);
3454 return opts;
3456 if (strstart(filename, "unix:", &p)) {
3457 qemu_opt_set(opts, "backend", "socket", &error_abort);
3458 qemu_opts_do_parse(opts, p, "path", &local_err);
3459 if (local_err) {
3460 error_report_err(local_err);
3461 goto fail;
3463 return opts;
3465 if (strstart(filename, "/dev/parport", NULL) ||
3466 strstart(filename, "/dev/ppi", NULL)) {
3467 qemu_opt_set(opts, "backend", "parport", &error_abort);
3468 qemu_opt_set(opts, "path", filename, &error_abort);
3469 return opts;
3471 if (strstart(filename, "/dev/", NULL)) {
3472 qemu_opt_set(opts, "backend", "tty", &error_abort);
3473 qemu_opt_set(opts, "path", filename, &error_abort);
3474 return opts;
3477 fail:
3478 qemu_opts_del(opts);
3479 return NULL;
3482 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3483 Error **errp)
3485 const char *path = qemu_opt_get(opts, "path");
3487 if (path == NULL) {
3488 error_setg(errp, "chardev: file: no filename given");
3489 return;
3491 backend->u.file = g_new0(ChardevFile, 1);
3492 backend->u.file->out = g_strdup(path);
3494 backend->u.file->has_append = true;
3495 backend->u.file->append = qemu_opt_get_bool(opts, "append", false);
3498 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3499 Error **errp)
3501 backend->u.stdio = g_new0(ChardevStdio, 1);
3502 backend->u.stdio->has_signal = true;
3503 backend->u.stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3506 #ifdef HAVE_CHARDEV_SERIAL
3507 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3508 Error **errp)
3510 const char *device = qemu_opt_get(opts, "path");
3512 if (device == NULL) {
3513 error_setg(errp, "chardev: serial/tty: no device path given");
3514 return;
3516 backend->u.serial = g_new0(ChardevHostdev, 1);
3517 backend->u.serial->device = g_strdup(device);
3519 #endif
3521 #ifdef HAVE_CHARDEV_PARPORT
3522 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3523 Error **errp)
3525 const char *device = qemu_opt_get(opts, "path");
3527 if (device == NULL) {
3528 error_setg(errp, "chardev: parallel: no device path given");
3529 return;
3531 backend->u.parallel = g_new0(ChardevHostdev, 1);
3532 backend->u.parallel->device = g_strdup(device);
3534 #endif
3536 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3537 Error **errp)
3539 const char *device = qemu_opt_get(opts, "path");
3541 if (device == NULL) {
3542 error_setg(errp, "chardev: pipe: no device path given");
3543 return;
3545 backend->u.pipe = g_new0(ChardevHostdev, 1);
3546 backend->u.pipe->device = g_strdup(device);
3549 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3550 Error **errp)
3552 int val;
3554 backend->u.ringbuf = g_new0(ChardevRingbuf, 1);
3556 val = qemu_opt_get_size(opts, "size", 0);
3557 if (val != 0) {
3558 backend->u.ringbuf->has_size = true;
3559 backend->u.ringbuf->size = val;
3563 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3564 Error **errp)
3566 const char *chardev = qemu_opt_get(opts, "chardev");
3568 if (chardev == NULL) {
3569 error_setg(errp, "chardev: mux: no chardev given");
3570 return;
3572 backend->u.mux = g_new0(ChardevMux, 1);
3573 backend->u.mux->chardev = g_strdup(chardev);
3576 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3577 Error **errp)
3579 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3580 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3581 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3582 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3583 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3584 const char *path = qemu_opt_get(opts, "path");
3585 const char *host = qemu_opt_get(opts, "host");
3586 const char *port = qemu_opt_get(opts, "port");
3587 SocketAddress *addr;
3589 if (!path) {
3590 if (!host) {
3591 error_setg(errp, "chardev: socket: no host given");
3592 return;
3594 if (!port) {
3595 error_setg(errp, "chardev: socket: no port given");
3596 return;
3600 backend->u.socket = g_new0(ChardevSocket, 1);
3602 backend->u.socket->has_nodelay = true;
3603 backend->u.socket->nodelay = do_nodelay;
3604 backend->u.socket->has_server = true;
3605 backend->u.socket->server = is_listen;
3606 backend->u.socket->has_telnet = true;
3607 backend->u.socket->telnet = is_telnet;
3608 backend->u.socket->has_wait = true;
3609 backend->u.socket->wait = is_waitconnect;
3610 backend->u.socket->has_reconnect = true;
3611 backend->u.socket->reconnect = reconnect;
3613 addr = g_new0(SocketAddress, 1);
3614 if (path) {
3615 addr->type = SOCKET_ADDRESS_KIND_UNIX;
3616 addr->u.q_unix = g_new0(UnixSocketAddress, 1);
3617 addr->u.q_unix->path = g_strdup(path);
3618 } else {
3619 addr->type = SOCKET_ADDRESS_KIND_INET;
3620 addr->u.inet = g_new0(InetSocketAddress, 1);
3621 addr->u.inet->host = g_strdup(host);
3622 addr->u.inet->port = g_strdup(port);
3623 addr->u.inet->has_to = qemu_opt_get(opts, "to");
3624 addr->u.inet->to = qemu_opt_get_number(opts, "to", 0);
3625 addr->u.inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3626 addr->u.inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3627 addr->u.inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3628 addr->u.inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3630 backend->u.socket->addr = addr;
3633 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3634 Error **errp)
3636 const char *host = qemu_opt_get(opts, "host");
3637 const char *port = qemu_opt_get(opts, "port");
3638 const char *localaddr = qemu_opt_get(opts, "localaddr");
3639 const char *localport = qemu_opt_get(opts, "localport");
3640 bool has_local = false;
3641 SocketAddress *addr;
3643 if (host == NULL || strlen(host) == 0) {
3644 host = "localhost";
3646 if (port == NULL || strlen(port) == 0) {
3647 error_setg(errp, "chardev: udp: remote port not specified");
3648 return;
3650 if (localport == NULL || strlen(localport) == 0) {
3651 localport = "0";
3652 } else {
3653 has_local = true;
3655 if (localaddr == NULL || strlen(localaddr) == 0) {
3656 localaddr = "";
3657 } else {
3658 has_local = true;
3661 backend->u.udp = g_new0(ChardevUdp, 1);
3663 addr = g_new0(SocketAddress, 1);
3664 addr->type = SOCKET_ADDRESS_KIND_INET;
3665 addr->u.inet = g_new0(InetSocketAddress, 1);
3666 addr->u.inet->host = g_strdup(host);
3667 addr->u.inet->port = g_strdup(port);
3668 addr->u.inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3669 addr->u.inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3670 addr->u.inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3671 addr->u.inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3672 backend->u.udp->remote = addr;
3674 if (has_local) {
3675 backend->u.udp->has_local = true;
3676 addr = g_new0(SocketAddress, 1);
3677 addr->type = SOCKET_ADDRESS_KIND_INET;
3678 addr->u.inet = g_new0(InetSocketAddress, 1);
3679 addr->u.inet->host = g_strdup(localaddr);
3680 addr->u.inet->port = g_strdup(localport);
3681 backend->u.udp->local = addr;
3685 typedef struct CharDriver {
3686 const char *name;
3687 ChardevBackendKind kind;
3688 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3689 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3690 ChardevReturn *ret, Error **errp);
3691 } CharDriver;
3693 static GSList *backends;
3695 void register_char_driver(const char *name, ChardevBackendKind kind,
3696 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3697 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3698 ChardevReturn *ret, Error **errp))
3700 CharDriver *s;
3702 s = g_malloc0(sizeof(*s));
3703 s->name = g_strdup(name);
3704 s->kind = kind;
3705 s->parse = parse;
3706 s->create = create;
3708 backends = g_slist_append(backends, s);
3711 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3712 void (*init)(struct CharDriverState *s),
3713 Error **errp)
3715 Error *local_err = NULL;
3716 CharDriver *cd;
3717 CharDriverState *chr;
3718 GSList *i;
3719 ChardevReturn *ret = NULL;
3720 ChardevBackend *backend;
3721 const char *id = qemu_opts_id(opts);
3722 char *bid = NULL;
3724 if (id == NULL) {
3725 error_setg(errp, "chardev: no id specified");
3726 goto err;
3729 if (qemu_opt_get(opts, "backend") == NULL) {
3730 error_setg(errp, "chardev: \"%s\" missing backend",
3731 qemu_opts_id(opts));
3732 goto err;
3734 for (i = backends; i; i = i->next) {
3735 cd = i->data;
3737 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3738 break;
3741 if (i == NULL) {
3742 error_setg(errp, "chardev: backend \"%s\" not found",
3743 qemu_opt_get(opts, "backend"));
3744 goto err;
3747 backend = g_new0(ChardevBackend, 1);
3749 if (qemu_opt_get_bool(opts, "mux", 0)) {
3750 bid = g_strdup_printf("%s-base", id);
3753 chr = NULL;
3754 backend->type = cd->kind;
3755 if (cd->parse) {
3756 cd->parse(opts, backend, &local_err);
3757 if (local_err) {
3758 error_propagate(errp, local_err);
3759 goto qapi_out;
3762 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3763 if (!ret) {
3764 goto qapi_out;
3767 if (bid) {
3768 qapi_free_ChardevBackend(backend);
3769 qapi_free_ChardevReturn(ret);
3770 backend = g_new0(ChardevBackend, 1);
3771 backend->u.mux = g_new0(ChardevMux, 1);
3772 backend->type = CHARDEV_BACKEND_KIND_MUX;
3773 backend->u.mux->chardev = g_strdup(bid);
3774 ret = qmp_chardev_add(id, backend, errp);
3775 if (!ret) {
3776 chr = qemu_chr_find(bid);
3777 qemu_chr_delete(chr);
3778 chr = NULL;
3779 goto qapi_out;
3783 chr = qemu_chr_find(id);
3784 chr->opts = opts;
3786 qapi_out:
3787 qapi_free_ChardevBackend(backend);
3788 qapi_free_ChardevReturn(ret);
3789 g_free(bid);
3790 return chr;
3792 err:
3793 qemu_opts_del(opts);
3794 return NULL;
3797 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3799 const char *p;
3800 CharDriverState *chr;
3801 QemuOpts *opts;
3802 Error *err = NULL;
3804 if (strstart(filename, "chardev:", &p)) {
3805 return qemu_chr_find(p);
3808 opts = qemu_chr_parse_compat(label, filename);
3809 if (!opts)
3810 return NULL;
3812 chr = qemu_chr_new_from_opts(opts, init, &err);
3813 if (err) {
3814 error_report_err(err);
3816 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3817 qemu_chr_fe_claim_no_fail(chr);
3818 monitor_init(chr, MONITOR_USE_READLINE);
3820 return chr;
3823 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3825 if (chr->chr_set_echo) {
3826 chr->chr_set_echo(chr, echo);
3830 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3832 if (chr->fe_open == fe_open) {
3833 return;
3835 chr->fe_open = fe_open;
3836 if (chr->chr_set_fe_open) {
3837 chr->chr_set_fe_open(chr, fe_open);
3841 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3843 if (chr->chr_fe_event) {
3844 chr->chr_fe_event(chr, event);
3848 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3849 GIOFunc func, void *user_data)
3851 GSource *src;
3852 guint tag;
3854 if (s->chr_add_watch == NULL) {
3855 return -ENOSYS;
3858 src = s->chr_add_watch(s, cond);
3859 if (!src) {
3860 return -EINVAL;
3863 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3864 tag = g_source_attach(src, NULL);
3865 g_source_unref(src);
3867 return tag;
3870 int qemu_chr_fe_claim(CharDriverState *s)
3872 if (s->avail_connections < 1) {
3873 return -1;
3875 s->avail_connections--;
3876 return 0;
3879 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3881 if (qemu_chr_fe_claim(s) != 0) {
3882 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3883 __func__, s->label);
3884 exit(1);
3888 void qemu_chr_fe_release(CharDriverState *s)
3890 s->avail_connections++;
3893 void qemu_chr_free(CharDriverState *chr)
3895 if (chr->chr_close) {
3896 chr->chr_close(chr);
3898 g_free(chr->filename);
3899 g_free(chr->label);
3900 qemu_opts_del(chr->opts);
3901 g_free(chr);
3904 void qemu_chr_delete(CharDriverState *chr)
3906 QTAILQ_REMOVE(&chardevs, chr, next);
3907 qemu_chr_free(chr);
3910 ChardevInfoList *qmp_query_chardev(Error **errp)
3912 ChardevInfoList *chr_list = NULL;
3913 CharDriverState *chr;
3915 QTAILQ_FOREACH(chr, &chardevs, next) {
3916 ChardevInfoList *info = g_malloc0(sizeof(*info));
3917 info->value = g_malloc0(sizeof(*info->value));
3918 info->value->label = g_strdup(chr->label);
3919 info->value->filename = g_strdup(chr->filename);
3920 info->value->frontend_open = chr->fe_open;
3922 info->next = chr_list;
3923 chr_list = info;
3926 return chr_list;
3929 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
3931 ChardevBackendInfoList *backend_list = NULL;
3932 CharDriver *c = NULL;
3933 GSList *i = NULL;
3935 for (i = backends; i; i = i->next) {
3936 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
3937 c = i->data;
3938 info->value = g_malloc0(sizeof(*info->value));
3939 info->value->name = g_strdup(c->name);
3941 info->next = backend_list;
3942 backend_list = info;
3945 return backend_list;
3948 CharDriverState *qemu_chr_find(const char *name)
3950 CharDriverState *chr;
3952 QTAILQ_FOREACH(chr, &chardevs, next) {
3953 if (strcmp(chr->label, name) != 0)
3954 continue;
3955 return chr;
3957 return NULL;
3960 /* Get a character (serial) device interface. */
3961 CharDriverState *qemu_char_get_next_serial(void)
3963 static int next_serial;
3964 CharDriverState *chr;
3966 /* FIXME: This function needs to go away: use chardev properties! */
3968 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3969 chr = serial_hds[next_serial++];
3970 qemu_chr_fe_claim_no_fail(chr);
3971 return chr;
3973 return NULL;
3976 QemuOptsList qemu_chardev_opts = {
3977 .name = "chardev",
3978 .implied_opt_name = "backend",
3979 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3980 .desc = {
3982 .name = "backend",
3983 .type = QEMU_OPT_STRING,
3985 .name = "path",
3986 .type = QEMU_OPT_STRING,
3988 .name = "host",
3989 .type = QEMU_OPT_STRING,
3991 .name = "port",
3992 .type = QEMU_OPT_STRING,
3994 .name = "localaddr",
3995 .type = QEMU_OPT_STRING,
3997 .name = "localport",
3998 .type = QEMU_OPT_STRING,
4000 .name = "to",
4001 .type = QEMU_OPT_NUMBER,
4003 .name = "ipv4",
4004 .type = QEMU_OPT_BOOL,
4006 .name = "ipv6",
4007 .type = QEMU_OPT_BOOL,
4009 .name = "wait",
4010 .type = QEMU_OPT_BOOL,
4012 .name = "server",
4013 .type = QEMU_OPT_BOOL,
4015 .name = "delay",
4016 .type = QEMU_OPT_BOOL,
4018 .name = "reconnect",
4019 .type = QEMU_OPT_NUMBER,
4021 .name = "telnet",
4022 .type = QEMU_OPT_BOOL,
4024 .name = "width",
4025 .type = QEMU_OPT_NUMBER,
4027 .name = "height",
4028 .type = QEMU_OPT_NUMBER,
4030 .name = "cols",
4031 .type = QEMU_OPT_NUMBER,
4033 .name = "rows",
4034 .type = QEMU_OPT_NUMBER,
4036 .name = "mux",
4037 .type = QEMU_OPT_BOOL,
4039 .name = "signal",
4040 .type = QEMU_OPT_BOOL,
4042 .name = "name",
4043 .type = QEMU_OPT_STRING,
4045 .name = "debug",
4046 .type = QEMU_OPT_NUMBER,
4048 .name = "size",
4049 .type = QEMU_OPT_SIZE,
4051 .name = "chardev",
4052 .type = QEMU_OPT_STRING,
4054 .name = "append",
4055 .type = QEMU_OPT_BOOL,
4057 { /* end of list */ }
4061 #ifdef _WIN32
4063 static CharDriverState *qmp_chardev_open_file(const char *id,
4064 ChardevBackend *backend,
4065 ChardevReturn *ret,
4066 Error **errp)
4068 ChardevFile *file = backend->u.file;
4069 HANDLE out;
4071 if (file->has_in) {
4072 error_setg(errp, "input file not supported");
4073 return NULL;
4076 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
4077 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
4078 if (out == INVALID_HANDLE_VALUE) {
4079 error_setg(errp, "open %s failed", file->out);
4080 return NULL;
4082 return qemu_chr_open_win_file(out);
4085 static CharDriverState *qmp_chardev_open_serial(const char *id,
4086 ChardevBackend *backend,
4087 ChardevReturn *ret,
4088 Error **errp)
4090 ChardevHostdev *serial = backend->u.serial;
4091 return qemu_chr_open_win_path(serial->device, errp);
4094 #else /* WIN32 */
4096 static int qmp_chardev_open_file_source(char *src, int flags,
4097 Error **errp)
4099 int fd = -1;
4101 TFR(fd = qemu_open(src, flags, 0666));
4102 if (fd == -1) {
4103 error_setg_file_open(errp, errno, src);
4105 return fd;
4108 static CharDriverState *qmp_chardev_open_file(const char *id,
4109 ChardevBackend *backend,
4110 ChardevReturn *ret,
4111 Error **errp)
4113 ChardevFile *file = backend->u.file;
4114 int flags, in = -1, out;
4116 flags = O_WRONLY | O_CREAT | O_BINARY;
4117 if (file->has_append && file->append) {
4118 flags |= O_APPEND;
4119 } else {
4120 flags |= O_TRUNC;
4123 out = qmp_chardev_open_file_source(file->out, flags, errp);
4124 if (out < 0) {
4125 return NULL;
4128 if (file->has_in) {
4129 flags = O_RDONLY;
4130 in = qmp_chardev_open_file_source(file->in, flags, errp);
4131 if (in < 0) {
4132 qemu_close(out);
4133 return NULL;
4137 return qemu_chr_open_fd(in, out);
4140 #ifdef HAVE_CHARDEV_SERIAL
4141 static CharDriverState *qmp_chardev_open_serial(const char *id,
4142 ChardevBackend *backend,
4143 ChardevReturn *ret,
4144 Error **errp)
4146 ChardevHostdev *serial = backend->u.serial;
4147 int fd;
4149 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4150 if (fd < 0) {
4151 return NULL;
4153 qemu_set_nonblock(fd);
4154 return qemu_chr_open_tty_fd(fd);
4156 #endif
4158 #ifdef HAVE_CHARDEV_PARPORT
4159 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4160 ChardevBackend *backend,
4161 ChardevReturn *ret,
4162 Error **errp)
4164 ChardevHostdev *parallel = backend->u.parallel;
4165 int fd;
4167 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4168 if (fd < 0) {
4169 return NULL;
4171 return qemu_chr_open_pp_fd(fd, errp);
4173 #endif
4175 #endif /* WIN32 */
4177 static void socket_try_connect(CharDriverState *chr)
4179 Error *err = NULL;
4181 if (!qemu_chr_open_socket_fd(chr, &err)) {
4182 check_report_connect_error(chr, err);
4186 static gboolean socket_reconnect_timeout(gpointer opaque)
4188 CharDriverState *chr = opaque;
4189 TCPCharDriver *s = chr->opaque;
4191 s->reconnect_timer = 0;
4193 if (chr->be_open) {
4194 return false;
4197 socket_try_connect(chr);
4199 return false;
4202 static CharDriverState *qmp_chardev_open_socket(const char *id,
4203 ChardevBackend *backend,
4204 ChardevReturn *ret,
4205 Error **errp)
4207 CharDriverState *chr;
4208 TCPCharDriver *s;
4209 ChardevSocket *sock = backend->u.socket;
4210 SocketAddress *addr = sock->addr;
4211 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4212 bool is_listen = sock->has_server ? sock->server : true;
4213 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4214 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4215 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4217 chr = qemu_chr_alloc();
4218 s = g_new0(TCPCharDriver, 1);
4220 s->fd = -1;
4221 s->listen_fd = -1;
4222 s->is_unix = addr->type == SOCKET_ADDRESS_KIND_UNIX;
4223 s->is_listen = is_listen;
4224 s->is_telnet = is_telnet;
4225 s->do_nodelay = do_nodelay;
4226 qapi_copy_SocketAddress(&s->addr, sock->addr);
4228 chr->opaque = s;
4229 chr->chr_write = tcp_chr_write;
4230 chr->chr_sync_read = tcp_chr_sync_read;
4231 chr->chr_close = tcp_chr_close;
4232 chr->get_msgfds = tcp_get_msgfds;
4233 chr->set_msgfds = tcp_set_msgfds;
4234 chr->chr_add_client = tcp_chr_add_client;
4235 chr->chr_add_watch = tcp_chr_add_watch;
4236 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4237 /* be isn't opened until we get a connection */
4238 chr->explicit_be_open = true;
4240 chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
4241 SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, "disconnected:",
4242 addr, is_listen, is_telnet);
4244 if (is_listen) {
4245 if (is_telnet) {
4246 s->do_telnetopt = 1;
4248 } else if (reconnect > 0) {
4249 s->reconnect_time = reconnect;
4252 if (s->reconnect_time) {
4253 socket_try_connect(chr);
4254 } else if (!qemu_chr_open_socket_fd(chr, errp)) {
4255 g_free(s);
4256 g_free(chr->filename);
4257 g_free(chr);
4258 return NULL;
4261 if (is_listen && is_waitconnect) {
4262 fprintf(stderr, "QEMU waiting for connection on: %s\n",
4263 chr->filename);
4264 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
4265 qemu_set_nonblock(s->listen_fd);
4268 return chr;
4271 static CharDriverState *qmp_chardev_open_udp(const char *id,
4272 ChardevBackend *backend,
4273 ChardevReturn *ret,
4274 Error **errp)
4276 ChardevUdp *udp = backend->u.udp;
4277 int fd;
4279 fd = socket_dgram(udp->remote, udp->local, errp);
4280 if (fd < 0) {
4281 return NULL;
4283 return qemu_chr_open_udp_fd(fd);
4286 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4287 Error **errp)
4289 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4290 CharDriverState *chr = NULL;
4291 Error *local_err = NULL;
4292 GSList *i;
4293 CharDriver *cd;
4295 chr = qemu_chr_find(id);
4296 if (chr) {
4297 error_setg(errp, "Chardev '%s' already exists", id);
4298 g_free(ret);
4299 return NULL;
4302 for (i = backends; i; i = i->next) {
4303 cd = i->data;
4305 if (cd->kind == backend->type) {
4306 chr = cd->create(id, backend, ret, &local_err);
4307 if (local_err) {
4308 error_propagate(errp, local_err);
4309 goto out_error;
4311 break;
4315 if (chr == NULL) {
4316 assert(!i);
4317 error_setg(errp, "chardev backend not available");
4318 goto out_error;
4321 chr->label = g_strdup(id);
4322 chr->avail_connections =
4323 (backend->type == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4324 if (!chr->filename) {
4325 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->type]);
4327 if (!chr->explicit_be_open) {
4328 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4330 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4331 return ret;
4333 out_error:
4334 g_free(ret);
4335 return NULL;
4338 void qmp_chardev_remove(const char *id, Error **errp)
4340 CharDriverState *chr;
4342 chr = qemu_chr_find(id);
4343 if (chr == NULL) {
4344 error_setg(errp, "Chardev '%s' not found", id);
4345 return;
4347 if (chr->chr_can_read || chr->chr_read ||
4348 chr->chr_event || chr->handler_opaque) {
4349 error_setg(errp, "Chardev '%s' is busy", id);
4350 return;
4352 qemu_chr_delete(chr);
4355 static void register_types(void)
4357 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4358 qemu_chr_open_null);
4359 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4360 qemu_chr_parse_socket, qmp_chardev_open_socket);
4361 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4362 qmp_chardev_open_udp);
4363 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4364 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4365 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4366 qemu_chr_parse_file_out, qmp_chardev_open_file);
4367 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4368 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4369 #if defined HAVE_CHARDEV_SERIAL
4370 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4371 qemu_chr_parse_serial, qmp_chardev_open_serial);
4372 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4373 qemu_chr_parse_serial, qmp_chardev_open_serial);
4374 #endif
4375 #ifdef HAVE_CHARDEV_PARPORT
4376 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4377 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4378 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4379 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4380 #endif
4381 #ifdef HAVE_CHARDEV_PTY
4382 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4383 qemu_chr_open_pty);
4384 #endif
4385 #ifdef _WIN32
4386 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4387 qemu_chr_open_win_con);
4388 #endif
4389 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4390 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4391 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4392 qemu_chr_open_mux);
4393 /* Bug-compatibility: */
4394 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4395 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4396 /* this must be done after machine init, since we register FEs with muxes
4397 * as part of realize functions like serial_isa_realizefn when -nographic
4398 * is specified
4400 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4403 type_init(register_types);