mirror: Go through ready -> complete process for 0 len image
[qemu/ar7.git] / qemu-char.c
blob2e50a1093ec180bea1958886ed479d455fd7d76a
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 return chr;
100 void qemu_chr_be_event(CharDriverState *s, int event)
102 /* Keep track if the char device is open */
103 switch (event) {
104 case CHR_EVENT_OPENED:
105 s->be_open = 1;
106 break;
107 case CHR_EVENT_CLOSED:
108 s->be_open = 0;
109 break;
112 if (!s->chr_event)
113 return;
114 s->chr_event(s->handler_opaque, event);
117 void qemu_chr_be_generic_open(CharDriverState *s)
119 qemu_chr_be_event(s, CHR_EVENT_OPENED);
122 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
124 int ret;
126 qemu_mutex_lock(&s->chr_write_lock);
127 ret = s->chr_write(s, buf, len);
128 qemu_mutex_unlock(&s->chr_write_lock);
129 return ret;
132 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
134 int offset = 0;
135 int res;
137 qemu_mutex_lock(&s->chr_write_lock);
138 while (offset < len) {
139 do {
140 res = s->chr_write(s, buf + offset, len - offset);
141 if (res == -1 && errno == EAGAIN) {
142 g_usleep(100);
144 } while (res == -1 && errno == EAGAIN);
146 if (res <= 0) {
147 break;
150 offset += res;
152 qemu_mutex_unlock(&s->chr_write_lock);
154 if (res < 0) {
155 return res;
157 return offset;
160 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
162 int offset = 0, counter = 10;
163 int res;
165 if (!s->chr_sync_read) {
166 return 0;
169 while (offset < len) {
170 do {
171 res = s->chr_sync_read(s, buf + offset, len - offset);
172 if (res == -1 && errno == EAGAIN) {
173 g_usleep(100);
175 } while (res == -1 && errno == EAGAIN);
177 if (res == 0) {
178 break;
181 if (res < 0) {
182 return res;
185 offset += res;
187 if (!counter--) {
188 break;
192 return offset;
195 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
197 if (!s->chr_ioctl)
198 return -ENOTSUP;
199 return s->chr_ioctl(s, cmd, arg);
202 int qemu_chr_be_can_write(CharDriverState *s)
204 if (!s->chr_can_read)
205 return 0;
206 return s->chr_can_read(s->handler_opaque);
209 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
211 if (s->chr_read) {
212 s->chr_read(s->handler_opaque, buf, len);
216 int qemu_chr_fe_get_msgfd(CharDriverState *s)
218 int fd;
219 return (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
222 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
224 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
227 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
229 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
232 int qemu_chr_add_client(CharDriverState *s, int fd)
234 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
237 void qemu_chr_accept_input(CharDriverState *s)
239 if (s->chr_accept_input)
240 s->chr_accept_input(s);
241 qemu_notify_event();
244 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
246 char buf[READ_BUF_LEN];
247 va_list ap;
248 va_start(ap, fmt);
249 vsnprintf(buf, sizeof(buf), fmt, ap);
250 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
251 va_end(ap);
254 static void remove_fd_in_watch(CharDriverState *chr);
256 void qemu_chr_add_handlers(CharDriverState *s,
257 IOCanReadHandler *fd_can_read,
258 IOReadHandler *fd_read,
259 IOEventHandler *fd_event,
260 void *opaque)
262 int fe_open;
264 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
265 fe_open = 0;
266 remove_fd_in_watch(s);
267 } else {
268 fe_open = 1;
270 s->chr_can_read = fd_can_read;
271 s->chr_read = fd_read;
272 s->chr_event = fd_event;
273 s->handler_opaque = opaque;
274 if (fe_open && s->chr_update_read_handler)
275 s->chr_update_read_handler(s);
277 if (!s->explicit_fe_open) {
278 qemu_chr_fe_set_open(s, fe_open);
281 /* We're connecting to an already opened device, so let's make sure we
282 also get the open event */
283 if (fe_open && s->be_open) {
284 qemu_chr_be_generic_open(s);
288 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
290 return len;
293 static CharDriverState *qemu_chr_open_null(void)
295 CharDriverState *chr;
297 chr = qemu_chr_alloc();
298 chr->chr_write = null_chr_write;
299 chr->explicit_be_open = true;
300 return chr;
303 /* MUX driver for serial I/O splitting */
304 #define MAX_MUX 4
305 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
306 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
307 typedef struct {
308 IOCanReadHandler *chr_can_read[MAX_MUX];
309 IOReadHandler *chr_read[MAX_MUX];
310 IOEventHandler *chr_event[MAX_MUX];
311 void *ext_opaque[MAX_MUX];
312 CharDriverState *drv;
313 int focus;
314 int mux_cnt;
315 int term_got_escape;
316 int max_size;
317 /* Intermediate input buffer allows to catch escape sequences even if the
318 currently active device is not accepting any input - but only until it
319 is full as well. */
320 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
321 int prod[MAX_MUX];
322 int cons[MAX_MUX];
323 int timestamps;
325 /* Protected by the CharDriverState chr_write_lock. */
326 int linestart;
327 int64_t timestamps_start;
328 } MuxDriver;
331 /* Called with chr_write_lock held. */
332 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
334 MuxDriver *d = chr->opaque;
335 int ret;
336 if (!d->timestamps) {
337 ret = qemu_chr_fe_write(d->drv, buf, len);
338 } else {
339 int i;
341 ret = 0;
342 for (i = 0; i < len; i++) {
343 if (d->linestart) {
344 char buf1[64];
345 int64_t ti;
346 int secs;
348 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
349 if (d->timestamps_start == -1)
350 d->timestamps_start = ti;
351 ti -= d->timestamps_start;
352 secs = ti / 1000;
353 snprintf(buf1, sizeof(buf1),
354 "[%02d:%02d:%02d.%03d] ",
355 secs / 3600,
356 (secs / 60) % 60,
357 secs % 60,
358 (int)(ti % 1000));
359 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
360 d->linestart = 0;
362 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
363 if (buf[i] == '\n') {
364 d->linestart = 1;
368 return ret;
371 static const char * const mux_help[] = {
372 "% h print this help\n\r",
373 "% x exit emulator\n\r",
374 "% s save disk data back to file (if -snapshot)\n\r",
375 "% t toggle console timestamps\n\r"
376 "% b send break (magic sysrq)\n\r",
377 "% c switch between console and monitor\n\r",
378 "% % sends %\n\r",
379 NULL
382 int term_escape_char = 0x01; /* ctrl-a is used for escape */
383 static void mux_print_help(CharDriverState *chr)
385 int i, j;
386 char ebuf[15] = "Escape-Char";
387 char cbuf[50] = "\n\r";
389 if (term_escape_char > 0 && term_escape_char < 26) {
390 snprintf(cbuf, sizeof(cbuf), "\n\r");
391 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
392 } else {
393 snprintf(cbuf, sizeof(cbuf),
394 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
395 term_escape_char);
397 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
398 for (i = 0; mux_help[i] != NULL; i++) {
399 for (j=0; mux_help[i][j] != '\0'; j++) {
400 if (mux_help[i][j] == '%')
401 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
402 else
403 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
408 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
410 if (d->chr_event[mux_nr])
411 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
414 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
416 if (d->term_got_escape) {
417 d->term_got_escape = 0;
418 if (ch == term_escape_char)
419 goto send_char;
420 switch(ch) {
421 case '?':
422 case 'h':
423 mux_print_help(chr);
424 break;
425 case 'x':
427 const char *term = "QEMU: Terminated\n\r";
428 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
429 exit(0);
430 break;
432 case 's':
433 bdrv_commit_all();
434 break;
435 case 'b':
436 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
437 break;
438 case 'c':
439 /* Switch to the next registered device */
440 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
441 d->focus++;
442 if (d->focus >= d->mux_cnt)
443 d->focus = 0;
444 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
445 break;
446 case 't':
447 d->timestamps = !d->timestamps;
448 d->timestamps_start = -1;
449 d->linestart = 0;
450 break;
452 } else if (ch == term_escape_char) {
453 d->term_got_escape = 1;
454 } else {
455 send_char:
456 return 1;
458 return 0;
461 static void mux_chr_accept_input(CharDriverState *chr)
463 MuxDriver *d = chr->opaque;
464 int m = d->focus;
466 while (d->prod[m] != d->cons[m] &&
467 d->chr_can_read[m] &&
468 d->chr_can_read[m](d->ext_opaque[m])) {
469 d->chr_read[m](d->ext_opaque[m],
470 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
474 static int mux_chr_can_read(void *opaque)
476 CharDriverState *chr = opaque;
477 MuxDriver *d = chr->opaque;
478 int m = d->focus;
480 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
481 return 1;
482 if (d->chr_can_read[m])
483 return d->chr_can_read[m](d->ext_opaque[m]);
484 return 0;
487 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
489 CharDriverState *chr = opaque;
490 MuxDriver *d = chr->opaque;
491 int m = d->focus;
492 int i;
494 mux_chr_accept_input (opaque);
496 for(i = 0; i < size; i++)
497 if (mux_proc_byte(chr, d, buf[i])) {
498 if (d->prod[m] == d->cons[m] &&
499 d->chr_can_read[m] &&
500 d->chr_can_read[m](d->ext_opaque[m]))
501 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
502 else
503 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
507 static void mux_chr_event(void *opaque, int event)
509 CharDriverState *chr = opaque;
510 MuxDriver *d = chr->opaque;
511 int i;
513 /* Send the event to all registered listeners */
514 for (i = 0; i < d->mux_cnt; i++)
515 mux_chr_send_event(d, i, event);
518 static void mux_chr_update_read_handler(CharDriverState *chr)
520 MuxDriver *d = chr->opaque;
522 if (d->mux_cnt >= MAX_MUX) {
523 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
524 return;
526 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
527 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
528 d->chr_read[d->mux_cnt] = chr->chr_read;
529 d->chr_event[d->mux_cnt] = chr->chr_event;
530 /* Fix up the real driver with mux routines */
531 if (d->mux_cnt == 0) {
532 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
533 mux_chr_event, chr);
535 if (d->focus != -1) {
536 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
538 d->focus = d->mux_cnt;
539 d->mux_cnt++;
540 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
543 static bool muxes_realized;
546 * Called after processing of default and command-line-specified
547 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
548 * to a mux chardev. This is done here to ensure that
549 * output/prompts/banners are only displayed for the FE that has
550 * focus when initial command-line processing/machine init is
551 * completed.
553 * After this point, any new FE attached to any new or existing
554 * mux will receive CHR_EVENT_OPENED notifications for the BE
555 * immediately.
557 static void muxes_realize_done(Notifier *notifier, void *unused)
559 CharDriverState *chr;
561 QTAILQ_FOREACH(chr, &chardevs, next) {
562 if (chr->is_mux) {
563 MuxDriver *d = chr->opaque;
564 int i;
566 /* send OPENED to all already-attached FEs */
567 for (i = 0; i < d->mux_cnt; i++) {
568 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
570 /* mark mux as OPENED so any new FEs will immediately receive
571 * OPENED event
573 qemu_chr_be_generic_open(chr);
576 muxes_realized = true;
579 static Notifier muxes_realize_notify = {
580 .notify = muxes_realize_done,
583 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
585 CharDriverState *chr;
586 MuxDriver *d;
588 chr = qemu_chr_alloc();
589 d = g_malloc0(sizeof(MuxDriver));
591 chr->opaque = d;
592 d->drv = drv;
593 d->focus = -1;
594 chr->chr_write = mux_chr_write;
595 chr->chr_update_read_handler = mux_chr_update_read_handler;
596 chr->chr_accept_input = mux_chr_accept_input;
597 /* Frontend guest-open / -close notification is not support with muxes */
598 chr->chr_set_fe_open = NULL;
599 /* only default to opened state if we've realized the initial
600 * set of muxes
602 chr->explicit_be_open = muxes_realized ? 0 : 1;
603 chr->is_mux = 1;
605 return chr;
609 #ifdef _WIN32
610 int send_all(int fd, const void *buf, int len1)
612 int ret, len;
614 len = len1;
615 while (len > 0) {
616 ret = send(fd, buf, len, 0);
617 if (ret < 0) {
618 errno = WSAGetLastError();
619 if (errno != WSAEWOULDBLOCK) {
620 return -1;
622 } else if (ret == 0) {
623 break;
624 } else {
625 buf += ret;
626 len -= ret;
629 return len1 - len;
632 #else
634 int send_all(int fd, const void *_buf, int len1)
636 int ret, len;
637 const uint8_t *buf = _buf;
639 len = len1;
640 while (len > 0) {
641 ret = write(fd, buf, len);
642 if (ret < 0) {
643 if (errno != EINTR && errno != EAGAIN)
644 return -1;
645 } else if (ret == 0) {
646 break;
647 } else {
648 buf += ret;
649 len -= ret;
652 return len1 - len;
655 int recv_all(int fd, void *_buf, int len1, bool single_read)
657 int ret, len;
658 uint8_t *buf = _buf;
660 len = len1;
661 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
662 if (ret < 0) {
663 if (errno != EINTR && errno != EAGAIN) {
664 return -1;
666 continue;
667 } else {
668 if (single_read) {
669 return ret;
671 buf += ret;
672 len -= ret;
675 return len1 - len;
678 #endif /* !_WIN32 */
680 typedef struct IOWatchPoll
682 GSource parent;
684 GIOChannel *channel;
685 GSource *src;
687 IOCanReadHandler *fd_can_read;
688 GSourceFunc fd_read;
689 void *opaque;
690 } IOWatchPoll;
692 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
694 return container_of(source, IOWatchPoll, parent);
697 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
699 IOWatchPoll *iwp = io_watch_poll_from_source(source);
700 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
701 bool was_active = iwp->src != NULL;
702 if (was_active == now_active) {
703 return FALSE;
706 if (now_active) {
707 iwp->src = g_io_create_watch(iwp->channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
708 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
709 g_source_attach(iwp->src, NULL);
710 } else {
711 g_source_destroy(iwp->src);
712 g_source_unref(iwp->src);
713 iwp->src = NULL;
715 return FALSE;
718 static gboolean io_watch_poll_check(GSource *source)
720 return FALSE;
723 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
724 gpointer user_data)
726 abort();
729 static void io_watch_poll_finalize(GSource *source)
731 /* Due to a glib bug, removing the last reference to a source
732 * inside a finalize callback causes recursive locking (and a
733 * deadlock). This is not a problem inside other callbacks,
734 * including dispatch callbacks, so we call io_remove_watch_poll
735 * to remove this source. At this point, iwp->src must
736 * be NULL, or we would leak it.
738 * This would be solved much more elegantly by child sources,
739 * but we support older glib versions that do not have them.
741 IOWatchPoll *iwp = io_watch_poll_from_source(source);
742 assert(iwp->src == NULL);
745 static GSourceFuncs io_watch_poll_funcs = {
746 .prepare = io_watch_poll_prepare,
747 .check = io_watch_poll_check,
748 .dispatch = io_watch_poll_dispatch,
749 .finalize = io_watch_poll_finalize,
752 /* Can only be used for read */
753 static guint io_add_watch_poll(GIOChannel *channel,
754 IOCanReadHandler *fd_can_read,
755 GIOFunc fd_read,
756 gpointer user_data)
758 IOWatchPoll *iwp;
759 int tag;
761 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
762 iwp->fd_can_read = fd_can_read;
763 iwp->opaque = user_data;
764 iwp->channel = channel;
765 iwp->fd_read = (GSourceFunc) fd_read;
766 iwp->src = NULL;
768 tag = g_source_attach(&iwp->parent, NULL);
769 g_source_unref(&iwp->parent);
770 return tag;
773 static void io_remove_watch_poll(guint tag)
775 GSource *source;
776 IOWatchPoll *iwp;
778 g_return_if_fail (tag > 0);
780 source = g_main_context_find_source_by_id(NULL, tag);
781 g_return_if_fail (source != NULL);
783 iwp = io_watch_poll_from_source(source);
784 if (iwp->src) {
785 g_source_destroy(iwp->src);
786 g_source_unref(iwp->src);
787 iwp->src = NULL;
789 g_source_destroy(&iwp->parent);
792 static void remove_fd_in_watch(CharDriverState *chr)
794 if (chr->fd_in_tag) {
795 io_remove_watch_poll(chr->fd_in_tag);
796 chr->fd_in_tag = 0;
800 #ifndef _WIN32
801 static GIOChannel *io_channel_from_fd(int fd)
803 GIOChannel *chan;
805 if (fd == -1) {
806 return NULL;
809 chan = g_io_channel_unix_new(fd);
811 g_io_channel_set_encoding(chan, NULL, NULL);
812 g_io_channel_set_buffered(chan, FALSE);
814 return chan;
816 #endif
818 static GIOChannel *io_channel_from_socket(int fd)
820 GIOChannel *chan;
822 if (fd == -1) {
823 return NULL;
826 #ifdef _WIN32
827 chan = g_io_channel_win32_new_socket(fd);
828 #else
829 chan = g_io_channel_unix_new(fd);
830 #endif
832 g_io_channel_set_encoding(chan, NULL, NULL);
833 g_io_channel_set_buffered(chan, FALSE);
835 return chan;
838 static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
840 size_t offset = 0;
841 GIOStatus status = G_IO_STATUS_NORMAL;
843 while (offset < len && status == G_IO_STATUS_NORMAL) {
844 gsize bytes_written = 0;
846 status = g_io_channel_write_chars(fd, buf + offset, len - offset,
847 &bytes_written, NULL);
848 offset += bytes_written;
851 if (offset > 0) {
852 return offset;
854 switch (status) {
855 case G_IO_STATUS_NORMAL:
856 g_assert(len == 0);
857 return 0;
858 case G_IO_STATUS_AGAIN:
859 errno = EAGAIN;
860 return -1;
861 default:
862 break;
864 errno = EINVAL;
865 return -1;
868 #ifndef _WIN32
870 typedef struct FDCharDriver {
871 CharDriverState *chr;
872 GIOChannel *fd_in, *fd_out;
873 int max_size;
874 QTAILQ_ENTRY(FDCharDriver) node;
875 } FDCharDriver;
877 /* Called with chr_write_lock held. */
878 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
880 FDCharDriver *s = chr->opaque;
882 return io_channel_send(s->fd_out, buf, len);
885 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
887 CharDriverState *chr = opaque;
888 FDCharDriver *s = chr->opaque;
889 int len;
890 uint8_t buf[READ_BUF_LEN];
891 GIOStatus status;
892 gsize bytes_read;
894 len = sizeof(buf);
895 if (len > s->max_size) {
896 len = s->max_size;
898 if (len == 0) {
899 return TRUE;
902 status = g_io_channel_read_chars(chan, (gchar *)buf,
903 len, &bytes_read, NULL);
904 if (status == G_IO_STATUS_EOF) {
905 remove_fd_in_watch(chr);
906 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
907 return FALSE;
909 if (status == G_IO_STATUS_NORMAL) {
910 qemu_chr_be_write(chr, buf, bytes_read);
913 return TRUE;
916 static int fd_chr_read_poll(void *opaque)
918 CharDriverState *chr = opaque;
919 FDCharDriver *s = chr->opaque;
921 s->max_size = qemu_chr_be_can_write(chr);
922 return s->max_size;
925 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
927 FDCharDriver *s = chr->opaque;
928 return g_io_create_watch(s->fd_out, cond);
931 static void fd_chr_update_read_handler(CharDriverState *chr)
933 FDCharDriver *s = chr->opaque;
935 remove_fd_in_watch(chr);
936 if (s->fd_in) {
937 chr->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll,
938 fd_chr_read, chr);
942 static void fd_chr_close(struct CharDriverState *chr)
944 FDCharDriver *s = chr->opaque;
946 remove_fd_in_watch(chr);
947 if (s->fd_in) {
948 g_io_channel_unref(s->fd_in);
950 if (s->fd_out) {
951 g_io_channel_unref(s->fd_out);
954 g_free(s);
955 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
958 /* open a character device to a unix fd */
959 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
961 CharDriverState *chr;
962 FDCharDriver *s;
964 chr = qemu_chr_alloc();
965 s = g_malloc0(sizeof(FDCharDriver));
966 s->fd_in = io_channel_from_fd(fd_in);
967 s->fd_out = io_channel_from_fd(fd_out);
968 fcntl(fd_out, F_SETFL, O_NONBLOCK);
969 s->chr = chr;
970 chr->opaque = s;
971 chr->chr_add_watch = fd_chr_add_watch;
972 chr->chr_write = fd_chr_write;
973 chr->chr_update_read_handler = fd_chr_update_read_handler;
974 chr->chr_close = fd_chr_close;
976 return chr;
979 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
981 int fd_in, fd_out;
982 char filename_in[256], filename_out[256];
983 const char *filename = opts->device;
985 if (filename == NULL) {
986 fprintf(stderr, "chardev: pipe: no filename given\n");
987 return NULL;
990 snprintf(filename_in, 256, "%s.in", filename);
991 snprintf(filename_out, 256, "%s.out", filename);
992 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
993 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
994 if (fd_in < 0 || fd_out < 0) {
995 if (fd_in >= 0)
996 close(fd_in);
997 if (fd_out >= 0)
998 close(fd_out);
999 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1000 if (fd_in < 0) {
1001 return NULL;
1004 return qemu_chr_open_fd(fd_in, fd_out);
1007 /* init terminal so that we can grab keys */
1008 static struct termios oldtty;
1009 static int old_fd0_flags;
1010 static bool stdio_allow_signal;
1012 static void term_exit(void)
1014 tcsetattr (0, TCSANOW, &oldtty);
1015 fcntl(0, F_SETFL, old_fd0_flags);
1018 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1020 struct termios tty;
1022 tty = oldtty;
1023 if (!echo) {
1024 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1025 |INLCR|IGNCR|ICRNL|IXON);
1026 tty.c_oflag |= OPOST;
1027 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1028 tty.c_cflag &= ~(CSIZE|PARENB);
1029 tty.c_cflag |= CS8;
1030 tty.c_cc[VMIN] = 1;
1031 tty.c_cc[VTIME] = 0;
1033 if (!stdio_allow_signal)
1034 tty.c_lflag &= ~ISIG;
1036 tcsetattr (0, TCSANOW, &tty);
1039 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1041 term_exit();
1042 fd_chr_close(chr);
1045 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
1047 CharDriverState *chr;
1049 if (is_daemonized()) {
1050 error_report("cannot use stdio with -daemonize");
1051 return NULL;
1053 old_fd0_flags = fcntl(0, F_GETFL);
1054 tcgetattr (0, &oldtty);
1055 fcntl(0, F_SETFL, O_NONBLOCK);
1056 atexit(term_exit);
1058 chr = qemu_chr_open_fd(0, 1);
1059 chr->chr_close = qemu_chr_close_stdio;
1060 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1061 if (opts->has_signal) {
1062 stdio_allow_signal = opts->signal;
1064 qemu_chr_fe_set_echo(chr, false);
1066 return chr;
1069 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1070 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1071 || defined(__GLIBC__)
1073 #define HAVE_CHARDEV_TTY 1
1075 typedef struct {
1076 GIOChannel *fd;
1077 int read_bytes;
1079 /* Protected by the CharDriverState chr_write_lock. */
1080 int connected;
1081 guint timer_tag;
1082 } PtyCharDriver;
1084 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1085 static void pty_chr_state(CharDriverState *chr, int connected);
1087 static gboolean pty_chr_timer(gpointer opaque)
1089 struct CharDriverState *chr = opaque;
1090 PtyCharDriver *s = chr->opaque;
1092 qemu_mutex_lock(&chr->chr_write_lock);
1093 s->timer_tag = 0;
1094 if (!s->connected) {
1095 /* Next poll ... */
1096 pty_chr_update_read_handler_locked(chr);
1098 qemu_mutex_unlock(&chr->chr_write_lock);
1099 return FALSE;
1102 /* Called with chr_write_lock held. */
1103 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1105 PtyCharDriver *s = chr->opaque;
1107 if (s->timer_tag) {
1108 g_source_remove(s->timer_tag);
1109 s->timer_tag = 0;
1112 if (ms == 1000) {
1113 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1114 } else {
1115 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1119 /* Called with chr_write_lock held. */
1120 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1122 PtyCharDriver *s = chr->opaque;
1123 GPollFD pfd;
1125 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1126 pfd.events = G_IO_OUT;
1127 pfd.revents = 0;
1128 g_poll(&pfd, 1, 0);
1129 if (pfd.revents & G_IO_HUP) {
1130 pty_chr_state(chr, 0);
1131 } else {
1132 pty_chr_state(chr, 1);
1136 static void pty_chr_update_read_handler(CharDriverState *chr)
1138 qemu_mutex_lock(&chr->chr_write_lock);
1139 pty_chr_update_read_handler_locked(chr);
1140 qemu_mutex_unlock(&chr->chr_write_lock);
1143 /* Called with chr_write_lock held. */
1144 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1146 PtyCharDriver *s = chr->opaque;
1148 if (!s->connected) {
1149 /* guest sends data, check for (re-)connect */
1150 pty_chr_update_read_handler_locked(chr);
1151 return 0;
1153 return io_channel_send(s->fd, buf, len);
1156 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1158 PtyCharDriver *s = chr->opaque;
1159 return g_io_create_watch(s->fd, cond);
1162 static int pty_chr_read_poll(void *opaque)
1164 CharDriverState *chr = opaque;
1165 PtyCharDriver *s = chr->opaque;
1167 s->read_bytes = qemu_chr_be_can_write(chr);
1168 return s->read_bytes;
1171 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1173 CharDriverState *chr = opaque;
1174 PtyCharDriver *s = chr->opaque;
1175 gsize size, len;
1176 uint8_t buf[READ_BUF_LEN];
1177 GIOStatus status;
1179 len = sizeof(buf);
1180 if (len > s->read_bytes)
1181 len = s->read_bytes;
1182 if (len == 0) {
1183 return TRUE;
1185 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1186 if (status != G_IO_STATUS_NORMAL) {
1187 pty_chr_state(chr, 0);
1188 return FALSE;
1189 } else {
1190 pty_chr_state(chr, 1);
1191 qemu_chr_be_write(chr, buf, size);
1193 return TRUE;
1196 /* Called with chr_write_lock held. */
1197 static void pty_chr_state(CharDriverState *chr, int connected)
1199 PtyCharDriver *s = chr->opaque;
1201 if (!connected) {
1202 remove_fd_in_watch(chr);
1203 s->connected = 0;
1204 /* (re-)connect poll interval for idle guests: once per second.
1205 * We check more frequently in case the guests sends data to
1206 * the virtual device linked to our pty. */
1207 pty_chr_rearm_timer(chr, 1000);
1208 } else {
1209 if (s->timer_tag) {
1210 g_source_remove(s->timer_tag);
1211 s->timer_tag = 0;
1213 if (!s->connected) {
1214 s->connected = 1;
1215 qemu_chr_be_generic_open(chr);
1217 if (!chr->fd_in_tag) {
1218 chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
1219 pty_chr_read, chr);
1224 static void pty_chr_close(struct CharDriverState *chr)
1226 PtyCharDriver *s = chr->opaque;
1227 int fd;
1229 remove_fd_in_watch(chr);
1230 fd = g_io_channel_unix_get_fd(s->fd);
1231 g_io_channel_unref(s->fd);
1232 close(fd);
1233 if (s->timer_tag) {
1234 g_source_remove(s->timer_tag);
1235 s->timer_tag = 0;
1237 g_free(s);
1238 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1241 static CharDriverState *qemu_chr_open_pty(const char *id,
1242 ChardevReturn *ret)
1244 CharDriverState *chr;
1245 PtyCharDriver *s;
1246 int master_fd, slave_fd;
1247 char pty_name[PATH_MAX];
1249 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1250 if (master_fd < 0) {
1251 return NULL;
1254 close(slave_fd);
1256 chr = qemu_chr_alloc();
1258 chr->filename = g_strdup_printf("pty:%s", pty_name);
1259 ret->pty = g_strdup(pty_name);
1260 ret->has_pty = true;
1262 fprintf(stderr, "char device redirected to %s (label %s)\n",
1263 pty_name, id);
1265 s = g_malloc0(sizeof(PtyCharDriver));
1266 chr->opaque = s;
1267 chr->chr_write = pty_chr_write;
1268 chr->chr_update_read_handler = pty_chr_update_read_handler;
1269 chr->chr_close = pty_chr_close;
1270 chr->chr_add_watch = pty_chr_add_watch;
1271 chr->explicit_be_open = true;
1273 s->fd = io_channel_from_fd(master_fd);
1274 s->timer_tag = 0;
1276 return chr;
1279 static void tty_serial_init(int fd, int speed,
1280 int parity, int data_bits, int stop_bits)
1282 struct termios tty;
1283 speed_t spd;
1285 #if 0
1286 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1287 speed, parity, data_bits, stop_bits);
1288 #endif
1289 tcgetattr (fd, &tty);
1291 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1292 speed = speed * 10 / 11;
1293 do {
1294 check_speed(50);
1295 check_speed(75);
1296 check_speed(110);
1297 check_speed(134);
1298 check_speed(150);
1299 check_speed(200);
1300 check_speed(300);
1301 check_speed(600);
1302 check_speed(1200);
1303 check_speed(1800);
1304 check_speed(2400);
1305 check_speed(4800);
1306 check_speed(9600);
1307 check_speed(19200);
1308 check_speed(38400);
1309 /* Non-Posix values follow. They may be unsupported on some systems. */
1310 check_speed(57600);
1311 check_speed(115200);
1312 #ifdef B230400
1313 check_speed(230400);
1314 #endif
1315 #ifdef B460800
1316 check_speed(460800);
1317 #endif
1318 #ifdef B500000
1319 check_speed(500000);
1320 #endif
1321 #ifdef B576000
1322 check_speed(576000);
1323 #endif
1324 #ifdef B921600
1325 check_speed(921600);
1326 #endif
1327 #ifdef B1000000
1328 check_speed(1000000);
1329 #endif
1330 #ifdef B1152000
1331 check_speed(1152000);
1332 #endif
1333 #ifdef B1500000
1334 check_speed(1500000);
1335 #endif
1336 #ifdef B2000000
1337 check_speed(2000000);
1338 #endif
1339 #ifdef B2500000
1340 check_speed(2500000);
1341 #endif
1342 #ifdef B3000000
1343 check_speed(3000000);
1344 #endif
1345 #ifdef B3500000
1346 check_speed(3500000);
1347 #endif
1348 #ifdef B4000000
1349 check_speed(4000000);
1350 #endif
1351 spd = B115200;
1352 } while (0);
1354 cfsetispeed(&tty, spd);
1355 cfsetospeed(&tty, spd);
1357 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1358 |INLCR|IGNCR|ICRNL|IXON);
1359 tty.c_oflag |= OPOST;
1360 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1361 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1362 switch(data_bits) {
1363 default:
1364 case 8:
1365 tty.c_cflag |= CS8;
1366 break;
1367 case 7:
1368 tty.c_cflag |= CS7;
1369 break;
1370 case 6:
1371 tty.c_cflag |= CS6;
1372 break;
1373 case 5:
1374 tty.c_cflag |= CS5;
1375 break;
1377 switch(parity) {
1378 default:
1379 case 'N':
1380 break;
1381 case 'E':
1382 tty.c_cflag |= PARENB;
1383 break;
1384 case 'O':
1385 tty.c_cflag |= PARENB | PARODD;
1386 break;
1388 if (stop_bits == 2)
1389 tty.c_cflag |= CSTOPB;
1391 tcsetattr (fd, TCSANOW, &tty);
1394 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1396 FDCharDriver *s = chr->opaque;
1398 switch(cmd) {
1399 case CHR_IOCTL_SERIAL_SET_PARAMS:
1401 QEMUSerialSetParams *ssp = arg;
1402 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1403 ssp->speed, ssp->parity,
1404 ssp->data_bits, ssp->stop_bits);
1406 break;
1407 case CHR_IOCTL_SERIAL_SET_BREAK:
1409 int enable = *(int *)arg;
1410 if (enable) {
1411 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1414 break;
1415 case CHR_IOCTL_SERIAL_GET_TIOCM:
1417 int sarg = 0;
1418 int *targ = (int *)arg;
1419 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1420 *targ = 0;
1421 if (sarg & TIOCM_CTS)
1422 *targ |= CHR_TIOCM_CTS;
1423 if (sarg & TIOCM_CAR)
1424 *targ |= CHR_TIOCM_CAR;
1425 if (sarg & TIOCM_DSR)
1426 *targ |= CHR_TIOCM_DSR;
1427 if (sarg & TIOCM_RI)
1428 *targ |= CHR_TIOCM_RI;
1429 if (sarg & TIOCM_DTR)
1430 *targ |= CHR_TIOCM_DTR;
1431 if (sarg & TIOCM_RTS)
1432 *targ |= CHR_TIOCM_RTS;
1434 break;
1435 case CHR_IOCTL_SERIAL_SET_TIOCM:
1437 int sarg = *(int *)arg;
1438 int targ = 0;
1439 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1440 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1441 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1442 if (sarg & CHR_TIOCM_CTS)
1443 targ |= TIOCM_CTS;
1444 if (sarg & CHR_TIOCM_CAR)
1445 targ |= TIOCM_CAR;
1446 if (sarg & CHR_TIOCM_DSR)
1447 targ |= TIOCM_DSR;
1448 if (sarg & CHR_TIOCM_RI)
1449 targ |= TIOCM_RI;
1450 if (sarg & CHR_TIOCM_DTR)
1451 targ |= TIOCM_DTR;
1452 if (sarg & CHR_TIOCM_RTS)
1453 targ |= TIOCM_RTS;
1454 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1456 break;
1457 default:
1458 return -ENOTSUP;
1460 return 0;
1463 static void qemu_chr_close_tty(CharDriverState *chr)
1465 FDCharDriver *s = chr->opaque;
1466 int fd = -1;
1468 if (s) {
1469 fd = g_io_channel_unix_get_fd(s->fd_in);
1472 fd_chr_close(chr);
1474 if (fd >= 0) {
1475 close(fd);
1479 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1481 CharDriverState *chr;
1483 tty_serial_init(fd, 115200, 'N', 8, 1);
1484 chr = qemu_chr_open_fd(fd, fd);
1485 chr->chr_ioctl = tty_serial_ioctl;
1486 chr->chr_close = qemu_chr_close_tty;
1487 return chr;
1489 #endif /* __linux__ || __sun__ */
1491 #if defined(__linux__)
1493 #define HAVE_CHARDEV_PARPORT 1
1495 typedef struct {
1496 int fd;
1497 int mode;
1498 } ParallelCharDriver;
1500 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1502 if (s->mode != mode) {
1503 int m = mode;
1504 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1505 return 0;
1506 s->mode = mode;
1508 return 1;
1511 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1513 ParallelCharDriver *drv = chr->opaque;
1514 int fd = drv->fd;
1515 uint8_t b;
1517 switch(cmd) {
1518 case CHR_IOCTL_PP_READ_DATA:
1519 if (ioctl(fd, PPRDATA, &b) < 0)
1520 return -ENOTSUP;
1521 *(uint8_t *)arg = b;
1522 break;
1523 case CHR_IOCTL_PP_WRITE_DATA:
1524 b = *(uint8_t *)arg;
1525 if (ioctl(fd, PPWDATA, &b) < 0)
1526 return -ENOTSUP;
1527 break;
1528 case CHR_IOCTL_PP_READ_CONTROL:
1529 if (ioctl(fd, PPRCONTROL, &b) < 0)
1530 return -ENOTSUP;
1531 /* Linux gives only the lowest bits, and no way to know data
1532 direction! For better compatibility set the fixed upper
1533 bits. */
1534 *(uint8_t *)arg = b | 0xc0;
1535 break;
1536 case CHR_IOCTL_PP_WRITE_CONTROL:
1537 b = *(uint8_t *)arg;
1538 if (ioctl(fd, PPWCONTROL, &b) < 0)
1539 return -ENOTSUP;
1540 break;
1541 case CHR_IOCTL_PP_READ_STATUS:
1542 if (ioctl(fd, PPRSTATUS, &b) < 0)
1543 return -ENOTSUP;
1544 *(uint8_t *)arg = b;
1545 break;
1546 case CHR_IOCTL_PP_DATA_DIR:
1547 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1548 return -ENOTSUP;
1549 break;
1550 case CHR_IOCTL_PP_EPP_READ_ADDR:
1551 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1552 struct ParallelIOArg *parg = arg;
1553 int n = read(fd, parg->buffer, parg->count);
1554 if (n != parg->count) {
1555 return -EIO;
1558 break;
1559 case CHR_IOCTL_PP_EPP_READ:
1560 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1561 struct ParallelIOArg *parg = arg;
1562 int n = read(fd, parg->buffer, parg->count);
1563 if (n != parg->count) {
1564 return -EIO;
1567 break;
1568 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1569 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1570 struct ParallelIOArg *parg = arg;
1571 int n = write(fd, parg->buffer, parg->count);
1572 if (n != parg->count) {
1573 return -EIO;
1576 break;
1577 case CHR_IOCTL_PP_EPP_WRITE:
1578 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1579 struct ParallelIOArg *parg = arg;
1580 int n = write(fd, parg->buffer, parg->count);
1581 if (n != parg->count) {
1582 return -EIO;
1585 break;
1586 default:
1587 return -ENOTSUP;
1589 return 0;
1592 static void pp_close(CharDriverState *chr)
1594 ParallelCharDriver *drv = chr->opaque;
1595 int fd = drv->fd;
1597 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1598 ioctl(fd, PPRELEASE);
1599 close(fd);
1600 g_free(drv);
1601 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1604 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1606 CharDriverState *chr;
1607 ParallelCharDriver *drv;
1609 if (ioctl(fd, PPCLAIM) < 0) {
1610 close(fd);
1611 return NULL;
1614 drv = g_malloc0(sizeof(ParallelCharDriver));
1615 drv->fd = fd;
1616 drv->mode = IEEE1284_MODE_COMPAT;
1618 chr = qemu_chr_alloc();
1619 chr->chr_write = null_chr_write;
1620 chr->chr_ioctl = pp_ioctl;
1621 chr->chr_close = pp_close;
1622 chr->opaque = drv;
1624 return chr;
1626 #endif /* __linux__ */
1628 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1630 #define HAVE_CHARDEV_PARPORT 1
1632 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1634 int fd = (int)(intptr_t)chr->opaque;
1635 uint8_t b;
1637 switch(cmd) {
1638 case CHR_IOCTL_PP_READ_DATA:
1639 if (ioctl(fd, PPIGDATA, &b) < 0)
1640 return -ENOTSUP;
1641 *(uint8_t *)arg = b;
1642 break;
1643 case CHR_IOCTL_PP_WRITE_DATA:
1644 b = *(uint8_t *)arg;
1645 if (ioctl(fd, PPISDATA, &b) < 0)
1646 return -ENOTSUP;
1647 break;
1648 case CHR_IOCTL_PP_READ_CONTROL:
1649 if (ioctl(fd, PPIGCTRL, &b) < 0)
1650 return -ENOTSUP;
1651 *(uint8_t *)arg = b;
1652 break;
1653 case CHR_IOCTL_PP_WRITE_CONTROL:
1654 b = *(uint8_t *)arg;
1655 if (ioctl(fd, PPISCTRL, &b) < 0)
1656 return -ENOTSUP;
1657 break;
1658 case CHR_IOCTL_PP_READ_STATUS:
1659 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1660 return -ENOTSUP;
1661 *(uint8_t *)arg = b;
1662 break;
1663 default:
1664 return -ENOTSUP;
1666 return 0;
1669 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1671 CharDriverState *chr;
1673 chr = qemu_chr_alloc();
1674 chr->opaque = (void *)(intptr_t)fd;
1675 chr->chr_write = null_chr_write;
1676 chr->chr_ioctl = pp_ioctl;
1677 chr->explicit_be_open = true;
1678 return chr;
1680 #endif
1682 #else /* _WIN32 */
1684 typedef struct {
1685 int max_size;
1686 HANDLE hcom, hrecv, hsend;
1687 OVERLAPPED orecv;
1688 BOOL fpipe;
1689 DWORD len;
1691 /* Protected by the CharDriverState chr_write_lock. */
1692 OVERLAPPED osend;
1693 } WinCharState;
1695 typedef struct {
1696 HANDLE hStdIn;
1697 HANDLE hInputReadyEvent;
1698 HANDLE hInputDoneEvent;
1699 HANDLE hInputThread;
1700 uint8_t win_stdio_buf;
1701 } WinStdioCharState;
1703 #define NSENDBUF 2048
1704 #define NRECVBUF 2048
1705 #define MAXCONNECT 1
1706 #define NTIMEOUT 5000
1708 static int win_chr_poll(void *opaque);
1709 static int win_chr_pipe_poll(void *opaque);
1711 static void win_chr_close(CharDriverState *chr)
1713 WinCharState *s = chr->opaque;
1715 if (s->hsend) {
1716 CloseHandle(s->hsend);
1717 s->hsend = NULL;
1719 if (s->hrecv) {
1720 CloseHandle(s->hrecv);
1721 s->hrecv = NULL;
1723 if (s->hcom) {
1724 CloseHandle(s->hcom);
1725 s->hcom = NULL;
1727 if (s->fpipe)
1728 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1729 else
1730 qemu_del_polling_cb(win_chr_poll, chr);
1732 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1735 static int win_chr_init(CharDriverState *chr, const char *filename)
1737 WinCharState *s = chr->opaque;
1738 COMMCONFIG comcfg;
1739 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1740 COMSTAT comstat;
1741 DWORD size;
1742 DWORD err;
1744 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1745 if (!s->hsend) {
1746 fprintf(stderr, "Failed CreateEvent\n");
1747 goto fail;
1749 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1750 if (!s->hrecv) {
1751 fprintf(stderr, "Failed CreateEvent\n");
1752 goto fail;
1755 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1756 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1757 if (s->hcom == INVALID_HANDLE_VALUE) {
1758 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1759 s->hcom = NULL;
1760 goto fail;
1763 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1764 fprintf(stderr, "Failed SetupComm\n");
1765 goto fail;
1768 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1769 size = sizeof(COMMCONFIG);
1770 GetDefaultCommConfig(filename, &comcfg, &size);
1771 comcfg.dcb.DCBlength = sizeof(DCB);
1772 CommConfigDialog(filename, NULL, &comcfg);
1774 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1775 fprintf(stderr, "Failed SetCommState\n");
1776 goto fail;
1779 if (!SetCommMask(s->hcom, EV_ERR)) {
1780 fprintf(stderr, "Failed SetCommMask\n");
1781 goto fail;
1784 cto.ReadIntervalTimeout = MAXDWORD;
1785 if (!SetCommTimeouts(s->hcom, &cto)) {
1786 fprintf(stderr, "Failed SetCommTimeouts\n");
1787 goto fail;
1790 if (!ClearCommError(s->hcom, &err, &comstat)) {
1791 fprintf(stderr, "Failed ClearCommError\n");
1792 goto fail;
1794 qemu_add_polling_cb(win_chr_poll, chr);
1795 return 0;
1797 fail:
1798 win_chr_close(chr);
1799 return -1;
1802 /* Called with chr_write_lock held. */
1803 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1805 WinCharState *s = chr->opaque;
1806 DWORD len, ret, size, err;
1808 len = len1;
1809 ZeroMemory(&s->osend, sizeof(s->osend));
1810 s->osend.hEvent = s->hsend;
1811 while (len > 0) {
1812 if (s->hsend)
1813 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1814 else
1815 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1816 if (!ret) {
1817 err = GetLastError();
1818 if (err == ERROR_IO_PENDING) {
1819 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1820 if (ret) {
1821 buf += size;
1822 len -= size;
1823 } else {
1824 break;
1826 } else {
1827 break;
1829 } else {
1830 buf += size;
1831 len -= size;
1834 return len1 - len;
1837 static int win_chr_read_poll(CharDriverState *chr)
1839 WinCharState *s = chr->opaque;
1841 s->max_size = qemu_chr_be_can_write(chr);
1842 return s->max_size;
1845 static void win_chr_readfile(CharDriverState *chr)
1847 WinCharState *s = chr->opaque;
1848 int ret, err;
1849 uint8_t buf[READ_BUF_LEN];
1850 DWORD size;
1852 ZeroMemory(&s->orecv, sizeof(s->orecv));
1853 s->orecv.hEvent = s->hrecv;
1854 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1855 if (!ret) {
1856 err = GetLastError();
1857 if (err == ERROR_IO_PENDING) {
1858 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1862 if (size > 0) {
1863 qemu_chr_be_write(chr, buf, size);
1867 static void win_chr_read(CharDriverState *chr)
1869 WinCharState *s = chr->opaque;
1871 if (s->len > s->max_size)
1872 s->len = s->max_size;
1873 if (s->len == 0)
1874 return;
1876 win_chr_readfile(chr);
1879 static int win_chr_poll(void *opaque)
1881 CharDriverState *chr = opaque;
1882 WinCharState *s = chr->opaque;
1883 COMSTAT status;
1884 DWORD comerr;
1886 ClearCommError(s->hcom, &comerr, &status);
1887 if (status.cbInQue > 0) {
1888 s->len = status.cbInQue;
1889 win_chr_read_poll(chr);
1890 win_chr_read(chr);
1891 return 1;
1893 return 0;
1896 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1898 CharDriverState *chr;
1899 WinCharState *s;
1901 chr = qemu_chr_alloc();
1902 s = g_malloc0(sizeof(WinCharState));
1903 chr->opaque = s;
1904 chr->chr_write = win_chr_write;
1905 chr->chr_close = win_chr_close;
1907 if (win_chr_init(chr, filename) < 0) {
1908 g_free(s);
1909 g_free(chr);
1910 return NULL;
1912 return chr;
1915 static int win_chr_pipe_poll(void *opaque)
1917 CharDriverState *chr = opaque;
1918 WinCharState *s = chr->opaque;
1919 DWORD size;
1921 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1922 if (size > 0) {
1923 s->len = size;
1924 win_chr_read_poll(chr);
1925 win_chr_read(chr);
1926 return 1;
1928 return 0;
1931 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1933 WinCharState *s = chr->opaque;
1934 OVERLAPPED ov;
1935 int ret;
1936 DWORD size;
1937 char openname[256];
1939 s->fpipe = TRUE;
1941 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1942 if (!s->hsend) {
1943 fprintf(stderr, "Failed CreateEvent\n");
1944 goto fail;
1946 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1947 if (!s->hrecv) {
1948 fprintf(stderr, "Failed CreateEvent\n");
1949 goto fail;
1952 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1953 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1954 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1955 PIPE_WAIT,
1956 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1957 if (s->hcom == INVALID_HANDLE_VALUE) {
1958 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1959 s->hcom = NULL;
1960 goto fail;
1963 ZeroMemory(&ov, sizeof(ov));
1964 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1965 ret = ConnectNamedPipe(s->hcom, &ov);
1966 if (ret) {
1967 fprintf(stderr, "Failed ConnectNamedPipe\n");
1968 goto fail;
1971 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1972 if (!ret) {
1973 fprintf(stderr, "Failed GetOverlappedResult\n");
1974 if (ov.hEvent) {
1975 CloseHandle(ov.hEvent);
1976 ov.hEvent = NULL;
1978 goto fail;
1981 if (ov.hEvent) {
1982 CloseHandle(ov.hEvent);
1983 ov.hEvent = NULL;
1985 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1986 return 0;
1988 fail:
1989 win_chr_close(chr);
1990 return -1;
1994 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
1996 const char *filename = opts->device;
1997 CharDriverState *chr;
1998 WinCharState *s;
2000 chr = qemu_chr_alloc();
2001 s = g_malloc0(sizeof(WinCharState));
2002 chr->opaque = s;
2003 chr->chr_write = win_chr_write;
2004 chr->chr_close = win_chr_close;
2006 if (win_chr_pipe_init(chr, filename) < 0) {
2007 g_free(s);
2008 g_free(chr);
2009 return NULL;
2011 return chr;
2014 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2016 CharDriverState *chr;
2017 WinCharState *s;
2019 chr = qemu_chr_alloc();
2020 s = g_malloc0(sizeof(WinCharState));
2021 s->hcom = fd_out;
2022 chr->opaque = s;
2023 chr->chr_write = win_chr_write;
2024 return chr;
2027 static CharDriverState *qemu_chr_open_win_con(void)
2029 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2032 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2034 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2035 DWORD dwSize;
2036 int len1;
2038 len1 = len;
2040 while (len1 > 0) {
2041 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2042 break;
2044 buf += dwSize;
2045 len1 -= dwSize;
2048 return len - len1;
2051 static void win_stdio_wait_func(void *opaque)
2053 CharDriverState *chr = opaque;
2054 WinStdioCharState *stdio = chr->opaque;
2055 INPUT_RECORD buf[4];
2056 int ret;
2057 DWORD dwSize;
2058 int i;
2060 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2062 if (!ret) {
2063 /* Avoid error storm */
2064 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2065 return;
2068 for (i = 0; i < dwSize; i++) {
2069 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2071 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2072 int j;
2073 if (kev->uChar.AsciiChar != 0) {
2074 for (j = 0; j < kev->wRepeatCount; j++) {
2075 if (qemu_chr_be_can_write(chr)) {
2076 uint8_t c = kev->uChar.AsciiChar;
2077 qemu_chr_be_write(chr, &c, 1);
2085 static DWORD WINAPI win_stdio_thread(LPVOID param)
2087 CharDriverState *chr = param;
2088 WinStdioCharState *stdio = chr->opaque;
2089 int ret;
2090 DWORD dwSize;
2092 while (1) {
2094 /* Wait for one byte */
2095 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2097 /* Exit in case of error, continue if nothing read */
2098 if (!ret) {
2099 break;
2101 if (!dwSize) {
2102 continue;
2105 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2106 if (stdio->win_stdio_buf == '\r') {
2107 continue;
2110 /* Signal the main thread and wait until the byte was eaten */
2111 if (!SetEvent(stdio->hInputReadyEvent)) {
2112 break;
2114 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2115 != WAIT_OBJECT_0) {
2116 break;
2120 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2121 return 0;
2124 static void win_stdio_thread_wait_func(void *opaque)
2126 CharDriverState *chr = opaque;
2127 WinStdioCharState *stdio = chr->opaque;
2129 if (qemu_chr_be_can_write(chr)) {
2130 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2133 SetEvent(stdio->hInputDoneEvent);
2136 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2138 WinStdioCharState *stdio = chr->opaque;
2139 DWORD dwMode = 0;
2141 GetConsoleMode(stdio->hStdIn, &dwMode);
2143 if (echo) {
2144 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2145 } else {
2146 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2150 static void win_stdio_close(CharDriverState *chr)
2152 WinStdioCharState *stdio = chr->opaque;
2154 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2155 CloseHandle(stdio->hInputReadyEvent);
2157 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2158 CloseHandle(stdio->hInputDoneEvent);
2160 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2161 TerminateThread(stdio->hInputThread, 0);
2164 g_free(chr->opaque);
2165 g_free(chr);
2168 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2170 CharDriverState *chr;
2171 WinStdioCharState *stdio;
2172 DWORD dwMode;
2173 int is_console = 0;
2175 chr = qemu_chr_alloc();
2176 stdio = g_malloc0(sizeof(WinStdioCharState));
2178 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2179 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2180 fprintf(stderr, "cannot open stdio: invalid handle\n");
2181 exit(1);
2184 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2186 chr->opaque = stdio;
2187 chr->chr_write = win_stdio_write;
2188 chr->chr_close = win_stdio_close;
2190 if (is_console) {
2191 if (qemu_add_wait_object(stdio->hStdIn,
2192 win_stdio_wait_func, chr)) {
2193 fprintf(stderr, "qemu_add_wait_object: failed\n");
2195 } else {
2196 DWORD dwId;
2198 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2199 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2200 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2201 chr, 0, &dwId);
2203 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2204 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2205 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2206 fprintf(stderr, "cannot create stdio thread or event\n");
2207 exit(1);
2209 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2210 win_stdio_thread_wait_func, chr)) {
2211 fprintf(stderr, "qemu_add_wait_object: failed\n");
2215 dwMode |= ENABLE_LINE_INPUT;
2217 if (is_console) {
2218 /* set the terminal in raw mode */
2219 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2220 dwMode |= ENABLE_PROCESSED_INPUT;
2223 SetConsoleMode(stdio->hStdIn, dwMode);
2225 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2226 qemu_chr_fe_set_echo(chr, false);
2228 return chr;
2230 #endif /* !_WIN32 */
2233 /***********************************************************/
2234 /* UDP Net console */
2236 typedef struct {
2237 int fd;
2238 GIOChannel *chan;
2239 uint8_t buf[READ_BUF_LEN];
2240 int bufcnt;
2241 int bufptr;
2242 int max_size;
2243 } NetCharDriver;
2245 /* Called with chr_write_lock held. */
2246 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2248 NetCharDriver *s = chr->opaque;
2249 gsize bytes_written;
2250 GIOStatus status;
2252 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2253 if (status == G_IO_STATUS_EOF) {
2254 return 0;
2255 } else if (status != G_IO_STATUS_NORMAL) {
2256 return -1;
2259 return bytes_written;
2262 static int udp_chr_read_poll(void *opaque)
2264 CharDriverState *chr = opaque;
2265 NetCharDriver *s = chr->opaque;
2267 s->max_size = qemu_chr_be_can_write(chr);
2269 /* If there were any stray characters in the queue process them
2270 * first
2272 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2273 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2274 s->bufptr++;
2275 s->max_size = qemu_chr_be_can_write(chr);
2277 return s->max_size;
2280 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2282 CharDriverState *chr = opaque;
2283 NetCharDriver *s = chr->opaque;
2284 gsize bytes_read = 0;
2285 GIOStatus status;
2287 if (s->max_size == 0) {
2288 return TRUE;
2290 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2291 &bytes_read, NULL);
2292 s->bufcnt = bytes_read;
2293 s->bufptr = s->bufcnt;
2294 if (status != G_IO_STATUS_NORMAL) {
2295 remove_fd_in_watch(chr);
2296 return FALSE;
2299 s->bufptr = 0;
2300 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2301 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2302 s->bufptr++;
2303 s->max_size = qemu_chr_be_can_write(chr);
2306 return TRUE;
2309 static void udp_chr_update_read_handler(CharDriverState *chr)
2311 NetCharDriver *s = chr->opaque;
2313 remove_fd_in_watch(chr);
2314 if (s->chan) {
2315 chr->fd_in_tag = io_add_watch_poll(s->chan, udp_chr_read_poll,
2316 udp_chr_read, chr);
2320 static void udp_chr_close(CharDriverState *chr)
2322 NetCharDriver *s = chr->opaque;
2324 remove_fd_in_watch(chr);
2325 if (s->chan) {
2326 g_io_channel_unref(s->chan);
2327 closesocket(s->fd);
2329 g_free(s);
2330 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2333 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2335 CharDriverState *chr = NULL;
2336 NetCharDriver *s = NULL;
2338 chr = qemu_chr_alloc();
2339 s = g_malloc0(sizeof(NetCharDriver));
2341 s->fd = fd;
2342 s->chan = io_channel_from_socket(s->fd);
2343 s->bufcnt = 0;
2344 s->bufptr = 0;
2345 chr->opaque = s;
2346 chr->chr_write = udp_chr_write;
2347 chr->chr_update_read_handler = udp_chr_update_read_handler;
2348 chr->chr_close = udp_chr_close;
2349 /* be isn't opened until we get a connection */
2350 chr->explicit_be_open = true;
2351 return chr;
2354 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2356 Error *local_err = NULL;
2357 int fd = -1;
2359 fd = inet_dgram_opts(opts, &local_err);
2360 if (fd < 0) {
2361 qerror_report_err(local_err);
2362 error_free(local_err);
2363 return NULL;
2365 return qemu_chr_open_udp_fd(fd);
2368 /***********************************************************/
2369 /* TCP Net console */
2371 typedef struct {
2373 GIOChannel *chan, *listen_chan;
2374 guint listen_tag;
2375 int fd, listen_fd;
2376 int connected;
2377 int max_size;
2378 int do_telnetopt;
2379 int do_nodelay;
2380 int is_unix;
2381 int *read_msgfds;
2382 int read_msgfds_num;
2383 int *write_msgfds;
2384 int write_msgfds_num;
2385 } TCPCharDriver;
2387 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2389 #ifndef _WIN32
2390 static int unix_send_msgfds(CharDriverState *chr, const uint8_t *buf, int len)
2392 TCPCharDriver *s = chr->opaque;
2393 struct msghdr msgh;
2394 struct iovec iov;
2395 int r;
2397 size_t fd_size = s->write_msgfds_num * sizeof(int);
2398 char control[CMSG_SPACE(fd_size)];
2399 struct cmsghdr *cmsg;
2401 memset(&msgh, 0, sizeof(msgh));
2402 memset(control, 0, sizeof(control));
2404 /* set the payload */
2405 iov.iov_base = (uint8_t *) buf;
2406 iov.iov_len = len;
2408 msgh.msg_iov = &iov;
2409 msgh.msg_iovlen = 1;
2411 msgh.msg_control = control;
2412 msgh.msg_controllen = sizeof(control);
2414 cmsg = CMSG_FIRSTHDR(&msgh);
2416 cmsg->cmsg_len = CMSG_LEN(fd_size);
2417 cmsg->cmsg_level = SOL_SOCKET;
2418 cmsg->cmsg_type = SCM_RIGHTS;
2419 memcpy(CMSG_DATA(cmsg), s->write_msgfds, fd_size);
2421 do {
2422 r = sendmsg(s->fd, &msgh, 0);
2423 } while (r < 0 && errno == EINTR);
2425 /* free the written msgfds, no matter what */
2426 if (s->write_msgfds_num) {
2427 g_free(s->write_msgfds);
2428 s->write_msgfds = 0;
2429 s->write_msgfds_num = 0;
2432 return r;
2434 #endif
2436 /* Called with chr_write_lock held. */
2437 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2439 TCPCharDriver *s = chr->opaque;
2440 if (s->connected) {
2441 #ifndef _WIN32
2442 if (s->is_unix && s->write_msgfds_num) {
2443 return unix_send_msgfds(chr, buf, len);
2444 } else
2445 #endif
2447 return io_channel_send(s->chan, buf, len);
2449 } else {
2450 /* XXX: indicate an error ? */
2451 return len;
2455 static int tcp_chr_read_poll(void *opaque)
2457 CharDriverState *chr = opaque;
2458 TCPCharDriver *s = chr->opaque;
2459 if (!s->connected)
2460 return 0;
2461 s->max_size = qemu_chr_be_can_write(chr);
2462 return s->max_size;
2465 #define IAC 255
2466 #define IAC_BREAK 243
2467 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2468 TCPCharDriver *s,
2469 uint8_t *buf, int *size)
2471 /* Handle any telnet client's basic IAC options to satisfy char by
2472 * char mode with no echo. All IAC options will be removed from
2473 * the buf and the do_telnetopt variable will be used to track the
2474 * state of the width of the IAC information.
2476 * IAC commands come in sets of 3 bytes with the exception of the
2477 * "IAC BREAK" command and the double IAC.
2480 int i;
2481 int j = 0;
2483 for (i = 0; i < *size; i++) {
2484 if (s->do_telnetopt > 1) {
2485 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2486 /* Double IAC means send an IAC */
2487 if (j != i)
2488 buf[j] = buf[i];
2489 j++;
2490 s->do_telnetopt = 1;
2491 } else {
2492 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2493 /* Handle IAC break commands by sending a serial break */
2494 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2495 s->do_telnetopt++;
2497 s->do_telnetopt++;
2499 if (s->do_telnetopt >= 4) {
2500 s->do_telnetopt = 1;
2502 } else {
2503 if ((unsigned char)buf[i] == IAC) {
2504 s->do_telnetopt = 2;
2505 } else {
2506 if (j != i)
2507 buf[j] = buf[i];
2508 j++;
2512 *size = j;
2515 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2517 TCPCharDriver *s = chr->opaque;
2518 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2520 if (to_copy) {
2521 int i;
2523 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2525 /* Close unused fds */
2526 for (i = to_copy; i < s->read_msgfds_num; i++) {
2527 close(s->read_msgfds[i]);
2530 g_free(s->read_msgfds);
2531 s->read_msgfds = 0;
2532 s->read_msgfds_num = 0;
2535 return to_copy;
2538 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2540 TCPCharDriver *s = chr->opaque;
2542 /* clear old pending fd array */
2543 if (s->write_msgfds) {
2544 g_free(s->write_msgfds);
2547 if (num) {
2548 s->write_msgfds = g_malloc(num * sizeof(int));
2549 memcpy(s->write_msgfds, fds, num * sizeof(int));
2552 s->write_msgfds_num = num;
2554 return 0;
2557 #ifndef _WIN32
2558 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2560 TCPCharDriver *s = chr->opaque;
2561 struct cmsghdr *cmsg;
2563 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2564 int fd_size, i;
2566 if (cmsg->cmsg_len < CMSG_LEN(sizeof(int)) ||
2567 cmsg->cmsg_level != SOL_SOCKET ||
2568 cmsg->cmsg_type != SCM_RIGHTS) {
2569 continue;
2572 fd_size = cmsg->cmsg_len - CMSG_LEN(0);
2574 if (!fd_size) {
2575 continue;
2578 /* close and clean read_msgfds */
2579 for (i = 0; i < s->read_msgfds_num; i++) {
2580 close(s->read_msgfds[i]);
2583 if (s->read_msgfds_num) {
2584 g_free(s->read_msgfds);
2587 s->read_msgfds_num = fd_size / sizeof(int);
2588 s->read_msgfds = g_malloc(fd_size);
2589 memcpy(s->read_msgfds, CMSG_DATA(cmsg), fd_size);
2591 for (i = 0; i < s->read_msgfds_num; i++) {
2592 int fd = s->read_msgfds[i];
2593 if (fd < 0) {
2594 continue;
2597 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2598 qemu_set_block(fd);
2600 #ifndef MSG_CMSG_CLOEXEC
2601 qemu_set_cloexec(fd);
2602 #endif
2607 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2609 TCPCharDriver *s = chr->opaque;
2610 struct msghdr msg = { NULL, };
2611 struct iovec iov[1];
2612 union {
2613 struct cmsghdr cmsg;
2614 char control[CMSG_SPACE(sizeof(int))];
2615 } msg_control;
2616 int flags = 0;
2617 ssize_t ret;
2619 iov[0].iov_base = buf;
2620 iov[0].iov_len = len;
2622 msg.msg_iov = iov;
2623 msg.msg_iovlen = 1;
2624 msg.msg_control = &msg_control;
2625 msg.msg_controllen = sizeof(msg_control);
2627 #ifdef MSG_CMSG_CLOEXEC
2628 flags |= MSG_CMSG_CLOEXEC;
2629 #endif
2630 ret = recvmsg(s->fd, &msg, flags);
2631 if (ret > 0 && s->is_unix) {
2632 unix_process_msgfd(chr, &msg);
2635 return ret;
2637 #else
2638 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2640 TCPCharDriver *s = chr->opaque;
2641 return qemu_recv(s->fd, buf, len, 0);
2643 #endif
2645 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2647 TCPCharDriver *s = chr->opaque;
2648 return g_io_create_watch(s->chan, cond);
2651 static void tcp_chr_disconnect(CharDriverState *chr)
2653 TCPCharDriver *s = chr->opaque;
2655 s->connected = 0;
2656 if (s->listen_chan) {
2657 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
2658 tcp_chr_accept, chr);
2660 remove_fd_in_watch(chr);
2661 g_io_channel_unref(s->chan);
2662 s->chan = NULL;
2663 closesocket(s->fd);
2664 s->fd = -1;
2665 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2668 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2670 CharDriverState *chr = opaque;
2671 TCPCharDriver *s = chr->opaque;
2672 uint8_t buf[READ_BUF_LEN];
2673 int len, size;
2675 if (!s->connected || s->max_size <= 0) {
2676 return TRUE;
2678 len = sizeof(buf);
2679 if (len > s->max_size)
2680 len = s->max_size;
2681 size = tcp_chr_recv(chr, (void *)buf, len);
2682 if (size == 0) {
2683 /* connection closed */
2684 tcp_chr_disconnect(chr);
2685 } else if (size > 0) {
2686 if (s->do_telnetopt)
2687 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2688 if (size > 0)
2689 qemu_chr_be_write(chr, buf, size);
2692 return TRUE;
2695 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2697 TCPCharDriver *s = chr->opaque;
2698 int size;
2700 if (!s->connected) {
2701 return 0;
2704 size = tcp_chr_recv(chr, (void *) buf, len);
2705 if (size == 0) {
2706 /* connection closed */
2707 tcp_chr_disconnect(chr);
2710 return size;
2713 #ifndef _WIN32
2714 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2716 CharDriverState *chr = qemu_chr_open_fd(eventfd, eventfd);
2718 if (chr) {
2719 chr->avail_connections = 1;
2722 return chr;
2724 #endif
2726 static gboolean tcp_chr_chan_close(GIOChannel *channel, GIOCondition cond,
2727 void *opaque)
2729 CharDriverState *chr = opaque;
2731 if (cond != G_IO_HUP) {
2732 return FALSE;
2735 /* connection closed */
2736 tcp_chr_disconnect(chr);
2737 if (chr->fd_hup_tag) {
2738 g_source_remove(chr->fd_hup_tag);
2739 chr->fd_hup_tag = 0;
2742 return TRUE;
2745 static void tcp_chr_connect(void *opaque)
2747 CharDriverState *chr = opaque;
2748 TCPCharDriver *s = chr->opaque;
2750 s->connected = 1;
2751 if (s->chan) {
2752 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2753 tcp_chr_read, chr);
2754 chr->fd_hup_tag = g_io_add_watch(s->chan, G_IO_HUP, tcp_chr_chan_close,
2755 chr);
2757 qemu_chr_be_generic_open(chr);
2760 static void tcp_chr_update_read_handler(CharDriverState *chr)
2762 TCPCharDriver *s = chr->opaque;
2764 remove_fd_in_watch(chr);
2765 if (s->chan) {
2766 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2767 tcp_chr_read, chr);
2771 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2772 static void tcp_chr_telnet_init(int fd)
2774 char buf[3];
2775 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2776 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2777 send(fd, (char *)buf, 3, 0);
2778 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2779 send(fd, (char *)buf, 3, 0);
2780 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2781 send(fd, (char *)buf, 3, 0);
2782 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2783 send(fd, (char *)buf, 3, 0);
2786 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2788 TCPCharDriver *s = chr->opaque;
2789 if (s->fd != -1)
2790 return -1;
2792 qemu_set_nonblock(fd);
2793 if (s->do_nodelay)
2794 socket_set_nodelay(fd);
2795 s->fd = fd;
2796 s->chan = io_channel_from_socket(fd);
2797 if (s->listen_tag) {
2798 g_source_remove(s->listen_tag);
2799 s->listen_tag = 0;
2801 tcp_chr_connect(chr);
2803 return 0;
2806 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2808 CharDriverState *chr = opaque;
2809 TCPCharDriver *s = chr->opaque;
2810 struct sockaddr_in saddr;
2811 #ifndef _WIN32
2812 struct sockaddr_un uaddr;
2813 #endif
2814 struct sockaddr *addr;
2815 socklen_t len;
2816 int fd;
2818 for(;;) {
2819 #ifndef _WIN32
2820 if (s->is_unix) {
2821 len = sizeof(uaddr);
2822 addr = (struct sockaddr *)&uaddr;
2823 } else
2824 #endif
2826 len = sizeof(saddr);
2827 addr = (struct sockaddr *)&saddr;
2829 fd = qemu_accept(s->listen_fd, addr, &len);
2830 if (fd < 0 && errno != EINTR) {
2831 s->listen_tag = 0;
2832 return FALSE;
2833 } else if (fd >= 0) {
2834 if (s->do_telnetopt)
2835 tcp_chr_telnet_init(fd);
2836 break;
2839 if (tcp_chr_add_client(chr, fd) < 0)
2840 close(fd);
2842 return TRUE;
2845 static void tcp_chr_close(CharDriverState *chr)
2847 TCPCharDriver *s = chr->opaque;
2848 int i;
2849 if (s->fd >= 0) {
2850 remove_fd_in_watch(chr);
2851 if (s->chan) {
2852 g_io_channel_unref(s->chan);
2854 closesocket(s->fd);
2856 if (s->listen_fd >= 0) {
2857 if (s->listen_tag) {
2858 g_source_remove(s->listen_tag);
2859 s->listen_tag = 0;
2861 if (s->listen_chan) {
2862 g_io_channel_unref(s->listen_chan);
2864 closesocket(s->listen_fd);
2866 if (s->read_msgfds_num) {
2867 for (i = 0; i < s->read_msgfds_num; i++) {
2868 close(s->read_msgfds[i]);
2870 g_free(s->read_msgfds);
2872 if (s->write_msgfds_num) {
2873 g_free(s->write_msgfds);
2875 g_free(s);
2876 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2879 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2880 bool is_listen, bool is_telnet,
2881 bool is_waitconnect,
2882 Error **errp)
2884 CharDriverState *chr = NULL;
2885 TCPCharDriver *s = NULL;
2886 char host[NI_MAXHOST], serv[NI_MAXSERV];
2887 const char *left = "", *right = "";
2888 struct sockaddr_storage ss;
2889 socklen_t ss_len = sizeof(ss);
2891 memset(&ss, 0, ss_len);
2892 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2893 error_setg_errno(errp, errno, "getsockname");
2894 return NULL;
2897 chr = qemu_chr_alloc();
2898 s = g_malloc0(sizeof(TCPCharDriver));
2900 s->connected = 0;
2901 s->fd = -1;
2902 s->listen_fd = -1;
2903 s->read_msgfds = 0;
2904 s->read_msgfds_num = 0;
2905 s->write_msgfds = 0;
2906 s->write_msgfds_num = 0;
2908 chr->filename = g_malloc(256);
2909 switch (ss.ss_family) {
2910 #ifndef _WIN32
2911 case AF_UNIX:
2912 s->is_unix = 1;
2913 snprintf(chr->filename, 256, "unix:%s%s",
2914 ((struct sockaddr_un *)(&ss))->sun_path,
2915 is_listen ? ",server" : "");
2916 break;
2917 #endif
2918 case AF_INET6:
2919 left = "[";
2920 right = "]";
2921 /* fall through */
2922 case AF_INET:
2923 s->do_nodelay = do_nodelay;
2924 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2925 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2926 snprintf(chr->filename, 256, "%s:%s%s%s:%s%s",
2927 is_telnet ? "telnet" : "tcp",
2928 left, host, right, serv,
2929 is_listen ? ",server" : "");
2930 break;
2933 chr->opaque = s;
2934 chr->chr_write = tcp_chr_write;
2935 chr->chr_sync_read = tcp_chr_sync_read;
2936 chr->chr_close = tcp_chr_close;
2937 chr->get_msgfds = tcp_get_msgfds;
2938 chr->set_msgfds = tcp_set_msgfds;
2939 chr->chr_add_client = tcp_chr_add_client;
2940 chr->chr_add_watch = tcp_chr_add_watch;
2941 chr->chr_update_read_handler = tcp_chr_update_read_handler;
2942 /* be isn't opened until we get a connection */
2943 chr->explicit_be_open = true;
2945 if (is_listen) {
2946 s->listen_fd = fd;
2947 s->listen_chan = io_channel_from_socket(s->listen_fd);
2948 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2949 if (is_telnet) {
2950 s->do_telnetopt = 1;
2952 } else {
2953 s->connected = 1;
2954 s->fd = fd;
2955 socket_set_nodelay(fd);
2956 s->chan = io_channel_from_socket(s->fd);
2957 tcp_chr_connect(chr);
2960 if (is_listen && is_waitconnect) {
2961 fprintf(stderr, "QEMU waiting for connection on: %s\n",
2962 chr->filename);
2963 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2964 qemu_set_nonblock(s->listen_fd);
2966 return chr;
2969 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2971 CharDriverState *chr = NULL;
2972 Error *local_err = NULL;
2973 int fd = -1;
2975 bool is_listen = qemu_opt_get_bool(opts, "server", false);
2976 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
2977 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
2978 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
2979 bool is_unix = qemu_opt_get(opts, "path") != NULL;
2981 if (is_unix) {
2982 if (is_listen) {
2983 fd = unix_listen_opts(opts, &local_err);
2984 } else {
2985 fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2987 } else {
2988 if (is_listen) {
2989 fd = inet_listen_opts(opts, 0, &local_err);
2990 } else {
2991 fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2994 if (fd < 0) {
2995 goto fail;
2998 if (!is_waitconnect)
2999 qemu_set_nonblock(fd);
3001 chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
3002 is_waitconnect, &local_err);
3003 if (local_err) {
3004 goto fail;
3006 return chr;
3009 fail:
3010 if (local_err) {
3011 qerror_report_err(local_err);
3012 error_free(local_err);
3014 if (fd >= 0) {
3015 closesocket(fd);
3017 if (chr) {
3018 g_free(chr->opaque);
3019 g_free(chr);
3021 return NULL;
3024 /*********************************************************/
3025 /* Ring buffer chardev */
3027 typedef struct {
3028 size_t size;
3029 size_t prod;
3030 size_t cons;
3031 uint8_t *cbuf;
3032 } RingBufCharDriver;
3034 static size_t ringbuf_count(const CharDriverState *chr)
3036 const RingBufCharDriver *d = chr->opaque;
3038 return d->prod - d->cons;
3041 /* Called with chr_write_lock held. */
3042 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3044 RingBufCharDriver *d = chr->opaque;
3045 int i;
3047 if (!buf || (len < 0)) {
3048 return -1;
3051 for (i = 0; i < len; i++ ) {
3052 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
3053 if (d->prod - d->cons > d->size) {
3054 d->cons = d->prod - d->size;
3058 return 0;
3061 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3063 RingBufCharDriver *d = chr->opaque;
3064 int i;
3066 qemu_mutex_lock(&chr->chr_write_lock);
3067 for (i = 0; i < len && d->cons != d->prod; i++) {
3068 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3070 qemu_mutex_unlock(&chr->chr_write_lock);
3072 return i;
3075 static void ringbuf_chr_close(struct CharDriverState *chr)
3077 RingBufCharDriver *d = chr->opaque;
3079 g_free(d->cbuf);
3080 g_free(d);
3081 chr->opaque = NULL;
3084 static CharDriverState *qemu_chr_open_ringbuf(ChardevRingbuf *opts,
3085 Error **errp)
3087 CharDriverState *chr;
3088 RingBufCharDriver *d;
3090 chr = qemu_chr_alloc();
3091 d = g_malloc(sizeof(*d));
3093 d->size = opts->has_size ? opts->size : 65536;
3095 /* The size must be power of 2 */
3096 if (d->size & (d->size - 1)) {
3097 error_setg(errp, "size of ringbuf chardev must be power of two");
3098 goto fail;
3101 d->prod = 0;
3102 d->cons = 0;
3103 d->cbuf = g_malloc0(d->size);
3105 chr->opaque = d;
3106 chr->chr_write = ringbuf_chr_write;
3107 chr->chr_close = ringbuf_chr_close;
3109 return chr;
3111 fail:
3112 g_free(d);
3113 g_free(chr);
3114 return NULL;
3117 bool chr_is_ringbuf(const CharDriverState *chr)
3119 return chr->chr_write == ringbuf_chr_write;
3122 void qmp_ringbuf_write(const char *device, const char *data,
3123 bool has_format, enum DataFormat format,
3124 Error **errp)
3126 CharDriverState *chr;
3127 const uint8_t *write_data;
3128 int ret;
3129 gsize write_count;
3131 chr = qemu_chr_find(device);
3132 if (!chr) {
3133 error_setg(errp, "Device '%s' not found", device);
3134 return;
3137 if (!chr_is_ringbuf(chr)) {
3138 error_setg(errp,"%s is not a ringbuf device", device);
3139 return;
3142 if (has_format && (format == DATA_FORMAT_BASE64)) {
3143 write_data = g_base64_decode(data, &write_count);
3144 } else {
3145 write_data = (uint8_t *)data;
3146 write_count = strlen(data);
3149 ret = ringbuf_chr_write(chr, write_data, write_count);
3151 if (write_data != (uint8_t *)data) {
3152 g_free((void *)write_data);
3155 if (ret < 0) {
3156 error_setg(errp, "Failed to write to device %s", device);
3157 return;
3161 char *qmp_ringbuf_read(const char *device, int64_t size,
3162 bool has_format, enum DataFormat format,
3163 Error **errp)
3165 CharDriverState *chr;
3166 uint8_t *read_data;
3167 size_t count;
3168 char *data;
3170 chr = qemu_chr_find(device);
3171 if (!chr) {
3172 error_setg(errp, "Device '%s' not found", device);
3173 return NULL;
3176 if (!chr_is_ringbuf(chr)) {
3177 error_setg(errp,"%s is not a ringbuf device", device);
3178 return NULL;
3181 if (size <= 0) {
3182 error_setg(errp, "size must be greater than zero");
3183 return NULL;
3186 count = ringbuf_count(chr);
3187 size = size > count ? count : size;
3188 read_data = g_malloc(size + 1);
3190 ringbuf_chr_read(chr, read_data, size);
3192 if (has_format && (format == DATA_FORMAT_BASE64)) {
3193 data = g_base64_encode(read_data, size);
3194 g_free(read_data);
3195 } else {
3197 * FIXME should read only complete, valid UTF-8 characters up
3198 * to @size bytes. Invalid sequences should be replaced by a
3199 * suitable replacement character. Except when (and only
3200 * when) ring buffer lost characters since last read, initial
3201 * continuation characters should be dropped.
3203 read_data[size] = 0;
3204 data = (char *)read_data;
3207 return data;
3210 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3212 char host[65], port[33], width[8], height[8];
3213 int pos;
3214 const char *p;
3215 QemuOpts *opts;
3216 Error *local_err = NULL;
3218 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3219 if (local_err) {
3220 qerror_report_err(local_err);
3221 error_free(local_err);
3222 return NULL;
3225 if (strstart(filename, "mon:", &p)) {
3226 filename = p;
3227 qemu_opt_set(opts, "mux", "on");
3228 if (strcmp(filename, "stdio") == 0) {
3229 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3230 * but pass it to the guest. Handle this only for compat syntax,
3231 * for -chardev syntax we have special option for this.
3232 * This is what -nographic did, redirecting+muxing serial+monitor
3233 * to stdio causing Ctrl+C to be passed to guest. */
3234 qemu_opt_set(opts, "signal", "off");
3238 if (strcmp(filename, "null") == 0 ||
3239 strcmp(filename, "pty") == 0 ||
3240 strcmp(filename, "msmouse") == 0 ||
3241 strcmp(filename, "braille") == 0 ||
3242 strcmp(filename, "stdio") == 0) {
3243 qemu_opt_set(opts, "backend", filename);
3244 return opts;
3246 if (strstart(filename, "vc", &p)) {
3247 qemu_opt_set(opts, "backend", "vc");
3248 if (*p == ':') {
3249 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3250 /* pixels */
3251 qemu_opt_set(opts, "width", width);
3252 qemu_opt_set(opts, "height", height);
3253 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3254 /* chars */
3255 qemu_opt_set(opts, "cols", width);
3256 qemu_opt_set(opts, "rows", height);
3257 } else {
3258 goto fail;
3261 return opts;
3263 if (strcmp(filename, "con:") == 0) {
3264 qemu_opt_set(opts, "backend", "console");
3265 return opts;
3267 if (strstart(filename, "COM", NULL)) {
3268 qemu_opt_set(opts, "backend", "serial");
3269 qemu_opt_set(opts, "path", filename);
3270 return opts;
3272 if (strstart(filename, "file:", &p)) {
3273 qemu_opt_set(opts, "backend", "file");
3274 qemu_opt_set(opts, "path", p);
3275 return opts;
3277 if (strstart(filename, "pipe:", &p)) {
3278 qemu_opt_set(opts, "backend", "pipe");
3279 qemu_opt_set(opts, "path", p);
3280 return opts;
3282 if (strstart(filename, "tcp:", &p) ||
3283 strstart(filename, "telnet:", &p)) {
3284 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3285 host[0] = 0;
3286 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3287 goto fail;
3289 qemu_opt_set(opts, "backend", "socket");
3290 qemu_opt_set(opts, "host", host);
3291 qemu_opt_set(opts, "port", port);
3292 if (p[pos] == ',') {
3293 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3294 goto fail;
3296 if (strstart(filename, "telnet:", &p))
3297 qemu_opt_set(opts, "telnet", "on");
3298 return opts;
3300 if (strstart(filename, "udp:", &p)) {
3301 qemu_opt_set(opts, "backend", "udp");
3302 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3303 host[0] = 0;
3304 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3305 goto fail;
3308 qemu_opt_set(opts, "host", host);
3309 qemu_opt_set(opts, "port", port);
3310 if (p[pos] == '@') {
3311 p += pos + 1;
3312 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3313 host[0] = 0;
3314 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3315 goto fail;
3318 qemu_opt_set(opts, "localaddr", host);
3319 qemu_opt_set(opts, "localport", port);
3321 return opts;
3323 if (strstart(filename, "unix:", &p)) {
3324 qemu_opt_set(opts, "backend", "socket");
3325 if (qemu_opts_do_parse(opts, p, "path") != 0)
3326 goto fail;
3327 return opts;
3329 if (strstart(filename, "/dev/parport", NULL) ||
3330 strstart(filename, "/dev/ppi", NULL)) {
3331 qemu_opt_set(opts, "backend", "parport");
3332 qemu_opt_set(opts, "path", filename);
3333 return opts;
3335 if (strstart(filename, "/dev/", NULL)) {
3336 qemu_opt_set(opts, "backend", "tty");
3337 qemu_opt_set(opts, "path", filename);
3338 return opts;
3341 fail:
3342 qemu_opts_del(opts);
3343 return NULL;
3346 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3347 Error **errp)
3349 const char *path = qemu_opt_get(opts, "path");
3351 if (path == NULL) {
3352 error_setg(errp, "chardev: file: no filename given");
3353 return;
3355 backend->file = g_new0(ChardevFile, 1);
3356 backend->file->out = g_strdup(path);
3359 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3360 Error **errp)
3362 backend->stdio = g_new0(ChardevStdio, 1);
3363 backend->stdio->has_signal = true;
3364 backend->stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3367 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3368 Error **errp)
3370 const char *device = qemu_opt_get(opts, "path");
3372 if (device == NULL) {
3373 error_setg(errp, "chardev: serial/tty: no device path given");
3374 return;
3376 backend->serial = g_new0(ChardevHostdev, 1);
3377 backend->serial->device = g_strdup(device);
3380 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3381 Error **errp)
3383 const char *device = qemu_opt_get(opts, "path");
3385 if (device == NULL) {
3386 error_setg(errp, "chardev: parallel: no device path given");
3387 return;
3389 backend->parallel = g_new0(ChardevHostdev, 1);
3390 backend->parallel->device = g_strdup(device);
3393 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3394 Error **errp)
3396 const char *device = qemu_opt_get(opts, "path");
3398 if (device == NULL) {
3399 error_setg(errp, "chardev: pipe: no device path given");
3400 return;
3402 backend->pipe = g_new0(ChardevHostdev, 1);
3403 backend->pipe->device = g_strdup(device);
3406 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3407 Error **errp)
3409 int val;
3411 backend->ringbuf = g_new0(ChardevRingbuf, 1);
3413 val = qemu_opt_get_size(opts, "size", 0);
3414 if (val != 0) {
3415 backend->ringbuf->has_size = true;
3416 backend->ringbuf->size = val;
3420 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3421 Error **errp)
3423 const char *chardev = qemu_opt_get(opts, "chardev");
3425 if (chardev == NULL) {
3426 error_setg(errp, "chardev: mux: no chardev given");
3427 return;
3429 backend->mux = g_new0(ChardevMux, 1);
3430 backend->mux->chardev = g_strdup(chardev);
3433 typedef struct CharDriver {
3434 const char *name;
3435 /* old, pre qapi */
3436 CharDriverState *(*open)(QemuOpts *opts);
3437 /* new, qapi-based */
3438 ChardevBackendKind kind;
3439 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3440 } CharDriver;
3442 static GSList *backends;
3444 void register_char_driver(const char *name, CharDriverState *(*open)(QemuOpts *))
3446 CharDriver *s;
3448 s = g_malloc0(sizeof(*s));
3449 s->name = g_strdup(name);
3450 s->open = open;
3452 backends = g_slist_append(backends, s);
3455 void register_char_driver_qapi(const char *name, ChardevBackendKind kind,
3456 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3458 CharDriver *s;
3460 s = g_malloc0(sizeof(*s));
3461 s->name = g_strdup(name);
3462 s->kind = kind;
3463 s->parse = parse;
3465 backends = g_slist_append(backends, s);
3468 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3469 void (*init)(struct CharDriverState *s),
3470 Error **errp)
3472 Error *local_err = NULL;
3473 CharDriver *cd;
3474 CharDriverState *chr;
3475 GSList *i;
3477 if (qemu_opts_id(opts) == NULL) {
3478 error_setg(errp, "chardev: no id specified");
3479 goto err;
3482 if (qemu_opt_get(opts, "backend") == NULL) {
3483 error_setg(errp, "chardev: \"%s\" missing backend",
3484 qemu_opts_id(opts));
3485 goto err;
3487 for (i = backends; i; i = i->next) {
3488 cd = i->data;
3490 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3491 break;
3494 if (i == NULL) {
3495 error_setg(errp, "chardev: backend \"%s\" not found",
3496 qemu_opt_get(opts, "backend"));
3497 goto err;
3500 if (!cd->open) {
3501 /* using new, qapi init */
3502 ChardevBackend *backend = g_new0(ChardevBackend, 1);
3503 ChardevReturn *ret = NULL;
3504 const char *id = qemu_opts_id(opts);
3505 char *bid = NULL;
3507 if (qemu_opt_get_bool(opts, "mux", 0)) {
3508 bid = g_strdup_printf("%s-base", id);
3511 chr = NULL;
3512 backend->kind = cd->kind;
3513 if (cd->parse) {
3514 cd->parse(opts, backend, &local_err);
3515 if (local_err) {
3516 error_propagate(errp, local_err);
3517 goto qapi_out;
3520 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3521 if (!ret) {
3522 goto qapi_out;
3525 if (bid) {
3526 qapi_free_ChardevBackend(backend);
3527 qapi_free_ChardevReturn(ret);
3528 backend = g_new0(ChardevBackend, 1);
3529 backend->mux = g_new0(ChardevMux, 1);
3530 backend->kind = CHARDEV_BACKEND_KIND_MUX;
3531 backend->mux->chardev = g_strdup(bid);
3532 ret = qmp_chardev_add(id, backend, errp);
3533 if (!ret) {
3534 chr = qemu_chr_find(bid);
3535 qemu_chr_delete(chr);
3536 chr = NULL;
3537 goto qapi_out;
3541 chr = qemu_chr_find(id);
3542 chr->opts = opts;
3544 qapi_out:
3545 qapi_free_ChardevBackend(backend);
3546 qapi_free_ChardevReturn(ret);
3547 g_free(bid);
3548 return chr;
3551 chr = cd->open(opts);
3552 if (!chr) {
3553 error_setg(errp, "chardev: opening backend \"%s\" failed",
3554 qemu_opt_get(opts, "backend"));
3555 goto err;
3558 if (!chr->filename)
3559 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3560 chr->init = init;
3561 /* if we didn't create the chardev via qmp_chardev_add, we
3562 * need to send the OPENED event here
3564 if (!chr->explicit_be_open) {
3565 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
3567 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3569 if (qemu_opt_get_bool(opts, "mux", 0)) {
3570 CharDriverState *base = chr;
3571 int len = strlen(qemu_opts_id(opts)) + 6;
3572 base->label = g_malloc(len);
3573 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3574 chr = qemu_chr_open_mux(base);
3575 chr->filename = base->filename;
3576 chr->avail_connections = MAX_MUX;
3577 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3578 } else {
3579 chr->avail_connections = 1;
3581 chr->label = g_strdup(qemu_opts_id(opts));
3582 chr->opts = opts;
3583 return chr;
3585 err:
3586 qemu_opts_del(opts);
3587 return NULL;
3590 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3592 const char *p;
3593 CharDriverState *chr;
3594 QemuOpts *opts;
3595 Error *err = NULL;
3597 if (strstart(filename, "chardev:", &p)) {
3598 return qemu_chr_find(p);
3601 opts = qemu_chr_parse_compat(label, filename);
3602 if (!opts)
3603 return NULL;
3605 chr = qemu_chr_new_from_opts(opts, init, &err);
3606 if (err) {
3607 error_report("%s", error_get_pretty(err));
3608 error_free(err);
3610 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3611 qemu_chr_fe_claim_no_fail(chr);
3612 monitor_init(chr, MONITOR_USE_READLINE);
3614 return chr;
3617 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3619 if (chr->chr_set_echo) {
3620 chr->chr_set_echo(chr, echo);
3624 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3626 if (chr->fe_open == fe_open) {
3627 return;
3629 chr->fe_open = fe_open;
3630 if (chr->chr_set_fe_open) {
3631 chr->chr_set_fe_open(chr, fe_open);
3635 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3637 if (chr->chr_fe_event) {
3638 chr->chr_fe_event(chr, event);
3642 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3643 GIOFunc func, void *user_data)
3645 GSource *src;
3646 guint tag;
3648 if (s->chr_add_watch == NULL) {
3649 return -ENOSYS;
3652 src = s->chr_add_watch(s, cond);
3653 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3654 tag = g_source_attach(src, NULL);
3655 g_source_unref(src);
3657 return tag;
3660 int qemu_chr_fe_claim(CharDriverState *s)
3662 if (s->avail_connections < 1) {
3663 return -1;
3665 s->avail_connections--;
3666 return 0;
3669 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3671 if (qemu_chr_fe_claim(s) != 0) {
3672 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3673 __func__, s->label);
3674 exit(1);
3678 void qemu_chr_fe_release(CharDriverState *s)
3680 s->avail_connections++;
3683 void qemu_chr_delete(CharDriverState *chr)
3685 QTAILQ_REMOVE(&chardevs, chr, next);
3686 if (chr->chr_close) {
3687 chr->chr_close(chr);
3689 g_free(chr->filename);
3690 g_free(chr->label);
3691 if (chr->opts) {
3692 qemu_opts_del(chr->opts);
3694 g_free(chr);
3697 ChardevInfoList *qmp_query_chardev(Error **errp)
3699 ChardevInfoList *chr_list = NULL;
3700 CharDriverState *chr;
3702 QTAILQ_FOREACH(chr, &chardevs, next) {
3703 ChardevInfoList *info = g_malloc0(sizeof(*info));
3704 info->value = g_malloc0(sizeof(*info->value));
3705 info->value->label = g_strdup(chr->label);
3706 info->value->filename = g_strdup(chr->filename);
3708 info->next = chr_list;
3709 chr_list = info;
3712 return chr_list;
3715 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
3717 ChardevBackendInfoList *backend_list = NULL;
3718 CharDriver *c = NULL;
3719 GSList *i = NULL;
3721 for (i = backends; i; i = i->next) {
3722 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
3723 c = i->data;
3724 info->value = g_malloc0(sizeof(*info->value));
3725 info->value->name = g_strdup(c->name);
3727 info->next = backend_list;
3728 backend_list = info;
3731 return backend_list;
3734 CharDriverState *qemu_chr_find(const char *name)
3736 CharDriverState *chr;
3738 QTAILQ_FOREACH(chr, &chardevs, next) {
3739 if (strcmp(chr->label, name) != 0)
3740 continue;
3741 return chr;
3743 return NULL;
3746 /* Get a character (serial) device interface. */
3747 CharDriverState *qemu_char_get_next_serial(void)
3749 static int next_serial;
3750 CharDriverState *chr;
3752 /* FIXME: This function needs to go away: use chardev properties! */
3754 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3755 chr = serial_hds[next_serial++];
3756 qemu_chr_fe_claim_no_fail(chr);
3757 return chr;
3759 return NULL;
3762 QemuOptsList qemu_chardev_opts = {
3763 .name = "chardev",
3764 .implied_opt_name = "backend",
3765 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3766 .desc = {
3768 .name = "backend",
3769 .type = QEMU_OPT_STRING,
3771 .name = "path",
3772 .type = QEMU_OPT_STRING,
3774 .name = "host",
3775 .type = QEMU_OPT_STRING,
3777 .name = "port",
3778 .type = QEMU_OPT_STRING,
3780 .name = "localaddr",
3781 .type = QEMU_OPT_STRING,
3783 .name = "localport",
3784 .type = QEMU_OPT_STRING,
3786 .name = "to",
3787 .type = QEMU_OPT_NUMBER,
3789 .name = "ipv4",
3790 .type = QEMU_OPT_BOOL,
3792 .name = "ipv6",
3793 .type = QEMU_OPT_BOOL,
3795 .name = "wait",
3796 .type = QEMU_OPT_BOOL,
3798 .name = "server",
3799 .type = QEMU_OPT_BOOL,
3801 .name = "delay",
3802 .type = QEMU_OPT_BOOL,
3804 .name = "telnet",
3805 .type = QEMU_OPT_BOOL,
3807 .name = "width",
3808 .type = QEMU_OPT_NUMBER,
3810 .name = "height",
3811 .type = QEMU_OPT_NUMBER,
3813 .name = "cols",
3814 .type = QEMU_OPT_NUMBER,
3816 .name = "rows",
3817 .type = QEMU_OPT_NUMBER,
3819 .name = "mux",
3820 .type = QEMU_OPT_BOOL,
3822 .name = "signal",
3823 .type = QEMU_OPT_BOOL,
3825 .name = "name",
3826 .type = QEMU_OPT_STRING,
3828 .name = "debug",
3829 .type = QEMU_OPT_NUMBER,
3831 .name = "size",
3832 .type = QEMU_OPT_SIZE,
3834 .name = "chardev",
3835 .type = QEMU_OPT_STRING,
3837 { /* end of list */ }
3841 #ifdef _WIN32
3843 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3845 HANDLE out;
3847 if (file->has_in) {
3848 error_setg(errp, "input file not supported");
3849 return NULL;
3852 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3853 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3854 if (out == INVALID_HANDLE_VALUE) {
3855 error_setg(errp, "open %s failed", file->out);
3856 return NULL;
3858 return qemu_chr_open_win_file(out);
3861 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3862 Error **errp)
3864 return qemu_chr_open_win_path(serial->device);
3867 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3868 Error **errp)
3870 error_setg(errp, "character device backend type 'parallel' not supported");
3871 return NULL;
3874 #else /* WIN32 */
3876 static int qmp_chardev_open_file_source(char *src, int flags,
3877 Error **errp)
3879 int fd = -1;
3881 TFR(fd = qemu_open(src, flags, 0666));
3882 if (fd == -1) {
3883 error_setg_file_open(errp, errno, src);
3885 return fd;
3888 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3890 int flags, in = -1, out;
3892 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3893 out = qmp_chardev_open_file_source(file->out, flags, errp);
3894 if (out < 0) {
3895 return NULL;
3898 if (file->has_in) {
3899 flags = O_RDONLY;
3900 in = qmp_chardev_open_file_source(file->in, flags, errp);
3901 if (in < 0) {
3902 qemu_close(out);
3903 return NULL;
3907 return qemu_chr_open_fd(in, out);
3910 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3911 Error **errp)
3913 #ifdef HAVE_CHARDEV_TTY
3914 int fd;
3916 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3917 if (fd < 0) {
3918 return NULL;
3920 qemu_set_nonblock(fd);
3921 return qemu_chr_open_tty_fd(fd);
3922 #else
3923 error_setg(errp, "character device backend type 'serial' not supported");
3924 return NULL;
3925 #endif
3928 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3929 Error **errp)
3931 #ifdef HAVE_CHARDEV_PARPORT
3932 int fd;
3934 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3935 if (fd < 0) {
3936 return NULL;
3938 return qemu_chr_open_pp_fd(fd);
3939 #else
3940 error_setg(errp, "character device backend type 'parallel' not supported");
3941 return NULL;
3942 #endif
3945 #endif /* WIN32 */
3947 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3948 Error **errp)
3950 SocketAddress *addr = sock->addr;
3951 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3952 bool is_listen = sock->has_server ? sock->server : true;
3953 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3954 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3955 int fd;
3957 if (is_listen) {
3958 fd = socket_listen(addr, errp);
3959 } else {
3960 fd = socket_connect(addr, errp, NULL, NULL);
3962 if (fd < 0) {
3963 return NULL;
3965 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3966 is_telnet, is_waitconnect, errp);
3969 static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
3970 Error **errp)
3972 int fd;
3974 fd = socket_dgram(udp->remote, udp->local, errp);
3975 if (fd < 0) {
3976 return NULL;
3978 return qemu_chr_open_udp_fd(fd);
3981 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3982 Error **errp)
3984 ChardevReturn *ret = g_new0(ChardevReturn, 1);
3985 CharDriverState *base, *chr = NULL;
3987 chr = qemu_chr_find(id);
3988 if (chr) {
3989 error_setg(errp, "Chardev '%s' already exists", id);
3990 g_free(ret);
3991 return NULL;
3994 switch (backend->kind) {
3995 case CHARDEV_BACKEND_KIND_FILE:
3996 chr = qmp_chardev_open_file(backend->file, errp);
3997 break;
3998 case CHARDEV_BACKEND_KIND_SERIAL:
3999 chr = qmp_chardev_open_serial(backend->serial, errp);
4000 break;
4001 case CHARDEV_BACKEND_KIND_PARALLEL:
4002 chr = qmp_chardev_open_parallel(backend->parallel, errp);
4003 break;
4004 case CHARDEV_BACKEND_KIND_PIPE:
4005 chr = qemu_chr_open_pipe(backend->pipe);
4006 break;
4007 case CHARDEV_BACKEND_KIND_SOCKET:
4008 chr = qmp_chardev_open_socket(backend->socket, errp);
4009 break;
4010 case CHARDEV_BACKEND_KIND_UDP:
4011 chr = qmp_chardev_open_udp(backend->udp, errp);
4012 break;
4013 #ifdef HAVE_CHARDEV_TTY
4014 case CHARDEV_BACKEND_KIND_PTY:
4015 chr = qemu_chr_open_pty(id, ret);
4016 break;
4017 #endif
4018 case CHARDEV_BACKEND_KIND_NULL:
4019 chr = qemu_chr_open_null();
4020 break;
4021 case CHARDEV_BACKEND_KIND_MUX:
4022 base = qemu_chr_find(backend->mux->chardev);
4023 if (base == NULL) {
4024 error_setg(errp, "mux: base chardev %s not found",
4025 backend->mux->chardev);
4026 break;
4028 chr = qemu_chr_open_mux(base);
4029 break;
4030 case CHARDEV_BACKEND_KIND_MSMOUSE:
4031 chr = qemu_chr_open_msmouse();
4032 break;
4033 #ifdef CONFIG_BRLAPI
4034 case CHARDEV_BACKEND_KIND_BRAILLE:
4035 chr = chr_baum_init();
4036 break;
4037 #endif
4038 case CHARDEV_BACKEND_KIND_STDIO:
4039 chr = qemu_chr_open_stdio(backend->stdio);
4040 break;
4041 #ifdef _WIN32
4042 case CHARDEV_BACKEND_KIND_CONSOLE:
4043 chr = qemu_chr_open_win_con();
4044 break;
4045 #endif
4046 #ifdef CONFIG_SPICE
4047 case CHARDEV_BACKEND_KIND_SPICEVMC:
4048 chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
4049 break;
4050 case CHARDEV_BACKEND_KIND_SPICEPORT:
4051 chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
4052 break;
4053 #endif
4054 case CHARDEV_BACKEND_KIND_VC:
4055 chr = vc_init(backend->vc);
4056 break;
4057 case CHARDEV_BACKEND_KIND_RINGBUF:
4058 case CHARDEV_BACKEND_KIND_MEMORY:
4059 chr = qemu_chr_open_ringbuf(backend->ringbuf, errp);
4060 break;
4061 default:
4062 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
4063 break;
4067 * Character backend open hasn't been fully converted to the Error
4068 * API. Some opens fail without setting an error. Set a generic
4069 * error then.
4070 * TODO full conversion to Error API
4072 if (chr == NULL && errp && !*errp) {
4073 error_setg(errp, "Failed to create chardev");
4075 if (chr) {
4076 chr->label = g_strdup(id);
4077 chr->avail_connections =
4078 (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4079 if (!chr->filename) {
4080 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
4082 if (!chr->explicit_be_open) {
4083 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4085 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4086 return ret;
4087 } else {
4088 g_free(ret);
4089 return NULL;
4093 void qmp_chardev_remove(const char *id, Error **errp)
4095 CharDriverState *chr;
4097 chr = qemu_chr_find(id);
4098 if (NULL == chr) {
4099 error_setg(errp, "Chardev '%s' not found", id);
4100 return;
4102 if (chr->chr_can_read || chr->chr_read ||
4103 chr->chr_event || chr->handler_opaque) {
4104 error_setg(errp, "Chardev '%s' is busy", id);
4105 return;
4107 qemu_chr_delete(chr);
4110 static void register_types(void)
4112 register_char_driver_qapi("null", CHARDEV_BACKEND_KIND_NULL, NULL);
4113 register_char_driver("socket", qemu_chr_open_socket);
4114 register_char_driver("udp", qemu_chr_open_udp);
4115 register_char_driver_qapi("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4116 qemu_chr_parse_ringbuf);
4117 register_char_driver_qapi("file", CHARDEV_BACKEND_KIND_FILE,
4118 qemu_chr_parse_file_out);
4119 register_char_driver_qapi("stdio", CHARDEV_BACKEND_KIND_STDIO,
4120 qemu_chr_parse_stdio);
4121 register_char_driver_qapi("serial", CHARDEV_BACKEND_KIND_SERIAL,
4122 qemu_chr_parse_serial);
4123 register_char_driver_qapi("tty", CHARDEV_BACKEND_KIND_SERIAL,
4124 qemu_chr_parse_serial);
4125 register_char_driver_qapi("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4126 qemu_chr_parse_parallel);
4127 register_char_driver_qapi("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4128 qemu_chr_parse_parallel);
4129 register_char_driver_qapi("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
4130 register_char_driver_qapi("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
4131 register_char_driver_qapi("pipe", CHARDEV_BACKEND_KIND_PIPE,
4132 qemu_chr_parse_pipe);
4133 register_char_driver_qapi("mux", CHARDEV_BACKEND_KIND_MUX,
4134 qemu_chr_parse_mux);
4135 /* Bug-compatibility: */
4136 register_char_driver_qapi("memory", CHARDEV_BACKEND_KIND_MEMORY,
4137 qemu_chr_parse_ringbuf);
4138 /* this must be done after machine init, since we register FEs with muxes
4139 * as part of realize functions like serial_isa_realizefn when -nographic
4140 * is specified
4142 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4145 type_init(register_types);