virtio-9p: use aliases instead of duplicate qdev properties
[qemu/ar7.git] / qemu-char.c
blob8623c7096446a32e2b3e37c78cb9640e9827b25f
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"
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <time.h>
35 #include <errno.h>
36 #include <sys/time.h>
37 #include <zlib.h>
39 #ifndef _WIN32
40 #include <sys/times.h>
41 #include <sys/wait.h>
42 #include <termios.h>
43 #include <sys/mman.h>
44 #include <sys/ioctl.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <net/if.h>
49 #include <arpa/inet.h>
50 #include <dirent.h>
51 #include <netdb.h>
52 #include <sys/select.h>
53 #ifdef CONFIG_BSD
54 #include <sys/stat.h>
55 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
56 #include <dev/ppbus/ppi.h>
57 #include <dev/ppbus/ppbconf.h>
58 #elif defined(__DragonFly__)
59 #include <dev/misc/ppi/ppi.h>
60 #include <bus/ppbus/ppbconf.h>
61 #endif
62 #else
63 #ifdef __linux__
64 #include <linux/ppdev.h>
65 #include <linux/parport.h>
66 #endif
67 #ifdef __sun__
68 #include <sys/stat.h>
69 #include <sys/ethernet.h>
70 #include <sys/sockio.h>
71 #include <netinet/arp.h>
72 #include <netinet/in.h>
73 #include <netinet/in_systm.h>
74 #include <netinet/ip.h>
75 #include <netinet/ip_icmp.h> // must come after ip.h
76 #include <netinet/udp.h>
77 #include <netinet/tcp.h>
78 #endif
79 #endif
80 #endif
82 #include "qemu/sockets.h"
83 #include "ui/qemu-spice.h"
85 #define READ_BUF_LEN 4096
86 #define READ_RETRIES 10
88 /***********************************************************/
89 /* character device */
91 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
92 QTAILQ_HEAD_INITIALIZER(chardevs);
94 CharDriverState *qemu_chr_alloc(void)
96 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
97 qemu_mutex_init(&chr->chr_write_lock);
98 return chr;
101 void qemu_chr_be_event(CharDriverState *s, int event)
103 /* Keep track if the char device is open */
104 switch (event) {
105 case CHR_EVENT_OPENED:
106 s->be_open = 1;
107 break;
108 case CHR_EVENT_CLOSED:
109 s->be_open = 0;
110 break;
113 if (!s->chr_event)
114 return;
115 s->chr_event(s->handler_opaque, event);
118 void qemu_chr_be_generic_open(CharDriverState *s)
120 qemu_chr_be_event(s, CHR_EVENT_OPENED);
123 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
125 int ret;
127 qemu_mutex_lock(&s->chr_write_lock);
128 ret = s->chr_write(s, buf, len);
129 qemu_mutex_unlock(&s->chr_write_lock);
130 return ret;
133 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
135 int offset = 0;
136 int res = 0;
138 qemu_mutex_lock(&s->chr_write_lock);
139 while (offset < len) {
140 do {
141 res = s->chr_write(s, buf + offset, len - offset);
142 if (res == -1 && errno == EAGAIN) {
143 g_usleep(100);
145 } while (res == -1 && errno == EAGAIN);
147 if (res <= 0) {
148 break;
151 offset += res;
153 qemu_mutex_unlock(&s->chr_write_lock);
155 if (res < 0) {
156 return res;
158 return offset;
161 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
163 int offset = 0, counter = 10;
164 int res;
166 if (!s->chr_sync_read) {
167 return 0;
170 while (offset < len) {
171 do {
172 res = s->chr_sync_read(s, buf + offset, len - offset);
173 if (res == -1 && errno == EAGAIN) {
174 g_usleep(100);
176 } while (res == -1 && errno == EAGAIN);
178 if (res == 0) {
179 break;
182 if (res < 0) {
183 return res;
186 offset += res;
188 if (!counter--) {
189 break;
193 return offset;
196 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
198 if (!s->chr_ioctl)
199 return -ENOTSUP;
200 return s->chr_ioctl(s, cmd, arg);
203 int qemu_chr_be_can_write(CharDriverState *s)
205 if (!s->chr_can_read)
206 return 0;
207 return s->chr_can_read(s->handler_opaque);
210 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
212 if (s->chr_read) {
213 s->chr_read(s->handler_opaque, buf, len);
217 int qemu_chr_fe_get_msgfd(CharDriverState *s)
219 int fd;
220 return (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
223 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
225 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
228 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
230 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
233 int qemu_chr_add_client(CharDriverState *s, int fd)
235 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
238 void qemu_chr_accept_input(CharDriverState *s)
240 if (s->chr_accept_input)
241 s->chr_accept_input(s);
242 qemu_notify_event();
245 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
247 char buf[READ_BUF_LEN];
248 va_list ap;
249 va_start(ap, fmt);
250 vsnprintf(buf, sizeof(buf), fmt, ap);
251 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
252 va_end(ap);
255 static void remove_fd_in_watch(CharDriverState *chr);
257 void qemu_chr_add_handlers(CharDriverState *s,
258 IOCanReadHandler *fd_can_read,
259 IOReadHandler *fd_read,
260 IOEventHandler *fd_event,
261 void *opaque)
263 int fe_open;
265 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
266 fe_open = 0;
267 remove_fd_in_watch(s);
268 } else {
269 fe_open = 1;
271 s->chr_can_read = fd_can_read;
272 s->chr_read = fd_read;
273 s->chr_event = fd_event;
274 s->handler_opaque = opaque;
275 if (fe_open && s->chr_update_read_handler)
276 s->chr_update_read_handler(s);
278 if (!s->explicit_fe_open) {
279 qemu_chr_fe_set_open(s, fe_open);
282 /* We're connecting to an already opened device, so let's make sure we
283 also get the open event */
284 if (fe_open && s->be_open) {
285 qemu_chr_be_generic_open(s);
289 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
291 return len;
294 static CharDriverState *qemu_chr_open_null(void)
296 CharDriverState *chr;
298 chr = qemu_chr_alloc();
299 chr->chr_write = null_chr_write;
300 chr->explicit_be_open = true;
301 return chr;
304 /* MUX driver for serial I/O splitting */
305 #define MAX_MUX 4
306 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
307 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
308 typedef struct {
309 IOCanReadHandler *chr_can_read[MAX_MUX];
310 IOReadHandler *chr_read[MAX_MUX];
311 IOEventHandler *chr_event[MAX_MUX];
312 void *ext_opaque[MAX_MUX];
313 CharDriverState *drv;
314 int focus;
315 int mux_cnt;
316 int term_got_escape;
317 int max_size;
318 /* Intermediate input buffer allows to catch escape sequences even if the
319 currently active device is not accepting any input - but only until it
320 is full as well. */
321 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
322 int prod[MAX_MUX];
323 int cons[MAX_MUX];
324 int timestamps;
326 /* Protected by the CharDriverState chr_write_lock. */
327 int linestart;
328 int64_t timestamps_start;
329 } MuxDriver;
332 /* Called with chr_write_lock held. */
333 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
335 MuxDriver *d = chr->opaque;
336 int ret;
337 if (!d->timestamps) {
338 ret = qemu_chr_fe_write(d->drv, buf, len);
339 } else {
340 int i;
342 ret = 0;
343 for (i = 0; i < len; i++) {
344 if (d->linestart) {
345 char buf1[64];
346 int64_t ti;
347 int secs;
349 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
350 if (d->timestamps_start == -1)
351 d->timestamps_start = ti;
352 ti -= d->timestamps_start;
353 secs = ti / 1000;
354 snprintf(buf1, sizeof(buf1),
355 "[%02d:%02d:%02d.%03d] ",
356 secs / 3600,
357 (secs / 60) % 60,
358 secs % 60,
359 (int)(ti % 1000));
360 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
361 d->linestart = 0;
363 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
364 if (buf[i] == '\n') {
365 d->linestart = 1;
369 return ret;
372 static const char * const mux_help[] = {
373 "% h print this help\n\r",
374 "% x exit emulator\n\r",
375 "% s save disk data back to file (if -snapshot)\n\r",
376 "% t toggle console timestamps\n\r"
377 "% b send break (magic sysrq)\n\r",
378 "% c switch between console and monitor\n\r",
379 "% % sends %\n\r",
380 NULL
383 int term_escape_char = 0x01; /* ctrl-a is used for escape */
384 static void mux_print_help(CharDriverState *chr)
386 int i, j;
387 char ebuf[15] = "Escape-Char";
388 char cbuf[50] = "\n\r";
390 if (term_escape_char > 0 && term_escape_char < 26) {
391 snprintf(cbuf, sizeof(cbuf), "\n\r");
392 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
393 } else {
394 snprintf(cbuf, sizeof(cbuf),
395 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
396 term_escape_char);
398 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
399 for (i = 0; mux_help[i] != NULL; i++) {
400 for (j=0; mux_help[i][j] != '\0'; j++) {
401 if (mux_help[i][j] == '%')
402 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
403 else
404 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
409 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
411 if (d->chr_event[mux_nr])
412 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
415 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
417 if (d->term_got_escape) {
418 d->term_got_escape = 0;
419 if (ch == term_escape_char)
420 goto send_char;
421 switch(ch) {
422 case '?':
423 case 'h':
424 mux_print_help(chr);
425 break;
426 case 'x':
428 const char *term = "QEMU: Terminated\n\r";
429 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
430 exit(0);
431 break;
433 case 's':
434 bdrv_commit_all();
435 break;
436 case 'b':
437 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
438 break;
439 case 'c':
440 /* Switch to the next registered device */
441 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
442 d->focus++;
443 if (d->focus >= d->mux_cnt)
444 d->focus = 0;
445 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
446 break;
447 case 't':
448 d->timestamps = !d->timestamps;
449 d->timestamps_start = -1;
450 d->linestart = 0;
451 break;
453 } else if (ch == term_escape_char) {
454 d->term_got_escape = 1;
455 } else {
456 send_char:
457 return 1;
459 return 0;
462 static void mux_chr_accept_input(CharDriverState *chr)
464 MuxDriver *d = chr->opaque;
465 int m = d->focus;
467 while (d->prod[m] != d->cons[m] &&
468 d->chr_can_read[m] &&
469 d->chr_can_read[m](d->ext_opaque[m])) {
470 d->chr_read[m](d->ext_opaque[m],
471 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
475 static int mux_chr_can_read(void *opaque)
477 CharDriverState *chr = opaque;
478 MuxDriver *d = chr->opaque;
479 int m = d->focus;
481 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
482 return 1;
483 if (d->chr_can_read[m])
484 return d->chr_can_read[m](d->ext_opaque[m]);
485 return 0;
488 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
490 CharDriverState *chr = opaque;
491 MuxDriver *d = chr->opaque;
492 int m = d->focus;
493 int i;
495 mux_chr_accept_input (opaque);
497 for(i = 0; i < size; i++)
498 if (mux_proc_byte(chr, d, buf[i])) {
499 if (d->prod[m] == d->cons[m] &&
500 d->chr_can_read[m] &&
501 d->chr_can_read[m](d->ext_opaque[m]))
502 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
503 else
504 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
508 static void mux_chr_event(void *opaque, int event)
510 CharDriverState *chr = opaque;
511 MuxDriver *d = chr->opaque;
512 int i;
514 /* Send the event to all registered listeners */
515 for (i = 0; i < d->mux_cnt; i++)
516 mux_chr_send_event(d, i, event);
519 static void mux_chr_update_read_handler(CharDriverState *chr)
521 MuxDriver *d = chr->opaque;
523 if (d->mux_cnt >= MAX_MUX) {
524 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
525 return;
527 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
528 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
529 d->chr_read[d->mux_cnt] = chr->chr_read;
530 d->chr_event[d->mux_cnt] = chr->chr_event;
531 /* Fix up the real driver with mux routines */
532 if (d->mux_cnt == 0) {
533 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
534 mux_chr_event, chr);
536 if (d->focus != -1) {
537 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
539 d->focus = d->mux_cnt;
540 d->mux_cnt++;
541 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
544 static bool muxes_realized;
547 * Called after processing of default and command-line-specified
548 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
549 * to a mux chardev. This is done here to ensure that
550 * output/prompts/banners are only displayed for the FE that has
551 * focus when initial command-line processing/machine init is
552 * completed.
554 * After this point, any new FE attached to any new or existing
555 * mux will receive CHR_EVENT_OPENED notifications for the BE
556 * immediately.
558 static void muxes_realize_done(Notifier *notifier, void *unused)
560 CharDriverState *chr;
562 QTAILQ_FOREACH(chr, &chardevs, next) {
563 if (chr->is_mux) {
564 MuxDriver *d = chr->opaque;
565 int i;
567 /* send OPENED to all already-attached FEs */
568 for (i = 0; i < d->mux_cnt; i++) {
569 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
571 /* mark mux as OPENED so any new FEs will immediately receive
572 * OPENED event
574 qemu_chr_be_generic_open(chr);
577 muxes_realized = true;
580 static Notifier muxes_realize_notify = {
581 .notify = muxes_realize_done,
584 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
586 MuxDriver *d = s->opaque;
587 return d->drv->chr_add_watch(d->drv, cond);
590 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
592 CharDriverState *chr;
593 MuxDriver *d;
595 chr = qemu_chr_alloc();
596 d = g_malloc0(sizeof(MuxDriver));
598 chr->opaque = d;
599 d->drv = drv;
600 d->focus = -1;
601 chr->chr_write = mux_chr_write;
602 chr->chr_update_read_handler = mux_chr_update_read_handler;
603 chr->chr_accept_input = mux_chr_accept_input;
604 /* Frontend guest-open / -close notification is not support with muxes */
605 chr->chr_set_fe_open = NULL;
606 if (drv->chr_add_watch) {
607 chr->chr_add_watch = mux_chr_add_watch;
609 /* only default to opened state if we've realized the initial
610 * set of muxes
612 chr->explicit_be_open = muxes_realized ? 0 : 1;
613 chr->is_mux = 1;
615 return chr;
619 #ifdef _WIN32
620 int send_all(int fd, const void *buf, int len1)
622 int ret, len;
624 len = len1;
625 while (len > 0) {
626 ret = send(fd, buf, len, 0);
627 if (ret < 0) {
628 errno = WSAGetLastError();
629 if (errno != WSAEWOULDBLOCK) {
630 return -1;
632 } else if (ret == 0) {
633 break;
634 } else {
635 buf += ret;
636 len -= ret;
639 return len1 - len;
642 #else
644 int send_all(int fd, const void *_buf, int len1)
646 int ret, len;
647 const uint8_t *buf = _buf;
649 len = len1;
650 while (len > 0) {
651 ret = write(fd, buf, len);
652 if (ret < 0) {
653 if (errno != EINTR && errno != EAGAIN)
654 return -1;
655 } else if (ret == 0) {
656 break;
657 } else {
658 buf += ret;
659 len -= ret;
662 return len1 - len;
665 int recv_all(int fd, void *_buf, int len1, bool single_read)
667 int ret, len;
668 uint8_t *buf = _buf;
670 len = len1;
671 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
672 if (ret < 0) {
673 if (errno != EINTR && errno != EAGAIN) {
674 return -1;
676 continue;
677 } else {
678 if (single_read) {
679 return ret;
681 buf += ret;
682 len -= ret;
685 return len1 - len;
688 #endif /* !_WIN32 */
690 typedef struct IOWatchPoll
692 GSource parent;
694 GIOChannel *channel;
695 GSource *src;
697 IOCanReadHandler *fd_can_read;
698 GSourceFunc fd_read;
699 void *opaque;
700 } IOWatchPoll;
702 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
704 return container_of(source, IOWatchPoll, parent);
707 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
709 IOWatchPoll *iwp = io_watch_poll_from_source(source);
710 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
711 bool was_active = iwp->src != NULL;
712 if (was_active == now_active) {
713 return FALSE;
716 if (now_active) {
717 iwp->src = g_io_create_watch(iwp->channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
718 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
719 g_source_attach(iwp->src, NULL);
720 } else {
721 g_source_destroy(iwp->src);
722 g_source_unref(iwp->src);
723 iwp->src = NULL;
725 return FALSE;
728 static gboolean io_watch_poll_check(GSource *source)
730 return FALSE;
733 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
734 gpointer user_data)
736 abort();
739 static void io_watch_poll_finalize(GSource *source)
741 /* Due to a glib bug, removing the last reference to a source
742 * inside a finalize callback causes recursive locking (and a
743 * deadlock). This is not a problem inside other callbacks,
744 * including dispatch callbacks, so we call io_remove_watch_poll
745 * to remove this source. At this point, iwp->src must
746 * be NULL, or we would leak it.
748 * This would be solved much more elegantly by child sources,
749 * but we support older glib versions that do not have them.
751 IOWatchPoll *iwp = io_watch_poll_from_source(source);
752 assert(iwp->src == NULL);
755 static GSourceFuncs io_watch_poll_funcs = {
756 .prepare = io_watch_poll_prepare,
757 .check = io_watch_poll_check,
758 .dispatch = io_watch_poll_dispatch,
759 .finalize = io_watch_poll_finalize,
762 /* Can only be used for read */
763 static guint io_add_watch_poll(GIOChannel *channel,
764 IOCanReadHandler *fd_can_read,
765 GIOFunc fd_read,
766 gpointer user_data)
768 IOWatchPoll *iwp;
769 int tag;
771 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
772 iwp->fd_can_read = fd_can_read;
773 iwp->opaque = user_data;
774 iwp->channel = channel;
775 iwp->fd_read = (GSourceFunc) fd_read;
776 iwp->src = NULL;
778 tag = g_source_attach(&iwp->parent, NULL);
779 g_source_unref(&iwp->parent);
780 return tag;
783 static void io_remove_watch_poll(guint tag)
785 GSource *source;
786 IOWatchPoll *iwp;
788 g_return_if_fail (tag > 0);
790 source = g_main_context_find_source_by_id(NULL, tag);
791 g_return_if_fail (source != NULL);
793 iwp = io_watch_poll_from_source(source);
794 if (iwp->src) {
795 g_source_destroy(iwp->src);
796 g_source_unref(iwp->src);
797 iwp->src = NULL;
799 g_source_destroy(&iwp->parent);
802 static void remove_fd_in_watch(CharDriverState *chr)
804 if (chr->fd_in_tag) {
805 io_remove_watch_poll(chr->fd_in_tag);
806 chr->fd_in_tag = 0;
810 #ifndef _WIN32
811 static GIOChannel *io_channel_from_fd(int fd)
813 GIOChannel *chan;
815 if (fd == -1) {
816 return NULL;
819 chan = g_io_channel_unix_new(fd);
821 g_io_channel_set_encoding(chan, NULL, NULL);
822 g_io_channel_set_buffered(chan, FALSE);
824 return chan;
826 #endif
828 static GIOChannel *io_channel_from_socket(int fd)
830 GIOChannel *chan;
832 if (fd == -1) {
833 return NULL;
836 #ifdef _WIN32
837 chan = g_io_channel_win32_new_socket(fd);
838 #else
839 chan = g_io_channel_unix_new(fd);
840 #endif
842 g_io_channel_set_encoding(chan, NULL, NULL);
843 g_io_channel_set_buffered(chan, FALSE);
845 return chan;
848 static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
850 size_t offset = 0;
851 GIOStatus status = G_IO_STATUS_NORMAL;
853 while (offset < len && status == G_IO_STATUS_NORMAL) {
854 gsize bytes_written = 0;
856 status = g_io_channel_write_chars(fd, buf + offset, len - offset,
857 &bytes_written, NULL);
858 offset += bytes_written;
861 if (offset > 0) {
862 return offset;
864 switch (status) {
865 case G_IO_STATUS_NORMAL:
866 g_assert(len == 0);
867 return 0;
868 case G_IO_STATUS_AGAIN:
869 errno = EAGAIN;
870 return -1;
871 default:
872 break;
874 errno = EINVAL;
875 return -1;
878 #ifndef _WIN32
880 typedef struct FDCharDriver {
881 CharDriverState *chr;
882 GIOChannel *fd_in, *fd_out;
883 int max_size;
884 QTAILQ_ENTRY(FDCharDriver) node;
885 } FDCharDriver;
887 /* Called with chr_write_lock held. */
888 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
890 FDCharDriver *s = chr->opaque;
892 return io_channel_send(s->fd_out, buf, len);
895 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
897 CharDriverState *chr = opaque;
898 FDCharDriver *s = chr->opaque;
899 int len;
900 uint8_t buf[READ_BUF_LEN];
901 GIOStatus status;
902 gsize bytes_read;
904 len = sizeof(buf);
905 if (len > s->max_size) {
906 len = s->max_size;
908 if (len == 0) {
909 return TRUE;
912 status = g_io_channel_read_chars(chan, (gchar *)buf,
913 len, &bytes_read, NULL);
914 if (status == G_IO_STATUS_EOF) {
915 remove_fd_in_watch(chr);
916 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
917 return FALSE;
919 if (status == G_IO_STATUS_NORMAL) {
920 qemu_chr_be_write(chr, buf, bytes_read);
923 return TRUE;
926 static int fd_chr_read_poll(void *opaque)
928 CharDriverState *chr = opaque;
929 FDCharDriver *s = chr->opaque;
931 s->max_size = qemu_chr_be_can_write(chr);
932 return s->max_size;
935 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
937 FDCharDriver *s = chr->opaque;
938 return g_io_create_watch(s->fd_out, cond);
941 static void fd_chr_update_read_handler(CharDriverState *chr)
943 FDCharDriver *s = chr->opaque;
945 remove_fd_in_watch(chr);
946 if (s->fd_in) {
947 chr->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll,
948 fd_chr_read, chr);
952 static void fd_chr_close(struct CharDriverState *chr)
954 FDCharDriver *s = chr->opaque;
956 remove_fd_in_watch(chr);
957 if (s->fd_in) {
958 g_io_channel_unref(s->fd_in);
960 if (s->fd_out) {
961 g_io_channel_unref(s->fd_out);
964 g_free(s);
965 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
968 /* open a character device to a unix fd */
969 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
971 CharDriverState *chr;
972 FDCharDriver *s;
974 chr = qemu_chr_alloc();
975 s = g_malloc0(sizeof(FDCharDriver));
976 s->fd_in = io_channel_from_fd(fd_in);
977 s->fd_out = io_channel_from_fd(fd_out);
978 qemu_set_nonblock(fd_out);
979 s->chr = chr;
980 chr->opaque = s;
981 chr->chr_add_watch = fd_chr_add_watch;
982 chr->chr_write = fd_chr_write;
983 chr->chr_update_read_handler = fd_chr_update_read_handler;
984 chr->chr_close = fd_chr_close;
986 return chr;
989 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
991 int fd_in, fd_out;
992 char filename_in[256], filename_out[256];
993 const char *filename = opts->device;
995 if (filename == NULL) {
996 fprintf(stderr, "chardev: pipe: no filename given\n");
997 return NULL;
1000 snprintf(filename_in, 256, "%s.in", filename);
1001 snprintf(filename_out, 256, "%s.out", filename);
1002 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1003 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1004 if (fd_in < 0 || fd_out < 0) {
1005 if (fd_in >= 0)
1006 close(fd_in);
1007 if (fd_out >= 0)
1008 close(fd_out);
1009 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1010 if (fd_in < 0) {
1011 return NULL;
1014 return qemu_chr_open_fd(fd_in, fd_out);
1017 /* init terminal so that we can grab keys */
1018 static struct termios oldtty;
1019 static int old_fd0_flags;
1020 static bool stdio_in_use;
1021 static bool stdio_allow_signal;
1023 static void term_exit(void)
1025 tcsetattr (0, TCSANOW, &oldtty);
1026 fcntl(0, F_SETFL, old_fd0_flags);
1029 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1031 struct termios tty;
1033 tty = oldtty;
1034 if (!echo) {
1035 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1036 |INLCR|IGNCR|ICRNL|IXON);
1037 tty.c_oflag |= OPOST;
1038 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1039 tty.c_cflag &= ~(CSIZE|PARENB);
1040 tty.c_cflag |= CS8;
1041 tty.c_cc[VMIN] = 1;
1042 tty.c_cc[VTIME] = 0;
1044 if (!stdio_allow_signal)
1045 tty.c_lflag &= ~ISIG;
1047 tcsetattr (0, TCSANOW, &tty);
1050 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1052 term_exit();
1053 fd_chr_close(chr);
1056 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
1058 CharDriverState *chr;
1060 if (is_daemonized()) {
1061 error_report("cannot use stdio with -daemonize");
1062 return NULL;
1065 if (stdio_in_use) {
1066 error_report("cannot use stdio by multiple character devices");
1067 exit(1);
1070 stdio_in_use = true;
1071 old_fd0_flags = fcntl(0, F_GETFL);
1072 tcgetattr(0, &oldtty);
1073 qemu_set_nonblock(0);
1074 atexit(term_exit);
1076 chr = qemu_chr_open_fd(0, 1);
1077 chr->chr_close = qemu_chr_close_stdio;
1078 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1079 if (opts->has_signal) {
1080 stdio_allow_signal = opts->signal;
1082 qemu_chr_fe_set_echo(chr, false);
1084 return chr;
1087 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1088 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1089 || defined(__GLIBC__)
1091 #define HAVE_CHARDEV_TTY 1
1093 typedef struct {
1094 GIOChannel *fd;
1095 int read_bytes;
1097 /* Protected by the CharDriverState chr_write_lock. */
1098 int connected;
1099 guint timer_tag;
1100 guint open_tag;
1101 } PtyCharDriver;
1103 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1104 static void pty_chr_state(CharDriverState *chr, int connected);
1106 static gboolean pty_chr_timer(gpointer opaque)
1108 struct CharDriverState *chr = opaque;
1109 PtyCharDriver *s = chr->opaque;
1111 qemu_mutex_lock(&chr->chr_write_lock);
1112 s->timer_tag = 0;
1113 s->open_tag = 0;
1114 if (!s->connected) {
1115 /* Next poll ... */
1116 pty_chr_update_read_handler_locked(chr);
1118 qemu_mutex_unlock(&chr->chr_write_lock);
1119 return FALSE;
1122 /* Called with chr_write_lock held. */
1123 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1125 PtyCharDriver *s = chr->opaque;
1127 if (s->timer_tag) {
1128 g_source_remove(s->timer_tag);
1129 s->timer_tag = 0;
1132 if (ms == 1000) {
1133 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1134 } else {
1135 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1139 /* Called with chr_write_lock held. */
1140 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1142 PtyCharDriver *s = chr->opaque;
1143 GPollFD pfd;
1145 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1146 pfd.events = G_IO_OUT;
1147 pfd.revents = 0;
1148 g_poll(&pfd, 1, 0);
1149 if (pfd.revents & G_IO_HUP) {
1150 pty_chr_state(chr, 0);
1151 } else {
1152 pty_chr_state(chr, 1);
1156 static void pty_chr_update_read_handler(CharDriverState *chr)
1158 qemu_mutex_lock(&chr->chr_write_lock);
1159 pty_chr_update_read_handler_locked(chr);
1160 qemu_mutex_unlock(&chr->chr_write_lock);
1163 /* Called with chr_write_lock held. */
1164 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1166 PtyCharDriver *s = chr->opaque;
1168 if (!s->connected) {
1169 /* guest sends data, check for (re-)connect */
1170 pty_chr_update_read_handler_locked(chr);
1171 if (!s->connected) {
1172 return 0;
1175 return io_channel_send(s->fd, buf, len);
1178 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1180 PtyCharDriver *s = chr->opaque;
1181 if (!s->connected) {
1182 return NULL;
1184 return g_io_create_watch(s->fd, cond);
1187 static int pty_chr_read_poll(void *opaque)
1189 CharDriverState *chr = opaque;
1190 PtyCharDriver *s = chr->opaque;
1192 s->read_bytes = qemu_chr_be_can_write(chr);
1193 return s->read_bytes;
1196 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1198 CharDriverState *chr = opaque;
1199 PtyCharDriver *s = chr->opaque;
1200 gsize size, len;
1201 uint8_t buf[READ_BUF_LEN];
1202 GIOStatus status;
1204 len = sizeof(buf);
1205 if (len > s->read_bytes)
1206 len = s->read_bytes;
1207 if (len == 0) {
1208 return TRUE;
1210 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1211 if (status != G_IO_STATUS_NORMAL) {
1212 pty_chr_state(chr, 0);
1213 return FALSE;
1214 } else {
1215 pty_chr_state(chr, 1);
1216 qemu_chr_be_write(chr, buf, size);
1218 return TRUE;
1221 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1223 CharDriverState *chr = opaque;
1224 PtyCharDriver *s = chr->opaque;
1226 s->open_tag = 0;
1227 qemu_chr_be_generic_open(chr);
1228 return FALSE;
1231 /* Called with chr_write_lock held. */
1232 static void pty_chr_state(CharDriverState *chr, int connected)
1234 PtyCharDriver *s = chr->opaque;
1236 if (!connected) {
1237 if (s->open_tag) {
1238 g_source_remove(s->open_tag);
1239 s->open_tag = 0;
1241 remove_fd_in_watch(chr);
1242 s->connected = 0;
1243 /* (re-)connect poll interval for idle guests: once per second.
1244 * We check more frequently in case the guests sends data to
1245 * the virtual device linked to our pty. */
1246 pty_chr_rearm_timer(chr, 1000);
1247 } else {
1248 if (s->timer_tag) {
1249 g_source_remove(s->timer_tag);
1250 s->timer_tag = 0;
1252 if (!s->connected) {
1253 g_assert(s->open_tag == 0);
1254 s->connected = 1;
1255 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1257 if (!chr->fd_in_tag) {
1258 chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
1259 pty_chr_read, chr);
1264 static void pty_chr_close(struct CharDriverState *chr)
1266 PtyCharDriver *s = chr->opaque;
1267 int fd;
1269 qemu_mutex_lock(&chr->chr_write_lock);
1270 pty_chr_state(chr, 0);
1271 fd = g_io_channel_unix_get_fd(s->fd);
1272 g_io_channel_unref(s->fd);
1273 close(fd);
1274 if (s->timer_tag) {
1275 g_source_remove(s->timer_tag);
1276 s->timer_tag = 0;
1278 qemu_mutex_unlock(&chr->chr_write_lock);
1279 g_free(s);
1280 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1283 static CharDriverState *qemu_chr_open_pty(const char *id,
1284 ChardevReturn *ret)
1286 CharDriverState *chr;
1287 PtyCharDriver *s;
1288 int master_fd, slave_fd;
1289 char pty_name[PATH_MAX];
1291 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1292 if (master_fd < 0) {
1293 return NULL;
1296 close(slave_fd);
1298 chr = qemu_chr_alloc();
1300 chr->filename = g_strdup_printf("pty:%s", pty_name);
1301 ret->pty = g_strdup(pty_name);
1302 ret->has_pty = true;
1304 fprintf(stderr, "char device redirected to %s (label %s)\n",
1305 pty_name, id);
1307 s = g_malloc0(sizeof(PtyCharDriver));
1308 chr->opaque = s;
1309 chr->chr_write = pty_chr_write;
1310 chr->chr_update_read_handler = pty_chr_update_read_handler;
1311 chr->chr_close = pty_chr_close;
1312 chr->chr_add_watch = pty_chr_add_watch;
1313 chr->explicit_be_open = true;
1315 s->fd = io_channel_from_fd(master_fd);
1316 s->timer_tag = 0;
1318 return chr;
1321 static void tty_serial_init(int fd, int speed,
1322 int parity, int data_bits, int stop_bits)
1324 struct termios tty;
1325 speed_t spd;
1327 #if 0
1328 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1329 speed, parity, data_bits, stop_bits);
1330 #endif
1331 tcgetattr (fd, &tty);
1333 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1334 speed = speed * 10 / 11;
1335 do {
1336 check_speed(50);
1337 check_speed(75);
1338 check_speed(110);
1339 check_speed(134);
1340 check_speed(150);
1341 check_speed(200);
1342 check_speed(300);
1343 check_speed(600);
1344 check_speed(1200);
1345 check_speed(1800);
1346 check_speed(2400);
1347 check_speed(4800);
1348 check_speed(9600);
1349 check_speed(19200);
1350 check_speed(38400);
1351 /* Non-Posix values follow. They may be unsupported on some systems. */
1352 check_speed(57600);
1353 check_speed(115200);
1354 #ifdef B230400
1355 check_speed(230400);
1356 #endif
1357 #ifdef B460800
1358 check_speed(460800);
1359 #endif
1360 #ifdef B500000
1361 check_speed(500000);
1362 #endif
1363 #ifdef B576000
1364 check_speed(576000);
1365 #endif
1366 #ifdef B921600
1367 check_speed(921600);
1368 #endif
1369 #ifdef B1000000
1370 check_speed(1000000);
1371 #endif
1372 #ifdef B1152000
1373 check_speed(1152000);
1374 #endif
1375 #ifdef B1500000
1376 check_speed(1500000);
1377 #endif
1378 #ifdef B2000000
1379 check_speed(2000000);
1380 #endif
1381 #ifdef B2500000
1382 check_speed(2500000);
1383 #endif
1384 #ifdef B3000000
1385 check_speed(3000000);
1386 #endif
1387 #ifdef B3500000
1388 check_speed(3500000);
1389 #endif
1390 #ifdef B4000000
1391 check_speed(4000000);
1392 #endif
1393 spd = B115200;
1394 } while (0);
1396 cfsetispeed(&tty, spd);
1397 cfsetospeed(&tty, spd);
1399 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1400 |INLCR|IGNCR|ICRNL|IXON);
1401 tty.c_oflag |= OPOST;
1402 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1403 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1404 switch(data_bits) {
1405 default:
1406 case 8:
1407 tty.c_cflag |= CS8;
1408 break;
1409 case 7:
1410 tty.c_cflag |= CS7;
1411 break;
1412 case 6:
1413 tty.c_cflag |= CS6;
1414 break;
1415 case 5:
1416 tty.c_cflag |= CS5;
1417 break;
1419 switch(parity) {
1420 default:
1421 case 'N':
1422 break;
1423 case 'E':
1424 tty.c_cflag |= PARENB;
1425 break;
1426 case 'O':
1427 tty.c_cflag |= PARENB | PARODD;
1428 break;
1430 if (stop_bits == 2)
1431 tty.c_cflag |= CSTOPB;
1433 tcsetattr (fd, TCSANOW, &tty);
1436 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1438 FDCharDriver *s = chr->opaque;
1440 switch(cmd) {
1441 case CHR_IOCTL_SERIAL_SET_PARAMS:
1443 QEMUSerialSetParams *ssp = arg;
1444 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1445 ssp->speed, ssp->parity,
1446 ssp->data_bits, ssp->stop_bits);
1448 break;
1449 case CHR_IOCTL_SERIAL_SET_BREAK:
1451 int enable = *(int *)arg;
1452 if (enable) {
1453 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1456 break;
1457 case CHR_IOCTL_SERIAL_GET_TIOCM:
1459 int sarg = 0;
1460 int *targ = (int *)arg;
1461 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1462 *targ = 0;
1463 if (sarg & TIOCM_CTS)
1464 *targ |= CHR_TIOCM_CTS;
1465 if (sarg & TIOCM_CAR)
1466 *targ |= CHR_TIOCM_CAR;
1467 if (sarg & TIOCM_DSR)
1468 *targ |= CHR_TIOCM_DSR;
1469 if (sarg & TIOCM_RI)
1470 *targ |= CHR_TIOCM_RI;
1471 if (sarg & TIOCM_DTR)
1472 *targ |= CHR_TIOCM_DTR;
1473 if (sarg & TIOCM_RTS)
1474 *targ |= CHR_TIOCM_RTS;
1476 break;
1477 case CHR_IOCTL_SERIAL_SET_TIOCM:
1479 int sarg = *(int *)arg;
1480 int targ = 0;
1481 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1482 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1483 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1484 if (sarg & CHR_TIOCM_CTS)
1485 targ |= TIOCM_CTS;
1486 if (sarg & CHR_TIOCM_CAR)
1487 targ |= TIOCM_CAR;
1488 if (sarg & CHR_TIOCM_DSR)
1489 targ |= TIOCM_DSR;
1490 if (sarg & CHR_TIOCM_RI)
1491 targ |= TIOCM_RI;
1492 if (sarg & CHR_TIOCM_DTR)
1493 targ |= TIOCM_DTR;
1494 if (sarg & CHR_TIOCM_RTS)
1495 targ |= TIOCM_RTS;
1496 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1498 break;
1499 default:
1500 return -ENOTSUP;
1502 return 0;
1505 static void qemu_chr_close_tty(CharDriverState *chr)
1507 FDCharDriver *s = chr->opaque;
1508 int fd = -1;
1510 if (s) {
1511 fd = g_io_channel_unix_get_fd(s->fd_in);
1514 fd_chr_close(chr);
1516 if (fd >= 0) {
1517 close(fd);
1521 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1523 CharDriverState *chr;
1525 tty_serial_init(fd, 115200, 'N', 8, 1);
1526 chr = qemu_chr_open_fd(fd, fd);
1527 chr->chr_ioctl = tty_serial_ioctl;
1528 chr->chr_close = qemu_chr_close_tty;
1529 return chr;
1531 #endif /* __linux__ || __sun__ */
1533 #if defined(__linux__)
1535 #define HAVE_CHARDEV_PARPORT 1
1537 typedef struct {
1538 int fd;
1539 int mode;
1540 } ParallelCharDriver;
1542 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1544 if (s->mode != mode) {
1545 int m = mode;
1546 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1547 return 0;
1548 s->mode = mode;
1550 return 1;
1553 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1555 ParallelCharDriver *drv = chr->opaque;
1556 int fd = drv->fd;
1557 uint8_t b;
1559 switch(cmd) {
1560 case CHR_IOCTL_PP_READ_DATA:
1561 if (ioctl(fd, PPRDATA, &b) < 0)
1562 return -ENOTSUP;
1563 *(uint8_t *)arg = b;
1564 break;
1565 case CHR_IOCTL_PP_WRITE_DATA:
1566 b = *(uint8_t *)arg;
1567 if (ioctl(fd, PPWDATA, &b) < 0)
1568 return -ENOTSUP;
1569 break;
1570 case CHR_IOCTL_PP_READ_CONTROL:
1571 if (ioctl(fd, PPRCONTROL, &b) < 0)
1572 return -ENOTSUP;
1573 /* Linux gives only the lowest bits, and no way to know data
1574 direction! For better compatibility set the fixed upper
1575 bits. */
1576 *(uint8_t *)arg = b | 0xc0;
1577 break;
1578 case CHR_IOCTL_PP_WRITE_CONTROL:
1579 b = *(uint8_t *)arg;
1580 if (ioctl(fd, PPWCONTROL, &b) < 0)
1581 return -ENOTSUP;
1582 break;
1583 case CHR_IOCTL_PP_READ_STATUS:
1584 if (ioctl(fd, PPRSTATUS, &b) < 0)
1585 return -ENOTSUP;
1586 *(uint8_t *)arg = b;
1587 break;
1588 case CHR_IOCTL_PP_DATA_DIR:
1589 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1590 return -ENOTSUP;
1591 break;
1592 case CHR_IOCTL_PP_EPP_READ_ADDR:
1593 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1594 struct ParallelIOArg *parg = arg;
1595 int n = read(fd, parg->buffer, parg->count);
1596 if (n != parg->count) {
1597 return -EIO;
1600 break;
1601 case CHR_IOCTL_PP_EPP_READ:
1602 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1603 struct ParallelIOArg *parg = arg;
1604 int n = read(fd, parg->buffer, parg->count);
1605 if (n != parg->count) {
1606 return -EIO;
1609 break;
1610 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1611 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1612 struct ParallelIOArg *parg = arg;
1613 int n = write(fd, parg->buffer, parg->count);
1614 if (n != parg->count) {
1615 return -EIO;
1618 break;
1619 case CHR_IOCTL_PP_EPP_WRITE:
1620 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1621 struct ParallelIOArg *parg = arg;
1622 int n = write(fd, parg->buffer, parg->count);
1623 if (n != parg->count) {
1624 return -EIO;
1627 break;
1628 default:
1629 return -ENOTSUP;
1631 return 0;
1634 static void pp_close(CharDriverState *chr)
1636 ParallelCharDriver *drv = chr->opaque;
1637 int fd = drv->fd;
1639 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1640 ioctl(fd, PPRELEASE);
1641 close(fd);
1642 g_free(drv);
1643 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1646 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1648 CharDriverState *chr;
1649 ParallelCharDriver *drv;
1651 if (ioctl(fd, PPCLAIM) < 0) {
1652 close(fd);
1653 return NULL;
1656 drv = g_malloc0(sizeof(ParallelCharDriver));
1657 drv->fd = fd;
1658 drv->mode = IEEE1284_MODE_COMPAT;
1660 chr = qemu_chr_alloc();
1661 chr->chr_write = null_chr_write;
1662 chr->chr_ioctl = pp_ioctl;
1663 chr->chr_close = pp_close;
1664 chr->opaque = drv;
1666 return chr;
1668 #endif /* __linux__ */
1670 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1672 #define HAVE_CHARDEV_PARPORT 1
1674 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1676 int fd = (int)(intptr_t)chr->opaque;
1677 uint8_t b;
1679 switch(cmd) {
1680 case CHR_IOCTL_PP_READ_DATA:
1681 if (ioctl(fd, PPIGDATA, &b) < 0)
1682 return -ENOTSUP;
1683 *(uint8_t *)arg = b;
1684 break;
1685 case CHR_IOCTL_PP_WRITE_DATA:
1686 b = *(uint8_t *)arg;
1687 if (ioctl(fd, PPISDATA, &b) < 0)
1688 return -ENOTSUP;
1689 break;
1690 case CHR_IOCTL_PP_READ_CONTROL:
1691 if (ioctl(fd, PPIGCTRL, &b) < 0)
1692 return -ENOTSUP;
1693 *(uint8_t *)arg = b;
1694 break;
1695 case CHR_IOCTL_PP_WRITE_CONTROL:
1696 b = *(uint8_t *)arg;
1697 if (ioctl(fd, PPISCTRL, &b) < 0)
1698 return -ENOTSUP;
1699 break;
1700 case CHR_IOCTL_PP_READ_STATUS:
1701 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1702 return -ENOTSUP;
1703 *(uint8_t *)arg = b;
1704 break;
1705 default:
1706 return -ENOTSUP;
1708 return 0;
1711 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1713 CharDriverState *chr;
1715 chr = qemu_chr_alloc();
1716 chr->opaque = (void *)(intptr_t)fd;
1717 chr->chr_write = null_chr_write;
1718 chr->chr_ioctl = pp_ioctl;
1719 chr->explicit_be_open = true;
1720 return chr;
1722 #endif
1724 #else /* _WIN32 */
1726 typedef struct {
1727 int max_size;
1728 HANDLE hcom, hrecv, hsend;
1729 OVERLAPPED orecv;
1730 BOOL fpipe;
1731 DWORD len;
1733 /* Protected by the CharDriverState chr_write_lock. */
1734 OVERLAPPED osend;
1735 } WinCharState;
1737 typedef struct {
1738 HANDLE hStdIn;
1739 HANDLE hInputReadyEvent;
1740 HANDLE hInputDoneEvent;
1741 HANDLE hInputThread;
1742 uint8_t win_stdio_buf;
1743 } WinStdioCharState;
1745 #define NSENDBUF 2048
1746 #define NRECVBUF 2048
1747 #define MAXCONNECT 1
1748 #define NTIMEOUT 5000
1750 static int win_chr_poll(void *opaque);
1751 static int win_chr_pipe_poll(void *opaque);
1753 static void win_chr_close(CharDriverState *chr)
1755 WinCharState *s = chr->opaque;
1757 if (s->hsend) {
1758 CloseHandle(s->hsend);
1759 s->hsend = NULL;
1761 if (s->hrecv) {
1762 CloseHandle(s->hrecv);
1763 s->hrecv = NULL;
1765 if (s->hcom) {
1766 CloseHandle(s->hcom);
1767 s->hcom = NULL;
1769 if (s->fpipe)
1770 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1771 else
1772 qemu_del_polling_cb(win_chr_poll, chr);
1774 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1777 static int win_chr_init(CharDriverState *chr, const char *filename)
1779 WinCharState *s = chr->opaque;
1780 COMMCONFIG comcfg;
1781 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1782 COMSTAT comstat;
1783 DWORD size;
1784 DWORD err;
1786 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1787 if (!s->hsend) {
1788 fprintf(stderr, "Failed CreateEvent\n");
1789 goto fail;
1791 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1792 if (!s->hrecv) {
1793 fprintf(stderr, "Failed CreateEvent\n");
1794 goto fail;
1797 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1798 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1799 if (s->hcom == INVALID_HANDLE_VALUE) {
1800 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1801 s->hcom = NULL;
1802 goto fail;
1805 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1806 fprintf(stderr, "Failed SetupComm\n");
1807 goto fail;
1810 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1811 size = sizeof(COMMCONFIG);
1812 GetDefaultCommConfig(filename, &comcfg, &size);
1813 comcfg.dcb.DCBlength = sizeof(DCB);
1814 CommConfigDialog(filename, NULL, &comcfg);
1816 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1817 fprintf(stderr, "Failed SetCommState\n");
1818 goto fail;
1821 if (!SetCommMask(s->hcom, EV_ERR)) {
1822 fprintf(stderr, "Failed SetCommMask\n");
1823 goto fail;
1826 cto.ReadIntervalTimeout = MAXDWORD;
1827 if (!SetCommTimeouts(s->hcom, &cto)) {
1828 fprintf(stderr, "Failed SetCommTimeouts\n");
1829 goto fail;
1832 if (!ClearCommError(s->hcom, &err, &comstat)) {
1833 fprintf(stderr, "Failed ClearCommError\n");
1834 goto fail;
1836 qemu_add_polling_cb(win_chr_poll, chr);
1837 return 0;
1839 fail:
1840 win_chr_close(chr);
1841 return -1;
1844 /* Called with chr_write_lock held. */
1845 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1847 WinCharState *s = chr->opaque;
1848 DWORD len, ret, size, err;
1850 len = len1;
1851 ZeroMemory(&s->osend, sizeof(s->osend));
1852 s->osend.hEvent = s->hsend;
1853 while (len > 0) {
1854 if (s->hsend)
1855 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1856 else
1857 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1858 if (!ret) {
1859 err = GetLastError();
1860 if (err == ERROR_IO_PENDING) {
1861 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1862 if (ret) {
1863 buf += size;
1864 len -= size;
1865 } else {
1866 break;
1868 } else {
1869 break;
1871 } else {
1872 buf += size;
1873 len -= size;
1876 return len1 - len;
1879 static int win_chr_read_poll(CharDriverState *chr)
1881 WinCharState *s = chr->opaque;
1883 s->max_size = qemu_chr_be_can_write(chr);
1884 return s->max_size;
1887 static void win_chr_readfile(CharDriverState *chr)
1889 WinCharState *s = chr->opaque;
1890 int ret, err;
1891 uint8_t buf[READ_BUF_LEN];
1892 DWORD size;
1894 ZeroMemory(&s->orecv, sizeof(s->orecv));
1895 s->orecv.hEvent = s->hrecv;
1896 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1897 if (!ret) {
1898 err = GetLastError();
1899 if (err == ERROR_IO_PENDING) {
1900 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1904 if (size > 0) {
1905 qemu_chr_be_write(chr, buf, size);
1909 static void win_chr_read(CharDriverState *chr)
1911 WinCharState *s = chr->opaque;
1913 if (s->len > s->max_size)
1914 s->len = s->max_size;
1915 if (s->len == 0)
1916 return;
1918 win_chr_readfile(chr);
1921 static int win_chr_poll(void *opaque)
1923 CharDriverState *chr = opaque;
1924 WinCharState *s = chr->opaque;
1925 COMSTAT status;
1926 DWORD comerr;
1928 ClearCommError(s->hcom, &comerr, &status);
1929 if (status.cbInQue > 0) {
1930 s->len = status.cbInQue;
1931 win_chr_read_poll(chr);
1932 win_chr_read(chr);
1933 return 1;
1935 return 0;
1938 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1940 CharDriverState *chr;
1941 WinCharState *s;
1943 chr = qemu_chr_alloc();
1944 s = g_malloc0(sizeof(WinCharState));
1945 chr->opaque = s;
1946 chr->chr_write = win_chr_write;
1947 chr->chr_close = win_chr_close;
1949 if (win_chr_init(chr, filename) < 0) {
1950 g_free(s);
1951 g_free(chr);
1952 return NULL;
1954 return chr;
1957 static int win_chr_pipe_poll(void *opaque)
1959 CharDriverState *chr = opaque;
1960 WinCharState *s = chr->opaque;
1961 DWORD size;
1963 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1964 if (size > 0) {
1965 s->len = size;
1966 win_chr_read_poll(chr);
1967 win_chr_read(chr);
1968 return 1;
1970 return 0;
1973 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1975 WinCharState *s = chr->opaque;
1976 OVERLAPPED ov;
1977 int ret;
1978 DWORD size;
1979 char openname[256];
1981 s->fpipe = TRUE;
1983 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1984 if (!s->hsend) {
1985 fprintf(stderr, "Failed CreateEvent\n");
1986 goto fail;
1988 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1989 if (!s->hrecv) {
1990 fprintf(stderr, "Failed CreateEvent\n");
1991 goto fail;
1994 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1995 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1996 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1997 PIPE_WAIT,
1998 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1999 if (s->hcom == INVALID_HANDLE_VALUE) {
2000 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2001 s->hcom = NULL;
2002 goto fail;
2005 ZeroMemory(&ov, sizeof(ov));
2006 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2007 ret = ConnectNamedPipe(s->hcom, &ov);
2008 if (ret) {
2009 fprintf(stderr, "Failed ConnectNamedPipe\n");
2010 goto fail;
2013 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2014 if (!ret) {
2015 fprintf(stderr, "Failed GetOverlappedResult\n");
2016 if (ov.hEvent) {
2017 CloseHandle(ov.hEvent);
2018 ov.hEvent = NULL;
2020 goto fail;
2023 if (ov.hEvent) {
2024 CloseHandle(ov.hEvent);
2025 ov.hEvent = NULL;
2027 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2028 return 0;
2030 fail:
2031 win_chr_close(chr);
2032 return -1;
2036 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
2038 const char *filename = opts->device;
2039 CharDriverState *chr;
2040 WinCharState *s;
2042 chr = qemu_chr_alloc();
2043 s = g_malloc0(sizeof(WinCharState));
2044 chr->opaque = s;
2045 chr->chr_write = win_chr_write;
2046 chr->chr_close = win_chr_close;
2048 if (win_chr_pipe_init(chr, filename) < 0) {
2049 g_free(s);
2050 g_free(chr);
2051 return NULL;
2053 return chr;
2056 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2058 CharDriverState *chr;
2059 WinCharState *s;
2061 chr = qemu_chr_alloc();
2062 s = g_malloc0(sizeof(WinCharState));
2063 s->hcom = fd_out;
2064 chr->opaque = s;
2065 chr->chr_write = win_chr_write;
2066 return chr;
2069 static CharDriverState *qemu_chr_open_win_con(void)
2071 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2074 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2076 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2077 DWORD dwSize;
2078 int len1;
2080 len1 = len;
2082 while (len1 > 0) {
2083 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2084 break;
2086 buf += dwSize;
2087 len1 -= dwSize;
2090 return len - len1;
2093 static void win_stdio_wait_func(void *opaque)
2095 CharDriverState *chr = opaque;
2096 WinStdioCharState *stdio = chr->opaque;
2097 INPUT_RECORD buf[4];
2098 int ret;
2099 DWORD dwSize;
2100 int i;
2102 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2104 if (!ret) {
2105 /* Avoid error storm */
2106 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2107 return;
2110 for (i = 0; i < dwSize; i++) {
2111 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2113 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2114 int j;
2115 if (kev->uChar.AsciiChar != 0) {
2116 for (j = 0; j < kev->wRepeatCount; j++) {
2117 if (qemu_chr_be_can_write(chr)) {
2118 uint8_t c = kev->uChar.AsciiChar;
2119 qemu_chr_be_write(chr, &c, 1);
2127 static DWORD WINAPI win_stdio_thread(LPVOID param)
2129 CharDriverState *chr = param;
2130 WinStdioCharState *stdio = chr->opaque;
2131 int ret;
2132 DWORD dwSize;
2134 while (1) {
2136 /* Wait for one byte */
2137 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2139 /* Exit in case of error, continue if nothing read */
2140 if (!ret) {
2141 break;
2143 if (!dwSize) {
2144 continue;
2147 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2148 if (stdio->win_stdio_buf == '\r') {
2149 continue;
2152 /* Signal the main thread and wait until the byte was eaten */
2153 if (!SetEvent(stdio->hInputReadyEvent)) {
2154 break;
2156 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2157 != WAIT_OBJECT_0) {
2158 break;
2162 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2163 return 0;
2166 static void win_stdio_thread_wait_func(void *opaque)
2168 CharDriverState *chr = opaque;
2169 WinStdioCharState *stdio = chr->opaque;
2171 if (qemu_chr_be_can_write(chr)) {
2172 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2175 SetEvent(stdio->hInputDoneEvent);
2178 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2180 WinStdioCharState *stdio = chr->opaque;
2181 DWORD dwMode = 0;
2183 GetConsoleMode(stdio->hStdIn, &dwMode);
2185 if (echo) {
2186 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2187 } else {
2188 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2192 static void win_stdio_close(CharDriverState *chr)
2194 WinStdioCharState *stdio = chr->opaque;
2196 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2197 CloseHandle(stdio->hInputReadyEvent);
2199 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2200 CloseHandle(stdio->hInputDoneEvent);
2202 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2203 TerminateThread(stdio->hInputThread, 0);
2206 g_free(chr->opaque);
2207 g_free(chr);
2210 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2212 CharDriverState *chr;
2213 WinStdioCharState *stdio;
2214 DWORD dwMode;
2215 int is_console = 0;
2217 chr = qemu_chr_alloc();
2218 stdio = g_malloc0(sizeof(WinStdioCharState));
2220 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2221 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2222 fprintf(stderr, "cannot open stdio: invalid handle\n");
2223 exit(1);
2226 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2228 chr->opaque = stdio;
2229 chr->chr_write = win_stdio_write;
2230 chr->chr_close = win_stdio_close;
2232 if (is_console) {
2233 if (qemu_add_wait_object(stdio->hStdIn,
2234 win_stdio_wait_func, chr)) {
2235 fprintf(stderr, "qemu_add_wait_object: failed\n");
2237 } else {
2238 DWORD dwId;
2240 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2241 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2242 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2243 chr, 0, &dwId);
2245 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2246 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2247 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2248 fprintf(stderr, "cannot create stdio thread or event\n");
2249 exit(1);
2251 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2252 win_stdio_thread_wait_func, chr)) {
2253 fprintf(stderr, "qemu_add_wait_object: failed\n");
2257 dwMode |= ENABLE_LINE_INPUT;
2259 if (is_console) {
2260 /* set the terminal in raw mode */
2261 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2262 dwMode |= ENABLE_PROCESSED_INPUT;
2265 SetConsoleMode(stdio->hStdIn, dwMode);
2267 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2268 qemu_chr_fe_set_echo(chr, false);
2270 return chr;
2272 #endif /* !_WIN32 */
2275 /***********************************************************/
2276 /* UDP Net console */
2278 typedef struct {
2279 int fd;
2280 GIOChannel *chan;
2281 uint8_t buf[READ_BUF_LEN];
2282 int bufcnt;
2283 int bufptr;
2284 int max_size;
2285 } NetCharDriver;
2287 /* Called with chr_write_lock held. */
2288 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2290 NetCharDriver *s = chr->opaque;
2291 gsize bytes_written;
2292 GIOStatus status;
2294 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2295 if (status == G_IO_STATUS_EOF) {
2296 return 0;
2297 } else if (status != G_IO_STATUS_NORMAL) {
2298 return -1;
2301 return bytes_written;
2304 static int udp_chr_read_poll(void *opaque)
2306 CharDriverState *chr = opaque;
2307 NetCharDriver *s = chr->opaque;
2309 s->max_size = qemu_chr_be_can_write(chr);
2311 /* If there were any stray characters in the queue process them
2312 * first
2314 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2315 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2316 s->bufptr++;
2317 s->max_size = qemu_chr_be_can_write(chr);
2319 return s->max_size;
2322 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2324 CharDriverState *chr = opaque;
2325 NetCharDriver *s = chr->opaque;
2326 gsize bytes_read = 0;
2327 GIOStatus status;
2329 if (s->max_size == 0) {
2330 return TRUE;
2332 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2333 &bytes_read, NULL);
2334 s->bufcnt = bytes_read;
2335 s->bufptr = s->bufcnt;
2336 if (status != G_IO_STATUS_NORMAL) {
2337 remove_fd_in_watch(chr);
2338 return FALSE;
2341 s->bufptr = 0;
2342 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2343 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2344 s->bufptr++;
2345 s->max_size = qemu_chr_be_can_write(chr);
2348 return TRUE;
2351 static void udp_chr_update_read_handler(CharDriverState *chr)
2353 NetCharDriver *s = chr->opaque;
2355 remove_fd_in_watch(chr);
2356 if (s->chan) {
2357 chr->fd_in_tag = io_add_watch_poll(s->chan, udp_chr_read_poll,
2358 udp_chr_read, chr);
2362 static void udp_chr_close(CharDriverState *chr)
2364 NetCharDriver *s = chr->opaque;
2366 remove_fd_in_watch(chr);
2367 if (s->chan) {
2368 g_io_channel_unref(s->chan);
2369 closesocket(s->fd);
2371 g_free(s);
2372 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2375 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2377 CharDriverState *chr = NULL;
2378 NetCharDriver *s = NULL;
2380 chr = qemu_chr_alloc();
2381 s = g_malloc0(sizeof(NetCharDriver));
2383 s->fd = fd;
2384 s->chan = io_channel_from_socket(s->fd);
2385 s->bufcnt = 0;
2386 s->bufptr = 0;
2387 chr->opaque = s;
2388 chr->chr_write = udp_chr_write;
2389 chr->chr_update_read_handler = udp_chr_update_read_handler;
2390 chr->chr_close = udp_chr_close;
2391 /* be isn't opened until we get a connection */
2392 chr->explicit_be_open = true;
2393 return chr;
2396 /***********************************************************/
2397 /* TCP Net console */
2399 typedef struct {
2401 GIOChannel *chan, *listen_chan;
2402 guint listen_tag;
2403 int fd, listen_fd;
2404 int connected;
2405 int max_size;
2406 int do_telnetopt;
2407 int do_nodelay;
2408 int is_unix;
2409 int *read_msgfds;
2410 int read_msgfds_num;
2411 int *write_msgfds;
2412 int write_msgfds_num;
2413 } TCPCharDriver;
2415 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2417 #ifndef _WIN32
2418 static int unix_send_msgfds(CharDriverState *chr, const uint8_t *buf, int len)
2420 TCPCharDriver *s = chr->opaque;
2421 struct msghdr msgh;
2422 struct iovec iov;
2423 int r;
2425 size_t fd_size = s->write_msgfds_num * sizeof(int);
2426 char control[CMSG_SPACE(fd_size)];
2427 struct cmsghdr *cmsg;
2429 memset(&msgh, 0, sizeof(msgh));
2430 memset(control, 0, sizeof(control));
2432 /* set the payload */
2433 iov.iov_base = (uint8_t *) buf;
2434 iov.iov_len = len;
2436 msgh.msg_iov = &iov;
2437 msgh.msg_iovlen = 1;
2439 msgh.msg_control = control;
2440 msgh.msg_controllen = sizeof(control);
2442 cmsg = CMSG_FIRSTHDR(&msgh);
2444 cmsg->cmsg_len = CMSG_LEN(fd_size);
2445 cmsg->cmsg_level = SOL_SOCKET;
2446 cmsg->cmsg_type = SCM_RIGHTS;
2447 memcpy(CMSG_DATA(cmsg), s->write_msgfds, fd_size);
2449 do {
2450 r = sendmsg(s->fd, &msgh, 0);
2451 } while (r < 0 && errno == EINTR);
2453 /* free the written msgfds, no matter what */
2454 if (s->write_msgfds_num) {
2455 g_free(s->write_msgfds);
2456 s->write_msgfds = 0;
2457 s->write_msgfds_num = 0;
2460 return r;
2462 #endif
2464 /* Called with chr_write_lock held. */
2465 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2467 TCPCharDriver *s = chr->opaque;
2468 if (s->connected) {
2469 #ifndef _WIN32
2470 if (s->is_unix && s->write_msgfds_num) {
2471 return unix_send_msgfds(chr, buf, len);
2472 } else
2473 #endif
2475 return io_channel_send(s->chan, buf, len);
2477 } else {
2478 /* XXX: indicate an error ? */
2479 return len;
2483 static int tcp_chr_read_poll(void *opaque)
2485 CharDriverState *chr = opaque;
2486 TCPCharDriver *s = chr->opaque;
2487 if (!s->connected)
2488 return 0;
2489 s->max_size = qemu_chr_be_can_write(chr);
2490 return s->max_size;
2493 #define IAC 255
2494 #define IAC_BREAK 243
2495 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2496 TCPCharDriver *s,
2497 uint8_t *buf, int *size)
2499 /* Handle any telnet client's basic IAC options to satisfy char by
2500 * char mode with no echo. All IAC options will be removed from
2501 * the buf and the do_telnetopt variable will be used to track the
2502 * state of the width of the IAC information.
2504 * IAC commands come in sets of 3 bytes with the exception of the
2505 * "IAC BREAK" command and the double IAC.
2508 int i;
2509 int j = 0;
2511 for (i = 0; i < *size; i++) {
2512 if (s->do_telnetopt > 1) {
2513 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2514 /* Double IAC means send an IAC */
2515 if (j != i)
2516 buf[j] = buf[i];
2517 j++;
2518 s->do_telnetopt = 1;
2519 } else {
2520 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2521 /* Handle IAC break commands by sending a serial break */
2522 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2523 s->do_telnetopt++;
2525 s->do_telnetopt++;
2527 if (s->do_telnetopt >= 4) {
2528 s->do_telnetopt = 1;
2530 } else {
2531 if ((unsigned char)buf[i] == IAC) {
2532 s->do_telnetopt = 2;
2533 } else {
2534 if (j != i)
2535 buf[j] = buf[i];
2536 j++;
2540 *size = j;
2543 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2545 TCPCharDriver *s = chr->opaque;
2546 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2548 if (to_copy) {
2549 int i;
2551 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2553 /* Close unused fds */
2554 for (i = to_copy; i < s->read_msgfds_num; i++) {
2555 close(s->read_msgfds[i]);
2558 g_free(s->read_msgfds);
2559 s->read_msgfds = 0;
2560 s->read_msgfds_num = 0;
2563 return to_copy;
2566 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2568 TCPCharDriver *s = chr->opaque;
2570 /* clear old pending fd array */
2571 if (s->write_msgfds) {
2572 g_free(s->write_msgfds);
2575 if (num) {
2576 s->write_msgfds = g_malloc(num * sizeof(int));
2577 memcpy(s->write_msgfds, fds, num * sizeof(int));
2580 s->write_msgfds_num = num;
2582 return 0;
2585 #ifndef _WIN32
2586 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2588 TCPCharDriver *s = chr->opaque;
2589 struct cmsghdr *cmsg;
2591 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2592 int fd_size, i;
2594 if (cmsg->cmsg_len < CMSG_LEN(sizeof(int)) ||
2595 cmsg->cmsg_level != SOL_SOCKET ||
2596 cmsg->cmsg_type != SCM_RIGHTS) {
2597 continue;
2600 fd_size = cmsg->cmsg_len - CMSG_LEN(0);
2602 if (!fd_size) {
2603 continue;
2606 /* close and clean read_msgfds */
2607 for (i = 0; i < s->read_msgfds_num; i++) {
2608 close(s->read_msgfds[i]);
2611 if (s->read_msgfds_num) {
2612 g_free(s->read_msgfds);
2615 s->read_msgfds_num = fd_size / sizeof(int);
2616 s->read_msgfds = g_malloc(fd_size);
2617 memcpy(s->read_msgfds, CMSG_DATA(cmsg), fd_size);
2619 for (i = 0; i < s->read_msgfds_num; i++) {
2620 int fd = s->read_msgfds[i];
2621 if (fd < 0) {
2622 continue;
2625 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2626 qemu_set_block(fd);
2628 #ifndef MSG_CMSG_CLOEXEC
2629 qemu_set_cloexec(fd);
2630 #endif
2635 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2637 TCPCharDriver *s = chr->opaque;
2638 struct msghdr msg = { NULL, };
2639 struct iovec iov[1];
2640 union {
2641 struct cmsghdr cmsg;
2642 char control[CMSG_SPACE(sizeof(int))];
2643 } msg_control;
2644 int flags = 0;
2645 ssize_t ret;
2647 iov[0].iov_base = buf;
2648 iov[0].iov_len = len;
2650 msg.msg_iov = iov;
2651 msg.msg_iovlen = 1;
2652 msg.msg_control = &msg_control;
2653 msg.msg_controllen = sizeof(msg_control);
2655 #ifdef MSG_CMSG_CLOEXEC
2656 flags |= MSG_CMSG_CLOEXEC;
2657 #endif
2658 ret = recvmsg(s->fd, &msg, flags);
2659 if (ret > 0 && s->is_unix) {
2660 unix_process_msgfd(chr, &msg);
2663 return ret;
2665 #else
2666 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2668 TCPCharDriver *s = chr->opaque;
2669 return qemu_recv(s->fd, buf, len, 0);
2671 #endif
2673 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2675 TCPCharDriver *s = chr->opaque;
2676 return g_io_create_watch(s->chan, cond);
2679 static void tcp_chr_disconnect(CharDriverState *chr)
2681 TCPCharDriver *s = chr->opaque;
2683 s->connected = 0;
2684 if (s->listen_chan) {
2685 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
2686 tcp_chr_accept, chr);
2688 remove_fd_in_watch(chr);
2689 g_io_channel_unref(s->chan);
2690 s->chan = NULL;
2691 closesocket(s->fd);
2692 s->fd = -1;
2693 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2696 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2698 CharDriverState *chr = opaque;
2699 TCPCharDriver *s = chr->opaque;
2700 uint8_t buf[READ_BUF_LEN];
2701 int len, size;
2703 if (cond & G_IO_HUP) {
2704 /* connection closed */
2705 tcp_chr_disconnect(chr);
2706 return TRUE;
2709 if (!s->connected || s->max_size <= 0) {
2710 return TRUE;
2712 len = sizeof(buf);
2713 if (len > s->max_size)
2714 len = s->max_size;
2715 size = tcp_chr_recv(chr, (void *)buf, len);
2716 if (size == 0) {
2717 /* connection closed */
2718 tcp_chr_disconnect(chr);
2719 } else if (size > 0) {
2720 if (s->do_telnetopt)
2721 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2722 if (size > 0)
2723 qemu_chr_be_write(chr, buf, size);
2726 return TRUE;
2729 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2731 TCPCharDriver *s = chr->opaque;
2732 int size;
2734 if (!s->connected) {
2735 return 0;
2738 size = tcp_chr_recv(chr, (void *) buf, len);
2739 if (size == 0) {
2740 /* connection closed */
2741 tcp_chr_disconnect(chr);
2744 return size;
2747 #ifndef _WIN32
2748 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2750 CharDriverState *chr = qemu_chr_open_fd(eventfd, eventfd);
2752 if (chr) {
2753 chr->avail_connections = 1;
2756 return chr;
2758 #endif
2760 static void tcp_chr_connect(void *opaque)
2762 CharDriverState *chr = opaque;
2763 TCPCharDriver *s = chr->opaque;
2765 s->connected = 1;
2766 if (s->chan) {
2767 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2768 tcp_chr_read, chr);
2770 qemu_chr_be_generic_open(chr);
2773 static void tcp_chr_update_read_handler(CharDriverState *chr)
2775 TCPCharDriver *s = chr->opaque;
2777 remove_fd_in_watch(chr);
2778 if (s->chan) {
2779 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2780 tcp_chr_read, chr);
2784 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2785 static void tcp_chr_telnet_init(int fd)
2787 char buf[3];
2788 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2789 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2790 send(fd, (char *)buf, 3, 0);
2791 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2792 send(fd, (char *)buf, 3, 0);
2793 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2794 send(fd, (char *)buf, 3, 0);
2795 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2796 send(fd, (char *)buf, 3, 0);
2799 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2801 TCPCharDriver *s = chr->opaque;
2802 if (s->fd != -1)
2803 return -1;
2805 qemu_set_nonblock(fd);
2806 if (s->do_nodelay)
2807 socket_set_nodelay(fd);
2808 s->fd = fd;
2809 s->chan = io_channel_from_socket(fd);
2810 if (s->listen_tag) {
2811 g_source_remove(s->listen_tag);
2812 s->listen_tag = 0;
2814 tcp_chr_connect(chr);
2816 return 0;
2819 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2821 CharDriverState *chr = opaque;
2822 TCPCharDriver *s = chr->opaque;
2823 struct sockaddr_in saddr;
2824 #ifndef _WIN32
2825 struct sockaddr_un uaddr;
2826 #endif
2827 struct sockaddr *addr;
2828 socklen_t len;
2829 int fd;
2831 for(;;) {
2832 #ifndef _WIN32
2833 if (s->is_unix) {
2834 len = sizeof(uaddr);
2835 addr = (struct sockaddr *)&uaddr;
2836 } else
2837 #endif
2839 len = sizeof(saddr);
2840 addr = (struct sockaddr *)&saddr;
2842 fd = qemu_accept(s->listen_fd, addr, &len);
2843 if (fd < 0 && errno != EINTR) {
2844 s->listen_tag = 0;
2845 return FALSE;
2846 } else if (fd >= 0) {
2847 if (s->do_telnetopt)
2848 tcp_chr_telnet_init(fd);
2849 break;
2852 if (tcp_chr_add_client(chr, fd) < 0)
2853 close(fd);
2855 return TRUE;
2858 static void tcp_chr_close(CharDriverState *chr)
2860 TCPCharDriver *s = chr->opaque;
2861 int i;
2862 if (s->fd >= 0) {
2863 remove_fd_in_watch(chr);
2864 if (s->chan) {
2865 g_io_channel_unref(s->chan);
2867 closesocket(s->fd);
2869 if (s->listen_fd >= 0) {
2870 if (s->listen_tag) {
2871 g_source_remove(s->listen_tag);
2872 s->listen_tag = 0;
2874 if (s->listen_chan) {
2875 g_io_channel_unref(s->listen_chan);
2877 closesocket(s->listen_fd);
2879 if (s->read_msgfds_num) {
2880 for (i = 0; i < s->read_msgfds_num; i++) {
2881 close(s->read_msgfds[i]);
2883 g_free(s->read_msgfds);
2885 if (s->write_msgfds_num) {
2886 g_free(s->write_msgfds);
2888 g_free(s);
2889 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2892 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2893 bool is_listen, bool is_telnet,
2894 bool is_waitconnect,
2895 Error **errp)
2897 CharDriverState *chr = NULL;
2898 TCPCharDriver *s = NULL;
2899 char host[NI_MAXHOST], serv[NI_MAXSERV];
2900 const char *left = "", *right = "";
2901 struct sockaddr_storage ss;
2902 socklen_t ss_len = sizeof(ss);
2904 memset(&ss, 0, ss_len);
2905 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2906 error_setg_errno(errp, errno, "getsockname");
2907 return NULL;
2910 chr = qemu_chr_alloc();
2911 s = g_malloc0(sizeof(TCPCharDriver));
2913 s->connected = 0;
2914 s->fd = -1;
2915 s->listen_fd = -1;
2916 s->read_msgfds = 0;
2917 s->read_msgfds_num = 0;
2918 s->write_msgfds = 0;
2919 s->write_msgfds_num = 0;
2921 chr->filename = g_malloc(256);
2922 switch (ss.ss_family) {
2923 #ifndef _WIN32
2924 case AF_UNIX:
2925 s->is_unix = 1;
2926 snprintf(chr->filename, 256, "unix:%s%s",
2927 ((struct sockaddr_un *)(&ss))->sun_path,
2928 is_listen ? ",server" : "");
2929 break;
2930 #endif
2931 case AF_INET6:
2932 left = "[";
2933 right = "]";
2934 /* fall through */
2935 case AF_INET:
2936 s->do_nodelay = do_nodelay;
2937 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2938 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2939 snprintf(chr->filename, 256, "%s:%s%s%s:%s%s",
2940 is_telnet ? "telnet" : "tcp",
2941 left, host, right, serv,
2942 is_listen ? ",server" : "");
2943 break;
2946 chr->opaque = s;
2947 chr->chr_write = tcp_chr_write;
2948 chr->chr_sync_read = tcp_chr_sync_read;
2949 chr->chr_close = tcp_chr_close;
2950 chr->get_msgfds = tcp_get_msgfds;
2951 chr->set_msgfds = tcp_set_msgfds;
2952 chr->chr_add_client = tcp_chr_add_client;
2953 chr->chr_add_watch = tcp_chr_add_watch;
2954 chr->chr_update_read_handler = tcp_chr_update_read_handler;
2955 /* be isn't opened until we get a connection */
2956 chr->explicit_be_open = true;
2958 if (is_listen) {
2959 s->listen_fd = fd;
2960 s->listen_chan = io_channel_from_socket(s->listen_fd);
2961 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2962 if (is_telnet) {
2963 s->do_telnetopt = 1;
2965 } else {
2966 s->connected = 1;
2967 s->fd = fd;
2968 socket_set_nodelay(fd);
2969 s->chan = io_channel_from_socket(s->fd);
2970 tcp_chr_connect(chr);
2973 if (is_listen && is_waitconnect) {
2974 fprintf(stderr, "QEMU waiting for connection on: %s\n",
2975 chr->filename);
2976 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2977 qemu_set_nonblock(s->listen_fd);
2979 return chr;
2982 /*********************************************************/
2983 /* Ring buffer chardev */
2985 typedef struct {
2986 size_t size;
2987 size_t prod;
2988 size_t cons;
2989 uint8_t *cbuf;
2990 } RingBufCharDriver;
2992 static size_t ringbuf_count(const CharDriverState *chr)
2994 const RingBufCharDriver *d = chr->opaque;
2996 return d->prod - d->cons;
2999 /* Called with chr_write_lock held. */
3000 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3002 RingBufCharDriver *d = chr->opaque;
3003 int i;
3005 if (!buf || (len < 0)) {
3006 return -1;
3009 for (i = 0; i < len; i++ ) {
3010 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3011 if (d->prod - d->cons > d->size) {
3012 d->cons = d->prod - d->size;
3016 return 0;
3019 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3021 RingBufCharDriver *d = chr->opaque;
3022 int i;
3024 qemu_mutex_lock(&chr->chr_write_lock);
3025 for (i = 0; i < len && d->cons != d->prod; i++) {
3026 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3028 qemu_mutex_unlock(&chr->chr_write_lock);
3030 return i;
3033 static void ringbuf_chr_close(struct CharDriverState *chr)
3035 RingBufCharDriver *d = chr->opaque;
3037 g_free(d->cbuf);
3038 g_free(d);
3039 chr->opaque = NULL;
3042 static CharDriverState *qemu_chr_open_ringbuf(ChardevRingbuf *opts,
3043 Error **errp)
3045 CharDriverState *chr;
3046 RingBufCharDriver *d;
3048 chr = qemu_chr_alloc();
3049 d = g_malloc(sizeof(*d));
3051 d->size = opts->has_size ? opts->size : 65536;
3053 /* The size must be power of 2 */
3054 if (d->size & (d->size - 1)) {
3055 error_setg(errp, "size of ringbuf chardev must be power of two");
3056 goto fail;
3059 d->prod = 0;
3060 d->cons = 0;
3061 d->cbuf = g_malloc0(d->size);
3063 chr->opaque = d;
3064 chr->chr_write = ringbuf_chr_write;
3065 chr->chr_close = ringbuf_chr_close;
3067 return chr;
3069 fail:
3070 g_free(d);
3071 g_free(chr);
3072 return NULL;
3075 bool chr_is_ringbuf(const CharDriverState *chr)
3077 return chr->chr_write == ringbuf_chr_write;
3080 void qmp_ringbuf_write(const char *device, const char *data,
3081 bool has_format, enum DataFormat format,
3082 Error **errp)
3084 CharDriverState *chr;
3085 const uint8_t *write_data;
3086 int ret;
3087 gsize write_count;
3089 chr = qemu_chr_find(device);
3090 if (!chr) {
3091 error_setg(errp, "Device '%s' not found", device);
3092 return;
3095 if (!chr_is_ringbuf(chr)) {
3096 error_setg(errp,"%s is not a ringbuf device", device);
3097 return;
3100 if (has_format && (format == DATA_FORMAT_BASE64)) {
3101 write_data = g_base64_decode(data, &write_count);
3102 } else {
3103 write_data = (uint8_t *)data;
3104 write_count = strlen(data);
3107 ret = ringbuf_chr_write(chr, write_data, write_count);
3109 if (write_data != (uint8_t *)data) {
3110 g_free((void *)write_data);
3113 if (ret < 0) {
3114 error_setg(errp, "Failed to write to device %s", device);
3115 return;
3119 char *qmp_ringbuf_read(const char *device, int64_t size,
3120 bool has_format, enum DataFormat format,
3121 Error **errp)
3123 CharDriverState *chr;
3124 uint8_t *read_data;
3125 size_t count;
3126 char *data;
3128 chr = qemu_chr_find(device);
3129 if (!chr) {
3130 error_setg(errp, "Device '%s' not found", device);
3131 return NULL;
3134 if (!chr_is_ringbuf(chr)) {
3135 error_setg(errp,"%s is not a ringbuf device", device);
3136 return NULL;
3139 if (size <= 0) {
3140 error_setg(errp, "size must be greater than zero");
3141 return NULL;
3144 count = ringbuf_count(chr);
3145 size = size > count ? count : size;
3146 read_data = g_malloc(size + 1);
3148 ringbuf_chr_read(chr, read_data, size);
3150 if (has_format && (format == DATA_FORMAT_BASE64)) {
3151 data = g_base64_encode(read_data, size);
3152 g_free(read_data);
3153 } else {
3155 * FIXME should read only complete, valid UTF-8 characters up
3156 * to @size bytes. Invalid sequences should be replaced by a
3157 * suitable replacement character. Except when (and only
3158 * when) ring buffer lost characters since last read, initial
3159 * continuation characters should be dropped.
3161 read_data[size] = 0;
3162 data = (char *)read_data;
3165 return data;
3168 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3170 char host[65], port[33], width[8], height[8];
3171 int pos;
3172 const char *p;
3173 QemuOpts *opts;
3174 Error *local_err = NULL;
3176 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3177 if (local_err) {
3178 qerror_report_err(local_err);
3179 error_free(local_err);
3180 return NULL;
3183 if (strstart(filename, "mon:", &p)) {
3184 filename = p;
3185 qemu_opt_set(opts, "mux", "on");
3186 if (strcmp(filename, "stdio") == 0) {
3187 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3188 * but pass it to the guest. Handle this only for compat syntax,
3189 * for -chardev syntax we have special option for this.
3190 * This is what -nographic did, redirecting+muxing serial+monitor
3191 * to stdio causing Ctrl+C to be passed to guest. */
3192 qemu_opt_set(opts, "signal", "off");
3196 if (strcmp(filename, "null") == 0 ||
3197 strcmp(filename, "pty") == 0 ||
3198 strcmp(filename, "msmouse") == 0 ||
3199 strcmp(filename, "braille") == 0 ||
3200 strcmp(filename, "testdev") == 0 ||
3201 strcmp(filename, "stdio") == 0) {
3202 qemu_opt_set(opts, "backend", filename);
3203 return opts;
3205 if (strstart(filename, "vc", &p)) {
3206 qemu_opt_set(opts, "backend", "vc");
3207 if (*p == ':') {
3208 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3209 /* pixels */
3210 qemu_opt_set(opts, "width", width);
3211 qemu_opt_set(opts, "height", height);
3212 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3213 /* chars */
3214 qemu_opt_set(opts, "cols", width);
3215 qemu_opt_set(opts, "rows", height);
3216 } else {
3217 goto fail;
3220 return opts;
3222 if (strcmp(filename, "con:") == 0) {
3223 qemu_opt_set(opts, "backend", "console");
3224 return opts;
3226 if (strstart(filename, "COM", NULL)) {
3227 qemu_opt_set(opts, "backend", "serial");
3228 qemu_opt_set(opts, "path", filename);
3229 return opts;
3231 if (strstart(filename, "file:", &p)) {
3232 qemu_opt_set(opts, "backend", "file");
3233 qemu_opt_set(opts, "path", p);
3234 return opts;
3236 if (strstart(filename, "pipe:", &p)) {
3237 qemu_opt_set(opts, "backend", "pipe");
3238 qemu_opt_set(opts, "path", p);
3239 return opts;
3241 if (strstart(filename, "tcp:", &p) ||
3242 strstart(filename, "telnet:", &p)) {
3243 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3244 host[0] = 0;
3245 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3246 goto fail;
3248 qemu_opt_set(opts, "backend", "socket");
3249 qemu_opt_set(opts, "host", host);
3250 qemu_opt_set(opts, "port", port);
3251 if (p[pos] == ',') {
3252 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3253 goto fail;
3255 if (strstart(filename, "telnet:", &p))
3256 qemu_opt_set(opts, "telnet", "on");
3257 return opts;
3259 if (strstart(filename, "udp:", &p)) {
3260 qemu_opt_set(opts, "backend", "udp");
3261 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3262 host[0] = 0;
3263 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3264 goto fail;
3267 qemu_opt_set(opts, "host", host);
3268 qemu_opt_set(opts, "port", port);
3269 if (p[pos] == '@') {
3270 p += pos + 1;
3271 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3272 host[0] = 0;
3273 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3274 goto fail;
3277 qemu_opt_set(opts, "localaddr", host);
3278 qemu_opt_set(opts, "localport", port);
3280 return opts;
3282 if (strstart(filename, "unix:", &p)) {
3283 qemu_opt_set(opts, "backend", "socket");
3284 if (qemu_opts_do_parse(opts, p, "path") != 0)
3285 goto fail;
3286 return opts;
3288 if (strstart(filename, "/dev/parport", NULL) ||
3289 strstart(filename, "/dev/ppi", NULL)) {
3290 qemu_opt_set(opts, "backend", "parport");
3291 qemu_opt_set(opts, "path", filename);
3292 return opts;
3294 if (strstart(filename, "/dev/", NULL)) {
3295 qemu_opt_set(opts, "backend", "tty");
3296 qemu_opt_set(opts, "path", filename);
3297 return opts;
3300 fail:
3301 qemu_opts_del(opts);
3302 return NULL;
3305 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3306 Error **errp)
3308 const char *path = qemu_opt_get(opts, "path");
3310 if (path == NULL) {
3311 error_setg(errp, "chardev: file: no filename given");
3312 return;
3314 backend->file = g_new0(ChardevFile, 1);
3315 backend->file->out = g_strdup(path);
3318 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3319 Error **errp)
3321 backend->stdio = g_new0(ChardevStdio, 1);
3322 backend->stdio->has_signal = true;
3323 backend->stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3326 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3327 Error **errp)
3329 const char *device = qemu_opt_get(opts, "path");
3331 if (device == NULL) {
3332 error_setg(errp, "chardev: serial/tty: no device path given");
3333 return;
3335 backend->serial = g_new0(ChardevHostdev, 1);
3336 backend->serial->device = g_strdup(device);
3339 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3340 Error **errp)
3342 const char *device = qemu_opt_get(opts, "path");
3344 if (device == NULL) {
3345 error_setg(errp, "chardev: parallel: no device path given");
3346 return;
3348 backend->parallel = g_new0(ChardevHostdev, 1);
3349 backend->parallel->device = g_strdup(device);
3352 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3353 Error **errp)
3355 const char *device = qemu_opt_get(opts, "path");
3357 if (device == NULL) {
3358 error_setg(errp, "chardev: pipe: no device path given");
3359 return;
3361 backend->pipe = g_new0(ChardevHostdev, 1);
3362 backend->pipe->device = g_strdup(device);
3365 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3366 Error **errp)
3368 int val;
3370 backend->ringbuf = g_new0(ChardevRingbuf, 1);
3372 val = qemu_opt_get_size(opts, "size", 0);
3373 if (val != 0) {
3374 backend->ringbuf->has_size = true;
3375 backend->ringbuf->size = val;
3379 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3380 Error **errp)
3382 const char *chardev = qemu_opt_get(opts, "chardev");
3384 if (chardev == NULL) {
3385 error_setg(errp, "chardev: mux: no chardev given");
3386 return;
3388 backend->mux = g_new0(ChardevMux, 1);
3389 backend->mux->chardev = g_strdup(chardev);
3392 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3393 Error **errp)
3395 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3396 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3397 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3398 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3399 const char *path = qemu_opt_get(opts, "path");
3400 const char *host = qemu_opt_get(opts, "host");
3401 const char *port = qemu_opt_get(opts, "port");
3402 SocketAddress *addr;
3404 if (!path) {
3405 if (!host) {
3406 error_setg(errp, "chardev: socket: no host given");
3407 return;
3409 if (!port) {
3410 error_setg(errp, "chardev: socket: no port given");
3411 return;
3415 backend->socket = g_new0(ChardevSocket, 1);
3417 backend->socket->has_nodelay = true;
3418 backend->socket->nodelay = do_nodelay;
3419 backend->socket->has_server = true;
3420 backend->socket->server = is_listen;
3421 backend->socket->has_telnet = true;
3422 backend->socket->telnet = is_telnet;
3423 backend->socket->has_wait = true;
3424 backend->socket->wait = is_waitconnect;
3426 addr = g_new0(SocketAddress, 1);
3427 if (path) {
3428 addr->kind = SOCKET_ADDRESS_KIND_UNIX;
3429 addr->q_unix = g_new0(UnixSocketAddress, 1);
3430 addr->q_unix->path = g_strdup(path);
3431 } else {
3432 addr->kind = SOCKET_ADDRESS_KIND_INET;
3433 addr->inet = g_new0(InetSocketAddress, 1);
3434 addr->inet->host = g_strdup(host);
3435 addr->inet->port = g_strdup(port);
3436 addr->inet->has_to = qemu_opt_get(opts, "to");
3437 addr->inet->to = qemu_opt_get_number(opts, "to", 0);
3438 addr->inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3439 addr->inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3440 addr->inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3441 addr->inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3443 backend->socket->addr = addr;
3446 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3447 Error **errp)
3449 const char *host = qemu_opt_get(opts, "host");
3450 const char *port = qemu_opt_get(opts, "port");
3451 const char *localaddr = qemu_opt_get(opts, "localaddr");
3452 const char *localport = qemu_opt_get(opts, "localport");
3453 bool has_local = false;
3454 SocketAddress *addr;
3456 if (host == NULL || strlen(host) == 0) {
3457 host = "localhost";
3459 if (port == NULL || strlen(port) == 0) {
3460 error_setg(errp, "chardev: udp: remote port not specified");
3461 return;
3463 if (localport == NULL || strlen(localport) == 0) {
3464 localport = "0";
3465 } else {
3466 has_local = true;
3468 if (localaddr == NULL || strlen(localaddr) == 0) {
3469 localaddr = "";
3470 } else {
3471 has_local = true;
3474 backend->udp = g_new0(ChardevUdp, 1);
3476 addr = g_new0(SocketAddress, 1);
3477 addr->kind = SOCKET_ADDRESS_KIND_INET;
3478 addr->inet = g_new0(InetSocketAddress, 1);
3479 addr->inet->host = g_strdup(host);
3480 addr->inet->port = g_strdup(port);
3481 addr->inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3482 addr->inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3483 addr->inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3484 addr->inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3485 backend->udp->remote = addr;
3487 if (has_local) {
3488 backend->udp->has_local = true;
3489 addr = g_new0(SocketAddress, 1);
3490 addr->kind = SOCKET_ADDRESS_KIND_INET;
3491 addr->inet = g_new0(InetSocketAddress, 1);
3492 addr->inet->host = g_strdup(localaddr);
3493 addr->inet->port = g_strdup(localport);
3494 backend->udp->local = addr;
3498 typedef struct CharDriver {
3499 const char *name;
3500 ChardevBackendKind kind;
3501 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3502 } CharDriver;
3504 static GSList *backends;
3506 void register_char_driver(const char *name, ChardevBackendKind kind,
3507 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3509 CharDriver *s;
3511 s = g_malloc0(sizeof(*s));
3512 s->name = g_strdup(name);
3513 s->kind = kind;
3514 s->parse = parse;
3516 backends = g_slist_append(backends, s);
3519 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3520 void (*init)(struct CharDriverState *s),
3521 Error **errp)
3523 Error *local_err = NULL;
3524 CharDriver *cd;
3525 CharDriverState *chr;
3526 GSList *i;
3527 ChardevReturn *ret = NULL;
3528 ChardevBackend *backend;
3529 const char *id = qemu_opts_id(opts);
3530 char *bid = NULL;
3532 if (id == NULL) {
3533 error_setg(errp, "chardev: no id specified");
3534 goto err;
3537 if (qemu_opt_get(opts, "backend") == NULL) {
3538 error_setg(errp, "chardev: \"%s\" missing backend",
3539 qemu_opts_id(opts));
3540 goto err;
3542 for (i = backends; i; i = i->next) {
3543 cd = i->data;
3545 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3546 break;
3549 if (i == NULL) {
3550 error_setg(errp, "chardev: backend \"%s\" not found",
3551 qemu_opt_get(opts, "backend"));
3552 goto err;
3555 backend = g_new0(ChardevBackend, 1);
3557 if (qemu_opt_get_bool(opts, "mux", 0)) {
3558 bid = g_strdup_printf("%s-base", id);
3561 chr = NULL;
3562 backend->kind = cd->kind;
3563 if (cd->parse) {
3564 cd->parse(opts, backend, &local_err);
3565 if (local_err) {
3566 error_propagate(errp, local_err);
3567 goto qapi_out;
3570 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3571 if (!ret) {
3572 goto qapi_out;
3575 if (bid) {
3576 qapi_free_ChardevBackend(backend);
3577 qapi_free_ChardevReturn(ret);
3578 backend = g_new0(ChardevBackend, 1);
3579 backend->mux = g_new0(ChardevMux, 1);
3580 backend->kind = CHARDEV_BACKEND_KIND_MUX;
3581 backend->mux->chardev = g_strdup(bid);
3582 ret = qmp_chardev_add(id, backend, errp);
3583 if (!ret) {
3584 chr = qemu_chr_find(bid);
3585 qemu_chr_delete(chr);
3586 chr = NULL;
3587 goto qapi_out;
3591 chr = qemu_chr_find(id);
3592 chr->opts = opts;
3594 qapi_out:
3595 qapi_free_ChardevBackend(backend);
3596 qapi_free_ChardevReturn(ret);
3597 g_free(bid);
3598 return chr;
3600 err:
3601 qemu_opts_del(opts);
3602 return NULL;
3605 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3607 const char *p;
3608 CharDriverState *chr;
3609 QemuOpts *opts;
3610 Error *err = NULL;
3612 if (strstart(filename, "chardev:", &p)) {
3613 return qemu_chr_find(p);
3616 opts = qemu_chr_parse_compat(label, filename);
3617 if (!opts)
3618 return NULL;
3620 chr = qemu_chr_new_from_opts(opts, init, &err);
3621 if (err) {
3622 error_report("%s", error_get_pretty(err));
3623 error_free(err);
3625 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3626 qemu_chr_fe_claim_no_fail(chr);
3627 monitor_init(chr, MONITOR_USE_READLINE);
3629 return chr;
3632 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3634 if (chr->chr_set_echo) {
3635 chr->chr_set_echo(chr, echo);
3639 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3641 if (chr->fe_open == fe_open) {
3642 return;
3644 chr->fe_open = fe_open;
3645 if (chr->chr_set_fe_open) {
3646 chr->chr_set_fe_open(chr, fe_open);
3650 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3652 if (chr->chr_fe_event) {
3653 chr->chr_fe_event(chr, event);
3657 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3658 GIOFunc func, void *user_data)
3660 GSource *src;
3661 guint tag;
3663 if (s->chr_add_watch == NULL) {
3664 return -ENOSYS;
3667 src = s->chr_add_watch(s, cond);
3668 if (!src) {
3669 return -EINVAL;
3672 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3673 tag = g_source_attach(src, NULL);
3674 g_source_unref(src);
3676 return tag;
3679 int qemu_chr_fe_claim(CharDriverState *s)
3681 if (s->avail_connections < 1) {
3682 return -1;
3684 s->avail_connections--;
3685 return 0;
3688 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3690 if (qemu_chr_fe_claim(s) != 0) {
3691 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3692 __func__, s->label);
3693 exit(1);
3697 void qemu_chr_fe_release(CharDriverState *s)
3699 s->avail_connections++;
3702 void qemu_chr_delete(CharDriverState *chr)
3704 QTAILQ_REMOVE(&chardevs, chr, next);
3705 if (chr->chr_close) {
3706 chr->chr_close(chr);
3708 g_free(chr->filename);
3709 g_free(chr->label);
3710 if (chr->opts) {
3711 qemu_opts_del(chr->opts);
3713 g_free(chr);
3716 ChardevInfoList *qmp_query_chardev(Error **errp)
3718 ChardevInfoList *chr_list = NULL;
3719 CharDriverState *chr;
3721 QTAILQ_FOREACH(chr, &chardevs, next) {
3722 ChardevInfoList *info = g_malloc0(sizeof(*info));
3723 info->value = g_malloc0(sizeof(*info->value));
3724 info->value->label = g_strdup(chr->label);
3725 info->value->filename = g_strdup(chr->filename);
3726 info->value->frontend_open = chr->fe_open;
3728 info->next = chr_list;
3729 chr_list = info;
3732 return chr_list;
3735 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
3737 ChardevBackendInfoList *backend_list = NULL;
3738 CharDriver *c = NULL;
3739 GSList *i = NULL;
3741 for (i = backends; i; i = i->next) {
3742 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
3743 c = i->data;
3744 info->value = g_malloc0(sizeof(*info->value));
3745 info->value->name = g_strdup(c->name);
3747 info->next = backend_list;
3748 backend_list = info;
3751 return backend_list;
3754 CharDriverState *qemu_chr_find(const char *name)
3756 CharDriverState *chr;
3758 QTAILQ_FOREACH(chr, &chardevs, next) {
3759 if (strcmp(chr->label, name) != 0)
3760 continue;
3761 return chr;
3763 return NULL;
3766 /* Get a character (serial) device interface. */
3767 CharDriverState *qemu_char_get_next_serial(void)
3769 static int next_serial;
3770 CharDriverState *chr;
3772 /* FIXME: This function needs to go away: use chardev properties! */
3774 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3775 chr = serial_hds[next_serial++];
3776 qemu_chr_fe_claim_no_fail(chr);
3777 return chr;
3779 return NULL;
3782 QemuOptsList qemu_chardev_opts = {
3783 .name = "chardev",
3784 .implied_opt_name = "backend",
3785 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3786 .desc = {
3788 .name = "backend",
3789 .type = QEMU_OPT_STRING,
3791 .name = "path",
3792 .type = QEMU_OPT_STRING,
3794 .name = "host",
3795 .type = QEMU_OPT_STRING,
3797 .name = "port",
3798 .type = QEMU_OPT_STRING,
3800 .name = "localaddr",
3801 .type = QEMU_OPT_STRING,
3803 .name = "localport",
3804 .type = QEMU_OPT_STRING,
3806 .name = "to",
3807 .type = QEMU_OPT_NUMBER,
3809 .name = "ipv4",
3810 .type = QEMU_OPT_BOOL,
3812 .name = "ipv6",
3813 .type = QEMU_OPT_BOOL,
3815 .name = "wait",
3816 .type = QEMU_OPT_BOOL,
3818 .name = "server",
3819 .type = QEMU_OPT_BOOL,
3821 .name = "delay",
3822 .type = QEMU_OPT_BOOL,
3824 .name = "telnet",
3825 .type = QEMU_OPT_BOOL,
3827 .name = "width",
3828 .type = QEMU_OPT_NUMBER,
3830 .name = "height",
3831 .type = QEMU_OPT_NUMBER,
3833 .name = "cols",
3834 .type = QEMU_OPT_NUMBER,
3836 .name = "rows",
3837 .type = QEMU_OPT_NUMBER,
3839 .name = "mux",
3840 .type = QEMU_OPT_BOOL,
3842 .name = "signal",
3843 .type = QEMU_OPT_BOOL,
3845 .name = "name",
3846 .type = QEMU_OPT_STRING,
3848 .name = "debug",
3849 .type = QEMU_OPT_NUMBER,
3851 .name = "size",
3852 .type = QEMU_OPT_SIZE,
3854 .name = "chardev",
3855 .type = QEMU_OPT_STRING,
3857 { /* end of list */ }
3861 #ifdef _WIN32
3863 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3865 HANDLE out;
3867 if (file->has_in) {
3868 error_setg(errp, "input file not supported");
3869 return NULL;
3872 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3873 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3874 if (out == INVALID_HANDLE_VALUE) {
3875 error_setg(errp, "open %s failed", file->out);
3876 return NULL;
3878 return qemu_chr_open_win_file(out);
3881 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3882 Error **errp)
3884 return qemu_chr_open_win_path(serial->device);
3887 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3888 Error **errp)
3890 error_setg(errp, "character device backend type 'parallel' not supported");
3891 return NULL;
3894 #else /* WIN32 */
3896 static int qmp_chardev_open_file_source(char *src, int flags,
3897 Error **errp)
3899 int fd = -1;
3901 TFR(fd = qemu_open(src, flags, 0666));
3902 if (fd == -1) {
3903 error_setg_file_open(errp, errno, src);
3905 return fd;
3908 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3910 int flags, in = -1, out;
3912 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3913 out = qmp_chardev_open_file_source(file->out, flags, errp);
3914 if (out < 0) {
3915 return NULL;
3918 if (file->has_in) {
3919 flags = O_RDONLY;
3920 in = qmp_chardev_open_file_source(file->in, flags, errp);
3921 if (in < 0) {
3922 qemu_close(out);
3923 return NULL;
3927 return qemu_chr_open_fd(in, out);
3930 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3931 Error **errp)
3933 #ifdef HAVE_CHARDEV_TTY
3934 int fd;
3936 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3937 if (fd < 0) {
3938 return NULL;
3940 qemu_set_nonblock(fd);
3941 return qemu_chr_open_tty_fd(fd);
3942 #else
3943 error_setg(errp, "character device backend type 'serial' not supported");
3944 return NULL;
3945 #endif
3948 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3949 Error **errp)
3951 #ifdef HAVE_CHARDEV_PARPORT
3952 int fd;
3954 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3955 if (fd < 0) {
3956 return NULL;
3958 return qemu_chr_open_pp_fd(fd);
3959 #else
3960 error_setg(errp, "character device backend type 'parallel' not supported");
3961 return NULL;
3962 #endif
3965 #endif /* WIN32 */
3967 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3968 Error **errp)
3970 SocketAddress *addr = sock->addr;
3971 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3972 bool is_listen = sock->has_server ? sock->server : true;
3973 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3974 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3975 int fd;
3977 if (is_listen) {
3978 fd = socket_listen(addr, errp);
3979 } else {
3980 fd = socket_connect(addr, errp, NULL, NULL);
3982 if (fd < 0) {
3983 return NULL;
3985 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3986 is_telnet, is_waitconnect, errp);
3989 static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
3990 Error **errp)
3992 int fd;
3994 fd = socket_dgram(udp->remote, udp->local, errp);
3995 if (fd < 0) {
3996 return NULL;
3998 return qemu_chr_open_udp_fd(fd);
4001 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4002 Error **errp)
4004 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4005 CharDriverState *base, *chr = NULL;
4007 chr = qemu_chr_find(id);
4008 if (chr) {
4009 error_setg(errp, "Chardev '%s' already exists", id);
4010 g_free(ret);
4011 return NULL;
4014 switch (backend->kind) {
4015 case CHARDEV_BACKEND_KIND_FILE:
4016 chr = qmp_chardev_open_file(backend->file, errp);
4017 break;
4018 case CHARDEV_BACKEND_KIND_SERIAL:
4019 chr = qmp_chardev_open_serial(backend->serial, errp);
4020 break;
4021 case CHARDEV_BACKEND_KIND_PARALLEL:
4022 chr = qmp_chardev_open_parallel(backend->parallel, errp);
4023 break;
4024 case CHARDEV_BACKEND_KIND_PIPE:
4025 chr = qemu_chr_open_pipe(backend->pipe);
4026 break;
4027 case CHARDEV_BACKEND_KIND_SOCKET:
4028 chr = qmp_chardev_open_socket(backend->socket, errp);
4029 break;
4030 case CHARDEV_BACKEND_KIND_UDP:
4031 chr = qmp_chardev_open_udp(backend->udp, errp);
4032 break;
4033 #ifdef HAVE_CHARDEV_TTY
4034 case CHARDEV_BACKEND_KIND_PTY:
4035 chr = qemu_chr_open_pty(id, ret);
4036 break;
4037 #endif
4038 case CHARDEV_BACKEND_KIND_NULL:
4039 chr = qemu_chr_open_null();
4040 break;
4041 case CHARDEV_BACKEND_KIND_MUX:
4042 base = qemu_chr_find(backend->mux->chardev);
4043 if (base == NULL) {
4044 error_setg(errp, "mux: base chardev %s not found",
4045 backend->mux->chardev);
4046 break;
4048 chr = qemu_chr_open_mux(base);
4049 break;
4050 case CHARDEV_BACKEND_KIND_MSMOUSE:
4051 chr = qemu_chr_open_msmouse();
4052 break;
4053 #ifdef CONFIG_BRLAPI
4054 case CHARDEV_BACKEND_KIND_BRAILLE:
4055 chr = chr_baum_init();
4056 break;
4057 #endif
4058 case CHARDEV_BACKEND_KIND_TESTDEV:
4059 chr = chr_testdev_init();
4060 break;
4061 case CHARDEV_BACKEND_KIND_STDIO:
4062 chr = qemu_chr_open_stdio(backend->stdio);
4063 break;
4064 #ifdef _WIN32
4065 case CHARDEV_BACKEND_KIND_CONSOLE:
4066 chr = qemu_chr_open_win_con();
4067 break;
4068 #endif
4069 #ifdef CONFIG_SPICE
4070 case CHARDEV_BACKEND_KIND_SPICEVMC:
4071 chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
4072 break;
4073 case CHARDEV_BACKEND_KIND_SPICEPORT:
4074 chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
4075 break;
4076 #endif
4077 case CHARDEV_BACKEND_KIND_VC:
4078 chr = vc_init(backend->vc);
4079 break;
4080 case CHARDEV_BACKEND_KIND_RINGBUF:
4081 case CHARDEV_BACKEND_KIND_MEMORY:
4082 chr = qemu_chr_open_ringbuf(backend->ringbuf, errp);
4083 break;
4084 default:
4085 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
4086 break;
4090 * Character backend open hasn't been fully converted to the Error
4091 * API. Some opens fail without setting an error. Set a generic
4092 * error then.
4093 * TODO full conversion to Error API
4095 if (chr == NULL && errp && !*errp) {
4096 error_setg(errp, "Failed to create chardev");
4098 if (chr) {
4099 chr->label = g_strdup(id);
4100 chr->avail_connections =
4101 (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4102 if (!chr->filename) {
4103 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
4105 if (!chr->explicit_be_open) {
4106 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4108 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4109 return ret;
4110 } else {
4111 g_free(ret);
4112 return NULL;
4116 void qmp_chardev_remove(const char *id, Error **errp)
4118 CharDriverState *chr;
4120 chr = qemu_chr_find(id);
4121 if (chr == NULL) {
4122 error_setg(errp, "Chardev '%s' not found", id);
4123 return;
4125 if (chr->chr_can_read || chr->chr_read ||
4126 chr->chr_event || chr->handler_opaque) {
4127 error_setg(errp, "Chardev '%s' is busy", id);
4128 return;
4130 qemu_chr_delete(chr);
4133 static void register_types(void)
4135 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL);
4136 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4137 qemu_chr_parse_socket);
4138 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp);
4139 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4140 qemu_chr_parse_ringbuf);
4141 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4142 qemu_chr_parse_file_out);
4143 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4144 qemu_chr_parse_stdio);
4145 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4146 qemu_chr_parse_serial);
4147 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4148 qemu_chr_parse_serial);
4149 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4150 qemu_chr_parse_parallel);
4151 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4152 qemu_chr_parse_parallel);
4153 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
4154 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
4155 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4156 qemu_chr_parse_pipe);
4157 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux);
4158 /* Bug-compatibility: */
4159 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4160 qemu_chr_parse_ringbuf);
4161 /* this must be done after machine init, since we register FEs with muxes
4162 * as part of realize functions like serial_isa_realizefn when -nographic
4163 * is specified
4165 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4168 type_init(register_types);