s390x/virtio-ccw: fix 2.4 virtio compat
[qemu/ar7.git] / qemu-char.c
blob13371c49313733ddbf5537113ab3d581307114db
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"
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <time.h>
39 #include <errno.h>
40 #include <sys/time.h>
41 #include <zlib.h>
43 #ifndef _WIN32
44 #include <sys/times.h>
45 #include <sys/wait.h>
46 #include <termios.h>
47 #include <sys/mman.h>
48 #include <sys/ioctl.h>
49 #include <sys/resource.h>
50 #include <sys/socket.h>
51 #include <netinet/in.h>
52 #include <net/if.h>
53 #include <arpa/inet.h>
54 #include <netdb.h>
55 #include <sys/select.h>
56 #ifdef CONFIG_BSD
57 #include <sys/stat.h>
58 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
59 #include <dev/ppbus/ppi.h>
60 #include <dev/ppbus/ppbconf.h>
61 #elif defined(__DragonFly__)
62 #include <dev/misc/ppi/ppi.h>
63 #include <bus/ppbus/ppbconf.h>
64 #endif
65 #else
66 #ifdef __linux__
67 #include <linux/ppdev.h>
68 #include <linux/parport.h>
69 #endif
70 #ifdef __sun__
71 #include <sys/stat.h>
72 #include <sys/ethernet.h>
73 #include <sys/sockio.h>
74 #include <netinet/arp.h>
75 #include <netinet/in.h>
76 #include <netinet/in_systm.h>
77 #include <netinet/ip.h>
78 #include <netinet/ip_icmp.h> // must come after ip.h
79 #include <netinet/udp.h>
80 #include <netinet/tcp.h>
81 #endif
82 #endif
83 #endif
85 #include "qemu/sockets.h"
86 #include "ui/qemu-spice.h"
88 #define READ_BUF_LEN 4096
89 #define READ_RETRIES 10
90 #define CHR_MAX_FILENAME_SIZE 256
91 #define TCP_MAX_FDS 16
93 /***********************************************************/
94 /* Socket address helpers */
95 static void qapi_copy_SocketAddress(SocketAddress **p_dest,
96 SocketAddress *src)
98 QmpOutputVisitor *qov;
99 QmpInputVisitor *qiv;
100 Visitor *ov, *iv;
101 QObject *obj;
103 *p_dest = NULL;
105 qov = qmp_output_visitor_new();
106 ov = qmp_output_get_visitor(qov);
107 visit_type_SocketAddress(ov, &src, NULL, &error_abort);
108 obj = qmp_output_get_qobject(qov);
109 qmp_output_visitor_cleanup(qov);
110 if (!obj) {
111 return;
114 qiv = qmp_input_visitor_new(obj);
115 iv = qmp_input_get_visitor(qiv);
116 visit_type_SocketAddress(iv, p_dest, NULL, &error_abort);
117 qmp_input_visitor_cleanup(qiv);
118 qobject_decref(obj);
121 static int SocketAddress_to_str(char *dest, int max_len,
122 const char *prefix, SocketAddress *addr,
123 bool is_listen, bool is_telnet)
125 switch (addr->kind) {
126 case SOCKET_ADDRESS_KIND_INET:
127 return snprintf(dest, max_len, "%s%s:%s:%s%s", prefix,
128 is_telnet ? "telnet" : "tcp", addr->inet->host,
129 addr->inet->port, is_listen ? ",server" : "");
130 break;
131 case SOCKET_ADDRESS_KIND_UNIX:
132 return snprintf(dest, max_len, "%sunix:%s%s", prefix,
133 addr->q_unix->path, is_listen ? ",server" : "");
134 break;
135 case SOCKET_ADDRESS_KIND_FD:
136 return snprintf(dest, max_len, "%sfd:%s%s", prefix, addr->fd->str,
137 is_listen ? ",server" : "");
138 break;
139 default:
140 abort();
144 static int sockaddr_to_str(char *dest, int max_len,
145 struct sockaddr_storage *ss, socklen_t ss_len,
146 struct sockaddr_storage *ps, socklen_t ps_len,
147 bool is_listen, bool is_telnet)
149 char shost[NI_MAXHOST], sserv[NI_MAXSERV];
150 char phost[NI_MAXHOST], pserv[NI_MAXSERV];
151 const char *left = "", *right = "";
153 switch (ss->ss_family) {
154 #ifndef _WIN32
155 case AF_UNIX:
156 return snprintf(dest, max_len, "unix:%s%s",
157 ((struct sockaddr_un *)(ss))->sun_path,
158 is_listen ? ",server" : "");
159 #endif
160 case AF_INET6:
161 left = "[";
162 right = "]";
163 /* fall through */
164 case AF_INET:
165 getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
166 sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
167 getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
168 pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
169 return snprintf(dest, max_len, "%s:%s%s%s:%s%s <-> %s%s%s:%s",
170 is_telnet ? "telnet" : "tcp",
171 left, shost, right, sserv,
172 is_listen ? ",server" : "",
173 left, phost, right, pserv);
175 default:
176 return snprintf(dest, max_len, "unknown");
180 /***********************************************************/
181 /* character device */
183 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
184 QTAILQ_HEAD_INITIALIZER(chardevs);
186 CharDriverState *qemu_chr_alloc(void)
188 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
189 qemu_mutex_init(&chr->chr_write_lock);
190 return chr;
193 void qemu_chr_be_event(CharDriverState *s, int event)
195 /* Keep track if the char device is open */
196 switch (event) {
197 case CHR_EVENT_OPENED:
198 s->be_open = 1;
199 break;
200 case CHR_EVENT_CLOSED:
201 s->be_open = 0;
202 break;
205 if (!s->chr_event)
206 return;
207 s->chr_event(s->handler_opaque, event);
210 void qemu_chr_be_generic_open(CharDriverState *s)
212 qemu_chr_be_event(s, CHR_EVENT_OPENED);
215 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
217 int ret;
219 qemu_mutex_lock(&s->chr_write_lock);
220 ret = s->chr_write(s, buf, len);
221 qemu_mutex_unlock(&s->chr_write_lock);
222 return ret;
225 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
227 int offset = 0;
228 int res = 0;
230 qemu_mutex_lock(&s->chr_write_lock);
231 while (offset < len) {
232 do {
233 res = s->chr_write(s, buf + offset, len - offset);
234 if (res == -1 && errno == EAGAIN) {
235 g_usleep(100);
237 } while (res == -1 && errno == EAGAIN);
239 if (res <= 0) {
240 break;
243 offset += res;
245 qemu_mutex_unlock(&s->chr_write_lock);
247 if (res < 0) {
248 return res;
250 return offset;
253 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
255 int offset = 0, counter = 10;
256 int res;
258 if (!s->chr_sync_read) {
259 return 0;
262 while (offset < len) {
263 do {
264 res = s->chr_sync_read(s, buf + offset, len - offset);
265 if (res == -1 && errno == EAGAIN) {
266 g_usleep(100);
268 } while (res == -1 && errno == EAGAIN);
270 if (res == 0) {
271 break;
274 if (res < 0) {
275 return res;
278 offset += res;
280 if (!counter--) {
281 break;
285 return offset;
288 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
290 if (!s->chr_ioctl)
291 return -ENOTSUP;
292 return s->chr_ioctl(s, cmd, arg);
295 int qemu_chr_be_can_write(CharDriverState *s)
297 if (!s->chr_can_read)
298 return 0;
299 return s->chr_can_read(s->handler_opaque);
302 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
304 if (s->chr_read) {
305 s->chr_read(s->handler_opaque, buf, len);
309 int qemu_chr_fe_get_msgfd(CharDriverState *s)
311 int fd;
312 return (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
315 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
317 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
320 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
322 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
325 int qemu_chr_add_client(CharDriverState *s, int fd)
327 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
330 void qemu_chr_accept_input(CharDriverState *s)
332 if (s->chr_accept_input)
333 s->chr_accept_input(s);
334 qemu_notify_event();
337 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
339 char buf[READ_BUF_LEN];
340 va_list ap;
341 va_start(ap, fmt);
342 vsnprintf(buf, sizeof(buf), fmt, ap);
343 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
344 va_end(ap);
347 static void remove_fd_in_watch(CharDriverState *chr);
349 void qemu_chr_add_handlers(CharDriverState *s,
350 IOCanReadHandler *fd_can_read,
351 IOReadHandler *fd_read,
352 IOEventHandler *fd_event,
353 void *opaque)
355 int fe_open;
357 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
358 fe_open = 0;
359 remove_fd_in_watch(s);
360 } else {
361 fe_open = 1;
363 s->chr_can_read = fd_can_read;
364 s->chr_read = fd_read;
365 s->chr_event = fd_event;
366 s->handler_opaque = opaque;
367 if (fe_open && s->chr_update_read_handler)
368 s->chr_update_read_handler(s);
370 if (!s->explicit_fe_open) {
371 qemu_chr_fe_set_open(s, fe_open);
374 /* We're connecting to an already opened device, so let's make sure we
375 also get the open event */
376 if (fe_open && s->be_open) {
377 qemu_chr_be_generic_open(s);
381 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
383 return len;
386 static CharDriverState *qemu_chr_open_null(const char *id,
387 ChardevBackend *backend,
388 ChardevReturn *ret,
389 Error **errp)
391 CharDriverState *chr;
393 chr = qemu_chr_alloc();
394 chr->chr_write = null_chr_write;
395 chr->explicit_be_open = true;
396 return chr;
399 /* MUX driver for serial I/O splitting */
400 #define MAX_MUX 4
401 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
402 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
403 typedef struct {
404 IOCanReadHandler *chr_can_read[MAX_MUX];
405 IOReadHandler *chr_read[MAX_MUX];
406 IOEventHandler *chr_event[MAX_MUX];
407 void *ext_opaque[MAX_MUX];
408 CharDriverState *drv;
409 int focus;
410 int mux_cnt;
411 int term_got_escape;
412 int max_size;
413 /* Intermediate input buffer allows to catch escape sequences even if the
414 currently active device is not accepting any input - but only until it
415 is full as well. */
416 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
417 int prod[MAX_MUX];
418 int cons[MAX_MUX];
419 int timestamps;
421 /* Protected by the CharDriverState chr_write_lock. */
422 int linestart;
423 int64_t timestamps_start;
424 } MuxDriver;
427 /* Called with chr_write_lock held. */
428 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
430 MuxDriver *d = chr->opaque;
431 int ret;
432 if (!d->timestamps) {
433 ret = qemu_chr_fe_write(d->drv, buf, len);
434 } else {
435 int i;
437 ret = 0;
438 for (i = 0; i < len; i++) {
439 if (d->linestart) {
440 char buf1[64];
441 int64_t ti;
442 int secs;
444 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
445 if (d->timestamps_start == -1)
446 d->timestamps_start = ti;
447 ti -= d->timestamps_start;
448 secs = ti / 1000;
449 snprintf(buf1, sizeof(buf1),
450 "[%02d:%02d:%02d.%03d] ",
451 secs / 3600,
452 (secs / 60) % 60,
453 secs % 60,
454 (int)(ti % 1000));
455 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
456 d->linestart = 0;
458 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
459 if (buf[i] == '\n') {
460 d->linestart = 1;
464 return ret;
467 static const char * const mux_help[] = {
468 "% h print this help\n\r",
469 "% x exit emulator\n\r",
470 "% s save disk data back to file (if -snapshot)\n\r",
471 "% t toggle console timestamps\n\r",
472 "% b send break (magic sysrq)\n\r",
473 "% c switch between console and monitor\n\r",
474 "% % sends %\n\r",
475 NULL
478 int term_escape_char = 0x01; /* ctrl-a is used for escape */
479 static void mux_print_help(CharDriverState *chr)
481 int i, j;
482 char ebuf[15] = "Escape-Char";
483 char cbuf[50] = "\n\r";
485 if (term_escape_char > 0 && term_escape_char < 26) {
486 snprintf(cbuf, sizeof(cbuf), "\n\r");
487 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
488 } else {
489 snprintf(cbuf, sizeof(cbuf),
490 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
491 term_escape_char);
493 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
494 for (i = 0; mux_help[i] != NULL; i++) {
495 for (j=0; mux_help[i][j] != '\0'; j++) {
496 if (mux_help[i][j] == '%')
497 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
498 else
499 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
504 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
506 if (d->chr_event[mux_nr])
507 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
510 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
512 if (d->term_got_escape) {
513 d->term_got_escape = 0;
514 if (ch == term_escape_char)
515 goto send_char;
516 switch(ch) {
517 case '?':
518 case 'h':
519 mux_print_help(chr);
520 break;
521 case 'x':
523 const char *term = "QEMU: Terminated\n\r";
524 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
525 exit(0);
526 break;
528 case 's':
529 bdrv_commit_all();
530 break;
531 case 'b':
532 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
533 break;
534 case 'c':
535 /* Switch to the next registered device */
536 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
537 d->focus++;
538 if (d->focus >= d->mux_cnt)
539 d->focus = 0;
540 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
541 break;
542 case 't':
543 d->timestamps = !d->timestamps;
544 d->timestamps_start = -1;
545 d->linestart = 0;
546 break;
548 } else if (ch == term_escape_char) {
549 d->term_got_escape = 1;
550 } else {
551 send_char:
552 return 1;
554 return 0;
557 static void mux_chr_accept_input(CharDriverState *chr)
559 MuxDriver *d = chr->opaque;
560 int m = d->focus;
562 while (d->prod[m] != d->cons[m] &&
563 d->chr_can_read[m] &&
564 d->chr_can_read[m](d->ext_opaque[m])) {
565 d->chr_read[m](d->ext_opaque[m],
566 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
570 static int mux_chr_can_read(void *opaque)
572 CharDriverState *chr = opaque;
573 MuxDriver *d = chr->opaque;
574 int m = d->focus;
576 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
577 return 1;
578 if (d->chr_can_read[m])
579 return d->chr_can_read[m](d->ext_opaque[m]);
580 return 0;
583 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
585 CharDriverState *chr = opaque;
586 MuxDriver *d = chr->opaque;
587 int m = d->focus;
588 int i;
590 mux_chr_accept_input (opaque);
592 for(i = 0; i < size; i++)
593 if (mux_proc_byte(chr, d, buf[i])) {
594 if (d->prod[m] == d->cons[m] &&
595 d->chr_can_read[m] &&
596 d->chr_can_read[m](d->ext_opaque[m]))
597 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
598 else
599 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
603 static void mux_chr_event(void *opaque, int event)
605 CharDriverState *chr = opaque;
606 MuxDriver *d = chr->opaque;
607 int i;
609 /* Send the event to all registered listeners */
610 for (i = 0; i < d->mux_cnt; i++)
611 mux_chr_send_event(d, i, event);
614 static void mux_chr_update_read_handler(CharDriverState *chr)
616 MuxDriver *d = chr->opaque;
618 if (d->mux_cnt >= MAX_MUX) {
619 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
620 return;
622 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
623 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
624 d->chr_read[d->mux_cnt] = chr->chr_read;
625 d->chr_event[d->mux_cnt] = chr->chr_event;
626 /* Fix up the real driver with mux routines */
627 if (d->mux_cnt == 0) {
628 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
629 mux_chr_event, chr);
631 if (d->focus != -1) {
632 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
634 d->focus = d->mux_cnt;
635 d->mux_cnt++;
636 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
639 static bool muxes_realized;
642 * Called after processing of default and command-line-specified
643 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
644 * to a mux chardev. This is done here to ensure that
645 * output/prompts/banners are only displayed for the FE that has
646 * focus when initial command-line processing/machine init is
647 * completed.
649 * After this point, any new FE attached to any new or existing
650 * mux will receive CHR_EVENT_OPENED notifications for the BE
651 * immediately.
653 static void muxes_realize_done(Notifier *notifier, void *unused)
655 CharDriverState *chr;
657 QTAILQ_FOREACH(chr, &chardevs, next) {
658 if (chr->is_mux) {
659 MuxDriver *d = chr->opaque;
660 int i;
662 /* send OPENED to all already-attached FEs */
663 for (i = 0; i < d->mux_cnt; i++) {
664 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
666 /* mark mux as OPENED so any new FEs will immediately receive
667 * OPENED event
669 qemu_chr_be_generic_open(chr);
672 muxes_realized = true;
675 static Notifier muxes_realize_notify = {
676 .notify = muxes_realize_done,
679 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
681 MuxDriver *d = s->opaque;
682 return d->drv->chr_add_watch(d->drv, cond);
685 static CharDriverState *qemu_chr_open_mux(const char *id,
686 ChardevBackend *backend,
687 ChardevReturn *ret, Error **errp)
689 ChardevMux *mux = backend->mux;
690 CharDriverState *chr, *drv;
691 MuxDriver *d;
693 drv = qemu_chr_find(mux->chardev);
694 if (drv == NULL) {
695 error_setg(errp, "mux: base chardev %s not found", mux->chardev);
696 return NULL;
699 chr = qemu_chr_alloc();
700 d = g_new0(MuxDriver, 1);
702 chr->opaque = d;
703 d->drv = drv;
704 d->focus = -1;
705 chr->chr_write = mux_chr_write;
706 chr->chr_update_read_handler = mux_chr_update_read_handler;
707 chr->chr_accept_input = mux_chr_accept_input;
708 /* Frontend guest-open / -close notification is not support with muxes */
709 chr->chr_set_fe_open = NULL;
710 if (drv->chr_add_watch) {
711 chr->chr_add_watch = mux_chr_add_watch;
713 /* only default to opened state if we've realized the initial
714 * set of muxes
716 chr->explicit_be_open = muxes_realized ? 0 : 1;
717 chr->is_mux = 1;
719 return chr;
723 #ifdef _WIN32
724 int send_all(int fd, const void *buf, int len1)
726 int ret, len;
728 len = len1;
729 while (len > 0) {
730 ret = send(fd, buf, len, 0);
731 if (ret < 0) {
732 errno = WSAGetLastError();
733 if (errno != WSAEWOULDBLOCK) {
734 return -1;
736 } else if (ret == 0) {
737 break;
738 } else {
739 buf += ret;
740 len -= ret;
743 return len1 - len;
746 #else
748 int send_all(int fd, const void *_buf, int len1)
750 int ret, len;
751 const uint8_t *buf = _buf;
753 len = len1;
754 while (len > 0) {
755 ret = write(fd, buf, len);
756 if (ret < 0) {
757 if (errno != EINTR && errno != EAGAIN)
758 return -1;
759 } else if (ret == 0) {
760 break;
761 } else {
762 buf += ret;
763 len -= ret;
766 return len1 - len;
769 int recv_all(int fd, void *_buf, int len1, bool single_read)
771 int ret, len;
772 uint8_t *buf = _buf;
774 len = len1;
775 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
776 if (ret < 0) {
777 if (errno != EINTR && errno != EAGAIN) {
778 return -1;
780 continue;
781 } else {
782 if (single_read) {
783 return ret;
785 buf += ret;
786 len -= ret;
789 return len1 - len;
792 #endif /* !_WIN32 */
794 typedef struct IOWatchPoll
796 GSource parent;
798 GIOChannel *channel;
799 GSource *src;
801 IOCanReadHandler *fd_can_read;
802 GSourceFunc fd_read;
803 void *opaque;
804 } IOWatchPoll;
806 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
808 return container_of(source, IOWatchPoll, parent);
811 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
813 IOWatchPoll *iwp = io_watch_poll_from_source(source);
814 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
815 bool was_active = iwp->src != NULL;
816 if (was_active == now_active) {
817 return FALSE;
820 if (now_active) {
821 iwp->src = g_io_create_watch(iwp->channel,
822 G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
823 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
824 g_source_attach(iwp->src, NULL);
825 } else {
826 g_source_destroy(iwp->src);
827 g_source_unref(iwp->src);
828 iwp->src = NULL;
830 return FALSE;
833 static gboolean io_watch_poll_check(GSource *source)
835 return FALSE;
838 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
839 gpointer user_data)
841 abort();
844 static void io_watch_poll_finalize(GSource *source)
846 /* Due to a glib bug, removing the last reference to a source
847 * inside a finalize callback causes recursive locking (and a
848 * deadlock). This is not a problem inside other callbacks,
849 * including dispatch callbacks, so we call io_remove_watch_poll
850 * to remove this source. At this point, iwp->src must
851 * be NULL, or we would leak it.
853 * This would be solved much more elegantly by child sources,
854 * but we support older glib versions that do not have them.
856 IOWatchPoll *iwp = io_watch_poll_from_source(source);
857 assert(iwp->src == NULL);
860 static GSourceFuncs io_watch_poll_funcs = {
861 .prepare = io_watch_poll_prepare,
862 .check = io_watch_poll_check,
863 .dispatch = io_watch_poll_dispatch,
864 .finalize = io_watch_poll_finalize,
867 /* Can only be used for read */
868 static guint io_add_watch_poll(GIOChannel *channel,
869 IOCanReadHandler *fd_can_read,
870 GIOFunc fd_read,
871 gpointer user_data)
873 IOWatchPoll *iwp;
874 int tag;
876 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
877 iwp->fd_can_read = fd_can_read;
878 iwp->opaque = user_data;
879 iwp->channel = channel;
880 iwp->fd_read = (GSourceFunc) fd_read;
881 iwp->src = NULL;
883 tag = g_source_attach(&iwp->parent, NULL);
884 g_source_unref(&iwp->parent);
885 return tag;
888 static void io_remove_watch_poll(guint tag)
890 GSource *source;
891 IOWatchPoll *iwp;
893 g_return_if_fail (tag > 0);
895 source = g_main_context_find_source_by_id(NULL, tag);
896 g_return_if_fail (source != NULL);
898 iwp = io_watch_poll_from_source(source);
899 if (iwp->src) {
900 g_source_destroy(iwp->src);
901 g_source_unref(iwp->src);
902 iwp->src = NULL;
904 g_source_destroy(&iwp->parent);
907 static void remove_fd_in_watch(CharDriverState *chr)
909 if (chr->fd_in_tag) {
910 io_remove_watch_poll(chr->fd_in_tag);
911 chr->fd_in_tag = 0;
915 #ifndef _WIN32
916 static GIOChannel *io_channel_from_fd(int fd)
918 GIOChannel *chan;
920 if (fd == -1) {
921 return NULL;
924 chan = g_io_channel_unix_new(fd);
926 g_io_channel_set_encoding(chan, NULL, NULL);
927 g_io_channel_set_buffered(chan, FALSE);
929 return chan;
931 #endif
933 static GIOChannel *io_channel_from_socket(int fd)
935 GIOChannel *chan;
937 if (fd == -1) {
938 return NULL;
941 #ifdef _WIN32
942 chan = g_io_channel_win32_new_socket(fd);
943 #else
944 chan = g_io_channel_unix_new(fd);
945 #endif
947 g_io_channel_set_encoding(chan, NULL, NULL);
948 g_io_channel_set_buffered(chan, FALSE);
950 return chan;
953 static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
955 size_t offset = 0;
956 GIOStatus status = G_IO_STATUS_NORMAL;
958 while (offset < len && status == G_IO_STATUS_NORMAL) {
959 gsize bytes_written = 0;
961 status = g_io_channel_write_chars(fd, buf + offset, len - offset,
962 &bytes_written, NULL);
963 offset += bytes_written;
966 if (offset > 0) {
967 return offset;
969 switch (status) {
970 case G_IO_STATUS_NORMAL:
971 g_assert(len == 0);
972 return 0;
973 case G_IO_STATUS_AGAIN:
974 errno = EAGAIN;
975 return -1;
976 default:
977 break;
979 errno = EINVAL;
980 return -1;
983 #ifndef _WIN32
985 typedef struct FDCharDriver {
986 CharDriverState *chr;
987 GIOChannel *fd_in, *fd_out;
988 int max_size;
989 } FDCharDriver;
991 /* Called with chr_write_lock held. */
992 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
994 FDCharDriver *s = chr->opaque;
996 return io_channel_send(s->fd_out, buf, len);
999 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1001 CharDriverState *chr = opaque;
1002 FDCharDriver *s = chr->opaque;
1003 int len;
1004 uint8_t buf[READ_BUF_LEN];
1005 GIOStatus status;
1006 gsize bytes_read;
1008 len = sizeof(buf);
1009 if (len > s->max_size) {
1010 len = s->max_size;
1012 if (len == 0) {
1013 return TRUE;
1016 status = g_io_channel_read_chars(chan, (gchar *)buf,
1017 len, &bytes_read, NULL);
1018 if (status == G_IO_STATUS_EOF) {
1019 remove_fd_in_watch(chr);
1020 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1021 return FALSE;
1023 if (status == G_IO_STATUS_NORMAL) {
1024 qemu_chr_be_write(chr, buf, bytes_read);
1027 return TRUE;
1030 static int fd_chr_read_poll(void *opaque)
1032 CharDriverState *chr = opaque;
1033 FDCharDriver *s = chr->opaque;
1035 s->max_size = qemu_chr_be_can_write(chr);
1036 return s->max_size;
1039 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1041 FDCharDriver *s = chr->opaque;
1042 return g_io_create_watch(s->fd_out, cond);
1045 static void fd_chr_update_read_handler(CharDriverState *chr)
1047 FDCharDriver *s = chr->opaque;
1049 remove_fd_in_watch(chr);
1050 if (s->fd_in) {
1051 chr->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll,
1052 fd_chr_read, chr);
1056 static void fd_chr_close(struct CharDriverState *chr)
1058 FDCharDriver *s = chr->opaque;
1060 remove_fd_in_watch(chr);
1061 if (s->fd_in) {
1062 g_io_channel_unref(s->fd_in);
1064 if (s->fd_out) {
1065 g_io_channel_unref(s->fd_out);
1068 g_free(s);
1069 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1072 /* open a character device to a unix fd */
1073 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1075 CharDriverState *chr;
1076 FDCharDriver *s;
1078 chr = qemu_chr_alloc();
1079 s = g_new0(FDCharDriver, 1);
1080 s->fd_in = io_channel_from_fd(fd_in);
1081 s->fd_out = io_channel_from_fd(fd_out);
1082 qemu_set_nonblock(fd_out);
1083 s->chr = chr;
1084 chr->opaque = s;
1085 chr->chr_add_watch = fd_chr_add_watch;
1086 chr->chr_write = fd_chr_write;
1087 chr->chr_update_read_handler = fd_chr_update_read_handler;
1088 chr->chr_close = fd_chr_close;
1090 return chr;
1093 static CharDriverState *qemu_chr_open_pipe(const char *id,
1094 ChardevBackend *backend,
1095 ChardevReturn *ret,
1096 Error **errp)
1098 ChardevHostdev *opts = backend->pipe;
1099 int fd_in, fd_out;
1100 char filename_in[CHR_MAX_FILENAME_SIZE];
1101 char filename_out[CHR_MAX_FILENAME_SIZE];
1102 const char *filename = opts->device;
1104 snprintf(filename_in, CHR_MAX_FILENAME_SIZE, "%s.in", filename);
1105 snprintf(filename_out, CHR_MAX_FILENAME_SIZE, "%s.out", filename);
1106 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1107 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1108 if (fd_in < 0 || fd_out < 0) {
1109 if (fd_in >= 0)
1110 close(fd_in);
1111 if (fd_out >= 0)
1112 close(fd_out);
1113 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1114 if (fd_in < 0) {
1115 error_setg_file_open(errp, errno, filename);
1116 return NULL;
1119 return qemu_chr_open_fd(fd_in, fd_out);
1122 /* init terminal so that we can grab keys */
1123 static struct termios oldtty;
1124 static int old_fd0_flags;
1125 static bool stdio_in_use;
1126 static bool stdio_allow_signal;
1127 static bool stdio_echo_state;
1129 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo);
1131 static void term_exit(void)
1133 tcsetattr (0, TCSANOW, &oldtty);
1134 fcntl(0, F_SETFL, old_fd0_flags);
1137 static void term_stdio_handler(int sig)
1139 /* restore echo after resume from suspend. */
1140 qemu_chr_set_echo_stdio(NULL, stdio_echo_state);
1143 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1145 struct termios tty;
1147 stdio_echo_state = echo;
1148 tty = oldtty;
1149 if (!echo) {
1150 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1151 |INLCR|IGNCR|ICRNL|IXON);
1152 tty.c_oflag |= OPOST;
1153 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1154 tty.c_cflag &= ~(CSIZE|PARENB);
1155 tty.c_cflag |= CS8;
1156 tty.c_cc[VMIN] = 1;
1157 tty.c_cc[VTIME] = 0;
1159 if (!stdio_allow_signal)
1160 tty.c_lflag &= ~ISIG;
1162 tcsetattr (0, TCSANOW, &tty);
1165 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1167 term_exit();
1168 fd_chr_close(chr);
1171 static CharDriverState *qemu_chr_open_stdio(const char *id,
1172 ChardevBackend *backend,
1173 ChardevReturn *ret,
1174 Error **errp)
1176 ChardevStdio *opts = backend->stdio;
1177 CharDriverState *chr;
1178 struct sigaction act;
1180 if (is_daemonized()) {
1181 error_setg(errp, "cannot use stdio with -daemonize");
1182 return NULL;
1185 if (stdio_in_use) {
1186 error_setg(errp, "cannot use stdio by multiple character devices");
1187 return NULL;
1190 stdio_in_use = true;
1191 old_fd0_flags = fcntl(0, F_GETFL);
1192 tcgetattr(0, &oldtty);
1193 qemu_set_nonblock(0);
1194 atexit(term_exit);
1196 memset(&act, 0, sizeof(act));
1197 act.sa_handler = term_stdio_handler;
1198 sigaction(SIGCONT, &act, NULL);
1200 chr = qemu_chr_open_fd(0, 1);
1201 chr->chr_close = qemu_chr_close_stdio;
1202 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1203 if (opts->has_signal) {
1204 stdio_allow_signal = opts->signal;
1206 qemu_chr_fe_set_echo(chr, false);
1208 return chr;
1211 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1212 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1213 || defined(__GLIBC__)
1215 #define HAVE_CHARDEV_SERIAL 1
1216 #define HAVE_CHARDEV_PTY 1
1218 typedef struct {
1219 GIOChannel *fd;
1220 int read_bytes;
1222 /* Protected by the CharDriverState chr_write_lock. */
1223 int connected;
1224 guint timer_tag;
1225 guint open_tag;
1226 } PtyCharDriver;
1228 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1229 static void pty_chr_state(CharDriverState *chr, int connected);
1231 static gboolean pty_chr_timer(gpointer opaque)
1233 struct CharDriverState *chr = opaque;
1234 PtyCharDriver *s = chr->opaque;
1236 qemu_mutex_lock(&chr->chr_write_lock);
1237 s->timer_tag = 0;
1238 s->open_tag = 0;
1239 if (!s->connected) {
1240 /* Next poll ... */
1241 pty_chr_update_read_handler_locked(chr);
1243 qemu_mutex_unlock(&chr->chr_write_lock);
1244 return FALSE;
1247 /* Called with chr_write_lock held. */
1248 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1250 PtyCharDriver *s = chr->opaque;
1252 if (s->timer_tag) {
1253 g_source_remove(s->timer_tag);
1254 s->timer_tag = 0;
1257 if (ms == 1000) {
1258 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1259 } else {
1260 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1264 /* Called with chr_write_lock held. */
1265 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1267 PtyCharDriver *s = chr->opaque;
1268 GPollFD pfd;
1270 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1271 pfd.events = G_IO_OUT;
1272 pfd.revents = 0;
1273 g_poll(&pfd, 1, 0);
1274 if (pfd.revents & G_IO_HUP) {
1275 pty_chr_state(chr, 0);
1276 } else {
1277 pty_chr_state(chr, 1);
1281 static void pty_chr_update_read_handler(CharDriverState *chr)
1283 qemu_mutex_lock(&chr->chr_write_lock);
1284 pty_chr_update_read_handler_locked(chr);
1285 qemu_mutex_unlock(&chr->chr_write_lock);
1288 /* Called with chr_write_lock held. */
1289 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1291 PtyCharDriver *s = chr->opaque;
1293 if (!s->connected) {
1294 /* guest sends data, check for (re-)connect */
1295 pty_chr_update_read_handler_locked(chr);
1296 if (!s->connected) {
1297 return 0;
1300 return io_channel_send(s->fd, buf, len);
1303 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1305 PtyCharDriver *s = chr->opaque;
1306 if (!s->connected) {
1307 return NULL;
1309 return g_io_create_watch(s->fd, cond);
1312 static int pty_chr_read_poll(void *opaque)
1314 CharDriverState *chr = opaque;
1315 PtyCharDriver *s = chr->opaque;
1317 s->read_bytes = qemu_chr_be_can_write(chr);
1318 return s->read_bytes;
1321 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1323 CharDriverState *chr = opaque;
1324 PtyCharDriver *s = chr->opaque;
1325 gsize size, len;
1326 uint8_t buf[READ_BUF_LEN];
1327 GIOStatus status;
1329 len = sizeof(buf);
1330 if (len > s->read_bytes)
1331 len = s->read_bytes;
1332 if (len == 0) {
1333 return TRUE;
1335 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1336 if (status != G_IO_STATUS_NORMAL) {
1337 pty_chr_state(chr, 0);
1338 return FALSE;
1339 } else {
1340 pty_chr_state(chr, 1);
1341 qemu_chr_be_write(chr, buf, size);
1343 return TRUE;
1346 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1348 CharDriverState *chr = opaque;
1349 PtyCharDriver *s = chr->opaque;
1351 s->open_tag = 0;
1352 qemu_chr_be_generic_open(chr);
1353 return FALSE;
1356 /* Called with chr_write_lock held. */
1357 static void pty_chr_state(CharDriverState *chr, int connected)
1359 PtyCharDriver *s = chr->opaque;
1361 if (!connected) {
1362 if (s->open_tag) {
1363 g_source_remove(s->open_tag);
1364 s->open_tag = 0;
1366 remove_fd_in_watch(chr);
1367 s->connected = 0;
1368 /* (re-)connect poll interval for idle guests: once per second.
1369 * We check more frequently in case the guests sends data to
1370 * the virtual device linked to our pty. */
1371 pty_chr_rearm_timer(chr, 1000);
1372 } else {
1373 if (s->timer_tag) {
1374 g_source_remove(s->timer_tag);
1375 s->timer_tag = 0;
1377 if (!s->connected) {
1378 g_assert(s->open_tag == 0);
1379 s->connected = 1;
1380 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1382 if (!chr->fd_in_tag) {
1383 chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
1384 pty_chr_read, chr);
1389 static void pty_chr_close(struct CharDriverState *chr)
1391 PtyCharDriver *s = chr->opaque;
1392 int fd;
1394 qemu_mutex_lock(&chr->chr_write_lock);
1395 pty_chr_state(chr, 0);
1396 fd = g_io_channel_unix_get_fd(s->fd);
1397 g_io_channel_unref(s->fd);
1398 close(fd);
1399 if (s->timer_tag) {
1400 g_source_remove(s->timer_tag);
1401 s->timer_tag = 0;
1403 qemu_mutex_unlock(&chr->chr_write_lock);
1404 g_free(s);
1405 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1408 static CharDriverState *qemu_chr_open_pty(const char *id,
1409 ChardevBackend *backend,
1410 ChardevReturn *ret,
1411 Error **errp)
1413 CharDriverState *chr;
1414 PtyCharDriver *s;
1415 int master_fd, slave_fd;
1416 char pty_name[PATH_MAX];
1418 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1419 if (master_fd < 0) {
1420 error_setg_errno(errp, errno, "Failed to create PTY");
1421 return NULL;
1424 close(slave_fd);
1425 qemu_set_nonblock(master_fd);
1427 chr = qemu_chr_alloc();
1429 chr->filename = g_strdup_printf("pty:%s", pty_name);
1430 ret->pty = g_strdup(pty_name);
1431 ret->has_pty = true;
1433 fprintf(stderr, "char device redirected to %s (label %s)\n",
1434 pty_name, id);
1436 s = g_new0(PtyCharDriver, 1);
1437 chr->opaque = s;
1438 chr->chr_write = pty_chr_write;
1439 chr->chr_update_read_handler = pty_chr_update_read_handler;
1440 chr->chr_close = pty_chr_close;
1441 chr->chr_add_watch = pty_chr_add_watch;
1442 chr->explicit_be_open = true;
1444 s->fd = io_channel_from_fd(master_fd);
1445 s->timer_tag = 0;
1447 return chr;
1450 static void tty_serial_init(int fd, int speed,
1451 int parity, int data_bits, int stop_bits)
1453 struct termios tty;
1454 speed_t spd;
1456 #if 0
1457 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1458 speed, parity, data_bits, stop_bits);
1459 #endif
1460 tcgetattr (fd, &tty);
1462 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1463 speed = speed * 10 / 11;
1464 do {
1465 check_speed(50);
1466 check_speed(75);
1467 check_speed(110);
1468 check_speed(134);
1469 check_speed(150);
1470 check_speed(200);
1471 check_speed(300);
1472 check_speed(600);
1473 check_speed(1200);
1474 check_speed(1800);
1475 check_speed(2400);
1476 check_speed(4800);
1477 check_speed(9600);
1478 check_speed(19200);
1479 check_speed(38400);
1480 /* Non-Posix values follow. They may be unsupported on some systems. */
1481 check_speed(57600);
1482 check_speed(115200);
1483 #ifdef B230400
1484 check_speed(230400);
1485 #endif
1486 #ifdef B460800
1487 check_speed(460800);
1488 #endif
1489 #ifdef B500000
1490 check_speed(500000);
1491 #endif
1492 #ifdef B576000
1493 check_speed(576000);
1494 #endif
1495 #ifdef B921600
1496 check_speed(921600);
1497 #endif
1498 #ifdef B1000000
1499 check_speed(1000000);
1500 #endif
1501 #ifdef B1152000
1502 check_speed(1152000);
1503 #endif
1504 #ifdef B1500000
1505 check_speed(1500000);
1506 #endif
1507 #ifdef B2000000
1508 check_speed(2000000);
1509 #endif
1510 #ifdef B2500000
1511 check_speed(2500000);
1512 #endif
1513 #ifdef B3000000
1514 check_speed(3000000);
1515 #endif
1516 #ifdef B3500000
1517 check_speed(3500000);
1518 #endif
1519 #ifdef B4000000
1520 check_speed(4000000);
1521 #endif
1522 spd = B115200;
1523 } while (0);
1525 cfsetispeed(&tty, spd);
1526 cfsetospeed(&tty, spd);
1528 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1529 |INLCR|IGNCR|ICRNL|IXON);
1530 tty.c_oflag |= OPOST;
1531 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1532 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1533 switch(data_bits) {
1534 default:
1535 case 8:
1536 tty.c_cflag |= CS8;
1537 break;
1538 case 7:
1539 tty.c_cflag |= CS7;
1540 break;
1541 case 6:
1542 tty.c_cflag |= CS6;
1543 break;
1544 case 5:
1545 tty.c_cflag |= CS5;
1546 break;
1548 switch(parity) {
1549 default:
1550 case 'N':
1551 break;
1552 case 'E':
1553 tty.c_cflag |= PARENB;
1554 break;
1555 case 'O':
1556 tty.c_cflag |= PARENB | PARODD;
1557 break;
1559 if (stop_bits == 2)
1560 tty.c_cflag |= CSTOPB;
1562 tcsetattr (fd, TCSANOW, &tty);
1565 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1567 FDCharDriver *s = chr->opaque;
1569 switch(cmd) {
1570 case CHR_IOCTL_SERIAL_SET_PARAMS:
1572 QEMUSerialSetParams *ssp = arg;
1573 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1574 ssp->speed, ssp->parity,
1575 ssp->data_bits, ssp->stop_bits);
1577 break;
1578 case CHR_IOCTL_SERIAL_SET_BREAK:
1580 int enable = *(int *)arg;
1581 if (enable) {
1582 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1585 break;
1586 case CHR_IOCTL_SERIAL_GET_TIOCM:
1588 int sarg = 0;
1589 int *targ = (int *)arg;
1590 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1591 *targ = 0;
1592 if (sarg & TIOCM_CTS)
1593 *targ |= CHR_TIOCM_CTS;
1594 if (sarg & TIOCM_CAR)
1595 *targ |= CHR_TIOCM_CAR;
1596 if (sarg & TIOCM_DSR)
1597 *targ |= CHR_TIOCM_DSR;
1598 if (sarg & TIOCM_RI)
1599 *targ |= CHR_TIOCM_RI;
1600 if (sarg & TIOCM_DTR)
1601 *targ |= CHR_TIOCM_DTR;
1602 if (sarg & TIOCM_RTS)
1603 *targ |= CHR_TIOCM_RTS;
1605 break;
1606 case CHR_IOCTL_SERIAL_SET_TIOCM:
1608 int sarg = *(int *)arg;
1609 int targ = 0;
1610 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1611 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1612 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1613 if (sarg & CHR_TIOCM_CTS)
1614 targ |= TIOCM_CTS;
1615 if (sarg & CHR_TIOCM_CAR)
1616 targ |= TIOCM_CAR;
1617 if (sarg & CHR_TIOCM_DSR)
1618 targ |= TIOCM_DSR;
1619 if (sarg & CHR_TIOCM_RI)
1620 targ |= TIOCM_RI;
1621 if (sarg & CHR_TIOCM_DTR)
1622 targ |= TIOCM_DTR;
1623 if (sarg & CHR_TIOCM_RTS)
1624 targ |= TIOCM_RTS;
1625 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1627 break;
1628 default:
1629 return -ENOTSUP;
1631 return 0;
1634 static void qemu_chr_close_tty(CharDriverState *chr)
1636 FDCharDriver *s = chr->opaque;
1637 int fd = -1;
1639 if (s) {
1640 fd = g_io_channel_unix_get_fd(s->fd_in);
1643 fd_chr_close(chr);
1645 if (fd >= 0) {
1646 close(fd);
1650 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1652 CharDriverState *chr;
1654 tty_serial_init(fd, 115200, 'N', 8, 1);
1655 chr = qemu_chr_open_fd(fd, fd);
1656 chr->chr_ioctl = tty_serial_ioctl;
1657 chr->chr_close = qemu_chr_close_tty;
1658 return chr;
1660 #endif /* __linux__ || __sun__ */
1662 #if defined(__linux__)
1664 #define HAVE_CHARDEV_PARPORT 1
1666 typedef struct {
1667 int fd;
1668 int mode;
1669 } ParallelCharDriver;
1671 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1673 if (s->mode != mode) {
1674 int m = mode;
1675 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1676 return 0;
1677 s->mode = mode;
1679 return 1;
1682 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1684 ParallelCharDriver *drv = chr->opaque;
1685 int fd = drv->fd;
1686 uint8_t b;
1688 switch(cmd) {
1689 case CHR_IOCTL_PP_READ_DATA:
1690 if (ioctl(fd, PPRDATA, &b) < 0)
1691 return -ENOTSUP;
1692 *(uint8_t *)arg = b;
1693 break;
1694 case CHR_IOCTL_PP_WRITE_DATA:
1695 b = *(uint8_t *)arg;
1696 if (ioctl(fd, PPWDATA, &b) < 0)
1697 return -ENOTSUP;
1698 break;
1699 case CHR_IOCTL_PP_READ_CONTROL:
1700 if (ioctl(fd, PPRCONTROL, &b) < 0)
1701 return -ENOTSUP;
1702 /* Linux gives only the lowest bits, and no way to know data
1703 direction! For better compatibility set the fixed upper
1704 bits. */
1705 *(uint8_t *)arg = b | 0xc0;
1706 break;
1707 case CHR_IOCTL_PP_WRITE_CONTROL:
1708 b = *(uint8_t *)arg;
1709 if (ioctl(fd, PPWCONTROL, &b) < 0)
1710 return -ENOTSUP;
1711 break;
1712 case CHR_IOCTL_PP_READ_STATUS:
1713 if (ioctl(fd, PPRSTATUS, &b) < 0)
1714 return -ENOTSUP;
1715 *(uint8_t *)arg = b;
1716 break;
1717 case CHR_IOCTL_PP_DATA_DIR:
1718 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1719 return -ENOTSUP;
1720 break;
1721 case CHR_IOCTL_PP_EPP_READ_ADDR:
1722 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1723 struct ParallelIOArg *parg = arg;
1724 int n = read(fd, parg->buffer, parg->count);
1725 if (n != parg->count) {
1726 return -EIO;
1729 break;
1730 case CHR_IOCTL_PP_EPP_READ:
1731 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1732 struct ParallelIOArg *parg = arg;
1733 int n = read(fd, parg->buffer, parg->count);
1734 if (n != parg->count) {
1735 return -EIO;
1738 break;
1739 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1740 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1741 struct ParallelIOArg *parg = arg;
1742 int n = write(fd, parg->buffer, parg->count);
1743 if (n != parg->count) {
1744 return -EIO;
1747 break;
1748 case CHR_IOCTL_PP_EPP_WRITE:
1749 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1750 struct ParallelIOArg *parg = arg;
1751 int n = write(fd, parg->buffer, parg->count);
1752 if (n != parg->count) {
1753 return -EIO;
1756 break;
1757 default:
1758 return -ENOTSUP;
1760 return 0;
1763 static void pp_close(CharDriverState *chr)
1765 ParallelCharDriver *drv = chr->opaque;
1766 int fd = drv->fd;
1768 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1769 ioctl(fd, PPRELEASE);
1770 close(fd);
1771 g_free(drv);
1772 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1775 static CharDriverState *qemu_chr_open_pp_fd(int fd, Error **errp)
1777 CharDriverState *chr;
1778 ParallelCharDriver *drv;
1780 if (ioctl(fd, PPCLAIM) < 0) {
1781 error_setg_errno(errp, errno, "not a parallel port");
1782 close(fd);
1783 return NULL;
1786 drv = g_new0(ParallelCharDriver, 1);
1787 drv->fd = fd;
1788 drv->mode = IEEE1284_MODE_COMPAT;
1790 chr = qemu_chr_alloc();
1791 chr->chr_write = null_chr_write;
1792 chr->chr_ioctl = pp_ioctl;
1793 chr->chr_close = pp_close;
1794 chr->opaque = drv;
1796 return chr;
1798 #endif /* __linux__ */
1800 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1802 #define HAVE_CHARDEV_PARPORT 1
1804 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1806 int fd = (int)(intptr_t)chr->opaque;
1807 uint8_t b;
1809 switch(cmd) {
1810 case CHR_IOCTL_PP_READ_DATA:
1811 if (ioctl(fd, PPIGDATA, &b) < 0)
1812 return -ENOTSUP;
1813 *(uint8_t *)arg = b;
1814 break;
1815 case CHR_IOCTL_PP_WRITE_DATA:
1816 b = *(uint8_t *)arg;
1817 if (ioctl(fd, PPISDATA, &b) < 0)
1818 return -ENOTSUP;
1819 break;
1820 case CHR_IOCTL_PP_READ_CONTROL:
1821 if (ioctl(fd, PPIGCTRL, &b) < 0)
1822 return -ENOTSUP;
1823 *(uint8_t *)arg = b;
1824 break;
1825 case CHR_IOCTL_PP_WRITE_CONTROL:
1826 b = *(uint8_t *)arg;
1827 if (ioctl(fd, PPISCTRL, &b) < 0)
1828 return -ENOTSUP;
1829 break;
1830 case CHR_IOCTL_PP_READ_STATUS:
1831 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1832 return -ENOTSUP;
1833 *(uint8_t *)arg = b;
1834 break;
1835 default:
1836 return -ENOTSUP;
1838 return 0;
1841 static CharDriverState *qemu_chr_open_pp_fd(int fd, Error **errp)
1843 CharDriverState *chr;
1845 chr = qemu_chr_alloc();
1846 chr->opaque = (void *)(intptr_t)fd;
1847 chr->chr_write = null_chr_write;
1848 chr->chr_ioctl = pp_ioctl;
1849 chr->explicit_be_open = true;
1850 return chr;
1852 #endif
1854 #else /* _WIN32 */
1856 #define HAVE_CHARDEV_SERIAL 1
1858 typedef struct {
1859 int max_size;
1860 HANDLE hcom, hrecv, hsend;
1861 OVERLAPPED orecv;
1862 BOOL fpipe;
1863 DWORD len;
1865 /* Protected by the CharDriverState chr_write_lock. */
1866 OVERLAPPED osend;
1867 } WinCharState;
1869 typedef struct {
1870 HANDLE hStdIn;
1871 HANDLE hInputReadyEvent;
1872 HANDLE hInputDoneEvent;
1873 HANDLE hInputThread;
1874 uint8_t win_stdio_buf;
1875 } WinStdioCharState;
1877 #define NSENDBUF 2048
1878 #define NRECVBUF 2048
1879 #define MAXCONNECT 1
1880 #define NTIMEOUT 5000
1882 static int win_chr_poll(void *opaque);
1883 static int win_chr_pipe_poll(void *opaque);
1885 static void win_chr_close(CharDriverState *chr)
1887 WinCharState *s = chr->opaque;
1889 if (s->hsend) {
1890 CloseHandle(s->hsend);
1891 s->hsend = NULL;
1893 if (s->hrecv) {
1894 CloseHandle(s->hrecv);
1895 s->hrecv = NULL;
1897 if (s->hcom) {
1898 CloseHandle(s->hcom);
1899 s->hcom = NULL;
1901 if (s->fpipe)
1902 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1903 else
1904 qemu_del_polling_cb(win_chr_poll, chr);
1906 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1909 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1911 WinCharState *s = chr->opaque;
1912 COMMCONFIG comcfg;
1913 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1914 COMSTAT comstat;
1915 DWORD size;
1916 DWORD err;
1918 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1919 if (!s->hsend) {
1920 error_setg(errp, "Failed CreateEvent");
1921 goto fail;
1923 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1924 if (!s->hrecv) {
1925 error_setg(errp, "Failed CreateEvent");
1926 goto fail;
1929 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1930 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1931 if (s->hcom == INVALID_HANDLE_VALUE) {
1932 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1933 s->hcom = NULL;
1934 goto fail;
1937 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1938 error_setg(errp, "Failed SetupComm");
1939 goto fail;
1942 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1943 size = sizeof(COMMCONFIG);
1944 GetDefaultCommConfig(filename, &comcfg, &size);
1945 comcfg.dcb.DCBlength = sizeof(DCB);
1946 CommConfigDialog(filename, NULL, &comcfg);
1948 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1949 error_setg(errp, "Failed SetCommState");
1950 goto fail;
1953 if (!SetCommMask(s->hcom, EV_ERR)) {
1954 error_setg(errp, "Failed SetCommMask");
1955 goto fail;
1958 cto.ReadIntervalTimeout = MAXDWORD;
1959 if (!SetCommTimeouts(s->hcom, &cto)) {
1960 error_setg(errp, "Failed SetCommTimeouts");
1961 goto fail;
1964 if (!ClearCommError(s->hcom, &err, &comstat)) {
1965 error_setg(errp, "Failed ClearCommError");
1966 goto fail;
1968 qemu_add_polling_cb(win_chr_poll, chr);
1969 return 0;
1971 fail:
1972 win_chr_close(chr);
1973 return -1;
1976 /* Called with chr_write_lock held. */
1977 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1979 WinCharState *s = chr->opaque;
1980 DWORD len, ret, size, err;
1982 len = len1;
1983 ZeroMemory(&s->osend, sizeof(s->osend));
1984 s->osend.hEvent = s->hsend;
1985 while (len > 0) {
1986 if (s->hsend)
1987 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1988 else
1989 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1990 if (!ret) {
1991 err = GetLastError();
1992 if (err == ERROR_IO_PENDING) {
1993 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1994 if (ret) {
1995 buf += size;
1996 len -= size;
1997 } else {
1998 break;
2000 } else {
2001 break;
2003 } else {
2004 buf += size;
2005 len -= size;
2008 return len1 - len;
2011 static int win_chr_read_poll(CharDriverState *chr)
2013 WinCharState *s = chr->opaque;
2015 s->max_size = qemu_chr_be_can_write(chr);
2016 return s->max_size;
2019 static void win_chr_readfile(CharDriverState *chr)
2021 WinCharState *s = chr->opaque;
2022 int ret, err;
2023 uint8_t buf[READ_BUF_LEN];
2024 DWORD size;
2026 ZeroMemory(&s->orecv, sizeof(s->orecv));
2027 s->orecv.hEvent = s->hrecv;
2028 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2029 if (!ret) {
2030 err = GetLastError();
2031 if (err == ERROR_IO_PENDING) {
2032 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2036 if (size > 0) {
2037 qemu_chr_be_write(chr, buf, size);
2041 static void win_chr_read(CharDriverState *chr)
2043 WinCharState *s = chr->opaque;
2045 if (s->len > s->max_size)
2046 s->len = s->max_size;
2047 if (s->len == 0)
2048 return;
2050 win_chr_readfile(chr);
2053 static int win_chr_poll(void *opaque)
2055 CharDriverState *chr = opaque;
2056 WinCharState *s = chr->opaque;
2057 COMSTAT status;
2058 DWORD comerr;
2060 ClearCommError(s->hcom, &comerr, &status);
2061 if (status.cbInQue > 0) {
2062 s->len = status.cbInQue;
2063 win_chr_read_poll(chr);
2064 win_chr_read(chr);
2065 return 1;
2067 return 0;
2070 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2071 Error **errp)
2073 CharDriverState *chr;
2074 WinCharState *s;
2076 chr = qemu_chr_alloc();
2077 s = g_new0(WinCharState, 1);
2078 chr->opaque = s;
2079 chr->chr_write = win_chr_write;
2080 chr->chr_close = win_chr_close;
2082 if (win_chr_init(chr, filename, errp) < 0) {
2083 g_free(s);
2084 g_free(chr);
2085 return NULL;
2087 return chr;
2090 static int win_chr_pipe_poll(void *opaque)
2092 CharDriverState *chr = opaque;
2093 WinCharState *s = chr->opaque;
2094 DWORD size;
2096 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2097 if (size > 0) {
2098 s->len = size;
2099 win_chr_read_poll(chr);
2100 win_chr_read(chr);
2101 return 1;
2103 return 0;
2106 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2107 Error **errp)
2109 WinCharState *s = chr->opaque;
2110 OVERLAPPED ov;
2111 int ret;
2112 DWORD size;
2113 char openname[CHR_MAX_FILENAME_SIZE];
2115 s->fpipe = TRUE;
2117 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2118 if (!s->hsend) {
2119 error_setg(errp, "Failed CreateEvent");
2120 goto fail;
2122 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2123 if (!s->hrecv) {
2124 error_setg(errp, "Failed CreateEvent");
2125 goto fail;
2128 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2129 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2130 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2131 PIPE_WAIT,
2132 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2133 if (s->hcom == INVALID_HANDLE_VALUE) {
2134 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2135 s->hcom = NULL;
2136 goto fail;
2139 ZeroMemory(&ov, sizeof(ov));
2140 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2141 ret = ConnectNamedPipe(s->hcom, &ov);
2142 if (ret) {
2143 error_setg(errp, "Failed ConnectNamedPipe");
2144 goto fail;
2147 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2148 if (!ret) {
2149 error_setg(errp, "Failed GetOverlappedResult");
2150 if (ov.hEvent) {
2151 CloseHandle(ov.hEvent);
2152 ov.hEvent = NULL;
2154 goto fail;
2157 if (ov.hEvent) {
2158 CloseHandle(ov.hEvent);
2159 ov.hEvent = NULL;
2161 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2162 return 0;
2164 fail:
2165 win_chr_close(chr);
2166 return -1;
2170 static CharDriverState *qemu_chr_open_pipe(const char *id,
2171 ChardevBackend *backend,
2172 ChardevReturn *ret,
2173 Error **errp)
2175 ChardevHostdev *opts = backend->pipe;
2176 const char *filename = opts->device;
2177 CharDriverState *chr;
2178 WinCharState *s;
2180 chr = qemu_chr_alloc();
2181 s = g_new0(WinCharState, 1);
2182 chr->opaque = s;
2183 chr->chr_write = win_chr_write;
2184 chr->chr_close = win_chr_close;
2186 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2187 g_free(s);
2188 g_free(chr);
2189 return NULL;
2191 return chr;
2194 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2196 CharDriverState *chr;
2197 WinCharState *s;
2199 chr = qemu_chr_alloc();
2200 s = g_new0(WinCharState, 1);
2201 s->hcom = fd_out;
2202 chr->opaque = s;
2203 chr->chr_write = win_chr_write;
2204 return chr;
2207 static CharDriverState *qemu_chr_open_win_con(const char *id,
2208 ChardevBackend *backend,
2209 ChardevReturn *ret,
2210 Error **errp)
2212 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2215 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2217 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2218 DWORD dwSize;
2219 int len1;
2221 len1 = len;
2223 while (len1 > 0) {
2224 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2225 break;
2227 buf += dwSize;
2228 len1 -= dwSize;
2231 return len - len1;
2234 static void win_stdio_wait_func(void *opaque)
2236 CharDriverState *chr = opaque;
2237 WinStdioCharState *stdio = chr->opaque;
2238 INPUT_RECORD buf[4];
2239 int ret;
2240 DWORD dwSize;
2241 int i;
2243 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2245 if (!ret) {
2246 /* Avoid error storm */
2247 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2248 return;
2251 for (i = 0; i < dwSize; i++) {
2252 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2254 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2255 int j;
2256 if (kev->uChar.AsciiChar != 0) {
2257 for (j = 0; j < kev->wRepeatCount; j++) {
2258 if (qemu_chr_be_can_write(chr)) {
2259 uint8_t c = kev->uChar.AsciiChar;
2260 qemu_chr_be_write(chr, &c, 1);
2268 static DWORD WINAPI win_stdio_thread(LPVOID param)
2270 CharDriverState *chr = param;
2271 WinStdioCharState *stdio = chr->opaque;
2272 int ret;
2273 DWORD dwSize;
2275 while (1) {
2277 /* Wait for one byte */
2278 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2280 /* Exit in case of error, continue if nothing read */
2281 if (!ret) {
2282 break;
2284 if (!dwSize) {
2285 continue;
2288 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2289 if (stdio->win_stdio_buf == '\r') {
2290 continue;
2293 /* Signal the main thread and wait until the byte was eaten */
2294 if (!SetEvent(stdio->hInputReadyEvent)) {
2295 break;
2297 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2298 != WAIT_OBJECT_0) {
2299 break;
2303 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2304 return 0;
2307 static void win_stdio_thread_wait_func(void *opaque)
2309 CharDriverState *chr = opaque;
2310 WinStdioCharState *stdio = chr->opaque;
2312 if (qemu_chr_be_can_write(chr)) {
2313 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2316 SetEvent(stdio->hInputDoneEvent);
2319 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2321 WinStdioCharState *stdio = chr->opaque;
2322 DWORD dwMode = 0;
2324 GetConsoleMode(stdio->hStdIn, &dwMode);
2326 if (echo) {
2327 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2328 } else {
2329 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2333 static void win_stdio_close(CharDriverState *chr)
2335 WinStdioCharState *stdio = chr->opaque;
2337 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2338 CloseHandle(stdio->hInputReadyEvent);
2340 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2341 CloseHandle(stdio->hInputDoneEvent);
2343 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2344 TerminateThread(stdio->hInputThread, 0);
2347 g_free(chr->opaque);
2348 g_free(chr);
2351 static CharDriverState *qemu_chr_open_stdio(const char *id,
2352 ChardevBackend *backend,
2353 ChardevReturn *ret,
2354 Error **errp)
2356 CharDriverState *chr;
2357 WinStdioCharState *stdio;
2358 DWORD dwMode;
2359 int is_console = 0;
2361 chr = qemu_chr_alloc();
2362 stdio = g_new0(WinStdioCharState, 1);
2364 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2365 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2366 error_setg(errp, "cannot open stdio: invalid handle");
2367 return NULL;
2370 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2372 chr->opaque = stdio;
2373 chr->chr_write = win_stdio_write;
2374 chr->chr_close = win_stdio_close;
2376 if (is_console) {
2377 if (qemu_add_wait_object(stdio->hStdIn,
2378 win_stdio_wait_func, chr)) {
2379 error_setg(errp, "qemu_add_wait_object: failed");
2380 goto err1;
2382 } else {
2383 DWORD dwId;
2385 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2386 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2387 if (stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2388 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2389 error_setg(errp, "cannot create event");
2390 goto err2;
2392 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2393 win_stdio_thread_wait_func, chr)) {
2394 error_setg(errp, "qemu_add_wait_object: failed");
2395 goto err2;
2397 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2398 chr, 0, &dwId);
2400 if (stdio->hInputThread == INVALID_HANDLE_VALUE) {
2401 error_setg(errp, "cannot create stdio thread");
2402 goto err3;
2406 dwMode |= ENABLE_LINE_INPUT;
2408 if (is_console) {
2409 /* set the terminal in raw mode */
2410 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2411 dwMode |= ENABLE_PROCESSED_INPUT;
2414 SetConsoleMode(stdio->hStdIn, dwMode);
2416 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2417 qemu_chr_fe_set_echo(chr, false);
2419 return chr;
2421 err3:
2422 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2423 err2:
2424 CloseHandle(stdio->hInputReadyEvent);
2425 CloseHandle(stdio->hInputDoneEvent);
2426 err1:
2427 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2428 return NULL;
2430 #endif /* !_WIN32 */
2433 /***********************************************************/
2434 /* UDP Net console */
2436 typedef struct {
2437 int fd;
2438 GIOChannel *chan;
2439 uint8_t buf[READ_BUF_LEN];
2440 int bufcnt;
2441 int bufptr;
2442 int max_size;
2443 } NetCharDriver;
2445 /* Called with chr_write_lock held. */
2446 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2448 NetCharDriver *s = chr->opaque;
2449 gsize bytes_written;
2450 GIOStatus status;
2452 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2453 if (status == G_IO_STATUS_EOF) {
2454 return 0;
2455 } else if (status != G_IO_STATUS_NORMAL) {
2456 return -1;
2459 return bytes_written;
2462 static int udp_chr_read_poll(void *opaque)
2464 CharDriverState *chr = opaque;
2465 NetCharDriver *s = chr->opaque;
2467 s->max_size = qemu_chr_be_can_write(chr);
2469 /* If there were any stray characters in the queue process them
2470 * first
2472 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2473 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2474 s->bufptr++;
2475 s->max_size = qemu_chr_be_can_write(chr);
2477 return s->max_size;
2480 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2482 CharDriverState *chr = opaque;
2483 NetCharDriver *s = chr->opaque;
2484 gsize bytes_read = 0;
2485 GIOStatus status;
2487 if (s->max_size == 0) {
2488 return TRUE;
2490 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2491 &bytes_read, NULL);
2492 s->bufcnt = bytes_read;
2493 s->bufptr = s->bufcnt;
2494 if (status != G_IO_STATUS_NORMAL) {
2495 remove_fd_in_watch(chr);
2496 return FALSE;
2499 s->bufptr = 0;
2500 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2501 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2502 s->bufptr++;
2503 s->max_size = qemu_chr_be_can_write(chr);
2506 return TRUE;
2509 static void udp_chr_update_read_handler(CharDriverState *chr)
2511 NetCharDriver *s = chr->opaque;
2513 remove_fd_in_watch(chr);
2514 if (s->chan) {
2515 chr->fd_in_tag = io_add_watch_poll(s->chan, udp_chr_read_poll,
2516 udp_chr_read, chr);
2520 static void udp_chr_close(CharDriverState *chr)
2522 NetCharDriver *s = chr->opaque;
2524 remove_fd_in_watch(chr);
2525 if (s->chan) {
2526 g_io_channel_unref(s->chan);
2527 closesocket(s->fd);
2529 g_free(s);
2530 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2533 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2535 CharDriverState *chr = NULL;
2536 NetCharDriver *s = NULL;
2538 chr = qemu_chr_alloc();
2539 s = g_new0(NetCharDriver, 1);
2541 s->fd = fd;
2542 s->chan = io_channel_from_socket(s->fd);
2543 s->bufcnt = 0;
2544 s->bufptr = 0;
2545 chr->opaque = s;
2546 chr->chr_write = udp_chr_write;
2547 chr->chr_update_read_handler = udp_chr_update_read_handler;
2548 chr->chr_close = udp_chr_close;
2549 /* be isn't opened until we get a connection */
2550 chr->explicit_be_open = true;
2551 return chr;
2554 /***********************************************************/
2555 /* TCP Net console */
2557 typedef struct {
2559 GIOChannel *chan, *listen_chan;
2560 guint listen_tag;
2561 int fd, listen_fd;
2562 int connected;
2563 int max_size;
2564 int do_telnetopt;
2565 int do_nodelay;
2566 int is_unix;
2567 int *read_msgfds;
2568 int read_msgfds_num;
2569 int *write_msgfds;
2570 int write_msgfds_num;
2572 SocketAddress *addr;
2573 bool is_listen;
2574 bool is_telnet;
2576 guint reconnect_timer;
2577 int64_t reconnect_time;
2578 bool connect_err_reported;
2579 } TCPCharDriver;
2581 static gboolean socket_reconnect_timeout(gpointer opaque);
2583 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2585 TCPCharDriver *s = chr->opaque;
2586 assert(s->connected == 0);
2587 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2588 socket_reconnect_timeout, chr);
2591 static void check_report_connect_error(CharDriverState *chr,
2592 Error *err)
2594 TCPCharDriver *s = chr->opaque;
2596 if (!s->connect_err_reported) {
2597 error_report("Unable to connect character device %s: %s",
2598 chr->label, error_get_pretty(err));
2599 s->connect_err_reported = true;
2601 qemu_chr_socket_restart_timer(chr);
2604 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2606 #ifndef _WIN32
2607 static int unix_send_msgfds(CharDriverState *chr, const uint8_t *buf, int len)
2609 TCPCharDriver *s = chr->opaque;
2610 struct msghdr msgh;
2611 struct iovec iov;
2612 int r;
2614 size_t fd_size = s->write_msgfds_num * sizeof(int);
2615 char control[CMSG_SPACE(fd_size)];
2616 struct cmsghdr *cmsg;
2618 memset(&msgh, 0, sizeof(msgh));
2619 memset(control, 0, sizeof(control));
2621 /* set the payload */
2622 iov.iov_base = (uint8_t *) buf;
2623 iov.iov_len = len;
2625 msgh.msg_iov = &iov;
2626 msgh.msg_iovlen = 1;
2628 msgh.msg_control = control;
2629 msgh.msg_controllen = sizeof(control);
2631 cmsg = CMSG_FIRSTHDR(&msgh);
2633 cmsg->cmsg_len = CMSG_LEN(fd_size);
2634 cmsg->cmsg_level = SOL_SOCKET;
2635 cmsg->cmsg_type = SCM_RIGHTS;
2636 memcpy(CMSG_DATA(cmsg), s->write_msgfds, fd_size);
2638 do {
2639 r = sendmsg(s->fd, &msgh, 0);
2640 } while (r < 0 && errno == EINTR);
2642 /* free the written msgfds, no matter what */
2643 if (s->write_msgfds_num) {
2644 g_free(s->write_msgfds);
2645 s->write_msgfds = 0;
2646 s->write_msgfds_num = 0;
2649 return r;
2651 #endif
2653 /* Called with chr_write_lock held. */
2654 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2656 TCPCharDriver *s = chr->opaque;
2657 if (s->connected) {
2658 #ifndef _WIN32
2659 if (s->is_unix && s->write_msgfds_num) {
2660 return unix_send_msgfds(chr, buf, len);
2661 } else
2662 #endif
2664 return io_channel_send(s->chan, buf, len);
2666 } else {
2667 /* XXX: indicate an error ? */
2668 return len;
2672 static int tcp_chr_read_poll(void *opaque)
2674 CharDriverState *chr = opaque;
2675 TCPCharDriver *s = chr->opaque;
2676 if (!s->connected)
2677 return 0;
2678 s->max_size = qemu_chr_be_can_write(chr);
2679 return s->max_size;
2682 #define IAC 255
2683 #define IAC_BREAK 243
2684 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2685 TCPCharDriver *s,
2686 uint8_t *buf, int *size)
2688 /* Handle any telnet client's basic IAC options to satisfy char by
2689 * char mode with no echo. All IAC options will be removed from
2690 * the buf and the do_telnetopt variable will be used to track the
2691 * state of the width of the IAC information.
2693 * IAC commands come in sets of 3 bytes with the exception of the
2694 * "IAC BREAK" command and the double IAC.
2697 int i;
2698 int j = 0;
2700 for (i = 0; i < *size; i++) {
2701 if (s->do_telnetopt > 1) {
2702 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2703 /* Double IAC means send an IAC */
2704 if (j != i)
2705 buf[j] = buf[i];
2706 j++;
2707 s->do_telnetopt = 1;
2708 } else {
2709 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2710 /* Handle IAC break commands by sending a serial break */
2711 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2712 s->do_telnetopt++;
2714 s->do_telnetopt++;
2716 if (s->do_telnetopt >= 4) {
2717 s->do_telnetopt = 1;
2719 } else {
2720 if ((unsigned char)buf[i] == IAC) {
2721 s->do_telnetopt = 2;
2722 } else {
2723 if (j != i)
2724 buf[j] = buf[i];
2725 j++;
2729 *size = j;
2732 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2734 TCPCharDriver *s = chr->opaque;
2735 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2737 assert(num <= TCP_MAX_FDS);
2739 if (to_copy) {
2740 int i;
2742 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2744 /* Close unused fds */
2745 for (i = to_copy; i < s->read_msgfds_num; i++) {
2746 close(s->read_msgfds[i]);
2749 g_free(s->read_msgfds);
2750 s->read_msgfds = 0;
2751 s->read_msgfds_num = 0;
2754 return to_copy;
2757 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2759 TCPCharDriver *s = chr->opaque;
2761 /* clear old pending fd array */
2762 g_free(s->write_msgfds);
2764 if (num) {
2765 s->write_msgfds = g_new(int, num);
2766 memcpy(s->write_msgfds, fds, num * sizeof(int));
2769 s->write_msgfds_num = num;
2771 return 0;
2774 #ifndef _WIN32
2775 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2777 TCPCharDriver *s = chr->opaque;
2778 struct cmsghdr *cmsg;
2780 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2781 int fd_size, i;
2783 if (cmsg->cmsg_len < CMSG_LEN(sizeof(int)) ||
2784 cmsg->cmsg_level != SOL_SOCKET ||
2785 cmsg->cmsg_type != SCM_RIGHTS) {
2786 continue;
2789 fd_size = cmsg->cmsg_len - CMSG_LEN(0);
2791 if (!fd_size) {
2792 continue;
2795 /* close and clean read_msgfds */
2796 for (i = 0; i < s->read_msgfds_num; i++) {
2797 close(s->read_msgfds[i]);
2800 if (s->read_msgfds_num) {
2801 g_free(s->read_msgfds);
2804 s->read_msgfds_num = fd_size / sizeof(int);
2805 s->read_msgfds = g_malloc(fd_size);
2806 memcpy(s->read_msgfds, CMSG_DATA(cmsg), fd_size);
2808 for (i = 0; i < s->read_msgfds_num; i++) {
2809 int fd = s->read_msgfds[i];
2810 if (fd < 0) {
2811 continue;
2814 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2815 qemu_set_block(fd);
2817 #ifndef MSG_CMSG_CLOEXEC
2818 qemu_set_cloexec(fd);
2819 #endif
2824 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2826 TCPCharDriver *s = chr->opaque;
2827 struct msghdr msg = { NULL, };
2828 struct iovec iov[1];
2829 union {
2830 struct cmsghdr cmsg;
2831 char control[CMSG_SPACE(sizeof(int) * TCP_MAX_FDS)];
2832 } msg_control;
2833 int flags = 0;
2834 ssize_t ret;
2836 iov[0].iov_base = buf;
2837 iov[0].iov_len = len;
2839 msg.msg_iov = iov;
2840 msg.msg_iovlen = 1;
2841 msg.msg_control = &msg_control;
2842 msg.msg_controllen = sizeof(msg_control);
2844 #ifdef MSG_CMSG_CLOEXEC
2845 flags |= MSG_CMSG_CLOEXEC;
2846 #endif
2847 do {
2848 ret = recvmsg(s->fd, &msg, flags);
2849 } while (ret == -1 && errno == EINTR);
2851 if (ret > 0 && s->is_unix) {
2852 unix_process_msgfd(chr, &msg);
2855 return ret;
2857 #else
2858 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2860 TCPCharDriver *s = chr->opaque;
2861 ssize_t ret;
2863 do {
2864 ret = qemu_recv(s->fd, buf, len, 0);
2865 } while (ret == -1 && socket_error() == EINTR);
2867 return ret;
2869 #endif
2871 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2873 TCPCharDriver *s = chr->opaque;
2874 return g_io_create_watch(s->chan, cond);
2877 static void tcp_chr_disconnect(CharDriverState *chr)
2879 TCPCharDriver *s = chr->opaque;
2881 s->connected = 0;
2882 if (s->listen_chan) {
2883 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
2884 tcp_chr_accept, chr);
2886 remove_fd_in_watch(chr);
2887 g_io_channel_unref(s->chan);
2888 s->chan = NULL;
2889 closesocket(s->fd);
2890 s->fd = -1;
2891 SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
2892 "disconnected:", s->addr, s->is_listen, s->is_telnet);
2893 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2894 if (s->reconnect_time) {
2895 qemu_chr_socket_restart_timer(chr);
2899 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2901 CharDriverState *chr = opaque;
2902 TCPCharDriver *s = chr->opaque;
2903 uint8_t buf[READ_BUF_LEN];
2904 int len, size;
2906 if (!s->connected || s->max_size <= 0) {
2907 return TRUE;
2909 len = sizeof(buf);
2910 if (len > s->max_size)
2911 len = s->max_size;
2912 size = tcp_chr_recv(chr, (void *)buf, len);
2913 if (size == 0 ||
2914 (size < 0 &&
2915 socket_error() != EAGAIN && socket_error() != EWOULDBLOCK)) {
2916 /* connection closed */
2917 tcp_chr_disconnect(chr);
2918 } else if (size > 0) {
2919 if (s->do_telnetopt)
2920 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2921 if (size > 0)
2922 qemu_chr_be_write(chr, buf, size);
2925 return TRUE;
2928 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2930 TCPCharDriver *s = chr->opaque;
2931 int size;
2933 if (!s->connected) {
2934 return 0;
2937 size = tcp_chr_recv(chr, (void *) buf, len);
2938 if (size == 0) {
2939 /* connection closed */
2940 tcp_chr_disconnect(chr);
2943 return size;
2946 #ifndef _WIN32
2947 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2949 CharDriverState *chr = qemu_chr_open_fd(eventfd, eventfd);
2951 if (chr) {
2952 chr->avail_connections = 1;
2955 return chr;
2957 #endif
2959 static void tcp_chr_connect(void *opaque)
2961 CharDriverState *chr = opaque;
2962 TCPCharDriver *s = chr->opaque;
2963 struct sockaddr_storage ss, ps;
2964 socklen_t ss_len = sizeof(ss), ps_len = sizeof(ps);
2966 memset(&ss, 0, ss_len);
2967 if (getsockname(s->fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2968 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
2969 "Error in getsockname: %s\n", strerror(errno));
2970 } else if (getpeername(s->fd, (struct sockaddr *) &ps, &ps_len) != 0) {
2971 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
2972 "Error in getpeername: %s\n", strerror(errno));
2973 } else {
2974 sockaddr_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
2975 &ss, ss_len, &ps, ps_len,
2976 s->is_listen, s->is_telnet);
2979 s->connected = 1;
2980 if (s->chan) {
2981 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2982 tcp_chr_read, chr);
2984 qemu_chr_be_generic_open(chr);
2987 static void tcp_chr_update_read_handler(CharDriverState *chr)
2989 TCPCharDriver *s = chr->opaque;
2991 remove_fd_in_watch(chr);
2992 if (s->chan) {
2993 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2994 tcp_chr_read, chr);
2998 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2999 static void tcp_chr_telnet_init(int fd)
3001 char buf[3];
3002 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3003 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3004 send(fd, (char *)buf, 3, 0);
3005 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3006 send(fd, (char *)buf, 3, 0);
3007 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3008 send(fd, (char *)buf, 3, 0);
3009 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3010 send(fd, (char *)buf, 3, 0);
3013 static int tcp_chr_add_client(CharDriverState *chr, int fd)
3015 TCPCharDriver *s = chr->opaque;
3016 if (s->fd != -1)
3017 return -1;
3019 qemu_set_nonblock(fd);
3020 if (s->do_nodelay)
3021 socket_set_nodelay(fd);
3022 s->fd = fd;
3023 s->chan = io_channel_from_socket(fd);
3024 if (s->listen_tag) {
3025 g_source_remove(s->listen_tag);
3026 s->listen_tag = 0;
3028 tcp_chr_connect(chr);
3030 return 0;
3033 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
3035 CharDriverState *chr = opaque;
3036 TCPCharDriver *s = chr->opaque;
3037 struct sockaddr_in saddr;
3038 #ifndef _WIN32
3039 struct sockaddr_un uaddr;
3040 #endif
3041 struct sockaddr *addr;
3042 socklen_t len;
3043 int fd;
3045 for(;;) {
3046 #ifndef _WIN32
3047 if (s->is_unix) {
3048 len = sizeof(uaddr);
3049 addr = (struct sockaddr *)&uaddr;
3050 } else
3051 #endif
3053 len = sizeof(saddr);
3054 addr = (struct sockaddr *)&saddr;
3056 fd = qemu_accept(s->listen_fd, addr, &len);
3057 if (fd < 0 && errno != EINTR) {
3058 s->listen_tag = 0;
3059 return FALSE;
3060 } else if (fd >= 0) {
3061 if (s->do_telnetopt)
3062 tcp_chr_telnet_init(fd);
3063 break;
3066 if (tcp_chr_add_client(chr, fd) < 0)
3067 close(fd);
3069 return TRUE;
3072 static void tcp_chr_close(CharDriverState *chr)
3074 TCPCharDriver *s = chr->opaque;
3075 int i;
3077 if (s->reconnect_timer) {
3078 g_source_remove(s->reconnect_timer);
3079 s->reconnect_timer = 0;
3081 qapi_free_SocketAddress(s->addr);
3082 if (s->fd >= 0) {
3083 remove_fd_in_watch(chr);
3084 if (s->chan) {
3085 g_io_channel_unref(s->chan);
3087 closesocket(s->fd);
3089 if (s->listen_fd >= 0) {
3090 if (s->listen_tag) {
3091 g_source_remove(s->listen_tag);
3092 s->listen_tag = 0;
3094 if (s->listen_chan) {
3095 g_io_channel_unref(s->listen_chan);
3097 closesocket(s->listen_fd);
3099 if (s->read_msgfds_num) {
3100 for (i = 0; i < s->read_msgfds_num; i++) {
3101 close(s->read_msgfds[i]);
3103 g_free(s->read_msgfds);
3105 if (s->write_msgfds_num) {
3106 g_free(s->write_msgfds);
3108 g_free(s);
3109 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3112 static void qemu_chr_finish_socket_connection(CharDriverState *chr, int fd)
3114 TCPCharDriver *s = chr->opaque;
3116 if (s->is_listen) {
3117 s->listen_fd = fd;
3118 s->listen_chan = io_channel_from_socket(s->listen_fd);
3119 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
3120 tcp_chr_accept, chr);
3121 } else {
3122 s->connected = 1;
3123 s->fd = fd;
3124 socket_set_nodelay(fd);
3125 s->chan = io_channel_from_socket(s->fd);
3126 tcp_chr_connect(chr);
3130 static void qemu_chr_socket_connected(int fd, Error *err, void *opaque)
3132 CharDriverState *chr = opaque;
3133 TCPCharDriver *s = chr->opaque;
3135 if (fd < 0) {
3136 check_report_connect_error(chr, err);
3137 return;
3140 s->connect_err_reported = false;
3141 qemu_chr_finish_socket_connection(chr, fd);
3144 static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp)
3146 TCPCharDriver *s = chr->opaque;
3147 int fd;
3149 if (s->is_listen) {
3150 fd = socket_listen(s->addr, errp);
3151 } else if (s->reconnect_time) {
3152 fd = socket_connect(s->addr, errp, qemu_chr_socket_connected, chr);
3153 return fd >= 0;
3154 } else {
3155 fd = socket_connect(s->addr, errp, NULL, NULL);
3157 if (fd < 0) {
3158 return false;
3161 qemu_chr_finish_socket_connection(chr, fd);
3162 return true;
3165 /*********************************************************/
3166 /* Ring buffer chardev */
3168 typedef struct {
3169 size_t size;
3170 size_t prod;
3171 size_t cons;
3172 uint8_t *cbuf;
3173 } RingBufCharDriver;
3175 static size_t ringbuf_count(const CharDriverState *chr)
3177 const RingBufCharDriver *d = chr->opaque;
3179 return d->prod - d->cons;
3182 /* Called with chr_write_lock held. */
3183 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3185 RingBufCharDriver *d = chr->opaque;
3186 int i;
3188 if (!buf || (len < 0)) {
3189 return -1;
3192 for (i = 0; i < len; i++ ) {
3193 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3194 if (d->prod - d->cons > d->size) {
3195 d->cons = d->prod - d->size;
3199 return 0;
3202 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3204 RingBufCharDriver *d = chr->opaque;
3205 int i;
3207 qemu_mutex_lock(&chr->chr_write_lock);
3208 for (i = 0; i < len && d->cons != d->prod; i++) {
3209 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3211 qemu_mutex_unlock(&chr->chr_write_lock);
3213 return i;
3216 static void ringbuf_chr_close(struct CharDriverState *chr)
3218 RingBufCharDriver *d = chr->opaque;
3220 g_free(d->cbuf);
3221 g_free(d);
3222 chr->opaque = NULL;
3225 static CharDriverState *qemu_chr_open_ringbuf(const char *id,
3226 ChardevBackend *backend,
3227 ChardevReturn *ret,
3228 Error **errp)
3230 ChardevRingbuf *opts = backend->ringbuf;
3231 CharDriverState *chr;
3232 RingBufCharDriver *d;
3234 chr = qemu_chr_alloc();
3235 d = g_malloc(sizeof(*d));
3237 d->size = opts->has_size ? opts->size : 65536;
3239 /* The size must be power of 2 */
3240 if (d->size & (d->size - 1)) {
3241 error_setg(errp, "size of ringbuf chardev must be power of two");
3242 goto fail;
3245 d->prod = 0;
3246 d->cons = 0;
3247 d->cbuf = g_malloc0(d->size);
3249 chr->opaque = d;
3250 chr->chr_write = ringbuf_chr_write;
3251 chr->chr_close = ringbuf_chr_close;
3253 return chr;
3255 fail:
3256 g_free(d);
3257 g_free(chr);
3258 return NULL;
3261 bool chr_is_ringbuf(const CharDriverState *chr)
3263 return chr->chr_write == ringbuf_chr_write;
3266 void qmp_ringbuf_write(const char *device, const char *data,
3267 bool has_format, enum DataFormat format,
3268 Error **errp)
3270 CharDriverState *chr;
3271 const uint8_t *write_data;
3272 int ret;
3273 gsize write_count;
3275 chr = qemu_chr_find(device);
3276 if (!chr) {
3277 error_setg(errp, "Device '%s' not found", device);
3278 return;
3281 if (!chr_is_ringbuf(chr)) {
3282 error_setg(errp,"%s is not a ringbuf device", device);
3283 return;
3286 if (has_format && (format == DATA_FORMAT_BASE64)) {
3287 write_data = g_base64_decode(data, &write_count);
3288 } else {
3289 write_data = (uint8_t *)data;
3290 write_count = strlen(data);
3293 ret = ringbuf_chr_write(chr, write_data, write_count);
3295 if (write_data != (uint8_t *)data) {
3296 g_free((void *)write_data);
3299 if (ret < 0) {
3300 error_setg(errp, "Failed to write to device %s", device);
3301 return;
3305 char *qmp_ringbuf_read(const char *device, int64_t size,
3306 bool has_format, enum DataFormat format,
3307 Error **errp)
3309 CharDriverState *chr;
3310 uint8_t *read_data;
3311 size_t count;
3312 char *data;
3314 chr = qemu_chr_find(device);
3315 if (!chr) {
3316 error_setg(errp, "Device '%s' not found", device);
3317 return NULL;
3320 if (!chr_is_ringbuf(chr)) {
3321 error_setg(errp,"%s is not a ringbuf device", device);
3322 return NULL;
3325 if (size <= 0) {
3326 error_setg(errp, "size must be greater than zero");
3327 return NULL;
3330 count = ringbuf_count(chr);
3331 size = size > count ? count : size;
3332 read_data = g_malloc(size + 1);
3334 ringbuf_chr_read(chr, read_data, size);
3336 if (has_format && (format == DATA_FORMAT_BASE64)) {
3337 data = g_base64_encode(read_data, size);
3338 g_free(read_data);
3339 } else {
3341 * FIXME should read only complete, valid UTF-8 characters up
3342 * to @size bytes. Invalid sequences should be replaced by a
3343 * suitable replacement character. Except when (and only
3344 * when) ring buffer lost characters since last read, initial
3345 * continuation characters should be dropped.
3347 read_data[size] = 0;
3348 data = (char *)read_data;
3351 return data;
3354 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3356 char host[65], port[33], width[8], height[8];
3357 int pos;
3358 const char *p;
3359 QemuOpts *opts;
3360 Error *local_err = NULL;
3362 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3363 if (local_err) {
3364 error_report_err(local_err);
3365 return NULL;
3368 if (strstart(filename, "mon:", &p)) {
3369 filename = p;
3370 qemu_opt_set(opts, "mux", "on", &error_abort);
3371 if (strcmp(filename, "stdio") == 0) {
3372 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3373 * but pass it to the guest. Handle this only for compat syntax,
3374 * for -chardev syntax we have special option for this.
3375 * This is what -nographic did, redirecting+muxing serial+monitor
3376 * to stdio causing Ctrl+C to be passed to guest. */
3377 qemu_opt_set(opts, "signal", "off", &error_abort);
3381 if (strcmp(filename, "null") == 0 ||
3382 strcmp(filename, "pty") == 0 ||
3383 strcmp(filename, "msmouse") == 0 ||
3384 strcmp(filename, "braille") == 0 ||
3385 strcmp(filename, "testdev") == 0 ||
3386 strcmp(filename, "stdio") == 0) {
3387 qemu_opt_set(opts, "backend", filename, &error_abort);
3388 return opts;
3390 if (strstart(filename, "vc", &p)) {
3391 qemu_opt_set(opts, "backend", "vc", &error_abort);
3392 if (*p == ':') {
3393 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3394 /* pixels */
3395 qemu_opt_set(opts, "width", width, &error_abort);
3396 qemu_opt_set(opts, "height", height, &error_abort);
3397 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3398 /* chars */
3399 qemu_opt_set(opts, "cols", width, &error_abort);
3400 qemu_opt_set(opts, "rows", height, &error_abort);
3401 } else {
3402 goto fail;
3405 return opts;
3407 if (strcmp(filename, "con:") == 0) {
3408 qemu_opt_set(opts, "backend", "console", &error_abort);
3409 return opts;
3411 if (strstart(filename, "COM", NULL)) {
3412 qemu_opt_set(opts, "backend", "serial", &error_abort);
3413 qemu_opt_set(opts, "path", filename, &error_abort);
3414 return opts;
3416 if (strstart(filename, "file:", &p)) {
3417 qemu_opt_set(opts, "backend", "file", &error_abort);
3418 qemu_opt_set(opts, "path", p, &error_abort);
3419 return opts;
3421 if (strstart(filename, "pipe:", &p)) {
3422 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3423 qemu_opt_set(opts, "path", p, &error_abort);
3424 return opts;
3426 if (strstart(filename, "tcp:", &p) ||
3427 strstart(filename, "telnet:", &p)) {
3428 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3429 host[0] = 0;
3430 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3431 goto fail;
3433 qemu_opt_set(opts, "backend", "socket", &error_abort);
3434 qemu_opt_set(opts, "host", host, &error_abort);
3435 qemu_opt_set(opts, "port", port, &error_abort);
3436 if (p[pos] == ',') {
3437 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3438 if (local_err) {
3439 error_report_err(local_err);
3440 goto fail;
3443 if (strstart(filename, "telnet:", &p))
3444 qemu_opt_set(opts, "telnet", "on", &error_abort);
3445 return opts;
3447 if (strstart(filename, "udp:", &p)) {
3448 qemu_opt_set(opts, "backend", "udp", &error_abort);
3449 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3450 host[0] = 0;
3451 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3452 goto fail;
3455 qemu_opt_set(opts, "host", host, &error_abort);
3456 qemu_opt_set(opts, "port", port, &error_abort);
3457 if (p[pos] == '@') {
3458 p += pos + 1;
3459 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3460 host[0] = 0;
3461 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3462 goto fail;
3465 qemu_opt_set(opts, "localaddr", host, &error_abort);
3466 qemu_opt_set(opts, "localport", port, &error_abort);
3468 return opts;
3470 if (strstart(filename, "unix:", &p)) {
3471 qemu_opt_set(opts, "backend", "socket", &error_abort);
3472 qemu_opts_do_parse(opts, p, "path", &local_err);
3473 if (local_err) {
3474 error_report_err(local_err);
3475 goto fail;
3477 return opts;
3479 if (strstart(filename, "/dev/parport", NULL) ||
3480 strstart(filename, "/dev/ppi", NULL)) {
3481 qemu_opt_set(opts, "backend", "parport", &error_abort);
3482 qemu_opt_set(opts, "path", filename, &error_abort);
3483 return opts;
3485 if (strstart(filename, "/dev/", NULL)) {
3486 qemu_opt_set(opts, "backend", "tty", &error_abort);
3487 qemu_opt_set(opts, "path", filename, &error_abort);
3488 return opts;
3491 fail:
3492 qemu_opts_del(opts);
3493 return NULL;
3496 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3497 Error **errp)
3499 const char *path = qemu_opt_get(opts, "path");
3501 if (path == NULL) {
3502 error_setg(errp, "chardev: file: no filename given");
3503 return;
3505 backend->file = g_new0(ChardevFile, 1);
3506 backend->file->out = g_strdup(path);
3509 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3510 Error **errp)
3512 backend->stdio = g_new0(ChardevStdio, 1);
3513 backend->stdio->has_signal = true;
3514 backend->stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3517 #ifdef HAVE_CHARDEV_SERIAL
3518 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3519 Error **errp)
3521 const char *device = qemu_opt_get(opts, "path");
3523 if (device == NULL) {
3524 error_setg(errp, "chardev: serial/tty: no device path given");
3525 return;
3527 backend->serial = g_new0(ChardevHostdev, 1);
3528 backend->serial->device = g_strdup(device);
3530 #endif
3532 #ifdef HAVE_CHARDEV_PARPORT
3533 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3534 Error **errp)
3536 const char *device = qemu_opt_get(opts, "path");
3538 if (device == NULL) {
3539 error_setg(errp, "chardev: parallel: no device path given");
3540 return;
3542 backend->parallel = g_new0(ChardevHostdev, 1);
3543 backend->parallel->device = g_strdup(device);
3545 #endif
3547 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3548 Error **errp)
3550 const char *device = qemu_opt_get(opts, "path");
3552 if (device == NULL) {
3553 error_setg(errp, "chardev: pipe: no device path given");
3554 return;
3556 backend->pipe = g_new0(ChardevHostdev, 1);
3557 backend->pipe->device = g_strdup(device);
3560 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3561 Error **errp)
3563 int val;
3565 backend->ringbuf = g_new0(ChardevRingbuf, 1);
3567 val = qemu_opt_get_size(opts, "size", 0);
3568 if (val != 0) {
3569 backend->ringbuf->has_size = true;
3570 backend->ringbuf->size = val;
3574 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3575 Error **errp)
3577 const char *chardev = qemu_opt_get(opts, "chardev");
3579 if (chardev == NULL) {
3580 error_setg(errp, "chardev: mux: no chardev given");
3581 return;
3583 backend->mux = g_new0(ChardevMux, 1);
3584 backend->mux->chardev = g_strdup(chardev);
3587 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3588 Error **errp)
3590 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3591 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3592 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3593 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3594 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3595 const char *path = qemu_opt_get(opts, "path");
3596 const char *host = qemu_opt_get(opts, "host");
3597 const char *port = qemu_opt_get(opts, "port");
3598 SocketAddress *addr;
3600 if (!path) {
3601 if (!host) {
3602 error_setg(errp, "chardev: socket: no host given");
3603 return;
3605 if (!port) {
3606 error_setg(errp, "chardev: socket: no port given");
3607 return;
3611 backend->socket = g_new0(ChardevSocket, 1);
3613 backend->socket->has_nodelay = true;
3614 backend->socket->nodelay = do_nodelay;
3615 backend->socket->has_server = true;
3616 backend->socket->server = is_listen;
3617 backend->socket->has_telnet = true;
3618 backend->socket->telnet = is_telnet;
3619 backend->socket->has_wait = true;
3620 backend->socket->wait = is_waitconnect;
3621 backend->socket->has_reconnect = true;
3622 backend->socket->reconnect = reconnect;
3624 addr = g_new0(SocketAddress, 1);
3625 if (path) {
3626 addr->kind = SOCKET_ADDRESS_KIND_UNIX;
3627 addr->q_unix = g_new0(UnixSocketAddress, 1);
3628 addr->q_unix->path = g_strdup(path);
3629 } else {
3630 addr->kind = SOCKET_ADDRESS_KIND_INET;
3631 addr->inet = g_new0(InetSocketAddress, 1);
3632 addr->inet->host = g_strdup(host);
3633 addr->inet->port = g_strdup(port);
3634 addr->inet->has_to = qemu_opt_get(opts, "to");
3635 addr->inet->to = qemu_opt_get_number(opts, "to", 0);
3636 addr->inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3637 addr->inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3638 addr->inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3639 addr->inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3641 backend->socket->addr = addr;
3644 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3645 Error **errp)
3647 const char *host = qemu_opt_get(opts, "host");
3648 const char *port = qemu_opt_get(opts, "port");
3649 const char *localaddr = qemu_opt_get(opts, "localaddr");
3650 const char *localport = qemu_opt_get(opts, "localport");
3651 bool has_local = false;
3652 SocketAddress *addr;
3654 if (host == NULL || strlen(host) == 0) {
3655 host = "localhost";
3657 if (port == NULL || strlen(port) == 0) {
3658 error_setg(errp, "chardev: udp: remote port not specified");
3659 return;
3661 if (localport == NULL || strlen(localport) == 0) {
3662 localport = "0";
3663 } else {
3664 has_local = true;
3666 if (localaddr == NULL || strlen(localaddr) == 0) {
3667 localaddr = "";
3668 } else {
3669 has_local = true;
3672 backend->udp = g_new0(ChardevUdp, 1);
3674 addr = g_new0(SocketAddress, 1);
3675 addr->kind = SOCKET_ADDRESS_KIND_INET;
3676 addr->inet = g_new0(InetSocketAddress, 1);
3677 addr->inet->host = g_strdup(host);
3678 addr->inet->port = g_strdup(port);
3679 addr->inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3680 addr->inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3681 addr->inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3682 addr->inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3683 backend->udp->remote = addr;
3685 if (has_local) {
3686 backend->udp->has_local = true;
3687 addr = g_new0(SocketAddress, 1);
3688 addr->kind = SOCKET_ADDRESS_KIND_INET;
3689 addr->inet = g_new0(InetSocketAddress, 1);
3690 addr->inet->host = g_strdup(localaddr);
3691 addr->inet->port = g_strdup(localport);
3692 backend->udp->local = addr;
3696 typedef struct CharDriver {
3697 const char *name;
3698 ChardevBackendKind kind;
3699 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3700 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3701 ChardevReturn *ret, Error **errp);
3702 } CharDriver;
3704 static GSList *backends;
3706 void register_char_driver(const char *name, ChardevBackendKind kind,
3707 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3708 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3709 ChardevReturn *ret, Error **errp))
3711 CharDriver *s;
3713 s = g_malloc0(sizeof(*s));
3714 s->name = g_strdup(name);
3715 s->kind = kind;
3716 s->parse = parse;
3717 s->create = create;
3719 backends = g_slist_append(backends, s);
3722 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3723 void (*init)(struct CharDriverState *s),
3724 Error **errp)
3726 Error *local_err = NULL;
3727 CharDriver *cd;
3728 CharDriverState *chr;
3729 GSList *i;
3730 ChardevReturn *ret = NULL;
3731 ChardevBackend *backend;
3732 const char *id = qemu_opts_id(opts);
3733 char *bid = NULL;
3735 if (id == NULL) {
3736 error_setg(errp, "chardev: no id specified");
3737 goto err;
3740 if (qemu_opt_get(opts, "backend") == NULL) {
3741 error_setg(errp, "chardev: \"%s\" missing backend",
3742 qemu_opts_id(opts));
3743 goto err;
3745 for (i = backends; i; i = i->next) {
3746 cd = i->data;
3748 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3749 break;
3752 if (i == NULL) {
3753 error_setg(errp, "chardev: backend \"%s\" not found",
3754 qemu_opt_get(opts, "backend"));
3755 goto err;
3758 backend = g_new0(ChardevBackend, 1);
3760 if (qemu_opt_get_bool(opts, "mux", 0)) {
3761 bid = g_strdup_printf("%s-base", id);
3764 chr = NULL;
3765 backend->kind = cd->kind;
3766 if (cd->parse) {
3767 cd->parse(opts, backend, &local_err);
3768 if (local_err) {
3769 error_propagate(errp, local_err);
3770 goto qapi_out;
3773 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3774 if (!ret) {
3775 goto qapi_out;
3778 if (bid) {
3779 qapi_free_ChardevBackend(backend);
3780 qapi_free_ChardevReturn(ret);
3781 backend = g_new0(ChardevBackend, 1);
3782 backend->mux = g_new0(ChardevMux, 1);
3783 backend->kind = CHARDEV_BACKEND_KIND_MUX;
3784 backend->mux->chardev = g_strdup(bid);
3785 ret = qmp_chardev_add(id, backend, errp);
3786 if (!ret) {
3787 chr = qemu_chr_find(bid);
3788 qemu_chr_delete(chr);
3789 chr = NULL;
3790 goto qapi_out;
3794 chr = qemu_chr_find(id);
3795 chr->opts = opts;
3797 qapi_out:
3798 qapi_free_ChardevBackend(backend);
3799 qapi_free_ChardevReturn(ret);
3800 g_free(bid);
3801 return chr;
3803 err:
3804 qemu_opts_del(opts);
3805 return NULL;
3808 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3810 const char *p;
3811 CharDriverState *chr;
3812 QemuOpts *opts;
3813 Error *err = NULL;
3815 if (strstart(filename, "chardev:", &p)) {
3816 return qemu_chr_find(p);
3819 opts = qemu_chr_parse_compat(label, filename);
3820 if (!opts)
3821 return NULL;
3823 chr = qemu_chr_new_from_opts(opts, init, &err);
3824 if (err) {
3825 error_report_err(err);
3827 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3828 qemu_chr_fe_claim_no_fail(chr);
3829 monitor_init(chr, MONITOR_USE_READLINE);
3831 return chr;
3834 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3836 if (chr->chr_set_echo) {
3837 chr->chr_set_echo(chr, echo);
3841 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3843 if (chr->fe_open == fe_open) {
3844 return;
3846 chr->fe_open = fe_open;
3847 if (chr->chr_set_fe_open) {
3848 chr->chr_set_fe_open(chr, fe_open);
3852 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3854 if (chr->chr_fe_event) {
3855 chr->chr_fe_event(chr, event);
3859 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3860 GIOFunc func, void *user_data)
3862 GSource *src;
3863 guint tag;
3865 if (s->chr_add_watch == NULL) {
3866 return -ENOSYS;
3869 src = s->chr_add_watch(s, cond);
3870 if (!src) {
3871 return -EINVAL;
3874 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3875 tag = g_source_attach(src, NULL);
3876 g_source_unref(src);
3878 return tag;
3881 int qemu_chr_fe_claim(CharDriverState *s)
3883 if (s->avail_connections < 1) {
3884 return -1;
3886 s->avail_connections--;
3887 return 0;
3890 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3892 if (qemu_chr_fe_claim(s) != 0) {
3893 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3894 __func__, s->label);
3895 exit(1);
3899 void qemu_chr_fe_release(CharDriverState *s)
3901 s->avail_connections++;
3904 void qemu_chr_delete(CharDriverState *chr)
3906 QTAILQ_REMOVE(&chardevs, chr, next);
3907 if (chr->chr_close) {
3908 chr->chr_close(chr);
3910 g_free(chr->filename);
3911 g_free(chr->label);
3912 qemu_opts_del(chr->opts);
3913 g_free(chr);
3916 ChardevInfoList *qmp_query_chardev(Error **errp)
3918 ChardevInfoList *chr_list = NULL;
3919 CharDriverState *chr;
3921 QTAILQ_FOREACH(chr, &chardevs, next) {
3922 ChardevInfoList *info = g_malloc0(sizeof(*info));
3923 info->value = g_malloc0(sizeof(*info->value));
3924 info->value->label = g_strdup(chr->label);
3925 info->value->filename = g_strdup(chr->filename);
3926 info->value->frontend_open = chr->fe_open;
3928 info->next = chr_list;
3929 chr_list = info;
3932 return chr_list;
3935 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
3937 ChardevBackendInfoList *backend_list = NULL;
3938 CharDriver *c = NULL;
3939 GSList *i = NULL;
3941 for (i = backends; i; i = i->next) {
3942 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
3943 c = i->data;
3944 info->value = g_malloc0(sizeof(*info->value));
3945 info->value->name = g_strdup(c->name);
3947 info->next = backend_list;
3948 backend_list = info;
3951 return backend_list;
3954 CharDriverState *qemu_chr_find(const char *name)
3956 CharDriverState *chr;
3958 QTAILQ_FOREACH(chr, &chardevs, next) {
3959 if (strcmp(chr->label, name) != 0)
3960 continue;
3961 return chr;
3963 return NULL;
3966 /* Get a character (serial) device interface. */
3967 CharDriverState *qemu_char_get_next_serial(void)
3969 static int next_serial;
3970 CharDriverState *chr;
3972 /* FIXME: This function needs to go away: use chardev properties! */
3974 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3975 chr = serial_hds[next_serial++];
3976 qemu_chr_fe_claim_no_fail(chr);
3977 return chr;
3979 return NULL;
3982 QemuOptsList qemu_chardev_opts = {
3983 .name = "chardev",
3984 .implied_opt_name = "backend",
3985 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3986 .desc = {
3988 .name = "backend",
3989 .type = QEMU_OPT_STRING,
3991 .name = "path",
3992 .type = QEMU_OPT_STRING,
3994 .name = "host",
3995 .type = QEMU_OPT_STRING,
3997 .name = "port",
3998 .type = QEMU_OPT_STRING,
4000 .name = "localaddr",
4001 .type = QEMU_OPT_STRING,
4003 .name = "localport",
4004 .type = QEMU_OPT_STRING,
4006 .name = "to",
4007 .type = QEMU_OPT_NUMBER,
4009 .name = "ipv4",
4010 .type = QEMU_OPT_BOOL,
4012 .name = "ipv6",
4013 .type = QEMU_OPT_BOOL,
4015 .name = "wait",
4016 .type = QEMU_OPT_BOOL,
4018 .name = "server",
4019 .type = QEMU_OPT_BOOL,
4021 .name = "delay",
4022 .type = QEMU_OPT_BOOL,
4024 .name = "reconnect",
4025 .type = QEMU_OPT_NUMBER,
4027 .name = "telnet",
4028 .type = QEMU_OPT_BOOL,
4030 .name = "width",
4031 .type = QEMU_OPT_NUMBER,
4033 .name = "height",
4034 .type = QEMU_OPT_NUMBER,
4036 .name = "cols",
4037 .type = QEMU_OPT_NUMBER,
4039 .name = "rows",
4040 .type = QEMU_OPT_NUMBER,
4042 .name = "mux",
4043 .type = QEMU_OPT_BOOL,
4045 .name = "signal",
4046 .type = QEMU_OPT_BOOL,
4048 .name = "name",
4049 .type = QEMU_OPT_STRING,
4051 .name = "debug",
4052 .type = QEMU_OPT_NUMBER,
4054 .name = "size",
4055 .type = QEMU_OPT_SIZE,
4057 .name = "chardev",
4058 .type = QEMU_OPT_STRING,
4060 { /* end of list */ }
4064 #ifdef _WIN32
4066 static CharDriverState *qmp_chardev_open_file(const char *id,
4067 ChardevBackend *backend,
4068 ChardevReturn *ret,
4069 Error **errp)
4071 ChardevFile *file = backend->file;
4072 HANDLE out;
4074 if (file->has_in) {
4075 error_setg(errp, "input file not supported");
4076 return NULL;
4079 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
4080 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
4081 if (out == INVALID_HANDLE_VALUE) {
4082 error_setg(errp, "open %s failed", file->out);
4083 return NULL;
4085 return qemu_chr_open_win_file(out);
4088 static CharDriverState *qmp_chardev_open_serial(const char *id,
4089 ChardevBackend *backend,
4090 ChardevReturn *ret,
4091 Error **errp)
4093 ChardevHostdev *serial = backend->serial;
4094 return qemu_chr_open_win_path(serial->device, errp);
4097 #else /* WIN32 */
4099 static int qmp_chardev_open_file_source(char *src, int flags,
4100 Error **errp)
4102 int fd = -1;
4104 TFR(fd = qemu_open(src, flags, 0666));
4105 if (fd == -1) {
4106 error_setg_file_open(errp, errno, src);
4108 return fd;
4111 static CharDriverState *qmp_chardev_open_file(const char *id,
4112 ChardevBackend *backend,
4113 ChardevReturn *ret,
4114 Error **errp)
4116 ChardevFile *file = backend->file;
4117 int flags, in = -1, out;
4119 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
4120 out = qmp_chardev_open_file_source(file->out, flags, errp);
4121 if (out < 0) {
4122 return NULL;
4125 if (file->has_in) {
4126 flags = O_RDONLY;
4127 in = qmp_chardev_open_file_source(file->in, flags, errp);
4128 if (in < 0) {
4129 qemu_close(out);
4130 return NULL;
4134 return qemu_chr_open_fd(in, out);
4137 #ifdef HAVE_CHARDEV_SERIAL
4138 static CharDriverState *qmp_chardev_open_serial(const char *id,
4139 ChardevBackend *backend,
4140 ChardevReturn *ret,
4141 Error **errp)
4143 ChardevHostdev *serial = backend->serial;
4144 int fd;
4146 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4147 if (fd < 0) {
4148 return NULL;
4150 qemu_set_nonblock(fd);
4151 return qemu_chr_open_tty_fd(fd);
4153 #endif
4155 #ifdef HAVE_CHARDEV_PARPORT
4156 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4157 ChardevBackend *backend,
4158 ChardevReturn *ret,
4159 Error **errp)
4161 ChardevHostdev *parallel = backend->parallel;
4162 int fd;
4164 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4165 if (fd < 0) {
4166 return NULL;
4168 return qemu_chr_open_pp_fd(fd, errp);
4170 #endif
4172 #endif /* WIN32 */
4174 static void socket_try_connect(CharDriverState *chr)
4176 Error *err = NULL;
4178 if (!qemu_chr_open_socket_fd(chr, &err)) {
4179 check_report_connect_error(chr, err);
4183 static gboolean socket_reconnect_timeout(gpointer opaque)
4185 CharDriverState *chr = opaque;
4186 TCPCharDriver *s = chr->opaque;
4188 s->reconnect_timer = 0;
4190 if (chr->be_open) {
4191 return false;
4194 socket_try_connect(chr);
4196 return false;
4199 static CharDriverState *qmp_chardev_open_socket(const char *id,
4200 ChardevBackend *backend,
4201 ChardevReturn *ret,
4202 Error **errp)
4204 CharDriverState *chr;
4205 TCPCharDriver *s;
4206 ChardevSocket *sock = backend->socket;
4207 SocketAddress *addr = sock->addr;
4208 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4209 bool is_listen = sock->has_server ? sock->server : true;
4210 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4211 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4212 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4214 chr = qemu_chr_alloc();
4215 s = g_new0(TCPCharDriver, 1);
4217 s->fd = -1;
4218 s->listen_fd = -1;
4219 s->is_unix = addr->kind == SOCKET_ADDRESS_KIND_UNIX;
4220 s->is_listen = is_listen;
4221 s->is_telnet = is_telnet;
4222 s->do_nodelay = do_nodelay;
4223 qapi_copy_SocketAddress(&s->addr, sock->addr);
4225 chr->opaque = s;
4226 chr->chr_write = tcp_chr_write;
4227 chr->chr_sync_read = tcp_chr_sync_read;
4228 chr->chr_close = tcp_chr_close;
4229 chr->get_msgfds = tcp_get_msgfds;
4230 chr->set_msgfds = tcp_set_msgfds;
4231 chr->chr_add_client = tcp_chr_add_client;
4232 chr->chr_add_watch = tcp_chr_add_watch;
4233 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4234 /* be isn't opened until we get a connection */
4235 chr->explicit_be_open = true;
4237 chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
4238 SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, "disconnected:",
4239 addr, is_listen, is_telnet);
4241 if (is_listen) {
4242 if (is_telnet) {
4243 s->do_telnetopt = 1;
4245 } else if (reconnect > 0) {
4246 s->reconnect_time = reconnect;
4249 if (s->reconnect_time) {
4250 socket_try_connect(chr);
4251 } else if (!qemu_chr_open_socket_fd(chr, errp)) {
4252 g_free(s);
4253 g_free(chr->filename);
4254 g_free(chr);
4255 return NULL;
4258 if (is_listen && is_waitconnect) {
4259 fprintf(stderr, "QEMU waiting for connection on: %s\n",
4260 chr->filename);
4261 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
4262 qemu_set_nonblock(s->listen_fd);
4265 return chr;
4268 static CharDriverState *qmp_chardev_open_udp(const char *id,
4269 ChardevBackend *backend,
4270 ChardevReturn *ret,
4271 Error **errp)
4273 ChardevUdp *udp = backend->udp;
4274 int fd;
4276 fd = socket_dgram(udp->remote, udp->local, errp);
4277 if (fd < 0) {
4278 return NULL;
4280 return qemu_chr_open_udp_fd(fd);
4283 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4284 Error **errp)
4286 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4287 CharDriverState *chr = NULL;
4288 Error *local_err = NULL;
4289 GSList *i;
4290 CharDriver *cd;
4292 chr = qemu_chr_find(id);
4293 if (chr) {
4294 error_setg(errp, "Chardev '%s' already exists", id);
4295 g_free(ret);
4296 return NULL;
4299 for (i = backends; i; i = i->next) {
4300 cd = i->data;
4302 if (cd->kind == backend->kind) {
4303 chr = cd->create(id, backend, ret, &local_err);
4304 if (local_err) {
4305 error_propagate(errp, local_err);
4306 goto out_error;
4308 break;
4312 if (chr == NULL) {
4313 assert(!i);
4314 error_setg(errp, "chardev backend not available");
4315 goto out_error;
4318 chr->label = g_strdup(id);
4319 chr->avail_connections =
4320 (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4321 if (!chr->filename) {
4322 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
4324 if (!chr->explicit_be_open) {
4325 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4327 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4328 return ret;
4330 out_error:
4331 g_free(ret);
4332 return NULL;
4335 void qmp_chardev_remove(const char *id, Error **errp)
4337 CharDriverState *chr;
4339 chr = qemu_chr_find(id);
4340 if (chr == NULL) {
4341 error_setg(errp, "Chardev '%s' not found", id);
4342 return;
4344 if (chr->chr_can_read || chr->chr_read ||
4345 chr->chr_event || chr->handler_opaque) {
4346 error_setg(errp, "Chardev '%s' is busy", id);
4347 return;
4349 qemu_chr_delete(chr);
4352 static void register_types(void)
4354 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4355 qemu_chr_open_null);
4356 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4357 qemu_chr_parse_socket, qmp_chardev_open_socket);
4358 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4359 qmp_chardev_open_udp);
4360 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4361 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4362 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4363 qemu_chr_parse_file_out, qmp_chardev_open_file);
4364 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4365 qemu_chr_parse_stdio, qemu_chr_open_stdio);
4366 #if defined HAVE_CHARDEV_SERIAL
4367 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4368 qemu_chr_parse_serial, qmp_chardev_open_serial);
4369 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4370 qemu_chr_parse_serial, qmp_chardev_open_serial);
4371 #endif
4372 #ifdef HAVE_CHARDEV_PARPORT
4373 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4374 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4375 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4376 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4377 #endif
4378 #ifdef HAVE_CHARDEV_PTY
4379 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4380 qemu_chr_open_pty);
4381 #endif
4382 #ifdef _WIN32
4383 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4384 qemu_chr_open_win_con);
4385 #endif
4386 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4387 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4388 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4389 qemu_chr_open_mux);
4390 /* Bug-compatibility: */
4391 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4392 qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);
4393 /* this must be done after machine init, since we register FEs with muxes
4394 * as part of realize functions like serial_isa_realizefn when -nographic
4395 * is specified
4397 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4400 type_init(register_types);