qemu-io: Move qemu_strsep() to cutils.c
[qemu-kvm.git] / qemu-char.c
blobd04b429a034e4f35cfe3d156508d4170d320f4cb
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 #include <net/if.h>
80 #include <syslog.h>
81 #endif
82 #endif
83 #endif
85 #include "qemu/sockets.h"
86 #include "ui/qemu-spice.h"
88 #define READ_BUF_LEN 4096
90 /***********************************************************/
91 /* character device */
93 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
94 QTAILQ_HEAD_INITIALIZER(chardevs);
96 void qemu_chr_be_event(CharDriverState *s, int event)
98 /* Keep track if the char device is open */
99 switch (event) {
100 case CHR_EVENT_OPENED:
101 s->be_open = 1;
102 break;
103 case CHR_EVENT_CLOSED:
104 s->be_open = 0;
105 break;
108 if (!s->chr_event)
109 return;
110 s->chr_event(s->handler_opaque, event);
113 static gboolean qemu_chr_be_generic_open_bh(gpointer opaque)
115 CharDriverState *s = opaque;
116 qemu_chr_be_event(s, CHR_EVENT_OPENED);
117 s->idle_tag = 0;
118 return FALSE;
121 void qemu_chr_be_generic_open(CharDriverState *s)
123 if (s->idle_tag == 0) {
124 s->idle_tag = g_idle_add(qemu_chr_be_generic_open_bh, s);
128 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
130 return s->chr_write(s, buf, len);
133 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
135 int offset = 0;
136 int res;
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 if (res < 0) {
151 return res;
154 offset += res;
157 return offset;
160 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
162 if (!s->chr_ioctl)
163 return -ENOTSUP;
164 return s->chr_ioctl(s, cmd, arg);
167 int qemu_chr_be_can_write(CharDriverState *s)
169 if (!s->chr_can_read)
170 return 0;
171 return s->chr_can_read(s->handler_opaque);
174 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
176 if (s->chr_read) {
177 s->chr_read(s->handler_opaque, buf, len);
181 int qemu_chr_fe_get_msgfd(CharDriverState *s)
183 return s->get_msgfd ? s->get_msgfd(s) : -1;
186 int qemu_chr_add_client(CharDriverState *s, int fd)
188 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
191 void qemu_chr_accept_input(CharDriverState *s)
193 if (s->chr_accept_input)
194 s->chr_accept_input(s);
195 qemu_notify_event();
198 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
200 char buf[READ_BUF_LEN];
201 va_list ap;
202 va_start(ap, fmt);
203 vsnprintf(buf, sizeof(buf), fmt, ap);
204 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
205 va_end(ap);
208 void qemu_chr_add_handlers(CharDriverState *s,
209 IOCanReadHandler *fd_can_read,
210 IOReadHandler *fd_read,
211 IOEventHandler *fd_event,
212 void *opaque)
214 int fe_open;
216 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
217 fe_open = 0;
218 } else {
219 fe_open = 1;
221 s->chr_can_read = fd_can_read;
222 s->chr_read = fd_read;
223 s->chr_event = fd_event;
224 s->handler_opaque = opaque;
225 if (s->chr_update_read_handler)
226 s->chr_update_read_handler(s);
228 if (!s->explicit_fe_open) {
229 qemu_chr_fe_set_open(s, fe_open);
232 /* We're connecting to an already opened device, so let's make sure we
233 also get the open event */
234 if (fe_open && s->be_open) {
235 qemu_chr_be_generic_open(s);
239 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
241 return len;
244 static CharDriverState *qemu_chr_open_null(void)
246 CharDriverState *chr;
248 chr = g_malloc0(sizeof(CharDriverState));
249 chr->chr_write = null_chr_write;
250 return chr;
253 /* MUX driver for serial I/O splitting */
254 #define MAX_MUX 4
255 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
256 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
257 typedef struct {
258 IOCanReadHandler *chr_can_read[MAX_MUX];
259 IOReadHandler *chr_read[MAX_MUX];
260 IOEventHandler *chr_event[MAX_MUX];
261 void *ext_opaque[MAX_MUX];
262 CharDriverState *drv;
263 int focus;
264 int mux_cnt;
265 int term_got_escape;
266 int max_size;
267 /* Intermediate input buffer allows to catch escape sequences even if the
268 currently active device is not accepting any input - but only until it
269 is full as well. */
270 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
271 int prod[MAX_MUX];
272 int cons[MAX_MUX];
273 int timestamps;
274 int linestart;
275 int64_t timestamps_start;
276 } MuxDriver;
279 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
281 MuxDriver *d = chr->opaque;
282 int ret;
283 if (!d->timestamps) {
284 ret = d->drv->chr_write(d->drv, buf, len);
285 } else {
286 int i;
288 ret = 0;
289 for (i = 0; i < len; i++) {
290 if (d->linestart) {
291 char buf1[64];
292 int64_t ti;
293 int secs;
295 ti = qemu_get_clock_ms(rt_clock);
296 if (d->timestamps_start == -1)
297 d->timestamps_start = ti;
298 ti -= d->timestamps_start;
299 secs = ti / 1000;
300 snprintf(buf1, sizeof(buf1),
301 "[%02d:%02d:%02d.%03d] ",
302 secs / 3600,
303 (secs / 60) % 60,
304 secs % 60,
305 (int)(ti % 1000));
306 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
307 d->linestart = 0;
309 ret += d->drv->chr_write(d->drv, buf+i, 1);
310 if (buf[i] == '\n') {
311 d->linestart = 1;
315 return ret;
318 static const char * const mux_help[] = {
319 "% h print this help\n\r",
320 "% x exit emulator\n\r",
321 "% s save disk data back to file (if -snapshot)\n\r",
322 "% t toggle console timestamps\n\r"
323 "% b send break (magic sysrq)\n\r",
324 "% c switch between console and monitor\n\r",
325 "% % sends %\n\r",
326 NULL
329 int term_escape_char = 0x01; /* ctrl-a is used for escape */
330 static void mux_print_help(CharDriverState *chr)
332 int i, j;
333 char ebuf[15] = "Escape-Char";
334 char cbuf[50] = "\n\r";
336 if (term_escape_char > 0 && term_escape_char < 26) {
337 snprintf(cbuf, sizeof(cbuf), "\n\r");
338 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
339 } else {
340 snprintf(cbuf, sizeof(cbuf),
341 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
342 term_escape_char);
344 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
345 for (i = 0; mux_help[i] != NULL; i++) {
346 for (j=0; mux_help[i][j] != '\0'; j++) {
347 if (mux_help[i][j] == '%')
348 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
349 else
350 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
355 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
357 if (d->chr_event[mux_nr])
358 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
361 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
363 if (d->term_got_escape) {
364 d->term_got_escape = 0;
365 if (ch == term_escape_char)
366 goto send_char;
367 switch(ch) {
368 case '?':
369 case 'h':
370 mux_print_help(chr);
371 break;
372 case 'x':
374 const char *term = "QEMU: Terminated\n\r";
375 chr->chr_write(chr,(uint8_t *)term,strlen(term));
376 exit(0);
377 break;
379 case 's':
380 bdrv_commit_all();
381 break;
382 case 'b':
383 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
384 break;
385 case 'c':
386 /* Switch to the next registered device */
387 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
388 d->focus++;
389 if (d->focus >= d->mux_cnt)
390 d->focus = 0;
391 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
392 break;
393 case 't':
394 d->timestamps = !d->timestamps;
395 d->timestamps_start = -1;
396 d->linestart = 0;
397 break;
399 } else if (ch == term_escape_char) {
400 d->term_got_escape = 1;
401 } else {
402 send_char:
403 return 1;
405 return 0;
408 static void mux_chr_accept_input(CharDriverState *chr)
410 MuxDriver *d = chr->opaque;
411 int m = d->focus;
413 while (d->prod[m] != d->cons[m] &&
414 d->chr_can_read[m] &&
415 d->chr_can_read[m](d->ext_opaque[m])) {
416 d->chr_read[m](d->ext_opaque[m],
417 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
421 static int mux_chr_can_read(void *opaque)
423 CharDriverState *chr = opaque;
424 MuxDriver *d = chr->opaque;
425 int m = d->focus;
427 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
428 return 1;
429 if (d->chr_can_read[m])
430 return d->chr_can_read[m](d->ext_opaque[m]);
431 return 0;
434 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
436 CharDriverState *chr = opaque;
437 MuxDriver *d = chr->opaque;
438 int m = d->focus;
439 int i;
441 mux_chr_accept_input (opaque);
443 for(i = 0; i < size; i++)
444 if (mux_proc_byte(chr, d, buf[i])) {
445 if (d->prod[m] == d->cons[m] &&
446 d->chr_can_read[m] &&
447 d->chr_can_read[m](d->ext_opaque[m]))
448 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
449 else
450 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
454 static void mux_chr_event(void *opaque, int event)
456 CharDriverState *chr = opaque;
457 MuxDriver *d = chr->opaque;
458 int i;
460 /* Send the event to all registered listeners */
461 for (i = 0; i < d->mux_cnt; i++)
462 mux_chr_send_event(d, i, event);
465 static void mux_chr_update_read_handler(CharDriverState *chr)
467 MuxDriver *d = chr->opaque;
469 if (d->mux_cnt >= MAX_MUX) {
470 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
471 return;
473 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
474 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
475 d->chr_read[d->mux_cnt] = chr->chr_read;
476 d->chr_event[d->mux_cnt] = chr->chr_event;
477 /* Fix up the real driver with mux routines */
478 if (d->mux_cnt == 0) {
479 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
480 mux_chr_event, chr);
482 if (d->focus != -1) {
483 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
485 d->focus = d->mux_cnt;
486 d->mux_cnt++;
487 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
490 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
492 CharDriverState *chr;
493 MuxDriver *d;
495 chr = g_malloc0(sizeof(CharDriverState));
496 d = g_malloc0(sizeof(MuxDriver));
498 chr->opaque = d;
499 d->drv = drv;
500 d->focus = -1;
501 chr->chr_write = mux_chr_write;
502 chr->chr_update_read_handler = mux_chr_update_read_handler;
503 chr->chr_accept_input = mux_chr_accept_input;
504 /* Frontend guest-open / -close notification is not support with muxes */
505 chr->chr_set_fe_open = NULL;
507 /* Muxes are always open on creation */
508 qemu_chr_be_generic_open(chr);
510 return chr;
514 #ifdef _WIN32
515 int send_all(int fd, const void *buf, int len1)
517 int ret, len;
519 len = len1;
520 while (len > 0) {
521 ret = send(fd, buf, len, 0);
522 if (ret < 0) {
523 errno = WSAGetLastError();
524 if (errno != WSAEWOULDBLOCK) {
525 return -1;
527 } else if (ret == 0) {
528 break;
529 } else {
530 buf += ret;
531 len -= ret;
534 return len1 - len;
537 #else
539 int send_all(int fd, const void *_buf, int len1)
541 int ret, len;
542 const uint8_t *buf = _buf;
544 len = len1;
545 while (len > 0) {
546 ret = write(fd, buf, len);
547 if (ret < 0) {
548 if (errno != EINTR && errno != EAGAIN)
549 return -1;
550 } else if (ret == 0) {
551 break;
552 } else {
553 buf += ret;
554 len -= ret;
557 return len1 - len;
560 int recv_all(int fd, void *_buf, int len1, bool single_read)
562 int ret, len;
563 uint8_t *buf = _buf;
565 len = len1;
566 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
567 if (ret < 0) {
568 if (errno != EINTR && errno != EAGAIN) {
569 return -1;
571 continue;
572 } else {
573 if (single_read) {
574 return ret;
576 buf += ret;
577 len -= ret;
580 return len1 - len;
583 #endif /* !_WIN32 */
585 typedef struct IOWatchPoll
587 GSource parent;
589 GIOChannel *channel;
590 GSource *src;
592 IOCanReadHandler *fd_can_read;
593 GSourceFunc fd_read;
594 void *opaque;
595 } IOWatchPoll;
597 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
599 return container_of(source, IOWatchPoll, parent);
602 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
604 IOWatchPoll *iwp = io_watch_poll_from_source(source);
605 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
606 bool was_active = iwp->src != NULL;
607 if (was_active == now_active) {
608 return FALSE;
611 if (now_active) {
612 iwp->src = g_io_create_watch(iwp->channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
613 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
614 g_source_attach(iwp->src, NULL);
615 } else {
616 g_source_destroy(iwp->src);
617 g_source_unref(iwp->src);
618 iwp->src = NULL;
620 return FALSE;
623 static gboolean io_watch_poll_check(GSource *source)
625 return FALSE;
628 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
629 gpointer user_data)
631 abort();
634 static void io_watch_poll_finalize(GSource *source)
636 /* Due to a glib bug, removing the last reference to a source
637 * inside a finalize callback causes recursive locking (and a
638 * deadlock). This is not a problem inside other callbacks,
639 * including dispatch callbacks, so we call io_remove_watch_poll
640 * to remove this source. At this point, iwp->src must
641 * be NULL, or we would leak it.
643 * This would be solved much more elegantly by child sources,
644 * but we support older glib versions that do not have them.
646 IOWatchPoll *iwp = io_watch_poll_from_source(source);
647 assert(iwp->src == NULL);
650 static GSourceFuncs io_watch_poll_funcs = {
651 .prepare = io_watch_poll_prepare,
652 .check = io_watch_poll_check,
653 .dispatch = io_watch_poll_dispatch,
654 .finalize = io_watch_poll_finalize,
657 /* Can only be used for read */
658 static guint io_add_watch_poll(GIOChannel *channel,
659 IOCanReadHandler *fd_can_read,
660 GIOFunc fd_read,
661 gpointer user_data)
663 IOWatchPoll *iwp;
664 int tag;
666 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
667 iwp->fd_can_read = fd_can_read;
668 iwp->opaque = user_data;
669 iwp->channel = channel;
670 iwp->fd_read = (GSourceFunc) fd_read;
671 iwp->src = NULL;
673 tag = g_source_attach(&iwp->parent, NULL);
674 g_source_unref(&iwp->parent);
675 return tag;
678 static void io_remove_watch_poll(guint tag)
680 GSource *source;
681 IOWatchPoll *iwp;
683 g_return_if_fail (tag > 0);
685 source = g_main_context_find_source_by_id(NULL, tag);
686 g_return_if_fail (source != NULL);
688 iwp = io_watch_poll_from_source(source);
689 if (iwp->src) {
690 g_source_destroy(iwp->src);
691 g_source_unref(iwp->src);
692 iwp->src = NULL;
694 g_source_destroy(&iwp->parent);
697 #ifndef _WIN32
698 static GIOChannel *io_channel_from_fd(int fd)
700 GIOChannel *chan;
702 if (fd == -1) {
703 return NULL;
706 chan = g_io_channel_unix_new(fd);
708 g_io_channel_set_encoding(chan, NULL, NULL);
709 g_io_channel_set_buffered(chan, FALSE);
711 return chan;
713 #endif
715 static GIOChannel *io_channel_from_socket(int fd)
717 GIOChannel *chan;
719 if (fd == -1) {
720 return NULL;
723 #ifdef _WIN32
724 chan = g_io_channel_win32_new_socket(fd);
725 #else
726 chan = g_io_channel_unix_new(fd);
727 #endif
729 g_io_channel_set_encoding(chan, NULL, NULL);
730 g_io_channel_set_buffered(chan, FALSE);
732 return chan;
735 static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
737 GIOStatus status;
738 size_t offset;
740 offset = 0;
741 while (offset < len) {
742 gsize bytes_written;
744 status = g_io_channel_write_chars(fd, buf + offset, len - offset,
745 &bytes_written, NULL);
746 if (status != G_IO_STATUS_NORMAL) {
747 if (status == G_IO_STATUS_AGAIN) {
748 /* If we've written any data, return a partial write. */
749 if (offset) {
750 break;
752 errno = EAGAIN;
753 } else {
754 errno = EINVAL;
757 return -1;
758 } else if (status == G_IO_STATUS_EOF) {
759 break;
762 offset += bytes_written;
765 return offset;
768 #ifndef _WIN32
770 typedef struct FDCharDriver {
771 CharDriverState *chr;
772 GIOChannel *fd_in, *fd_out;
773 guint fd_in_tag;
774 int max_size;
775 QTAILQ_ENTRY(FDCharDriver) node;
776 } FDCharDriver;
778 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
780 FDCharDriver *s = chr->opaque;
782 return io_channel_send(s->fd_out, buf, len);
785 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
787 CharDriverState *chr = opaque;
788 FDCharDriver *s = chr->opaque;
789 int len;
790 uint8_t buf[READ_BUF_LEN];
791 GIOStatus status;
792 gsize bytes_read;
794 len = sizeof(buf);
795 if (len > s->max_size) {
796 len = s->max_size;
798 if (len == 0) {
799 return TRUE;
802 status = g_io_channel_read_chars(chan, (gchar *)buf,
803 len, &bytes_read, NULL);
804 if (status == G_IO_STATUS_EOF) {
805 if (s->fd_in_tag) {
806 io_remove_watch_poll(s->fd_in_tag);
807 s->fd_in_tag = 0;
809 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
810 return FALSE;
812 if (status == G_IO_STATUS_NORMAL) {
813 qemu_chr_be_write(chr, buf, bytes_read);
816 return TRUE;
819 static int fd_chr_read_poll(void *opaque)
821 CharDriverState *chr = opaque;
822 FDCharDriver *s = chr->opaque;
824 s->max_size = qemu_chr_be_can_write(chr);
825 return s->max_size;
828 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
830 FDCharDriver *s = chr->opaque;
831 return g_io_create_watch(s->fd_out, cond);
834 static void fd_chr_update_read_handler(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 s->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll, fd_chr_read, chr);
848 static void fd_chr_close(struct CharDriverState *chr)
850 FDCharDriver *s = chr->opaque;
852 if (s->fd_in_tag) {
853 io_remove_watch_poll(s->fd_in_tag);
854 s->fd_in_tag = 0;
857 if (s->fd_in) {
858 g_io_channel_unref(s->fd_in);
860 if (s->fd_out) {
861 g_io_channel_unref(s->fd_out);
864 g_free(s);
865 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
868 /* open a character device to a unix fd */
869 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
871 CharDriverState *chr;
872 FDCharDriver *s;
874 chr = g_malloc0(sizeof(CharDriverState));
875 s = g_malloc0(sizeof(FDCharDriver));
876 s->fd_in = io_channel_from_fd(fd_in);
877 s->fd_out = io_channel_from_fd(fd_out);
878 fcntl(fd_out, F_SETFL, O_NONBLOCK);
879 s->chr = chr;
880 chr->opaque = s;
881 chr->chr_add_watch = fd_chr_add_watch;
882 chr->chr_write = fd_chr_write;
883 chr->chr_update_read_handler = fd_chr_update_read_handler;
884 chr->chr_close = fd_chr_close;
886 qemu_chr_be_generic_open(chr);
888 return chr;
891 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
893 int fd_in, fd_out;
894 char filename_in[256], filename_out[256];
895 const char *filename = opts->device;
897 if (filename == NULL) {
898 fprintf(stderr, "chardev: pipe: no filename given\n");
899 return NULL;
902 snprintf(filename_in, 256, "%s.in", filename);
903 snprintf(filename_out, 256, "%s.out", filename);
904 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
905 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
906 if (fd_in < 0 || fd_out < 0) {
907 if (fd_in >= 0)
908 close(fd_in);
909 if (fd_out >= 0)
910 close(fd_out);
911 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
912 if (fd_in < 0) {
913 return NULL;
916 return qemu_chr_open_fd(fd_in, fd_out);
919 /* init terminal so that we can grab keys */
920 static struct termios oldtty;
921 static int old_fd0_flags;
922 static bool stdio_allow_signal;
924 static void term_exit(void)
926 tcsetattr (0, TCSANOW, &oldtty);
927 fcntl(0, F_SETFL, old_fd0_flags);
930 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
932 struct termios tty;
934 tty = oldtty;
935 if (!echo) {
936 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
937 |INLCR|IGNCR|ICRNL|IXON);
938 tty.c_oflag |= OPOST;
939 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
940 tty.c_cflag &= ~(CSIZE|PARENB);
941 tty.c_cflag |= CS8;
942 tty.c_cc[VMIN] = 1;
943 tty.c_cc[VTIME] = 0;
945 /* if graphical mode, we allow Ctrl-C handling */
946 if (!stdio_allow_signal)
947 tty.c_lflag &= ~ISIG;
949 tcsetattr (0, TCSANOW, &tty);
952 static void qemu_chr_close_stdio(struct CharDriverState *chr)
954 term_exit();
955 fd_chr_close(chr);
958 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
960 CharDriverState *chr;
962 if (is_daemonized()) {
963 error_report("cannot use stdio with -daemonize");
964 return NULL;
966 old_fd0_flags = fcntl(0, F_GETFL);
967 tcgetattr (0, &oldtty);
968 fcntl(0, F_SETFL, O_NONBLOCK);
969 atexit(term_exit);
971 chr = qemu_chr_open_fd(0, 1);
972 chr->chr_close = qemu_chr_close_stdio;
973 chr->chr_set_echo = qemu_chr_set_echo_stdio;
974 stdio_allow_signal = display_type != DT_NOGRAPHIC;
975 if (opts->has_signal) {
976 stdio_allow_signal = opts->signal;
978 qemu_chr_fe_set_echo(chr, false);
980 return chr;
983 #ifdef __sun__
984 /* Once Solaris has openpty(), this is going to be removed. */
985 static int openpty(int *amaster, int *aslave, char *name,
986 struct termios *termp, struct winsize *winp)
988 const char *slave;
989 int mfd = -1, sfd = -1;
991 *amaster = *aslave = -1;
993 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
994 if (mfd < 0)
995 goto err;
997 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
998 goto err;
1000 if ((slave = ptsname(mfd)) == NULL)
1001 goto err;
1003 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
1004 goto err;
1006 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
1007 (termp != NULL && tcgetattr(sfd, termp) < 0))
1008 goto err;
1010 if (amaster)
1011 *amaster = mfd;
1012 if (aslave)
1013 *aslave = sfd;
1014 if (winp)
1015 ioctl(sfd, TIOCSWINSZ, winp);
1017 return 0;
1019 err:
1020 if (sfd != -1)
1021 close(sfd);
1022 close(mfd);
1023 return -1;
1026 static void cfmakeraw (struct termios *termios_p)
1028 termios_p->c_iflag &=
1029 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
1030 termios_p->c_oflag &= ~OPOST;
1031 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
1032 termios_p->c_cflag &= ~(CSIZE|PARENB);
1033 termios_p->c_cflag |= CS8;
1035 termios_p->c_cc[VMIN] = 0;
1036 termios_p->c_cc[VTIME] = 0;
1038 #endif
1040 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1041 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1042 || defined(__GLIBC__)
1044 #define HAVE_CHARDEV_TTY 1
1046 typedef struct {
1047 GIOChannel *fd;
1048 guint fd_tag;
1049 int connected;
1050 int read_bytes;
1051 guint timer_tag;
1052 } PtyCharDriver;
1054 static void pty_chr_update_read_handler(CharDriverState *chr);
1055 static void pty_chr_state(CharDriverState *chr, int connected);
1057 static gboolean pty_chr_timer(gpointer opaque)
1059 struct CharDriverState *chr = opaque;
1060 PtyCharDriver *s = chr->opaque;
1062 if (s->connected) {
1063 goto out;
1066 /* Next poll ... */
1067 pty_chr_update_read_handler(chr);
1069 out:
1070 s->timer_tag = 0;
1071 return FALSE;
1074 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1076 PtyCharDriver *s = chr->opaque;
1078 if (s->timer_tag) {
1079 g_source_remove(s->timer_tag);
1080 s->timer_tag = 0;
1083 if (ms == 1000) {
1084 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1085 } else {
1086 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1090 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1092 PtyCharDriver *s = chr->opaque;
1094 if (!s->connected) {
1095 /* guest sends data, check for (re-)connect */
1096 pty_chr_update_read_handler(chr);
1097 return 0;
1099 return io_channel_send(s->fd, buf, len);
1102 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1104 PtyCharDriver *s = chr->opaque;
1105 return g_io_create_watch(s->fd, cond);
1108 static int pty_chr_read_poll(void *opaque)
1110 CharDriverState *chr = opaque;
1111 PtyCharDriver *s = chr->opaque;
1113 s->read_bytes = qemu_chr_be_can_write(chr);
1114 return s->read_bytes;
1117 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1119 CharDriverState *chr = opaque;
1120 PtyCharDriver *s = chr->opaque;
1121 gsize size, len;
1122 uint8_t buf[READ_BUF_LEN];
1123 GIOStatus status;
1125 len = sizeof(buf);
1126 if (len > s->read_bytes)
1127 len = s->read_bytes;
1128 if (len == 0) {
1129 return TRUE;
1131 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1132 if (status != G_IO_STATUS_NORMAL) {
1133 pty_chr_state(chr, 0);
1134 return FALSE;
1135 } else {
1136 pty_chr_state(chr, 1);
1137 qemu_chr_be_write(chr, buf, size);
1139 return TRUE;
1142 static void pty_chr_update_read_handler(CharDriverState *chr)
1144 PtyCharDriver *s = chr->opaque;
1145 GPollFD pfd;
1147 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1148 pfd.events = G_IO_OUT;
1149 pfd.revents = 0;
1150 g_poll(&pfd, 1, 0);
1151 if (pfd.revents & G_IO_HUP) {
1152 pty_chr_state(chr, 0);
1153 } else {
1154 pty_chr_state(chr, 1);
1158 static void pty_chr_state(CharDriverState *chr, int connected)
1160 PtyCharDriver *s = chr->opaque;
1162 if (!connected) {
1163 if (s->fd_tag) {
1164 io_remove_watch_poll(s->fd_tag);
1165 s->fd_tag = 0;
1167 s->connected = 0;
1168 /* (re-)connect poll interval for idle guests: once per second.
1169 * We check more frequently in case the guests sends data to
1170 * the virtual device linked to our pty. */
1171 pty_chr_rearm_timer(chr, 1000);
1172 } else {
1173 if (s->timer_tag) {
1174 g_source_remove(s->timer_tag);
1175 s->timer_tag = 0;
1177 if (!s->connected) {
1178 qemu_chr_be_generic_open(chr);
1179 s->connected = 1;
1180 s->fd_tag = io_add_watch_poll(s->fd, pty_chr_read_poll, pty_chr_read, chr);
1186 static void pty_chr_close(struct CharDriverState *chr)
1188 PtyCharDriver *s = chr->opaque;
1189 int fd;
1191 if (s->fd_tag) {
1192 io_remove_watch_poll(s->fd_tag);
1193 s->fd_tag = 0;
1195 fd = g_io_channel_unix_get_fd(s->fd);
1196 g_io_channel_unref(s->fd);
1197 close(fd);
1198 if (s->timer_tag) {
1199 g_source_remove(s->timer_tag);
1200 s->timer_tag = 0;
1202 g_free(s);
1203 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1206 static CharDriverState *qemu_chr_open_pty(const char *id,
1207 ChardevReturn *ret)
1209 CharDriverState *chr;
1210 PtyCharDriver *s;
1211 struct termios tty;
1212 int master_fd, slave_fd;
1213 #if defined(__OpenBSD__) || defined(__DragonFly__)
1214 char pty_name[PATH_MAX];
1215 #define q_ptsname(x) pty_name
1216 #else
1217 char *pty_name = NULL;
1218 #define q_ptsname(x) ptsname(x)
1219 #endif
1221 if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1222 return NULL;
1225 /* Set raw attributes on the pty. */
1226 tcgetattr(slave_fd, &tty);
1227 cfmakeraw(&tty);
1228 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1229 close(slave_fd);
1231 chr = g_malloc0(sizeof(CharDriverState));
1233 chr->filename = g_strdup_printf("pty:%s", q_ptsname(master_fd));
1234 ret->pty = g_strdup(q_ptsname(master_fd));
1235 ret->has_pty = true;
1237 fprintf(stderr, "char device redirected to %s (label %s)\n",
1238 q_ptsname(master_fd), id);
1240 s = g_malloc0(sizeof(PtyCharDriver));
1241 chr->opaque = s;
1242 chr->chr_write = pty_chr_write;
1243 chr->chr_update_read_handler = pty_chr_update_read_handler;
1244 chr->chr_close = pty_chr_close;
1245 chr->chr_add_watch = pty_chr_add_watch;
1247 s->fd = io_channel_from_fd(master_fd);
1248 s->timer_tag = 0;
1250 return chr;
1253 static void tty_serial_init(int fd, int speed,
1254 int parity, int data_bits, int stop_bits)
1256 struct termios tty;
1257 speed_t spd;
1259 #if 0
1260 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1261 speed, parity, data_bits, stop_bits);
1262 #endif
1263 tcgetattr (fd, &tty);
1265 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1266 speed = speed * 10 / 11;
1267 do {
1268 check_speed(50);
1269 check_speed(75);
1270 check_speed(110);
1271 check_speed(134);
1272 check_speed(150);
1273 check_speed(200);
1274 check_speed(300);
1275 check_speed(600);
1276 check_speed(1200);
1277 check_speed(1800);
1278 check_speed(2400);
1279 check_speed(4800);
1280 check_speed(9600);
1281 check_speed(19200);
1282 check_speed(38400);
1283 /* Non-Posix values follow. They may be unsupported on some systems. */
1284 check_speed(57600);
1285 check_speed(115200);
1286 #ifdef B230400
1287 check_speed(230400);
1288 #endif
1289 #ifdef B460800
1290 check_speed(460800);
1291 #endif
1292 #ifdef B500000
1293 check_speed(500000);
1294 #endif
1295 #ifdef B576000
1296 check_speed(576000);
1297 #endif
1298 #ifdef B921600
1299 check_speed(921600);
1300 #endif
1301 #ifdef B1000000
1302 check_speed(1000000);
1303 #endif
1304 #ifdef B1152000
1305 check_speed(1152000);
1306 #endif
1307 #ifdef B1500000
1308 check_speed(1500000);
1309 #endif
1310 #ifdef B2000000
1311 check_speed(2000000);
1312 #endif
1313 #ifdef B2500000
1314 check_speed(2500000);
1315 #endif
1316 #ifdef B3000000
1317 check_speed(3000000);
1318 #endif
1319 #ifdef B3500000
1320 check_speed(3500000);
1321 #endif
1322 #ifdef B4000000
1323 check_speed(4000000);
1324 #endif
1325 spd = B115200;
1326 } while (0);
1328 cfsetispeed(&tty, spd);
1329 cfsetospeed(&tty, spd);
1331 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1332 |INLCR|IGNCR|ICRNL|IXON);
1333 tty.c_oflag |= OPOST;
1334 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1335 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1336 switch(data_bits) {
1337 default:
1338 case 8:
1339 tty.c_cflag |= CS8;
1340 break;
1341 case 7:
1342 tty.c_cflag |= CS7;
1343 break;
1344 case 6:
1345 tty.c_cflag |= CS6;
1346 break;
1347 case 5:
1348 tty.c_cflag |= CS5;
1349 break;
1351 switch(parity) {
1352 default:
1353 case 'N':
1354 break;
1355 case 'E':
1356 tty.c_cflag |= PARENB;
1357 break;
1358 case 'O':
1359 tty.c_cflag |= PARENB | PARODD;
1360 break;
1362 if (stop_bits == 2)
1363 tty.c_cflag |= CSTOPB;
1365 tcsetattr (fd, TCSANOW, &tty);
1368 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1370 FDCharDriver *s = chr->opaque;
1372 switch(cmd) {
1373 case CHR_IOCTL_SERIAL_SET_PARAMS:
1375 QEMUSerialSetParams *ssp = arg;
1376 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1377 ssp->speed, ssp->parity,
1378 ssp->data_bits, ssp->stop_bits);
1380 break;
1381 case CHR_IOCTL_SERIAL_SET_BREAK:
1383 int enable = *(int *)arg;
1384 if (enable) {
1385 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1388 break;
1389 case CHR_IOCTL_SERIAL_GET_TIOCM:
1391 int sarg = 0;
1392 int *targ = (int *)arg;
1393 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1394 *targ = 0;
1395 if (sarg & TIOCM_CTS)
1396 *targ |= CHR_TIOCM_CTS;
1397 if (sarg & TIOCM_CAR)
1398 *targ |= CHR_TIOCM_CAR;
1399 if (sarg & TIOCM_DSR)
1400 *targ |= CHR_TIOCM_DSR;
1401 if (sarg & TIOCM_RI)
1402 *targ |= CHR_TIOCM_RI;
1403 if (sarg & TIOCM_DTR)
1404 *targ |= CHR_TIOCM_DTR;
1405 if (sarg & TIOCM_RTS)
1406 *targ |= CHR_TIOCM_RTS;
1408 break;
1409 case CHR_IOCTL_SERIAL_SET_TIOCM:
1411 int sarg = *(int *)arg;
1412 int targ = 0;
1413 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1414 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1415 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1416 if (sarg & CHR_TIOCM_CTS)
1417 targ |= TIOCM_CTS;
1418 if (sarg & CHR_TIOCM_CAR)
1419 targ |= TIOCM_CAR;
1420 if (sarg & CHR_TIOCM_DSR)
1421 targ |= TIOCM_DSR;
1422 if (sarg & CHR_TIOCM_RI)
1423 targ |= TIOCM_RI;
1424 if (sarg & CHR_TIOCM_DTR)
1425 targ |= TIOCM_DTR;
1426 if (sarg & CHR_TIOCM_RTS)
1427 targ |= TIOCM_RTS;
1428 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1430 break;
1431 default:
1432 return -ENOTSUP;
1434 return 0;
1437 static void qemu_chr_close_tty(CharDriverState *chr)
1439 FDCharDriver *s = chr->opaque;
1440 int fd = -1;
1442 if (s) {
1443 fd = g_io_channel_unix_get_fd(s->fd_in);
1446 fd_chr_close(chr);
1448 if (fd >= 0) {
1449 close(fd);
1453 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1455 CharDriverState *chr;
1457 tty_serial_init(fd, 115200, 'N', 8, 1);
1458 chr = qemu_chr_open_fd(fd, fd);
1459 chr->chr_ioctl = tty_serial_ioctl;
1460 chr->chr_close = qemu_chr_close_tty;
1461 return chr;
1463 #endif /* __linux__ || __sun__ */
1465 #if defined(__linux__)
1467 #define HAVE_CHARDEV_PARPORT 1
1469 typedef struct {
1470 int fd;
1471 int mode;
1472 } ParallelCharDriver;
1474 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1476 if (s->mode != mode) {
1477 int m = mode;
1478 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1479 return 0;
1480 s->mode = mode;
1482 return 1;
1485 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1487 ParallelCharDriver *drv = chr->opaque;
1488 int fd = drv->fd;
1489 uint8_t b;
1491 switch(cmd) {
1492 case CHR_IOCTL_PP_READ_DATA:
1493 if (ioctl(fd, PPRDATA, &b) < 0)
1494 return -ENOTSUP;
1495 *(uint8_t *)arg = b;
1496 break;
1497 case CHR_IOCTL_PP_WRITE_DATA:
1498 b = *(uint8_t *)arg;
1499 if (ioctl(fd, PPWDATA, &b) < 0)
1500 return -ENOTSUP;
1501 break;
1502 case CHR_IOCTL_PP_READ_CONTROL:
1503 if (ioctl(fd, PPRCONTROL, &b) < 0)
1504 return -ENOTSUP;
1505 /* Linux gives only the lowest bits, and no way to know data
1506 direction! For better compatibility set the fixed upper
1507 bits. */
1508 *(uint8_t *)arg = b | 0xc0;
1509 break;
1510 case CHR_IOCTL_PP_WRITE_CONTROL:
1511 b = *(uint8_t *)arg;
1512 if (ioctl(fd, PPWCONTROL, &b) < 0)
1513 return -ENOTSUP;
1514 break;
1515 case CHR_IOCTL_PP_READ_STATUS:
1516 if (ioctl(fd, PPRSTATUS, &b) < 0)
1517 return -ENOTSUP;
1518 *(uint8_t *)arg = b;
1519 break;
1520 case CHR_IOCTL_PP_DATA_DIR:
1521 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1522 return -ENOTSUP;
1523 break;
1524 case CHR_IOCTL_PP_EPP_READ_ADDR:
1525 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1526 struct ParallelIOArg *parg = arg;
1527 int n = read(fd, parg->buffer, parg->count);
1528 if (n != parg->count) {
1529 return -EIO;
1532 break;
1533 case CHR_IOCTL_PP_EPP_READ:
1534 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1535 struct ParallelIOArg *parg = arg;
1536 int n = read(fd, parg->buffer, parg->count);
1537 if (n != parg->count) {
1538 return -EIO;
1541 break;
1542 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1543 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1544 struct ParallelIOArg *parg = arg;
1545 int n = write(fd, parg->buffer, parg->count);
1546 if (n != parg->count) {
1547 return -EIO;
1550 break;
1551 case CHR_IOCTL_PP_EPP_WRITE:
1552 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1553 struct ParallelIOArg *parg = arg;
1554 int n = write(fd, parg->buffer, parg->count);
1555 if (n != parg->count) {
1556 return -EIO;
1559 break;
1560 default:
1561 return -ENOTSUP;
1563 return 0;
1566 static void pp_close(CharDriverState *chr)
1568 ParallelCharDriver *drv = chr->opaque;
1569 int fd = drv->fd;
1571 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1572 ioctl(fd, PPRELEASE);
1573 close(fd);
1574 g_free(drv);
1575 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1578 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1580 CharDriverState *chr;
1581 ParallelCharDriver *drv;
1583 if (ioctl(fd, PPCLAIM) < 0) {
1584 close(fd);
1585 return NULL;
1588 drv = g_malloc0(sizeof(ParallelCharDriver));
1589 drv->fd = fd;
1590 drv->mode = IEEE1284_MODE_COMPAT;
1592 chr = g_malloc0(sizeof(CharDriverState));
1593 chr->chr_write = null_chr_write;
1594 chr->chr_ioctl = pp_ioctl;
1595 chr->chr_close = pp_close;
1596 chr->opaque = drv;
1598 qemu_chr_be_generic_open(chr);
1600 return chr;
1602 #endif /* __linux__ */
1604 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1606 #define HAVE_CHARDEV_PARPORT 1
1608 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1610 int fd = (int)(intptr_t)chr->opaque;
1611 uint8_t b;
1613 switch(cmd) {
1614 case CHR_IOCTL_PP_READ_DATA:
1615 if (ioctl(fd, PPIGDATA, &b) < 0)
1616 return -ENOTSUP;
1617 *(uint8_t *)arg = b;
1618 break;
1619 case CHR_IOCTL_PP_WRITE_DATA:
1620 b = *(uint8_t *)arg;
1621 if (ioctl(fd, PPISDATA, &b) < 0)
1622 return -ENOTSUP;
1623 break;
1624 case CHR_IOCTL_PP_READ_CONTROL:
1625 if (ioctl(fd, PPIGCTRL, &b) < 0)
1626 return -ENOTSUP;
1627 *(uint8_t *)arg = b;
1628 break;
1629 case CHR_IOCTL_PP_WRITE_CONTROL:
1630 b = *(uint8_t *)arg;
1631 if (ioctl(fd, PPISCTRL, &b) < 0)
1632 return -ENOTSUP;
1633 break;
1634 case CHR_IOCTL_PP_READ_STATUS:
1635 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1636 return -ENOTSUP;
1637 *(uint8_t *)arg = b;
1638 break;
1639 default:
1640 return -ENOTSUP;
1642 return 0;
1645 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1647 CharDriverState *chr;
1649 chr = g_malloc0(sizeof(CharDriverState));
1650 chr->opaque = (void *)(intptr_t)fd;
1651 chr->chr_write = null_chr_write;
1652 chr->chr_ioctl = pp_ioctl;
1653 return chr;
1655 #endif
1657 #else /* _WIN32 */
1659 typedef struct {
1660 int max_size;
1661 HANDLE hcom, hrecv, hsend;
1662 OVERLAPPED orecv, osend;
1663 BOOL fpipe;
1664 DWORD len;
1665 } WinCharState;
1667 typedef struct {
1668 HANDLE hStdIn;
1669 HANDLE hInputReadyEvent;
1670 HANDLE hInputDoneEvent;
1671 HANDLE hInputThread;
1672 uint8_t win_stdio_buf;
1673 } WinStdioCharState;
1675 #define NSENDBUF 2048
1676 #define NRECVBUF 2048
1677 #define MAXCONNECT 1
1678 #define NTIMEOUT 5000
1680 static int win_chr_poll(void *opaque);
1681 static int win_chr_pipe_poll(void *opaque);
1683 static void win_chr_close(CharDriverState *chr)
1685 WinCharState *s = chr->opaque;
1687 if (s->hsend) {
1688 CloseHandle(s->hsend);
1689 s->hsend = NULL;
1691 if (s->hrecv) {
1692 CloseHandle(s->hrecv);
1693 s->hrecv = NULL;
1695 if (s->hcom) {
1696 CloseHandle(s->hcom);
1697 s->hcom = NULL;
1699 if (s->fpipe)
1700 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1701 else
1702 qemu_del_polling_cb(win_chr_poll, chr);
1704 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1707 static int win_chr_init(CharDriverState *chr, const char *filename)
1709 WinCharState *s = chr->opaque;
1710 COMMCONFIG comcfg;
1711 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1712 COMSTAT comstat;
1713 DWORD size;
1714 DWORD err;
1716 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1717 if (!s->hsend) {
1718 fprintf(stderr, "Failed CreateEvent\n");
1719 goto fail;
1721 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1722 if (!s->hrecv) {
1723 fprintf(stderr, "Failed CreateEvent\n");
1724 goto fail;
1727 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1728 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1729 if (s->hcom == INVALID_HANDLE_VALUE) {
1730 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1731 s->hcom = NULL;
1732 goto fail;
1735 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1736 fprintf(stderr, "Failed SetupComm\n");
1737 goto fail;
1740 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1741 size = sizeof(COMMCONFIG);
1742 GetDefaultCommConfig(filename, &comcfg, &size);
1743 comcfg.dcb.DCBlength = sizeof(DCB);
1744 CommConfigDialog(filename, NULL, &comcfg);
1746 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1747 fprintf(stderr, "Failed SetCommState\n");
1748 goto fail;
1751 if (!SetCommMask(s->hcom, EV_ERR)) {
1752 fprintf(stderr, "Failed SetCommMask\n");
1753 goto fail;
1756 cto.ReadIntervalTimeout = MAXDWORD;
1757 if (!SetCommTimeouts(s->hcom, &cto)) {
1758 fprintf(stderr, "Failed SetCommTimeouts\n");
1759 goto fail;
1762 if (!ClearCommError(s->hcom, &err, &comstat)) {
1763 fprintf(stderr, "Failed ClearCommError\n");
1764 goto fail;
1766 qemu_add_polling_cb(win_chr_poll, chr);
1767 return 0;
1769 fail:
1770 win_chr_close(chr);
1771 return -1;
1774 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1776 WinCharState *s = chr->opaque;
1777 DWORD len, ret, size, err;
1779 len = len1;
1780 ZeroMemory(&s->osend, sizeof(s->osend));
1781 s->osend.hEvent = s->hsend;
1782 while (len > 0) {
1783 if (s->hsend)
1784 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1785 else
1786 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1787 if (!ret) {
1788 err = GetLastError();
1789 if (err == ERROR_IO_PENDING) {
1790 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1791 if (ret) {
1792 buf += size;
1793 len -= size;
1794 } else {
1795 break;
1797 } else {
1798 break;
1800 } else {
1801 buf += size;
1802 len -= size;
1805 return len1 - len;
1808 static int win_chr_read_poll(CharDriverState *chr)
1810 WinCharState *s = chr->opaque;
1812 s->max_size = qemu_chr_be_can_write(chr);
1813 return s->max_size;
1816 static void win_chr_readfile(CharDriverState *chr)
1818 WinCharState *s = chr->opaque;
1819 int ret, err;
1820 uint8_t buf[READ_BUF_LEN];
1821 DWORD size;
1823 ZeroMemory(&s->orecv, sizeof(s->orecv));
1824 s->orecv.hEvent = s->hrecv;
1825 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1826 if (!ret) {
1827 err = GetLastError();
1828 if (err == ERROR_IO_PENDING) {
1829 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1833 if (size > 0) {
1834 qemu_chr_be_write(chr, buf, size);
1838 static void win_chr_read(CharDriverState *chr)
1840 WinCharState *s = chr->opaque;
1842 if (s->len > s->max_size)
1843 s->len = s->max_size;
1844 if (s->len == 0)
1845 return;
1847 win_chr_readfile(chr);
1850 static int win_chr_poll(void *opaque)
1852 CharDriverState *chr = opaque;
1853 WinCharState *s = chr->opaque;
1854 COMSTAT status;
1855 DWORD comerr;
1857 ClearCommError(s->hcom, &comerr, &status);
1858 if (status.cbInQue > 0) {
1859 s->len = status.cbInQue;
1860 win_chr_read_poll(chr);
1861 win_chr_read(chr);
1862 return 1;
1864 return 0;
1867 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1869 CharDriverState *chr;
1870 WinCharState *s;
1872 chr = g_malloc0(sizeof(CharDriverState));
1873 s = g_malloc0(sizeof(WinCharState));
1874 chr->opaque = s;
1875 chr->chr_write = win_chr_write;
1876 chr->chr_close = win_chr_close;
1878 if (win_chr_init(chr, filename) < 0) {
1879 g_free(s);
1880 g_free(chr);
1881 return NULL;
1883 qemu_chr_be_generic_open(chr);
1884 return chr;
1887 static int win_chr_pipe_poll(void *opaque)
1889 CharDriverState *chr = opaque;
1890 WinCharState *s = chr->opaque;
1891 DWORD size;
1893 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1894 if (size > 0) {
1895 s->len = size;
1896 win_chr_read_poll(chr);
1897 win_chr_read(chr);
1898 return 1;
1900 return 0;
1903 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1905 WinCharState *s = chr->opaque;
1906 OVERLAPPED ov;
1907 int ret;
1908 DWORD size;
1909 char openname[256];
1911 s->fpipe = TRUE;
1913 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1914 if (!s->hsend) {
1915 fprintf(stderr, "Failed CreateEvent\n");
1916 goto fail;
1918 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1919 if (!s->hrecv) {
1920 fprintf(stderr, "Failed CreateEvent\n");
1921 goto fail;
1924 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1925 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1926 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1927 PIPE_WAIT,
1928 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1929 if (s->hcom == INVALID_HANDLE_VALUE) {
1930 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1931 s->hcom = NULL;
1932 goto fail;
1935 ZeroMemory(&ov, sizeof(ov));
1936 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1937 ret = ConnectNamedPipe(s->hcom, &ov);
1938 if (ret) {
1939 fprintf(stderr, "Failed ConnectNamedPipe\n");
1940 goto fail;
1943 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1944 if (!ret) {
1945 fprintf(stderr, "Failed GetOverlappedResult\n");
1946 if (ov.hEvent) {
1947 CloseHandle(ov.hEvent);
1948 ov.hEvent = NULL;
1950 goto fail;
1953 if (ov.hEvent) {
1954 CloseHandle(ov.hEvent);
1955 ov.hEvent = NULL;
1957 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1958 return 0;
1960 fail:
1961 win_chr_close(chr);
1962 return -1;
1966 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
1968 const char *filename = opts->device;
1969 CharDriverState *chr;
1970 WinCharState *s;
1972 chr = g_malloc0(sizeof(CharDriverState));
1973 s = g_malloc0(sizeof(WinCharState));
1974 chr->opaque = s;
1975 chr->chr_write = win_chr_write;
1976 chr->chr_close = win_chr_close;
1978 if (win_chr_pipe_init(chr, filename) < 0) {
1979 g_free(s);
1980 g_free(chr);
1981 return NULL;
1983 qemu_chr_be_generic_open(chr);
1984 return chr;
1987 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1989 CharDriverState *chr;
1990 WinCharState *s;
1992 chr = g_malloc0(sizeof(CharDriverState));
1993 s = g_malloc0(sizeof(WinCharState));
1994 s->hcom = fd_out;
1995 chr->opaque = s;
1996 chr->chr_write = win_chr_write;
1997 qemu_chr_be_generic_open(chr);
1998 return chr;
2001 static CharDriverState *qemu_chr_open_win_con(void)
2003 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2006 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2008 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2009 DWORD dwSize;
2010 int len1;
2012 len1 = len;
2014 while (len1 > 0) {
2015 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2016 break;
2018 buf += dwSize;
2019 len1 -= dwSize;
2022 return len - len1;
2025 static void win_stdio_wait_func(void *opaque)
2027 CharDriverState *chr = opaque;
2028 WinStdioCharState *stdio = chr->opaque;
2029 INPUT_RECORD buf[4];
2030 int ret;
2031 DWORD dwSize;
2032 int i;
2034 ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
2035 &dwSize);
2037 if (!ret) {
2038 /* Avoid error storm */
2039 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2040 return;
2043 for (i = 0; i < dwSize; i++) {
2044 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2046 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2047 int j;
2048 if (kev->uChar.AsciiChar != 0) {
2049 for (j = 0; j < kev->wRepeatCount; j++) {
2050 if (qemu_chr_be_can_write(chr)) {
2051 uint8_t c = kev->uChar.AsciiChar;
2052 qemu_chr_be_write(chr, &c, 1);
2060 static DWORD WINAPI win_stdio_thread(LPVOID param)
2062 CharDriverState *chr = param;
2063 WinStdioCharState *stdio = chr->opaque;
2064 int ret;
2065 DWORD dwSize;
2067 while (1) {
2069 /* Wait for one byte */
2070 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2072 /* Exit in case of error, continue if nothing read */
2073 if (!ret) {
2074 break;
2076 if (!dwSize) {
2077 continue;
2080 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2081 if (stdio->win_stdio_buf == '\r') {
2082 continue;
2085 /* Signal the main thread and wait until the byte was eaten */
2086 if (!SetEvent(stdio->hInputReadyEvent)) {
2087 break;
2089 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2090 != WAIT_OBJECT_0) {
2091 break;
2095 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2096 return 0;
2099 static void win_stdio_thread_wait_func(void *opaque)
2101 CharDriverState *chr = opaque;
2102 WinStdioCharState *stdio = chr->opaque;
2104 if (qemu_chr_be_can_write(chr)) {
2105 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2108 SetEvent(stdio->hInputDoneEvent);
2111 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2113 WinStdioCharState *stdio = chr->opaque;
2114 DWORD dwMode = 0;
2116 GetConsoleMode(stdio->hStdIn, &dwMode);
2118 if (echo) {
2119 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2120 } else {
2121 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2125 static void win_stdio_close(CharDriverState *chr)
2127 WinStdioCharState *stdio = chr->opaque;
2129 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2130 CloseHandle(stdio->hInputReadyEvent);
2132 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2133 CloseHandle(stdio->hInputDoneEvent);
2135 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2136 TerminateThread(stdio->hInputThread, 0);
2139 g_free(chr->opaque);
2140 g_free(chr);
2143 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2145 CharDriverState *chr;
2146 WinStdioCharState *stdio;
2147 DWORD dwMode;
2148 int is_console = 0;
2150 chr = g_malloc0(sizeof(CharDriverState));
2151 stdio = g_malloc0(sizeof(WinStdioCharState));
2153 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2154 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2155 fprintf(stderr, "cannot open stdio: invalid handle\n");
2156 exit(1);
2159 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2161 chr->opaque = stdio;
2162 chr->chr_write = win_stdio_write;
2163 chr->chr_close = win_stdio_close;
2165 if (is_console) {
2166 if (qemu_add_wait_object(stdio->hStdIn,
2167 win_stdio_wait_func, chr)) {
2168 fprintf(stderr, "qemu_add_wait_object: failed\n");
2170 } else {
2171 DWORD dwId;
2173 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2174 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2175 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2176 chr, 0, &dwId);
2178 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2179 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2180 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2181 fprintf(stderr, "cannot create stdio thread or event\n");
2182 exit(1);
2184 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2185 win_stdio_thread_wait_func, chr)) {
2186 fprintf(stderr, "qemu_add_wait_object: failed\n");
2190 dwMode |= ENABLE_LINE_INPUT;
2192 if (is_console) {
2193 /* set the terminal in raw mode */
2194 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2195 dwMode |= ENABLE_PROCESSED_INPUT;
2198 SetConsoleMode(stdio->hStdIn, dwMode);
2200 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2201 qemu_chr_fe_set_echo(chr, false);
2203 return chr;
2205 #endif /* !_WIN32 */
2208 /***********************************************************/
2209 /* UDP Net console */
2211 typedef struct {
2212 int fd;
2213 GIOChannel *chan;
2214 guint tag;
2215 uint8_t buf[READ_BUF_LEN];
2216 int bufcnt;
2217 int bufptr;
2218 int max_size;
2219 } NetCharDriver;
2221 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2223 NetCharDriver *s = chr->opaque;
2224 gsize bytes_written;
2225 GIOStatus status;
2227 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2228 if (status == G_IO_STATUS_EOF) {
2229 return 0;
2230 } else if (status != G_IO_STATUS_NORMAL) {
2231 return -1;
2234 return bytes_written;
2237 static int udp_chr_read_poll(void *opaque)
2239 CharDriverState *chr = opaque;
2240 NetCharDriver *s = chr->opaque;
2242 s->max_size = qemu_chr_be_can_write(chr);
2244 /* If there were any stray characters in the queue process them
2245 * first
2247 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2248 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2249 s->bufptr++;
2250 s->max_size = qemu_chr_be_can_write(chr);
2252 return s->max_size;
2255 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2257 CharDriverState *chr = opaque;
2258 NetCharDriver *s = chr->opaque;
2259 gsize bytes_read = 0;
2260 GIOStatus status;
2262 if (s->max_size == 0) {
2263 return TRUE;
2265 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2266 &bytes_read, NULL);
2267 s->bufcnt = bytes_read;
2268 s->bufptr = s->bufcnt;
2269 if (status != G_IO_STATUS_NORMAL) {
2270 if (s->tag) {
2271 io_remove_watch_poll(s->tag);
2272 s->tag = 0;
2274 return FALSE;
2277 s->bufptr = 0;
2278 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2279 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2280 s->bufptr++;
2281 s->max_size = qemu_chr_be_can_write(chr);
2284 return TRUE;
2287 static void udp_chr_update_read_handler(CharDriverState *chr)
2289 NetCharDriver *s = chr->opaque;
2291 if (s->tag) {
2292 io_remove_watch_poll(s->tag);
2293 s->tag = 0;
2296 if (s->chan) {
2297 s->tag = io_add_watch_poll(s->chan, udp_chr_read_poll, udp_chr_read, chr);
2301 static void udp_chr_close(CharDriverState *chr)
2303 NetCharDriver *s = chr->opaque;
2304 if (s->tag) {
2305 io_remove_watch_poll(s->tag);
2306 s->tag = 0;
2308 if (s->chan) {
2309 g_io_channel_unref(s->chan);
2310 closesocket(s->fd);
2312 g_free(s);
2313 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2316 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2318 CharDriverState *chr = NULL;
2319 NetCharDriver *s = NULL;
2321 chr = g_malloc0(sizeof(CharDriverState));
2322 s = g_malloc0(sizeof(NetCharDriver));
2324 s->fd = fd;
2325 s->chan = io_channel_from_socket(s->fd);
2326 s->bufcnt = 0;
2327 s->bufptr = 0;
2328 chr->opaque = s;
2329 chr->chr_write = udp_chr_write;
2330 chr->chr_update_read_handler = udp_chr_update_read_handler;
2331 chr->chr_close = udp_chr_close;
2332 return chr;
2335 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2337 Error *local_err = NULL;
2338 int fd = -1;
2340 fd = inet_dgram_opts(opts, &local_err);
2341 if (fd < 0) {
2342 return NULL;
2344 return qemu_chr_open_udp_fd(fd);
2347 /***********************************************************/
2348 /* TCP Net console */
2350 typedef struct {
2352 GIOChannel *chan, *listen_chan;
2353 guint tag, listen_tag;
2354 int fd, listen_fd;
2355 int connected;
2356 int max_size;
2357 int do_telnetopt;
2358 int do_nodelay;
2359 int is_unix;
2360 int msgfd;
2361 } TCPCharDriver;
2363 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2365 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2367 TCPCharDriver *s = chr->opaque;
2368 if (s->connected) {
2369 return io_channel_send(s->chan, buf, len);
2370 } else {
2371 /* XXX: indicate an error ? */
2372 return len;
2376 static int tcp_chr_read_poll(void *opaque)
2378 CharDriverState *chr = opaque;
2379 TCPCharDriver *s = chr->opaque;
2380 if (!s->connected)
2381 return 0;
2382 s->max_size = qemu_chr_be_can_write(chr);
2383 return s->max_size;
2386 #define IAC 255
2387 #define IAC_BREAK 243
2388 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2389 TCPCharDriver *s,
2390 uint8_t *buf, int *size)
2392 /* Handle any telnet client's basic IAC options to satisfy char by
2393 * char mode with no echo. All IAC options will be removed from
2394 * the buf and the do_telnetopt variable will be used to track the
2395 * state of the width of the IAC information.
2397 * IAC commands come in sets of 3 bytes with the exception of the
2398 * "IAC BREAK" command and the double IAC.
2401 int i;
2402 int j = 0;
2404 for (i = 0; i < *size; i++) {
2405 if (s->do_telnetopt > 1) {
2406 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2407 /* Double IAC means send an IAC */
2408 if (j != i)
2409 buf[j] = buf[i];
2410 j++;
2411 s->do_telnetopt = 1;
2412 } else {
2413 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2414 /* Handle IAC break commands by sending a serial break */
2415 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2416 s->do_telnetopt++;
2418 s->do_telnetopt++;
2420 if (s->do_telnetopt >= 4) {
2421 s->do_telnetopt = 1;
2423 } else {
2424 if ((unsigned char)buf[i] == IAC) {
2425 s->do_telnetopt = 2;
2426 } else {
2427 if (j != i)
2428 buf[j] = buf[i];
2429 j++;
2433 *size = j;
2436 static int tcp_get_msgfd(CharDriverState *chr)
2438 TCPCharDriver *s = chr->opaque;
2439 int fd = s->msgfd;
2440 s->msgfd = -1;
2441 return fd;
2444 #ifndef _WIN32
2445 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2447 TCPCharDriver *s = chr->opaque;
2448 struct cmsghdr *cmsg;
2450 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2451 int fd;
2453 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2454 cmsg->cmsg_level != SOL_SOCKET ||
2455 cmsg->cmsg_type != SCM_RIGHTS)
2456 continue;
2458 fd = *((int *)CMSG_DATA(cmsg));
2459 if (fd < 0)
2460 continue;
2462 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2463 qemu_set_block(fd);
2465 #ifndef MSG_CMSG_CLOEXEC
2466 qemu_set_cloexec(fd);
2467 #endif
2468 if (s->msgfd != -1)
2469 close(s->msgfd);
2470 s->msgfd = fd;
2474 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2476 TCPCharDriver *s = chr->opaque;
2477 struct msghdr msg = { NULL, };
2478 struct iovec iov[1];
2479 union {
2480 struct cmsghdr cmsg;
2481 char control[CMSG_SPACE(sizeof(int))];
2482 } msg_control;
2483 int flags = 0;
2484 ssize_t ret;
2486 iov[0].iov_base = buf;
2487 iov[0].iov_len = len;
2489 msg.msg_iov = iov;
2490 msg.msg_iovlen = 1;
2491 msg.msg_control = &msg_control;
2492 msg.msg_controllen = sizeof(msg_control);
2494 #ifdef MSG_CMSG_CLOEXEC
2495 flags |= MSG_CMSG_CLOEXEC;
2496 #endif
2497 ret = recvmsg(s->fd, &msg, flags);
2498 if (ret > 0 && s->is_unix) {
2499 unix_process_msgfd(chr, &msg);
2502 return ret;
2504 #else
2505 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2507 TCPCharDriver *s = chr->opaque;
2508 return qemu_recv(s->fd, buf, len, 0);
2510 #endif
2512 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2514 TCPCharDriver *s = chr->opaque;
2515 return g_io_create_watch(s->chan, cond);
2518 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2520 CharDriverState *chr = opaque;
2521 TCPCharDriver *s = chr->opaque;
2522 uint8_t buf[READ_BUF_LEN];
2523 int len, size;
2525 if (!s->connected || s->max_size <= 0) {
2526 return TRUE;
2528 len = sizeof(buf);
2529 if (len > s->max_size)
2530 len = s->max_size;
2531 size = tcp_chr_recv(chr, (void *)buf, len);
2532 if (size == 0) {
2533 /* connection closed */
2534 s->connected = 0;
2535 if (s->listen_chan) {
2536 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2538 if (s->tag) {
2539 io_remove_watch_poll(s->tag);
2540 s->tag = 0;
2542 g_io_channel_unref(s->chan);
2543 s->chan = NULL;
2544 closesocket(s->fd);
2545 s->fd = -1;
2546 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2547 } else if (size > 0) {
2548 if (s->do_telnetopt)
2549 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2550 if (size > 0)
2551 qemu_chr_be_write(chr, buf, size);
2554 return TRUE;
2557 #ifndef _WIN32
2558 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2560 return qemu_chr_open_fd(eventfd, eventfd);
2562 #endif
2564 static void tcp_chr_connect(void *opaque)
2566 CharDriverState *chr = opaque;
2567 TCPCharDriver *s = chr->opaque;
2569 s->connected = 1;
2570 if (s->chan) {
2571 s->tag = io_add_watch_poll(s->chan, tcp_chr_read_poll, tcp_chr_read, chr);
2573 qemu_chr_be_generic_open(chr);
2576 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2577 static void tcp_chr_telnet_init(int fd)
2579 char buf[3];
2580 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2581 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2582 send(fd, (char *)buf, 3, 0);
2583 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2584 send(fd, (char *)buf, 3, 0);
2585 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2586 send(fd, (char *)buf, 3, 0);
2587 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2588 send(fd, (char *)buf, 3, 0);
2591 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2593 TCPCharDriver *s = chr->opaque;
2594 if (s->fd != -1)
2595 return -1;
2597 qemu_set_nonblock(fd);
2598 if (s->do_nodelay)
2599 socket_set_nodelay(fd);
2600 s->fd = fd;
2601 s->chan = io_channel_from_socket(fd);
2602 if (s->listen_tag) {
2603 g_source_remove(s->listen_tag);
2604 s->listen_tag = 0;
2606 tcp_chr_connect(chr);
2608 return 0;
2611 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2613 CharDriverState *chr = opaque;
2614 TCPCharDriver *s = chr->opaque;
2615 struct sockaddr_in saddr;
2616 #ifndef _WIN32
2617 struct sockaddr_un uaddr;
2618 #endif
2619 struct sockaddr *addr;
2620 socklen_t len;
2621 int fd;
2623 for(;;) {
2624 #ifndef _WIN32
2625 if (s->is_unix) {
2626 len = sizeof(uaddr);
2627 addr = (struct sockaddr *)&uaddr;
2628 } else
2629 #endif
2631 len = sizeof(saddr);
2632 addr = (struct sockaddr *)&saddr;
2634 fd = qemu_accept(s->listen_fd, addr, &len);
2635 if (fd < 0 && errno != EINTR) {
2636 s->listen_tag = 0;
2637 return FALSE;
2638 } else if (fd >= 0) {
2639 if (s->do_telnetopt)
2640 tcp_chr_telnet_init(fd);
2641 break;
2644 if (tcp_chr_add_client(chr, fd) < 0)
2645 close(fd);
2647 return TRUE;
2650 static void tcp_chr_close(CharDriverState *chr)
2652 TCPCharDriver *s = chr->opaque;
2653 if (s->fd >= 0) {
2654 if (s->tag) {
2655 io_remove_watch_poll(s->tag);
2656 s->tag = 0;
2658 if (s->chan) {
2659 g_io_channel_unref(s->chan);
2661 closesocket(s->fd);
2663 if (s->listen_fd >= 0) {
2664 if (s->listen_tag) {
2665 g_source_remove(s->listen_tag);
2666 s->listen_tag = 0;
2668 if (s->listen_chan) {
2669 g_io_channel_unref(s->listen_chan);
2671 closesocket(s->listen_fd);
2673 g_free(s);
2674 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2677 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2678 bool is_listen, bool is_telnet,
2679 bool is_waitconnect,
2680 Error **errp)
2682 CharDriverState *chr = NULL;
2683 TCPCharDriver *s = NULL;
2684 char host[NI_MAXHOST], serv[NI_MAXSERV];
2685 const char *left = "", *right = "";
2686 struct sockaddr_storage ss;
2687 socklen_t ss_len = sizeof(ss);
2689 memset(&ss, 0, ss_len);
2690 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2691 error_setg(errp, "getsockname: %s", strerror(errno));
2692 return NULL;
2695 chr = g_malloc0(sizeof(CharDriverState));
2696 s = g_malloc0(sizeof(TCPCharDriver));
2698 s->connected = 0;
2699 s->fd = -1;
2700 s->listen_fd = -1;
2701 s->msgfd = -1;
2703 chr->filename = g_malloc(256);
2704 switch (ss.ss_family) {
2705 #ifndef _WIN32
2706 case AF_UNIX:
2707 s->is_unix = 1;
2708 snprintf(chr->filename, 256, "unix:%s%s",
2709 ((struct sockaddr_un *)(&ss))->sun_path,
2710 is_listen ? ",server" : "");
2711 break;
2712 #endif
2713 case AF_INET6:
2714 left = "[";
2715 right = "]";
2716 /* fall through */
2717 case AF_INET:
2718 s->do_nodelay = do_nodelay;
2719 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2720 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2721 snprintf(chr->filename, 256, "%s:%s%s%s:%s%s",
2722 is_telnet ? "telnet" : "tcp",
2723 left, host, right, serv,
2724 is_listen ? ",server" : "");
2725 break;
2728 chr->opaque = s;
2729 chr->chr_write = tcp_chr_write;
2730 chr->chr_close = tcp_chr_close;
2731 chr->get_msgfd = tcp_get_msgfd;
2732 chr->chr_add_client = tcp_chr_add_client;
2733 chr->chr_add_watch = tcp_chr_add_watch;
2735 if (is_listen) {
2736 s->listen_fd = fd;
2737 s->listen_chan = io_channel_from_socket(s->listen_fd);
2738 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2739 if (is_telnet) {
2740 s->do_telnetopt = 1;
2742 } else {
2743 s->connected = 1;
2744 s->fd = fd;
2745 socket_set_nodelay(fd);
2746 s->chan = io_channel_from_socket(s->fd);
2747 tcp_chr_connect(chr);
2750 if (is_listen && is_waitconnect) {
2751 printf("QEMU waiting for connection on: %s\n",
2752 chr->filename);
2753 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2754 qemu_set_nonblock(s->listen_fd);
2756 return chr;
2759 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2761 CharDriverState *chr = NULL;
2762 Error *local_err = NULL;
2763 int fd = -1;
2764 int is_listen;
2765 int is_waitconnect;
2766 int do_nodelay;
2767 int is_unix;
2768 int is_telnet;
2770 is_listen = qemu_opt_get_bool(opts, "server", 0);
2771 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2772 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2773 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2774 is_unix = qemu_opt_get(opts, "path") != NULL;
2775 if (!is_listen)
2776 is_waitconnect = 0;
2778 if (is_unix) {
2779 if (is_listen) {
2780 fd = unix_listen_opts(opts, &local_err);
2781 } else {
2782 fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2784 } else {
2785 if (is_listen) {
2786 fd = inet_listen_opts(opts, 0, &local_err);
2787 } else {
2788 fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2791 if (fd < 0) {
2792 goto fail;
2795 if (!is_waitconnect)
2796 qemu_set_nonblock(fd);
2798 chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2799 is_waitconnect, &local_err);
2800 if (error_is_set(&local_err)) {
2801 goto fail;
2803 return chr;
2806 fail:
2807 if (local_err) {
2808 qerror_report_err(local_err);
2809 error_free(local_err);
2811 if (fd >= 0) {
2812 closesocket(fd);
2814 if (chr) {
2815 g_free(chr->opaque);
2816 g_free(chr);
2818 return NULL;
2821 /*********************************************************/
2822 /* Ring buffer chardev */
2824 typedef struct {
2825 size_t size;
2826 size_t prod;
2827 size_t cons;
2828 uint8_t *cbuf;
2829 } RingBufCharDriver;
2831 static size_t ringbuf_count(const CharDriverState *chr)
2833 const RingBufCharDriver *d = chr->opaque;
2835 return d->prod - d->cons;
2838 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2840 RingBufCharDriver *d = chr->opaque;
2841 int i;
2843 if (!buf || (len < 0)) {
2844 return -1;
2847 for (i = 0; i < len; i++ ) {
2848 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2849 if (d->prod - d->cons > d->size) {
2850 d->cons = d->prod - d->size;
2854 return 0;
2857 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2859 RingBufCharDriver *d = chr->opaque;
2860 int i;
2862 for (i = 0; i < len && d->cons != d->prod; i++) {
2863 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2866 return i;
2869 static void ringbuf_chr_close(struct CharDriverState *chr)
2871 RingBufCharDriver *d = chr->opaque;
2873 g_free(d->cbuf);
2874 g_free(d);
2875 chr->opaque = NULL;
2878 static CharDriverState *qemu_chr_open_memory(ChardevMemory *opts,
2879 Error **errp)
2881 CharDriverState *chr;
2882 RingBufCharDriver *d;
2884 chr = g_malloc0(sizeof(CharDriverState));
2885 d = g_malloc(sizeof(*d));
2887 d->size = opts->has_size ? opts->size : 65536;
2889 /* The size must be power of 2 */
2890 if (d->size & (d->size - 1)) {
2891 error_setg(errp, "size of memory chardev must be power of two");
2892 goto fail;
2895 d->prod = 0;
2896 d->cons = 0;
2897 d->cbuf = g_malloc0(d->size);
2899 chr->opaque = d;
2900 chr->chr_write = ringbuf_chr_write;
2901 chr->chr_close = ringbuf_chr_close;
2903 return chr;
2905 fail:
2906 g_free(d);
2907 g_free(chr);
2908 return NULL;
2911 static bool chr_is_ringbuf(const CharDriverState *chr)
2913 return chr->chr_write == ringbuf_chr_write;
2916 void qmp_ringbuf_write(const char *device, const char *data,
2917 bool has_format, enum DataFormat format,
2918 Error **errp)
2920 CharDriverState *chr;
2921 const uint8_t *write_data;
2922 int ret;
2923 gsize write_count;
2925 chr = qemu_chr_find(device);
2926 if (!chr) {
2927 error_setg(errp, "Device '%s' not found", device);
2928 return;
2931 if (!chr_is_ringbuf(chr)) {
2932 error_setg(errp,"%s is not a ringbuf device", device);
2933 return;
2936 if (has_format && (format == DATA_FORMAT_BASE64)) {
2937 write_data = g_base64_decode(data, &write_count);
2938 } else {
2939 write_data = (uint8_t *)data;
2940 write_count = strlen(data);
2943 ret = ringbuf_chr_write(chr, write_data, write_count);
2945 if (write_data != (uint8_t *)data) {
2946 g_free((void *)write_data);
2949 if (ret < 0) {
2950 error_setg(errp, "Failed to write to device %s", device);
2951 return;
2955 char *qmp_ringbuf_read(const char *device, int64_t size,
2956 bool has_format, enum DataFormat format,
2957 Error **errp)
2959 CharDriverState *chr;
2960 uint8_t *read_data;
2961 size_t count;
2962 char *data;
2964 chr = qemu_chr_find(device);
2965 if (!chr) {
2966 error_setg(errp, "Device '%s' not found", device);
2967 return NULL;
2970 if (!chr_is_ringbuf(chr)) {
2971 error_setg(errp,"%s is not a ringbuf device", device);
2972 return NULL;
2975 if (size <= 0) {
2976 error_setg(errp, "size must be greater than zero");
2977 return NULL;
2980 count = ringbuf_count(chr);
2981 size = size > count ? count : size;
2982 read_data = g_malloc(size + 1);
2984 ringbuf_chr_read(chr, read_data, size);
2986 if (has_format && (format == DATA_FORMAT_BASE64)) {
2987 data = g_base64_encode(read_data, size);
2988 g_free(read_data);
2989 } else {
2991 * FIXME should read only complete, valid UTF-8 characters up
2992 * to @size bytes. Invalid sequences should be replaced by a
2993 * suitable replacement character. Except when (and only
2994 * when) ring buffer lost characters since last read, initial
2995 * continuation characters should be dropped.
2997 read_data[size] = 0;
2998 data = (char *)read_data;
3001 return data;
3004 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3006 char host[65], port[33], width[8], height[8];
3007 int pos;
3008 const char *p;
3009 QemuOpts *opts;
3010 Error *local_err = NULL;
3012 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3013 if (error_is_set(&local_err)) {
3014 qerror_report_err(local_err);
3015 error_free(local_err);
3016 return NULL;
3019 if (strstart(filename, "mon:", &p)) {
3020 filename = p;
3021 qemu_opt_set(opts, "mux", "on");
3024 if (strcmp(filename, "null") == 0 ||
3025 strcmp(filename, "pty") == 0 ||
3026 strcmp(filename, "msmouse") == 0 ||
3027 strcmp(filename, "braille") == 0 ||
3028 strcmp(filename, "stdio") == 0) {
3029 qemu_opt_set(opts, "backend", filename);
3030 return opts;
3032 if (strstart(filename, "vc", &p)) {
3033 qemu_opt_set(opts, "backend", "vc");
3034 if (*p == ':') {
3035 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
3036 /* pixels */
3037 qemu_opt_set(opts, "width", width);
3038 qemu_opt_set(opts, "height", height);
3039 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
3040 /* chars */
3041 qemu_opt_set(opts, "cols", width);
3042 qemu_opt_set(opts, "rows", height);
3043 } else {
3044 goto fail;
3047 return opts;
3049 if (strcmp(filename, "con:") == 0) {
3050 qemu_opt_set(opts, "backend", "console");
3051 return opts;
3053 if (strstart(filename, "COM", NULL)) {
3054 qemu_opt_set(opts, "backend", "serial");
3055 qemu_opt_set(opts, "path", filename);
3056 return opts;
3058 if (strstart(filename, "file:", &p)) {
3059 qemu_opt_set(opts, "backend", "file");
3060 qemu_opt_set(opts, "path", p);
3061 return opts;
3063 if (strstart(filename, "pipe:", &p)) {
3064 qemu_opt_set(opts, "backend", "pipe");
3065 qemu_opt_set(opts, "path", p);
3066 return opts;
3068 if (strstart(filename, "tcp:", &p) ||
3069 strstart(filename, "telnet:", &p)) {
3070 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3071 host[0] = 0;
3072 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3073 goto fail;
3075 qemu_opt_set(opts, "backend", "socket");
3076 qemu_opt_set(opts, "host", host);
3077 qemu_opt_set(opts, "port", port);
3078 if (p[pos] == ',') {
3079 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3080 goto fail;
3082 if (strstart(filename, "telnet:", &p))
3083 qemu_opt_set(opts, "telnet", "on");
3084 return opts;
3086 if (strstart(filename, "udp:", &p)) {
3087 qemu_opt_set(opts, "backend", "udp");
3088 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3089 host[0] = 0;
3090 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3091 goto fail;
3094 qemu_opt_set(opts, "host", host);
3095 qemu_opt_set(opts, "port", port);
3096 if (p[pos] == '@') {
3097 p += pos + 1;
3098 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3099 host[0] = 0;
3100 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3101 goto fail;
3104 qemu_opt_set(opts, "localaddr", host);
3105 qemu_opt_set(opts, "localport", port);
3107 return opts;
3109 if (strstart(filename, "unix:", &p)) {
3110 qemu_opt_set(opts, "backend", "socket");
3111 if (qemu_opts_do_parse(opts, p, "path") != 0)
3112 goto fail;
3113 return opts;
3115 if (strstart(filename, "/dev/parport", NULL) ||
3116 strstart(filename, "/dev/ppi", NULL)) {
3117 qemu_opt_set(opts, "backend", "parport");
3118 qemu_opt_set(opts, "path", filename);
3119 return opts;
3121 if (strstart(filename, "/dev/", NULL)) {
3122 qemu_opt_set(opts, "backend", "tty");
3123 qemu_opt_set(opts, "path", filename);
3124 return opts;
3127 fail:
3128 qemu_opts_del(opts);
3129 return NULL;
3132 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3133 Error **errp)
3135 const char *path = qemu_opt_get(opts, "path");
3137 if (path == NULL) {
3138 error_setg(errp, "chardev: file: no filename given");
3139 return;
3141 backend->file = g_new0(ChardevFile, 1);
3142 backend->file->out = g_strdup(path);
3145 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3146 Error **errp)
3148 backend->stdio = g_new0(ChardevStdio, 1);
3149 backend->stdio->has_signal = true;
3150 backend->stdio->signal =
3151 qemu_opt_get_bool(opts, "signal", display_type != DT_NOGRAPHIC);
3154 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3155 Error **errp)
3157 const char *device = qemu_opt_get(opts, "path");
3159 if (device == NULL) {
3160 error_setg(errp, "chardev: serial/tty: no device path given");
3161 return;
3163 backend->serial = g_new0(ChardevHostdev, 1);
3164 backend->serial->device = g_strdup(device);
3167 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3168 Error **errp)
3170 const char *device = qemu_opt_get(opts, "path");
3172 if (device == NULL) {
3173 error_setg(errp, "chardev: parallel: no device path given");
3174 return;
3176 backend->parallel = g_new0(ChardevHostdev, 1);
3177 backend->parallel->device = g_strdup(device);
3180 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3181 Error **errp)
3183 const char *device = qemu_opt_get(opts, "path");
3185 if (device == NULL) {
3186 error_setg(errp, "chardev: pipe: no device path given");
3187 return;
3189 backend->pipe = g_new0(ChardevHostdev, 1);
3190 backend->pipe->device = g_strdup(device);
3193 static void qemu_chr_parse_memory(QemuOpts *opts, ChardevBackend *backend,
3194 Error **errp)
3196 int val;
3198 backend->memory = g_new0(ChardevMemory, 1);
3200 val = qemu_opt_get_number(opts, "size", 0);
3201 if (val != 0) {
3202 backend->memory->has_size = true;
3203 backend->memory->size = val;
3207 typedef struct CharDriver {
3208 const char *name;
3209 /* old, pre qapi */
3210 CharDriverState *(*open)(QemuOpts *opts);
3211 /* new, qapi-based */
3212 int kind;
3213 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3214 } CharDriver;
3216 static GSList *backends;
3218 void register_char_driver(const char *name, CharDriverState *(*open)(QemuOpts *))
3220 CharDriver *s;
3222 s = g_malloc0(sizeof(*s));
3223 s->name = g_strdup(name);
3224 s->open = open;
3226 backends = g_slist_append(backends, s);
3229 void register_char_driver_qapi(const char *name, int kind,
3230 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3232 CharDriver *s;
3234 s = g_malloc0(sizeof(*s));
3235 s->name = g_strdup(name);
3236 s->kind = kind;
3237 s->parse = parse;
3239 backends = g_slist_append(backends, s);
3242 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3243 void (*init)(struct CharDriverState *s),
3244 Error **errp)
3246 CharDriver *cd;
3247 CharDriverState *chr;
3248 GSList *i;
3250 if (qemu_opts_id(opts) == NULL) {
3251 error_setg(errp, "chardev: no id specified");
3252 goto err;
3255 if (qemu_opt_get(opts, "backend") == NULL) {
3256 error_setg(errp, "chardev: \"%s\" missing backend",
3257 qemu_opts_id(opts));
3258 goto err;
3260 for (i = backends; i; i = i->next) {
3261 cd = i->data;
3263 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3264 break;
3267 if (i == NULL) {
3268 error_setg(errp, "chardev: backend \"%s\" not found",
3269 qemu_opt_get(opts, "backend"));
3270 return NULL;
3273 if (!cd->open) {
3274 /* using new, qapi init */
3275 ChardevBackend *backend = g_new0(ChardevBackend, 1);
3276 ChardevReturn *ret = NULL;
3277 const char *id = qemu_opts_id(opts);
3278 const char *bid = NULL;
3280 if (qemu_opt_get_bool(opts, "mux", 0)) {
3281 bid = g_strdup_printf("%s-base", id);
3284 chr = NULL;
3285 backend->kind = cd->kind;
3286 if (cd->parse) {
3287 cd->parse(opts, backend, errp);
3288 if (error_is_set(errp)) {
3289 goto qapi_out;
3292 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3293 if (error_is_set(errp)) {
3294 goto qapi_out;
3297 if (bid) {
3298 qapi_free_ChardevBackend(backend);
3299 qapi_free_ChardevReturn(ret);
3300 backend = g_new0(ChardevBackend, 1);
3301 backend->mux = g_new0(ChardevMux, 1);
3302 backend->kind = CHARDEV_BACKEND_KIND_MUX;
3303 backend->mux->chardev = g_strdup(bid);
3304 ret = qmp_chardev_add(id, backend, errp);
3305 if (error_is_set(errp)) {
3306 goto qapi_out;
3310 chr = qemu_chr_find(id);
3312 qapi_out:
3313 qapi_free_ChardevBackend(backend);
3314 qapi_free_ChardevReturn(ret);
3315 return chr;
3318 chr = cd->open(opts);
3319 if (!chr) {
3320 error_setg(errp, "chardev: opening backend \"%s\" failed",
3321 qemu_opt_get(opts, "backend"));
3322 goto err;
3325 if (!chr->filename)
3326 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3327 chr->init = init;
3328 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3330 if (qemu_opt_get_bool(opts, "mux", 0)) {
3331 CharDriverState *base = chr;
3332 int len = strlen(qemu_opts_id(opts)) + 6;
3333 base->label = g_malloc(len);
3334 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3335 chr = qemu_chr_open_mux(base);
3336 chr->filename = base->filename;
3337 chr->avail_connections = MAX_MUX;
3338 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3339 } else {
3340 chr->avail_connections = 1;
3342 chr->label = g_strdup(qemu_opts_id(opts));
3343 chr->opts = opts;
3344 return chr;
3346 err:
3347 qemu_opts_del(opts);
3348 return NULL;
3351 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3353 const char *p;
3354 CharDriverState *chr;
3355 QemuOpts *opts;
3356 Error *err = NULL;
3358 if (strstart(filename, "chardev:", &p)) {
3359 return qemu_chr_find(p);
3362 opts = qemu_chr_parse_compat(label, filename);
3363 if (!opts)
3364 return NULL;
3366 chr = qemu_chr_new_from_opts(opts, init, &err);
3367 if (error_is_set(&err)) {
3368 fprintf(stderr, "%s\n", error_get_pretty(err));
3369 error_free(err);
3371 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3372 qemu_chr_fe_claim_no_fail(chr);
3373 monitor_init(chr, MONITOR_USE_READLINE);
3375 return chr;
3378 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3380 if (chr->chr_set_echo) {
3381 chr->chr_set_echo(chr, echo);
3385 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3387 if (chr->fe_open == fe_open) {
3388 return;
3390 chr->fe_open = fe_open;
3391 if (chr->chr_set_fe_open) {
3392 chr->chr_set_fe_open(chr, fe_open);
3396 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3397 GIOFunc func, void *user_data)
3399 GSource *src;
3400 guint tag;
3402 if (s->chr_add_watch == NULL) {
3403 return -ENOSYS;
3406 src = s->chr_add_watch(s, cond);
3407 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3408 tag = g_source_attach(src, NULL);
3409 g_source_unref(src);
3411 return tag;
3414 int qemu_chr_fe_claim(CharDriverState *s)
3416 if (s->avail_connections < 1) {
3417 return -1;
3419 s->avail_connections--;
3420 return 0;
3423 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3425 if (qemu_chr_fe_claim(s) != 0) {
3426 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3427 __func__, s->label);
3428 exit(1);
3432 void qemu_chr_fe_release(CharDriverState *s)
3434 s->avail_connections++;
3437 void qemu_chr_delete(CharDriverState *chr)
3439 QTAILQ_REMOVE(&chardevs, chr, next);
3440 if (chr->chr_close) {
3441 chr->chr_close(chr);
3443 g_free(chr->filename);
3444 g_free(chr->label);
3445 if (chr->opts) {
3446 qemu_opts_del(chr->opts);
3448 g_free(chr);
3451 ChardevInfoList *qmp_query_chardev(Error **errp)
3453 ChardevInfoList *chr_list = NULL;
3454 CharDriverState *chr;
3456 QTAILQ_FOREACH(chr, &chardevs, next) {
3457 ChardevInfoList *info = g_malloc0(sizeof(*info));
3458 info->value = g_malloc0(sizeof(*info->value));
3459 info->value->label = g_strdup(chr->label);
3460 info->value->filename = g_strdup(chr->filename);
3462 info->next = chr_list;
3463 chr_list = info;
3466 return chr_list;
3469 CharDriverState *qemu_chr_find(const char *name)
3471 CharDriverState *chr;
3473 QTAILQ_FOREACH(chr, &chardevs, next) {
3474 if (strcmp(chr->label, name) != 0)
3475 continue;
3476 return chr;
3478 return NULL;
3481 /* Get a character (serial) device interface. */
3482 CharDriverState *qemu_char_get_next_serial(void)
3484 static int next_serial;
3485 CharDriverState *chr;
3487 /* FIXME: This function needs to go away: use chardev properties! */
3489 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3490 chr = serial_hds[next_serial++];
3491 qemu_chr_fe_claim_no_fail(chr);
3492 return chr;
3494 return NULL;
3497 QemuOptsList qemu_chardev_opts = {
3498 .name = "chardev",
3499 .implied_opt_name = "backend",
3500 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3501 .desc = {
3503 .name = "backend",
3504 .type = QEMU_OPT_STRING,
3506 .name = "path",
3507 .type = QEMU_OPT_STRING,
3509 .name = "host",
3510 .type = QEMU_OPT_STRING,
3512 .name = "port",
3513 .type = QEMU_OPT_STRING,
3515 .name = "localaddr",
3516 .type = QEMU_OPT_STRING,
3518 .name = "localport",
3519 .type = QEMU_OPT_STRING,
3521 .name = "to",
3522 .type = QEMU_OPT_NUMBER,
3524 .name = "ipv4",
3525 .type = QEMU_OPT_BOOL,
3527 .name = "ipv6",
3528 .type = QEMU_OPT_BOOL,
3530 .name = "wait",
3531 .type = QEMU_OPT_BOOL,
3533 .name = "server",
3534 .type = QEMU_OPT_BOOL,
3536 .name = "delay",
3537 .type = QEMU_OPT_BOOL,
3539 .name = "telnet",
3540 .type = QEMU_OPT_BOOL,
3542 .name = "width",
3543 .type = QEMU_OPT_NUMBER,
3545 .name = "height",
3546 .type = QEMU_OPT_NUMBER,
3548 .name = "cols",
3549 .type = QEMU_OPT_NUMBER,
3551 .name = "rows",
3552 .type = QEMU_OPT_NUMBER,
3554 .name = "mux",
3555 .type = QEMU_OPT_BOOL,
3557 .name = "signal",
3558 .type = QEMU_OPT_BOOL,
3560 .name = "name",
3561 .type = QEMU_OPT_STRING,
3563 .name = "debug",
3564 .type = QEMU_OPT_NUMBER,
3566 .name = "size",
3567 .type = QEMU_OPT_SIZE,
3569 { /* end of list */ }
3573 #ifdef _WIN32
3575 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3577 HANDLE out;
3579 if (file->in) {
3580 error_setg(errp, "input file not supported");
3581 return NULL;
3584 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3585 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3586 if (out == INVALID_HANDLE_VALUE) {
3587 error_setg(errp, "open %s failed", file->out);
3588 return NULL;
3590 return qemu_chr_open_win_file(out);
3593 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3594 Error **errp)
3596 return qemu_chr_open_win_path(serial->device);
3599 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3600 Error **errp)
3602 error_setg(errp, "character device backend type 'parallel' not supported");
3603 return NULL;
3606 #else /* WIN32 */
3608 static int qmp_chardev_open_file_source(char *src, int flags,
3609 Error **errp)
3611 int fd = -1;
3613 TFR(fd = qemu_open(src, flags, 0666));
3614 if (fd == -1) {
3615 error_setg(errp, "open %s: %s", src, strerror(errno));
3617 return fd;
3620 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3622 int flags, in = -1, out = -1;
3624 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3625 out = qmp_chardev_open_file_source(file->out, flags, errp);
3626 if (error_is_set(errp)) {
3627 return NULL;
3630 if (file->in) {
3631 flags = O_RDONLY;
3632 in = qmp_chardev_open_file_source(file->in, flags, errp);
3633 if (error_is_set(errp)) {
3634 qemu_close(out);
3635 return NULL;
3639 return qemu_chr_open_fd(in, out);
3642 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3643 Error **errp)
3645 #ifdef HAVE_CHARDEV_TTY
3646 int fd;
3648 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3649 if (error_is_set(errp)) {
3650 return NULL;
3652 qemu_set_nonblock(fd);
3653 return qemu_chr_open_tty_fd(fd);
3654 #else
3655 error_setg(errp, "character device backend type 'serial' not supported");
3656 return NULL;
3657 #endif
3660 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3661 Error **errp)
3663 #ifdef HAVE_CHARDEV_PARPORT
3664 int fd;
3666 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3667 if (error_is_set(errp)) {
3668 return NULL;
3670 return qemu_chr_open_pp_fd(fd);
3671 #else
3672 error_setg(errp, "character device backend type 'parallel' not supported");
3673 return NULL;
3674 #endif
3677 #endif /* WIN32 */
3679 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3680 Error **errp)
3682 SocketAddress *addr = sock->addr;
3683 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3684 bool is_listen = sock->has_server ? sock->server : true;
3685 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3686 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3687 int fd;
3689 if (is_listen) {
3690 fd = socket_listen(addr, errp);
3691 } else {
3692 fd = socket_connect(addr, errp, NULL, NULL);
3694 if (error_is_set(errp)) {
3695 return NULL;
3697 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3698 is_telnet, is_waitconnect, errp);
3701 static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
3702 Error **errp)
3704 int fd;
3706 fd = socket_dgram(udp->remote, udp->local, errp);
3707 if (error_is_set(errp)) {
3708 return NULL;
3710 return qemu_chr_open_udp_fd(fd);
3713 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3714 Error **errp)
3716 ChardevReturn *ret = g_new0(ChardevReturn, 1);
3717 CharDriverState *base, *chr = NULL;
3719 chr = qemu_chr_find(id);
3720 if (chr) {
3721 error_setg(errp, "Chardev '%s' already exists", id);
3722 g_free(ret);
3723 return NULL;
3726 switch (backend->kind) {
3727 case CHARDEV_BACKEND_KIND_FILE:
3728 chr = qmp_chardev_open_file(backend->file, errp);
3729 break;
3730 case CHARDEV_BACKEND_KIND_SERIAL:
3731 chr = qmp_chardev_open_serial(backend->serial, errp);
3732 break;
3733 case CHARDEV_BACKEND_KIND_PARALLEL:
3734 chr = qmp_chardev_open_parallel(backend->parallel, errp);
3735 break;
3736 case CHARDEV_BACKEND_KIND_PIPE:
3737 chr = qemu_chr_open_pipe(backend->pipe);
3738 break;
3739 case CHARDEV_BACKEND_KIND_SOCKET:
3740 chr = qmp_chardev_open_socket(backend->socket, errp);
3741 break;
3742 case CHARDEV_BACKEND_KIND_UDP:
3743 chr = qmp_chardev_open_udp(backend->udp, errp);
3744 break;
3745 #ifdef HAVE_CHARDEV_TTY
3746 case CHARDEV_BACKEND_KIND_PTY:
3747 chr = qemu_chr_open_pty(id, ret);
3748 break;
3749 #endif
3750 case CHARDEV_BACKEND_KIND_NULL:
3751 chr = qemu_chr_open_null();
3752 break;
3753 case CHARDEV_BACKEND_KIND_MUX:
3754 base = qemu_chr_find(backend->mux->chardev);
3755 if (base == NULL) {
3756 error_setg(errp, "mux: base chardev %s not found",
3757 backend->mux->chardev);
3758 break;
3760 chr = qemu_chr_open_mux(base);
3761 break;
3762 case CHARDEV_BACKEND_KIND_MSMOUSE:
3763 chr = qemu_chr_open_msmouse();
3764 break;
3765 #ifdef CONFIG_BRLAPI
3766 case CHARDEV_BACKEND_KIND_BRAILLE:
3767 chr = chr_baum_init();
3768 break;
3769 #endif
3770 case CHARDEV_BACKEND_KIND_STDIO:
3771 chr = qemu_chr_open_stdio(backend->stdio);
3772 break;
3773 #ifdef _WIN32
3774 case CHARDEV_BACKEND_KIND_CONSOLE:
3775 chr = qemu_chr_open_win_con();
3776 break;
3777 #endif
3778 #ifdef CONFIG_SPICE
3779 case CHARDEV_BACKEND_KIND_SPICEVMC:
3780 chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
3781 break;
3782 case CHARDEV_BACKEND_KIND_SPICEPORT:
3783 chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
3784 break;
3785 #endif
3786 case CHARDEV_BACKEND_KIND_VC:
3787 chr = vc_init(backend->vc);
3788 break;
3789 case CHARDEV_BACKEND_KIND_MEMORY:
3790 chr = qemu_chr_open_memory(backend->memory, errp);
3791 break;
3792 default:
3793 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3794 break;
3797 if (chr == NULL && !error_is_set(errp)) {
3798 error_setg(errp, "Failed to create chardev");
3800 if (chr) {
3801 chr->label = g_strdup(id);
3802 chr->avail_connections =
3803 (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
3804 if (!chr->filename) {
3805 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
3807 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3808 return ret;
3809 } else {
3810 g_free(ret);
3811 return NULL;
3815 void qmp_chardev_remove(const char *id, Error **errp)
3817 CharDriverState *chr;
3819 chr = qemu_chr_find(id);
3820 if (NULL == chr) {
3821 error_setg(errp, "Chardev '%s' not found", id);
3822 return;
3824 if (chr->chr_can_read || chr->chr_read ||
3825 chr->chr_event || chr->handler_opaque) {
3826 error_setg(errp, "Chardev '%s' is busy", id);
3827 return;
3829 qemu_chr_delete(chr);
3832 static void register_types(void)
3834 register_char_driver_qapi("null", CHARDEV_BACKEND_KIND_NULL, NULL);
3835 register_char_driver("socket", qemu_chr_open_socket);
3836 register_char_driver("udp", qemu_chr_open_udp);
3837 register_char_driver_qapi("memory", CHARDEV_BACKEND_KIND_MEMORY,
3838 qemu_chr_parse_memory);
3839 register_char_driver_qapi("file", CHARDEV_BACKEND_KIND_FILE,
3840 qemu_chr_parse_file_out);
3841 register_char_driver_qapi("stdio", CHARDEV_BACKEND_KIND_STDIO,
3842 qemu_chr_parse_stdio);
3843 register_char_driver_qapi("serial", CHARDEV_BACKEND_KIND_SERIAL,
3844 qemu_chr_parse_serial);
3845 register_char_driver_qapi("tty", CHARDEV_BACKEND_KIND_SERIAL,
3846 qemu_chr_parse_serial);
3847 register_char_driver_qapi("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
3848 qemu_chr_parse_parallel);
3849 register_char_driver_qapi("parport", CHARDEV_BACKEND_KIND_PARALLEL,
3850 qemu_chr_parse_parallel);
3851 register_char_driver_qapi("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
3852 register_char_driver_qapi("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
3853 register_char_driver_qapi("pipe", CHARDEV_BACKEND_KIND_PIPE,
3854 qemu_chr_parse_pipe);
3857 type_init(register_types);