libcacard/vscclient: fix leakage of socket on error paths
[qemu/ar7.git] / qemu-char.c
blob596bf9e376313d5bef8a35bd170535a1647f885c
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 "ui/console.h"
27 #include "sysemu/sysemu.h"
28 #include "qemu/timer.h"
29 #include "sysemu/char.h"
30 #include "hw/usb.h"
31 #include "qmp-commands.h"
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <time.h>
36 #include <errno.h>
37 #include <sys/time.h>
38 #include <zlib.h>
40 #ifndef _WIN32
41 #include <sys/times.h>
42 #include <sys/wait.h>
43 #include <termios.h>
44 #include <sys/mman.h>
45 #include <sys/ioctl.h>
46 #include <sys/resource.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #include <net/if.h>
50 #include <arpa/inet.h>
51 #include <dirent.h>
52 #include <netdb.h>
53 #include <sys/select.h>
54 #ifdef CONFIG_BSD
55 #include <sys/stat.h>
56 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
57 #include <dev/ppbus/ppi.h>
58 #include <dev/ppbus/ppbconf.h>
59 #elif defined(__DragonFly__)
60 #include <dev/misc/ppi/ppi.h>
61 #include <bus/ppbus/ppbconf.h>
62 #endif
63 #else
64 #ifdef __linux__
65 #include <linux/ppdev.h>
66 #include <linux/parport.h>
67 #endif
68 #ifdef __sun__
69 #include <sys/stat.h>
70 #include <sys/ethernet.h>
71 #include <sys/sockio.h>
72 #include <netinet/arp.h>
73 #include <netinet/in.h>
74 #include <netinet/in_systm.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_icmp.h> // must come after ip.h
77 #include <netinet/udp.h>
78 #include <netinet/tcp.h>
79 #endif
80 #endif
81 #endif
83 #include "qemu/sockets.h"
84 #include "ui/qemu-spice.h"
86 #define READ_BUF_LEN 4096
88 /***********************************************************/
89 /* character device */
91 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
92 QTAILQ_HEAD_INITIALIZER(chardevs);
94 void qemu_chr_be_event(CharDriverState *s, int event)
96 /* Keep track if the char device is open */
97 switch (event) {
98 case CHR_EVENT_OPENED:
99 s->be_open = 1;
100 break;
101 case CHR_EVENT_CLOSED:
102 s->be_open = 0;
103 break;
106 if (!s->chr_event)
107 return;
108 s->chr_event(s->handler_opaque, event);
111 void qemu_chr_be_generic_open(CharDriverState *s)
113 qemu_chr_be_event(s, CHR_EVENT_OPENED);
116 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
118 return s->chr_write(s, buf, len);
121 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
123 int offset = 0;
124 int res;
126 while (offset < len) {
127 do {
128 res = s->chr_write(s, buf + offset, len - offset);
129 if (res == -1 && errno == EAGAIN) {
130 g_usleep(100);
132 } while (res == -1 && errno == EAGAIN);
134 if (res == 0) {
135 break;
138 if (res < 0) {
139 return res;
142 offset += res;
145 return offset;
148 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
150 if (!s->chr_ioctl)
151 return -ENOTSUP;
152 return s->chr_ioctl(s, cmd, arg);
155 int qemu_chr_be_can_write(CharDriverState *s)
157 if (!s->chr_can_read)
158 return 0;
159 return s->chr_can_read(s->handler_opaque);
162 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
164 if (s->chr_read) {
165 s->chr_read(s->handler_opaque, buf, len);
169 int qemu_chr_fe_get_msgfd(CharDriverState *s)
171 return s->get_msgfd ? s->get_msgfd(s) : -1;
174 int qemu_chr_add_client(CharDriverState *s, int fd)
176 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
179 void qemu_chr_accept_input(CharDriverState *s)
181 if (s->chr_accept_input)
182 s->chr_accept_input(s);
183 qemu_notify_event();
186 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
188 char buf[READ_BUF_LEN];
189 va_list ap;
190 va_start(ap, fmt);
191 vsnprintf(buf, sizeof(buf), fmt, ap);
192 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
193 va_end(ap);
196 void qemu_chr_add_handlers(CharDriverState *s,
197 IOCanReadHandler *fd_can_read,
198 IOReadHandler *fd_read,
199 IOEventHandler *fd_event,
200 void *opaque)
202 int fe_open;
204 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
205 fe_open = 0;
206 } else {
207 fe_open = 1;
209 s->chr_can_read = fd_can_read;
210 s->chr_read = fd_read;
211 s->chr_event = fd_event;
212 s->handler_opaque = opaque;
213 if (s->chr_update_read_handler)
214 s->chr_update_read_handler(s);
216 if (!s->explicit_fe_open) {
217 qemu_chr_fe_set_open(s, fe_open);
220 /* We're connecting to an already opened device, so let's make sure we
221 also get the open event */
222 if (fe_open && s->be_open) {
223 qemu_chr_be_generic_open(s);
227 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
229 return len;
232 static CharDriverState *qemu_chr_open_null(void)
234 CharDriverState *chr;
236 chr = g_malloc0(sizeof(CharDriverState));
237 chr->chr_write = null_chr_write;
238 chr->explicit_be_open = true;
239 return chr;
242 /* MUX driver for serial I/O splitting */
243 #define MAX_MUX 4
244 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
245 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
246 typedef struct {
247 IOCanReadHandler *chr_can_read[MAX_MUX];
248 IOReadHandler *chr_read[MAX_MUX];
249 IOEventHandler *chr_event[MAX_MUX];
250 void *ext_opaque[MAX_MUX];
251 CharDriverState *drv;
252 int focus;
253 int mux_cnt;
254 int term_got_escape;
255 int max_size;
256 /* Intermediate input buffer allows to catch escape sequences even if the
257 currently active device is not accepting any input - but only until it
258 is full as well. */
259 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
260 int prod[MAX_MUX];
261 int cons[MAX_MUX];
262 int timestamps;
263 int linestart;
264 int64_t timestamps_start;
265 } MuxDriver;
268 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
270 MuxDriver *d = chr->opaque;
271 int ret;
272 if (!d->timestamps) {
273 ret = d->drv->chr_write(d->drv, buf, len);
274 } else {
275 int i;
277 ret = 0;
278 for (i = 0; i < len; i++) {
279 if (d->linestart) {
280 char buf1[64];
281 int64_t ti;
282 int secs;
284 ti = qemu_get_clock_ms(rt_clock);
285 if (d->timestamps_start == -1)
286 d->timestamps_start = ti;
287 ti -= d->timestamps_start;
288 secs = ti / 1000;
289 snprintf(buf1, sizeof(buf1),
290 "[%02d:%02d:%02d.%03d] ",
291 secs / 3600,
292 (secs / 60) % 60,
293 secs % 60,
294 (int)(ti % 1000));
295 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
296 d->linestart = 0;
298 ret += d->drv->chr_write(d->drv, buf+i, 1);
299 if (buf[i] == '\n') {
300 d->linestart = 1;
304 return ret;
307 static const char * const mux_help[] = {
308 "% h print this help\n\r",
309 "% x exit emulator\n\r",
310 "% s save disk data back to file (if -snapshot)\n\r",
311 "% t toggle console timestamps\n\r"
312 "% b send break (magic sysrq)\n\r",
313 "% c switch between console and monitor\n\r",
314 "% % sends %\n\r",
315 NULL
318 int term_escape_char = 0x01; /* ctrl-a is used for escape */
319 static void mux_print_help(CharDriverState *chr)
321 int i, j;
322 char ebuf[15] = "Escape-Char";
323 char cbuf[50] = "\n\r";
325 if (term_escape_char > 0 && term_escape_char < 26) {
326 snprintf(cbuf, sizeof(cbuf), "\n\r");
327 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
328 } else {
329 snprintf(cbuf, sizeof(cbuf),
330 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
331 term_escape_char);
333 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
334 for (i = 0; mux_help[i] != NULL; i++) {
335 for (j=0; mux_help[i][j] != '\0'; j++) {
336 if (mux_help[i][j] == '%')
337 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
338 else
339 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
344 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
346 if (d->chr_event[mux_nr])
347 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
350 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
352 if (d->term_got_escape) {
353 d->term_got_escape = 0;
354 if (ch == term_escape_char)
355 goto send_char;
356 switch(ch) {
357 case '?':
358 case 'h':
359 mux_print_help(chr);
360 break;
361 case 'x':
363 const char *term = "QEMU: Terminated\n\r";
364 chr->chr_write(chr,(uint8_t *)term,strlen(term));
365 exit(0);
366 break;
368 case 's':
369 bdrv_commit_all();
370 break;
371 case 'b':
372 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
373 break;
374 case 'c':
375 /* Switch to the next registered device */
376 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
377 d->focus++;
378 if (d->focus >= d->mux_cnt)
379 d->focus = 0;
380 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
381 break;
382 case 't':
383 d->timestamps = !d->timestamps;
384 d->timestamps_start = -1;
385 d->linestart = 0;
386 break;
388 } else if (ch == term_escape_char) {
389 d->term_got_escape = 1;
390 } else {
391 send_char:
392 return 1;
394 return 0;
397 static void mux_chr_accept_input(CharDriverState *chr)
399 MuxDriver *d = chr->opaque;
400 int m = d->focus;
402 while (d->prod[m] != d->cons[m] &&
403 d->chr_can_read[m] &&
404 d->chr_can_read[m](d->ext_opaque[m])) {
405 d->chr_read[m](d->ext_opaque[m],
406 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
410 static int mux_chr_can_read(void *opaque)
412 CharDriverState *chr = opaque;
413 MuxDriver *d = chr->opaque;
414 int m = d->focus;
416 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
417 return 1;
418 if (d->chr_can_read[m])
419 return d->chr_can_read[m](d->ext_opaque[m]);
420 return 0;
423 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
425 CharDriverState *chr = opaque;
426 MuxDriver *d = chr->opaque;
427 int m = d->focus;
428 int i;
430 mux_chr_accept_input (opaque);
432 for(i = 0; i < size; i++)
433 if (mux_proc_byte(chr, d, buf[i])) {
434 if (d->prod[m] == d->cons[m] &&
435 d->chr_can_read[m] &&
436 d->chr_can_read[m](d->ext_opaque[m]))
437 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
438 else
439 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
443 static void mux_chr_event(void *opaque, int event)
445 CharDriverState *chr = opaque;
446 MuxDriver *d = chr->opaque;
447 int i;
449 /* Send the event to all registered listeners */
450 for (i = 0; i < d->mux_cnt; i++)
451 mux_chr_send_event(d, i, event);
454 static void mux_chr_update_read_handler(CharDriverState *chr)
456 MuxDriver *d = chr->opaque;
458 if (d->mux_cnt >= MAX_MUX) {
459 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
460 return;
462 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
463 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
464 d->chr_read[d->mux_cnt] = chr->chr_read;
465 d->chr_event[d->mux_cnt] = chr->chr_event;
466 /* Fix up the real driver with mux routines */
467 if (d->mux_cnt == 0) {
468 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
469 mux_chr_event, chr);
471 if (d->focus != -1) {
472 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
474 d->focus = d->mux_cnt;
475 d->mux_cnt++;
476 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
479 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
481 CharDriverState *chr;
482 MuxDriver *d;
484 chr = g_malloc0(sizeof(CharDriverState));
485 d = g_malloc0(sizeof(MuxDriver));
487 chr->opaque = d;
488 d->drv = drv;
489 d->focus = -1;
490 chr->chr_write = mux_chr_write;
491 chr->chr_update_read_handler = mux_chr_update_read_handler;
492 chr->chr_accept_input = mux_chr_accept_input;
493 /* Frontend guest-open / -close notification is not support with muxes */
494 chr->chr_set_fe_open = NULL;
496 return chr;
500 #ifdef _WIN32
501 int send_all(int fd, const void *buf, int len1)
503 int ret, len;
505 len = len1;
506 while (len > 0) {
507 ret = send(fd, buf, len, 0);
508 if (ret < 0) {
509 errno = WSAGetLastError();
510 if (errno != WSAEWOULDBLOCK) {
511 return -1;
513 } else if (ret == 0) {
514 break;
515 } else {
516 buf += ret;
517 len -= ret;
520 return len1 - len;
523 #else
525 int send_all(int fd, const void *_buf, int len1)
527 int ret, len;
528 const uint8_t *buf = _buf;
530 len = len1;
531 while (len > 0) {
532 ret = write(fd, buf, len);
533 if (ret < 0) {
534 if (errno != EINTR && errno != EAGAIN)
535 return -1;
536 } else if (ret == 0) {
537 break;
538 } else {
539 buf += ret;
540 len -= ret;
543 return len1 - len;
546 int recv_all(int fd, void *_buf, int len1, bool single_read)
548 int ret, len;
549 uint8_t *buf = _buf;
551 len = len1;
552 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
553 if (ret < 0) {
554 if (errno != EINTR && errno != EAGAIN) {
555 return -1;
557 continue;
558 } else {
559 if (single_read) {
560 return ret;
562 buf += ret;
563 len -= ret;
566 return len1 - len;
569 #endif /* !_WIN32 */
571 typedef struct IOWatchPoll
573 GSource parent;
575 GIOChannel *channel;
576 GSource *src;
578 IOCanReadHandler *fd_can_read;
579 GSourceFunc fd_read;
580 void *opaque;
581 } IOWatchPoll;
583 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
585 return container_of(source, IOWatchPoll, parent);
588 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
590 IOWatchPoll *iwp = io_watch_poll_from_source(source);
591 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
592 bool was_active = iwp->src != NULL;
593 if (was_active == now_active) {
594 return FALSE;
597 if (now_active) {
598 iwp->src = g_io_create_watch(iwp->channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
599 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
600 g_source_attach(iwp->src, NULL);
601 } else {
602 g_source_destroy(iwp->src);
603 g_source_unref(iwp->src);
604 iwp->src = NULL;
606 return FALSE;
609 static gboolean io_watch_poll_check(GSource *source)
611 return FALSE;
614 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
615 gpointer user_data)
617 abort();
620 static void io_watch_poll_finalize(GSource *source)
622 /* Due to a glib bug, removing the last reference to a source
623 * inside a finalize callback causes recursive locking (and a
624 * deadlock). This is not a problem inside other callbacks,
625 * including dispatch callbacks, so we call io_remove_watch_poll
626 * to remove this source. At this point, iwp->src must
627 * be NULL, or we would leak it.
629 * This would be solved much more elegantly by child sources,
630 * but we support older glib versions that do not have them.
632 IOWatchPoll *iwp = io_watch_poll_from_source(source);
633 assert(iwp->src == NULL);
636 static GSourceFuncs io_watch_poll_funcs = {
637 .prepare = io_watch_poll_prepare,
638 .check = io_watch_poll_check,
639 .dispatch = io_watch_poll_dispatch,
640 .finalize = io_watch_poll_finalize,
643 /* Can only be used for read */
644 static guint io_add_watch_poll(GIOChannel *channel,
645 IOCanReadHandler *fd_can_read,
646 GIOFunc fd_read,
647 gpointer user_data)
649 IOWatchPoll *iwp;
650 int tag;
652 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
653 iwp->fd_can_read = fd_can_read;
654 iwp->opaque = user_data;
655 iwp->channel = channel;
656 iwp->fd_read = (GSourceFunc) fd_read;
657 iwp->src = NULL;
659 tag = g_source_attach(&iwp->parent, NULL);
660 g_source_unref(&iwp->parent);
661 return tag;
664 static void io_remove_watch_poll(guint tag)
666 GSource *source;
667 IOWatchPoll *iwp;
669 g_return_if_fail (tag > 0);
671 source = g_main_context_find_source_by_id(NULL, tag);
672 g_return_if_fail (source != NULL);
674 iwp = io_watch_poll_from_source(source);
675 if (iwp->src) {
676 g_source_destroy(iwp->src);
677 g_source_unref(iwp->src);
678 iwp->src = NULL;
680 g_source_destroy(&iwp->parent);
683 #ifndef _WIN32
684 static GIOChannel *io_channel_from_fd(int fd)
686 GIOChannel *chan;
688 if (fd == -1) {
689 return NULL;
692 chan = g_io_channel_unix_new(fd);
694 g_io_channel_set_encoding(chan, NULL, NULL);
695 g_io_channel_set_buffered(chan, FALSE);
697 return chan;
699 #endif
701 static GIOChannel *io_channel_from_socket(int fd)
703 GIOChannel *chan;
705 if (fd == -1) {
706 return NULL;
709 #ifdef _WIN32
710 chan = g_io_channel_win32_new_socket(fd);
711 #else
712 chan = g_io_channel_unix_new(fd);
713 #endif
715 g_io_channel_set_encoding(chan, NULL, NULL);
716 g_io_channel_set_buffered(chan, FALSE);
718 return chan;
721 static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
723 GIOStatus status;
724 size_t offset;
726 offset = 0;
727 while (offset < len) {
728 gsize bytes_written;
730 status = g_io_channel_write_chars(fd, buf + offset, len - offset,
731 &bytes_written, NULL);
732 if (status != G_IO_STATUS_NORMAL) {
733 if (status == G_IO_STATUS_AGAIN) {
734 /* If we've written any data, return a partial write. */
735 if (offset) {
736 break;
738 errno = EAGAIN;
739 } else {
740 errno = EINVAL;
743 return -1;
744 } else if (status == G_IO_STATUS_EOF) {
745 break;
748 offset += bytes_written;
751 return offset;
754 #ifndef _WIN32
756 typedef struct FDCharDriver {
757 CharDriverState *chr;
758 GIOChannel *fd_in, *fd_out;
759 guint fd_in_tag;
760 int max_size;
761 QTAILQ_ENTRY(FDCharDriver) node;
762 } FDCharDriver;
764 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
766 FDCharDriver *s = chr->opaque;
768 return io_channel_send(s->fd_out, buf, len);
771 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
773 CharDriverState *chr = opaque;
774 FDCharDriver *s = chr->opaque;
775 int len;
776 uint8_t buf[READ_BUF_LEN];
777 GIOStatus status;
778 gsize bytes_read;
780 len = sizeof(buf);
781 if (len > s->max_size) {
782 len = s->max_size;
784 if (len == 0) {
785 return TRUE;
788 status = g_io_channel_read_chars(chan, (gchar *)buf,
789 len, &bytes_read, NULL);
790 if (status == G_IO_STATUS_EOF) {
791 if (s->fd_in_tag) {
792 io_remove_watch_poll(s->fd_in_tag);
793 s->fd_in_tag = 0;
795 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
796 return FALSE;
798 if (status == G_IO_STATUS_NORMAL) {
799 qemu_chr_be_write(chr, buf, bytes_read);
802 return TRUE;
805 static int fd_chr_read_poll(void *opaque)
807 CharDriverState *chr = opaque;
808 FDCharDriver *s = chr->opaque;
810 s->max_size = qemu_chr_be_can_write(chr);
811 return s->max_size;
814 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
816 FDCharDriver *s = chr->opaque;
817 return g_io_create_watch(s->fd_out, cond);
820 static void fd_chr_update_read_handler(CharDriverState *chr)
822 FDCharDriver *s = chr->opaque;
824 if (s->fd_in_tag) {
825 io_remove_watch_poll(s->fd_in_tag);
826 s->fd_in_tag = 0;
829 if (s->fd_in) {
830 s->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll, fd_chr_read, chr);
834 static void fd_chr_close(struct CharDriverState *chr)
836 FDCharDriver *s = chr->opaque;
838 if (s->fd_in_tag) {
839 io_remove_watch_poll(s->fd_in_tag);
840 s->fd_in_tag = 0;
843 if (s->fd_in) {
844 g_io_channel_unref(s->fd_in);
846 if (s->fd_out) {
847 g_io_channel_unref(s->fd_out);
850 g_free(s);
851 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
854 /* open a character device to a unix fd */
855 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
857 CharDriverState *chr;
858 FDCharDriver *s;
860 chr = g_malloc0(sizeof(CharDriverState));
861 s = g_malloc0(sizeof(FDCharDriver));
862 s->fd_in = io_channel_from_fd(fd_in);
863 s->fd_out = io_channel_from_fd(fd_out);
864 fcntl(fd_out, F_SETFL, O_NONBLOCK);
865 s->chr = chr;
866 chr->opaque = s;
867 chr->chr_add_watch = fd_chr_add_watch;
868 chr->chr_write = fd_chr_write;
869 chr->chr_update_read_handler = fd_chr_update_read_handler;
870 chr->chr_close = fd_chr_close;
872 return chr;
875 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
877 int fd_in, fd_out;
878 char filename_in[256], filename_out[256];
879 const char *filename = opts->device;
881 if (filename == NULL) {
882 fprintf(stderr, "chardev: pipe: no filename given\n");
883 return NULL;
886 snprintf(filename_in, 256, "%s.in", filename);
887 snprintf(filename_out, 256, "%s.out", filename);
888 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
889 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
890 if (fd_in < 0 || fd_out < 0) {
891 if (fd_in >= 0)
892 close(fd_in);
893 if (fd_out >= 0)
894 close(fd_out);
895 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
896 if (fd_in < 0) {
897 return NULL;
900 return qemu_chr_open_fd(fd_in, fd_out);
903 /* init terminal so that we can grab keys */
904 static struct termios oldtty;
905 static int old_fd0_flags;
906 static bool stdio_allow_signal;
908 static void term_exit(void)
910 tcsetattr (0, TCSANOW, &oldtty);
911 fcntl(0, F_SETFL, old_fd0_flags);
914 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
916 struct termios tty;
918 tty = oldtty;
919 if (!echo) {
920 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
921 |INLCR|IGNCR|ICRNL|IXON);
922 tty.c_oflag |= OPOST;
923 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
924 tty.c_cflag &= ~(CSIZE|PARENB);
925 tty.c_cflag |= CS8;
926 tty.c_cc[VMIN] = 1;
927 tty.c_cc[VTIME] = 0;
929 /* if graphical mode, we allow Ctrl-C handling */
930 if (!stdio_allow_signal)
931 tty.c_lflag &= ~ISIG;
933 tcsetattr (0, TCSANOW, &tty);
936 static void qemu_chr_close_stdio(struct CharDriverState *chr)
938 term_exit();
939 fd_chr_close(chr);
942 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
944 CharDriverState *chr;
946 if (is_daemonized()) {
947 error_report("cannot use stdio with -daemonize");
948 return NULL;
950 old_fd0_flags = fcntl(0, F_GETFL);
951 tcgetattr (0, &oldtty);
952 fcntl(0, F_SETFL, O_NONBLOCK);
953 atexit(term_exit);
955 chr = qemu_chr_open_fd(0, 1);
956 chr->chr_close = qemu_chr_close_stdio;
957 chr->chr_set_echo = qemu_chr_set_echo_stdio;
958 stdio_allow_signal = display_type != DT_NOGRAPHIC;
959 if (opts->has_signal) {
960 stdio_allow_signal = opts->signal;
962 qemu_chr_fe_set_echo(chr, false);
964 return chr;
967 #ifdef __sun__
968 /* Once Solaris has openpty(), this is going to be removed. */
969 static int openpty(int *amaster, int *aslave, char *name,
970 struct termios *termp, struct winsize *winp)
972 const char *slave;
973 int mfd = -1, sfd = -1;
975 *amaster = *aslave = -1;
977 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
978 if (mfd < 0)
979 goto err;
981 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
982 goto err;
984 if ((slave = ptsname(mfd)) == NULL)
985 goto err;
987 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
988 goto err;
990 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
991 (termp != NULL && tcgetattr(sfd, termp) < 0))
992 goto err;
994 if (amaster)
995 *amaster = mfd;
996 if (aslave)
997 *aslave = sfd;
998 if (winp)
999 ioctl(sfd, TIOCSWINSZ, winp);
1001 return 0;
1003 err:
1004 if (sfd != -1)
1005 close(sfd);
1006 close(mfd);
1007 return -1;
1010 static void cfmakeraw (struct termios *termios_p)
1012 termios_p->c_iflag &=
1013 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
1014 termios_p->c_oflag &= ~OPOST;
1015 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
1016 termios_p->c_cflag &= ~(CSIZE|PARENB);
1017 termios_p->c_cflag |= CS8;
1019 termios_p->c_cc[VMIN] = 0;
1020 termios_p->c_cc[VTIME] = 0;
1022 #endif
1024 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1025 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1026 || defined(__GLIBC__)
1028 #define HAVE_CHARDEV_TTY 1
1030 typedef struct {
1031 GIOChannel *fd;
1032 guint fd_tag;
1033 int connected;
1034 int read_bytes;
1035 guint timer_tag;
1036 } PtyCharDriver;
1038 static void pty_chr_update_read_handler(CharDriverState *chr);
1039 static void pty_chr_state(CharDriverState *chr, int connected);
1041 static gboolean pty_chr_timer(gpointer opaque)
1043 struct CharDriverState *chr = opaque;
1044 PtyCharDriver *s = chr->opaque;
1046 if (s->connected) {
1047 goto out;
1050 /* Next poll ... */
1051 pty_chr_update_read_handler(chr);
1053 out:
1054 s->timer_tag = 0;
1055 return FALSE;
1058 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1060 PtyCharDriver *s = chr->opaque;
1062 if (s->timer_tag) {
1063 g_source_remove(s->timer_tag);
1064 s->timer_tag = 0;
1067 if (ms == 1000) {
1068 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1069 } else {
1070 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1074 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1076 PtyCharDriver *s = chr->opaque;
1078 if (!s->connected) {
1079 /* guest sends data, check for (re-)connect */
1080 pty_chr_update_read_handler(chr);
1081 return 0;
1083 return io_channel_send(s->fd, buf, len);
1086 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1088 PtyCharDriver *s = chr->opaque;
1089 return g_io_create_watch(s->fd, cond);
1092 static int pty_chr_read_poll(void *opaque)
1094 CharDriverState *chr = opaque;
1095 PtyCharDriver *s = chr->opaque;
1097 s->read_bytes = qemu_chr_be_can_write(chr);
1098 return s->read_bytes;
1101 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1103 CharDriverState *chr = opaque;
1104 PtyCharDriver *s = chr->opaque;
1105 gsize size, len;
1106 uint8_t buf[READ_BUF_LEN];
1107 GIOStatus status;
1109 len = sizeof(buf);
1110 if (len > s->read_bytes)
1111 len = s->read_bytes;
1112 if (len == 0) {
1113 return TRUE;
1115 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1116 if (status != G_IO_STATUS_NORMAL) {
1117 pty_chr_state(chr, 0);
1118 return FALSE;
1119 } else {
1120 pty_chr_state(chr, 1);
1121 qemu_chr_be_write(chr, buf, size);
1123 return TRUE;
1126 static void pty_chr_update_read_handler(CharDriverState *chr)
1128 PtyCharDriver *s = chr->opaque;
1129 GPollFD pfd;
1131 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1132 pfd.events = G_IO_OUT;
1133 pfd.revents = 0;
1134 g_poll(&pfd, 1, 0);
1135 if (pfd.revents & G_IO_HUP) {
1136 pty_chr_state(chr, 0);
1137 } else {
1138 pty_chr_state(chr, 1);
1142 static void pty_chr_state(CharDriverState *chr, int connected)
1144 PtyCharDriver *s = chr->opaque;
1146 if (!connected) {
1147 if (s->fd_tag) {
1148 io_remove_watch_poll(s->fd_tag);
1149 s->fd_tag = 0;
1151 s->connected = 0;
1152 /* (re-)connect poll interval for idle guests: once per second.
1153 * We check more frequently in case the guests sends data to
1154 * the virtual device linked to our pty. */
1155 pty_chr_rearm_timer(chr, 1000);
1156 } else {
1157 if (s->timer_tag) {
1158 g_source_remove(s->timer_tag);
1159 s->timer_tag = 0;
1161 if (!s->connected) {
1162 qemu_chr_be_generic_open(chr);
1163 s->connected = 1;
1164 s->fd_tag = io_add_watch_poll(s->fd, pty_chr_read_poll, pty_chr_read, chr);
1170 static void pty_chr_close(struct CharDriverState *chr)
1172 PtyCharDriver *s = chr->opaque;
1173 int fd;
1175 if (s->fd_tag) {
1176 io_remove_watch_poll(s->fd_tag);
1177 s->fd_tag = 0;
1179 fd = g_io_channel_unix_get_fd(s->fd);
1180 g_io_channel_unref(s->fd);
1181 close(fd);
1182 if (s->timer_tag) {
1183 g_source_remove(s->timer_tag);
1184 s->timer_tag = 0;
1186 g_free(s);
1187 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1190 static CharDriverState *qemu_chr_open_pty(const char *id,
1191 ChardevReturn *ret)
1193 CharDriverState *chr;
1194 PtyCharDriver *s;
1195 struct termios tty;
1196 int master_fd, slave_fd;
1197 #if defined(__OpenBSD__) || defined(__DragonFly__)
1198 char pty_name[PATH_MAX];
1199 #define q_ptsname(x) pty_name
1200 #else
1201 char *pty_name = NULL;
1202 #define q_ptsname(x) ptsname(x)
1203 #endif
1205 if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1206 return NULL;
1209 /* Set raw attributes on the pty. */
1210 tcgetattr(slave_fd, &tty);
1211 cfmakeraw(&tty);
1212 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1213 close(slave_fd);
1215 chr = g_malloc0(sizeof(CharDriverState));
1217 chr->filename = g_strdup_printf("pty:%s", q_ptsname(master_fd));
1218 ret->pty = g_strdup(q_ptsname(master_fd));
1219 ret->has_pty = true;
1221 fprintf(stderr, "char device redirected to %s (label %s)\n",
1222 q_ptsname(master_fd), id);
1224 s = g_malloc0(sizeof(PtyCharDriver));
1225 chr->opaque = s;
1226 chr->chr_write = pty_chr_write;
1227 chr->chr_update_read_handler = pty_chr_update_read_handler;
1228 chr->chr_close = pty_chr_close;
1229 chr->chr_add_watch = pty_chr_add_watch;
1230 chr->explicit_be_open = true;
1232 s->fd = io_channel_from_fd(master_fd);
1233 s->timer_tag = 0;
1235 return chr;
1238 static void tty_serial_init(int fd, int speed,
1239 int parity, int data_bits, int stop_bits)
1241 struct termios tty;
1242 speed_t spd;
1244 #if 0
1245 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1246 speed, parity, data_bits, stop_bits);
1247 #endif
1248 tcgetattr (fd, &tty);
1250 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1251 speed = speed * 10 / 11;
1252 do {
1253 check_speed(50);
1254 check_speed(75);
1255 check_speed(110);
1256 check_speed(134);
1257 check_speed(150);
1258 check_speed(200);
1259 check_speed(300);
1260 check_speed(600);
1261 check_speed(1200);
1262 check_speed(1800);
1263 check_speed(2400);
1264 check_speed(4800);
1265 check_speed(9600);
1266 check_speed(19200);
1267 check_speed(38400);
1268 /* Non-Posix values follow. They may be unsupported on some systems. */
1269 check_speed(57600);
1270 check_speed(115200);
1271 #ifdef B230400
1272 check_speed(230400);
1273 #endif
1274 #ifdef B460800
1275 check_speed(460800);
1276 #endif
1277 #ifdef B500000
1278 check_speed(500000);
1279 #endif
1280 #ifdef B576000
1281 check_speed(576000);
1282 #endif
1283 #ifdef B921600
1284 check_speed(921600);
1285 #endif
1286 #ifdef B1000000
1287 check_speed(1000000);
1288 #endif
1289 #ifdef B1152000
1290 check_speed(1152000);
1291 #endif
1292 #ifdef B1500000
1293 check_speed(1500000);
1294 #endif
1295 #ifdef B2000000
1296 check_speed(2000000);
1297 #endif
1298 #ifdef B2500000
1299 check_speed(2500000);
1300 #endif
1301 #ifdef B3000000
1302 check_speed(3000000);
1303 #endif
1304 #ifdef B3500000
1305 check_speed(3500000);
1306 #endif
1307 #ifdef B4000000
1308 check_speed(4000000);
1309 #endif
1310 spd = B115200;
1311 } while (0);
1313 cfsetispeed(&tty, spd);
1314 cfsetospeed(&tty, spd);
1316 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1317 |INLCR|IGNCR|ICRNL|IXON);
1318 tty.c_oflag |= OPOST;
1319 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1320 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1321 switch(data_bits) {
1322 default:
1323 case 8:
1324 tty.c_cflag |= CS8;
1325 break;
1326 case 7:
1327 tty.c_cflag |= CS7;
1328 break;
1329 case 6:
1330 tty.c_cflag |= CS6;
1331 break;
1332 case 5:
1333 tty.c_cflag |= CS5;
1334 break;
1336 switch(parity) {
1337 default:
1338 case 'N':
1339 break;
1340 case 'E':
1341 tty.c_cflag |= PARENB;
1342 break;
1343 case 'O':
1344 tty.c_cflag |= PARENB | PARODD;
1345 break;
1347 if (stop_bits == 2)
1348 tty.c_cflag |= CSTOPB;
1350 tcsetattr (fd, TCSANOW, &tty);
1353 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1355 FDCharDriver *s = chr->opaque;
1357 switch(cmd) {
1358 case CHR_IOCTL_SERIAL_SET_PARAMS:
1360 QEMUSerialSetParams *ssp = arg;
1361 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1362 ssp->speed, ssp->parity,
1363 ssp->data_bits, ssp->stop_bits);
1365 break;
1366 case CHR_IOCTL_SERIAL_SET_BREAK:
1368 int enable = *(int *)arg;
1369 if (enable) {
1370 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1373 break;
1374 case CHR_IOCTL_SERIAL_GET_TIOCM:
1376 int sarg = 0;
1377 int *targ = (int *)arg;
1378 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1379 *targ = 0;
1380 if (sarg & TIOCM_CTS)
1381 *targ |= CHR_TIOCM_CTS;
1382 if (sarg & TIOCM_CAR)
1383 *targ |= CHR_TIOCM_CAR;
1384 if (sarg & TIOCM_DSR)
1385 *targ |= CHR_TIOCM_DSR;
1386 if (sarg & TIOCM_RI)
1387 *targ |= CHR_TIOCM_RI;
1388 if (sarg & TIOCM_DTR)
1389 *targ |= CHR_TIOCM_DTR;
1390 if (sarg & TIOCM_RTS)
1391 *targ |= CHR_TIOCM_RTS;
1393 break;
1394 case CHR_IOCTL_SERIAL_SET_TIOCM:
1396 int sarg = *(int *)arg;
1397 int targ = 0;
1398 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1399 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1400 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1401 if (sarg & CHR_TIOCM_CTS)
1402 targ |= TIOCM_CTS;
1403 if (sarg & CHR_TIOCM_CAR)
1404 targ |= TIOCM_CAR;
1405 if (sarg & CHR_TIOCM_DSR)
1406 targ |= TIOCM_DSR;
1407 if (sarg & CHR_TIOCM_RI)
1408 targ |= TIOCM_RI;
1409 if (sarg & CHR_TIOCM_DTR)
1410 targ |= TIOCM_DTR;
1411 if (sarg & CHR_TIOCM_RTS)
1412 targ |= TIOCM_RTS;
1413 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1415 break;
1416 default:
1417 return -ENOTSUP;
1419 return 0;
1422 static void qemu_chr_close_tty(CharDriverState *chr)
1424 FDCharDriver *s = chr->opaque;
1425 int fd = -1;
1427 if (s) {
1428 fd = g_io_channel_unix_get_fd(s->fd_in);
1431 fd_chr_close(chr);
1433 if (fd >= 0) {
1434 close(fd);
1438 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1440 CharDriverState *chr;
1442 tty_serial_init(fd, 115200, 'N', 8, 1);
1443 chr = qemu_chr_open_fd(fd, fd);
1444 chr->chr_ioctl = tty_serial_ioctl;
1445 chr->chr_close = qemu_chr_close_tty;
1446 return chr;
1448 #endif /* __linux__ || __sun__ */
1450 #if defined(__linux__)
1452 #define HAVE_CHARDEV_PARPORT 1
1454 typedef struct {
1455 int fd;
1456 int mode;
1457 } ParallelCharDriver;
1459 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1461 if (s->mode != mode) {
1462 int m = mode;
1463 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1464 return 0;
1465 s->mode = mode;
1467 return 1;
1470 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1472 ParallelCharDriver *drv = chr->opaque;
1473 int fd = drv->fd;
1474 uint8_t b;
1476 switch(cmd) {
1477 case CHR_IOCTL_PP_READ_DATA:
1478 if (ioctl(fd, PPRDATA, &b) < 0)
1479 return -ENOTSUP;
1480 *(uint8_t *)arg = b;
1481 break;
1482 case CHR_IOCTL_PP_WRITE_DATA:
1483 b = *(uint8_t *)arg;
1484 if (ioctl(fd, PPWDATA, &b) < 0)
1485 return -ENOTSUP;
1486 break;
1487 case CHR_IOCTL_PP_READ_CONTROL:
1488 if (ioctl(fd, PPRCONTROL, &b) < 0)
1489 return -ENOTSUP;
1490 /* Linux gives only the lowest bits, and no way to know data
1491 direction! For better compatibility set the fixed upper
1492 bits. */
1493 *(uint8_t *)arg = b | 0xc0;
1494 break;
1495 case CHR_IOCTL_PP_WRITE_CONTROL:
1496 b = *(uint8_t *)arg;
1497 if (ioctl(fd, PPWCONTROL, &b) < 0)
1498 return -ENOTSUP;
1499 break;
1500 case CHR_IOCTL_PP_READ_STATUS:
1501 if (ioctl(fd, PPRSTATUS, &b) < 0)
1502 return -ENOTSUP;
1503 *(uint8_t *)arg = b;
1504 break;
1505 case CHR_IOCTL_PP_DATA_DIR:
1506 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1507 return -ENOTSUP;
1508 break;
1509 case CHR_IOCTL_PP_EPP_READ_ADDR:
1510 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1511 struct ParallelIOArg *parg = arg;
1512 int n = read(fd, parg->buffer, parg->count);
1513 if (n != parg->count) {
1514 return -EIO;
1517 break;
1518 case CHR_IOCTL_PP_EPP_READ:
1519 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1520 struct ParallelIOArg *parg = arg;
1521 int n = read(fd, parg->buffer, parg->count);
1522 if (n != parg->count) {
1523 return -EIO;
1526 break;
1527 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1528 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1529 struct ParallelIOArg *parg = arg;
1530 int n = write(fd, parg->buffer, parg->count);
1531 if (n != parg->count) {
1532 return -EIO;
1535 break;
1536 case CHR_IOCTL_PP_EPP_WRITE:
1537 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1538 struct ParallelIOArg *parg = arg;
1539 int n = write(fd, parg->buffer, parg->count);
1540 if (n != parg->count) {
1541 return -EIO;
1544 break;
1545 default:
1546 return -ENOTSUP;
1548 return 0;
1551 static void pp_close(CharDriverState *chr)
1553 ParallelCharDriver *drv = chr->opaque;
1554 int fd = drv->fd;
1556 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1557 ioctl(fd, PPRELEASE);
1558 close(fd);
1559 g_free(drv);
1560 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1563 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1565 CharDriverState *chr;
1566 ParallelCharDriver *drv;
1568 if (ioctl(fd, PPCLAIM) < 0) {
1569 close(fd);
1570 return NULL;
1573 drv = g_malloc0(sizeof(ParallelCharDriver));
1574 drv->fd = fd;
1575 drv->mode = IEEE1284_MODE_COMPAT;
1577 chr = g_malloc0(sizeof(CharDriverState));
1578 chr->chr_write = null_chr_write;
1579 chr->chr_ioctl = pp_ioctl;
1580 chr->chr_close = pp_close;
1581 chr->opaque = drv;
1583 return chr;
1585 #endif /* __linux__ */
1587 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1589 #define HAVE_CHARDEV_PARPORT 1
1591 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1593 int fd = (int)(intptr_t)chr->opaque;
1594 uint8_t b;
1596 switch(cmd) {
1597 case CHR_IOCTL_PP_READ_DATA:
1598 if (ioctl(fd, PPIGDATA, &b) < 0)
1599 return -ENOTSUP;
1600 *(uint8_t *)arg = b;
1601 break;
1602 case CHR_IOCTL_PP_WRITE_DATA:
1603 b = *(uint8_t *)arg;
1604 if (ioctl(fd, PPISDATA, &b) < 0)
1605 return -ENOTSUP;
1606 break;
1607 case CHR_IOCTL_PP_READ_CONTROL:
1608 if (ioctl(fd, PPIGCTRL, &b) < 0)
1609 return -ENOTSUP;
1610 *(uint8_t *)arg = b;
1611 break;
1612 case CHR_IOCTL_PP_WRITE_CONTROL:
1613 b = *(uint8_t *)arg;
1614 if (ioctl(fd, PPISCTRL, &b) < 0)
1615 return -ENOTSUP;
1616 break;
1617 case CHR_IOCTL_PP_READ_STATUS:
1618 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1619 return -ENOTSUP;
1620 *(uint8_t *)arg = b;
1621 break;
1622 default:
1623 return -ENOTSUP;
1625 return 0;
1628 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1630 CharDriverState *chr;
1632 chr = g_malloc0(sizeof(CharDriverState));
1633 chr->opaque = (void *)(intptr_t)fd;
1634 chr->chr_write = null_chr_write;
1635 chr->chr_ioctl = pp_ioctl;
1636 chr->explicit_be_open = true;
1637 return chr;
1639 #endif
1641 #else /* _WIN32 */
1643 typedef struct {
1644 int max_size;
1645 HANDLE hcom, hrecv, hsend;
1646 OVERLAPPED orecv, osend;
1647 BOOL fpipe;
1648 DWORD len;
1649 } WinCharState;
1651 typedef struct {
1652 HANDLE hStdIn;
1653 HANDLE hInputReadyEvent;
1654 HANDLE hInputDoneEvent;
1655 HANDLE hInputThread;
1656 uint8_t win_stdio_buf;
1657 } WinStdioCharState;
1659 #define NSENDBUF 2048
1660 #define NRECVBUF 2048
1661 #define MAXCONNECT 1
1662 #define NTIMEOUT 5000
1664 static int win_chr_poll(void *opaque);
1665 static int win_chr_pipe_poll(void *opaque);
1667 static void win_chr_close(CharDriverState *chr)
1669 WinCharState *s = chr->opaque;
1671 if (s->hsend) {
1672 CloseHandle(s->hsend);
1673 s->hsend = NULL;
1675 if (s->hrecv) {
1676 CloseHandle(s->hrecv);
1677 s->hrecv = NULL;
1679 if (s->hcom) {
1680 CloseHandle(s->hcom);
1681 s->hcom = NULL;
1683 if (s->fpipe)
1684 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1685 else
1686 qemu_del_polling_cb(win_chr_poll, chr);
1688 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1691 static int win_chr_init(CharDriverState *chr, const char *filename)
1693 WinCharState *s = chr->opaque;
1694 COMMCONFIG comcfg;
1695 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1696 COMSTAT comstat;
1697 DWORD size;
1698 DWORD err;
1700 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1701 if (!s->hsend) {
1702 fprintf(stderr, "Failed CreateEvent\n");
1703 goto fail;
1705 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1706 if (!s->hrecv) {
1707 fprintf(stderr, "Failed CreateEvent\n");
1708 goto fail;
1711 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1712 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1713 if (s->hcom == INVALID_HANDLE_VALUE) {
1714 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1715 s->hcom = NULL;
1716 goto fail;
1719 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1720 fprintf(stderr, "Failed SetupComm\n");
1721 goto fail;
1724 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1725 size = sizeof(COMMCONFIG);
1726 GetDefaultCommConfig(filename, &comcfg, &size);
1727 comcfg.dcb.DCBlength = sizeof(DCB);
1728 CommConfigDialog(filename, NULL, &comcfg);
1730 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1731 fprintf(stderr, "Failed SetCommState\n");
1732 goto fail;
1735 if (!SetCommMask(s->hcom, EV_ERR)) {
1736 fprintf(stderr, "Failed SetCommMask\n");
1737 goto fail;
1740 cto.ReadIntervalTimeout = MAXDWORD;
1741 if (!SetCommTimeouts(s->hcom, &cto)) {
1742 fprintf(stderr, "Failed SetCommTimeouts\n");
1743 goto fail;
1746 if (!ClearCommError(s->hcom, &err, &comstat)) {
1747 fprintf(stderr, "Failed ClearCommError\n");
1748 goto fail;
1750 qemu_add_polling_cb(win_chr_poll, chr);
1751 return 0;
1753 fail:
1754 win_chr_close(chr);
1755 return -1;
1758 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1760 WinCharState *s = chr->opaque;
1761 DWORD len, ret, size, err;
1763 len = len1;
1764 ZeroMemory(&s->osend, sizeof(s->osend));
1765 s->osend.hEvent = s->hsend;
1766 while (len > 0) {
1767 if (s->hsend)
1768 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1769 else
1770 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1771 if (!ret) {
1772 err = GetLastError();
1773 if (err == ERROR_IO_PENDING) {
1774 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1775 if (ret) {
1776 buf += size;
1777 len -= size;
1778 } else {
1779 break;
1781 } else {
1782 break;
1784 } else {
1785 buf += size;
1786 len -= size;
1789 return len1 - len;
1792 static int win_chr_read_poll(CharDriverState *chr)
1794 WinCharState *s = chr->opaque;
1796 s->max_size = qemu_chr_be_can_write(chr);
1797 return s->max_size;
1800 static void win_chr_readfile(CharDriverState *chr)
1802 WinCharState *s = chr->opaque;
1803 int ret, err;
1804 uint8_t buf[READ_BUF_LEN];
1805 DWORD size;
1807 ZeroMemory(&s->orecv, sizeof(s->orecv));
1808 s->orecv.hEvent = s->hrecv;
1809 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1810 if (!ret) {
1811 err = GetLastError();
1812 if (err == ERROR_IO_PENDING) {
1813 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1817 if (size > 0) {
1818 qemu_chr_be_write(chr, buf, size);
1822 static void win_chr_read(CharDriverState *chr)
1824 WinCharState *s = chr->opaque;
1826 if (s->len > s->max_size)
1827 s->len = s->max_size;
1828 if (s->len == 0)
1829 return;
1831 win_chr_readfile(chr);
1834 static int win_chr_poll(void *opaque)
1836 CharDriverState *chr = opaque;
1837 WinCharState *s = chr->opaque;
1838 COMSTAT status;
1839 DWORD comerr;
1841 ClearCommError(s->hcom, &comerr, &status);
1842 if (status.cbInQue > 0) {
1843 s->len = status.cbInQue;
1844 win_chr_read_poll(chr);
1845 win_chr_read(chr);
1846 return 1;
1848 return 0;
1851 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1853 CharDriverState *chr;
1854 WinCharState *s;
1856 chr = g_malloc0(sizeof(CharDriverState));
1857 s = g_malloc0(sizeof(WinCharState));
1858 chr->opaque = s;
1859 chr->chr_write = win_chr_write;
1860 chr->chr_close = win_chr_close;
1862 if (win_chr_init(chr, filename) < 0) {
1863 g_free(s);
1864 g_free(chr);
1865 return NULL;
1867 return chr;
1870 static int win_chr_pipe_poll(void *opaque)
1872 CharDriverState *chr = opaque;
1873 WinCharState *s = chr->opaque;
1874 DWORD size;
1876 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1877 if (size > 0) {
1878 s->len = size;
1879 win_chr_read_poll(chr);
1880 win_chr_read(chr);
1881 return 1;
1883 return 0;
1886 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1888 WinCharState *s = chr->opaque;
1889 OVERLAPPED ov;
1890 int ret;
1891 DWORD size;
1892 char openname[256];
1894 s->fpipe = TRUE;
1896 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1897 if (!s->hsend) {
1898 fprintf(stderr, "Failed CreateEvent\n");
1899 goto fail;
1901 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1902 if (!s->hrecv) {
1903 fprintf(stderr, "Failed CreateEvent\n");
1904 goto fail;
1907 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1908 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1909 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1910 PIPE_WAIT,
1911 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1912 if (s->hcom == INVALID_HANDLE_VALUE) {
1913 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1914 s->hcom = NULL;
1915 goto fail;
1918 ZeroMemory(&ov, sizeof(ov));
1919 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1920 ret = ConnectNamedPipe(s->hcom, &ov);
1921 if (ret) {
1922 fprintf(stderr, "Failed ConnectNamedPipe\n");
1923 goto fail;
1926 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1927 if (!ret) {
1928 fprintf(stderr, "Failed GetOverlappedResult\n");
1929 if (ov.hEvent) {
1930 CloseHandle(ov.hEvent);
1931 ov.hEvent = NULL;
1933 goto fail;
1936 if (ov.hEvent) {
1937 CloseHandle(ov.hEvent);
1938 ov.hEvent = NULL;
1940 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1941 return 0;
1943 fail:
1944 win_chr_close(chr);
1945 return -1;
1949 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
1951 const char *filename = opts->device;
1952 CharDriverState *chr;
1953 WinCharState *s;
1955 chr = g_malloc0(sizeof(CharDriverState));
1956 s = g_malloc0(sizeof(WinCharState));
1957 chr->opaque = s;
1958 chr->chr_write = win_chr_write;
1959 chr->chr_close = win_chr_close;
1961 if (win_chr_pipe_init(chr, filename) < 0) {
1962 g_free(s);
1963 g_free(chr);
1964 return NULL;
1966 return chr;
1969 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1971 CharDriverState *chr;
1972 WinCharState *s;
1974 chr = g_malloc0(sizeof(CharDriverState));
1975 s = g_malloc0(sizeof(WinCharState));
1976 s->hcom = fd_out;
1977 chr->opaque = s;
1978 chr->chr_write = win_chr_write;
1979 return chr;
1982 static CharDriverState *qemu_chr_open_win_con(void)
1984 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1987 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1989 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1990 DWORD dwSize;
1991 int len1;
1993 len1 = len;
1995 while (len1 > 0) {
1996 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
1997 break;
1999 buf += dwSize;
2000 len1 -= dwSize;
2003 return len - len1;
2006 static void win_stdio_wait_func(void *opaque)
2008 CharDriverState *chr = opaque;
2009 WinStdioCharState *stdio = chr->opaque;
2010 INPUT_RECORD buf[4];
2011 int ret;
2012 DWORD dwSize;
2013 int i;
2015 ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
2016 &dwSize);
2018 if (!ret) {
2019 /* Avoid error storm */
2020 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2021 return;
2024 for (i = 0; i < dwSize; i++) {
2025 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2027 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2028 int j;
2029 if (kev->uChar.AsciiChar != 0) {
2030 for (j = 0; j < kev->wRepeatCount; j++) {
2031 if (qemu_chr_be_can_write(chr)) {
2032 uint8_t c = kev->uChar.AsciiChar;
2033 qemu_chr_be_write(chr, &c, 1);
2041 static DWORD WINAPI win_stdio_thread(LPVOID param)
2043 CharDriverState *chr = param;
2044 WinStdioCharState *stdio = chr->opaque;
2045 int ret;
2046 DWORD dwSize;
2048 while (1) {
2050 /* Wait for one byte */
2051 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2053 /* Exit in case of error, continue if nothing read */
2054 if (!ret) {
2055 break;
2057 if (!dwSize) {
2058 continue;
2061 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2062 if (stdio->win_stdio_buf == '\r') {
2063 continue;
2066 /* Signal the main thread and wait until the byte was eaten */
2067 if (!SetEvent(stdio->hInputReadyEvent)) {
2068 break;
2070 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2071 != WAIT_OBJECT_0) {
2072 break;
2076 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2077 return 0;
2080 static void win_stdio_thread_wait_func(void *opaque)
2082 CharDriverState *chr = opaque;
2083 WinStdioCharState *stdio = chr->opaque;
2085 if (qemu_chr_be_can_write(chr)) {
2086 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2089 SetEvent(stdio->hInputDoneEvent);
2092 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2094 WinStdioCharState *stdio = chr->opaque;
2095 DWORD dwMode = 0;
2097 GetConsoleMode(stdio->hStdIn, &dwMode);
2099 if (echo) {
2100 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2101 } else {
2102 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2106 static void win_stdio_close(CharDriverState *chr)
2108 WinStdioCharState *stdio = chr->opaque;
2110 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2111 CloseHandle(stdio->hInputReadyEvent);
2113 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2114 CloseHandle(stdio->hInputDoneEvent);
2116 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2117 TerminateThread(stdio->hInputThread, 0);
2120 g_free(chr->opaque);
2121 g_free(chr);
2124 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2126 CharDriverState *chr;
2127 WinStdioCharState *stdio;
2128 DWORD dwMode;
2129 int is_console = 0;
2131 chr = g_malloc0(sizeof(CharDriverState));
2132 stdio = g_malloc0(sizeof(WinStdioCharState));
2134 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2135 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2136 fprintf(stderr, "cannot open stdio: invalid handle\n");
2137 exit(1);
2140 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2142 chr->opaque = stdio;
2143 chr->chr_write = win_stdio_write;
2144 chr->chr_close = win_stdio_close;
2146 if (is_console) {
2147 if (qemu_add_wait_object(stdio->hStdIn,
2148 win_stdio_wait_func, chr)) {
2149 fprintf(stderr, "qemu_add_wait_object: failed\n");
2151 } else {
2152 DWORD dwId;
2154 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2155 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2156 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2157 chr, 0, &dwId);
2159 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2160 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2161 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2162 fprintf(stderr, "cannot create stdio thread or event\n");
2163 exit(1);
2165 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2166 win_stdio_thread_wait_func, chr)) {
2167 fprintf(stderr, "qemu_add_wait_object: failed\n");
2171 dwMode |= ENABLE_LINE_INPUT;
2173 if (is_console) {
2174 /* set the terminal in raw mode */
2175 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2176 dwMode |= ENABLE_PROCESSED_INPUT;
2179 SetConsoleMode(stdio->hStdIn, dwMode);
2181 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2182 qemu_chr_fe_set_echo(chr, false);
2184 return chr;
2186 #endif /* !_WIN32 */
2189 /***********************************************************/
2190 /* UDP Net console */
2192 typedef struct {
2193 int fd;
2194 GIOChannel *chan;
2195 guint tag;
2196 uint8_t buf[READ_BUF_LEN];
2197 int bufcnt;
2198 int bufptr;
2199 int max_size;
2200 } NetCharDriver;
2202 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2204 NetCharDriver *s = chr->opaque;
2205 gsize bytes_written;
2206 GIOStatus status;
2208 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2209 if (status == G_IO_STATUS_EOF) {
2210 return 0;
2211 } else if (status != G_IO_STATUS_NORMAL) {
2212 return -1;
2215 return bytes_written;
2218 static int udp_chr_read_poll(void *opaque)
2220 CharDriverState *chr = opaque;
2221 NetCharDriver *s = chr->opaque;
2223 s->max_size = qemu_chr_be_can_write(chr);
2225 /* If there were any stray characters in the queue process them
2226 * first
2228 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2229 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2230 s->bufptr++;
2231 s->max_size = qemu_chr_be_can_write(chr);
2233 return s->max_size;
2236 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2238 CharDriverState *chr = opaque;
2239 NetCharDriver *s = chr->opaque;
2240 gsize bytes_read = 0;
2241 GIOStatus status;
2243 if (s->max_size == 0) {
2244 return TRUE;
2246 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2247 &bytes_read, NULL);
2248 s->bufcnt = bytes_read;
2249 s->bufptr = s->bufcnt;
2250 if (status != G_IO_STATUS_NORMAL) {
2251 if (s->tag) {
2252 io_remove_watch_poll(s->tag);
2253 s->tag = 0;
2255 return FALSE;
2258 s->bufptr = 0;
2259 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2260 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2261 s->bufptr++;
2262 s->max_size = qemu_chr_be_can_write(chr);
2265 return TRUE;
2268 static void udp_chr_update_read_handler(CharDriverState *chr)
2270 NetCharDriver *s = chr->opaque;
2272 if (s->tag) {
2273 io_remove_watch_poll(s->tag);
2274 s->tag = 0;
2277 if (s->chan) {
2278 s->tag = io_add_watch_poll(s->chan, udp_chr_read_poll, udp_chr_read, chr);
2282 static void udp_chr_close(CharDriverState *chr)
2284 NetCharDriver *s = chr->opaque;
2285 if (s->tag) {
2286 io_remove_watch_poll(s->tag);
2287 s->tag = 0;
2289 if (s->chan) {
2290 g_io_channel_unref(s->chan);
2291 closesocket(s->fd);
2293 g_free(s);
2294 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2297 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2299 CharDriverState *chr = NULL;
2300 NetCharDriver *s = NULL;
2302 chr = g_malloc0(sizeof(CharDriverState));
2303 s = g_malloc0(sizeof(NetCharDriver));
2305 s->fd = fd;
2306 s->chan = io_channel_from_socket(s->fd);
2307 s->bufcnt = 0;
2308 s->bufptr = 0;
2309 chr->opaque = s;
2310 chr->chr_write = udp_chr_write;
2311 chr->chr_update_read_handler = udp_chr_update_read_handler;
2312 chr->chr_close = udp_chr_close;
2313 /* be isn't opened until we get a connection */
2314 chr->explicit_be_open = true;
2315 return chr;
2318 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2320 Error *local_err = NULL;
2321 int fd = -1;
2323 fd = inet_dgram_opts(opts, &local_err);
2324 if (fd < 0) {
2325 return NULL;
2327 return qemu_chr_open_udp_fd(fd);
2330 /***********************************************************/
2331 /* TCP Net console */
2333 typedef struct {
2335 GIOChannel *chan, *listen_chan;
2336 guint tag, listen_tag;
2337 int fd, listen_fd;
2338 int connected;
2339 int max_size;
2340 int do_telnetopt;
2341 int do_nodelay;
2342 int is_unix;
2343 int msgfd;
2344 } TCPCharDriver;
2346 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2348 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2350 TCPCharDriver *s = chr->opaque;
2351 if (s->connected) {
2352 return io_channel_send(s->chan, buf, len);
2353 } else {
2354 /* XXX: indicate an error ? */
2355 return len;
2359 static int tcp_chr_read_poll(void *opaque)
2361 CharDriverState *chr = opaque;
2362 TCPCharDriver *s = chr->opaque;
2363 if (!s->connected)
2364 return 0;
2365 s->max_size = qemu_chr_be_can_write(chr);
2366 return s->max_size;
2369 #define IAC 255
2370 #define IAC_BREAK 243
2371 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2372 TCPCharDriver *s,
2373 uint8_t *buf, int *size)
2375 /* Handle any telnet client's basic IAC options to satisfy char by
2376 * char mode with no echo. All IAC options will be removed from
2377 * the buf and the do_telnetopt variable will be used to track the
2378 * state of the width of the IAC information.
2380 * IAC commands come in sets of 3 bytes with the exception of the
2381 * "IAC BREAK" command and the double IAC.
2384 int i;
2385 int j = 0;
2387 for (i = 0; i < *size; i++) {
2388 if (s->do_telnetopt > 1) {
2389 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2390 /* Double IAC means send an IAC */
2391 if (j != i)
2392 buf[j] = buf[i];
2393 j++;
2394 s->do_telnetopt = 1;
2395 } else {
2396 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2397 /* Handle IAC break commands by sending a serial break */
2398 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2399 s->do_telnetopt++;
2401 s->do_telnetopt++;
2403 if (s->do_telnetopt >= 4) {
2404 s->do_telnetopt = 1;
2406 } else {
2407 if ((unsigned char)buf[i] == IAC) {
2408 s->do_telnetopt = 2;
2409 } else {
2410 if (j != i)
2411 buf[j] = buf[i];
2412 j++;
2416 *size = j;
2419 static int tcp_get_msgfd(CharDriverState *chr)
2421 TCPCharDriver *s = chr->opaque;
2422 int fd = s->msgfd;
2423 s->msgfd = -1;
2424 return fd;
2427 #ifndef _WIN32
2428 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2430 TCPCharDriver *s = chr->opaque;
2431 struct cmsghdr *cmsg;
2433 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2434 int fd;
2436 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2437 cmsg->cmsg_level != SOL_SOCKET ||
2438 cmsg->cmsg_type != SCM_RIGHTS)
2439 continue;
2441 fd = *((int *)CMSG_DATA(cmsg));
2442 if (fd < 0)
2443 continue;
2445 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2446 qemu_set_block(fd);
2448 #ifndef MSG_CMSG_CLOEXEC
2449 qemu_set_cloexec(fd);
2450 #endif
2451 if (s->msgfd != -1)
2452 close(s->msgfd);
2453 s->msgfd = fd;
2457 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2459 TCPCharDriver *s = chr->opaque;
2460 struct msghdr msg = { NULL, };
2461 struct iovec iov[1];
2462 union {
2463 struct cmsghdr cmsg;
2464 char control[CMSG_SPACE(sizeof(int))];
2465 } msg_control;
2466 int flags = 0;
2467 ssize_t ret;
2469 iov[0].iov_base = buf;
2470 iov[0].iov_len = len;
2472 msg.msg_iov = iov;
2473 msg.msg_iovlen = 1;
2474 msg.msg_control = &msg_control;
2475 msg.msg_controllen = sizeof(msg_control);
2477 #ifdef MSG_CMSG_CLOEXEC
2478 flags |= MSG_CMSG_CLOEXEC;
2479 #endif
2480 ret = recvmsg(s->fd, &msg, flags);
2481 if (ret > 0 && s->is_unix) {
2482 unix_process_msgfd(chr, &msg);
2485 return ret;
2487 #else
2488 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2490 TCPCharDriver *s = chr->opaque;
2491 return qemu_recv(s->fd, buf, len, 0);
2493 #endif
2495 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2497 TCPCharDriver *s = chr->opaque;
2498 return g_io_create_watch(s->chan, cond);
2501 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2503 CharDriverState *chr = opaque;
2504 TCPCharDriver *s = chr->opaque;
2505 uint8_t buf[READ_BUF_LEN];
2506 int len, size;
2508 if (!s->connected || s->max_size <= 0) {
2509 return TRUE;
2511 len = sizeof(buf);
2512 if (len > s->max_size)
2513 len = s->max_size;
2514 size = tcp_chr_recv(chr, (void *)buf, len);
2515 if (size == 0) {
2516 /* connection closed */
2517 s->connected = 0;
2518 if (s->listen_chan) {
2519 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2521 if (s->tag) {
2522 io_remove_watch_poll(s->tag);
2523 s->tag = 0;
2525 g_io_channel_unref(s->chan);
2526 s->chan = NULL;
2527 closesocket(s->fd);
2528 s->fd = -1;
2529 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2530 } else if (size > 0) {
2531 if (s->do_telnetopt)
2532 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2533 if (size > 0)
2534 qemu_chr_be_write(chr, buf, size);
2537 return TRUE;
2540 #ifndef _WIN32
2541 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2543 return qemu_chr_open_fd(eventfd, eventfd);
2545 #endif
2547 static void tcp_chr_connect(void *opaque)
2549 CharDriverState *chr = opaque;
2550 TCPCharDriver *s = chr->opaque;
2552 s->connected = 1;
2553 if (s->chan) {
2554 s->tag = io_add_watch_poll(s->chan, tcp_chr_read_poll, tcp_chr_read, chr);
2556 qemu_chr_be_generic_open(chr);
2559 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2560 static void tcp_chr_telnet_init(int fd)
2562 char buf[3];
2563 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2564 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2565 send(fd, (char *)buf, 3, 0);
2566 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2567 send(fd, (char *)buf, 3, 0);
2568 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2569 send(fd, (char *)buf, 3, 0);
2570 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2571 send(fd, (char *)buf, 3, 0);
2574 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2576 TCPCharDriver *s = chr->opaque;
2577 if (s->fd != -1)
2578 return -1;
2580 qemu_set_nonblock(fd);
2581 if (s->do_nodelay)
2582 socket_set_nodelay(fd);
2583 s->fd = fd;
2584 s->chan = io_channel_from_socket(fd);
2585 if (s->listen_tag) {
2586 g_source_remove(s->listen_tag);
2587 s->listen_tag = 0;
2589 tcp_chr_connect(chr);
2591 return 0;
2594 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2596 CharDriverState *chr = opaque;
2597 TCPCharDriver *s = chr->opaque;
2598 struct sockaddr_in saddr;
2599 #ifndef _WIN32
2600 struct sockaddr_un uaddr;
2601 #endif
2602 struct sockaddr *addr;
2603 socklen_t len;
2604 int fd;
2606 for(;;) {
2607 #ifndef _WIN32
2608 if (s->is_unix) {
2609 len = sizeof(uaddr);
2610 addr = (struct sockaddr *)&uaddr;
2611 } else
2612 #endif
2614 len = sizeof(saddr);
2615 addr = (struct sockaddr *)&saddr;
2617 fd = qemu_accept(s->listen_fd, addr, &len);
2618 if (fd < 0 && errno != EINTR) {
2619 s->listen_tag = 0;
2620 return FALSE;
2621 } else if (fd >= 0) {
2622 if (s->do_telnetopt)
2623 tcp_chr_telnet_init(fd);
2624 break;
2627 if (tcp_chr_add_client(chr, fd) < 0)
2628 close(fd);
2630 return TRUE;
2633 static void tcp_chr_close(CharDriverState *chr)
2635 TCPCharDriver *s = chr->opaque;
2636 if (s->fd >= 0) {
2637 if (s->tag) {
2638 io_remove_watch_poll(s->tag);
2639 s->tag = 0;
2641 if (s->chan) {
2642 g_io_channel_unref(s->chan);
2644 closesocket(s->fd);
2646 if (s->listen_fd >= 0) {
2647 if (s->listen_tag) {
2648 g_source_remove(s->listen_tag);
2649 s->listen_tag = 0;
2651 if (s->listen_chan) {
2652 g_io_channel_unref(s->listen_chan);
2654 closesocket(s->listen_fd);
2656 g_free(s);
2657 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2660 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2661 bool is_listen, bool is_telnet,
2662 bool is_waitconnect,
2663 Error **errp)
2665 CharDriverState *chr = NULL;
2666 TCPCharDriver *s = NULL;
2667 char host[NI_MAXHOST], serv[NI_MAXSERV];
2668 const char *left = "", *right = "";
2669 struct sockaddr_storage ss;
2670 socklen_t ss_len = sizeof(ss);
2672 memset(&ss, 0, ss_len);
2673 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2674 error_setg(errp, "getsockname: %s", strerror(errno));
2675 return NULL;
2678 chr = g_malloc0(sizeof(CharDriverState));
2679 s = g_malloc0(sizeof(TCPCharDriver));
2681 s->connected = 0;
2682 s->fd = -1;
2683 s->listen_fd = -1;
2684 s->msgfd = -1;
2686 chr->filename = g_malloc(256);
2687 switch (ss.ss_family) {
2688 #ifndef _WIN32
2689 case AF_UNIX:
2690 s->is_unix = 1;
2691 snprintf(chr->filename, 256, "unix:%s%s",
2692 ((struct sockaddr_un *)(&ss))->sun_path,
2693 is_listen ? ",server" : "");
2694 break;
2695 #endif
2696 case AF_INET6:
2697 left = "[";
2698 right = "]";
2699 /* fall through */
2700 case AF_INET:
2701 s->do_nodelay = do_nodelay;
2702 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2703 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2704 snprintf(chr->filename, 256, "%s:%s%s%s:%s%s",
2705 is_telnet ? "telnet" : "tcp",
2706 left, host, right, serv,
2707 is_listen ? ",server" : "");
2708 break;
2711 chr->opaque = s;
2712 chr->chr_write = tcp_chr_write;
2713 chr->chr_close = tcp_chr_close;
2714 chr->get_msgfd = tcp_get_msgfd;
2715 chr->chr_add_client = tcp_chr_add_client;
2716 chr->chr_add_watch = tcp_chr_add_watch;
2717 /* be isn't opened until we get a connection */
2718 chr->explicit_be_open = true;
2720 if (is_listen) {
2721 s->listen_fd = fd;
2722 s->listen_chan = io_channel_from_socket(s->listen_fd);
2723 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2724 if (is_telnet) {
2725 s->do_telnetopt = 1;
2727 } else {
2728 s->connected = 1;
2729 s->fd = fd;
2730 socket_set_nodelay(fd);
2731 s->chan = io_channel_from_socket(s->fd);
2732 tcp_chr_connect(chr);
2735 if (is_listen && is_waitconnect) {
2736 printf("QEMU waiting for connection on: %s\n",
2737 chr->filename);
2738 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2739 qemu_set_nonblock(s->listen_fd);
2741 return chr;
2744 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2746 CharDriverState *chr = NULL;
2747 Error *local_err = NULL;
2748 int fd = -1;
2749 int is_listen;
2750 int is_waitconnect;
2751 int do_nodelay;
2752 int is_unix;
2753 int is_telnet;
2755 is_listen = qemu_opt_get_bool(opts, "server", 0);
2756 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2757 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2758 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2759 is_unix = qemu_opt_get(opts, "path") != NULL;
2760 if (!is_listen)
2761 is_waitconnect = 0;
2763 if (is_unix) {
2764 if (is_listen) {
2765 fd = unix_listen_opts(opts, &local_err);
2766 } else {
2767 fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2769 } else {
2770 if (is_listen) {
2771 fd = inet_listen_opts(opts, 0, &local_err);
2772 } else {
2773 fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2776 if (fd < 0) {
2777 goto fail;
2780 if (!is_waitconnect)
2781 qemu_set_nonblock(fd);
2783 chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2784 is_waitconnect, &local_err);
2785 if (error_is_set(&local_err)) {
2786 goto fail;
2788 return chr;
2791 fail:
2792 if (local_err) {
2793 qerror_report_err(local_err);
2794 error_free(local_err);
2796 if (fd >= 0) {
2797 closesocket(fd);
2799 if (chr) {
2800 g_free(chr->opaque);
2801 g_free(chr);
2803 return NULL;
2806 /*********************************************************/
2807 /* Ring buffer chardev */
2809 typedef struct {
2810 size_t size;
2811 size_t prod;
2812 size_t cons;
2813 uint8_t *cbuf;
2814 } RingBufCharDriver;
2816 static size_t ringbuf_count(const CharDriverState *chr)
2818 const RingBufCharDriver *d = chr->opaque;
2820 return d->prod - d->cons;
2823 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2825 RingBufCharDriver *d = chr->opaque;
2826 int i;
2828 if (!buf || (len < 0)) {
2829 return -1;
2832 for (i = 0; i < len; i++ ) {
2833 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2834 if (d->prod - d->cons > d->size) {
2835 d->cons = d->prod - d->size;
2839 return 0;
2842 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2844 RingBufCharDriver *d = chr->opaque;
2845 int i;
2847 for (i = 0; i < len && d->cons != d->prod; i++) {
2848 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2851 return i;
2854 static void ringbuf_chr_close(struct CharDriverState *chr)
2856 RingBufCharDriver *d = chr->opaque;
2858 g_free(d->cbuf);
2859 g_free(d);
2860 chr->opaque = NULL;
2863 static CharDriverState *qemu_chr_open_memory(ChardevMemory *opts,
2864 Error **errp)
2866 CharDriverState *chr;
2867 RingBufCharDriver *d;
2869 chr = g_malloc0(sizeof(CharDriverState));
2870 d = g_malloc(sizeof(*d));
2872 d->size = opts->has_size ? opts->size : 65536;
2874 /* The size must be power of 2 */
2875 if (d->size & (d->size - 1)) {
2876 error_setg(errp, "size of memory chardev must be power of two");
2877 goto fail;
2880 d->prod = 0;
2881 d->cons = 0;
2882 d->cbuf = g_malloc0(d->size);
2884 chr->opaque = d;
2885 chr->chr_write = ringbuf_chr_write;
2886 chr->chr_close = ringbuf_chr_close;
2888 return chr;
2890 fail:
2891 g_free(d);
2892 g_free(chr);
2893 return NULL;
2896 static bool chr_is_ringbuf(const CharDriverState *chr)
2898 return chr->chr_write == ringbuf_chr_write;
2901 void qmp_ringbuf_write(const char *device, const char *data,
2902 bool has_format, enum DataFormat format,
2903 Error **errp)
2905 CharDriverState *chr;
2906 const uint8_t *write_data;
2907 int ret;
2908 gsize write_count;
2910 chr = qemu_chr_find(device);
2911 if (!chr) {
2912 error_setg(errp, "Device '%s' not found", device);
2913 return;
2916 if (!chr_is_ringbuf(chr)) {
2917 error_setg(errp,"%s is not a ringbuf device", device);
2918 return;
2921 if (has_format && (format == DATA_FORMAT_BASE64)) {
2922 write_data = g_base64_decode(data, &write_count);
2923 } else {
2924 write_data = (uint8_t *)data;
2925 write_count = strlen(data);
2928 ret = ringbuf_chr_write(chr, write_data, write_count);
2930 if (write_data != (uint8_t *)data) {
2931 g_free((void *)write_data);
2934 if (ret < 0) {
2935 error_setg(errp, "Failed to write to device %s", device);
2936 return;
2940 char *qmp_ringbuf_read(const char *device, int64_t size,
2941 bool has_format, enum DataFormat format,
2942 Error **errp)
2944 CharDriverState *chr;
2945 uint8_t *read_data;
2946 size_t count;
2947 char *data;
2949 chr = qemu_chr_find(device);
2950 if (!chr) {
2951 error_setg(errp, "Device '%s' not found", device);
2952 return NULL;
2955 if (!chr_is_ringbuf(chr)) {
2956 error_setg(errp,"%s is not a ringbuf device", device);
2957 return NULL;
2960 if (size <= 0) {
2961 error_setg(errp, "size must be greater than zero");
2962 return NULL;
2965 count = ringbuf_count(chr);
2966 size = size > count ? count : size;
2967 read_data = g_malloc(size + 1);
2969 ringbuf_chr_read(chr, read_data, size);
2971 if (has_format && (format == DATA_FORMAT_BASE64)) {
2972 data = g_base64_encode(read_data, size);
2973 g_free(read_data);
2974 } else {
2976 * FIXME should read only complete, valid UTF-8 characters up
2977 * to @size bytes. Invalid sequences should be replaced by a
2978 * suitable replacement character. Except when (and only
2979 * when) ring buffer lost characters since last read, initial
2980 * continuation characters should be dropped.
2982 read_data[size] = 0;
2983 data = (char *)read_data;
2986 return data;
2989 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2991 char host[65], port[33], width[8], height[8];
2992 int pos;
2993 const char *p;
2994 QemuOpts *opts;
2995 Error *local_err = NULL;
2997 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
2998 if (error_is_set(&local_err)) {
2999 qerror_report_err(local_err);
3000 error_free(local_err);
3001 return NULL;
3004 if (strstart(filename, "mon:", &p)) {
3005 filename = p;
3006 qemu_opt_set(opts, "mux", "on");
3009 if (strcmp(filename, "null") == 0 ||
3010 strcmp(filename, "pty") == 0 ||
3011 strcmp(filename, "msmouse") == 0 ||
3012 strcmp(filename, "braille") == 0 ||
3013 strcmp(filename, "stdio") == 0) {
3014 qemu_opt_set(opts, "backend", filename);
3015 return opts;
3017 if (strstart(filename, "vc", &p)) {
3018 qemu_opt_set(opts, "backend", "vc");
3019 if (*p == ':') {
3020 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
3021 /* pixels */
3022 qemu_opt_set(opts, "width", width);
3023 qemu_opt_set(opts, "height", height);
3024 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
3025 /* chars */
3026 qemu_opt_set(opts, "cols", width);
3027 qemu_opt_set(opts, "rows", height);
3028 } else {
3029 goto fail;
3032 return opts;
3034 if (strcmp(filename, "con:") == 0) {
3035 qemu_opt_set(opts, "backend", "console");
3036 return opts;
3038 if (strstart(filename, "COM", NULL)) {
3039 qemu_opt_set(opts, "backend", "serial");
3040 qemu_opt_set(opts, "path", filename);
3041 return opts;
3043 if (strstart(filename, "file:", &p)) {
3044 qemu_opt_set(opts, "backend", "file");
3045 qemu_opt_set(opts, "path", p);
3046 return opts;
3048 if (strstart(filename, "pipe:", &p)) {
3049 qemu_opt_set(opts, "backend", "pipe");
3050 qemu_opt_set(opts, "path", p);
3051 return opts;
3053 if (strstart(filename, "tcp:", &p) ||
3054 strstart(filename, "telnet:", &p)) {
3055 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3056 host[0] = 0;
3057 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3058 goto fail;
3060 qemu_opt_set(opts, "backend", "socket");
3061 qemu_opt_set(opts, "host", host);
3062 qemu_opt_set(opts, "port", port);
3063 if (p[pos] == ',') {
3064 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3065 goto fail;
3067 if (strstart(filename, "telnet:", &p))
3068 qemu_opt_set(opts, "telnet", "on");
3069 return opts;
3071 if (strstart(filename, "udp:", &p)) {
3072 qemu_opt_set(opts, "backend", "udp");
3073 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3074 host[0] = 0;
3075 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3076 goto fail;
3079 qemu_opt_set(opts, "host", host);
3080 qemu_opt_set(opts, "port", port);
3081 if (p[pos] == '@') {
3082 p += pos + 1;
3083 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3084 host[0] = 0;
3085 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3086 goto fail;
3089 qemu_opt_set(opts, "localaddr", host);
3090 qemu_opt_set(opts, "localport", port);
3092 return opts;
3094 if (strstart(filename, "unix:", &p)) {
3095 qemu_opt_set(opts, "backend", "socket");
3096 if (qemu_opts_do_parse(opts, p, "path") != 0)
3097 goto fail;
3098 return opts;
3100 if (strstart(filename, "/dev/parport", NULL) ||
3101 strstart(filename, "/dev/ppi", NULL)) {
3102 qemu_opt_set(opts, "backend", "parport");
3103 qemu_opt_set(opts, "path", filename);
3104 return opts;
3106 if (strstart(filename, "/dev/", NULL)) {
3107 qemu_opt_set(opts, "backend", "tty");
3108 qemu_opt_set(opts, "path", filename);
3109 return opts;
3112 fail:
3113 qemu_opts_del(opts);
3114 return NULL;
3117 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3118 Error **errp)
3120 const char *path = qemu_opt_get(opts, "path");
3122 if (path == NULL) {
3123 error_setg(errp, "chardev: file: no filename given");
3124 return;
3126 backend->file = g_new0(ChardevFile, 1);
3127 backend->file->out = g_strdup(path);
3130 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3131 Error **errp)
3133 backend->stdio = g_new0(ChardevStdio, 1);
3134 backend->stdio->has_signal = true;
3135 backend->stdio->signal =
3136 qemu_opt_get_bool(opts, "signal", display_type != DT_NOGRAPHIC);
3139 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3140 Error **errp)
3142 const char *device = qemu_opt_get(opts, "path");
3144 if (device == NULL) {
3145 error_setg(errp, "chardev: serial/tty: no device path given");
3146 return;
3148 backend->serial = g_new0(ChardevHostdev, 1);
3149 backend->serial->device = g_strdup(device);
3152 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3153 Error **errp)
3155 const char *device = qemu_opt_get(opts, "path");
3157 if (device == NULL) {
3158 error_setg(errp, "chardev: parallel: no device path given");
3159 return;
3161 backend->parallel = g_new0(ChardevHostdev, 1);
3162 backend->parallel->device = g_strdup(device);
3165 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3166 Error **errp)
3168 const char *device = qemu_opt_get(opts, "path");
3170 if (device == NULL) {
3171 error_setg(errp, "chardev: pipe: no device path given");
3172 return;
3174 backend->pipe = g_new0(ChardevHostdev, 1);
3175 backend->pipe->device = g_strdup(device);
3178 static void qemu_chr_parse_memory(QemuOpts *opts, ChardevBackend *backend,
3179 Error **errp)
3181 int val;
3183 backend->memory = g_new0(ChardevMemory, 1);
3185 val = qemu_opt_get_number(opts, "size", 0);
3186 if (val != 0) {
3187 backend->memory->has_size = true;
3188 backend->memory->size = val;
3192 typedef struct CharDriver {
3193 const char *name;
3194 /* old, pre qapi */
3195 CharDriverState *(*open)(QemuOpts *opts);
3196 /* new, qapi-based */
3197 int kind;
3198 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3199 } CharDriver;
3201 static GSList *backends;
3203 void register_char_driver(const char *name, CharDriverState *(*open)(QemuOpts *))
3205 CharDriver *s;
3207 s = g_malloc0(sizeof(*s));
3208 s->name = g_strdup(name);
3209 s->open = open;
3211 backends = g_slist_append(backends, s);
3214 void register_char_driver_qapi(const char *name, int kind,
3215 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3217 CharDriver *s;
3219 s = g_malloc0(sizeof(*s));
3220 s->name = g_strdup(name);
3221 s->kind = kind;
3222 s->parse = parse;
3224 backends = g_slist_append(backends, s);
3227 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3228 void (*init)(struct CharDriverState *s),
3229 Error **errp)
3231 CharDriver *cd;
3232 CharDriverState *chr;
3233 GSList *i;
3235 if (qemu_opts_id(opts) == NULL) {
3236 error_setg(errp, "chardev: no id specified");
3237 goto err;
3240 if (qemu_opt_get(opts, "backend") == NULL) {
3241 error_setg(errp, "chardev: \"%s\" missing backend",
3242 qemu_opts_id(opts));
3243 goto err;
3245 for (i = backends; i; i = i->next) {
3246 cd = i->data;
3248 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3249 break;
3252 if (i == NULL) {
3253 error_setg(errp, "chardev: backend \"%s\" not found",
3254 qemu_opt_get(opts, "backend"));
3255 return NULL;
3258 if (!cd->open) {
3259 /* using new, qapi init */
3260 ChardevBackend *backend = g_new0(ChardevBackend, 1);
3261 ChardevReturn *ret = NULL;
3262 const char *id = qemu_opts_id(opts);
3263 const char *bid = NULL;
3265 if (qemu_opt_get_bool(opts, "mux", 0)) {
3266 bid = g_strdup_printf("%s-base", id);
3269 chr = NULL;
3270 backend->kind = cd->kind;
3271 if (cd->parse) {
3272 cd->parse(opts, backend, errp);
3273 if (error_is_set(errp)) {
3274 goto qapi_out;
3277 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3278 if (error_is_set(errp)) {
3279 goto qapi_out;
3282 if (bid) {
3283 qapi_free_ChardevBackend(backend);
3284 qapi_free_ChardevReturn(ret);
3285 backend = g_new0(ChardevBackend, 1);
3286 backend->mux = g_new0(ChardevMux, 1);
3287 backend->kind = CHARDEV_BACKEND_KIND_MUX;
3288 backend->mux->chardev = g_strdup(bid);
3289 ret = qmp_chardev_add(id, backend, errp);
3290 if (error_is_set(errp)) {
3291 goto qapi_out;
3295 chr = qemu_chr_find(id);
3297 qapi_out:
3298 qapi_free_ChardevBackend(backend);
3299 qapi_free_ChardevReturn(ret);
3300 return chr;
3303 chr = cd->open(opts);
3304 if (!chr) {
3305 error_setg(errp, "chardev: opening backend \"%s\" failed",
3306 qemu_opt_get(opts, "backend"));
3307 goto err;
3310 if (!chr->filename)
3311 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3312 chr->init = init;
3313 /* if we didn't create the chardev via qmp_chardev_add, we
3314 * need to send the OPENED event here
3316 if (!chr->explicit_be_open) {
3317 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
3319 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3321 if (qemu_opt_get_bool(opts, "mux", 0)) {
3322 CharDriverState *base = chr;
3323 int len = strlen(qemu_opts_id(opts)) + 6;
3324 base->label = g_malloc(len);
3325 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3326 chr = qemu_chr_open_mux(base);
3327 chr->filename = base->filename;
3328 chr->avail_connections = MAX_MUX;
3329 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3330 } else {
3331 chr->avail_connections = 1;
3333 chr->label = g_strdup(qemu_opts_id(opts));
3334 chr->opts = opts;
3335 return chr;
3337 err:
3338 qemu_opts_del(opts);
3339 return NULL;
3342 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3344 const char *p;
3345 CharDriverState *chr;
3346 QemuOpts *opts;
3347 Error *err = NULL;
3349 if (strstart(filename, "chardev:", &p)) {
3350 return qemu_chr_find(p);
3353 opts = qemu_chr_parse_compat(label, filename);
3354 if (!opts)
3355 return NULL;
3357 chr = qemu_chr_new_from_opts(opts, init, &err);
3358 if (error_is_set(&err)) {
3359 fprintf(stderr, "%s\n", error_get_pretty(err));
3360 error_free(err);
3362 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3363 qemu_chr_fe_claim_no_fail(chr);
3364 monitor_init(chr, MONITOR_USE_READLINE);
3366 return chr;
3369 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3371 if (chr->chr_set_echo) {
3372 chr->chr_set_echo(chr, echo);
3376 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3378 if (chr->fe_open == fe_open) {
3379 return;
3381 chr->fe_open = fe_open;
3382 if (chr->chr_set_fe_open) {
3383 chr->chr_set_fe_open(chr, fe_open);
3387 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3388 GIOFunc func, void *user_data)
3390 GSource *src;
3391 guint tag;
3393 if (s->chr_add_watch == NULL) {
3394 return -ENOSYS;
3397 src = s->chr_add_watch(s, cond);
3398 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3399 tag = g_source_attach(src, NULL);
3400 g_source_unref(src);
3402 return tag;
3405 int qemu_chr_fe_claim(CharDriverState *s)
3407 if (s->avail_connections < 1) {
3408 return -1;
3410 s->avail_connections--;
3411 return 0;
3414 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3416 if (qemu_chr_fe_claim(s) != 0) {
3417 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3418 __func__, s->label);
3419 exit(1);
3423 void qemu_chr_fe_release(CharDriverState *s)
3425 s->avail_connections++;
3428 void qemu_chr_delete(CharDriverState *chr)
3430 QTAILQ_REMOVE(&chardevs, chr, next);
3431 if (chr->chr_close) {
3432 chr->chr_close(chr);
3434 g_free(chr->filename);
3435 g_free(chr->label);
3436 if (chr->opts) {
3437 qemu_opts_del(chr->opts);
3439 g_free(chr);
3442 ChardevInfoList *qmp_query_chardev(Error **errp)
3444 ChardevInfoList *chr_list = NULL;
3445 CharDriverState *chr;
3447 QTAILQ_FOREACH(chr, &chardevs, next) {
3448 ChardevInfoList *info = g_malloc0(sizeof(*info));
3449 info->value = g_malloc0(sizeof(*info->value));
3450 info->value->label = g_strdup(chr->label);
3451 info->value->filename = g_strdup(chr->filename);
3453 info->next = chr_list;
3454 chr_list = info;
3457 return chr_list;
3460 CharDriverState *qemu_chr_find(const char *name)
3462 CharDriverState *chr;
3464 QTAILQ_FOREACH(chr, &chardevs, next) {
3465 if (strcmp(chr->label, name) != 0)
3466 continue;
3467 return chr;
3469 return NULL;
3472 /* Get a character (serial) device interface. */
3473 CharDriverState *qemu_char_get_next_serial(void)
3475 static int next_serial;
3476 CharDriverState *chr;
3478 /* FIXME: This function needs to go away: use chardev properties! */
3480 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3481 chr = serial_hds[next_serial++];
3482 qemu_chr_fe_claim_no_fail(chr);
3483 return chr;
3485 return NULL;
3488 QemuOptsList qemu_chardev_opts = {
3489 .name = "chardev",
3490 .implied_opt_name = "backend",
3491 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3492 .desc = {
3494 .name = "backend",
3495 .type = QEMU_OPT_STRING,
3497 .name = "path",
3498 .type = QEMU_OPT_STRING,
3500 .name = "host",
3501 .type = QEMU_OPT_STRING,
3503 .name = "port",
3504 .type = QEMU_OPT_STRING,
3506 .name = "localaddr",
3507 .type = QEMU_OPT_STRING,
3509 .name = "localport",
3510 .type = QEMU_OPT_STRING,
3512 .name = "to",
3513 .type = QEMU_OPT_NUMBER,
3515 .name = "ipv4",
3516 .type = QEMU_OPT_BOOL,
3518 .name = "ipv6",
3519 .type = QEMU_OPT_BOOL,
3521 .name = "wait",
3522 .type = QEMU_OPT_BOOL,
3524 .name = "server",
3525 .type = QEMU_OPT_BOOL,
3527 .name = "delay",
3528 .type = QEMU_OPT_BOOL,
3530 .name = "telnet",
3531 .type = QEMU_OPT_BOOL,
3533 .name = "width",
3534 .type = QEMU_OPT_NUMBER,
3536 .name = "height",
3537 .type = QEMU_OPT_NUMBER,
3539 .name = "cols",
3540 .type = QEMU_OPT_NUMBER,
3542 .name = "rows",
3543 .type = QEMU_OPT_NUMBER,
3545 .name = "mux",
3546 .type = QEMU_OPT_BOOL,
3548 .name = "signal",
3549 .type = QEMU_OPT_BOOL,
3551 .name = "name",
3552 .type = QEMU_OPT_STRING,
3554 .name = "debug",
3555 .type = QEMU_OPT_NUMBER,
3557 .name = "size",
3558 .type = QEMU_OPT_SIZE,
3560 { /* end of list */ }
3564 #ifdef _WIN32
3566 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3568 HANDLE out;
3570 if (file->in) {
3571 error_setg(errp, "input file not supported");
3572 return NULL;
3575 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3576 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3577 if (out == INVALID_HANDLE_VALUE) {
3578 error_setg(errp, "open %s failed", file->out);
3579 return NULL;
3581 return qemu_chr_open_win_file(out);
3584 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3585 Error **errp)
3587 return qemu_chr_open_win_path(serial->device);
3590 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3591 Error **errp)
3593 error_setg(errp, "character device backend type 'parallel' not supported");
3594 return NULL;
3597 #else /* WIN32 */
3599 static int qmp_chardev_open_file_source(char *src, int flags,
3600 Error **errp)
3602 int fd = -1;
3604 TFR(fd = qemu_open(src, flags, 0666));
3605 if (fd == -1) {
3606 error_setg(errp, "open %s: %s", src, strerror(errno));
3608 return fd;
3611 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3613 int flags, in = -1, out = -1;
3615 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3616 out = qmp_chardev_open_file_source(file->out, flags, errp);
3617 if (error_is_set(errp)) {
3618 return NULL;
3621 if (file->in) {
3622 flags = O_RDONLY;
3623 in = qmp_chardev_open_file_source(file->in, flags, errp);
3624 if (error_is_set(errp)) {
3625 qemu_close(out);
3626 return NULL;
3630 return qemu_chr_open_fd(in, out);
3633 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3634 Error **errp)
3636 #ifdef HAVE_CHARDEV_TTY
3637 int fd;
3639 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3640 if (error_is_set(errp)) {
3641 return NULL;
3643 qemu_set_nonblock(fd);
3644 return qemu_chr_open_tty_fd(fd);
3645 #else
3646 error_setg(errp, "character device backend type 'serial' not supported");
3647 return NULL;
3648 #endif
3651 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3652 Error **errp)
3654 #ifdef HAVE_CHARDEV_PARPORT
3655 int fd;
3657 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3658 if (error_is_set(errp)) {
3659 return NULL;
3661 return qemu_chr_open_pp_fd(fd);
3662 #else
3663 error_setg(errp, "character device backend type 'parallel' not supported");
3664 return NULL;
3665 #endif
3668 #endif /* WIN32 */
3670 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3671 Error **errp)
3673 SocketAddress *addr = sock->addr;
3674 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3675 bool is_listen = sock->has_server ? sock->server : true;
3676 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3677 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3678 int fd;
3680 if (is_listen) {
3681 fd = socket_listen(addr, errp);
3682 } else {
3683 fd = socket_connect(addr, errp, NULL, NULL);
3685 if (error_is_set(errp)) {
3686 return NULL;
3688 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3689 is_telnet, is_waitconnect, errp);
3692 static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
3693 Error **errp)
3695 int fd;
3697 fd = socket_dgram(udp->remote, udp->local, errp);
3698 if (error_is_set(errp)) {
3699 return NULL;
3701 return qemu_chr_open_udp_fd(fd);
3704 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3705 Error **errp)
3707 ChardevReturn *ret = g_new0(ChardevReturn, 1);
3708 CharDriverState *base, *chr = NULL;
3710 chr = qemu_chr_find(id);
3711 if (chr) {
3712 error_setg(errp, "Chardev '%s' already exists", id);
3713 g_free(ret);
3714 return NULL;
3717 switch (backend->kind) {
3718 case CHARDEV_BACKEND_KIND_FILE:
3719 chr = qmp_chardev_open_file(backend->file, errp);
3720 break;
3721 case CHARDEV_BACKEND_KIND_SERIAL:
3722 chr = qmp_chardev_open_serial(backend->serial, errp);
3723 break;
3724 case CHARDEV_BACKEND_KIND_PARALLEL:
3725 chr = qmp_chardev_open_parallel(backend->parallel, errp);
3726 break;
3727 case CHARDEV_BACKEND_KIND_PIPE:
3728 chr = qemu_chr_open_pipe(backend->pipe);
3729 break;
3730 case CHARDEV_BACKEND_KIND_SOCKET:
3731 chr = qmp_chardev_open_socket(backend->socket, errp);
3732 break;
3733 case CHARDEV_BACKEND_KIND_UDP:
3734 chr = qmp_chardev_open_udp(backend->udp, errp);
3735 break;
3736 #ifdef HAVE_CHARDEV_TTY
3737 case CHARDEV_BACKEND_KIND_PTY:
3738 chr = qemu_chr_open_pty(id, ret);
3739 break;
3740 #endif
3741 case CHARDEV_BACKEND_KIND_NULL:
3742 chr = qemu_chr_open_null();
3743 break;
3744 case CHARDEV_BACKEND_KIND_MUX:
3745 base = qemu_chr_find(backend->mux->chardev);
3746 if (base == NULL) {
3747 error_setg(errp, "mux: base chardev %s not found",
3748 backend->mux->chardev);
3749 break;
3751 chr = qemu_chr_open_mux(base);
3752 break;
3753 case CHARDEV_BACKEND_KIND_MSMOUSE:
3754 chr = qemu_chr_open_msmouse();
3755 break;
3756 #ifdef CONFIG_BRLAPI
3757 case CHARDEV_BACKEND_KIND_BRAILLE:
3758 chr = chr_baum_init();
3759 break;
3760 #endif
3761 case CHARDEV_BACKEND_KIND_STDIO:
3762 chr = qemu_chr_open_stdio(backend->stdio);
3763 break;
3764 #ifdef _WIN32
3765 case CHARDEV_BACKEND_KIND_CONSOLE:
3766 chr = qemu_chr_open_win_con();
3767 break;
3768 #endif
3769 #ifdef CONFIG_SPICE
3770 case CHARDEV_BACKEND_KIND_SPICEVMC:
3771 chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
3772 break;
3773 case CHARDEV_BACKEND_KIND_SPICEPORT:
3774 chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
3775 break;
3776 #endif
3777 case CHARDEV_BACKEND_KIND_VC:
3778 chr = vc_init(backend->vc);
3779 break;
3780 case CHARDEV_BACKEND_KIND_MEMORY:
3781 chr = qemu_chr_open_memory(backend->memory, errp);
3782 break;
3783 default:
3784 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3785 break;
3788 if (chr == NULL && !error_is_set(errp)) {
3789 error_setg(errp, "Failed to create chardev");
3791 if (chr) {
3792 chr->label = g_strdup(id);
3793 chr->avail_connections =
3794 (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
3795 if (!chr->filename) {
3796 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
3798 if (!chr->explicit_be_open) {
3799 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
3801 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3802 return ret;
3803 } else {
3804 g_free(ret);
3805 return NULL;
3809 void qmp_chardev_remove(const char *id, Error **errp)
3811 CharDriverState *chr;
3813 chr = qemu_chr_find(id);
3814 if (NULL == chr) {
3815 error_setg(errp, "Chardev '%s' not found", id);
3816 return;
3818 if (chr->chr_can_read || chr->chr_read ||
3819 chr->chr_event || chr->handler_opaque) {
3820 error_setg(errp, "Chardev '%s' is busy", id);
3821 return;
3823 qemu_chr_delete(chr);
3826 static void register_types(void)
3828 register_char_driver_qapi("null", CHARDEV_BACKEND_KIND_NULL, NULL);
3829 register_char_driver("socket", qemu_chr_open_socket);
3830 register_char_driver("udp", qemu_chr_open_udp);
3831 register_char_driver_qapi("memory", CHARDEV_BACKEND_KIND_MEMORY,
3832 qemu_chr_parse_memory);
3833 register_char_driver_qapi("file", CHARDEV_BACKEND_KIND_FILE,
3834 qemu_chr_parse_file_out);
3835 register_char_driver_qapi("stdio", CHARDEV_BACKEND_KIND_STDIO,
3836 qemu_chr_parse_stdio);
3837 register_char_driver_qapi("serial", CHARDEV_BACKEND_KIND_SERIAL,
3838 qemu_chr_parse_serial);
3839 register_char_driver_qapi("tty", CHARDEV_BACKEND_KIND_SERIAL,
3840 qemu_chr_parse_serial);
3841 register_char_driver_qapi("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
3842 qemu_chr_parse_parallel);
3843 register_char_driver_qapi("parport", CHARDEV_BACKEND_KIND_PARALLEL,
3844 qemu_chr_parse_parallel);
3845 register_char_driver_qapi("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
3846 register_char_driver_qapi("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
3847 register_char_driver_qapi("pipe", CHARDEV_BACKEND_KIND_PIPE,
3848 qemu_chr_parse_pipe);
3851 type_init(register_types);