qemu-char: convert mux backend to data-driven creation
[qemu/ar7.git] / qemu-char.c
blob6f2202a3f9c9497ec48271a48c41fe6440acde0d
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(ChardevStdio *opts)
1173 CharDriverState *chr;
1174 struct sigaction act;
1176 if (is_daemonized()) {
1177 error_report("cannot use stdio with -daemonize");
1178 return NULL;
1181 if (stdio_in_use) {
1182 error_report("cannot use stdio by multiple character devices");
1183 exit(1);
1186 stdio_in_use = true;
1187 old_fd0_flags = fcntl(0, F_GETFL);
1188 tcgetattr(0, &oldtty);
1189 qemu_set_nonblock(0);
1190 atexit(term_exit);
1192 memset(&act, 0, sizeof(act));
1193 act.sa_handler = term_stdio_handler;
1194 sigaction(SIGCONT, &act, NULL);
1196 chr = qemu_chr_open_fd(0, 1);
1197 chr->chr_close = qemu_chr_close_stdio;
1198 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1199 if (opts->has_signal) {
1200 stdio_allow_signal = opts->signal;
1202 qemu_chr_fe_set_echo(chr, false);
1204 return chr;
1207 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1208 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1209 || defined(__GLIBC__)
1211 #define HAVE_CHARDEV_SERIAL 1
1212 #define HAVE_CHARDEV_PTY 1
1214 typedef struct {
1215 GIOChannel *fd;
1216 int read_bytes;
1218 /* Protected by the CharDriverState chr_write_lock. */
1219 int connected;
1220 guint timer_tag;
1221 guint open_tag;
1222 } PtyCharDriver;
1224 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1225 static void pty_chr_state(CharDriverState *chr, int connected);
1227 static gboolean pty_chr_timer(gpointer opaque)
1229 struct CharDriverState *chr = opaque;
1230 PtyCharDriver *s = chr->opaque;
1232 qemu_mutex_lock(&chr->chr_write_lock);
1233 s->timer_tag = 0;
1234 s->open_tag = 0;
1235 if (!s->connected) {
1236 /* Next poll ... */
1237 pty_chr_update_read_handler_locked(chr);
1239 qemu_mutex_unlock(&chr->chr_write_lock);
1240 return FALSE;
1243 /* Called with chr_write_lock held. */
1244 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1246 PtyCharDriver *s = chr->opaque;
1248 if (s->timer_tag) {
1249 g_source_remove(s->timer_tag);
1250 s->timer_tag = 0;
1253 if (ms == 1000) {
1254 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1255 } else {
1256 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1260 /* Called with chr_write_lock held. */
1261 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1263 PtyCharDriver *s = chr->opaque;
1264 GPollFD pfd;
1266 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1267 pfd.events = G_IO_OUT;
1268 pfd.revents = 0;
1269 g_poll(&pfd, 1, 0);
1270 if (pfd.revents & G_IO_HUP) {
1271 pty_chr_state(chr, 0);
1272 } else {
1273 pty_chr_state(chr, 1);
1277 static void pty_chr_update_read_handler(CharDriverState *chr)
1279 qemu_mutex_lock(&chr->chr_write_lock);
1280 pty_chr_update_read_handler_locked(chr);
1281 qemu_mutex_unlock(&chr->chr_write_lock);
1284 /* Called with chr_write_lock held. */
1285 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1287 PtyCharDriver *s = chr->opaque;
1289 if (!s->connected) {
1290 /* guest sends data, check for (re-)connect */
1291 pty_chr_update_read_handler_locked(chr);
1292 if (!s->connected) {
1293 return 0;
1296 return io_channel_send(s->fd, buf, len);
1299 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1301 PtyCharDriver *s = chr->opaque;
1302 if (!s->connected) {
1303 return NULL;
1305 return g_io_create_watch(s->fd, cond);
1308 static int pty_chr_read_poll(void *opaque)
1310 CharDriverState *chr = opaque;
1311 PtyCharDriver *s = chr->opaque;
1313 s->read_bytes = qemu_chr_be_can_write(chr);
1314 return s->read_bytes;
1317 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1319 CharDriverState *chr = opaque;
1320 PtyCharDriver *s = chr->opaque;
1321 gsize size, len;
1322 uint8_t buf[READ_BUF_LEN];
1323 GIOStatus status;
1325 len = sizeof(buf);
1326 if (len > s->read_bytes)
1327 len = s->read_bytes;
1328 if (len == 0) {
1329 return TRUE;
1331 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1332 if (status != G_IO_STATUS_NORMAL) {
1333 pty_chr_state(chr, 0);
1334 return FALSE;
1335 } else {
1336 pty_chr_state(chr, 1);
1337 qemu_chr_be_write(chr, buf, size);
1339 return TRUE;
1342 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1344 CharDriverState *chr = opaque;
1345 PtyCharDriver *s = chr->opaque;
1347 s->open_tag = 0;
1348 qemu_chr_be_generic_open(chr);
1349 return FALSE;
1352 /* Called with chr_write_lock held. */
1353 static void pty_chr_state(CharDriverState *chr, int connected)
1355 PtyCharDriver *s = chr->opaque;
1357 if (!connected) {
1358 if (s->open_tag) {
1359 g_source_remove(s->open_tag);
1360 s->open_tag = 0;
1362 remove_fd_in_watch(chr);
1363 s->connected = 0;
1364 /* (re-)connect poll interval for idle guests: once per second.
1365 * We check more frequently in case the guests sends data to
1366 * the virtual device linked to our pty. */
1367 pty_chr_rearm_timer(chr, 1000);
1368 } else {
1369 if (s->timer_tag) {
1370 g_source_remove(s->timer_tag);
1371 s->timer_tag = 0;
1373 if (!s->connected) {
1374 g_assert(s->open_tag == 0);
1375 s->connected = 1;
1376 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1378 if (!chr->fd_in_tag) {
1379 chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
1380 pty_chr_read, chr);
1385 static void pty_chr_close(struct CharDriverState *chr)
1387 PtyCharDriver *s = chr->opaque;
1388 int fd;
1390 qemu_mutex_lock(&chr->chr_write_lock);
1391 pty_chr_state(chr, 0);
1392 fd = g_io_channel_unix_get_fd(s->fd);
1393 g_io_channel_unref(s->fd);
1394 close(fd);
1395 if (s->timer_tag) {
1396 g_source_remove(s->timer_tag);
1397 s->timer_tag = 0;
1399 qemu_mutex_unlock(&chr->chr_write_lock);
1400 g_free(s);
1401 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1404 static CharDriverState *qemu_chr_open_pty(const char *id,
1405 ChardevBackend *backend,
1406 ChardevReturn *ret,
1407 Error **errp)
1409 CharDriverState *chr;
1410 PtyCharDriver *s;
1411 int master_fd, slave_fd;
1412 char pty_name[PATH_MAX];
1414 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1415 if (master_fd < 0) {
1416 error_setg_errno(errp, errno, "Failed to create PTY");
1417 return NULL;
1420 close(slave_fd);
1421 qemu_set_nonblock(master_fd);
1423 chr = qemu_chr_alloc();
1425 chr->filename = g_strdup_printf("pty:%s", pty_name);
1426 ret->pty = g_strdup(pty_name);
1427 ret->has_pty = true;
1429 fprintf(stderr, "char device redirected to %s (label %s)\n",
1430 pty_name, id);
1432 s = g_new0(PtyCharDriver, 1);
1433 chr->opaque = s;
1434 chr->chr_write = pty_chr_write;
1435 chr->chr_update_read_handler = pty_chr_update_read_handler;
1436 chr->chr_close = pty_chr_close;
1437 chr->chr_add_watch = pty_chr_add_watch;
1438 chr->explicit_be_open = true;
1440 s->fd = io_channel_from_fd(master_fd);
1441 s->timer_tag = 0;
1443 return chr;
1446 static void tty_serial_init(int fd, int speed,
1447 int parity, int data_bits, int stop_bits)
1449 struct termios tty;
1450 speed_t spd;
1452 #if 0
1453 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1454 speed, parity, data_bits, stop_bits);
1455 #endif
1456 tcgetattr (fd, &tty);
1458 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1459 speed = speed * 10 / 11;
1460 do {
1461 check_speed(50);
1462 check_speed(75);
1463 check_speed(110);
1464 check_speed(134);
1465 check_speed(150);
1466 check_speed(200);
1467 check_speed(300);
1468 check_speed(600);
1469 check_speed(1200);
1470 check_speed(1800);
1471 check_speed(2400);
1472 check_speed(4800);
1473 check_speed(9600);
1474 check_speed(19200);
1475 check_speed(38400);
1476 /* Non-Posix values follow. They may be unsupported on some systems. */
1477 check_speed(57600);
1478 check_speed(115200);
1479 #ifdef B230400
1480 check_speed(230400);
1481 #endif
1482 #ifdef B460800
1483 check_speed(460800);
1484 #endif
1485 #ifdef B500000
1486 check_speed(500000);
1487 #endif
1488 #ifdef B576000
1489 check_speed(576000);
1490 #endif
1491 #ifdef B921600
1492 check_speed(921600);
1493 #endif
1494 #ifdef B1000000
1495 check_speed(1000000);
1496 #endif
1497 #ifdef B1152000
1498 check_speed(1152000);
1499 #endif
1500 #ifdef B1500000
1501 check_speed(1500000);
1502 #endif
1503 #ifdef B2000000
1504 check_speed(2000000);
1505 #endif
1506 #ifdef B2500000
1507 check_speed(2500000);
1508 #endif
1509 #ifdef B3000000
1510 check_speed(3000000);
1511 #endif
1512 #ifdef B3500000
1513 check_speed(3500000);
1514 #endif
1515 #ifdef B4000000
1516 check_speed(4000000);
1517 #endif
1518 spd = B115200;
1519 } while (0);
1521 cfsetispeed(&tty, spd);
1522 cfsetospeed(&tty, spd);
1524 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1525 |INLCR|IGNCR|ICRNL|IXON);
1526 tty.c_oflag |= OPOST;
1527 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1528 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1529 switch(data_bits) {
1530 default:
1531 case 8:
1532 tty.c_cflag |= CS8;
1533 break;
1534 case 7:
1535 tty.c_cflag |= CS7;
1536 break;
1537 case 6:
1538 tty.c_cflag |= CS6;
1539 break;
1540 case 5:
1541 tty.c_cflag |= CS5;
1542 break;
1544 switch(parity) {
1545 default:
1546 case 'N':
1547 break;
1548 case 'E':
1549 tty.c_cflag |= PARENB;
1550 break;
1551 case 'O':
1552 tty.c_cflag |= PARENB | PARODD;
1553 break;
1555 if (stop_bits == 2)
1556 tty.c_cflag |= CSTOPB;
1558 tcsetattr (fd, TCSANOW, &tty);
1561 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1563 FDCharDriver *s = chr->opaque;
1565 switch(cmd) {
1566 case CHR_IOCTL_SERIAL_SET_PARAMS:
1568 QEMUSerialSetParams *ssp = arg;
1569 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1570 ssp->speed, ssp->parity,
1571 ssp->data_bits, ssp->stop_bits);
1573 break;
1574 case CHR_IOCTL_SERIAL_SET_BREAK:
1576 int enable = *(int *)arg;
1577 if (enable) {
1578 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1581 break;
1582 case CHR_IOCTL_SERIAL_GET_TIOCM:
1584 int sarg = 0;
1585 int *targ = (int *)arg;
1586 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1587 *targ = 0;
1588 if (sarg & TIOCM_CTS)
1589 *targ |= CHR_TIOCM_CTS;
1590 if (sarg & TIOCM_CAR)
1591 *targ |= CHR_TIOCM_CAR;
1592 if (sarg & TIOCM_DSR)
1593 *targ |= CHR_TIOCM_DSR;
1594 if (sarg & TIOCM_RI)
1595 *targ |= CHR_TIOCM_RI;
1596 if (sarg & TIOCM_DTR)
1597 *targ |= CHR_TIOCM_DTR;
1598 if (sarg & TIOCM_RTS)
1599 *targ |= CHR_TIOCM_RTS;
1601 break;
1602 case CHR_IOCTL_SERIAL_SET_TIOCM:
1604 int sarg = *(int *)arg;
1605 int targ = 0;
1606 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1607 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1608 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1609 if (sarg & CHR_TIOCM_CTS)
1610 targ |= TIOCM_CTS;
1611 if (sarg & CHR_TIOCM_CAR)
1612 targ |= TIOCM_CAR;
1613 if (sarg & CHR_TIOCM_DSR)
1614 targ |= TIOCM_DSR;
1615 if (sarg & CHR_TIOCM_RI)
1616 targ |= TIOCM_RI;
1617 if (sarg & CHR_TIOCM_DTR)
1618 targ |= TIOCM_DTR;
1619 if (sarg & CHR_TIOCM_RTS)
1620 targ |= TIOCM_RTS;
1621 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1623 break;
1624 default:
1625 return -ENOTSUP;
1627 return 0;
1630 static void qemu_chr_close_tty(CharDriverState *chr)
1632 FDCharDriver *s = chr->opaque;
1633 int fd = -1;
1635 if (s) {
1636 fd = g_io_channel_unix_get_fd(s->fd_in);
1639 fd_chr_close(chr);
1641 if (fd >= 0) {
1642 close(fd);
1646 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1648 CharDriverState *chr;
1650 tty_serial_init(fd, 115200, 'N', 8, 1);
1651 chr = qemu_chr_open_fd(fd, fd);
1652 chr->chr_ioctl = tty_serial_ioctl;
1653 chr->chr_close = qemu_chr_close_tty;
1654 return chr;
1656 #endif /* __linux__ || __sun__ */
1658 #if defined(__linux__)
1660 #define HAVE_CHARDEV_PARPORT 1
1662 typedef struct {
1663 int fd;
1664 int mode;
1665 } ParallelCharDriver;
1667 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1669 if (s->mode != mode) {
1670 int m = mode;
1671 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1672 return 0;
1673 s->mode = mode;
1675 return 1;
1678 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1680 ParallelCharDriver *drv = chr->opaque;
1681 int fd = drv->fd;
1682 uint8_t b;
1684 switch(cmd) {
1685 case CHR_IOCTL_PP_READ_DATA:
1686 if (ioctl(fd, PPRDATA, &b) < 0)
1687 return -ENOTSUP;
1688 *(uint8_t *)arg = b;
1689 break;
1690 case CHR_IOCTL_PP_WRITE_DATA:
1691 b = *(uint8_t *)arg;
1692 if (ioctl(fd, PPWDATA, &b) < 0)
1693 return -ENOTSUP;
1694 break;
1695 case CHR_IOCTL_PP_READ_CONTROL:
1696 if (ioctl(fd, PPRCONTROL, &b) < 0)
1697 return -ENOTSUP;
1698 /* Linux gives only the lowest bits, and no way to know data
1699 direction! For better compatibility set the fixed upper
1700 bits. */
1701 *(uint8_t *)arg = b | 0xc0;
1702 break;
1703 case CHR_IOCTL_PP_WRITE_CONTROL:
1704 b = *(uint8_t *)arg;
1705 if (ioctl(fd, PPWCONTROL, &b) < 0)
1706 return -ENOTSUP;
1707 break;
1708 case CHR_IOCTL_PP_READ_STATUS:
1709 if (ioctl(fd, PPRSTATUS, &b) < 0)
1710 return -ENOTSUP;
1711 *(uint8_t *)arg = b;
1712 break;
1713 case CHR_IOCTL_PP_DATA_DIR:
1714 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1715 return -ENOTSUP;
1716 break;
1717 case CHR_IOCTL_PP_EPP_READ_ADDR:
1718 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1719 struct ParallelIOArg *parg = arg;
1720 int n = read(fd, parg->buffer, parg->count);
1721 if (n != parg->count) {
1722 return -EIO;
1725 break;
1726 case CHR_IOCTL_PP_EPP_READ:
1727 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1728 struct ParallelIOArg *parg = arg;
1729 int n = read(fd, parg->buffer, parg->count);
1730 if (n != parg->count) {
1731 return -EIO;
1734 break;
1735 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1736 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1737 struct ParallelIOArg *parg = arg;
1738 int n = write(fd, parg->buffer, parg->count);
1739 if (n != parg->count) {
1740 return -EIO;
1743 break;
1744 case CHR_IOCTL_PP_EPP_WRITE:
1745 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1746 struct ParallelIOArg *parg = arg;
1747 int n = write(fd, parg->buffer, parg->count);
1748 if (n != parg->count) {
1749 return -EIO;
1752 break;
1753 default:
1754 return -ENOTSUP;
1756 return 0;
1759 static void pp_close(CharDriverState *chr)
1761 ParallelCharDriver *drv = chr->opaque;
1762 int fd = drv->fd;
1764 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1765 ioctl(fd, PPRELEASE);
1766 close(fd);
1767 g_free(drv);
1768 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1771 static CharDriverState *qemu_chr_open_pp_fd(int fd, Error **errp)
1773 CharDriverState *chr;
1774 ParallelCharDriver *drv;
1776 if (ioctl(fd, PPCLAIM) < 0) {
1777 error_setg_errno(errp, errno, "not a parallel port");
1778 close(fd);
1779 return NULL;
1782 drv = g_new0(ParallelCharDriver, 1);
1783 drv->fd = fd;
1784 drv->mode = IEEE1284_MODE_COMPAT;
1786 chr = qemu_chr_alloc();
1787 chr->chr_write = null_chr_write;
1788 chr->chr_ioctl = pp_ioctl;
1789 chr->chr_close = pp_close;
1790 chr->opaque = drv;
1792 return chr;
1794 #endif /* __linux__ */
1796 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1798 #define HAVE_CHARDEV_PARPORT 1
1800 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1802 int fd = (int)(intptr_t)chr->opaque;
1803 uint8_t b;
1805 switch(cmd) {
1806 case CHR_IOCTL_PP_READ_DATA:
1807 if (ioctl(fd, PPIGDATA, &b) < 0)
1808 return -ENOTSUP;
1809 *(uint8_t *)arg = b;
1810 break;
1811 case CHR_IOCTL_PP_WRITE_DATA:
1812 b = *(uint8_t *)arg;
1813 if (ioctl(fd, PPISDATA, &b) < 0)
1814 return -ENOTSUP;
1815 break;
1816 case CHR_IOCTL_PP_READ_CONTROL:
1817 if (ioctl(fd, PPIGCTRL, &b) < 0)
1818 return -ENOTSUP;
1819 *(uint8_t *)arg = b;
1820 break;
1821 case CHR_IOCTL_PP_WRITE_CONTROL:
1822 b = *(uint8_t *)arg;
1823 if (ioctl(fd, PPISCTRL, &b) < 0)
1824 return -ENOTSUP;
1825 break;
1826 case CHR_IOCTL_PP_READ_STATUS:
1827 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1828 return -ENOTSUP;
1829 *(uint8_t *)arg = b;
1830 break;
1831 default:
1832 return -ENOTSUP;
1834 return 0;
1837 static CharDriverState *qemu_chr_open_pp_fd(int fd, Error **errp)
1839 CharDriverState *chr;
1841 chr = qemu_chr_alloc();
1842 chr->opaque = (void *)(intptr_t)fd;
1843 chr->chr_write = null_chr_write;
1844 chr->chr_ioctl = pp_ioctl;
1845 chr->explicit_be_open = true;
1846 return chr;
1848 #endif
1850 #else /* _WIN32 */
1852 #define HAVE_CHARDEV_SERIAL 1
1854 typedef struct {
1855 int max_size;
1856 HANDLE hcom, hrecv, hsend;
1857 OVERLAPPED orecv;
1858 BOOL fpipe;
1859 DWORD len;
1861 /* Protected by the CharDriverState chr_write_lock. */
1862 OVERLAPPED osend;
1863 } WinCharState;
1865 typedef struct {
1866 HANDLE hStdIn;
1867 HANDLE hInputReadyEvent;
1868 HANDLE hInputDoneEvent;
1869 HANDLE hInputThread;
1870 uint8_t win_stdio_buf;
1871 } WinStdioCharState;
1873 #define NSENDBUF 2048
1874 #define NRECVBUF 2048
1875 #define MAXCONNECT 1
1876 #define NTIMEOUT 5000
1878 static int win_chr_poll(void *opaque);
1879 static int win_chr_pipe_poll(void *opaque);
1881 static void win_chr_close(CharDriverState *chr)
1883 WinCharState *s = chr->opaque;
1885 if (s->hsend) {
1886 CloseHandle(s->hsend);
1887 s->hsend = NULL;
1889 if (s->hrecv) {
1890 CloseHandle(s->hrecv);
1891 s->hrecv = NULL;
1893 if (s->hcom) {
1894 CloseHandle(s->hcom);
1895 s->hcom = NULL;
1897 if (s->fpipe)
1898 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1899 else
1900 qemu_del_polling_cb(win_chr_poll, chr);
1902 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1905 static int win_chr_init(CharDriverState *chr, const char *filename, Error **errp)
1907 WinCharState *s = chr->opaque;
1908 COMMCONFIG comcfg;
1909 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1910 COMSTAT comstat;
1911 DWORD size;
1912 DWORD err;
1914 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1915 if (!s->hsend) {
1916 error_setg(errp, "Failed CreateEvent");
1917 goto fail;
1919 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1920 if (!s->hrecv) {
1921 error_setg(errp, "Failed CreateEvent");
1922 goto fail;
1925 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1926 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1927 if (s->hcom == INVALID_HANDLE_VALUE) {
1928 error_setg(errp, "Failed CreateFile (%lu)", GetLastError());
1929 s->hcom = NULL;
1930 goto fail;
1933 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1934 error_setg(errp, "Failed SetupComm");
1935 goto fail;
1938 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1939 size = sizeof(COMMCONFIG);
1940 GetDefaultCommConfig(filename, &comcfg, &size);
1941 comcfg.dcb.DCBlength = sizeof(DCB);
1942 CommConfigDialog(filename, NULL, &comcfg);
1944 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1945 error_setg(errp, "Failed SetCommState");
1946 goto fail;
1949 if (!SetCommMask(s->hcom, EV_ERR)) {
1950 error_setg(errp, "Failed SetCommMask");
1951 goto fail;
1954 cto.ReadIntervalTimeout = MAXDWORD;
1955 if (!SetCommTimeouts(s->hcom, &cto)) {
1956 error_setg(errp, "Failed SetCommTimeouts");
1957 goto fail;
1960 if (!ClearCommError(s->hcom, &err, &comstat)) {
1961 error_setg(errp, "Failed ClearCommError");
1962 goto fail;
1964 qemu_add_polling_cb(win_chr_poll, chr);
1965 return 0;
1967 fail:
1968 win_chr_close(chr);
1969 return -1;
1972 /* Called with chr_write_lock held. */
1973 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1975 WinCharState *s = chr->opaque;
1976 DWORD len, ret, size, err;
1978 len = len1;
1979 ZeroMemory(&s->osend, sizeof(s->osend));
1980 s->osend.hEvent = s->hsend;
1981 while (len > 0) {
1982 if (s->hsend)
1983 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1984 else
1985 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1986 if (!ret) {
1987 err = GetLastError();
1988 if (err == ERROR_IO_PENDING) {
1989 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1990 if (ret) {
1991 buf += size;
1992 len -= size;
1993 } else {
1994 break;
1996 } else {
1997 break;
1999 } else {
2000 buf += size;
2001 len -= size;
2004 return len1 - len;
2007 static int win_chr_read_poll(CharDriverState *chr)
2009 WinCharState *s = chr->opaque;
2011 s->max_size = qemu_chr_be_can_write(chr);
2012 return s->max_size;
2015 static void win_chr_readfile(CharDriverState *chr)
2017 WinCharState *s = chr->opaque;
2018 int ret, err;
2019 uint8_t buf[READ_BUF_LEN];
2020 DWORD size;
2022 ZeroMemory(&s->orecv, sizeof(s->orecv));
2023 s->orecv.hEvent = s->hrecv;
2024 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2025 if (!ret) {
2026 err = GetLastError();
2027 if (err == ERROR_IO_PENDING) {
2028 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2032 if (size > 0) {
2033 qemu_chr_be_write(chr, buf, size);
2037 static void win_chr_read(CharDriverState *chr)
2039 WinCharState *s = chr->opaque;
2041 if (s->len > s->max_size)
2042 s->len = s->max_size;
2043 if (s->len == 0)
2044 return;
2046 win_chr_readfile(chr);
2049 static int win_chr_poll(void *opaque)
2051 CharDriverState *chr = opaque;
2052 WinCharState *s = chr->opaque;
2053 COMSTAT status;
2054 DWORD comerr;
2056 ClearCommError(s->hcom, &comerr, &status);
2057 if (status.cbInQue > 0) {
2058 s->len = status.cbInQue;
2059 win_chr_read_poll(chr);
2060 win_chr_read(chr);
2061 return 1;
2063 return 0;
2066 static CharDriverState *qemu_chr_open_win_path(const char *filename,
2067 Error **errp)
2069 CharDriverState *chr;
2070 WinCharState *s;
2072 chr = qemu_chr_alloc();
2073 s = g_new0(WinCharState, 1);
2074 chr->opaque = s;
2075 chr->chr_write = win_chr_write;
2076 chr->chr_close = win_chr_close;
2078 if (win_chr_init(chr, filename, errp) < 0) {
2079 g_free(s);
2080 g_free(chr);
2081 return NULL;
2083 return chr;
2086 static int win_chr_pipe_poll(void *opaque)
2088 CharDriverState *chr = opaque;
2089 WinCharState *s = chr->opaque;
2090 DWORD size;
2092 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2093 if (size > 0) {
2094 s->len = size;
2095 win_chr_read_poll(chr);
2096 win_chr_read(chr);
2097 return 1;
2099 return 0;
2102 static int win_chr_pipe_init(CharDriverState *chr, const char *filename,
2103 Error **errp)
2105 WinCharState *s = chr->opaque;
2106 OVERLAPPED ov;
2107 int ret;
2108 DWORD size;
2109 char openname[CHR_MAX_FILENAME_SIZE];
2111 s->fpipe = TRUE;
2113 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2114 if (!s->hsend) {
2115 error_setg(errp, "Failed CreateEvent");
2116 goto fail;
2118 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2119 if (!s->hrecv) {
2120 error_setg(errp, "Failed CreateEvent");
2121 goto fail;
2124 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2125 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2126 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2127 PIPE_WAIT,
2128 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2129 if (s->hcom == INVALID_HANDLE_VALUE) {
2130 error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());
2131 s->hcom = NULL;
2132 goto fail;
2135 ZeroMemory(&ov, sizeof(ov));
2136 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2137 ret = ConnectNamedPipe(s->hcom, &ov);
2138 if (ret) {
2139 error_setg(errp, "Failed ConnectNamedPipe");
2140 goto fail;
2143 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2144 if (!ret) {
2145 error_setg(errp, "Failed GetOverlappedResult");
2146 if (ov.hEvent) {
2147 CloseHandle(ov.hEvent);
2148 ov.hEvent = NULL;
2150 goto fail;
2153 if (ov.hEvent) {
2154 CloseHandle(ov.hEvent);
2155 ov.hEvent = NULL;
2157 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2158 return 0;
2160 fail:
2161 win_chr_close(chr);
2162 return -1;
2166 static CharDriverState *qemu_chr_open_pipe(const char *id,
2167 ChardevBackend *backend,
2168 ChardevReturn *ret,
2169 Error **errp)
2171 ChardevHostdev *opts = backend->pipe;
2172 const char *filename = opts->device;
2173 CharDriverState *chr;
2174 WinCharState *s;
2176 chr = qemu_chr_alloc();
2177 s = g_new0(WinCharState, 1);
2178 chr->opaque = s;
2179 chr->chr_write = win_chr_write;
2180 chr->chr_close = win_chr_close;
2182 if (win_chr_pipe_init(chr, filename, errp) < 0) {
2183 g_free(s);
2184 g_free(chr);
2185 return NULL;
2187 return chr;
2190 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2192 CharDriverState *chr;
2193 WinCharState *s;
2195 chr = qemu_chr_alloc();
2196 s = g_new0(WinCharState, 1);
2197 s->hcom = fd_out;
2198 chr->opaque = s;
2199 chr->chr_write = win_chr_write;
2200 return chr;
2203 static CharDriverState *qemu_chr_open_win_con(void)
2205 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2208 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2210 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2211 DWORD dwSize;
2212 int len1;
2214 len1 = len;
2216 while (len1 > 0) {
2217 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2218 break;
2220 buf += dwSize;
2221 len1 -= dwSize;
2224 return len - len1;
2227 static void win_stdio_wait_func(void *opaque)
2229 CharDriverState *chr = opaque;
2230 WinStdioCharState *stdio = chr->opaque;
2231 INPUT_RECORD buf[4];
2232 int ret;
2233 DWORD dwSize;
2234 int i;
2236 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2238 if (!ret) {
2239 /* Avoid error storm */
2240 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2241 return;
2244 for (i = 0; i < dwSize; i++) {
2245 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2247 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2248 int j;
2249 if (kev->uChar.AsciiChar != 0) {
2250 for (j = 0; j < kev->wRepeatCount; j++) {
2251 if (qemu_chr_be_can_write(chr)) {
2252 uint8_t c = kev->uChar.AsciiChar;
2253 qemu_chr_be_write(chr, &c, 1);
2261 static DWORD WINAPI win_stdio_thread(LPVOID param)
2263 CharDriverState *chr = param;
2264 WinStdioCharState *stdio = chr->opaque;
2265 int ret;
2266 DWORD dwSize;
2268 while (1) {
2270 /* Wait for one byte */
2271 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2273 /* Exit in case of error, continue if nothing read */
2274 if (!ret) {
2275 break;
2277 if (!dwSize) {
2278 continue;
2281 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2282 if (stdio->win_stdio_buf == '\r') {
2283 continue;
2286 /* Signal the main thread and wait until the byte was eaten */
2287 if (!SetEvent(stdio->hInputReadyEvent)) {
2288 break;
2290 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2291 != WAIT_OBJECT_0) {
2292 break;
2296 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2297 return 0;
2300 static void win_stdio_thread_wait_func(void *opaque)
2302 CharDriverState *chr = opaque;
2303 WinStdioCharState *stdio = chr->opaque;
2305 if (qemu_chr_be_can_write(chr)) {
2306 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2309 SetEvent(stdio->hInputDoneEvent);
2312 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2314 WinStdioCharState *stdio = chr->opaque;
2315 DWORD dwMode = 0;
2317 GetConsoleMode(stdio->hStdIn, &dwMode);
2319 if (echo) {
2320 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2321 } else {
2322 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2326 static void win_stdio_close(CharDriverState *chr)
2328 WinStdioCharState *stdio = chr->opaque;
2330 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2331 CloseHandle(stdio->hInputReadyEvent);
2333 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2334 CloseHandle(stdio->hInputDoneEvent);
2336 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2337 TerminateThread(stdio->hInputThread, 0);
2340 g_free(chr->opaque);
2341 g_free(chr);
2344 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2346 CharDriverState *chr;
2347 WinStdioCharState *stdio;
2348 DWORD dwMode;
2349 int is_console = 0;
2351 chr = qemu_chr_alloc();
2352 stdio = g_new0(WinStdioCharState, 1);
2354 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2355 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2356 fprintf(stderr, "cannot open stdio: invalid handle\n");
2357 exit(1);
2360 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2362 chr->opaque = stdio;
2363 chr->chr_write = win_stdio_write;
2364 chr->chr_close = win_stdio_close;
2366 if (is_console) {
2367 if (qemu_add_wait_object(stdio->hStdIn,
2368 win_stdio_wait_func, chr)) {
2369 fprintf(stderr, "qemu_add_wait_object: failed\n");
2371 } else {
2372 DWORD dwId;
2374 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2375 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2376 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2377 chr, 0, &dwId);
2379 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2380 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2381 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2382 fprintf(stderr, "cannot create stdio thread or event\n");
2383 exit(1);
2385 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2386 win_stdio_thread_wait_func, chr)) {
2387 fprintf(stderr, "qemu_add_wait_object: failed\n");
2391 dwMode |= ENABLE_LINE_INPUT;
2393 if (is_console) {
2394 /* set the terminal in raw mode */
2395 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2396 dwMode |= ENABLE_PROCESSED_INPUT;
2399 SetConsoleMode(stdio->hStdIn, dwMode);
2401 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2402 qemu_chr_fe_set_echo(chr, false);
2404 return chr;
2406 #endif /* !_WIN32 */
2409 /***********************************************************/
2410 /* UDP Net console */
2412 typedef struct {
2413 int fd;
2414 GIOChannel *chan;
2415 uint8_t buf[READ_BUF_LEN];
2416 int bufcnt;
2417 int bufptr;
2418 int max_size;
2419 } NetCharDriver;
2421 /* Called with chr_write_lock held. */
2422 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2424 NetCharDriver *s = chr->opaque;
2425 gsize bytes_written;
2426 GIOStatus status;
2428 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2429 if (status == G_IO_STATUS_EOF) {
2430 return 0;
2431 } else if (status != G_IO_STATUS_NORMAL) {
2432 return -1;
2435 return bytes_written;
2438 static int udp_chr_read_poll(void *opaque)
2440 CharDriverState *chr = opaque;
2441 NetCharDriver *s = chr->opaque;
2443 s->max_size = qemu_chr_be_can_write(chr);
2445 /* If there were any stray characters in the queue process them
2446 * first
2448 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2449 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2450 s->bufptr++;
2451 s->max_size = qemu_chr_be_can_write(chr);
2453 return s->max_size;
2456 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2458 CharDriverState *chr = opaque;
2459 NetCharDriver *s = chr->opaque;
2460 gsize bytes_read = 0;
2461 GIOStatus status;
2463 if (s->max_size == 0) {
2464 return TRUE;
2466 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2467 &bytes_read, NULL);
2468 s->bufcnt = bytes_read;
2469 s->bufptr = s->bufcnt;
2470 if (status != G_IO_STATUS_NORMAL) {
2471 remove_fd_in_watch(chr);
2472 return FALSE;
2475 s->bufptr = 0;
2476 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2477 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2478 s->bufptr++;
2479 s->max_size = qemu_chr_be_can_write(chr);
2482 return TRUE;
2485 static void udp_chr_update_read_handler(CharDriverState *chr)
2487 NetCharDriver *s = chr->opaque;
2489 remove_fd_in_watch(chr);
2490 if (s->chan) {
2491 chr->fd_in_tag = io_add_watch_poll(s->chan, udp_chr_read_poll,
2492 udp_chr_read, chr);
2496 static void udp_chr_close(CharDriverState *chr)
2498 NetCharDriver *s = chr->opaque;
2500 remove_fd_in_watch(chr);
2501 if (s->chan) {
2502 g_io_channel_unref(s->chan);
2503 closesocket(s->fd);
2505 g_free(s);
2506 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2509 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2511 CharDriverState *chr = NULL;
2512 NetCharDriver *s = NULL;
2514 chr = qemu_chr_alloc();
2515 s = g_new0(NetCharDriver, 1);
2517 s->fd = fd;
2518 s->chan = io_channel_from_socket(s->fd);
2519 s->bufcnt = 0;
2520 s->bufptr = 0;
2521 chr->opaque = s;
2522 chr->chr_write = udp_chr_write;
2523 chr->chr_update_read_handler = udp_chr_update_read_handler;
2524 chr->chr_close = udp_chr_close;
2525 /* be isn't opened until we get a connection */
2526 chr->explicit_be_open = true;
2527 return chr;
2530 /***********************************************************/
2531 /* TCP Net console */
2533 typedef struct {
2535 GIOChannel *chan, *listen_chan;
2536 guint listen_tag;
2537 int fd, listen_fd;
2538 int connected;
2539 int max_size;
2540 int do_telnetopt;
2541 int do_nodelay;
2542 int is_unix;
2543 int *read_msgfds;
2544 int read_msgfds_num;
2545 int *write_msgfds;
2546 int write_msgfds_num;
2548 SocketAddress *addr;
2549 bool is_listen;
2550 bool is_telnet;
2552 guint reconnect_timer;
2553 int64_t reconnect_time;
2554 bool connect_err_reported;
2555 } TCPCharDriver;
2557 static gboolean socket_reconnect_timeout(gpointer opaque);
2559 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2561 TCPCharDriver *s = chr->opaque;
2562 assert(s->connected == 0);
2563 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2564 socket_reconnect_timeout, chr);
2567 static void check_report_connect_error(CharDriverState *chr,
2568 Error *err)
2570 TCPCharDriver *s = chr->opaque;
2572 if (!s->connect_err_reported) {
2573 error_report("Unable to connect character device %s: %s",
2574 chr->label, error_get_pretty(err));
2575 s->connect_err_reported = true;
2577 qemu_chr_socket_restart_timer(chr);
2580 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2582 #ifndef _WIN32
2583 static int unix_send_msgfds(CharDriverState *chr, const uint8_t *buf, int len)
2585 TCPCharDriver *s = chr->opaque;
2586 struct msghdr msgh;
2587 struct iovec iov;
2588 int r;
2590 size_t fd_size = s->write_msgfds_num * sizeof(int);
2591 char control[CMSG_SPACE(fd_size)];
2592 struct cmsghdr *cmsg;
2594 memset(&msgh, 0, sizeof(msgh));
2595 memset(control, 0, sizeof(control));
2597 /* set the payload */
2598 iov.iov_base = (uint8_t *) buf;
2599 iov.iov_len = len;
2601 msgh.msg_iov = &iov;
2602 msgh.msg_iovlen = 1;
2604 msgh.msg_control = control;
2605 msgh.msg_controllen = sizeof(control);
2607 cmsg = CMSG_FIRSTHDR(&msgh);
2609 cmsg->cmsg_len = CMSG_LEN(fd_size);
2610 cmsg->cmsg_level = SOL_SOCKET;
2611 cmsg->cmsg_type = SCM_RIGHTS;
2612 memcpy(CMSG_DATA(cmsg), s->write_msgfds, fd_size);
2614 do {
2615 r = sendmsg(s->fd, &msgh, 0);
2616 } while (r < 0 && errno == EINTR);
2618 /* free the written msgfds, no matter what */
2619 if (s->write_msgfds_num) {
2620 g_free(s->write_msgfds);
2621 s->write_msgfds = 0;
2622 s->write_msgfds_num = 0;
2625 return r;
2627 #endif
2629 /* Called with chr_write_lock held. */
2630 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2632 TCPCharDriver *s = chr->opaque;
2633 if (s->connected) {
2634 #ifndef _WIN32
2635 if (s->is_unix && s->write_msgfds_num) {
2636 return unix_send_msgfds(chr, buf, len);
2637 } else
2638 #endif
2640 return io_channel_send(s->chan, buf, len);
2642 } else {
2643 /* XXX: indicate an error ? */
2644 return len;
2648 static int tcp_chr_read_poll(void *opaque)
2650 CharDriverState *chr = opaque;
2651 TCPCharDriver *s = chr->opaque;
2652 if (!s->connected)
2653 return 0;
2654 s->max_size = qemu_chr_be_can_write(chr);
2655 return s->max_size;
2658 #define IAC 255
2659 #define IAC_BREAK 243
2660 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2661 TCPCharDriver *s,
2662 uint8_t *buf, int *size)
2664 /* Handle any telnet client's basic IAC options to satisfy char by
2665 * char mode with no echo. All IAC options will be removed from
2666 * the buf and the do_telnetopt variable will be used to track the
2667 * state of the width of the IAC information.
2669 * IAC commands come in sets of 3 bytes with the exception of the
2670 * "IAC BREAK" command and the double IAC.
2673 int i;
2674 int j = 0;
2676 for (i = 0; i < *size; i++) {
2677 if (s->do_telnetopt > 1) {
2678 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2679 /* Double IAC means send an IAC */
2680 if (j != i)
2681 buf[j] = buf[i];
2682 j++;
2683 s->do_telnetopt = 1;
2684 } else {
2685 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2686 /* Handle IAC break commands by sending a serial break */
2687 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2688 s->do_telnetopt++;
2690 s->do_telnetopt++;
2692 if (s->do_telnetopt >= 4) {
2693 s->do_telnetopt = 1;
2695 } else {
2696 if ((unsigned char)buf[i] == IAC) {
2697 s->do_telnetopt = 2;
2698 } else {
2699 if (j != i)
2700 buf[j] = buf[i];
2701 j++;
2705 *size = j;
2708 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2710 TCPCharDriver *s = chr->opaque;
2711 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2713 assert(num <= TCP_MAX_FDS);
2715 if (to_copy) {
2716 int i;
2718 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2720 /* Close unused fds */
2721 for (i = to_copy; i < s->read_msgfds_num; i++) {
2722 close(s->read_msgfds[i]);
2725 g_free(s->read_msgfds);
2726 s->read_msgfds = 0;
2727 s->read_msgfds_num = 0;
2730 return to_copy;
2733 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2735 TCPCharDriver *s = chr->opaque;
2737 /* clear old pending fd array */
2738 g_free(s->write_msgfds);
2740 if (num) {
2741 s->write_msgfds = g_new(int, num);
2742 memcpy(s->write_msgfds, fds, num * sizeof(int));
2745 s->write_msgfds_num = num;
2747 return 0;
2750 #ifndef _WIN32
2751 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2753 TCPCharDriver *s = chr->opaque;
2754 struct cmsghdr *cmsg;
2756 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2757 int fd_size, i;
2759 if (cmsg->cmsg_len < CMSG_LEN(sizeof(int)) ||
2760 cmsg->cmsg_level != SOL_SOCKET ||
2761 cmsg->cmsg_type != SCM_RIGHTS) {
2762 continue;
2765 fd_size = cmsg->cmsg_len - CMSG_LEN(0);
2767 if (!fd_size) {
2768 continue;
2771 /* close and clean read_msgfds */
2772 for (i = 0; i < s->read_msgfds_num; i++) {
2773 close(s->read_msgfds[i]);
2776 if (s->read_msgfds_num) {
2777 g_free(s->read_msgfds);
2780 s->read_msgfds_num = fd_size / sizeof(int);
2781 s->read_msgfds = g_malloc(fd_size);
2782 memcpy(s->read_msgfds, CMSG_DATA(cmsg), fd_size);
2784 for (i = 0; i < s->read_msgfds_num; i++) {
2785 int fd = s->read_msgfds[i];
2786 if (fd < 0) {
2787 continue;
2790 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2791 qemu_set_block(fd);
2793 #ifndef MSG_CMSG_CLOEXEC
2794 qemu_set_cloexec(fd);
2795 #endif
2800 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2802 TCPCharDriver *s = chr->opaque;
2803 struct msghdr msg = { NULL, };
2804 struct iovec iov[1];
2805 union {
2806 struct cmsghdr cmsg;
2807 char control[CMSG_SPACE(sizeof(int) * TCP_MAX_FDS)];
2808 } msg_control;
2809 int flags = 0;
2810 ssize_t ret;
2812 iov[0].iov_base = buf;
2813 iov[0].iov_len = len;
2815 msg.msg_iov = iov;
2816 msg.msg_iovlen = 1;
2817 msg.msg_control = &msg_control;
2818 msg.msg_controllen = sizeof(msg_control);
2820 #ifdef MSG_CMSG_CLOEXEC
2821 flags |= MSG_CMSG_CLOEXEC;
2822 #endif
2823 do {
2824 ret = recvmsg(s->fd, &msg, flags);
2825 } while (ret == -1 && errno == EINTR);
2827 if (ret > 0 && s->is_unix) {
2828 unix_process_msgfd(chr, &msg);
2831 return ret;
2833 #else
2834 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2836 TCPCharDriver *s = chr->opaque;
2837 ssize_t ret;
2839 do {
2840 ret = qemu_recv(s->fd, buf, len, 0);
2841 } while (ret == -1 && socket_error() == EINTR);
2843 return ret;
2845 #endif
2847 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2849 TCPCharDriver *s = chr->opaque;
2850 return g_io_create_watch(s->chan, cond);
2853 static void tcp_chr_disconnect(CharDriverState *chr)
2855 TCPCharDriver *s = chr->opaque;
2857 s->connected = 0;
2858 if (s->listen_chan) {
2859 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
2860 tcp_chr_accept, chr);
2862 remove_fd_in_watch(chr);
2863 g_io_channel_unref(s->chan);
2864 s->chan = NULL;
2865 closesocket(s->fd);
2866 s->fd = -1;
2867 SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
2868 "disconnected:", s->addr, s->is_listen, s->is_telnet);
2869 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2870 if (s->reconnect_time) {
2871 qemu_chr_socket_restart_timer(chr);
2875 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2877 CharDriverState *chr = opaque;
2878 TCPCharDriver *s = chr->opaque;
2879 uint8_t buf[READ_BUF_LEN];
2880 int len, size;
2882 if (!s->connected || s->max_size <= 0) {
2883 return TRUE;
2885 len = sizeof(buf);
2886 if (len > s->max_size)
2887 len = s->max_size;
2888 size = tcp_chr_recv(chr, (void *)buf, len);
2889 if (size == 0 ||
2890 (size < 0 &&
2891 socket_error() != EAGAIN && socket_error() != EWOULDBLOCK)) {
2892 /* connection closed */
2893 tcp_chr_disconnect(chr);
2894 } else if (size > 0) {
2895 if (s->do_telnetopt)
2896 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2897 if (size > 0)
2898 qemu_chr_be_write(chr, buf, size);
2901 return TRUE;
2904 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2906 TCPCharDriver *s = chr->opaque;
2907 int size;
2909 if (!s->connected) {
2910 return 0;
2913 size = tcp_chr_recv(chr, (void *) buf, len);
2914 if (size == 0) {
2915 /* connection closed */
2916 tcp_chr_disconnect(chr);
2919 return size;
2922 #ifndef _WIN32
2923 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2925 CharDriverState *chr = qemu_chr_open_fd(eventfd, eventfd);
2927 if (chr) {
2928 chr->avail_connections = 1;
2931 return chr;
2933 #endif
2935 static void tcp_chr_connect(void *opaque)
2937 CharDriverState *chr = opaque;
2938 TCPCharDriver *s = chr->opaque;
2939 struct sockaddr_storage ss, ps;
2940 socklen_t ss_len = sizeof(ss), ps_len = sizeof(ps);
2942 memset(&ss, 0, ss_len);
2943 if (getsockname(s->fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2944 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
2945 "Error in getsockname: %s\n", strerror(errno));
2946 } else if (getpeername(s->fd, (struct sockaddr *) &ps, &ps_len) != 0) {
2947 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
2948 "Error in getpeername: %s\n", strerror(errno));
2949 } else {
2950 sockaddr_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
2951 &ss, ss_len, &ps, ps_len,
2952 s->is_listen, s->is_telnet);
2955 s->connected = 1;
2956 if (s->chan) {
2957 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2958 tcp_chr_read, chr);
2960 qemu_chr_be_generic_open(chr);
2963 static void tcp_chr_update_read_handler(CharDriverState *chr)
2965 TCPCharDriver *s = chr->opaque;
2967 remove_fd_in_watch(chr);
2968 if (s->chan) {
2969 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2970 tcp_chr_read, chr);
2974 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2975 static void tcp_chr_telnet_init(int fd)
2977 char buf[3];
2978 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2979 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2980 send(fd, (char *)buf, 3, 0);
2981 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2982 send(fd, (char *)buf, 3, 0);
2983 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2984 send(fd, (char *)buf, 3, 0);
2985 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2986 send(fd, (char *)buf, 3, 0);
2989 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2991 TCPCharDriver *s = chr->opaque;
2992 if (s->fd != -1)
2993 return -1;
2995 qemu_set_nonblock(fd);
2996 if (s->do_nodelay)
2997 socket_set_nodelay(fd);
2998 s->fd = fd;
2999 s->chan = io_channel_from_socket(fd);
3000 if (s->listen_tag) {
3001 g_source_remove(s->listen_tag);
3002 s->listen_tag = 0;
3004 tcp_chr_connect(chr);
3006 return 0;
3009 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
3011 CharDriverState *chr = opaque;
3012 TCPCharDriver *s = chr->opaque;
3013 struct sockaddr_in saddr;
3014 #ifndef _WIN32
3015 struct sockaddr_un uaddr;
3016 #endif
3017 struct sockaddr *addr;
3018 socklen_t len;
3019 int fd;
3021 for(;;) {
3022 #ifndef _WIN32
3023 if (s->is_unix) {
3024 len = sizeof(uaddr);
3025 addr = (struct sockaddr *)&uaddr;
3026 } else
3027 #endif
3029 len = sizeof(saddr);
3030 addr = (struct sockaddr *)&saddr;
3032 fd = qemu_accept(s->listen_fd, addr, &len);
3033 if (fd < 0 && errno != EINTR) {
3034 s->listen_tag = 0;
3035 return FALSE;
3036 } else if (fd >= 0) {
3037 if (s->do_telnetopt)
3038 tcp_chr_telnet_init(fd);
3039 break;
3042 if (tcp_chr_add_client(chr, fd) < 0)
3043 close(fd);
3045 return TRUE;
3048 static void tcp_chr_close(CharDriverState *chr)
3050 TCPCharDriver *s = chr->opaque;
3051 int i;
3053 if (s->reconnect_timer) {
3054 g_source_remove(s->reconnect_timer);
3055 s->reconnect_timer = 0;
3057 qapi_free_SocketAddress(s->addr);
3058 if (s->fd >= 0) {
3059 remove_fd_in_watch(chr);
3060 if (s->chan) {
3061 g_io_channel_unref(s->chan);
3063 closesocket(s->fd);
3065 if (s->listen_fd >= 0) {
3066 if (s->listen_tag) {
3067 g_source_remove(s->listen_tag);
3068 s->listen_tag = 0;
3070 if (s->listen_chan) {
3071 g_io_channel_unref(s->listen_chan);
3073 closesocket(s->listen_fd);
3075 if (s->read_msgfds_num) {
3076 for (i = 0; i < s->read_msgfds_num; i++) {
3077 close(s->read_msgfds[i]);
3079 g_free(s->read_msgfds);
3081 if (s->write_msgfds_num) {
3082 g_free(s->write_msgfds);
3084 g_free(s);
3085 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3088 static void qemu_chr_finish_socket_connection(CharDriverState *chr, int fd)
3090 TCPCharDriver *s = chr->opaque;
3092 if (s->is_listen) {
3093 s->listen_fd = fd;
3094 s->listen_chan = io_channel_from_socket(s->listen_fd);
3095 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
3096 tcp_chr_accept, chr);
3097 } else {
3098 s->connected = 1;
3099 s->fd = fd;
3100 socket_set_nodelay(fd);
3101 s->chan = io_channel_from_socket(s->fd);
3102 tcp_chr_connect(chr);
3106 static void qemu_chr_socket_connected(int fd, Error *err, void *opaque)
3108 CharDriverState *chr = opaque;
3109 TCPCharDriver *s = chr->opaque;
3111 if (fd < 0) {
3112 check_report_connect_error(chr, err);
3113 return;
3116 s->connect_err_reported = false;
3117 qemu_chr_finish_socket_connection(chr, fd);
3120 static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp)
3122 TCPCharDriver *s = chr->opaque;
3123 int fd;
3125 if (s->is_listen) {
3126 fd = socket_listen(s->addr, errp);
3127 } else if (s->reconnect_time) {
3128 fd = socket_connect(s->addr, errp, qemu_chr_socket_connected, chr);
3129 return fd >= 0;
3130 } else {
3131 fd = socket_connect(s->addr, errp, NULL, NULL);
3133 if (fd < 0) {
3134 return false;
3137 qemu_chr_finish_socket_connection(chr, fd);
3138 return true;
3141 /*********************************************************/
3142 /* Ring buffer chardev */
3144 typedef struct {
3145 size_t size;
3146 size_t prod;
3147 size_t cons;
3148 uint8_t *cbuf;
3149 } RingBufCharDriver;
3151 static size_t ringbuf_count(const CharDriverState *chr)
3153 const RingBufCharDriver *d = chr->opaque;
3155 return d->prod - d->cons;
3158 /* Called with chr_write_lock held. */
3159 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3161 RingBufCharDriver *d = chr->opaque;
3162 int i;
3164 if (!buf || (len < 0)) {
3165 return -1;
3168 for (i = 0; i < len; i++ ) {
3169 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3170 if (d->prod - d->cons > d->size) {
3171 d->cons = d->prod - d->size;
3175 return 0;
3178 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3180 RingBufCharDriver *d = chr->opaque;
3181 int i;
3183 qemu_mutex_lock(&chr->chr_write_lock);
3184 for (i = 0; i < len && d->cons != d->prod; i++) {
3185 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3187 qemu_mutex_unlock(&chr->chr_write_lock);
3189 return i;
3192 static void ringbuf_chr_close(struct CharDriverState *chr)
3194 RingBufCharDriver *d = chr->opaque;
3196 g_free(d->cbuf);
3197 g_free(d);
3198 chr->opaque = NULL;
3201 static CharDriverState *qemu_chr_open_ringbuf(ChardevRingbuf *opts,
3202 Error **errp)
3204 CharDriverState *chr;
3205 RingBufCharDriver *d;
3207 chr = qemu_chr_alloc();
3208 d = g_malloc(sizeof(*d));
3210 d->size = opts->has_size ? opts->size : 65536;
3212 /* The size must be power of 2 */
3213 if (d->size & (d->size - 1)) {
3214 error_setg(errp, "size of ringbuf chardev must be power of two");
3215 goto fail;
3218 d->prod = 0;
3219 d->cons = 0;
3220 d->cbuf = g_malloc0(d->size);
3222 chr->opaque = d;
3223 chr->chr_write = ringbuf_chr_write;
3224 chr->chr_close = ringbuf_chr_close;
3226 return chr;
3228 fail:
3229 g_free(d);
3230 g_free(chr);
3231 return NULL;
3234 bool chr_is_ringbuf(const CharDriverState *chr)
3236 return chr->chr_write == ringbuf_chr_write;
3239 void qmp_ringbuf_write(const char *device, const char *data,
3240 bool has_format, enum DataFormat format,
3241 Error **errp)
3243 CharDriverState *chr;
3244 const uint8_t *write_data;
3245 int ret;
3246 gsize write_count;
3248 chr = qemu_chr_find(device);
3249 if (!chr) {
3250 error_setg(errp, "Device '%s' not found", device);
3251 return;
3254 if (!chr_is_ringbuf(chr)) {
3255 error_setg(errp,"%s is not a ringbuf device", device);
3256 return;
3259 if (has_format && (format == DATA_FORMAT_BASE64)) {
3260 write_data = g_base64_decode(data, &write_count);
3261 } else {
3262 write_data = (uint8_t *)data;
3263 write_count = strlen(data);
3266 ret = ringbuf_chr_write(chr, write_data, write_count);
3268 if (write_data != (uint8_t *)data) {
3269 g_free((void *)write_data);
3272 if (ret < 0) {
3273 error_setg(errp, "Failed to write to device %s", device);
3274 return;
3278 char *qmp_ringbuf_read(const char *device, int64_t size,
3279 bool has_format, enum DataFormat format,
3280 Error **errp)
3282 CharDriverState *chr;
3283 uint8_t *read_data;
3284 size_t count;
3285 char *data;
3287 chr = qemu_chr_find(device);
3288 if (!chr) {
3289 error_setg(errp, "Device '%s' not found", device);
3290 return NULL;
3293 if (!chr_is_ringbuf(chr)) {
3294 error_setg(errp,"%s is not a ringbuf device", device);
3295 return NULL;
3298 if (size <= 0) {
3299 error_setg(errp, "size must be greater than zero");
3300 return NULL;
3303 count = ringbuf_count(chr);
3304 size = size > count ? count : size;
3305 read_data = g_malloc(size + 1);
3307 ringbuf_chr_read(chr, read_data, size);
3309 if (has_format && (format == DATA_FORMAT_BASE64)) {
3310 data = g_base64_encode(read_data, size);
3311 g_free(read_data);
3312 } else {
3314 * FIXME should read only complete, valid UTF-8 characters up
3315 * to @size bytes. Invalid sequences should be replaced by a
3316 * suitable replacement character. Except when (and only
3317 * when) ring buffer lost characters since last read, initial
3318 * continuation characters should be dropped.
3320 read_data[size] = 0;
3321 data = (char *)read_data;
3324 return data;
3327 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3329 char host[65], port[33], width[8], height[8];
3330 int pos;
3331 const char *p;
3332 QemuOpts *opts;
3333 Error *local_err = NULL;
3335 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3336 if (local_err) {
3337 error_report_err(local_err);
3338 return NULL;
3341 if (strstart(filename, "mon:", &p)) {
3342 filename = p;
3343 qemu_opt_set(opts, "mux", "on", &error_abort);
3344 if (strcmp(filename, "stdio") == 0) {
3345 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3346 * but pass it to the guest. Handle this only for compat syntax,
3347 * for -chardev syntax we have special option for this.
3348 * This is what -nographic did, redirecting+muxing serial+monitor
3349 * to stdio causing Ctrl+C to be passed to guest. */
3350 qemu_opt_set(opts, "signal", "off", &error_abort);
3354 if (strcmp(filename, "null") == 0 ||
3355 strcmp(filename, "pty") == 0 ||
3356 strcmp(filename, "msmouse") == 0 ||
3357 strcmp(filename, "braille") == 0 ||
3358 strcmp(filename, "testdev") == 0 ||
3359 strcmp(filename, "stdio") == 0) {
3360 qemu_opt_set(opts, "backend", filename, &error_abort);
3361 return opts;
3363 if (strstart(filename, "vc", &p)) {
3364 qemu_opt_set(opts, "backend", "vc", &error_abort);
3365 if (*p == ':') {
3366 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3367 /* pixels */
3368 qemu_opt_set(opts, "width", width, &error_abort);
3369 qemu_opt_set(opts, "height", height, &error_abort);
3370 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3371 /* chars */
3372 qemu_opt_set(opts, "cols", width, &error_abort);
3373 qemu_opt_set(opts, "rows", height, &error_abort);
3374 } else {
3375 goto fail;
3378 return opts;
3380 if (strcmp(filename, "con:") == 0) {
3381 qemu_opt_set(opts, "backend", "console", &error_abort);
3382 return opts;
3384 if (strstart(filename, "COM", NULL)) {
3385 qemu_opt_set(opts, "backend", "serial", &error_abort);
3386 qemu_opt_set(opts, "path", filename, &error_abort);
3387 return opts;
3389 if (strstart(filename, "file:", &p)) {
3390 qemu_opt_set(opts, "backend", "file", &error_abort);
3391 qemu_opt_set(opts, "path", p, &error_abort);
3392 return opts;
3394 if (strstart(filename, "pipe:", &p)) {
3395 qemu_opt_set(opts, "backend", "pipe", &error_abort);
3396 qemu_opt_set(opts, "path", p, &error_abort);
3397 return opts;
3399 if (strstart(filename, "tcp:", &p) ||
3400 strstart(filename, "telnet:", &p)) {
3401 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3402 host[0] = 0;
3403 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3404 goto fail;
3406 qemu_opt_set(opts, "backend", "socket", &error_abort);
3407 qemu_opt_set(opts, "host", host, &error_abort);
3408 qemu_opt_set(opts, "port", port, &error_abort);
3409 if (p[pos] == ',') {
3410 qemu_opts_do_parse(opts, p+pos+1, NULL, &local_err);
3411 if (local_err) {
3412 error_report_err(local_err);
3413 goto fail;
3416 if (strstart(filename, "telnet:", &p))
3417 qemu_opt_set(opts, "telnet", "on", &error_abort);
3418 return opts;
3420 if (strstart(filename, "udp:", &p)) {
3421 qemu_opt_set(opts, "backend", "udp", &error_abort);
3422 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3423 host[0] = 0;
3424 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3425 goto fail;
3428 qemu_opt_set(opts, "host", host, &error_abort);
3429 qemu_opt_set(opts, "port", port, &error_abort);
3430 if (p[pos] == '@') {
3431 p += pos + 1;
3432 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3433 host[0] = 0;
3434 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3435 goto fail;
3438 qemu_opt_set(opts, "localaddr", host, &error_abort);
3439 qemu_opt_set(opts, "localport", port, &error_abort);
3441 return opts;
3443 if (strstart(filename, "unix:", &p)) {
3444 qemu_opt_set(opts, "backend", "socket", &error_abort);
3445 qemu_opts_do_parse(opts, p, "path", &local_err);
3446 if (local_err) {
3447 error_report_err(local_err);
3448 goto fail;
3450 return opts;
3452 if (strstart(filename, "/dev/parport", NULL) ||
3453 strstart(filename, "/dev/ppi", NULL)) {
3454 qemu_opt_set(opts, "backend", "parport", &error_abort);
3455 qemu_opt_set(opts, "path", filename, &error_abort);
3456 return opts;
3458 if (strstart(filename, "/dev/", NULL)) {
3459 qemu_opt_set(opts, "backend", "tty", &error_abort);
3460 qemu_opt_set(opts, "path", filename, &error_abort);
3461 return opts;
3464 fail:
3465 qemu_opts_del(opts);
3466 return NULL;
3469 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3470 Error **errp)
3472 const char *path = qemu_opt_get(opts, "path");
3474 if (path == NULL) {
3475 error_setg(errp, "chardev: file: no filename given");
3476 return;
3478 backend->file = g_new0(ChardevFile, 1);
3479 backend->file->out = g_strdup(path);
3482 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3483 Error **errp)
3485 backend->stdio = g_new0(ChardevStdio, 1);
3486 backend->stdio->has_signal = true;
3487 backend->stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3490 #ifdef HAVE_CHARDEV_SERIAL
3491 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3492 Error **errp)
3494 const char *device = qemu_opt_get(opts, "path");
3496 if (device == NULL) {
3497 error_setg(errp, "chardev: serial/tty: no device path given");
3498 return;
3500 backend->serial = g_new0(ChardevHostdev, 1);
3501 backend->serial->device = g_strdup(device);
3503 #endif
3505 #ifdef HAVE_CHARDEV_PARPORT
3506 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3507 Error **errp)
3509 const char *device = qemu_opt_get(opts, "path");
3511 if (device == NULL) {
3512 error_setg(errp, "chardev: parallel: no device path given");
3513 return;
3515 backend->parallel = g_new0(ChardevHostdev, 1);
3516 backend->parallel->device = g_strdup(device);
3518 #endif
3520 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3521 Error **errp)
3523 const char *device = qemu_opt_get(opts, "path");
3525 if (device == NULL) {
3526 error_setg(errp, "chardev: pipe: no device path given");
3527 return;
3529 backend->pipe = g_new0(ChardevHostdev, 1);
3530 backend->pipe->device = g_strdup(device);
3533 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3534 Error **errp)
3536 int val;
3538 backend->ringbuf = g_new0(ChardevRingbuf, 1);
3540 val = qemu_opt_get_size(opts, "size", 0);
3541 if (val != 0) {
3542 backend->ringbuf->has_size = true;
3543 backend->ringbuf->size = val;
3547 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3548 Error **errp)
3550 const char *chardev = qemu_opt_get(opts, "chardev");
3552 if (chardev == NULL) {
3553 error_setg(errp, "chardev: mux: no chardev given");
3554 return;
3556 backend->mux = g_new0(ChardevMux, 1);
3557 backend->mux->chardev = g_strdup(chardev);
3560 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3561 Error **errp)
3563 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3564 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3565 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3566 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3567 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3568 const char *path = qemu_opt_get(opts, "path");
3569 const char *host = qemu_opt_get(opts, "host");
3570 const char *port = qemu_opt_get(opts, "port");
3571 SocketAddress *addr;
3573 if (!path) {
3574 if (!host) {
3575 error_setg(errp, "chardev: socket: no host given");
3576 return;
3578 if (!port) {
3579 error_setg(errp, "chardev: socket: no port given");
3580 return;
3584 backend->socket = g_new0(ChardevSocket, 1);
3586 backend->socket->has_nodelay = true;
3587 backend->socket->nodelay = do_nodelay;
3588 backend->socket->has_server = true;
3589 backend->socket->server = is_listen;
3590 backend->socket->has_telnet = true;
3591 backend->socket->telnet = is_telnet;
3592 backend->socket->has_wait = true;
3593 backend->socket->wait = is_waitconnect;
3594 backend->socket->has_reconnect = true;
3595 backend->socket->reconnect = reconnect;
3597 addr = g_new0(SocketAddress, 1);
3598 if (path) {
3599 addr->kind = SOCKET_ADDRESS_KIND_UNIX;
3600 addr->q_unix = g_new0(UnixSocketAddress, 1);
3601 addr->q_unix->path = g_strdup(path);
3602 } else {
3603 addr->kind = SOCKET_ADDRESS_KIND_INET;
3604 addr->inet = g_new0(InetSocketAddress, 1);
3605 addr->inet->host = g_strdup(host);
3606 addr->inet->port = g_strdup(port);
3607 addr->inet->has_to = qemu_opt_get(opts, "to");
3608 addr->inet->to = qemu_opt_get_number(opts, "to", 0);
3609 addr->inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3610 addr->inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3611 addr->inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3612 addr->inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3614 backend->socket->addr = addr;
3617 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3618 Error **errp)
3620 const char *host = qemu_opt_get(opts, "host");
3621 const char *port = qemu_opt_get(opts, "port");
3622 const char *localaddr = qemu_opt_get(opts, "localaddr");
3623 const char *localport = qemu_opt_get(opts, "localport");
3624 bool has_local = false;
3625 SocketAddress *addr;
3627 if (host == NULL || strlen(host) == 0) {
3628 host = "localhost";
3630 if (port == NULL || strlen(port) == 0) {
3631 error_setg(errp, "chardev: udp: remote port not specified");
3632 return;
3634 if (localport == NULL || strlen(localport) == 0) {
3635 localport = "0";
3636 } else {
3637 has_local = true;
3639 if (localaddr == NULL || strlen(localaddr) == 0) {
3640 localaddr = "";
3641 } else {
3642 has_local = true;
3645 backend->udp = g_new0(ChardevUdp, 1);
3647 addr = g_new0(SocketAddress, 1);
3648 addr->kind = SOCKET_ADDRESS_KIND_INET;
3649 addr->inet = g_new0(InetSocketAddress, 1);
3650 addr->inet->host = g_strdup(host);
3651 addr->inet->port = g_strdup(port);
3652 addr->inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3653 addr->inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3654 addr->inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3655 addr->inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3656 backend->udp->remote = addr;
3658 if (has_local) {
3659 backend->udp->has_local = true;
3660 addr = g_new0(SocketAddress, 1);
3661 addr->kind = SOCKET_ADDRESS_KIND_INET;
3662 addr->inet = g_new0(InetSocketAddress, 1);
3663 addr->inet->host = g_strdup(localaddr);
3664 addr->inet->port = g_strdup(localport);
3665 backend->udp->local = addr;
3669 typedef struct CharDriver {
3670 const char *name;
3671 ChardevBackendKind kind;
3672 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3673 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3674 ChardevReturn *ret, Error **errp);
3675 } CharDriver;
3677 static GSList *backends;
3679 void register_char_driver(const char *name, ChardevBackendKind kind,
3680 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp),
3681 CharDriverState *(*create)(const char *id, ChardevBackend *backend,
3682 ChardevReturn *ret, Error **errp))
3684 CharDriver *s;
3686 s = g_malloc0(sizeof(*s));
3687 s->name = g_strdup(name);
3688 s->kind = kind;
3689 s->parse = parse;
3690 s->create = create;
3692 backends = g_slist_append(backends, s);
3695 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3696 void (*init)(struct CharDriverState *s),
3697 Error **errp)
3699 Error *local_err = NULL;
3700 CharDriver *cd;
3701 CharDriverState *chr;
3702 GSList *i;
3703 ChardevReturn *ret = NULL;
3704 ChardevBackend *backend;
3705 const char *id = qemu_opts_id(opts);
3706 char *bid = NULL;
3708 if (id == NULL) {
3709 error_setg(errp, "chardev: no id specified");
3710 goto err;
3713 if (qemu_opt_get(opts, "backend") == NULL) {
3714 error_setg(errp, "chardev: \"%s\" missing backend",
3715 qemu_opts_id(opts));
3716 goto err;
3718 for (i = backends; i; i = i->next) {
3719 cd = i->data;
3721 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3722 break;
3725 if (i == NULL) {
3726 error_setg(errp, "chardev: backend \"%s\" not found",
3727 qemu_opt_get(opts, "backend"));
3728 goto err;
3731 backend = g_new0(ChardevBackend, 1);
3733 if (qemu_opt_get_bool(opts, "mux", 0)) {
3734 bid = g_strdup_printf("%s-base", id);
3737 chr = NULL;
3738 backend->kind = cd->kind;
3739 if (cd->parse) {
3740 cd->parse(opts, backend, &local_err);
3741 if (local_err) {
3742 error_propagate(errp, local_err);
3743 goto qapi_out;
3746 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3747 if (!ret) {
3748 goto qapi_out;
3751 if (bid) {
3752 qapi_free_ChardevBackend(backend);
3753 qapi_free_ChardevReturn(ret);
3754 backend = g_new0(ChardevBackend, 1);
3755 backend->mux = g_new0(ChardevMux, 1);
3756 backend->kind = CHARDEV_BACKEND_KIND_MUX;
3757 backend->mux->chardev = g_strdup(bid);
3758 ret = qmp_chardev_add(id, backend, errp);
3759 if (!ret) {
3760 chr = qemu_chr_find(bid);
3761 qemu_chr_delete(chr);
3762 chr = NULL;
3763 goto qapi_out;
3767 chr = qemu_chr_find(id);
3768 chr->opts = opts;
3770 qapi_out:
3771 qapi_free_ChardevBackend(backend);
3772 qapi_free_ChardevReturn(ret);
3773 g_free(bid);
3774 return chr;
3776 err:
3777 qemu_opts_del(opts);
3778 return NULL;
3781 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3783 const char *p;
3784 CharDriverState *chr;
3785 QemuOpts *opts;
3786 Error *err = NULL;
3788 if (strstart(filename, "chardev:", &p)) {
3789 return qemu_chr_find(p);
3792 opts = qemu_chr_parse_compat(label, filename);
3793 if (!opts)
3794 return NULL;
3796 chr = qemu_chr_new_from_opts(opts, init, &err);
3797 if (err) {
3798 error_report_err(err);
3800 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3801 qemu_chr_fe_claim_no_fail(chr);
3802 monitor_init(chr, MONITOR_USE_READLINE);
3804 return chr;
3807 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3809 if (chr->chr_set_echo) {
3810 chr->chr_set_echo(chr, echo);
3814 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3816 if (chr->fe_open == fe_open) {
3817 return;
3819 chr->fe_open = fe_open;
3820 if (chr->chr_set_fe_open) {
3821 chr->chr_set_fe_open(chr, fe_open);
3825 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3827 if (chr->chr_fe_event) {
3828 chr->chr_fe_event(chr, event);
3832 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3833 GIOFunc func, void *user_data)
3835 GSource *src;
3836 guint tag;
3838 if (s->chr_add_watch == NULL) {
3839 return -ENOSYS;
3842 src = s->chr_add_watch(s, cond);
3843 if (!src) {
3844 return -EINVAL;
3847 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3848 tag = g_source_attach(src, NULL);
3849 g_source_unref(src);
3851 return tag;
3854 int qemu_chr_fe_claim(CharDriverState *s)
3856 if (s->avail_connections < 1) {
3857 return -1;
3859 s->avail_connections--;
3860 return 0;
3863 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3865 if (qemu_chr_fe_claim(s) != 0) {
3866 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3867 __func__, s->label);
3868 exit(1);
3872 void qemu_chr_fe_release(CharDriverState *s)
3874 s->avail_connections++;
3877 void qemu_chr_delete(CharDriverState *chr)
3879 QTAILQ_REMOVE(&chardevs, chr, next);
3880 if (chr->chr_close) {
3881 chr->chr_close(chr);
3883 g_free(chr->filename);
3884 g_free(chr->label);
3885 qemu_opts_del(chr->opts);
3886 g_free(chr);
3889 ChardevInfoList *qmp_query_chardev(Error **errp)
3891 ChardevInfoList *chr_list = NULL;
3892 CharDriverState *chr;
3894 QTAILQ_FOREACH(chr, &chardevs, next) {
3895 ChardevInfoList *info = g_malloc0(sizeof(*info));
3896 info->value = g_malloc0(sizeof(*info->value));
3897 info->value->label = g_strdup(chr->label);
3898 info->value->filename = g_strdup(chr->filename);
3899 info->value->frontend_open = chr->fe_open;
3901 info->next = chr_list;
3902 chr_list = info;
3905 return chr_list;
3908 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
3910 ChardevBackendInfoList *backend_list = NULL;
3911 CharDriver *c = NULL;
3912 GSList *i = NULL;
3914 for (i = backends; i; i = i->next) {
3915 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
3916 c = i->data;
3917 info->value = g_malloc0(sizeof(*info->value));
3918 info->value->name = g_strdup(c->name);
3920 info->next = backend_list;
3921 backend_list = info;
3924 return backend_list;
3927 CharDriverState *qemu_chr_find(const char *name)
3929 CharDriverState *chr;
3931 QTAILQ_FOREACH(chr, &chardevs, next) {
3932 if (strcmp(chr->label, name) != 0)
3933 continue;
3934 return chr;
3936 return NULL;
3939 /* Get a character (serial) device interface. */
3940 CharDriverState *qemu_char_get_next_serial(void)
3942 static int next_serial;
3943 CharDriverState *chr;
3945 /* FIXME: This function needs to go away: use chardev properties! */
3947 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3948 chr = serial_hds[next_serial++];
3949 qemu_chr_fe_claim_no_fail(chr);
3950 return chr;
3952 return NULL;
3955 QemuOptsList qemu_chardev_opts = {
3956 .name = "chardev",
3957 .implied_opt_name = "backend",
3958 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3959 .desc = {
3961 .name = "backend",
3962 .type = QEMU_OPT_STRING,
3964 .name = "path",
3965 .type = QEMU_OPT_STRING,
3967 .name = "host",
3968 .type = QEMU_OPT_STRING,
3970 .name = "port",
3971 .type = QEMU_OPT_STRING,
3973 .name = "localaddr",
3974 .type = QEMU_OPT_STRING,
3976 .name = "localport",
3977 .type = QEMU_OPT_STRING,
3979 .name = "to",
3980 .type = QEMU_OPT_NUMBER,
3982 .name = "ipv4",
3983 .type = QEMU_OPT_BOOL,
3985 .name = "ipv6",
3986 .type = QEMU_OPT_BOOL,
3988 .name = "wait",
3989 .type = QEMU_OPT_BOOL,
3991 .name = "server",
3992 .type = QEMU_OPT_BOOL,
3994 .name = "delay",
3995 .type = QEMU_OPT_BOOL,
3997 .name = "reconnect",
3998 .type = QEMU_OPT_NUMBER,
4000 .name = "telnet",
4001 .type = QEMU_OPT_BOOL,
4003 .name = "width",
4004 .type = QEMU_OPT_NUMBER,
4006 .name = "height",
4007 .type = QEMU_OPT_NUMBER,
4009 .name = "cols",
4010 .type = QEMU_OPT_NUMBER,
4012 .name = "rows",
4013 .type = QEMU_OPT_NUMBER,
4015 .name = "mux",
4016 .type = QEMU_OPT_BOOL,
4018 .name = "signal",
4019 .type = QEMU_OPT_BOOL,
4021 .name = "name",
4022 .type = QEMU_OPT_STRING,
4024 .name = "debug",
4025 .type = QEMU_OPT_NUMBER,
4027 .name = "size",
4028 .type = QEMU_OPT_SIZE,
4030 .name = "chardev",
4031 .type = QEMU_OPT_STRING,
4033 { /* end of list */ }
4037 #ifdef _WIN32
4039 static CharDriverState *qmp_chardev_open_file(const char *id,
4040 ChardevBackend *backend,
4041 ChardevReturn *ret,
4042 Error **errp)
4044 ChardevFile *file = backend->file;
4045 HANDLE out;
4047 if (file->has_in) {
4048 error_setg(errp, "input file not supported");
4049 return NULL;
4052 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
4053 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
4054 if (out == INVALID_HANDLE_VALUE) {
4055 error_setg(errp, "open %s failed", file->out);
4056 return NULL;
4058 return qemu_chr_open_win_file(out);
4061 static CharDriverState *qmp_chardev_open_serial(const char *id,
4062 ChardevBackend *backend,
4063 ChardevReturn *ret,
4064 Error **errp)
4066 ChardevHostdev *serial = backend->serial;
4067 return qemu_chr_open_win_path(serial->device, errp);
4070 #else /* WIN32 */
4072 static int qmp_chardev_open_file_source(char *src, int flags,
4073 Error **errp)
4075 int fd = -1;
4077 TFR(fd = qemu_open(src, flags, 0666));
4078 if (fd == -1) {
4079 error_setg_file_open(errp, errno, src);
4081 return fd;
4084 static CharDriverState *qmp_chardev_open_file(const char *id,
4085 ChardevBackend *backend,
4086 ChardevReturn *ret,
4087 Error **errp)
4089 ChardevFile *file = backend->file;
4090 int flags, in = -1, out;
4092 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
4093 out = qmp_chardev_open_file_source(file->out, flags, errp);
4094 if (out < 0) {
4095 return NULL;
4098 if (file->has_in) {
4099 flags = O_RDONLY;
4100 in = qmp_chardev_open_file_source(file->in, flags, errp);
4101 if (in < 0) {
4102 qemu_close(out);
4103 return NULL;
4107 return qemu_chr_open_fd(in, out);
4110 #ifdef HAVE_CHARDEV_SERIAL
4111 static CharDriverState *qmp_chardev_open_serial(const char *id,
4112 ChardevBackend *backend,
4113 ChardevReturn *ret,
4114 Error **errp)
4116 ChardevHostdev *serial = backend->serial;
4117 int fd;
4119 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4120 if (fd < 0) {
4121 return NULL;
4123 qemu_set_nonblock(fd);
4124 return qemu_chr_open_tty_fd(fd);
4126 #endif
4128 #ifdef HAVE_CHARDEV_PARPORT
4129 static CharDriverState *qmp_chardev_open_parallel(const char *id,
4130 ChardevBackend *backend,
4131 ChardevReturn *ret,
4132 Error **errp)
4134 ChardevHostdev *parallel = backend->parallel;
4135 int fd;
4137 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4138 if (fd < 0) {
4139 return NULL;
4141 return qemu_chr_open_pp_fd(fd, errp);
4143 #endif
4145 #endif /* WIN32 */
4147 static void socket_try_connect(CharDriverState *chr)
4149 Error *err = NULL;
4151 if (!qemu_chr_open_socket_fd(chr, &err)) {
4152 check_report_connect_error(chr, err);
4156 static gboolean socket_reconnect_timeout(gpointer opaque)
4158 CharDriverState *chr = opaque;
4159 TCPCharDriver *s = chr->opaque;
4161 s->reconnect_timer = 0;
4163 if (chr->be_open) {
4164 return false;
4167 socket_try_connect(chr);
4169 return false;
4172 static CharDriverState *qmp_chardev_open_socket(const char *id,
4173 ChardevBackend *backend,
4174 ChardevReturn *ret,
4175 Error **errp)
4177 CharDriverState *chr;
4178 TCPCharDriver *s;
4179 ChardevSocket *sock = backend->socket;
4180 SocketAddress *addr = sock->addr;
4181 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4182 bool is_listen = sock->has_server ? sock->server : true;
4183 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4184 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4185 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4187 chr = qemu_chr_alloc();
4188 s = g_new0(TCPCharDriver, 1);
4190 s->fd = -1;
4191 s->listen_fd = -1;
4192 s->is_unix = addr->kind == SOCKET_ADDRESS_KIND_UNIX;
4193 s->is_listen = is_listen;
4194 s->is_telnet = is_telnet;
4195 s->do_nodelay = do_nodelay;
4196 qapi_copy_SocketAddress(&s->addr, sock->addr);
4198 chr->opaque = s;
4199 chr->chr_write = tcp_chr_write;
4200 chr->chr_sync_read = tcp_chr_sync_read;
4201 chr->chr_close = tcp_chr_close;
4202 chr->get_msgfds = tcp_get_msgfds;
4203 chr->set_msgfds = tcp_set_msgfds;
4204 chr->chr_add_client = tcp_chr_add_client;
4205 chr->chr_add_watch = tcp_chr_add_watch;
4206 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4207 /* be isn't opened until we get a connection */
4208 chr->explicit_be_open = true;
4210 chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
4211 SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, "disconnected:",
4212 addr, is_listen, is_telnet);
4214 if (is_listen) {
4215 if (is_telnet) {
4216 s->do_telnetopt = 1;
4218 } else if (reconnect > 0) {
4219 s->reconnect_time = reconnect;
4222 if (s->reconnect_time) {
4223 socket_try_connect(chr);
4224 } else if (!qemu_chr_open_socket_fd(chr, errp)) {
4225 g_free(s);
4226 g_free(chr->filename);
4227 g_free(chr);
4228 return NULL;
4231 if (is_listen && is_waitconnect) {
4232 fprintf(stderr, "QEMU waiting for connection on: %s\n",
4233 chr->filename);
4234 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
4235 qemu_set_nonblock(s->listen_fd);
4238 return chr;
4241 static CharDriverState *qmp_chardev_open_udp(const char *id,
4242 ChardevBackend *backend,
4243 ChardevReturn *ret,
4244 Error **errp)
4246 ChardevUdp *udp = backend->udp;
4247 int fd;
4249 fd = socket_dgram(udp->remote, udp->local, errp);
4250 if (fd < 0) {
4251 return NULL;
4253 return qemu_chr_open_udp_fd(fd);
4256 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4257 Error **errp)
4259 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4260 CharDriverState *chr = NULL;
4261 Error *local_err = NULL;
4262 GSList *i;
4263 CharDriver *cd;
4265 chr = qemu_chr_find(id);
4266 if (chr) {
4267 error_setg(errp, "Chardev '%s' already exists", id);
4268 g_free(ret);
4269 return NULL;
4272 for (i = backends; i; i = i->next) {
4273 cd = i->data;
4275 if (cd->kind == backend->kind && cd->create) {
4276 chr = cd->create(id, backend, ret, &local_err);
4277 if (local_err) {
4278 error_propagate(errp, local_err);
4279 goto out_error;
4281 break;
4285 if (chr == NULL) {
4286 switch (backend->kind) {
4287 case CHARDEV_BACKEND_KIND_FILE:
4288 abort();
4289 break;
4290 case CHARDEV_BACKEND_KIND_SERIAL:
4291 abort();
4292 break;
4293 case CHARDEV_BACKEND_KIND_PARALLEL:
4294 abort();
4295 break;
4296 case CHARDEV_BACKEND_KIND_PIPE:
4297 abort();
4298 break;
4299 case CHARDEV_BACKEND_KIND_SOCKET:
4300 abort();
4301 break;
4302 case CHARDEV_BACKEND_KIND_UDP:
4303 abort();
4304 break;
4305 case CHARDEV_BACKEND_KIND_PTY:
4306 abort();
4307 break;
4308 case CHARDEV_BACKEND_KIND_NULL:
4309 abort();
4310 break;
4311 case CHARDEV_BACKEND_KIND_MUX:
4312 abort();
4313 break;
4314 case CHARDEV_BACKEND_KIND_MSMOUSE:
4315 chr = qemu_chr_open_msmouse();
4316 break;
4317 #ifdef CONFIG_BRLAPI
4318 case CHARDEV_BACKEND_KIND_BRAILLE:
4319 chr = chr_baum_init();
4320 break;
4321 #endif
4322 case CHARDEV_BACKEND_KIND_TESTDEV:
4323 chr = chr_testdev_init();
4324 break;
4325 case CHARDEV_BACKEND_KIND_STDIO:
4326 chr = qemu_chr_open_stdio(backend->stdio);
4327 break;
4328 #ifdef _WIN32
4329 case CHARDEV_BACKEND_KIND_CONSOLE:
4330 chr = qemu_chr_open_win_con();
4331 break;
4332 #endif
4333 #ifdef CONFIG_SPICE
4334 case CHARDEV_BACKEND_KIND_SPICEVMC:
4335 chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
4336 break;
4337 case CHARDEV_BACKEND_KIND_SPICEPORT:
4338 chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
4339 break;
4340 #endif
4341 case CHARDEV_BACKEND_KIND_VC:
4342 chr = vc_init(backend->vc);
4343 break;
4344 case CHARDEV_BACKEND_KIND_RINGBUF:
4345 case CHARDEV_BACKEND_KIND_MEMORY:
4346 chr = qemu_chr_open_ringbuf(backend->ringbuf, &local_err);
4347 break;
4348 default:
4349 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
4350 goto out_error;
4354 * Character backend open hasn't been fully converted to the Error
4355 * API. Some opens fail without setting an error. Set a generic
4356 * error then.
4357 * TODO full conversion to Error API
4359 if (chr == NULL) {
4360 if (local_err) {
4361 error_propagate(errp, local_err);
4362 } else {
4363 error_setg(errp, "Failed to create chardev");
4365 goto out_error;
4369 chr->label = g_strdup(id);
4370 chr->avail_connections =
4371 (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4372 if (!chr->filename) {
4373 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
4375 if (!chr->explicit_be_open) {
4376 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4378 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4379 return ret;
4381 out_error:
4382 g_free(ret);
4383 return NULL;
4386 void qmp_chardev_remove(const char *id, Error **errp)
4388 CharDriverState *chr;
4390 chr = qemu_chr_find(id);
4391 if (chr == NULL) {
4392 error_setg(errp, "Chardev '%s' not found", id);
4393 return;
4395 if (chr->chr_can_read || chr->chr_read ||
4396 chr->chr_event || chr->handler_opaque) {
4397 error_setg(errp, "Chardev '%s' is busy", id);
4398 return;
4400 qemu_chr_delete(chr);
4403 static void register_types(void)
4405 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,
4406 qemu_chr_open_null);
4407 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4408 qemu_chr_parse_socket, qmp_chardev_open_socket);
4409 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,
4410 qmp_chardev_open_udp);
4411 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4412 qemu_chr_parse_ringbuf, NULL);
4413 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4414 qemu_chr_parse_file_out, qmp_chardev_open_file);
4415 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4416 qemu_chr_parse_stdio, NULL);
4417 #if defined HAVE_CHARDEV_SERIAL
4418 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4419 qemu_chr_parse_serial, qmp_chardev_open_serial);
4420 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4421 qemu_chr_parse_serial, qmp_chardev_open_serial);
4422 #endif
4423 #ifdef HAVE_CHARDEV_PARPORT
4424 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4425 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4426 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4427 qemu_chr_parse_parallel, qmp_chardev_open_parallel);
4428 #endif
4429 #ifdef HAVE_CHARDEV_PTY
4430 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,
4431 qemu_chr_open_pty);
4432 #endif
4433 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,
4434 NULL);
4435 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4436 qemu_chr_parse_pipe, qemu_chr_open_pipe);
4437 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,
4438 qemu_chr_open_mux);
4439 /* Bug-compatibility: */
4440 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4441 qemu_chr_parse_ringbuf, NULL);
4442 /* this must be done after machine init, since we register FEs with muxes
4443 * as part of realize functions like serial_isa_realizefn when -nographic
4444 * is specified
4446 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4449 type_init(register_types);