s390x/kvm: sync register support helper function
[qemu/ar7.git] / qemu-char.c
blobef84b5368160edcb710a41ad0b3085597c057978
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/timer.h"
28 #include "sysemu/char.h"
29 #include "hw/usb.h"
30 #include "qmp-commands.h"
31 #include "qapi/qmp-input-visitor.h"
32 #include "qapi/qmp-output-visitor.h"
33 #include "qapi-visit.h"
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <time.h>
38 #include <errno.h>
39 #include <sys/time.h>
40 #include <zlib.h>
42 #ifndef _WIN32
43 #include <sys/times.h>
44 #include <sys/wait.h>
45 #include <termios.h>
46 #include <sys/mman.h>
47 #include <sys/ioctl.h>
48 #include <sys/resource.h>
49 #include <sys/socket.h>
50 #include <netinet/in.h>
51 #include <net/if.h>
52 #include <arpa/inet.h>
53 #include <dirent.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(void)
388 CharDriverState *chr;
390 chr = qemu_chr_alloc();
391 chr->chr_write = null_chr_write;
392 chr->explicit_be_open = true;
393 return chr;
396 /* MUX driver for serial I/O splitting */
397 #define MAX_MUX 4
398 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
399 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
400 typedef struct {
401 IOCanReadHandler *chr_can_read[MAX_MUX];
402 IOReadHandler *chr_read[MAX_MUX];
403 IOEventHandler *chr_event[MAX_MUX];
404 void *ext_opaque[MAX_MUX];
405 CharDriverState *drv;
406 int focus;
407 int mux_cnt;
408 int term_got_escape;
409 int max_size;
410 /* Intermediate input buffer allows to catch escape sequences even if the
411 currently active device is not accepting any input - but only until it
412 is full as well. */
413 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
414 int prod[MAX_MUX];
415 int cons[MAX_MUX];
416 int timestamps;
418 /* Protected by the CharDriverState chr_write_lock. */
419 int linestart;
420 int64_t timestamps_start;
421 } MuxDriver;
424 /* Called with chr_write_lock held. */
425 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
427 MuxDriver *d = chr->opaque;
428 int ret;
429 if (!d->timestamps) {
430 ret = qemu_chr_fe_write(d->drv, buf, len);
431 } else {
432 int i;
434 ret = 0;
435 for (i = 0; i < len; i++) {
436 if (d->linestart) {
437 char buf1[64];
438 int64_t ti;
439 int secs;
441 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
442 if (d->timestamps_start == -1)
443 d->timestamps_start = ti;
444 ti -= d->timestamps_start;
445 secs = ti / 1000;
446 snprintf(buf1, sizeof(buf1),
447 "[%02d:%02d:%02d.%03d] ",
448 secs / 3600,
449 (secs / 60) % 60,
450 secs % 60,
451 (int)(ti % 1000));
452 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
453 d->linestart = 0;
455 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
456 if (buf[i] == '\n') {
457 d->linestart = 1;
461 return ret;
464 static const char * const mux_help[] = {
465 "% h print this help\n\r",
466 "% x exit emulator\n\r",
467 "% s save disk data back to file (if -snapshot)\n\r",
468 "% t toggle console timestamps\n\r",
469 "% b send break (magic sysrq)\n\r",
470 "% c switch between console and monitor\n\r",
471 "% % sends %\n\r",
472 NULL
475 int term_escape_char = 0x01; /* ctrl-a is used for escape */
476 static void mux_print_help(CharDriverState *chr)
478 int i, j;
479 char ebuf[15] = "Escape-Char";
480 char cbuf[50] = "\n\r";
482 if (term_escape_char > 0 && term_escape_char < 26) {
483 snprintf(cbuf, sizeof(cbuf), "\n\r");
484 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
485 } else {
486 snprintf(cbuf, sizeof(cbuf),
487 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
488 term_escape_char);
490 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
491 for (i = 0; mux_help[i] != NULL; i++) {
492 for (j=0; mux_help[i][j] != '\0'; j++) {
493 if (mux_help[i][j] == '%')
494 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
495 else
496 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
501 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
503 if (d->chr_event[mux_nr])
504 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
507 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
509 if (d->term_got_escape) {
510 d->term_got_escape = 0;
511 if (ch == term_escape_char)
512 goto send_char;
513 switch(ch) {
514 case '?':
515 case 'h':
516 mux_print_help(chr);
517 break;
518 case 'x':
520 const char *term = "QEMU: Terminated\n\r";
521 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
522 exit(0);
523 break;
525 case 's':
526 bdrv_commit_all();
527 break;
528 case 'b':
529 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
530 break;
531 case 'c':
532 /* Switch to the next registered device */
533 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
534 d->focus++;
535 if (d->focus >= d->mux_cnt)
536 d->focus = 0;
537 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
538 break;
539 case 't':
540 d->timestamps = !d->timestamps;
541 d->timestamps_start = -1;
542 d->linestart = 0;
543 break;
545 } else if (ch == term_escape_char) {
546 d->term_got_escape = 1;
547 } else {
548 send_char:
549 return 1;
551 return 0;
554 static void mux_chr_accept_input(CharDriverState *chr)
556 MuxDriver *d = chr->opaque;
557 int m = d->focus;
559 while (d->prod[m] != d->cons[m] &&
560 d->chr_can_read[m] &&
561 d->chr_can_read[m](d->ext_opaque[m])) {
562 d->chr_read[m](d->ext_opaque[m],
563 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
567 static int mux_chr_can_read(void *opaque)
569 CharDriverState *chr = opaque;
570 MuxDriver *d = chr->opaque;
571 int m = d->focus;
573 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
574 return 1;
575 if (d->chr_can_read[m])
576 return d->chr_can_read[m](d->ext_opaque[m]);
577 return 0;
580 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
582 CharDriverState *chr = opaque;
583 MuxDriver *d = chr->opaque;
584 int m = d->focus;
585 int i;
587 mux_chr_accept_input (opaque);
589 for(i = 0; i < size; i++)
590 if (mux_proc_byte(chr, d, buf[i])) {
591 if (d->prod[m] == d->cons[m] &&
592 d->chr_can_read[m] &&
593 d->chr_can_read[m](d->ext_opaque[m]))
594 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
595 else
596 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
600 static void mux_chr_event(void *opaque, int event)
602 CharDriverState *chr = opaque;
603 MuxDriver *d = chr->opaque;
604 int i;
606 /* Send the event to all registered listeners */
607 for (i = 0; i < d->mux_cnt; i++)
608 mux_chr_send_event(d, i, event);
611 static void mux_chr_update_read_handler(CharDriverState *chr)
613 MuxDriver *d = chr->opaque;
615 if (d->mux_cnt >= MAX_MUX) {
616 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
617 return;
619 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
620 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
621 d->chr_read[d->mux_cnt] = chr->chr_read;
622 d->chr_event[d->mux_cnt] = chr->chr_event;
623 /* Fix up the real driver with mux routines */
624 if (d->mux_cnt == 0) {
625 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
626 mux_chr_event, chr);
628 if (d->focus != -1) {
629 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
631 d->focus = d->mux_cnt;
632 d->mux_cnt++;
633 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
636 static bool muxes_realized;
639 * Called after processing of default and command-line-specified
640 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
641 * to a mux chardev. This is done here to ensure that
642 * output/prompts/banners are only displayed for the FE that has
643 * focus when initial command-line processing/machine init is
644 * completed.
646 * After this point, any new FE attached to any new or existing
647 * mux will receive CHR_EVENT_OPENED notifications for the BE
648 * immediately.
650 static void muxes_realize_done(Notifier *notifier, void *unused)
652 CharDriverState *chr;
654 QTAILQ_FOREACH(chr, &chardevs, next) {
655 if (chr->is_mux) {
656 MuxDriver *d = chr->opaque;
657 int i;
659 /* send OPENED to all already-attached FEs */
660 for (i = 0; i < d->mux_cnt; i++) {
661 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
663 /* mark mux as OPENED so any new FEs will immediately receive
664 * OPENED event
666 qemu_chr_be_generic_open(chr);
669 muxes_realized = true;
672 static Notifier muxes_realize_notify = {
673 .notify = muxes_realize_done,
676 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
678 MuxDriver *d = s->opaque;
679 return d->drv->chr_add_watch(d->drv, cond);
682 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
684 CharDriverState *chr;
685 MuxDriver *d;
687 chr = qemu_chr_alloc();
688 d = g_malloc0(sizeof(MuxDriver));
690 chr->opaque = d;
691 d->drv = drv;
692 d->focus = -1;
693 chr->chr_write = mux_chr_write;
694 chr->chr_update_read_handler = mux_chr_update_read_handler;
695 chr->chr_accept_input = mux_chr_accept_input;
696 /* Frontend guest-open / -close notification is not support with muxes */
697 chr->chr_set_fe_open = NULL;
698 if (drv->chr_add_watch) {
699 chr->chr_add_watch = mux_chr_add_watch;
701 /* only default to opened state if we've realized the initial
702 * set of muxes
704 chr->explicit_be_open = muxes_realized ? 0 : 1;
705 chr->is_mux = 1;
707 return chr;
711 #ifdef _WIN32
712 int send_all(int fd, const void *buf, int len1)
714 int ret, len;
716 len = len1;
717 while (len > 0) {
718 ret = send(fd, buf, len, 0);
719 if (ret < 0) {
720 errno = WSAGetLastError();
721 if (errno != WSAEWOULDBLOCK) {
722 return -1;
724 } else if (ret == 0) {
725 break;
726 } else {
727 buf += ret;
728 len -= ret;
731 return len1 - len;
734 #else
736 int send_all(int fd, const void *_buf, int len1)
738 int ret, len;
739 const uint8_t *buf = _buf;
741 len = len1;
742 while (len > 0) {
743 ret = write(fd, buf, len);
744 if (ret < 0) {
745 if (errno != EINTR && errno != EAGAIN)
746 return -1;
747 } else if (ret == 0) {
748 break;
749 } else {
750 buf += ret;
751 len -= ret;
754 return len1 - len;
757 int recv_all(int fd, void *_buf, int len1, bool single_read)
759 int ret, len;
760 uint8_t *buf = _buf;
762 len = len1;
763 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
764 if (ret < 0) {
765 if (errno != EINTR && errno != EAGAIN) {
766 return -1;
768 continue;
769 } else {
770 if (single_read) {
771 return ret;
773 buf += ret;
774 len -= ret;
777 return len1 - len;
780 #endif /* !_WIN32 */
782 typedef struct IOWatchPoll
784 GSource parent;
786 GIOChannel *channel;
787 GSource *src;
789 IOCanReadHandler *fd_can_read;
790 GSourceFunc fd_read;
791 void *opaque;
792 } IOWatchPoll;
794 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
796 return container_of(source, IOWatchPoll, parent);
799 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
801 IOWatchPoll *iwp = io_watch_poll_from_source(source);
802 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
803 bool was_active = iwp->src != NULL;
804 if (was_active == now_active) {
805 return FALSE;
808 if (now_active) {
809 iwp->src = g_io_create_watch(iwp->channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
810 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
811 g_source_attach(iwp->src, NULL);
812 } else {
813 g_source_destroy(iwp->src);
814 g_source_unref(iwp->src);
815 iwp->src = NULL;
817 return FALSE;
820 static gboolean io_watch_poll_check(GSource *source)
822 return FALSE;
825 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
826 gpointer user_data)
828 abort();
831 static void io_watch_poll_finalize(GSource *source)
833 /* Due to a glib bug, removing the last reference to a source
834 * inside a finalize callback causes recursive locking (and a
835 * deadlock). This is not a problem inside other callbacks,
836 * including dispatch callbacks, so we call io_remove_watch_poll
837 * to remove this source. At this point, iwp->src must
838 * be NULL, or we would leak it.
840 * This would be solved much more elegantly by child sources,
841 * but we support older glib versions that do not have them.
843 IOWatchPoll *iwp = io_watch_poll_from_source(source);
844 assert(iwp->src == NULL);
847 static GSourceFuncs io_watch_poll_funcs = {
848 .prepare = io_watch_poll_prepare,
849 .check = io_watch_poll_check,
850 .dispatch = io_watch_poll_dispatch,
851 .finalize = io_watch_poll_finalize,
854 /* Can only be used for read */
855 static guint io_add_watch_poll(GIOChannel *channel,
856 IOCanReadHandler *fd_can_read,
857 GIOFunc fd_read,
858 gpointer user_data)
860 IOWatchPoll *iwp;
861 int tag;
863 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
864 iwp->fd_can_read = fd_can_read;
865 iwp->opaque = user_data;
866 iwp->channel = channel;
867 iwp->fd_read = (GSourceFunc) fd_read;
868 iwp->src = NULL;
870 tag = g_source_attach(&iwp->parent, NULL);
871 g_source_unref(&iwp->parent);
872 return tag;
875 static void io_remove_watch_poll(guint tag)
877 GSource *source;
878 IOWatchPoll *iwp;
880 g_return_if_fail (tag > 0);
882 source = g_main_context_find_source_by_id(NULL, tag);
883 g_return_if_fail (source != NULL);
885 iwp = io_watch_poll_from_source(source);
886 if (iwp->src) {
887 g_source_destroy(iwp->src);
888 g_source_unref(iwp->src);
889 iwp->src = NULL;
891 g_source_destroy(&iwp->parent);
894 static void remove_fd_in_watch(CharDriverState *chr)
896 if (chr->fd_in_tag) {
897 io_remove_watch_poll(chr->fd_in_tag);
898 chr->fd_in_tag = 0;
902 #ifndef _WIN32
903 static GIOChannel *io_channel_from_fd(int fd)
905 GIOChannel *chan;
907 if (fd == -1) {
908 return NULL;
911 chan = g_io_channel_unix_new(fd);
913 g_io_channel_set_encoding(chan, NULL, NULL);
914 g_io_channel_set_buffered(chan, FALSE);
916 return chan;
918 #endif
920 static GIOChannel *io_channel_from_socket(int fd)
922 GIOChannel *chan;
924 if (fd == -1) {
925 return NULL;
928 #ifdef _WIN32
929 chan = g_io_channel_win32_new_socket(fd);
930 #else
931 chan = g_io_channel_unix_new(fd);
932 #endif
934 g_io_channel_set_encoding(chan, NULL, NULL);
935 g_io_channel_set_buffered(chan, FALSE);
937 return chan;
940 static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
942 size_t offset = 0;
943 GIOStatus status = G_IO_STATUS_NORMAL;
945 while (offset < len && status == G_IO_STATUS_NORMAL) {
946 gsize bytes_written = 0;
948 status = g_io_channel_write_chars(fd, buf + offset, len - offset,
949 &bytes_written, NULL);
950 offset += bytes_written;
953 if (offset > 0) {
954 return offset;
956 switch (status) {
957 case G_IO_STATUS_NORMAL:
958 g_assert(len == 0);
959 return 0;
960 case G_IO_STATUS_AGAIN:
961 errno = EAGAIN;
962 return -1;
963 default:
964 break;
966 errno = EINVAL;
967 return -1;
970 #ifndef _WIN32
972 typedef struct FDCharDriver {
973 CharDriverState *chr;
974 GIOChannel *fd_in, *fd_out;
975 int max_size;
976 QTAILQ_ENTRY(FDCharDriver) node;
977 } FDCharDriver;
979 /* Called with chr_write_lock held. */
980 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
982 FDCharDriver *s = chr->opaque;
984 return io_channel_send(s->fd_out, buf, len);
987 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
989 CharDriverState *chr = opaque;
990 FDCharDriver *s = chr->opaque;
991 int len;
992 uint8_t buf[READ_BUF_LEN];
993 GIOStatus status;
994 gsize bytes_read;
996 len = sizeof(buf);
997 if (len > s->max_size) {
998 len = s->max_size;
1000 if (len == 0) {
1001 return TRUE;
1004 status = g_io_channel_read_chars(chan, (gchar *)buf,
1005 len, &bytes_read, NULL);
1006 if (status == G_IO_STATUS_EOF) {
1007 remove_fd_in_watch(chr);
1008 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1009 return FALSE;
1011 if (status == G_IO_STATUS_NORMAL) {
1012 qemu_chr_be_write(chr, buf, bytes_read);
1015 return TRUE;
1018 static int fd_chr_read_poll(void *opaque)
1020 CharDriverState *chr = opaque;
1021 FDCharDriver *s = chr->opaque;
1023 s->max_size = qemu_chr_be_can_write(chr);
1024 return s->max_size;
1027 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1029 FDCharDriver *s = chr->opaque;
1030 return g_io_create_watch(s->fd_out, cond);
1033 static void fd_chr_update_read_handler(CharDriverState *chr)
1035 FDCharDriver *s = chr->opaque;
1037 remove_fd_in_watch(chr);
1038 if (s->fd_in) {
1039 chr->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll,
1040 fd_chr_read, chr);
1044 static void fd_chr_close(struct CharDriverState *chr)
1046 FDCharDriver *s = chr->opaque;
1048 remove_fd_in_watch(chr);
1049 if (s->fd_in) {
1050 g_io_channel_unref(s->fd_in);
1052 if (s->fd_out) {
1053 g_io_channel_unref(s->fd_out);
1056 g_free(s);
1057 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1060 /* open a character device to a unix fd */
1061 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1063 CharDriverState *chr;
1064 FDCharDriver *s;
1066 chr = qemu_chr_alloc();
1067 s = g_malloc0(sizeof(FDCharDriver));
1068 s->fd_in = io_channel_from_fd(fd_in);
1069 s->fd_out = io_channel_from_fd(fd_out);
1070 qemu_set_nonblock(fd_out);
1071 s->chr = chr;
1072 chr->opaque = s;
1073 chr->chr_add_watch = fd_chr_add_watch;
1074 chr->chr_write = fd_chr_write;
1075 chr->chr_update_read_handler = fd_chr_update_read_handler;
1076 chr->chr_close = fd_chr_close;
1078 return chr;
1081 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
1083 int fd_in, fd_out;
1084 char filename_in[CHR_MAX_FILENAME_SIZE];
1085 char filename_out[CHR_MAX_FILENAME_SIZE];
1086 const char *filename = opts->device;
1088 if (filename == NULL) {
1089 fprintf(stderr, "chardev: pipe: no filename given\n");
1090 return NULL;
1093 snprintf(filename_in, CHR_MAX_FILENAME_SIZE, "%s.in", filename);
1094 snprintf(filename_out, CHR_MAX_FILENAME_SIZE, "%s.out", filename);
1095 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1096 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1097 if (fd_in < 0 || fd_out < 0) {
1098 if (fd_in >= 0)
1099 close(fd_in);
1100 if (fd_out >= 0)
1101 close(fd_out);
1102 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1103 if (fd_in < 0) {
1104 return NULL;
1107 return qemu_chr_open_fd(fd_in, fd_out);
1110 /* init terminal so that we can grab keys */
1111 static struct termios oldtty;
1112 static int old_fd0_flags;
1113 static bool stdio_in_use;
1114 static bool stdio_allow_signal;
1116 static void term_exit(void)
1118 tcsetattr (0, TCSANOW, &oldtty);
1119 fcntl(0, F_SETFL, old_fd0_flags);
1122 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1124 struct termios tty;
1126 tty = oldtty;
1127 if (!echo) {
1128 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1129 |INLCR|IGNCR|ICRNL|IXON);
1130 tty.c_oflag |= OPOST;
1131 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1132 tty.c_cflag &= ~(CSIZE|PARENB);
1133 tty.c_cflag |= CS8;
1134 tty.c_cc[VMIN] = 1;
1135 tty.c_cc[VTIME] = 0;
1137 if (!stdio_allow_signal)
1138 tty.c_lflag &= ~ISIG;
1140 tcsetattr (0, TCSANOW, &tty);
1143 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1145 term_exit();
1146 fd_chr_close(chr);
1149 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
1151 CharDriverState *chr;
1153 if (is_daemonized()) {
1154 error_report("cannot use stdio with -daemonize");
1155 return NULL;
1158 if (stdio_in_use) {
1159 error_report("cannot use stdio by multiple character devices");
1160 exit(1);
1163 stdio_in_use = true;
1164 old_fd0_flags = fcntl(0, F_GETFL);
1165 tcgetattr(0, &oldtty);
1166 qemu_set_nonblock(0);
1167 atexit(term_exit);
1169 chr = qemu_chr_open_fd(0, 1);
1170 chr->chr_close = qemu_chr_close_stdio;
1171 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1172 if (opts->has_signal) {
1173 stdio_allow_signal = opts->signal;
1175 qemu_chr_fe_set_echo(chr, false);
1177 return chr;
1180 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1181 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1182 || defined(__GLIBC__)
1184 #define HAVE_CHARDEV_TTY 1
1186 typedef struct {
1187 GIOChannel *fd;
1188 int read_bytes;
1190 /* Protected by the CharDriverState chr_write_lock. */
1191 int connected;
1192 guint timer_tag;
1193 guint open_tag;
1194 } PtyCharDriver;
1196 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1197 static void pty_chr_state(CharDriverState *chr, int connected);
1199 static gboolean pty_chr_timer(gpointer opaque)
1201 struct CharDriverState *chr = opaque;
1202 PtyCharDriver *s = chr->opaque;
1204 qemu_mutex_lock(&chr->chr_write_lock);
1205 s->timer_tag = 0;
1206 s->open_tag = 0;
1207 if (!s->connected) {
1208 /* Next poll ... */
1209 pty_chr_update_read_handler_locked(chr);
1211 qemu_mutex_unlock(&chr->chr_write_lock);
1212 return FALSE;
1215 /* Called with chr_write_lock held. */
1216 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1218 PtyCharDriver *s = chr->opaque;
1220 if (s->timer_tag) {
1221 g_source_remove(s->timer_tag);
1222 s->timer_tag = 0;
1225 if (ms == 1000) {
1226 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1227 } else {
1228 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1232 /* Called with chr_write_lock held. */
1233 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1235 PtyCharDriver *s = chr->opaque;
1236 GPollFD pfd;
1238 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1239 pfd.events = G_IO_OUT;
1240 pfd.revents = 0;
1241 g_poll(&pfd, 1, 0);
1242 if (pfd.revents & G_IO_HUP) {
1243 pty_chr_state(chr, 0);
1244 } else {
1245 pty_chr_state(chr, 1);
1249 static void pty_chr_update_read_handler(CharDriverState *chr)
1251 qemu_mutex_lock(&chr->chr_write_lock);
1252 pty_chr_update_read_handler_locked(chr);
1253 qemu_mutex_unlock(&chr->chr_write_lock);
1256 /* Called with chr_write_lock held. */
1257 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1259 PtyCharDriver *s = chr->opaque;
1261 if (!s->connected) {
1262 /* guest sends data, check for (re-)connect */
1263 pty_chr_update_read_handler_locked(chr);
1264 if (!s->connected) {
1265 return 0;
1268 return io_channel_send(s->fd, buf, len);
1271 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1273 PtyCharDriver *s = chr->opaque;
1274 if (!s->connected) {
1275 return NULL;
1277 return g_io_create_watch(s->fd, cond);
1280 static int pty_chr_read_poll(void *opaque)
1282 CharDriverState *chr = opaque;
1283 PtyCharDriver *s = chr->opaque;
1285 s->read_bytes = qemu_chr_be_can_write(chr);
1286 return s->read_bytes;
1289 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1291 CharDriverState *chr = opaque;
1292 PtyCharDriver *s = chr->opaque;
1293 gsize size, len;
1294 uint8_t buf[READ_BUF_LEN];
1295 GIOStatus status;
1297 len = sizeof(buf);
1298 if (len > s->read_bytes)
1299 len = s->read_bytes;
1300 if (len == 0) {
1301 return TRUE;
1303 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1304 if (status != G_IO_STATUS_NORMAL) {
1305 pty_chr_state(chr, 0);
1306 return FALSE;
1307 } else {
1308 pty_chr_state(chr, 1);
1309 qemu_chr_be_write(chr, buf, size);
1311 return TRUE;
1314 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1316 CharDriverState *chr = opaque;
1317 PtyCharDriver *s = chr->opaque;
1319 s->open_tag = 0;
1320 qemu_chr_be_generic_open(chr);
1321 return FALSE;
1324 /* Called with chr_write_lock held. */
1325 static void pty_chr_state(CharDriverState *chr, int connected)
1327 PtyCharDriver *s = chr->opaque;
1329 if (!connected) {
1330 if (s->open_tag) {
1331 g_source_remove(s->open_tag);
1332 s->open_tag = 0;
1334 remove_fd_in_watch(chr);
1335 s->connected = 0;
1336 /* (re-)connect poll interval for idle guests: once per second.
1337 * We check more frequently in case the guests sends data to
1338 * the virtual device linked to our pty. */
1339 pty_chr_rearm_timer(chr, 1000);
1340 } else {
1341 if (s->timer_tag) {
1342 g_source_remove(s->timer_tag);
1343 s->timer_tag = 0;
1345 if (!s->connected) {
1346 g_assert(s->open_tag == 0);
1347 s->connected = 1;
1348 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1350 if (!chr->fd_in_tag) {
1351 chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
1352 pty_chr_read, chr);
1357 static void pty_chr_close(struct CharDriverState *chr)
1359 PtyCharDriver *s = chr->opaque;
1360 int fd;
1362 qemu_mutex_lock(&chr->chr_write_lock);
1363 pty_chr_state(chr, 0);
1364 fd = g_io_channel_unix_get_fd(s->fd);
1365 g_io_channel_unref(s->fd);
1366 close(fd);
1367 if (s->timer_tag) {
1368 g_source_remove(s->timer_tag);
1369 s->timer_tag = 0;
1371 qemu_mutex_unlock(&chr->chr_write_lock);
1372 g_free(s);
1373 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1376 static CharDriverState *qemu_chr_open_pty(const char *id,
1377 ChardevReturn *ret)
1379 CharDriverState *chr;
1380 PtyCharDriver *s;
1381 int master_fd, slave_fd;
1382 char pty_name[PATH_MAX];
1384 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1385 if (master_fd < 0) {
1386 return NULL;
1389 close(slave_fd);
1391 chr = qemu_chr_alloc();
1393 chr->filename = g_strdup_printf("pty:%s", pty_name);
1394 ret->pty = g_strdup(pty_name);
1395 ret->has_pty = true;
1397 fprintf(stderr, "char device redirected to %s (label %s)\n",
1398 pty_name, id);
1400 s = g_malloc0(sizeof(PtyCharDriver));
1401 chr->opaque = s;
1402 chr->chr_write = pty_chr_write;
1403 chr->chr_update_read_handler = pty_chr_update_read_handler;
1404 chr->chr_close = pty_chr_close;
1405 chr->chr_add_watch = pty_chr_add_watch;
1406 chr->explicit_be_open = true;
1408 s->fd = io_channel_from_fd(master_fd);
1409 s->timer_tag = 0;
1411 return chr;
1414 static void tty_serial_init(int fd, int speed,
1415 int parity, int data_bits, int stop_bits)
1417 struct termios tty;
1418 speed_t spd;
1420 #if 0
1421 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1422 speed, parity, data_bits, stop_bits);
1423 #endif
1424 tcgetattr (fd, &tty);
1426 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1427 speed = speed * 10 / 11;
1428 do {
1429 check_speed(50);
1430 check_speed(75);
1431 check_speed(110);
1432 check_speed(134);
1433 check_speed(150);
1434 check_speed(200);
1435 check_speed(300);
1436 check_speed(600);
1437 check_speed(1200);
1438 check_speed(1800);
1439 check_speed(2400);
1440 check_speed(4800);
1441 check_speed(9600);
1442 check_speed(19200);
1443 check_speed(38400);
1444 /* Non-Posix values follow. They may be unsupported on some systems. */
1445 check_speed(57600);
1446 check_speed(115200);
1447 #ifdef B230400
1448 check_speed(230400);
1449 #endif
1450 #ifdef B460800
1451 check_speed(460800);
1452 #endif
1453 #ifdef B500000
1454 check_speed(500000);
1455 #endif
1456 #ifdef B576000
1457 check_speed(576000);
1458 #endif
1459 #ifdef B921600
1460 check_speed(921600);
1461 #endif
1462 #ifdef B1000000
1463 check_speed(1000000);
1464 #endif
1465 #ifdef B1152000
1466 check_speed(1152000);
1467 #endif
1468 #ifdef B1500000
1469 check_speed(1500000);
1470 #endif
1471 #ifdef B2000000
1472 check_speed(2000000);
1473 #endif
1474 #ifdef B2500000
1475 check_speed(2500000);
1476 #endif
1477 #ifdef B3000000
1478 check_speed(3000000);
1479 #endif
1480 #ifdef B3500000
1481 check_speed(3500000);
1482 #endif
1483 #ifdef B4000000
1484 check_speed(4000000);
1485 #endif
1486 spd = B115200;
1487 } while (0);
1489 cfsetispeed(&tty, spd);
1490 cfsetospeed(&tty, spd);
1492 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1493 |INLCR|IGNCR|ICRNL|IXON);
1494 tty.c_oflag |= OPOST;
1495 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1496 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1497 switch(data_bits) {
1498 default:
1499 case 8:
1500 tty.c_cflag |= CS8;
1501 break;
1502 case 7:
1503 tty.c_cflag |= CS7;
1504 break;
1505 case 6:
1506 tty.c_cflag |= CS6;
1507 break;
1508 case 5:
1509 tty.c_cflag |= CS5;
1510 break;
1512 switch(parity) {
1513 default:
1514 case 'N':
1515 break;
1516 case 'E':
1517 tty.c_cflag |= PARENB;
1518 break;
1519 case 'O':
1520 tty.c_cflag |= PARENB | PARODD;
1521 break;
1523 if (stop_bits == 2)
1524 tty.c_cflag |= CSTOPB;
1526 tcsetattr (fd, TCSANOW, &tty);
1529 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1531 FDCharDriver *s = chr->opaque;
1533 switch(cmd) {
1534 case CHR_IOCTL_SERIAL_SET_PARAMS:
1536 QEMUSerialSetParams *ssp = arg;
1537 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1538 ssp->speed, ssp->parity,
1539 ssp->data_bits, ssp->stop_bits);
1541 break;
1542 case CHR_IOCTL_SERIAL_SET_BREAK:
1544 int enable = *(int *)arg;
1545 if (enable) {
1546 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1549 break;
1550 case CHR_IOCTL_SERIAL_GET_TIOCM:
1552 int sarg = 0;
1553 int *targ = (int *)arg;
1554 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1555 *targ = 0;
1556 if (sarg & TIOCM_CTS)
1557 *targ |= CHR_TIOCM_CTS;
1558 if (sarg & TIOCM_CAR)
1559 *targ |= CHR_TIOCM_CAR;
1560 if (sarg & TIOCM_DSR)
1561 *targ |= CHR_TIOCM_DSR;
1562 if (sarg & TIOCM_RI)
1563 *targ |= CHR_TIOCM_RI;
1564 if (sarg & TIOCM_DTR)
1565 *targ |= CHR_TIOCM_DTR;
1566 if (sarg & TIOCM_RTS)
1567 *targ |= CHR_TIOCM_RTS;
1569 break;
1570 case CHR_IOCTL_SERIAL_SET_TIOCM:
1572 int sarg = *(int *)arg;
1573 int targ = 0;
1574 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1575 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1576 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1577 if (sarg & CHR_TIOCM_CTS)
1578 targ |= TIOCM_CTS;
1579 if (sarg & CHR_TIOCM_CAR)
1580 targ |= TIOCM_CAR;
1581 if (sarg & CHR_TIOCM_DSR)
1582 targ |= TIOCM_DSR;
1583 if (sarg & CHR_TIOCM_RI)
1584 targ |= TIOCM_RI;
1585 if (sarg & CHR_TIOCM_DTR)
1586 targ |= TIOCM_DTR;
1587 if (sarg & CHR_TIOCM_RTS)
1588 targ |= TIOCM_RTS;
1589 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1591 break;
1592 default:
1593 return -ENOTSUP;
1595 return 0;
1598 static void qemu_chr_close_tty(CharDriverState *chr)
1600 FDCharDriver *s = chr->opaque;
1601 int fd = -1;
1603 if (s) {
1604 fd = g_io_channel_unix_get_fd(s->fd_in);
1607 fd_chr_close(chr);
1609 if (fd >= 0) {
1610 close(fd);
1614 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1616 CharDriverState *chr;
1618 tty_serial_init(fd, 115200, 'N', 8, 1);
1619 chr = qemu_chr_open_fd(fd, fd);
1620 chr->chr_ioctl = tty_serial_ioctl;
1621 chr->chr_close = qemu_chr_close_tty;
1622 return chr;
1624 #endif /* __linux__ || __sun__ */
1626 #if defined(__linux__)
1628 #define HAVE_CHARDEV_PARPORT 1
1630 typedef struct {
1631 int fd;
1632 int mode;
1633 } ParallelCharDriver;
1635 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1637 if (s->mode != mode) {
1638 int m = mode;
1639 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1640 return 0;
1641 s->mode = mode;
1643 return 1;
1646 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1648 ParallelCharDriver *drv = chr->opaque;
1649 int fd = drv->fd;
1650 uint8_t b;
1652 switch(cmd) {
1653 case CHR_IOCTL_PP_READ_DATA:
1654 if (ioctl(fd, PPRDATA, &b) < 0)
1655 return -ENOTSUP;
1656 *(uint8_t *)arg = b;
1657 break;
1658 case CHR_IOCTL_PP_WRITE_DATA:
1659 b = *(uint8_t *)arg;
1660 if (ioctl(fd, PPWDATA, &b) < 0)
1661 return -ENOTSUP;
1662 break;
1663 case CHR_IOCTL_PP_READ_CONTROL:
1664 if (ioctl(fd, PPRCONTROL, &b) < 0)
1665 return -ENOTSUP;
1666 /* Linux gives only the lowest bits, and no way to know data
1667 direction! For better compatibility set the fixed upper
1668 bits. */
1669 *(uint8_t *)arg = b | 0xc0;
1670 break;
1671 case CHR_IOCTL_PP_WRITE_CONTROL:
1672 b = *(uint8_t *)arg;
1673 if (ioctl(fd, PPWCONTROL, &b) < 0)
1674 return -ENOTSUP;
1675 break;
1676 case CHR_IOCTL_PP_READ_STATUS:
1677 if (ioctl(fd, PPRSTATUS, &b) < 0)
1678 return -ENOTSUP;
1679 *(uint8_t *)arg = b;
1680 break;
1681 case CHR_IOCTL_PP_DATA_DIR:
1682 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1683 return -ENOTSUP;
1684 break;
1685 case CHR_IOCTL_PP_EPP_READ_ADDR:
1686 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1687 struct ParallelIOArg *parg = arg;
1688 int n = read(fd, parg->buffer, parg->count);
1689 if (n != parg->count) {
1690 return -EIO;
1693 break;
1694 case CHR_IOCTL_PP_EPP_READ:
1695 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1696 struct ParallelIOArg *parg = arg;
1697 int n = read(fd, parg->buffer, parg->count);
1698 if (n != parg->count) {
1699 return -EIO;
1702 break;
1703 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1704 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1705 struct ParallelIOArg *parg = arg;
1706 int n = write(fd, parg->buffer, parg->count);
1707 if (n != parg->count) {
1708 return -EIO;
1711 break;
1712 case CHR_IOCTL_PP_EPP_WRITE:
1713 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1714 struct ParallelIOArg *parg = arg;
1715 int n = write(fd, parg->buffer, parg->count);
1716 if (n != parg->count) {
1717 return -EIO;
1720 break;
1721 default:
1722 return -ENOTSUP;
1724 return 0;
1727 static void pp_close(CharDriverState *chr)
1729 ParallelCharDriver *drv = chr->opaque;
1730 int fd = drv->fd;
1732 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1733 ioctl(fd, PPRELEASE);
1734 close(fd);
1735 g_free(drv);
1736 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1739 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1741 CharDriverState *chr;
1742 ParallelCharDriver *drv;
1744 if (ioctl(fd, PPCLAIM) < 0) {
1745 close(fd);
1746 return NULL;
1749 drv = g_malloc0(sizeof(ParallelCharDriver));
1750 drv->fd = fd;
1751 drv->mode = IEEE1284_MODE_COMPAT;
1753 chr = qemu_chr_alloc();
1754 chr->chr_write = null_chr_write;
1755 chr->chr_ioctl = pp_ioctl;
1756 chr->chr_close = pp_close;
1757 chr->opaque = drv;
1759 return chr;
1761 #endif /* __linux__ */
1763 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1765 #define HAVE_CHARDEV_PARPORT 1
1767 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1769 int fd = (int)(intptr_t)chr->opaque;
1770 uint8_t b;
1772 switch(cmd) {
1773 case CHR_IOCTL_PP_READ_DATA:
1774 if (ioctl(fd, PPIGDATA, &b) < 0)
1775 return -ENOTSUP;
1776 *(uint8_t *)arg = b;
1777 break;
1778 case CHR_IOCTL_PP_WRITE_DATA:
1779 b = *(uint8_t *)arg;
1780 if (ioctl(fd, PPISDATA, &b) < 0)
1781 return -ENOTSUP;
1782 break;
1783 case CHR_IOCTL_PP_READ_CONTROL:
1784 if (ioctl(fd, PPIGCTRL, &b) < 0)
1785 return -ENOTSUP;
1786 *(uint8_t *)arg = b;
1787 break;
1788 case CHR_IOCTL_PP_WRITE_CONTROL:
1789 b = *(uint8_t *)arg;
1790 if (ioctl(fd, PPISCTRL, &b) < 0)
1791 return -ENOTSUP;
1792 break;
1793 case CHR_IOCTL_PP_READ_STATUS:
1794 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1795 return -ENOTSUP;
1796 *(uint8_t *)arg = b;
1797 break;
1798 default:
1799 return -ENOTSUP;
1801 return 0;
1804 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1806 CharDriverState *chr;
1808 chr = qemu_chr_alloc();
1809 chr->opaque = (void *)(intptr_t)fd;
1810 chr->chr_write = null_chr_write;
1811 chr->chr_ioctl = pp_ioctl;
1812 chr->explicit_be_open = true;
1813 return chr;
1815 #endif
1817 #else /* _WIN32 */
1819 typedef struct {
1820 int max_size;
1821 HANDLE hcom, hrecv, hsend;
1822 OVERLAPPED orecv;
1823 BOOL fpipe;
1824 DWORD len;
1826 /* Protected by the CharDriverState chr_write_lock. */
1827 OVERLAPPED osend;
1828 } WinCharState;
1830 typedef struct {
1831 HANDLE hStdIn;
1832 HANDLE hInputReadyEvent;
1833 HANDLE hInputDoneEvent;
1834 HANDLE hInputThread;
1835 uint8_t win_stdio_buf;
1836 } WinStdioCharState;
1838 #define NSENDBUF 2048
1839 #define NRECVBUF 2048
1840 #define MAXCONNECT 1
1841 #define NTIMEOUT 5000
1843 static int win_chr_poll(void *opaque);
1844 static int win_chr_pipe_poll(void *opaque);
1846 static void win_chr_close(CharDriverState *chr)
1848 WinCharState *s = chr->opaque;
1850 if (s->hsend) {
1851 CloseHandle(s->hsend);
1852 s->hsend = NULL;
1854 if (s->hrecv) {
1855 CloseHandle(s->hrecv);
1856 s->hrecv = NULL;
1858 if (s->hcom) {
1859 CloseHandle(s->hcom);
1860 s->hcom = NULL;
1862 if (s->fpipe)
1863 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1864 else
1865 qemu_del_polling_cb(win_chr_poll, chr);
1867 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1870 static int win_chr_init(CharDriverState *chr, const char *filename)
1872 WinCharState *s = chr->opaque;
1873 COMMCONFIG comcfg;
1874 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1875 COMSTAT comstat;
1876 DWORD size;
1877 DWORD err;
1879 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1880 if (!s->hsend) {
1881 fprintf(stderr, "Failed CreateEvent\n");
1882 goto fail;
1884 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1885 if (!s->hrecv) {
1886 fprintf(stderr, "Failed CreateEvent\n");
1887 goto fail;
1890 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1891 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1892 if (s->hcom == INVALID_HANDLE_VALUE) {
1893 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1894 s->hcom = NULL;
1895 goto fail;
1898 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1899 fprintf(stderr, "Failed SetupComm\n");
1900 goto fail;
1903 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1904 size = sizeof(COMMCONFIG);
1905 GetDefaultCommConfig(filename, &comcfg, &size);
1906 comcfg.dcb.DCBlength = sizeof(DCB);
1907 CommConfigDialog(filename, NULL, &comcfg);
1909 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1910 fprintf(stderr, "Failed SetCommState\n");
1911 goto fail;
1914 if (!SetCommMask(s->hcom, EV_ERR)) {
1915 fprintf(stderr, "Failed SetCommMask\n");
1916 goto fail;
1919 cto.ReadIntervalTimeout = MAXDWORD;
1920 if (!SetCommTimeouts(s->hcom, &cto)) {
1921 fprintf(stderr, "Failed SetCommTimeouts\n");
1922 goto fail;
1925 if (!ClearCommError(s->hcom, &err, &comstat)) {
1926 fprintf(stderr, "Failed ClearCommError\n");
1927 goto fail;
1929 qemu_add_polling_cb(win_chr_poll, chr);
1930 return 0;
1932 fail:
1933 win_chr_close(chr);
1934 return -1;
1937 /* Called with chr_write_lock held. */
1938 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1940 WinCharState *s = chr->opaque;
1941 DWORD len, ret, size, err;
1943 len = len1;
1944 ZeroMemory(&s->osend, sizeof(s->osend));
1945 s->osend.hEvent = s->hsend;
1946 while (len > 0) {
1947 if (s->hsend)
1948 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1949 else
1950 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1951 if (!ret) {
1952 err = GetLastError();
1953 if (err == ERROR_IO_PENDING) {
1954 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1955 if (ret) {
1956 buf += size;
1957 len -= size;
1958 } else {
1959 break;
1961 } else {
1962 break;
1964 } else {
1965 buf += size;
1966 len -= size;
1969 return len1 - len;
1972 static int win_chr_read_poll(CharDriverState *chr)
1974 WinCharState *s = chr->opaque;
1976 s->max_size = qemu_chr_be_can_write(chr);
1977 return s->max_size;
1980 static void win_chr_readfile(CharDriverState *chr)
1982 WinCharState *s = chr->opaque;
1983 int ret, err;
1984 uint8_t buf[READ_BUF_LEN];
1985 DWORD size;
1987 ZeroMemory(&s->orecv, sizeof(s->orecv));
1988 s->orecv.hEvent = s->hrecv;
1989 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1990 if (!ret) {
1991 err = GetLastError();
1992 if (err == ERROR_IO_PENDING) {
1993 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1997 if (size > 0) {
1998 qemu_chr_be_write(chr, buf, size);
2002 static void win_chr_read(CharDriverState *chr)
2004 WinCharState *s = chr->opaque;
2006 if (s->len > s->max_size)
2007 s->len = s->max_size;
2008 if (s->len == 0)
2009 return;
2011 win_chr_readfile(chr);
2014 static int win_chr_poll(void *opaque)
2016 CharDriverState *chr = opaque;
2017 WinCharState *s = chr->opaque;
2018 COMSTAT status;
2019 DWORD comerr;
2021 ClearCommError(s->hcom, &comerr, &status);
2022 if (status.cbInQue > 0) {
2023 s->len = status.cbInQue;
2024 win_chr_read_poll(chr);
2025 win_chr_read(chr);
2026 return 1;
2028 return 0;
2031 static CharDriverState *qemu_chr_open_win_path(const char *filename)
2033 CharDriverState *chr;
2034 WinCharState *s;
2036 chr = qemu_chr_alloc();
2037 s = g_malloc0(sizeof(WinCharState));
2038 chr->opaque = s;
2039 chr->chr_write = win_chr_write;
2040 chr->chr_close = win_chr_close;
2042 if (win_chr_init(chr, filename) < 0) {
2043 g_free(s);
2044 g_free(chr);
2045 return NULL;
2047 return chr;
2050 static int win_chr_pipe_poll(void *opaque)
2052 CharDriverState *chr = opaque;
2053 WinCharState *s = chr->opaque;
2054 DWORD size;
2056 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2057 if (size > 0) {
2058 s->len = size;
2059 win_chr_read_poll(chr);
2060 win_chr_read(chr);
2061 return 1;
2063 return 0;
2066 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2068 WinCharState *s = chr->opaque;
2069 OVERLAPPED ov;
2070 int ret;
2071 DWORD size;
2072 char openname[CHR_MAX_FILENAME_SIZE];
2074 s->fpipe = TRUE;
2076 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2077 if (!s->hsend) {
2078 fprintf(stderr, "Failed CreateEvent\n");
2079 goto fail;
2081 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2082 if (!s->hrecv) {
2083 fprintf(stderr, "Failed CreateEvent\n");
2084 goto fail;
2087 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2088 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2089 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2090 PIPE_WAIT,
2091 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2092 if (s->hcom == INVALID_HANDLE_VALUE) {
2093 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2094 s->hcom = NULL;
2095 goto fail;
2098 ZeroMemory(&ov, sizeof(ov));
2099 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2100 ret = ConnectNamedPipe(s->hcom, &ov);
2101 if (ret) {
2102 fprintf(stderr, "Failed ConnectNamedPipe\n");
2103 goto fail;
2106 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2107 if (!ret) {
2108 fprintf(stderr, "Failed GetOverlappedResult\n");
2109 if (ov.hEvent) {
2110 CloseHandle(ov.hEvent);
2111 ov.hEvent = NULL;
2113 goto fail;
2116 if (ov.hEvent) {
2117 CloseHandle(ov.hEvent);
2118 ov.hEvent = NULL;
2120 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2121 return 0;
2123 fail:
2124 win_chr_close(chr);
2125 return -1;
2129 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
2131 const char *filename = opts->device;
2132 CharDriverState *chr;
2133 WinCharState *s;
2135 chr = qemu_chr_alloc();
2136 s = g_malloc0(sizeof(WinCharState));
2137 chr->opaque = s;
2138 chr->chr_write = win_chr_write;
2139 chr->chr_close = win_chr_close;
2141 if (win_chr_pipe_init(chr, filename) < 0) {
2142 g_free(s);
2143 g_free(chr);
2144 return NULL;
2146 return chr;
2149 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2151 CharDriverState *chr;
2152 WinCharState *s;
2154 chr = qemu_chr_alloc();
2155 s = g_malloc0(sizeof(WinCharState));
2156 s->hcom = fd_out;
2157 chr->opaque = s;
2158 chr->chr_write = win_chr_write;
2159 return chr;
2162 static CharDriverState *qemu_chr_open_win_con(void)
2164 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2167 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2169 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2170 DWORD dwSize;
2171 int len1;
2173 len1 = len;
2175 while (len1 > 0) {
2176 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2177 break;
2179 buf += dwSize;
2180 len1 -= dwSize;
2183 return len - len1;
2186 static void win_stdio_wait_func(void *opaque)
2188 CharDriverState *chr = opaque;
2189 WinStdioCharState *stdio = chr->opaque;
2190 INPUT_RECORD buf[4];
2191 int ret;
2192 DWORD dwSize;
2193 int i;
2195 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2197 if (!ret) {
2198 /* Avoid error storm */
2199 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2200 return;
2203 for (i = 0; i < dwSize; i++) {
2204 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2206 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2207 int j;
2208 if (kev->uChar.AsciiChar != 0) {
2209 for (j = 0; j < kev->wRepeatCount; j++) {
2210 if (qemu_chr_be_can_write(chr)) {
2211 uint8_t c = kev->uChar.AsciiChar;
2212 qemu_chr_be_write(chr, &c, 1);
2220 static DWORD WINAPI win_stdio_thread(LPVOID param)
2222 CharDriverState *chr = param;
2223 WinStdioCharState *stdio = chr->opaque;
2224 int ret;
2225 DWORD dwSize;
2227 while (1) {
2229 /* Wait for one byte */
2230 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2232 /* Exit in case of error, continue if nothing read */
2233 if (!ret) {
2234 break;
2236 if (!dwSize) {
2237 continue;
2240 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2241 if (stdio->win_stdio_buf == '\r') {
2242 continue;
2245 /* Signal the main thread and wait until the byte was eaten */
2246 if (!SetEvent(stdio->hInputReadyEvent)) {
2247 break;
2249 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2250 != WAIT_OBJECT_0) {
2251 break;
2255 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2256 return 0;
2259 static void win_stdio_thread_wait_func(void *opaque)
2261 CharDriverState *chr = opaque;
2262 WinStdioCharState *stdio = chr->opaque;
2264 if (qemu_chr_be_can_write(chr)) {
2265 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2268 SetEvent(stdio->hInputDoneEvent);
2271 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2273 WinStdioCharState *stdio = chr->opaque;
2274 DWORD dwMode = 0;
2276 GetConsoleMode(stdio->hStdIn, &dwMode);
2278 if (echo) {
2279 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2280 } else {
2281 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2285 static void win_stdio_close(CharDriverState *chr)
2287 WinStdioCharState *stdio = chr->opaque;
2289 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2290 CloseHandle(stdio->hInputReadyEvent);
2292 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2293 CloseHandle(stdio->hInputDoneEvent);
2295 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2296 TerminateThread(stdio->hInputThread, 0);
2299 g_free(chr->opaque);
2300 g_free(chr);
2303 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2305 CharDriverState *chr;
2306 WinStdioCharState *stdio;
2307 DWORD dwMode;
2308 int is_console = 0;
2310 chr = qemu_chr_alloc();
2311 stdio = g_malloc0(sizeof(WinStdioCharState));
2313 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2314 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2315 fprintf(stderr, "cannot open stdio: invalid handle\n");
2316 exit(1);
2319 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2321 chr->opaque = stdio;
2322 chr->chr_write = win_stdio_write;
2323 chr->chr_close = win_stdio_close;
2325 if (is_console) {
2326 if (qemu_add_wait_object(stdio->hStdIn,
2327 win_stdio_wait_func, chr)) {
2328 fprintf(stderr, "qemu_add_wait_object: failed\n");
2330 } else {
2331 DWORD dwId;
2333 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2334 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2335 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2336 chr, 0, &dwId);
2338 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2339 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2340 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2341 fprintf(stderr, "cannot create stdio thread or event\n");
2342 exit(1);
2344 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2345 win_stdio_thread_wait_func, chr)) {
2346 fprintf(stderr, "qemu_add_wait_object: failed\n");
2350 dwMode |= ENABLE_LINE_INPUT;
2352 if (is_console) {
2353 /* set the terminal in raw mode */
2354 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2355 dwMode |= ENABLE_PROCESSED_INPUT;
2358 SetConsoleMode(stdio->hStdIn, dwMode);
2360 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2361 qemu_chr_fe_set_echo(chr, false);
2363 return chr;
2365 #endif /* !_WIN32 */
2368 /***********************************************************/
2369 /* UDP Net console */
2371 typedef struct {
2372 int fd;
2373 GIOChannel *chan;
2374 uint8_t buf[READ_BUF_LEN];
2375 int bufcnt;
2376 int bufptr;
2377 int max_size;
2378 } NetCharDriver;
2380 /* Called with chr_write_lock held. */
2381 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2383 NetCharDriver *s = chr->opaque;
2384 gsize bytes_written;
2385 GIOStatus status;
2387 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2388 if (status == G_IO_STATUS_EOF) {
2389 return 0;
2390 } else if (status != G_IO_STATUS_NORMAL) {
2391 return -1;
2394 return bytes_written;
2397 static int udp_chr_read_poll(void *opaque)
2399 CharDriverState *chr = opaque;
2400 NetCharDriver *s = chr->opaque;
2402 s->max_size = qemu_chr_be_can_write(chr);
2404 /* If there were any stray characters in the queue process them
2405 * first
2407 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2408 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2409 s->bufptr++;
2410 s->max_size = qemu_chr_be_can_write(chr);
2412 return s->max_size;
2415 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2417 CharDriverState *chr = opaque;
2418 NetCharDriver *s = chr->opaque;
2419 gsize bytes_read = 0;
2420 GIOStatus status;
2422 if (s->max_size == 0) {
2423 return TRUE;
2425 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2426 &bytes_read, NULL);
2427 s->bufcnt = bytes_read;
2428 s->bufptr = s->bufcnt;
2429 if (status != G_IO_STATUS_NORMAL) {
2430 remove_fd_in_watch(chr);
2431 return FALSE;
2434 s->bufptr = 0;
2435 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2436 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2437 s->bufptr++;
2438 s->max_size = qemu_chr_be_can_write(chr);
2441 return TRUE;
2444 static void udp_chr_update_read_handler(CharDriverState *chr)
2446 NetCharDriver *s = chr->opaque;
2448 remove_fd_in_watch(chr);
2449 if (s->chan) {
2450 chr->fd_in_tag = io_add_watch_poll(s->chan, udp_chr_read_poll,
2451 udp_chr_read, chr);
2455 static void udp_chr_close(CharDriverState *chr)
2457 NetCharDriver *s = chr->opaque;
2459 remove_fd_in_watch(chr);
2460 if (s->chan) {
2461 g_io_channel_unref(s->chan);
2462 closesocket(s->fd);
2464 g_free(s);
2465 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2468 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2470 CharDriverState *chr = NULL;
2471 NetCharDriver *s = NULL;
2473 chr = qemu_chr_alloc();
2474 s = g_malloc0(sizeof(NetCharDriver));
2476 s->fd = fd;
2477 s->chan = io_channel_from_socket(s->fd);
2478 s->bufcnt = 0;
2479 s->bufptr = 0;
2480 chr->opaque = s;
2481 chr->chr_write = udp_chr_write;
2482 chr->chr_update_read_handler = udp_chr_update_read_handler;
2483 chr->chr_close = udp_chr_close;
2484 /* be isn't opened until we get a connection */
2485 chr->explicit_be_open = true;
2486 return chr;
2489 /***********************************************************/
2490 /* TCP Net console */
2492 typedef struct {
2494 GIOChannel *chan, *listen_chan;
2495 guint listen_tag;
2496 int fd, listen_fd;
2497 int connected;
2498 int max_size;
2499 int do_telnetopt;
2500 int do_nodelay;
2501 int is_unix;
2502 int *read_msgfds;
2503 int read_msgfds_num;
2504 int *write_msgfds;
2505 int write_msgfds_num;
2507 SocketAddress *addr;
2508 bool is_listen;
2509 bool is_telnet;
2511 guint reconnect_timer;
2512 int64_t reconnect_time;
2513 bool connect_err_reported;
2514 } TCPCharDriver;
2516 static gboolean socket_reconnect_timeout(gpointer opaque);
2518 static void qemu_chr_socket_restart_timer(CharDriverState *chr)
2520 TCPCharDriver *s = chr->opaque;
2521 assert(s->connected == 0);
2522 s->reconnect_timer = g_timeout_add_seconds(s->reconnect_time,
2523 socket_reconnect_timeout, chr);
2526 static void check_report_connect_error(CharDriverState *chr,
2527 Error *err)
2529 TCPCharDriver *s = chr->opaque;
2531 if (!s->connect_err_reported) {
2532 error_report("Unable to connect character device %s: %s",
2533 chr->label, error_get_pretty(err));
2534 s->connect_err_reported = true;
2536 qemu_chr_socket_restart_timer(chr);
2539 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2541 #ifndef _WIN32
2542 static int unix_send_msgfds(CharDriverState *chr, const uint8_t *buf, int len)
2544 TCPCharDriver *s = chr->opaque;
2545 struct msghdr msgh;
2546 struct iovec iov;
2547 int r;
2549 size_t fd_size = s->write_msgfds_num * sizeof(int);
2550 char control[CMSG_SPACE(fd_size)];
2551 struct cmsghdr *cmsg;
2553 memset(&msgh, 0, sizeof(msgh));
2554 memset(control, 0, sizeof(control));
2556 /* set the payload */
2557 iov.iov_base = (uint8_t *) buf;
2558 iov.iov_len = len;
2560 msgh.msg_iov = &iov;
2561 msgh.msg_iovlen = 1;
2563 msgh.msg_control = control;
2564 msgh.msg_controllen = sizeof(control);
2566 cmsg = CMSG_FIRSTHDR(&msgh);
2568 cmsg->cmsg_len = CMSG_LEN(fd_size);
2569 cmsg->cmsg_level = SOL_SOCKET;
2570 cmsg->cmsg_type = SCM_RIGHTS;
2571 memcpy(CMSG_DATA(cmsg), s->write_msgfds, fd_size);
2573 do {
2574 r = sendmsg(s->fd, &msgh, 0);
2575 } while (r < 0 && errno == EINTR);
2577 /* free the written msgfds, no matter what */
2578 if (s->write_msgfds_num) {
2579 g_free(s->write_msgfds);
2580 s->write_msgfds = 0;
2581 s->write_msgfds_num = 0;
2584 return r;
2586 #endif
2588 /* Called with chr_write_lock held. */
2589 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2591 TCPCharDriver *s = chr->opaque;
2592 if (s->connected) {
2593 #ifndef _WIN32
2594 if (s->is_unix && s->write_msgfds_num) {
2595 return unix_send_msgfds(chr, buf, len);
2596 } else
2597 #endif
2599 return io_channel_send(s->chan, buf, len);
2601 } else {
2602 /* XXX: indicate an error ? */
2603 return len;
2607 static int tcp_chr_read_poll(void *opaque)
2609 CharDriverState *chr = opaque;
2610 TCPCharDriver *s = chr->opaque;
2611 if (!s->connected)
2612 return 0;
2613 s->max_size = qemu_chr_be_can_write(chr);
2614 return s->max_size;
2617 #define IAC 255
2618 #define IAC_BREAK 243
2619 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2620 TCPCharDriver *s,
2621 uint8_t *buf, int *size)
2623 /* Handle any telnet client's basic IAC options to satisfy char by
2624 * char mode with no echo. All IAC options will be removed from
2625 * the buf and the do_telnetopt variable will be used to track the
2626 * state of the width of the IAC information.
2628 * IAC commands come in sets of 3 bytes with the exception of the
2629 * "IAC BREAK" command and the double IAC.
2632 int i;
2633 int j = 0;
2635 for (i = 0; i < *size; i++) {
2636 if (s->do_telnetopt > 1) {
2637 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2638 /* Double IAC means send an IAC */
2639 if (j != i)
2640 buf[j] = buf[i];
2641 j++;
2642 s->do_telnetopt = 1;
2643 } else {
2644 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2645 /* Handle IAC break commands by sending a serial break */
2646 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2647 s->do_telnetopt++;
2649 s->do_telnetopt++;
2651 if (s->do_telnetopt >= 4) {
2652 s->do_telnetopt = 1;
2654 } else {
2655 if ((unsigned char)buf[i] == IAC) {
2656 s->do_telnetopt = 2;
2657 } else {
2658 if (j != i)
2659 buf[j] = buf[i];
2660 j++;
2664 *size = j;
2667 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2669 TCPCharDriver *s = chr->opaque;
2670 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2672 assert(num <= TCP_MAX_FDS);
2674 if (to_copy) {
2675 int i;
2677 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2679 /* Close unused fds */
2680 for (i = to_copy; i < s->read_msgfds_num; i++) {
2681 close(s->read_msgfds[i]);
2684 g_free(s->read_msgfds);
2685 s->read_msgfds = 0;
2686 s->read_msgfds_num = 0;
2689 return to_copy;
2692 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2694 TCPCharDriver *s = chr->opaque;
2696 /* clear old pending fd array */
2697 if (s->write_msgfds) {
2698 g_free(s->write_msgfds);
2701 if (num) {
2702 s->write_msgfds = g_malloc(num * sizeof(int));
2703 memcpy(s->write_msgfds, fds, num * sizeof(int));
2706 s->write_msgfds_num = num;
2708 return 0;
2711 #ifndef _WIN32
2712 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2714 TCPCharDriver *s = chr->opaque;
2715 struct cmsghdr *cmsg;
2717 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2718 int fd_size, i;
2720 if (cmsg->cmsg_len < CMSG_LEN(sizeof(int)) ||
2721 cmsg->cmsg_level != SOL_SOCKET ||
2722 cmsg->cmsg_type != SCM_RIGHTS) {
2723 continue;
2726 fd_size = cmsg->cmsg_len - CMSG_LEN(0);
2728 if (!fd_size) {
2729 continue;
2732 /* close and clean read_msgfds */
2733 for (i = 0; i < s->read_msgfds_num; i++) {
2734 close(s->read_msgfds[i]);
2737 if (s->read_msgfds_num) {
2738 g_free(s->read_msgfds);
2741 s->read_msgfds_num = fd_size / sizeof(int);
2742 s->read_msgfds = g_malloc(fd_size);
2743 memcpy(s->read_msgfds, CMSG_DATA(cmsg), fd_size);
2745 for (i = 0; i < s->read_msgfds_num; i++) {
2746 int fd = s->read_msgfds[i];
2747 if (fd < 0) {
2748 continue;
2751 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2752 qemu_set_block(fd);
2754 #ifndef MSG_CMSG_CLOEXEC
2755 qemu_set_cloexec(fd);
2756 #endif
2761 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2763 TCPCharDriver *s = chr->opaque;
2764 struct msghdr msg = { NULL, };
2765 struct iovec iov[1];
2766 union {
2767 struct cmsghdr cmsg;
2768 char control[CMSG_SPACE(sizeof(int) * TCP_MAX_FDS)];
2769 } msg_control;
2770 int flags = 0;
2771 ssize_t ret;
2773 iov[0].iov_base = buf;
2774 iov[0].iov_len = len;
2776 msg.msg_iov = iov;
2777 msg.msg_iovlen = 1;
2778 msg.msg_control = &msg_control;
2779 msg.msg_controllen = sizeof(msg_control);
2781 #ifdef MSG_CMSG_CLOEXEC
2782 flags |= MSG_CMSG_CLOEXEC;
2783 #endif
2784 ret = recvmsg(s->fd, &msg, flags);
2785 if (ret > 0 && s->is_unix) {
2786 unix_process_msgfd(chr, &msg);
2789 return ret;
2791 #else
2792 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2794 TCPCharDriver *s = chr->opaque;
2795 return qemu_recv(s->fd, buf, len, 0);
2797 #endif
2799 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2801 TCPCharDriver *s = chr->opaque;
2802 return g_io_create_watch(s->chan, cond);
2805 static void tcp_chr_disconnect(CharDriverState *chr)
2807 TCPCharDriver *s = chr->opaque;
2809 s->connected = 0;
2810 if (s->listen_chan) {
2811 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
2812 tcp_chr_accept, chr);
2814 remove_fd_in_watch(chr);
2815 g_io_channel_unref(s->chan);
2816 s->chan = NULL;
2817 closesocket(s->fd);
2818 s->fd = -1;
2819 SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
2820 "disconnected:", s->addr, s->is_listen, s->is_telnet);
2821 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2822 if (s->reconnect_time) {
2823 qemu_chr_socket_restart_timer(chr);
2827 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2829 CharDriverState *chr = opaque;
2830 TCPCharDriver *s = chr->opaque;
2831 uint8_t buf[READ_BUF_LEN];
2832 int len, size;
2834 if (cond & G_IO_HUP) {
2835 /* connection closed */
2836 tcp_chr_disconnect(chr);
2837 return TRUE;
2840 if (!s->connected || s->max_size <= 0) {
2841 return TRUE;
2843 len = sizeof(buf);
2844 if (len > s->max_size)
2845 len = s->max_size;
2846 size = tcp_chr_recv(chr, (void *)buf, len);
2847 if (size == 0) {
2848 /* connection closed */
2849 tcp_chr_disconnect(chr);
2850 } else if (size > 0) {
2851 if (s->do_telnetopt)
2852 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2853 if (size > 0)
2854 qemu_chr_be_write(chr, buf, size);
2857 return TRUE;
2860 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2862 TCPCharDriver *s = chr->opaque;
2863 int size;
2865 if (!s->connected) {
2866 return 0;
2869 size = tcp_chr_recv(chr, (void *) buf, len);
2870 if (size == 0) {
2871 /* connection closed */
2872 tcp_chr_disconnect(chr);
2875 return size;
2878 #ifndef _WIN32
2879 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2881 CharDriverState *chr = qemu_chr_open_fd(eventfd, eventfd);
2883 if (chr) {
2884 chr->avail_connections = 1;
2887 return chr;
2889 #endif
2891 static void tcp_chr_connect(void *opaque)
2893 CharDriverState *chr = opaque;
2894 TCPCharDriver *s = chr->opaque;
2895 struct sockaddr_storage ss, ps;
2896 socklen_t ss_len = sizeof(ss), ps_len = sizeof(ps);
2898 memset(&ss, 0, ss_len);
2899 if (getsockname(s->fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2900 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
2901 "Error in getsockname: %s\n", strerror(errno));
2902 } else if (getpeername(s->fd, (struct sockaddr *) &ps, &ps_len) != 0) {
2903 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE,
2904 "Error in getpeername: %s\n", strerror(errno));
2905 } else {
2906 sockaddr_to_str(chr->filename, CHR_MAX_FILENAME_SIZE,
2907 &ss, ss_len, &ps, ps_len,
2908 s->is_listen, s->is_telnet);
2911 s->connected = 1;
2912 if (s->chan) {
2913 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2914 tcp_chr_read, chr);
2916 qemu_chr_be_generic_open(chr);
2919 static void tcp_chr_update_read_handler(CharDriverState *chr)
2921 TCPCharDriver *s = chr->opaque;
2923 remove_fd_in_watch(chr);
2924 if (s->chan) {
2925 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2926 tcp_chr_read, chr);
2930 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2931 static void tcp_chr_telnet_init(int fd)
2933 char buf[3];
2934 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2935 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2936 send(fd, (char *)buf, 3, 0);
2937 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2938 send(fd, (char *)buf, 3, 0);
2939 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2940 send(fd, (char *)buf, 3, 0);
2941 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2942 send(fd, (char *)buf, 3, 0);
2945 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2947 TCPCharDriver *s = chr->opaque;
2948 if (s->fd != -1)
2949 return -1;
2951 qemu_set_nonblock(fd);
2952 if (s->do_nodelay)
2953 socket_set_nodelay(fd);
2954 s->fd = fd;
2955 s->chan = io_channel_from_socket(fd);
2956 if (s->listen_tag) {
2957 g_source_remove(s->listen_tag);
2958 s->listen_tag = 0;
2960 tcp_chr_connect(chr);
2962 return 0;
2965 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2967 CharDriverState *chr = opaque;
2968 TCPCharDriver *s = chr->opaque;
2969 struct sockaddr_in saddr;
2970 #ifndef _WIN32
2971 struct sockaddr_un uaddr;
2972 #endif
2973 struct sockaddr *addr;
2974 socklen_t len;
2975 int fd;
2977 for(;;) {
2978 #ifndef _WIN32
2979 if (s->is_unix) {
2980 len = sizeof(uaddr);
2981 addr = (struct sockaddr *)&uaddr;
2982 } else
2983 #endif
2985 len = sizeof(saddr);
2986 addr = (struct sockaddr *)&saddr;
2988 fd = qemu_accept(s->listen_fd, addr, &len);
2989 if (fd < 0 && errno != EINTR) {
2990 s->listen_tag = 0;
2991 return FALSE;
2992 } else if (fd >= 0) {
2993 if (s->do_telnetopt)
2994 tcp_chr_telnet_init(fd);
2995 break;
2998 if (tcp_chr_add_client(chr, fd) < 0)
2999 close(fd);
3001 return TRUE;
3004 static void tcp_chr_close(CharDriverState *chr)
3006 TCPCharDriver *s = chr->opaque;
3007 int i;
3009 if (s->reconnect_timer) {
3010 g_source_remove(s->reconnect_timer);
3011 s->reconnect_timer = 0;
3013 qapi_free_SocketAddress(s->addr);
3014 if (s->fd >= 0) {
3015 remove_fd_in_watch(chr);
3016 if (s->chan) {
3017 g_io_channel_unref(s->chan);
3019 closesocket(s->fd);
3021 if (s->listen_fd >= 0) {
3022 if (s->listen_tag) {
3023 g_source_remove(s->listen_tag);
3024 s->listen_tag = 0;
3026 if (s->listen_chan) {
3027 g_io_channel_unref(s->listen_chan);
3029 closesocket(s->listen_fd);
3031 if (s->read_msgfds_num) {
3032 for (i = 0; i < s->read_msgfds_num; i++) {
3033 close(s->read_msgfds[i]);
3035 g_free(s->read_msgfds);
3037 if (s->write_msgfds_num) {
3038 g_free(s->write_msgfds);
3040 g_free(s);
3041 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
3044 static void qemu_chr_finish_socket_connection(CharDriverState *chr, int fd)
3046 TCPCharDriver *s = chr->opaque;
3048 if (s->is_listen) {
3049 s->listen_fd = fd;
3050 s->listen_chan = io_channel_from_socket(s->listen_fd);
3051 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
3052 tcp_chr_accept, chr);
3053 } else {
3054 s->connected = 1;
3055 s->fd = fd;
3056 socket_set_nodelay(fd);
3057 s->chan = io_channel_from_socket(s->fd);
3058 tcp_chr_connect(chr);
3062 static void qemu_chr_socket_connected(int fd, Error *err, void *opaque)
3064 CharDriverState *chr = opaque;
3065 TCPCharDriver *s = chr->opaque;
3067 if (fd < 0) {
3068 check_report_connect_error(chr, err);
3069 return;
3072 s->connect_err_reported = false;
3073 qemu_chr_finish_socket_connection(chr, fd);
3076 static bool qemu_chr_open_socket_fd(CharDriverState *chr, Error **errp)
3078 TCPCharDriver *s = chr->opaque;
3079 int fd;
3081 if (s->is_listen) {
3082 fd = socket_listen(s->addr, errp);
3083 } else if (s->reconnect_time) {
3084 fd = socket_connect(s->addr, errp, qemu_chr_socket_connected, chr);
3085 return fd >= 0;
3086 } else {
3087 fd = socket_connect(s->addr, errp, NULL, NULL);
3089 if (fd < 0) {
3090 return false;
3093 qemu_chr_finish_socket_connection(chr, fd);
3094 return true;
3097 /*********************************************************/
3098 /* Ring buffer chardev */
3100 typedef struct {
3101 size_t size;
3102 size_t prod;
3103 size_t cons;
3104 uint8_t *cbuf;
3105 } RingBufCharDriver;
3107 static size_t ringbuf_count(const CharDriverState *chr)
3109 const RingBufCharDriver *d = chr->opaque;
3111 return d->prod - d->cons;
3114 /* Called with chr_write_lock held. */
3115 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3117 RingBufCharDriver *d = chr->opaque;
3118 int i;
3120 if (!buf || (len < 0)) {
3121 return -1;
3124 for (i = 0; i < len; i++ ) {
3125 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3126 if (d->prod - d->cons > d->size) {
3127 d->cons = d->prod - d->size;
3131 return 0;
3134 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3136 RingBufCharDriver *d = chr->opaque;
3137 int i;
3139 qemu_mutex_lock(&chr->chr_write_lock);
3140 for (i = 0; i < len && d->cons != d->prod; i++) {
3141 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3143 qemu_mutex_unlock(&chr->chr_write_lock);
3145 return i;
3148 static void ringbuf_chr_close(struct CharDriverState *chr)
3150 RingBufCharDriver *d = chr->opaque;
3152 g_free(d->cbuf);
3153 g_free(d);
3154 chr->opaque = NULL;
3157 static CharDriverState *qemu_chr_open_ringbuf(ChardevRingbuf *opts,
3158 Error **errp)
3160 CharDriverState *chr;
3161 RingBufCharDriver *d;
3163 chr = qemu_chr_alloc();
3164 d = g_malloc(sizeof(*d));
3166 d->size = opts->has_size ? opts->size : 65536;
3168 /* The size must be power of 2 */
3169 if (d->size & (d->size - 1)) {
3170 error_setg(errp, "size of ringbuf chardev must be power of two");
3171 goto fail;
3174 d->prod = 0;
3175 d->cons = 0;
3176 d->cbuf = g_malloc0(d->size);
3178 chr->opaque = d;
3179 chr->chr_write = ringbuf_chr_write;
3180 chr->chr_close = ringbuf_chr_close;
3182 return chr;
3184 fail:
3185 g_free(d);
3186 g_free(chr);
3187 return NULL;
3190 bool chr_is_ringbuf(const CharDriverState *chr)
3192 return chr->chr_write == ringbuf_chr_write;
3195 void qmp_ringbuf_write(const char *device, const char *data,
3196 bool has_format, enum DataFormat format,
3197 Error **errp)
3199 CharDriverState *chr;
3200 const uint8_t *write_data;
3201 int ret;
3202 gsize write_count;
3204 chr = qemu_chr_find(device);
3205 if (!chr) {
3206 error_setg(errp, "Device '%s' not found", device);
3207 return;
3210 if (!chr_is_ringbuf(chr)) {
3211 error_setg(errp,"%s is not a ringbuf device", device);
3212 return;
3215 if (has_format && (format == DATA_FORMAT_BASE64)) {
3216 write_data = g_base64_decode(data, &write_count);
3217 } else {
3218 write_data = (uint8_t *)data;
3219 write_count = strlen(data);
3222 ret = ringbuf_chr_write(chr, write_data, write_count);
3224 if (write_data != (uint8_t *)data) {
3225 g_free((void *)write_data);
3228 if (ret < 0) {
3229 error_setg(errp, "Failed to write to device %s", device);
3230 return;
3234 char *qmp_ringbuf_read(const char *device, int64_t size,
3235 bool has_format, enum DataFormat format,
3236 Error **errp)
3238 CharDriverState *chr;
3239 uint8_t *read_data;
3240 size_t count;
3241 char *data;
3243 chr = qemu_chr_find(device);
3244 if (!chr) {
3245 error_setg(errp, "Device '%s' not found", device);
3246 return NULL;
3249 if (!chr_is_ringbuf(chr)) {
3250 error_setg(errp,"%s is not a ringbuf device", device);
3251 return NULL;
3254 if (size <= 0) {
3255 error_setg(errp, "size must be greater than zero");
3256 return NULL;
3259 count = ringbuf_count(chr);
3260 size = size > count ? count : size;
3261 read_data = g_malloc(size + 1);
3263 ringbuf_chr_read(chr, read_data, size);
3265 if (has_format && (format == DATA_FORMAT_BASE64)) {
3266 data = g_base64_encode(read_data, size);
3267 g_free(read_data);
3268 } else {
3270 * FIXME should read only complete, valid UTF-8 characters up
3271 * to @size bytes. Invalid sequences should be replaced by a
3272 * suitable replacement character. Except when (and only
3273 * when) ring buffer lost characters since last read, initial
3274 * continuation characters should be dropped.
3276 read_data[size] = 0;
3277 data = (char *)read_data;
3280 return data;
3283 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3285 char host[65], port[33], width[8], height[8];
3286 int pos;
3287 const char *p;
3288 QemuOpts *opts;
3289 Error *local_err = NULL;
3291 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3292 if (local_err) {
3293 qerror_report_err(local_err);
3294 error_free(local_err);
3295 return NULL;
3298 if (strstart(filename, "mon:", &p)) {
3299 filename = p;
3300 qemu_opt_set(opts, "mux", "on");
3301 if (strcmp(filename, "stdio") == 0) {
3302 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3303 * but pass it to the guest. Handle this only for compat syntax,
3304 * for -chardev syntax we have special option for this.
3305 * This is what -nographic did, redirecting+muxing serial+monitor
3306 * to stdio causing Ctrl+C to be passed to guest. */
3307 qemu_opt_set(opts, "signal", "off");
3311 if (strcmp(filename, "null") == 0 ||
3312 strcmp(filename, "pty") == 0 ||
3313 strcmp(filename, "msmouse") == 0 ||
3314 strcmp(filename, "braille") == 0 ||
3315 strcmp(filename, "testdev") == 0 ||
3316 strcmp(filename, "stdio") == 0) {
3317 qemu_opt_set(opts, "backend", filename);
3318 return opts;
3320 if (strstart(filename, "vc", &p)) {
3321 qemu_opt_set(opts, "backend", "vc");
3322 if (*p == ':') {
3323 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3324 /* pixels */
3325 qemu_opt_set(opts, "width", width);
3326 qemu_opt_set(opts, "height", height);
3327 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3328 /* chars */
3329 qemu_opt_set(opts, "cols", width);
3330 qemu_opt_set(opts, "rows", height);
3331 } else {
3332 goto fail;
3335 return opts;
3337 if (strcmp(filename, "con:") == 0) {
3338 qemu_opt_set(opts, "backend", "console");
3339 return opts;
3341 if (strstart(filename, "COM", NULL)) {
3342 qemu_opt_set(opts, "backend", "serial");
3343 qemu_opt_set(opts, "path", filename);
3344 return opts;
3346 if (strstart(filename, "file:", &p)) {
3347 qemu_opt_set(opts, "backend", "file");
3348 qemu_opt_set(opts, "path", p);
3349 return opts;
3351 if (strstart(filename, "pipe:", &p)) {
3352 qemu_opt_set(opts, "backend", "pipe");
3353 qemu_opt_set(opts, "path", p);
3354 return opts;
3356 if (strstart(filename, "tcp:", &p) ||
3357 strstart(filename, "telnet:", &p)) {
3358 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3359 host[0] = 0;
3360 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3361 goto fail;
3363 qemu_opt_set(opts, "backend", "socket");
3364 qemu_opt_set(opts, "host", host);
3365 qemu_opt_set(opts, "port", port);
3366 if (p[pos] == ',') {
3367 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3368 goto fail;
3370 if (strstart(filename, "telnet:", &p))
3371 qemu_opt_set(opts, "telnet", "on");
3372 return opts;
3374 if (strstart(filename, "udp:", &p)) {
3375 qemu_opt_set(opts, "backend", "udp");
3376 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3377 host[0] = 0;
3378 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3379 goto fail;
3382 qemu_opt_set(opts, "host", host);
3383 qemu_opt_set(opts, "port", port);
3384 if (p[pos] == '@') {
3385 p += pos + 1;
3386 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3387 host[0] = 0;
3388 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3389 goto fail;
3392 qemu_opt_set(opts, "localaddr", host);
3393 qemu_opt_set(opts, "localport", port);
3395 return opts;
3397 if (strstart(filename, "unix:", &p)) {
3398 qemu_opt_set(opts, "backend", "socket");
3399 if (qemu_opts_do_parse(opts, p, "path") != 0)
3400 goto fail;
3401 return opts;
3403 if (strstart(filename, "/dev/parport", NULL) ||
3404 strstart(filename, "/dev/ppi", NULL)) {
3405 qemu_opt_set(opts, "backend", "parport");
3406 qemu_opt_set(opts, "path", filename);
3407 return opts;
3409 if (strstart(filename, "/dev/", NULL)) {
3410 qemu_opt_set(opts, "backend", "tty");
3411 qemu_opt_set(opts, "path", filename);
3412 return opts;
3415 fail:
3416 qemu_opts_del(opts);
3417 return NULL;
3420 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3421 Error **errp)
3423 const char *path = qemu_opt_get(opts, "path");
3425 if (path == NULL) {
3426 error_setg(errp, "chardev: file: no filename given");
3427 return;
3429 backend->file = g_new0(ChardevFile, 1);
3430 backend->file->out = g_strdup(path);
3433 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3434 Error **errp)
3436 backend->stdio = g_new0(ChardevStdio, 1);
3437 backend->stdio->has_signal = true;
3438 backend->stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3441 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3442 Error **errp)
3444 const char *device = qemu_opt_get(opts, "path");
3446 if (device == NULL) {
3447 error_setg(errp, "chardev: serial/tty: no device path given");
3448 return;
3450 backend->serial = g_new0(ChardevHostdev, 1);
3451 backend->serial->device = g_strdup(device);
3454 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3455 Error **errp)
3457 const char *device = qemu_opt_get(opts, "path");
3459 if (device == NULL) {
3460 error_setg(errp, "chardev: parallel: no device path given");
3461 return;
3463 backend->parallel = g_new0(ChardevHostdev, 1);
3464 backend->parallel->device = g_strdup(device);
3467 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3468 Error **errp)
3470 const char *device = qemu_opt_get(opts, "path");
3472 if (device == NULL) {
3473 error_setg(errp, "chardev: pipe: no device path given");
3474 return;
3476 backend->pipe = g_new0(ChardevHostdev, 1);
3477 backend->pipe->device = g_strdup(device);
3480 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3481 Error **errp)
3483 int val;
3485 backend->ringbuf = g_new0(ChardevRingbuf, 1);
3487 val = qemu_opt_get_size(opts, "size", 0);
3488 if (val != 0) {
3489 backend->ringbuf->has_size = true;
3490 backend->ringbuf->size = val;
3494 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3495 Error **errp)
3497 const char *chardev = qemu_opt_get(opts, "chardev");
3499 if (chardev == NULL) {
3500 error_setg(errp, "chardev: mux: no chardev given");
3501 return;
3503 backend->mux = g_new0(ChardevMux, 1);
3504 backend->mux->chardev = g_strdup(chardev);
3507 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3508 Error **errp)
3510 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3511 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3512 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3513 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3514 int64_t reconnect = qemu_opt_get_number(opts, "reconnect", 0);
3515 const char *path = qemu_opt_get(opts, "path");
3516 const char *host = qemu_opt_get(opts, "host");
3517 const char *port = qemu_opt_get(opts, "port");
3518 SocketAddress *addr;
3520 if (!path) {
3521 if (!host) {
3522 error_setg(errp, "chardev: socket: no host given");
3523 return;
3525 if (!port) {
3526 error_setg(errp, "chardev: socket: no port given");
3527 return;
3531 backend->socket = g_new0(ChardevSocket, 1);
3533 backend->socket->has_nodelay = true;
3534 backend->socket->nodelay = do_nodelay;
3535 backend->socket->has_server = true;
3536 backend->socket->server = is_listen;
3537 backend->socket->has_telnet = true;
3538 backend->socket->telnet = is_telnet;
3539 backend->socket->has_wait = true;
3540 backend->socket->wait = is_waitconnect;
3541 backend->socket->has_reconnect = true;
3542 backend->socket->reconnect = reconnect;
3544 addr = g_new0(SocketAddress, 1);
3545 if (path) {
3546 addr->kind = SOCKET_ADDRESS_KIND_UNIX;
3547 addr->q_unix = g_new0(UnixSocketAddress, 1);
3548 addr->q_unix->path = g_strdup(path);
3549 } else {
3550 addr->kind = SOCKET_ADDRESS_KIND_INET;
3551 addr->inet = g_new0(InetSocketAddress, 1);
3552 addr->inet->host = g_strdup(host);
3553 addr->inet->port = g_strdup(port);
3554 addr->inet->has_to = qemu_opt_get(opts, "to");
3555 addr->inet->to = qemu_opt_get_number(opts, "to", 0);
3556 addr->inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3557 addr->inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3558 addr->inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3559 addr->inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3561 backend->socket->addr = addr;
3564 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3565 Error **errp)
3567 const char *host = qemu_opt_get(opts, "host");
3568 const char *port = qemu_opt_get(opts, "port");
3569 const char *localaddr = qemu_opt_get(opts, "localaddr");
3570 const char *localport = qemu_opt_get(opts, "localport");
3571 bool has_local = false;
3572 SocketAddress *addr;
3574 if (host == NULL || strlen(host) == 0) {
3575 host = "localhost";
3577 if (port == NULL || strlen(port) == 0) {
3578 error_setg(errp, "chardev: udp: remote port not specified");
3579 return;
3581 if (localport == NULL || strlen(localport) == 0) {
3582 localport = "0";
3583 } else {
3584 has_local = true;
3586 if (localaddr == NULL || strlen(localaddr) == 0) {
3587 localaddr = "";
3588 } else {
3589 has_local = true;
3592 backend->udp = g_new0(ChardevUdp, 1);
3594 addr = g_new0(SocketAddress, 1);
3595 addr->kind = SOCKET_ADDRESS_KIND_INET;
3596 addr->inet = g_new0(InetSocketAddress, 1);
3597 addr->inet->host = g_strdup(host);
3598 addr->inet->port = g_strdup(port);
3599 addr->inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3600 addr->inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3601 addr->inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3602 addr->inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3603 backend->udp->remote = addr;
3605 if (has_local) {
3606 backend->udp->has_local = true;
3607 addr = g_new0(SocketAddress, 1);
3608 addr->kind = SOCKET_ADDRESS_KIND_INET;
3609 addr->inet = g_new0(InetSocketAddress, 1);
3610 addr->inet->host = g_strdup(localaddr);
3611 addr->inet->port = g_strdup(localport);
3612 backend->udp->local = addr;
3616 typedef struct CharDriver {
3617 const char *name;
3618 ChardevBackendKind kind;
3619 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3620 } CharDriver;
3622 static GSList *backends;
3624 void register_char_driver(const char *name, ChardevBackendKind kind,
3625 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3627 CharDriver *s;
3629 s = g_malloc0(sizeof(*s));
3630 s->name = g_strdup(name);
3631 s->kind = kind;
3632 s->parse = parse;
3634 backends = g_slist_append(backends, s);
3637 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3638 void (*init)(struct CharDriverState *s),
3639 Error **errp)
3641 Error *local_err = NULL;
3642 CharDriver *cd;
3643 CharDriverState *chr;
3644 GSList *i;
3645 ChardevReturn *ret = NULL;
3646 ChardevBackend *backend;
3647 const char *id = qemu_opts_id(opts);
3648 char *bid = NULL;
3650 if (id == NULL) {
3651 error_setg(errp, "chardev: no id specified");
3652 goto err;
3655 if (qemu_opt_get(opts, "backend") == NULL) {
3656 error_setg(errp, "chardev: \"%s\" missing backend",
3657 qemu_opts_id(opts));
3658 goto err;
3660 for (i = backends; i; i = i->next) {
3661 cd = i->data;
3663 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3664 break;
3667 if (i == NULL) {
3668 error_setg(errp, "chardev: backend \"%s\" not found",
3669 qemu_opt_get(opts, "backend"));
3670 goto err;
3673 backend = g_new0(ChardevBackend, 1);
3675 if (qemu_opt_get_bool(opts, "mux", 0)) {
3676 bid = g_strdup_printf("%s-base", id);
3679 chr = NULL;
3680 backend->kind = cd->kind;
3681 if (cd->parse) {
3682 cd->parse(opts, backend, &local_err);
3683 if (local_err) {
3684 error_propagate(errp, local_err);
3685 goto qapi_out;
3688 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3689 if (!ret) {
3690 goto qapi_out;
3693 if (bid) {
3694 qapi_free_ChardevBackend(backend);
3695 qapi_free_ChardevReturn(ret);
3696 backend = g_new0(ChardevBackend, 1);
3697 backend->mux = g_new0(ChardevMux, 1);
3698 backend->kind = CHARDEV_BACKEND_KIND_MUX;
3699 backend->mux->chardev = g_strdup(bid);
3700 ret = qmp_chardev_add(id, backend, errp);
3701 if (!ret) {
3702 chr = qemu_chr_find(bid);
3703 qemu_chr_delete(chr);
3704 chr = NULL;
3705 goto qapi_out;
3709 chr = qemu_chr_find(id);
3710 chr->opts = opts;
3712 qapi_out:
3713 qapi_free_ChardevBackend(backend);
3714 qapi_free_ChardevReturn(ret);
3715 g_free(bid);
3716 return chr;
3718 err:
3719 qemu_opts_del(opts);
3720 return NULL;
3723 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3725 const char *p;
3726 CharDriverState *chr;
3727 QemuOpts *opts;
3728 Error *err = NULL;
3730 if (strstart(filename, "chardev:", &p)) {
3731 return qemu_chr_find(p);
3734 opts = qemu_chr_parse_compat(label, filename);
3735 if (!opts)
3736 return NULL;
3738 chr = qemu_chr_new_from_opts(opts, init, &err);
3739 if (err) {
3740 error_report("%s", error_get_pretty(err));
3741 error_free(err);
3743 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3744 qemu_chr_fe_claim_no_fail(chr);
3745 monitor_init(chr, MONITOR_USE_READLINE);
3747 return chr;
3750 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3752 if (chr->chr_set_echo) {
3753 chr->chr_set_echo(chr, echo);
3757 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3759 if (chr->fe_open == fe_open) {
3760 return;
3762 chr->fe_open = fe_open;
3763 if (chr->chr_set_fe_open) {
3764 chr->chr_set_fe_open(chr, fe_open);
3768 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3770 if (chr->chr_fe_event) {
3771 chr->chr_fe_event(chr, event);
3775 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3776 GIOFunc func, void *user_data)
3778 GSource *src;
3779 guint tag;
3781 if (s->chr_add_watch == NULL) {
3782 return -ENOSYS;
3785 src = s->chr_add_watch(s, cond);
3786 if (!src) {
3787 return -EINVAL;
3790 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3791 tag = g_source_attach(src, NULL);
3792 g_source_unref(src);
3794 return tag;
3797 int qemu_chr_fe_claim(CharDriverState *s)
3799 if (s->avail_connections < 1) {
3800 return -1;
3802 s->avail_connections--;
3803 return 0;
3806 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3808 if (qemu_chr_fe_claim(s) != 0) {
3809 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3810 __func__, s->label);
3811 exit(1);
3815 void qemu_chr_fe_release(CharDriverState *s)
3817 s->avail_connections++;
3820 void qemu_chr_delete(CharDriverState *chr)
3822 QTAILQ_REMOVE(&chardevs, chr, next);
3823 if (chr->chr_close) {
3824 chr->chr_close(chr);
3826 g_free(chr->filename);
3827 g_free(chr->label);
3828 qemu_opts_del(chr->opts);
3829 g_free(chr);
3832 ChardevInfoList *qmp_query_chardev(Error **errp)
3834 ChardevInfoList *chr_list = NULL;
3835 CharDriverState *chr;
3837 QTAILQ_FOREACH(chr, &chardevs, next) {
3838 ChardevInfoList *info = g_malloc0(sizeof(*info));
3839 info->value = g_malloc0(sizeof(*info->value));
3840 info->value->label = g_strdup(chr->label);
3841 info->value->filename = g_strdup(chr->filename);
3842 info->value->frontend_open = chr->fe_open;
3844 info->next = chr_list;
3845 chr_list = info;
3848 return chr_list;
3851 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
3853 ChardevBackendInfoList *backend_list = NULL;
3854 CharDriver *c = NULL;
3855 GSList *i = NULL;
3857 for (i = backends; i; i = i->next) {
3858 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
3859 c = i->data;
3860 info->value = g_malloc0(sizeof(*info->value));
3861 info->value->name = g_strdup(c->name);
3863 info->next = backend_list;
3864 backend_list = info;
3867 return backend_list;
3870 CharDriverState *qemu_chr_find(const char *name)
3872 CharDriverState *chr;
3874 QTAILQ_FOREACH(chr, &chardevs, next) {
3875 if (strcmp(chr->label, name) != 0)
3876 continue;
3877 return chr;
3879 return NULL;
3882 /* Get a character (serial) device interface. */
3883 CharDriverState *qemu_char_get_next_serial(void)
3885 static int next_serial;
3886 CharDriverState *chr;
3888 /* FIXME: This function needs to go away: use chardev properties! */
3890 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3891 chr = serial_hds[next_serial++];
3892 qemu_chr_fe_claim_no_fail(chr);
3893 return chr;
3895 return NULL;
3898 QemuOptsList qemu_chardev_opts = {
3899 .name = "chardev",
3900 .implied_opt_name = "backend",
3901 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3902 .desc = {
3904 .name = "backend",
3905 .type = QEMU_OPT_STRING,
3907 .name = "path",
3908 .type = QEMU_OPT_STRING,
3910 .name = "host",
3911 .type = QEMU_OPT_STRING,
3913 .name = "port",
3914 .type = QEMU_OPT_STRING,
3916 .name = "localaddr",
3917 .type = QEMU_OPT_STRING,
3919 .name = "localport",
3920 .type = QEMU_OPT_STRING,
3922 .name = "to",
3923 .type = QEMU_OPT_NUMBER,
3925 .name = "ipv4",
3926 .type = QEMU_OPT_BOOL,
3928 .name = "ipv6",
3929 .type = QEMU_OPT_BOOL,
3931 .name = "wait",
3932 .type = QEMU_OPT_BOOL,
3934 .name = "server",
3935 .type = QEMU_OPT_BOOL,
3937 .name = "delay",
3938 .type = QEMU_OPT_BOOL,
3940 .name = "reconnect",
3941 .type = QEMU_OPT_NUMBER,
3943 .name = "telnet",
3944 .type = QEMU_OPT_BOOL,
3946 .name = "width",
3947 .type = QEMU_OPT_NUMBER,
3949 .name = "height",
3950 .type = QEMU_OPT_NUMBER,
3952 .name = "cols",
3953 .type = QEMU_OPT_NUMBER,
3955 .name = "rows",
3956 .type = QEMU_OPT_NUMBER,
3958 .name = "mux",
3959 .type = QEMU_OPT_BOOL,
3961 .name = "signal",
3962 .type = QEMU_OPT_BOOL,
3964 .name = "name",
3965 .type = QEMU_OPT_STRING,
3967 .name = "debug",
3968 .type = QEMU_OPT_NUMBER,
3970 .name = "size",
3971 .type = QEMU_OPT_SIZE,
3973 .name = "chardev",
3974 .type = QEMU_OPT_STRING,
3976 { /* end of list */ }
3980 #ifdef _WIN32
3982 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3984 HANDLE out;
3986 if (file->has_in) {
3987 error_setg(errp, "input file not supported");
3988 return NULL;
3991 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3992 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3993 if (out == INVALID_HANDLE_VALUE) {
3994 error_setg(errp, "open %s failed", file->out);
3995 return NULL;
3997 return qemu_chr_open_win_file(out);
4000 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
4001 Error **errp)
4003 return qemu_chr_open_win_path(serial->device);
4006 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
4007 Error **errp)
4009 error_setg(errp, "character device backend type 'parallel' not supported");
4010 return NULL;
4013 #else /* WIN32 */
4015 static int qmp_chardev_open_file_source(char *src, int flags,
4016 Error **errp)
4018 int fd = -1;
4020 TFR(fd = qemu_open(src, flags, 0666));
4021 if (fd == -1) {
4022 error_setg_file_open(errp, errno, src);
4024 return fd;
4027 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
4029 int flags, in = -1, out;
4031 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
4032 out = qmp_chardev_open_file_source(file->out, flags, errp);
4033 if (out < 0) {
4034 return NULL;
4037 if (file->has_in) {
4038 flags = O_RDONLY;
4039 in = qmp_chardev_open_file_source(file->in, flags, errp);
4040 if (in < 0) {
4041 qemu_close(out);
4042 return NULL;
4046 return qemu_chr_open_fd(in, out);
4049 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
4050 Error **errp)
4052 #ifdef HAVE_CHARDEV_TTY
4053 int fd;
4055 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
4056 if (fd < 0) {
4057 return NULL;
4059 qemu_set_nonblock(fd);
4060 return qemu_chr_open_tty_fd(fd);
4061 #else
4062 error_setg(errp, "character device backend type 'serial' not supported");
4063 return NULL;
4064 #endif
4067 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
4068 Error **errp)
4070 #ifdef HAVE_CHARDEV_PARPORT
4071 int fd;
4073 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
4074 if (fd < 0) {
4075 return NULL;
4077 return qemu_chr_open_pp_fd(fd);
4078 #else
4079 error_setg(errp, "character device backend type 'parallel' not supported");
4080 return NULL;
4081 #endif
4084 #endif /* WIN32 */
4086 static void socket_try_connect(CharDriverState *chr)
4088 Error *err = NULL;
4090 if (!qemu_chr_open_socket_fd(chr, &err)) {
4091 check_report_connect_error(chr, err);
4095 static gboolean socket_reconnect_timeout(gpointer opaque)
4097 CharDriverState *chr = opaque;
4098 TCPCharDriver *s = chr->opaque;
4100 s->reconnect_timer = 0;
4102 if (chr->be_open) {
4103 return false;
4106 socket_try_connect(chr);
4108 return false;
4111 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
4112 Error **errp)
4114 CharDriverState *chr;
4115 TCPCharDriver *s;
4116 SocketAddress *addr = sock->addr;
4117 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
4118 bool is_listen = sock->has_server ? sock->server : true;
4119 bool is_telnet = sock->has_telnet ? sock->telnet : false;
4120 bool is_waitconnect = sock->has_wait ? sock->wait : false;
4121 int64_t reconnect = sock->has_reconnect ? sock->reconnect : 0;
4123 chr = qemu_chr_alloc();
4124 s = g_malloc0(sizeof(TCPCharDriver));
4126 s->fd = -1;
4127 s->listen_fd = -1;
4128 s->is_unix = addr->kind == SOCKET_ADDRESS_KIND_UNIX;
4129 s->is_listen = is_listen;
4130 s->is_telnet = is_telnet;
4131 s->do_nodelay = do_nodelay;
4132 qapi_copy_SocketAddress(&s->addr, sock->addr);
4134 chr->opaque = s;
4135 chr->chr_write = tcp_chr_write;
4136 chr->chr_sync_read = tcp_chr_sync_read;
4137 chr->chr_close = tcp_chr_close;
4138 chr->get_msgfds = tcp_get_msgfds;
4139 chr->set_msgfds = tcp_set_msgfds;
4140 chr->chr_add_client = tcp_chr_add_client;
4141 chr->chr_add_watch = tcp_chr_add_watch;
4142 chr->chr_update_read_handler = tcp_chr_update_read_handler;
4143 /* be isn't opened until we get a connection */
4144 chr->explicit_be_open = true;
4146 chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
4147 SocketAddress_to_str(chr->filename, CHR_MAX_FILENAME_SIZE, "disconnected:",
4148 addr, is_listen, is_telnet);
4150 if (is_listen) {
4151 if (is_telnet) {
4152 s->do_telnetopt = 1;
4154 } else if (reconnect > 0) {
4155 s->reconnect_time = reconnect;
4158 if (s->reconnect_time) {
4159 socket_try_connect(chr);
4160 } else if (!qemu_chr_open_socket_fd(chr, errp)) {
4161 g_free(s);
4162 g_free(chr->filename);
4163 g_free(chr);
4164 return NULL;
4167 if (is_listen && is_waitconnect) {
4168 fprintf(stderr, "QEMU waiting for connection on: %s\n",
4169 chr->filename);
4170 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
4171 qemu_set_nonblock(s->listen_fd);
4174 return chr;
4177 static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
4178 Error **errp)
4180 int fd;
4182 fd = socket_dgram(udp->remote, udp->local, errp);
4183 if (fd < 0) {
4184 return NULL;
4186 return qemu_chr_open_udp_fd(fd);
4189 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4190 Error **errp)
4192 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4193 CharDriverState *base, *chr = NULL;
4195 chr = qemu_chr_find(id);
4196 if (chr) {
4197 error_setg(errp, "Chardev '%s' already exists", id);
4198 g_free(ret);
4199 return NULL;
4202 switch (backend->kind) {
4203 case CHARDEV_BACKEND_KIND_FILE:
4204 chr = qmp_chardev_open_file(backend->file, errp);
4205 break;
4206 case CHARDEV_BACKEND_KIND_SERIAL:
4207 chr = qmp_chardev_open_serial(backend->serial, errp);
4208 break;
4209 case CHARDEV_BACKEND_KIND_PARALLEL:
4210 chr = qmp_chardev_open_parallel(backend->parallel, errp);
4211 break;
4212 case CHARDEV_BACKEND_KIND_PIPE:
4213 chr = qemu_chr_open_pipe(backend->pipe);
4214 break;
4215 case CHARDEV_BACKEND_KIND_SOCKET:
4216 chr = qmp_chardev_open_socket(backend->socket, errp);
4217 break;
4218 case CHARDEV_BACKEND_KIND_UDP:
4219 chr = qmp_chardev_open_udp(backend->udp, errp);
4220 break;
4221 #ifdef HAVE_CHARDEV_TTY
4222 case CHARDEV_BACKEND_KIND_PTY:
4223 chr = qemu_chr_open_pty(id, ret);
4224 break;
4225 #endif
4226 case CHARDEV_BACKEND_KIND_NULL:
4227 chr = qemu_chr_open_null();
4228 break;
4229 case CHARDEV_BACKEND_KIND_MUX:
4230 base = qemu_chr_find(backend->mux->chardev);
4231 if (base == NULL) {
4232 error_setg(errp, "mux: base chardev %s not found",
4233 backend->mux->chardev);
4234 break;
4236 chr = qemu_chr_open_mux(base);
4237 break;
4238 case CHARDEV_BACKEND_KIND_MSMOUSE:
4239 chr = qemu_chr_open_msmouse();
4240 break;
4241 #ifdef CONFIG_BRLAPI
4242 case CHARDEV_BACKEND_KIND_BRAILLE:
4243 chr = chr_baum_init();
4244 break;
4245 #endif
4246 case CHARDEV_BACKEND_KIND_TESTDEV:
4247 chr = chr_testdev_init();
4248 break;
4249 case CHARDEV_BACKEND_KIND_STDIO:
4250 chr = qemu_chr_open_stdio(backend->stdio);
4251 break;
4252 #ifdef _WIN32
4253 case CHARDEV_BACKEND_KIND_CONSOLE:
4254 chr = qemu_chr_open_win_con();
4255 break;
4256 #endif
4257 #ifdef CONFIG_SPICE
4258 case CHARDEV_BACKEND_KIND_SPICEVMC:
4259 chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
4260 break;
4261 case CHARDEV_BACKEND_KIND_SPICEPORT:
4262 chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
4263 break;
4264 #endif
4265 case CHARDEV_BACKEND_KIND_VC:
4266 chr = vc_init(backend->vc);
4267 break;
4268 case CHARDEV_BACKEND_KIND_RINGBUF:
4269 case CHARDEV_BACKEND_KIND_MEMORY:
4270 chr = qemu_chr_open_ringbuf(backend->ringbuf, errp);
4271 break;
4272 default:
4273 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
4274 break;
4278 * Character backend open hasn't been fully converted to the Error
4279 * API. Some opens fail without setting an error. Set a generic
4280 * error then.
4281 * TODO full conversion to Error API
4283 if (chr == NULL && errp && !*errp) {
4284 error_setg(errp, "Failed to create chardev");
4286 if (chr) {
4287 chr->label = g_strdup(id);
4288 chr->avail_connections =
4289 (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4290 if (!chr->filename) {
4291 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
4293 if (!chr->explicit_be_open) {
4294 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4296 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4297 return ret;
4298 } else {
4299 g_free(ret);
4300 return NULL;
4304 void qmp_chardev_remove(const char *id, Error **errp)
4306 CharDriverState *chr;
4308 chr = qemu_chr_find(id);
4309 if (chr == NULL) {
4310 error_setg(errp, "Chardev '%s' not found", id);
4311 return;
4313 if (chr->chr_can_read || chr->chr_read ||
4314 chr->chr_event || chr->handler_opaque) {
4315 error_setg(errp, "Chardev '%s' is busy", id);
4316 return;
4318 qemu_chr_delete(chr);
4321 static void register_types(void)
4323 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL);
4324 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4325 qemu_chr_parse_socket);
4326 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp);
4327 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4328 qemu_chr_parse_ringbuf);
4329 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4330 qemu_chr_parse_file_out);
4331 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4332 qemu_chr_parse_stdio);
4333 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4334 qemu_chr_parse_serial);
4335 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4336 qemu_chr_parse_serial);
4337 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4338 qemu_chr_parse_parallel);
4339 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4340 qemu_chr_parse_parallel);
4341 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
4342 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
4343 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4344 qemu_chr_parse_pipe);
4345 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux);
4346 /* Bug-compatibility: */
4347 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4348 qemu_chr_parse_ringbuf);
4349 /* this must be done after machine init, since we register FEs with muxes
4350 * as part of realize functions like serial_isa_realizefn when -nographic
4351 * is specified
4353 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4356 type_init(register_types);