Merge remote-tracking branch 'kraxel/chardev.5' into staging
[sdk/emulator/qemu.git] / qemu-char.c
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
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 "char/char.h"
30 #include "hw/usb.h"
31 #include "qmp-commands.h"
32
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>
39
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(__GLIBC__)
57 #include <pty.h>
58 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
59 #include <libutil.h>
60 #else
61 #include <util.h>
62 #endif
63 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
64 #include <dev/ppbus/ppi.h>
65 #include <dev/ppbus/ppbconf.h>
66 #elif defined(__DragonFly__)
67 #include <dev/misc/ppi/ppi.h>
68 #include <bus/ppbus/ppbconf.h>
69 #endif
70 #else
71 #ifdef __linux__
72 #include <pty.h>
73
74 #include <linux/ppdev.h>
75 #include <linux/parport.h>
76 #endif
77 #ifdef __sun__
78 #include <sys/stat.h>
79 #include <sys/ethernet.h>
80 #include <sys/sockio.h>
81 #include <netinet/arp.h>
82 #include <netinet/in.h>
83 #include <netinet/in_systm.h>
84 #include <netinet/ip.h>
85 #include <netinet/ip_icmp.h> // must come after ip.h
86 #include <netinet/udp.h>
87 #include <netinet/tcp.h>
88 #include <net/if.h>
89 #include <syslog.h>
90 #include <stropts.h>
91 #endif
92 #endif
93 #endif
94
95 #include "qemu/sockets.h"
96 #include "ui/qemu-spice.h"
97
98 #define READ_BUF_LEN 4096
99
100 /***********************************************************/
101 /* character device */
102
103 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
104     QTAILQ_HEAD_INITIALIZER(chardevs);
105
106 void qemu_chr_be_event(CharDriverState *s, int event)
107 {
108     /* Keep track if the char device is open */
109     switch (event) {
110         case CHR_EVENT_OPENED:
111             s->opened = 1;
112             break;
113         case CHR_EVENT_CLOSED:
114             s->opened = 0;
115             break;
116     }
117
118     if (!s->chr_event)
119         return;
120     s->chr_event(s->handler_opaque, event);
121 }
122
123 static gboolean qemu_chr_generic_open_bh(gpointer opaque)
124 {
125     CharDriverState *s = opaque;
126     qemu_chr_be_event(s, CHR_EVENT_OPENED);
127     s->idle_tag = 0;
128     return FALSE;
129 }
130
131 void qemu_chr_generic_open(CharDriverState *s)
132 {
133     if (s->idle_tag == 0) {
134         s->idle_tag = g_idle_add(qemu_chr_generic_open_bh, s);
135     }
136 }
137
138 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
139 {
140     return s->chr_write(s, buf, len);
141 }
142
143 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
144 {
145     if (!s->chr_ioctl)
146         return -ENOTSUP;
147     return s->chr_ioctl(s, cmd, arg);
148 }
149
150 int qemu_chr_be_can_write(CharDriverState *s)
151 {
152     if (!s->chr_can_read)
153         return 0;
154     return s->chr_can_read(s->handler_opaque);
155 }
156
157 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
158 {
159     if (s->chr_read) {
160         s->chr_read(s->handler_opaque, buf, len);
161     }
162 }
163
164 int qemu_chr_fe_get_msgfd(CharDriverState *s)
165 {
166     return s->get_msgfd ? s->get_msgfd(s) : -1;
167 }
168
169 int qemu_chr_add_client(CharDriverState *s, int fd)
170 {
171     return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
172 }
173
174 void qemu_chr_accept_input(CharDriverState *s)
175 {
176     if (s->chr_accept_input)
177         s->chr_accept_input(s);
178     qemu_notify_event();
179 }
180
181 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
182 {
183     char buf[READ_BUF_LEN];
184     va_list ap;
185     va_start(ap, fmt);
186     vsnprintf(buf, sizeof(buf), fmt, ap);
187     qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
188     va_end(ap);
189 }
190
191 void qemu_chr_add_handlers(CharDriverState *s,
192                            IOCanReadHandler *fd_can_read,
193                            IOReadHandler *fd_read,
194                            IOEventHandler *fd_event,
195                            void *opaque)
196 {
197     if (!opaque && !fd_can_read && !fd_read && !fd_event) {
198         /* chr driver being released. */
199         ++s->avail_connections;
200     }
201     s->chr_can_read = fd_can_read;
202     s->chr_read = fd_read;
203     s->chr_event = fd_event;
204     s->handler_opaque = opaque;
205     if (s->chr_update_read_handler)
206         s->chr_update_read_handler(s);
207
208     /* We're connecting to an already opened device, so let's make sure we
209        also get the open event */
210     if (s->opened) {
211         qemu_chr_generic_open(s);
212     }
213 }
214
215 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
216 {
217     return len;
218 }
219
220 static CharDriverState *qemu_chr_open_null(void)
221 {
222     CharDriverState *chr;
223
224     chr = g_malloc0(sizeof(CharDriverState));
225     chr->chr_write = null_chr_write;
226     return chr;
227 }
228
229 /* MUX driver for serial I/O splitting */
230 #define MAX_MUX 4
231 #define MUX_BUFFER_SIZE 32      /* Must be a power of 2.  */
232 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
233 typedef struct {
234     IOCanReadHandler *chr_can_read[MAX_MUX];
235     IOReadHandler *chr_read[MAX_MUX];
236     IOEventHandler *chr_event[MAX_MUX];
237     void *ext_opaque[MAX_MUX];
238     CharDriverState *drv;
239     int focus;
240     int mux_cnt;
241     int term_got_escape;
242     int max_size;
243     /* Intermediate input buffer allows to catch escape sequences even if the
244        currently active device is not accepting any input - but only until it
245        is full as well. */
246     unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
247     int prod[MAX_MUX];
248     int cons[MAX_MUX];
249     int timestamps;
250     int linestart;
251     int64_t timestamps_start;
252 } MuxDriver;
253
254
255 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
256 {
257     MuxDriver *d = chr->opaque;
258     int ret;
259     if (!d->timestamps) {
260         ret = d->drv->chr_write(d->drv, buf, len);
261     } else {
262         int i;
263
264         ret = 0;
265         for (i = 0; i < len; i++) {
266             if (d->linestart) {
267                 char buf1[64];
268                 int64_t ti;
269                 int secs;
270
271                 ti = qemu_get_clock_ms(rt_clock);
272                 if (d->timestamps_start == -1)
273                     d->timestamps_start = ti;
274                 ti -= d->timestamps_start;
275                 secs = ti / 1000;
276                 snprintf(buf1, sizeof(buf1),
277                          "[%02d:%02d:%02d.%03d] ",
278                          secs / 3600,
279                          (secs / 60) % 60,
280                          secs % 60,
281                          (int)(ti % 1000));
282                 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
283                 d->linestart = 0;
284             }
285             ret += d->drv->chr_write(d->drv, buf+i, 1);
286             if (buf[i] == '\n') {
287                 d->linestart = 1;
288             }
289         }
290     }
291     return ret;
292 }
293
294 static const char * const mux_help[] = {
295     "% h    print this help\n\r",
296     "% x    exit emulator\n\r",
297     "% s    save disk data back to file (if -snapshot)\n\r",
298     "% t    toggle console timestamps\n\r"
299     "% b    send break (magic sysrq)\n\r",
300     "% c    switch between console and monitor\n\r",
301     "% %  sends %\n\r",
302     NULL
303 };
304
305 int term_escape_char = 0x01; /* ctrl-a is used for escape */
306 static void mux_print_help(CharDriverState *chr)
307 {
308     int i, j;
309     char ebuf[15] = "Escape-Char";
310     char cbuf[50] = "\n\r";
311
312     if (term_escape_char > 0 && term_escape_char < 26) {
313         snprintf(cbuf, sizeof(cbuf), "\n\r");
314         snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
315     } else {
316         snprintf(cbuf, sizeof(cbuf),
317                  "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
318                  term_escape_char);
319     }
320     chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
321     for (i = 0; mux_help[i] != NULL; i++) {
322         for (j=0; mux_help[i][j] != '\0'; j++) {
323             if (mux_help[i][j] == '%')
324                 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
325             else
326                 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
327         }
328     }
329 }
330
331 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
332 {
333     if (d->chr_event[mux_nr])
334         d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
335 }
336
337 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
338 {
339     if (d->term_got_escape) {
340         d->term_got_escape = 0;
341         if (ch == term_escape_char)
342             goto send_char;
343         switch(ch) {
344         case '?':
345         case 'h':
346             mux_print_help(chr);
347             break;
348         case 'x':
349             {
350                  const char *term =  "QEMU: Terminated\n\r";
351                  chr->chr_write(chr,(uint8_t *)term,strlen(term));
352                  exit(0);
353                  break;
354             }
355         case 's':
356             bdrv_commit_all();
357             break;
358         case 'b':
359             qemu_chr_be_event(chr, CHR_EVENT_BREAK);
360             break;
361         case 'c':
362             /* Switch to the next registered device */
363             mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
364             d->focus++;
365             if (d->focus >= d->mux_cnt)
366                 d->focus = 0;
367             mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
368             break;
369         case 't':
370             d->timestamps = !d->timestamps;
371             d->timestamps_start = -1;
372             d->linestart = 0;
373             break;
374         }
375     } else if (ch == term_escape_char) {
376         d->term_got_escape = 1;
377     } else {
378     send_char:
379         return 1;
380     }
381     return 0;
382 }
383
384 static void mux_chr_accept_input(CharDriverState *chr)
385 {
386     MuxDriver *d = chr->opaque;
387     int m = d->focus;
388
389     while (d->prod[m] != d->cons[m] &&
390            d->chr_can_read[m] &&
391            d->chr_can_read[m](d->ext_opaque[m])) {
392         d->chr_read[m](d->ext_opaque[m],
393                        &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
394     }
395 }
396
397 static int mux_chr_can_read(void *opaque)
398 {
399     CharDriverState *chr = opaque;
400     MuxDriver *d = chr->opaque;
401     int m = d->focus;
402
403     if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
404         return 1;
405     if (d->chr_can_read[m])
406         return d->chr_can_read[m](d->ext_opaque[m]);
407     return 0;
408 }
409
410 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
411 {
412     CharDriverState *chr = opaque;
413     MuxDriver *d = chr->opaque;
414     int m = d->focus;
415     int i;
416
417     mux_chr_accept_input (opaque);
418
419     for(i = 0; i < size; i++)
420         if (mux_proc_byte(chr, d, buf[i])) {
421             if (d->prod[m] == d->cons[m] &&
422                 d->chr_can_read[m] &&
423                 d->chr_can_read[m](d->ext_opaque[m]))
424                 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
425             else
426                 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
427         }
428 }
429
430 static void mux_chr_event(void *opaque, int event)
431 {
432     CharDriverState *chr = opaque;
433     MuxDriver *d = chr->opaque;
434     int i;
435
436     /* Send the event to all registered listeners */
437     for (i = 0; i < d->mux_cnt; i++)
438         mux_chr_send_event(d, i, event);
439 }
440
441 static void mux_chr_update_read_handler(CharDriverState *chr)
442 {
443     MuxDriver *d = chr->opaque;
444
445     if (d->mux_cnt >= MAX_MUX) {
446         fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
447         return;
448     }
449     d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
450     d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
451     d->chr_read[d->mux_cnt] = chr->chr_read;
452     d->chr_event[d->mux_cnt] = chr->chr_event;
453     /* Fix up the real driver with mux routines */
454     if (d->mux_cnt == 0) {
455         qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
456                               mux_chr_event, chr);
457     }
458     if (d->focus != -1) {
459         mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
460     }
461     d->focus = d->mux_cnt;
462     d->mux_cnt++;
463     mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
464 }
465
466 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
467 {
468     CharDriverState *chr;
469     MuxDriver *d;
470
471     chr = g_malloc0(sizeof(CharDriverState));
472     d = g_malloc0(sizeof(MuxDriver));
473
474     chr->opaque = d;
475     d->drv = drv;
476     d->focus = -1;
477     chr->chr_write = mux_chr_write;
478     chr->chr_update_read_handler = mux_chr_update_read_handler;
479     chr->chr_accept_input = mux_chr_accept_input;
480     /* Frontend guest-open / -close notification is not support with muxes */
481     chr->chr_guest_open = NULL;
482     chr->chr_guest_close = NULL;
483
484     /* Muxes are always open on creation */
485     qemu_chr_generic_open(chr);
486
487     return chr;
488 }
489
490
491 #ifdef _WIN32
492 int send_all(int fd, const void *buf, int len1)
493 {
494     int ret, len;
495
496     len = len1;
497     while (len > 0) {
498         ret = send(fd, buf, len, 0);
499         if (ret < 0) {
500             errno = WSAGetLastError();
501             if (errno != WSAEWOULDBLOCK) {
502                 return -1;
503             }
504         } else if (ret == 0) {
505             break;
506         } else {
507             buf += ret;
508             len -= ret;
509         }
510     }
511     return len1 - len;
512 }
513
514 #else
515
516 int send_all(int fd, const void *_buf, int len1)
517 {
518     int ret, len;
519     const uint8_t *buf = _buf;
520
521     len = len1;
522     while (len > 0) {
523         ret = write(fd, buf, len);
524         if (ret < 0) {
525             if (errno != EINTR && errno != EAGAIN)
526                 return -1;
527         } else if (ret == 0) {
528             break;
529         } else {
530             buf += ret;
531             len -= ret;
532         }
533     }
534     return len1 - len;
535 }
536
537 int recv_all(int fd, void *_buf, int len1, bool single_read)
538 {
539     int ret, len;
540     uint8_t *buf = _buf;
541
542     len = len1;
543     while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
544         if (ret < 0) {
545             if (errno != EINTR && errno != EAGAIN) {
546                 return -1;
547             }
548             continue;
549         } else {
550             if (single_read) {
551                 return ret;
552             }
553             buf += ret;
554             len -= ret;
555         }
556     }
557     return len1 - len;
558 }
559
560 #endif /* !_WIN32 */
561
562 typedef struct IOWatchPoll
563 {
564     GSource *src;
565     int max_size;
566
567     IOCanReadHandler *fd_can_read;
568     void *opaque;
569
570     QTAILQ_ENTRY(IOWatchPoll) node;
571 } IOWatchPoll;
572
573 static QTAILQ_HEAD(, IOWatchPoll) io_watch_poll_list =
574     QTAILQ_HEAD_INITIALIZER(io_watch_poll_list);
575
576 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
577 {
578     IOWatchPoll *i;
579
580     QTAILQ_FOREACH(i, &io_watch_poll_list, node) {
581         if (i->src == source) {
582             return i;
583         }
584     }
585
586     return NULL;
587 }
588
589 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
590 {
591     IOWatchPoll *iwp = io_watch_poll_from_source(source);
592
593     iwp->max_size = iwp->fd_can_read(iwp->opaque);
594     if (iwp->max_size == 0) {
595         return FALSE;
596     }
597
598     return g_io_watch_funcs.prepare(source, timeout_);
599 }
600
601 static gboolean io_watch_poll_check(GSource *source)
602 {
603     IOWatchPoll *iwp = io_watch_poll_from_source(source);
604
605     if (iwp->max_size == 0) {
606         return FALSE;
607     }
608
609     return g_io_watch_funcs.check(source);
610 }
611
612 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
613                                        gpointer user_data)
614 {
615     return g_io_watch_funcs.dispatch(source, callback, user_data);
616 }
617
618 static void io_watch_poll_finalize(GSource *source)
619 {
620     IOWatchPoll *iwp = io_watch_poll_from_source(source);
621     QTAILQ_REMOVE(&io_watch_poll_list, iwp, node);
622     g_io_watch_funcs.finalize(source);
623 }
624
625 static GSourceFuncs io_watch_poll_funcs = {
626     .prepare = io_watch_poll_prepare,
627     .check = io_watch_poll_check,
628     .dispatch = io_watch_poll_dispatch,
629     .finalize = io_watch_poll_finalize,
630 };
631
632 /* Can only be used for read */
633 static guint io_add_watch_poll(GIOChannel *channel,
634                                IOCanReadHandler *fd_can_read,
635                                GIOFunc fd_read,
636                                gpointer user_data)
637 {
638     IOWatchPoll *iwp;
639     GSource *src;
640     guint tag;
641
642     src = g_io_create_watch(channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
643     g_source_set_funcs(src, &io_watch_poll_funcs);
644     g_source_set_callback(src, (GSourceFunc)fd_read, user_data, NULL);
645     tag = g_source_attach(src, NULL);
646     g_source_unref(src);
647
648     iwp = g_malloc0(sizeof(*iwp));
649     iwp->src = src;
650     iwp->max_size = 0;
651     iwp->fd_can_read = fd_can_read;
652     iwp->opaque = user_data;
653
654     QTAILQ_INSERT_HEAD(&io_watch_poll_list, iwp, node);
655
656     return tag;
657 }
658
659 #ifndef _WIN32
660 static GIOChannel *io_channel_from_fd(int fd)
661 {
662     GIOChannel *chan;
663
664     if (fd == -1) {
665         return NULL;
666     }
667
668     chan = g_io_channel_unix_new(fd);
669
670     g_io_channel_set_encoding(chan, NULL, NULL);
671     g_io_channel_set_buffered(chan, FALSE);
672
673     return chan;
674 }
675 #endif
676
677 static GIOChannel *io_channel_from_socket(int fd)
678 {
679     GIOChannel *chan;
680
681     if (fd == -1) {
682         return NULL;
683     }
684
685 #ifdef _WIN32
686     chan = g_io_channel_win32_new_socket(fd);
687 #else
688     chan = g_io_channel_unix_new(fd);
689 #endif
690
691     g_io_channel_set_encoding(chan, NULL, NULL);
692     g_io_channel_set_buffered(chan, FALSE);
693
694     return chan;
695 }
696
697 static int io_channel_send_all(GIOChannel *fd, const void *_buf, int len1)
698 {
699     GIOStatus status;
700     gsize bytes_written;
701     int len;
702     const uint8_t *buf = _buf;
703
704     len = len1;
705     while (len > 0) {
706         status = g_io_channel_write_chars(fd, (const gchar *)buf, len,
707                                           &bytes_written, NULL);
708         if (status != G_IO_STATUS_NORMAL) {
709             if (status == G_IO_STATUS_AGAIN) {
710                 errno = EAGAIN;
711                 return -1;
712             } else {
713                 errno = EINVAL;
714                 return -1;
715             }
716         } else if (status == G_IO_STATUS_EOF) {
717             break;
718         } else {
719             buf += bytes_written;
720             len -= bytes_written;
721         }
722     }
723     return len1 - len;
724 }
725
726 #ifndef _WIN32
727
728 typedef struct FDCharDriver {
729     CharDriverState *chr;
730     GIOChannel *fd_in, *fd_out;
731     guint fd_in_tag;
732     int max_size;
733     QTAILQ_ENTRY(FDCharDriver) node;
734 } FDCharDriver;
735
736 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
737 {
738     FDCharDriver *s = chr->opaque;
739     
740     return io_channel_send_all(s->fd_out, buf, len);
741 }
742
743 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
744 {
745     CharDriverState *chr = opaque;
746     FDCharDriver *s = chr->opaque;
747     int len;
748     uint8_t buf[READ_BUF_LEN];
749     GIOStatus status;
750     gsize bytes_read;
751
752     len = sizeof(buf);
753     if (len > s->max_size) {
754         len = s->max_size;
755     }
756     if (len == 0) {
757         return FALSE;
758     }
759
760     status = g_io_channel_read_chars(chan, (gchar *)buf,
761                                      len, &bytes_read, NULL);
762     if (status == G_IO_STATUS_EOF) {
763         qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
764         return FALSE;
765     }
766     if (status == G_IO_STATUS_NORMAL) {
767         qemu_chr_be_write(chr, buf, bytes_read);
768     }
769
770     return TRUE;
771 }
772
773 static int fd_chr_read_poll(void *opaque)
774 {
775     CharDriverState *chr = opaque;
776     FDCharDriver *s = chr->opaque;
777
778     s->max_size = qemu_chr_be_can_write(chr);
779     return s->max_size;
780 }
781
782 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
783 {
784     FDCharDriver *s = chr->opaque;
785     return g_io_create_watch(s->fd_out, cond);
786 }
787
788 static void fd_chr_update_read_handler(CharDriverState *chr)
789 {
790     FDCharDriver *s = chr->opaque;
791
792     if (s->fd_in_tag) {
793         g_source_remove(s->fd_in_tag);
794     }
795
796     if (s->fd_in) {
797         s->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll, fd_chr_read, chr);
798     }
799 }
800
801 static void fd_chr_close(struct CharDriverState *chr)
802 {
803     FDCharDriver *s = chr->opaque;
804
805     if (s->fd_in_tag) {
806         g_source_remove(s->fd_in_tag);
807         s->fd_in_tag = 0;
808     }
809
810     if (s->fd_in) {
811         g_io_channel_unref(s->fd_in);
812     }
813     if (s->fd_out) {
814         g_io_channel_unref(s->fd_out);
815     }
816
817     g_free(s);
818     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
819 }
820
821 /* open a character device to a unix fd */
822 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
823 {
824     CharDriverState *chr;
825     FDCharDriver *s;
826
827     chr = g_malloc0(sizeof(CharDriverState));
828     s = g_malloc0(sizeof(FDCharDriver));
829     s->fd_in = io_channel_from_fd(fd_in);
830     s->fd_out = io_channel_from_fd(fd_out);
831     fcntl(fd_out, F_SETFL, O_NONBLOCK);
832     s->chr = chr;
833     chr->opaque = s;
834     chr->chr_add_watch = fd_chr_add_watch;
835     chr->chr_write = fd_chr_write;
836     chr->chr_update_read_handler = fd_chr_update_read_handler;
837     chr->chr_close = fd_chr_close;
838
839     qemu_chr_generic_open(chr);
840
841     return chr;
842 }
843
844 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
845 {
846     int fd_in, fd_out;
847     char filename_in[256], filename_out[256];
848     const char *filename = opts->device;
849
850     if (filename == NULL) {
851         fprintf(stderr, "chardev: pipe: no filename given\n");
852         return NULL;
853     }
854
855     snprintf(filename_in, 256, "%s.in", filename);
856     snprintf(filename_out, 256, "%s.out", filename);
857     TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
858     TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
859     if (fd_in < 0 || fd_out < 0) {
860         if (fd_in >= 0)
861             close(fd_in);
862         if (fd_out >= 0)
863             close(fd_out);
864         TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
865         if (fd_in < 0) {
866             return NULL;
867         }
868     }
869     return qemu_chr_open_fd(fd_in, fd_out);
870 }
871
872 /* init terminal so that we can grab keys */
873 static struct termios oldtty;
874 static int old_fd0_flags;
875 static bool stdio_allow_signal;
876
877 static void term_exit(void)
878 {
879     tcsetattr (0, TCSANOW, &oldtty);
880     fcntl(0, F_SETFL, old_fd0_flags);
881 }
882
883 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
884 {
885     struct termios tty;
886
887     tty = oldtty;
888     if (!echo) {
889         tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
890                           |INLCR|IGNCR|ICRNL|IXON);
891         tty.c_oflag |= OPOST;
892         tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
893         tty.c_cflag &= ~(CSIZE|PARENB);
894         tty.c_cflag |= CS8;
895         tty.c_cc[VMIN] = 1;
896         tty.c_cc[VTIME] = 0;
897     }
898     /* if graphical mode, we allow Ctrl-C handling */
899     if (!stdio_allow_signal)
900         tty.c_lflag &= ~ISIG;
901
902     tcsetattr (0, TCSANOW, &tty);
903 }
904
905 static void qemu_chr_close_stdio(struct CharDriverState *chr)
906 {
907     term_exit();
908     fd_chr_close(chr);
909 }
910
911 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
912 {
913     CharDriverState *chr;
914
915     if (is_daemonized()) {
916         error_report("cannot use stdio with -daemonize");
917         return NULL;
918     }
919     old_fd0_flags = fcntl(0, F_GETFL);
920     tcgetattr (0, &oldtty);
921     fcntl(0, F_SETFL, O_NONBLOCK);
922     atexit(term_exit);
923
924     chr = qemu_chr_open_fd(0, 1);
925     chr->chr_close = qemu_chr_close_stdio;
926     chr->chr_set_echo = qemu_chr_set_echo_stdio;
927     stdio_allow_signal = display_type != DT_NOGRAPHIC;
928     if (opts->has_signal) {
929         stdio_allow_signal = opts->signal;
930     }
931     qemu_chr_fe_set_echo(chr, false);
932
933     return chr;
934 }
935
936 #ifdef __sun__
937 /* Once Solaris has openpty(), this is going to be removed. */
938 static int openpty(int *amaster, int *aslave, char *name,
939                    struct termios *termp, struct winsize *winp)
940 {
941         const char *slave;
942         int mfd = -1, sfd = -1;
943
944         *amaster = *aslave = -1;
945
946         mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
947         if (mfd < 0)
948                 goto err;
949
950         if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
951                 goto err;
952
953         if ((slave = ptsname(mfd)) == NULL)
954                 goto err;
955
956         if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
957                 goto err;
958
959         if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
960             (termp != NULL && tcgetattr(sfd, termp) < 0))
961                 goto err;
962
963         if (amaster)
964                 *amaster = mfd;
965         if (aslave)
966                 *aslave = sfd;
967         if (winp)
968                 ioctl(sfd, TIOCSWINSZ, winp);
969
970         return 0;
971
972 err:
973         if (sfd != -1)
974                 close(sfd);
975         close(mfd);
976         return -1;
977 }
978
979 static void cfmakeraw (struct termios *termios_p)
980 {
981         termios_p->c_iflag &=
982                 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
983         termios_p->c_oflag &= ~OPOST;
984         termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
985         termios_p->c_cflag &= ~(CSIZE|PARENB);
986         termios_p->c_cflag |= CS8;
987
988         termios_p->c_cc[VMIN] = 0;
989         termios_p->c_cc[VTIME] = 0;
990 }
991 #endif
992
993 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
994     || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
995     || defined(__GLIBC__)
996
997 #define HAVE_CHARDEV_TTY 1
998
999 typedef struct {
1000     GIOChannel *fd;
1001     guint fd_tag;
1002     int connected;
1003     int polling;
1004     int read_bytes;
1005     guint timer_tag;
1006 } PtyCharDriver;
1007
1008 static void pty_chr_update_read_handler(CharDriverState *chr);
1009 static void pty_chr_state(CharDriverState *chr, int connected);
1010
1011 static gboolean pty_chr_timer(gpointer opaque)
1012 {
1013     struct CharDriverState *chr = opaque;
1014     PtyCharDriver *s = chr->opaque;
1015
1016     if (s->connected) {
1017         goto out;
1018     }
1019     if (s->polling) {
1020         /* If we arrive here without polling being cleared due
1021          * read returning -EIO, then we are (re-)connected */
1022         pty_chr_state(chr, 1);
1023         goto out;
1024     }
1025
1026     /* Next poll ... */
1027     pty_chr_update_read_handler(chr);
1028
1029 out:
1030     return FALSE;
1031 }
1032
1033 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1034 {
1035     PtyCharDriver *s = chr->opaque;
1036
1037     if (s->timer_tag) {
1038         g_source_remove(s->timer_tag);
1039         s->timer_tag = 0;
1040     }
1041
1042     if (ms == 1000) {
1043         s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1044     } else {
1045         s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1046     }
1047 }
1048
1049 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1050 {
1051     PtyCharDriver *s = chr->opaque;
1052
1053     if (!s->connected) {
1054         /* guest sends data, check for (re-)connect */
1055         pty_chr_update_read_handler(chr);
1056         return 0;
1057     }
1058     return io_channel_send_all(s->fd, buf, len);
1059 }
1060
1061 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1062 {
1063     PtyCharDriver *s = chr->opaque;
1064     return g_io_create_watch(s->fd, cond);
1065 }
1066
1067 static int pty_chr_read_poll(void *opaque)
1068 {
1069     CharDriverState *chr = opaque;
1070     PtyCharDriver *s = chr->opaque;
1071
1072     s->read_bytes = qemu_chr_be_can_write(chr);
1073     return s->read_bytes;
1074 }
1075
1076 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1077 {
1078     CharDriverState *chr = opaque;
1079     PtyCharDriver *s = chr->opaque;
1080     gsize size, len;
1081     uint8_t buf[READ_BUF_LEN];
1082     GIOStatus status;
1083
1084     len = sizeof(buf);
1085     if (len > s->read_bytes)
1086         len = s->read_bytes;
1087     if (len == 0)
1088         return FALSE;
1089     status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1090     if (status != G_IO_STATUS_NORMAL) {
1091         pty_chr_state(chr, 0);
1092         return FALSE;
1093     } else {
1094         pty_chr_state(chr, 1);
1095         qemu_chr_be_write(chr, buf, size);
1096     }
1097     return TRUE;
1098 }
1099
1100 static void pty_chr_update_read_handler(CharDriverState *chr)
1101 {
1102     PtyCharDriver *s = chr->opaque;
1103
1104     if (s->fd_tag) {
1105         g_source_remove(s->fd_tag);
1106     }
1107
1108     s->fd_tag = io_add_watch_poll(s->fd, pty_chr_read_poll, pty_chr_read, chr);
1109     s->polling = 1;
1110     /*
1111      * Short timeout here: just need wait long enougth that qemu makes
1112      * it through the poll loop once.  When reconnected we want a
1113      * short timeout so we notice it almost instantly.  Otherwise
1114      * read() gives us -EIO instantly, making pty_chr_state() reset the
1115      * timeout to the normal (much longer) poll interval before the
1116      * timer triggers.
1117      */
1118     pty_chr_rearm_timer(chr, 10);
1119 }
1120
1121 static void pty_chr_state(CharDriverState *chr, int connected)
1122 {
1123     PtyCharDriver *s = chr->opaque;
1124
1125     if (!connected) {
1126         g_source_remove(s->fd_tag);
1127         s->fd_tag = 0;
1128         s->connected = 0;
1129         s->polling = 0;
1130         /* (re-)connect poll interval for idle guests: once per second.
1131          * We check more frequently in case the guests sends data to
1132          * the virtual device linked to our pty. */
1133         pty_chr_rearm_timer(chr, 1000);
1134     } else {
1135         if (!s->connected)
1136             qemu_chr_generic_open(chr);
1137         s->connected = 1;
1138     }
1139 }
1140
1141
1142 static void pty_chr_close(struct CharDriverState *chr)
1143 {
1144     PtyCharDriver *s = chr->opaque;
1145     int fd;
1146
1147     if (s->fd_tag) {
1148         g_source_remove(s->fd_tag);
1149     }
1150     fd = g_io_channel_unix_get_fd(s->fd);
1151     g_io_channel_unref(s->fd);
1152     close(fd);
1153     if (s->timer_tag) {
1154         g_source_remove(s->timer_tag);
1155     }
1156     g_free(s);
1157     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1158 }
1159
1160 static CharDriverState *qemu_chr_open_pty(const char *id,
1161                                           ChardevReturn *ret)
1162 {
1163     CharDriverState *chr;
1164     PtyCharDriver *s;
1165     struct termios tty;
1166     int master_fd, slave_fd;
1167 #if defined(__OpenBSD__) || defined(__DragonFly__)
1168     char pty_name[PATH_MAX];
1169 #define q_ptsname(x) pty_name
1170 #else
1171     char *pty_name = NULL;
1172 #define q_ptsname(x) ptsname(x)
1173 #endif
1174
1175     if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1176         return NULL;
1177     }
1178
1179     /* Set raw attributes on the pty. */
1180     tcgetattr(slave_fd, &tty);
1181     cfmakeraw(&tty);
1182     tcsetattr(slave_fd, TCSAFLUSH, &tty);
1183     close(slave_fd);
1184
1185     chr = g_malloc0(sizeof(CharDriverState));
1186
1187     chr->filename = g_strdup_printf("pty:%s", q_ptsname(master_fd));
1188     ret->pty = g_strdup(q_ptsname(master_fd));
1189     ret->has_pty = true;
1190
1191     fprintf(stderr, "char device redirected to %s (label %s)\n",
1192             q_ptsname(master_fd), id);
1193
1194     s = g_malloc0(sizeof(PtyCharDriver));
1195     chr->opaque = s;
1196     chr->chr_write = pty_chr_write;
1197     chr->chr_update_read_handler = pty_chr_update_read_handler;
1198     chr->chr_close = pty_chr_close;
1199     chr->chr_add_watch = pty_chr_add_watch;
1200
1201     s->fd = io_channel_from_fd(master_fd);
1202     s->timer_tag = 0;
1203
1204     return chr;
1205 }
1206
1207 static void tty_serial_init(int fd, int speed,
1208                             int parity, int data_bits, int stop_bits)
1209 {
1210     struct termios tty;
1211     speed_t spd;
1212
1213 #if 0
1214     printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1215            speed, parity, data_bits, stop_bits);
1216 #endif
1217     tcgetattr (fd, &tty);
1218
1219 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1220     speed = speed * 10 / 11;
1221     do {
1222         check_speed(50);
1223         check_speed(75);
1224         check_speed(110);
1225         check_speed(134);
1226         check_speed(150);
1227         check_speed(200);
1228         check_speed(300);
1229         check_speed(600);
1230         check_speed(1200);
1231         check_speed(1800);
1232         check_speed(2400);
1233         check_speed(4800);
1234         check_speed(9600);
1235         check_speed(19200);
1236         check_speed(38400);
1237         /* Non-Posix values follow. They may be unsupported on some systems. */
1238         check_speed(57600);
1239         check_speed(115200);
1240 #ifdef B230400
1241         check_speed(230400);
1242 #endif
1243 #ifdef B460800
1244         check_speed(460800);
1245 #endif
1246 #ifdef B500000
1247         check_speed(500000);
1248 #endif
1249 #ifdef B576000
1250         check_speed(576000);
1251 #endif
1252 #ifdef B921600
1253         check_speed(921600);
1254 #endif
1255 #ifdef B1000000
1256         check_speed(1000000);
1257 #endif
1258 #ifdef B1152000
1259         check_speed(1152000);
1260 #endif
1261 #ifdef B1500000
1262         check_speed(1500000);
1263 #endif
1264 #ifdef B2000000
1265         check_speed(2000000);
1266 #endif
1267 #ifdef B2500000
1268         check_speed(2500000);
1269 #endif
1270 #ifdef B3000000
1271         check_speed(3000000);
1272 #endif
1273 #ifdef B3500000
1274         check_speed(3500000);
1275 #endif
1276 #ifdef B4000000
1277         check_speed(4000000);
1278 #endif
1279         spd = B115200;
1280     } while (0);
1281
1282     cfsetispeed(&tty, spd);
1283     cfsetospeed(&tty, spd);
1284
1285     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1286                           |INLCR|IGNCR|ICRNL|IXON);
1287     tty.c_oflag |= OPOST;
1288     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1289     tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1290     switch(data_bits) {
1291     default:
1292     case 8:
1293         tty.c_cflag |= CS8;
1294         break;
1295     case 7:
1296         tty.c_cflag |= CS7;
1297         break;
1298     case 6:
1299         tty.c_cflag |= CS6;
1300         break;
1301     case 5:
1302         tty.c_cflag |= CS5;
1303         break;
1304     }
1305     switch(parity) {
1306     default:
1307     case 'N':
1308         break;
1309     case 'E':
1310         tty.c_cflag |= PARENB;
1311         break;
1312     case 'O':
1313         tty.c_cflag |= PARENB | PARODD;
1314         break;
1315     }
1316     if (stop_bits == 2)
1317         tty.c_cflag |= CSTOPB;
1318
1319     tcsetattr (fd, TCSANOW, &tty);
1320 }
1321
1322 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1323 {
1324     FDCharDriver *s = chr->opaque;
1325
1326     switch(cmd) {
1327     case CHR_IOCTL_SERIAL_SET_PARAMS:
1328         {
1329             QEMUSerialSetParams *ssp = arg;
1330             tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1331                             ssp->speed, ssp->parity,
1332                             ssp->data_bits, ssp->stop_bits);
1333         }
1334         break;
1335     case CHR_IOCTL_SERIAL_SET_BREAK:
1336         {
1337             int enable = *(int *)arg;
1338             if (enable) {
1339                 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1340             }
1341         }
1342         break;
1343     case CHR_IOCTL_SERIAL_GET_TIOCM:
1344         {
1345             int sarg = 0;
1346             int *targ = (int *)arg;
1347             ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1348             *targ = 0;
1349             if (sarg & TIOCM_CTS)
1350                 *targ |= CHR_TIOCM_CTS;
1351             if (sarg & TIOCM_CAR)
1352                 *targ |= CHR_TIOCM_CAR;
1353             if (sarg & TIOCM_DSR)
1354                 *targ |= CHR_TIOCM_DSR;
1355             if (sarg & TIOCM_RI)
1356                 *targ |= CHR_TIOCM_RI;
1357             if (sarg & TIOCM_DTR)
1358                 *targ |= CHR_TIOCM_DTR;
1359             if (sarg & TIOCM_RTS)
1360                 *targ |= CHR_TIOCM_RTS;
1361         }
1362         break;
1363     case CHR_IOCTL_SERIAL_SET_TIOCM:
1364         {
1365             int sarg = *(int *)arg;
1366             int targ = 0;
1367             ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1368             targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1369                      | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1370             if (sarg & CHR_TIOCM_CTS)
1371                 targ |= TIOCM_CTS;
1372             if (sarg & CHR_TIOCM_CAR)
1373                 targ |= TIOCM_CAR;
1374             if (sarg & CHR_TIOCM_DSR)
1375                 targ |= TIOCM_DSR;
1376             if (sarg & CHR_TIOCM_RI)
1377                 targ |= TIOCM_RI;
1378             if (sarg & CHR_TIOCM_DTR)
1379                 targ |= TIOCM_DTR;
1380             if (sarg & CHR_TIOCM_RTS)
1381                 targ |= TIOCM_RTS;
1382             ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1383         }
1384         break;
1385     default:
1386         return -ENOTSUP;
1387     }
1388     return 0;
1389 }
1390
1391 static void qemu_chr_close_tty(CharDriverState *chr)
1392 {
1393     FDCharDriver *s = chr->opaque;
1394     int fd = -1;
1395
1396     if (s) {
1397         fd = g_io_channel_unix_get_fd(s->fd_in);
1398     }
1399
1400     fd_chr_close(chr);
1401
1402     if (fd >= 0) {
1403         close(fd);
1404     }
1405 }
1406
1407 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1408 {
1409     CharDriverState *chr;
1410
1411     tty_serial_init(fd, 115200, 'N', 8, 1);
1412     chr = qemu_chr_open_fd(fd, fd);
1413     chr->chr_ioctl = tty_serial_ioctl;
1414     chr->chr_close = qemu_chr_close_tty;
1415     return chr;
1416 }
1417 #endif /* __linux__ || __sun__ */
1418
1419 #if defined(__linux__)
1420
1421 #define HAVE_CHARDEV_PARPORT 1
1422
1423 typedef struct {
1424     int fd;
1425     int mode;
1426 } ParallelCharDriver;
1427
1428 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1429 {
1430     if (s->mode != mode) {
1431         int m = mode;
1432         if (ioctl(s->fd, PPSETMODE, &m) < 0)
1433             return 0;
1434         s->mode = mode;
1435     }
1436     return 1;
1437 }
1438
1439 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1440 {
1441     ParallelCharDriver *drv = chr->opaque;
1442     int fd = drv->fd;
1443     uint8_t b;
1444
1445     switch(cmd) {
1446     case CHR_IOCTL_PP_READ_DATA:
1447         if (ioctl(fd, PPRDATA, &b) < 0)
1448             return -ENOTSUP;
1449         *(uint8_t *)arg = b;
1450         break;
1451     case CHR_IOCTL_PP_WRITE_DATA:
1452         b = *(uint8_t *)arg;
1453         if (ioctl(fd, PPWDATA, &b) < 0)
1454             return -ENOTSUP;
1455         break;
1456     case CHR_IOCTL_PP_READ_CONTROL:
1457         if (ioctl(fd, PPRCONTROL, &b) < 0)
1458             return -ENOTSUP;
1459         /* Linux gives only the lowest bits, and no way to know data
1460            direction! For better compatibility set the fixed upper
1461            bits. */
1462         *(uint8_t *)arg = b | 0xc0;
1463         break;
1464     case CHR_IOCTL_PP_WRITE_CONTROL:
1465         b = *(uint8_t *)arg;
1466         if (ioctl(fd, PPWCONTROL, &b) < 0)
1467             return -ENOTSUP;
1468         break;
1469     case CHR_IOCTL_PP_READ_STATUS:
1470         if (ioctl(fd, PPRSTATUS, &b) < 0)
1471             return -ENOTSUP;
1472         *(uint8_t *)arg = b;
1473         break;
1474     case CHR_IOCTL_PP_DATA_DIR:
1475         if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1476             return -ENOTSUP;
1477         break;
1478     case CHR_IOCTL_PP_EPP_READ_ADDR:
1479         if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1480             struct ParallelIOArg *parg = arg;
1481             int n = read(fd, parg->buffer, parg->count);
1482             if (n != parg->count) {
1483                 return -EIO;
1484             }
1485         }
1486         break;
1487     case CHR_IOCTL_PP_EPP_READ:
1488         if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1489             struct ParallelIOArg *parg = arg;
1490             int n = read(fd, parg->buffer, parg->count);
1491             if (n != parg->count) {
1492                 return -EIO;
1493             }
1494         }
1495         break;
1496     case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1497         if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1498             struct ParallelIOArg *parg = arg;
1499             int n = write(fd, parg->buffer, parg->count);
1500             if (n != parg->count) {
1501                 return -EIO;
1502             }
1503         }
1504         break;
1505     case CHR_IOCTL_PP_EPP_WRITE:
1506         if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1507             struct ParallelIOArg *parg = arg;
1508             int n = write(fd, parg->buffer, parg->count);
1509             if (n != parg->count) {
1510                 return -EIO;
1511             }
1512         }
1513         break;
1514     default:
1515         return -ENOTSUP;
1516     }
1517     return 0;
1518 }
1519
1520 static void pp_close(CharDriverState *chr)
1521 {
1522     ParallelCharDriver *drv = chr->opaque;
1523     int fd = drv->fd;
1524
1525     pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1526     ioctl(fd, PPRELEASE);
1527     close(fd);
1528     g_free(drv);
1529     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1530 }
1531
1532 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1533 {
1534     CharDriverState *chr;
1535     ParallelCharDriver *drv;
1536
1537     if (ioctl(fd, PPCLAIM) < 0) {
1538         close(fd);
1539         return NULL;
1540     }
1541
1542     drv = g_malloc0(sizeof(ParallelCharDriver));
1543     drv->fd = fd;
1544     drv->mode = IEEE1284_MODE_COMPAT;
1545
1546     chr = g_malloc0(sizeof(CharDriverState));
1547     chr->chr_write = null_chr_write;
1548     chr->chr_ioctl = pp_ioctl;
1549     chr->chr_close = pp_close;
1550     chr->opaque = drv;
1551
1552     qemu_chr_generic_open(chr);
1553
1554     return chr;
1555 }
1556 #endif /* __linux__ */
1557
1558 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1559
1560 #define HAVE_CHARDEV_PARPORT 1
1561
1562 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1563 {
1564     int fd = (int)(intptr_t)chr->opaque;
1565     uint8_t b;
1566
1567     switch(cmd) {
1568     case CHR_IOCTL_PP_READ_DATA:
1569         if (ioctl(fd, PPIGDATA, &b) < 0)
1570             return -ENOTSUP;
1571         *(uint8_t *)arg = b;
1572         break;
1573     case CHR_IOCTL_PP_WRITE_DATA:
1574         b = *(uint8_t *)arg;
1575         if (ioctl(fd, PPISDATA, &b) < 0)
1576             return -ENOTSUP;
1577         break;
1578     case CHR_IOCTL_PP_READ_CONTROL:
1579         if (ioctl(fd, PPIGCTRL, &b) < 0)
1580             return -ENOTSUP;
1581         *(uint8_t *)arg = b;
1582         break;
1583     case CHR_IOCTL_PP_WRITE_CONTROL:
1584         b = *(uint8_t *)arg;
1585         if (ioctl(fd, PPISCTRL, &b) < 0)
1586             return -ENOTSUP;
1587         break;
1588     case CHR_IOCTL_PP_READ_STATUS:
1589         if (ioctl(fd, PPIGSTATUS, &b) < 0)
1590             return -ENOTSUP;
1591         *(uint8_t *)arg = b;
1592         break;
1593     default:
1594         return -ENOTSUP;
1595     }
1596     return 0;
1597 }
1598
1599 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1600 {
1601     CharDriverState *chr;
1602
1603     chr = g_malloc0(sizeof(CharDriverState));
1604     chr->opaque = (void *)(intptr_t)fd;
1605     chr->chr_write = null_chr_write;
1606     chr->chr_ioctl = pp_ioctl;
1607     return chr;
1608 }
1609 #endif
1610
1611 #else /* _WIN32 */
1612
1613 typedef struct {
1614     int max_size;
1615     HANDLE hcom, hrecv, hsend;
1616     OVERLAPPED orecv, osend;
1617     BOOL fpipe;
1618     DWORD len;
1619 } WinCharState;
1620
1621 typedef struct {
1622     HANDLE  hStdIn;
1623     HANDLE  hInputReadyEvent;
1624     HANDLE  hInputDoneEvent;
1625     HANDLE  hInputThread;
1626     uint8_t win_stdio_buf;
1627 } WinStdioCharState;
1628
1629 #define NSENDBUF 2048
1630 #define NRECVBUF 2048
1631 #define MAXCONNECT 1
1632 #define NTIMEOUT 5000
1633
1634 static int win_chr_poll(void *opaque);
1635 static int win_chr_pipe_poll(void *opaque);
1636
1637 static void win_chr_close(CharDriverState *chr)
1638 {
1639     WinCharState *s = chr->opaque;
1640
1641     if (s->hsend) {
1642         CloseHandle(s->hsend);
1643         s->hsend = NULL;
1644     }
1645     if (s->hrecv) {
1646         CloseHandle(s->hrecv);
1647         s->hrecv = NULL;
1648     }
1649     if (s->hcom) {
1650         CloseHandle(s->hcom);
1651         s->hcom = NULL;
1652     }
1653     if (s->fpipe)
1654         qemu_del_polling_cb(win_chr_pipe_poll, chr);
1655     else
1656         qemu_del_polling_cb(win_chr_poll, chr);
1657
1658     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1659 }
1660
1661 static int win_chr_init(CharDriverState *chr, const char *filename)
1662 {
1663     WinCharState *s = chr->opaque;
1664     COMMCONFIG comcfg;
1665     COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1666     COMSTAT comstat;
1667     DWORD size;
1668     DWORD err;
1669
1670     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1671     if (!s->hsend) {
1672         fprintf(stderr, "Failed CreateEvent\n");
1673         goto fail;
1674     }
1675     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1676     if (!s->hrecv) {
1677         fprintf(stderr, "Failed CreateEvent\n");
1678         goto fail;
1679     }
1680
1681     s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1682                       OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1683     if (s->hcom == INVALID_HANDLE_VALUE) {
1684         fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1685         s->hcom = NULL;
1686         goto fail;
1687     }
1688
1689     if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1690         fprintf(stderr, "Failed SetupComm\n");
1691         goto fail;
1692     }
1693
1694     ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1695     size = sizeof(COMMCONFIG);
1696     GetDefaultCommConfig(filename, &comcfg, &size);
1697     comcfg.dcb.DCBlength = sizeof(DCB);
1698     CommConfigDialog(filename, NULL, &comcfg);
1699
1700     if (!SetCommState(s->hcom, &comcfg.dcb)) {
1701         fprintf(stderr, "Failed SetCommState\n");
1702         goto fail;
1703     }
1704
1705     if (!SetCommMask(s->hcom, EV_ERR)) {
1706         fprintf(stderr, "Failed SetCommMask\n");
1707         goto fail;
1708     }
1709
1710     cto.ReadIntervalTimeout = MAXDWORD;
1711     if (!SetCommTimeouts(s->hcom, &cto)) {
1712         fprintf(stderr, "Failed SetCommTimeouts\n");
1713         goto fail;
1714     }
1715
1716     if (!ClearCommError(s->hcom, &err, &comstat)) {
1717         fprintf(stderr, "Failed ClearCommError\n");
1718         goto fail;
1719     }
1720     qemu_add_polling_cb(win_chr_poll, chr);
1721     return 0;
1722
1723  fail:
1724     win_chr_close(chr);
1725     return -1;
1726 }
1727
1728 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1729 {
1730     WinCharState *s = chr->opaque;
1731     DWORD len, ret, size, err;
1732
1733     len = len1;
1734     ZeroMemory(&s->osend, sizeof(s->osend));
1735     s->osend.hEvent = s->hsend;
1736     while (len > 0) {
1737         if (s->hsend)
1738             ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1739         else
1740             ret = WriteFile(s->hcom, buf, len, &size, NULL);
1741         if (!ret) {
1742             err = GetLastError();
1743             if (err == ERROR_IO_PENDING) {
1744                 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1745                 if (ret) {
1746                     buf += size;
1747                     len -= size;
1748                 } else {
1749                     break;
1750                 }
1751             } else {
1752                 break;
1753             }
1754         } else {
1755             buf += size;
1756             len -= size;
1757         }
1758     }
1759     return len1 - len;
1760 }
1761
1762 static int win_chr_read_poll(CharDriverState *chr)
1763 {
1764     WinCharState *s = chr->opaque;
1765
1766     s->max_size = qemu_chr_be_can_write(chr);
1767     return s->max_size;
1768 }
1769
1770 static void win_chr_readfile(CharDriverState *chr)
1771 {
1772     WinCharState *s = chr->opaque;
1773     int ret, err;
1774     uint8_t buf[READ_BUF_LEN];
1775     DWORD size;
1776
1777     ZeroMemory(&s->orecv, sizeof(s->orecv));
1778     s->orecv.hEvent = s->hrecv;
1779     ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1780     if (!ret) {
1781         err = GetLastError();
1782         if (err == ERROR_IO_PENDING) {
1783             ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1784         }
1785     }
1786
1787     if (size > 0) {
1788         qemu_chr_be_write(chr, buf, size);
1789     }
1790 }
1791
1792 static void win_chr_read(CharDriverState *chr)
1793 {
1794     WinCharState *s = chr->opaque;
1795
1796     if (s->len > s->max_size)
1797         s->len = s->max_size;
1798     if (s->len == 0)
1799         return;
1800
1801     win_chr_readfile(chr);
1802 }
1803
1804 static int win_chr_poll(void *opaque)
1805 {
1806     CharDriverState *chr = opaque;
1807     WinCharState *s = chr->opaque;
1808     COMSTAT status;
1809     DWORD comerr;
1810
1811     ClearCommError(s->hcom, &comerr, &status);
1812     if (status.cbInQue > 0) {
1813         s->len = status.cbInQue;
1814         win_chr_read_poll(chr);
1815         win_chr_read(chr);
1816         return 1;
1817     }
1818     return 0;
1819 }
1820
1821 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1822 {
1823     CharDriverState *chr;
1824     WinCharState *s;
1825
1826     chr = g_malloc0(sizeof(CharDriverState));
1827     s = g_malloc0(sizeof(WinCharState));
1828     chr->opaque = s;
1829     chr->chr_write = win_chr_write;
1830     chr->chr_close = win_chr_close;
1831
1832     if (win_chr_init(chr, filename) < 0) {
1833         g_free(s);
1834         g_free(chr);
1835         return NULL;
1836     }
1837     qemu_chr_generic_open(chr);
1838     return chr;
1839 }
1840
1841 static int win_chr_pipe_poll(void *opaque)
1842 {
1843     CharDriverState *chr = opaque;
1844     WinCharState *s = chr->opaque;
1845     DWORD size;
1846
1847     PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1848     if (size > 0) {
1849         s->len = size;
1850         win_chr_read_poll(chr);
1851         win_chr_read(chr);
1852         return 1;
1853     }
1854     return 0;
1855 }
1856
1857 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1858 {
1859     WinCharState *s = chr->opaque;
1860     OVERLAPPED ov;
1861     int ret;
1862     DWORD size;
1863     char openname[256];
1864
1865     s->fpipe = TRUE;
1866
1867     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1868     if (!s->hsend) {
1869         fprintf(stderr, "Failed CreateEvent\n");
1870         goto fail;
1871     }
1872     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1873     if (!s->hrecv) {
1874         fprintf(stderr, "Failed CreateEvent\n");
1875         goto fail;
1876     }
1877
1878     snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1879     s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1880                               PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1881                               PIPE_WAIT,
1882                               MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1883     if (s->hcom == INVALID_HANDLE_VALUE) {
1884         fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1885         s->hcom = NULL;
1886         goto fail;
1887     }
1888
1889     ZeroMemory(&ov, sizeof(ov));
1890     ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1891     ret = ConnectNamedPipe(s->hcom, &ov);
1892     if (ret) {
1893         fprintf(stderr, "Failed ConnectNamedPipe\n");
1894         goto fail;
1895     }
1896
1897     ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1898     if (!ret) {
1899         fprintf(stderr, "Failed GetOverlappedResult\n");
1900         if (ov.hEvent) {
1901             CloseHandle(ov.hEvent);
1902             ov.hEvent = NULL;
1903         }
1904         goto fail;
1905     }
1906
1907     if (ov.hEvent) {
1908         CloseHandle(ov.hEvent);
1909         ov.hEvent = NULL;
1910     }
1911     qemu_add_polling_cb(win_chr_pipe_poll, chr);
1912     return 0;
1913
1914  fail:
1915     win_chr_close(chr);
1916     return -1;
1917 }
1918
1919
1920 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
1921 {
1922     const char *filename = opts->device;
1923     CharDriverState *chr;
1924     WinCharState *s;
1925
1926     chr = g_malloc0(sizeof(CharDriverState));
1927     s = g_malloc0(sizeof(WinCharState));
1928     chr->opaque = s;
1929     chr->chr_write = win_chr_write;
1930     chr->chr_close = win_chr_close;
1931
1932     if (win_chr_pipe_init(chr, filename) < 0) {
1933         g_free(s);
1934         g_free(chr);
1935         return NULL;
1936     }
1937     qemu_chr_generic_open(chr);
1938     return chr;
1939 }
1940
1941 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1942 {
1943     CharDriverState *chr;
1944     WinCharState *s;
1945
1946     chr = g_malloc0(sizeof(CharDriverState));
1947     s = g_malloc0(sizeof(WinCharState));
1948     s->hcom = fd_out;
1949     chr->opaque = s;
1950     chr->chr_write = win_chr_write;
1951     qemu_chr_generic_open(chr);
1952     return chr;
1953 }
1954
1955 static CharDriverState *qemu_chr_open_win_con(void)
1956 {
1957     return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1958 }
1959
1960 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1961 {
1962     HANDLE  hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1963     DWORD   dwSize;
1964     int     len1;
1965
1966     len1 = len;
1967
1968     while (len1 > 0) {
1969         if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
1970             break;
1971         }
1972         buf  += dwSize;
1973         len1 -= dwSize;
1974     }
1975
1976     return len - len1;
1977 }
1978
1979 static void win_stdio_wait_func(void *opaque)
1980 {
1981     CharDriverState   *chr   = opaque;
1982     WinStdioCharState *stdio = chr->opaque;
1983     INPUT_RECORD       buf[4];
1984     int                ret;
1985     DWORD              dwSize;
1986     int                i;
1987
1988     ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
1989                            &dwSize);
1990
1991     if (!ret) {
1992         /* Avoid error storm */
1993         qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
1994         return;
1995     }
1996
1997     for (i = 0; i < dwSize; i++) {
1998         KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
1999
2000         if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2001             int j;
2002             if (kev->uChar.AsciiChar != 0) {
2003                 for (j = 0; j < kev->wRepeatCount; j++) {
2004                     if (qemu_chr_be_can_write(chr)) {
2005                         uint8_t c = kev->uChar.AsciiChar;
2006                         qemu_chr_be_write(chr, &c, 1);
2007                     }
2008                 }
2009             }
2010         }
2011     }
2012 }
2013
2014 static DWORD WINAPI win_stdio_thread(LPVOID param)
2015 {
2016     CharDriverState   *chr   = param;
2017     WinStdioCharState *stdio = chr->opaque;
2018     int                ret;
2019     DWORD              dwSize;
2020
2021     while (1) {
2022
2023         /* Wait for one byte */
2024         ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2025
2026         /* Exit in case of error, continue if nothing read */
2027         if (!ret) {
2028             break;
2029         }
2030         if (!dwSize) {
2031             continue;
2032         }
2033
2034         /* Some terminal emulator returns \r\n for Enter, just pass \n */
2035         if (stdio->win_stdio_buf == '\r') {
2036             continue;
2037         }
2038
2039         /* Signal the main thread and wait until the byte was eaten */
2040         if (!SetEvent(stdio->hInputReadyEvent)) {
2041             break;
2042         }
2043         if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2044             != WAIT_OBJECT_0) {
2045             break;
2046         }
2047     }
2048
2049     qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2050     return 0;
2051 }
2052
2053 static void win_stdio_thread_wait_func(void *opaque)
2054 {
2055     CharDriverState   *chr   = opaque;
2056     WinStdioCharState *stdio = chr->opaque;
2057
2058     if (qemu_chr_be_can_write(chr)) {
2059         qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2060     }
2061
2062     SetEvent(stdio->hInputDoneEvent);
2063 }
2064
2065 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2066 {
2067     WinStdioCharState *stdio  = chr->opaque;
2068     DWORD              dwMode = 0;
2069
2070     GetConsoleMode(stdio->hStdIn, &dwMode);
2071
2072     if (echo) {
2073         SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2074     } else {
2075         SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2076     }
2077 }
2078
2079 static void win_stdio_close(CharDriverState *chr)
2080 {
2081     WinStdioCharState *stdio = chr->opaque;
2082
2083     if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2084         CloseHandle(stdio->hInputReadyEvent);
2085     }
2086     if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2087         CloseHandle(stdio->hInputDoneEvent);
2088     }
2089     if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2090         TerminateThread(stdio->hInputThread, 0);
2091     }
2092
2093     g_free(chr->opaque);
2094     g_free(chr);
2095 }
2096
2097 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2098 {
2099     CharDriverState   *chr;
2100     WinStdioCharState *stdio;
2101     DWORD              dwMode;
2102     int                is_console = 0;
2103
2104     chr   = g_malloc0(sizeof(CharDriverState));
2105     stdio = g_malloc0(sizeof(WinStdioCharState));
2106
2107     stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2108     if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2109         fprintf(stderr, "cannot open stdio: invalid handle\n");
2110         exit(1);
2111     }
2112
2113     is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2114
2115     chr->opaque    = stdio;
2116     chr->chr_write = win_stdio_write;
2117     chr->chr_close = win_stdio_close;
2118
2119     if (is_console) {
2120         if (qemu_add_wait_object(stdio->hStdIn,
2121                                  win_stdio_wait_func, chr)) {
2122             fprintf(stderr, "qemu_add_wait_object: failed\n");
2123         }
2124     } else {
2125         DWORD   dwId;
2126             
2127         stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2128         stdio->hInputDoneEvent  = CreateEvent(NULL, FALSE, FALSE, NULL);
2129         stdio->hInputThread     = CreateThread(NULL, 0, win_stdio_thread,
2130                                                chr, 0, &dwId);
2131
2132         if (stdio->hInputThread == INVALID_HANDLE_VALUE
2133             || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2134             || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2135             fprintf(stderr, "cannot create stdio thread or event\n");
2136             exit(1);
2137         }
2138         if (qemu_add_wait_object(stdio->hInputReadyEvent,
2139                                  win_stdio_thread_wait_func, chr)) {
2140             fprintf(stderr, "qemu_add_wait_object: failed\n");
2141         }
2142     }
2143
2144     dwMode |= ENABLE_LINE_INPUT;
2145
2146     if (is_console) {
2147         /* set the terminal in raw mode */
2148         /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2149         dwMode |= ENABLE_PROCESSED_INPUT;
2150     }
2151
2152     SetConsoleMode(stdio->hStdIn, dwMode);
2153
2154     chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2155     qemu_chr_fe_set_echo(chr, false);
2156
2157     return chr;
2158 }
2159 #endif /* !_WIN32 */
2160
2161
2162 /***********************************************************/
2163 /* UDP Net console */
2164
2165 typedef struct {
2166     int fd;
2167     GIOChannel *chan;
2168     guint tag;
2169     uint8_t buf[READ_BUF_LEN];
2170     int bufcnt;
2171     int bufptr;
2172     int max_size;
2173 } NetCharDriver;
2174
2175 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2176 {
2177     NetCharDriver *s = chr->opaque;
2178     gsize bytes_written;
2179     GIOStatus status;
2180
2181     status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2182     if (status == G_IO_STATUS_EOF) {
2183         return 0;
2184     } else if (status != G_IO_STATUS_NORMAL) {
2185         return -1;
2186     }
2187
2188     return bytes_written;
2189 }
2190
2191 static int udp_chr_read_poll(void *opaque)
2192 {
2193     CharDriverState *chr = opaque;
2194     NetCharDriver *s = chr->opaque;
2195
2196     s->max_size = qemu_chr_be_can_write(chr);
2197
2198     /* If there were any stray characters in the queue process them
2199      * first
2200      */
2201     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2202         qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2203         s->bufptr++;
2204         s->max_size = qemu_chr_be_can_write(chr);
2205     }
2206     return s->max_size;
2207 }
2208
2209 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2210 {
2211     CharDriverState *chr = opaque;
2212     NetCharDriver *s = chr->opaque;
2213     gsize bytes_read = 0;
2214     GIOStatus status;
2215
2216     if (s->max_size == 0)
2217         return FALSE;
2218     status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2219                                      &bytes_read, NULL);
2220     s->bufcnt = bytes_read;
2221     s->bufptr = s->bufcnt;
2222     if (status != G_IO_STATUS_NORMAL) {
2223         return FALSE;
2224     }
2225
2226     s->bufptr = 0;
2227     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2228         qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2229         s->bufptr++;
2230         s->max_size = qemu_chr_be_can_write(chr);
2231     }
2232
2233     return TRUE;
2234 }
2235
2236 static void udp_chr_update_read_handler(CharDriverState *chr)
2237 {
2238     NetCharDriver *s = chr->opaque;
2239
2240     if (s->tag) {
2241         g_source_remove(s->tag);
2242         s->tag = 0;
2243     }
2244
2245     if (s->chan) {
2246         s->tag = io_add_watch_poll(s->chan, udp_chr_read_poll, udp_chr_read, chr);
2247     }
2248 }
2249
2250 static void udp_chr_close(CharDriverState *chr)
2251 {
2252     NetCharDriver *s = chr->opaque;
2253     if (s->tag) {
2254         g_source_remove(s->tag);
2255     }
2256     if (s->chan) {
2257         g_io_channel_unref(s->chan);
2258         closesocket(s->fd);
2259     }
2260     g_free(s);
2261     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2262 }
2263
2264 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2265 {
2266     CharDriverState *chr = NULL;
2267     NetCharDriver *s = NULL;
2268
2269     chr = g_malloc0(sizeof(CharDriverState));
2270     s = g_malloc0(sizeof(NetCharDriver));
2271
2272     s->fd = fd;
2273     s->chan = io_channel_from_socket(s->fd);
2274     s->bufcnt = 0;
2275     s->bufptr = 0;
2276     chr->opaque = s;
2277     chr->chr_write = udp_chr_write;
2278     chr->chr_update_read_handler = udp_chr_update_read_handler;
2279     chr->chr_close = udp_chr_close;
2280     return chr;
2281 }
2282
2283 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2284 {
2285     Error *local_err = NULL;
2286     int fd = -1;
2287
2288     fd = inet_dgram_opts(opts, &local_err);
2289     if (fd < 0) {
2290         return NULL;
2291     }
2292     return qemu_chr_open_udp_fd(fd);
2293 }
2294
2295 /***********************************************************/
2296 /* TCP Net console */
2297
2298 typedef struct {
2299
2300     GIOChannel *chan, *listen_chan;
2301     guint tag, listen_tag;
2302     int fd, listen_fd;
2303     int connected;
2304     int max_size;
2305     int do_telnetopt;
2306     int do_nodelay;
2307     int is_unix;
2308     int msgfd;
2309 } TCPCharDriver;
2310
2311 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2312
2313 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2314 {
2315     TCPCharDriver *s = chr->opaque;
2316     if (s->connected) {
2317         return io_channel_send_all(s->chan, buf, len);
2318     } else {
2319         /* XXX: indicate an error ? */
2320         return len;
2321     }
2322 }
2323
2324 static int tcp_chr_read_poll(void *opaque)
2325 {
2326     CharDriverState *chr = opaque;
2327     TCPCharDriver *s = chr->opaque;
2328     if (!s->connected)
2329         return 0;
2330     s->max_size = qemu_chr_be_can_write(chr);
2331     return s->max_size;
2332 }
2333
2334 #define IAC 255
2335 #define IAC_BREAK 243
2336 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2337                                       TCPCharDriver *s,
2338                                       uint8_t *buf, int *size)
2339 {
2340     /* Handle any telnet client's basic IAC options to satisfy char by
2341      * char mode with no echo.  All IAC options will be removed from
2342      * the buf and the do_telnetopt variable will be used to track the
2343      * state of the width of the IAC information.
2344      *
2345      * IAC commands come in sets of 3 bytes with the exception of the
2346      * "IAC BREAK" command and the double IAC.
2347      */
2348
2349     int i;
2350     int j = 0;
2351
2352     for (i = 0; i < *size; i++) {
2353         if (s->do_telnetopt > 1) {
2354             if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2355                 /* Double IAC means send an IAC */
2356                 if (j != i)
2357                     buf[j] = buf[i];
2358                 j++;
2359                 s->do_telnetopt = 1;
2360             } else {
2361                 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2362                     /* Handle IAC break commands by sending a serial break */
2363                     qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2364                     s->do_telnetopt++;
2365                 }
2366                 s->do_telnetopt++;
2367             }
2368             if (s->do_telnetopt >= 4) {
2369                 s->do_telnetopt = 1;
2370             }
2371         } else {
2372             if ((unsigned char)buf[i] == IAC) {
2373                 s->do_telnetopt = 2;
2374             } else {
2375                 if (j != i)
2376                     buf[j] = buf[i];
2377                 j++;
2378             }
2379         }
2380     }
2381     *size = j;
2382 }
2383
2384 static int tcp_get_msgfd(CharDriverState *chr)
2385 {
2386     TCPCharDriver *s = chr->opaque;
2387     int fd = s->msgfd;
2388     s->msgfd = -1;
2389     return fd;
2390 }
2391
2392 #ifndef _WIN32
2393 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2394 {
2395     TCPCharDriver *s = chr->opaque;
2396     struct cmsghdr *cmsg;
2397
2398     for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2399         int fd;
2400
2401         if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2402             cmsg->cmsg_level != SOL_SOCKET ||
2403             cmsg->cmsg_type != SCM_RIGHTS)
2404             continue;
2405
2406         fd = *((int *)CMSG_DATA(cmsg));
2407         if (fd < 0)
2408             continue;
2409
2410 #ifndef MSG_CMSG_CLOEXEC
2411         qemu_set_cloexec(fd);
2412 #endif
2413         if (s->msgfd != -1)
2414             close(s->msgfd);
2415         s->msgfd = fd;
2416     }
2417 }
2418
2419 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2420 {
2421     TCPCharDriver *s = chr->opaque;
2422     struct msghdr msg = { NULL, };
2423     struct iovec iov[1];
2424     union {
2425         struct cmsghdr cmsg;
2426         char control[CMSG_SPACE(sizeof(int))];
2427     } msg_control;
2428     int flags = 0;
2429     ssize_t ret;
2430
2431     iov[0].iov_base = buf;
2432     iov[0].iov_len = len;
2433
2434     msg.msg_iov = iov;
2435     msg.msg_iovlen = 1;
2436     msg.msg_control = &msg_control;
2437     msg.msg_controllen = sizeof(msg_control);
2438
2439 #ifdef MSG_CMSG_CLOEXEC
2440     flags |= MSG_CMSG_CLOEXEC;
2441 #endif
2442     ret = recvmsg(s->fd, &msg, flags);
2443     if (ret > 0 && s->is_unix) {
2444         unix_process_msgfd(chr, &msg);
2445     }
2446
2447     return ret;
2448 }
2449 #else
2450 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2451 {
2452     TCPCharDriver *s = chr->opaque;
2453     return qemu_recv(s->fd, buf, len, 0);
2454 }
2455 #endif
2456
2457 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2458 {
2459     TCPCharDriver *s = chr->opaque;
2460     return g_io_create_watch(s->chan, cond);
2461 }
2462
2463 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2464 {
2465     CharDriverState *chr = opaque;
2466     TCPCharDriver *s = chr->opaque;
2467     uint8_t buf[READ_BUF_LEN];
2468     int len, size;
2469
2470     if (!s->connected || s->max_size <= 0) {
2471         return FALSE;
2472     }
2473     len = sizeof(buf);
2474     if (len > s->max_size)
2475         len = s->max_size;
2476     size = tcp_chr_recv(chr, (void *)buf, len);
2477     if (size == 0) {
2478         /* connection closed */
2479         s->connected = 0;
2480         if (s->listen_chan) {
2481             s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2482         }
2483         g_source_remove(s->tag);
2484         s->tag = 0;
2485         g_io_channel_unref(s->chan);
2486         s->chan = NULL;
2487         closesocket(s->fd);
2488         s->fd = -1;
2489         qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2490     } else if (size > 0) {
2491         if (s->do_telnetopt)
2492             tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2493         if (size > 0)
2494             qemu_chr_be_write(chr, buf, size);
2495     }
2496
2497     return TRUE;
2498 }
2499
2500 #ifndef _WIN32
2501 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2502 {
2503     return qemu_chr_open_fd(eventfd, eventfd);
2504 }
2505 #endif
2506
2507 static void tcp_chr_connect(void *opaque)
2508 {
2509     CharDriverState *chr = opaque;
2510     TCPCharDriver *s = chr->opaque;
2511
2512     s->connected = 1;
2513     if (s->chan) {
2514         s->tag = io_add_watch_poll(s->chan, tcp_chr_read_poll, tcp_chr_read, chr);
2515     }
2516     qemu_chr_generic_open(chr);
2517 }
2518
2519 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2520 static void tcp_chr_telnet_init(int fd)
2521 {
2522     char buf[3];
2523     /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2524     IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2525     send(fd, (char *)buf, 3, 0);
2526     IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2527     send(fd, (char *)buf, 3, 0);
2528     IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2529     send(fd, (char *)buf, 3, 0);
2530     IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2531     send(fd, (char *)buf, 3, 0);
2532 }
2533
2534 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2535 {
2536     TCPCharDriver *s = chr->opaque;
2537     if (s->fd != -1)
2538         return -1;
2539
2540     socket_set_nonblock(fd);
2541     if (s->do_nodelay)
2542         socket_set_nodelay(fd);
2543     s->fd = fd;
2544     s->chan = io_channel_from_socket(fd);
2545     g_source_remove(s->listen_tag);
2546     s->listen_tag = 0;
2547     tcp_chr_connect(chr);
2548
2549     return 0;
2550 }
2551
2552 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2553 {
2554     CharDriverState *chr = opaque;
2555     TCPCharDriver *s = chr->opaque;
2556     struct sockaddr_in saddr;
2557 #ifndef _WIN32
2558     struct sockaddr_un uaddr;
2559 #endif
2560     struct sockaddr *addr;
2561     socklen_t len;
2562     int fd;
2563
2564     for(;;) {
2565 #ifndef _WIN32
2566         if (s->is_unix) {
2567             len = sizeof(uaddr);
2568             addr = (struct sockaddr *)&uaddr;
2569         } else
2570 #endif
2571         {
2572             len = sizeof(saddr);
2573             addr = (struct sockaddr *)&saddr;
2574         }
2575         fd = qemu_accept(s->listen_fd, addr, &len);
2576         if (fd < 0 && errno != EINTR) {
2577             return FALSE;
2578         } else if (fd >= 0) {
2579             if (s->do_telnetopt)
2580                 tcp_chr_telnet_init(fd);
2581             break;
2582         }
2583     }
2584     if (tcp_chr_add_client(chr, fd) < 0)
2585         close(fd);
2586
2587     return TRUE;
2588 }
2589
2590 static void tcp_chr_close(CharDriverState *chr)
2591 {
2592     TCPCharDriver *s = chr->opaque;
2593     if (s->fd >= 0) {
2594         if (s->tag) {
2595             g_source_remove(s->tag);
2596         }
2597         if (s->chan) {
2598             g_io_channel_unref(s->chan);
2599         }
2600         closesocket(s->fd);
2601     }
2602     if (s->listen_fd >= 0) {
2603         if (s->listen_tag) {
2604             g_source_remove(s->listen_tag);
2605         }
2606         if (s->listen_chan) {
2607             g_io_channel_unref(s->listen_chan);
2608         }
2609         closesocket(s->listen_fd);
2610     }
2611     g_free(s);
2612     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2613 }
2614
2615 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2616                                                 bool is_listen, bool is_telnet,
2617                                                 bool is_waitconnect,
2618                                                 Error **errp)
2619 {
2620     CharDriverState *chr = NULL;
2621     TCPCharDriver *s = NULL;
2622     char host[NI_MAXHOST], serv[NI_MAXSERV];
2623     const char *left = "", *right = "";
2624     struct sockaddr_storage ss;
2625     socklen_t ss_len = sizeof(ss);
2626
2627     memset(&ss, 0, ss_len);
2628     if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2629         error_setg(errp, "getsockname: %s", strerror(errno));
2630         return NULL;
2631     }
2632
2633     chr = g_malloc0(sizeof(CharDriverState));
2634     s = g_malloc0(sizeof(TCPCharDriver));
2635
2636     s->connected = 0;
2637     s->fd = -1;
2638     s->listen_fd = -1;
2639     s->msgfd = -1;
2640
2641     chr->filename = g_malloc(256);
2642     switch (ss.ss_family) {
2643 #ifndef _WIN32
2644     case AF_UNIX:
2645         s->is_unix = 1;
2646         snprintf(chr->filename, 256, "unix:%s%s",
2647                  ((struct sockaddr_un *)(&ss))->sun_path,
2648                  is_listen ? ",server" : "");
2649         break;
2650 #endif
2651     case AF_INET6:
2652         left  = "[";
2653         right = "]";
2654         /* fall through */
2655     case AF_INET:
2656         s->do_nodelay = do_nodelay;
2657         getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2658                     serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2659         snprintf(chr->filename, 256, "%s:%s%s%s:%s%s",
2660                  is_telnet ? "telnet" : "tcp",
2661                  left, host, right, serv,
2662                  is_listen ? ",server" : "");
2663         break;
2664     }
2665
2666     chr->opaque = s;
2667     chr->chr_write = tcp_chr_write;
2668     chr->chr_close = tcp_chr_close;
2669     chr->get_msgfd = tcp_get_msgfd;
2670     chr->chr_add_client = tcp_chr_add_client;
2671     chr->chr_add_watch = tcp_chr_add_watch;
2672
2673     if (is_listen) {
2674         s->listen_fd = fd;
2675         s->listen_chan = io_channel_from_socket(s->listen_fd);
2676         s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2677         if (is_telnet) {
2678             s->do_telnetopt = 1;
2679         }
2680     } else {
2681         s->connected = 1;
2682         s->fd = fd;
2683         socket_set_nodelay(fd);
2684         s->chan = io_channel_from_socket(s->fd);
2685         tcp_chr_connect(chr);
2686     }
2687
2688     if (is_listen && is_waitconnect) {
2689         printf("QEMU waiting for connection on: %s\n",
2690                chr->filename);
2691         tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2692         socket_set_nonblock(s->listen_fd);
2693     }
2694     return chr;
2695 }
2696
2697 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2698 {
2699     CharDriverState *chr = NULL;
2700     Error *local_err = NULL;
2701     int fd = -1;
2702     int is_listen;
2703     int is_waitconnect;
2704     int do_nodelay;
2705     int is_unix;
2706     int is_telnet;
2707
2708     is_listen      = qemu_opt_get_bool(opts, "server", 0);
2709     is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2710     is_telnet      = qemu_opt_get_bool(opts, "telnet", 0);
2711     do_nodelay     = !qemu_opt_get_bool(opts, "delay", 1);
2712     is_unix        = qemu_opt_get(opts, "path") != NULL;
2713     if (!is_listen)
2714         is_waitconnect = 0;
2715
2716     if (is_unix) {
2717         if (is_listen) {
2718             fd = unix_listen_opts(opts, &local_err);
2719         } else {
2720             fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2721         }
2722     } else {
2723         if (is_listen) {
2724             fd = inet_listen_opts(opts, 0, &local_err);
2725         } else {
2726             fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2727         }
2728     }
2729     if (fd < 0) {
2730         goto fail;
2731     }
2732
2733     if (!is_waitconnect)
2734         socket_set_nonblock(fd);
2735
2736     chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2737                                   is_waitconnect, &local_err);
2738     if (error_is_set(&local_err)) {
2739         goto fail;
2740     }
2741     return chr;
2742
2743
2744  fail:
2745     if (local_err) {
2746         qerror_report_err(local_err);
2747         error_free(local_err);
2748     }
2749     if (fd >= 0) {
2750         closesocket(fd);
2751     }
2752     if (chr) {
2753         g_free(chr->opaque);
2754         g_free(chr);
2755     }
2756     return NULL;
2757 }
2758
2759 /***********************************************************/
2760 /* Memory chardev */
2761 typedef struct {
2762     size_t outbuf_size;
2763     size_t outbuf_capacity;
2764     uint8_t *outbuf;
2765 } MemoryDriver;
2766
2767 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2768 {
2769     MemoryDriver *d = chr->opaque;
2770
2771     /* TODO: the QString implementation has the same code, we should
2772      * introduce a generic way to do this in cutils.c */
2773     if (d->outbuf_capacity < d->outbuf_size + len) {
2774         /* grow outbuf */
2775         d->outbuf_capacity += len;
2776         d->outbuf_capacity *= 2;
2777         d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
2778     }
2779
2780     memcpy(d->outbuf + d->outbuf_size, buf, len);
2781     d->outbuf_size += len;
2782
2783     return len;
2784 }
2785
2786 void qemu_chr_init_mem(CharDriverState *chr)
2787 {
2788     MemoryDriver *d;
2789
2790     d = g_malloc(sizeof(*d));
2791     d->outbuf_size = 0;
2792     d->outbuf_capacity = 4096;
2793     d->outbuf = g_malloc0(d->outbuf_capacity);
2794
2795     memset(chr, 0, sizeof(*chr));
2796     chr->opaque = d;
2797     chr->chr_write = mem_chr_write;
2798 }
2799
2800 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2801 {
2802     MemoryDriver *d = chr->opaque;
2803     return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2804 }
2805
2806 /* NOTE: this driver can not be closed with qemu_chr_delete()! */
2807 void qemu_chr_close_mem(CharDriverState *chr)
2808 {
2809     MemoryDriver *d = chr->opaque;
2810
2811     g_free(d->outbuf);
2812     g_free(chr->opaque);
2813     chr->opaque = NULL;
2814     chr->chr_write = NULL;
2815 }
2816
2817 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2818 {
2819     const MemoryDriver *d = chr->opaque;
2820     return d->outbuf_size;
2821 }
2822
2823 /*********************************************************/
2824 /* Ring buffer chardev */
2825
2826 typedef struct {
2827     size_t size;
2828     size_t prod;
2829     size_t cons;
2830     uint8_t *cbuf;
2831 } RingBufCharDriver;
2832
2833 static size_t ringbuf_count(const CharDriverState *chr)
2834 {
2835     const RingBufCharDriver *d = chr->opaque;
2836
2837     return d->prod - d->cons;
2838 }
2839
2840 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2841 {
2842     RingBufCharDriver *d = chr->opaque;
2843     int i;
2844
2845     if (!buf || (len < 0)) {
2846         return -1;
2847     }
2848
2849     for (i = 0; i < len; i++ ) {
2850         d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2851         if (d->prod - d->cons > d->size) {
2852             d->cons = d->prod - d->size;
2853         }
2854     }
2855
2856     return 0;
2857 }
2858
2859 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2860 {
2861     RingBufCharDriver *d = chr->opaque;
2862     int i;
2863
2864     for (i = 0; i < len && d->cons != d->prod; i++) {
2865         buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2866     }
2867
2868     return i;
2869 }
2870
2871 static void ringbuf_chr_close(struct CharDriverState *chr)
2872 {
2873     RingBufCharDriver *d = chr->opaque;
2874
2875     g_free(d->cbuf);
2876     g_free(d);
2877     chr->opaque = NULL;
2878 }
2879
2880 static CharDriverState *qemu_chr_open_ringbuf(ChardevRingbuf *opts,
2881                                               Error **errp)
2882 {
2883     CharDriverState *chr;
2884     RingBufCharDriver *d;
2885
2886     chr = g_malloc0(sizeof(CharDriverState));
2887     d = g_malloc(sizeof(*d));
2888
2889     d->size = opts->has_size ? opts->size : 65536;
2890
2891     /* The size must be power of 2 */
2892     if (d->size & (d->size - 1)) {
2893         error_setg(errp, "size of ringbuf chardev must be power of two");
2894         goto fail;
2895     }
2896
2897     d->prod = 0;
2898     d->cons = 0;
2899     d->cbuf = g_malloc0(d->size);
2900
2901     chr->opaque = d;
2902     chr->chr_write = ringbuf_chr_write;
2903     chr->chr_close = ringbuf_chr_close;
2904
2905     return chr;
2906
2907 fail:
2908     g_free(d);
2909     g_free(chr);
2910     return NULL;
2911 }
2912
2913 static bool chr_is_ringbuf(const CharDriverState *chr)
2914 {
2915     return chr->chr_write == ringbuf_chr_write;
2916 }
2917
2918 void qmp_ringbuf_write(const char *device, const char *data,
2919                        bool has_format, enum DataFormat format,
2920                        Error **errp)
2921 {
2922     CharDriverState *chr;
2923     const uint8_t *write_data;
2924     int ret;
2925     size_t write_count;
2926
2927     chr = qemu_chr_find(device);
2928     if (!chr) {
2929         error_setg(errp, "Device '%s' not found", device);
2930         return;
2931     }
2932
2933     if (!chr_is_ringbuf(chr)) {
2934         error_setg(errp,"%s is not a ringbuf device", device);
2935         return;
2936     }
2937
2938     if (has_format && (format == DATA_FORMAT_BASE64)) {
2939         write_data = g_base64_decode(data, &write_count);
2940     } else {
2941         write_data = (uint8_t *)data;
2942         write_count = strlen(data);
2943     }
2944
2945     ret = ringbuf_chr_write(chr, write_data, write_count);
2946
2947     if (write_data != (uint8_t *)data) {
2948         g_free((void *)write_data);
2949     }
2950
2951     if (ret < 0) {
2952         error_setg(errp, "Failed to write to device %s", device);
2953         return;
2954     }
2955 }
2956
2957 char *qmp_ringbuf_read(const char *device, int64_t size,
2958                        bool has_format, enum DataFormat format,
2959                        Error **errp)
2960 {
2961     CharDriverState *chr;
2962     uint8_t *read_data;
2963     size_t count;
2964     char *data;
2965
2966     chr = qemu_chr_find(device);
2967     if (!chr) {
2968         error_setg(errp, "Device '%s' not found", device);
2969         return NULL;
2970     }
2971
2972     if (!chr_is_ringbuf(chr)) {
2973         error_setg(errp,"%s is not a ringbuf device", device);
2974         return NULL;
2975     }
2976
2977     if (size <= 0) {
2978         error_setg(errp, "size must be greater than zero");
2979         return NULL;
2980     }
2981
2982     count = ringbuf_count(chr);
2983     size = size > count ? count : size;
2984     read_data = g_malloc(size + 1);
2985
2986     ringbuf_chr_read(chr, read_data, size);
2987
2988     if (has_format && (format == DATA_FORMAT_BASE64)) {
2989         data = g_base64_encode(read_data, size);
2990         g_free(read_data);
2991     } else {
2992         /*
2993          * FIXME should read only complete, valid UTF-8 characters up
2994          * to @size bytes.  Invalid sequences should be replaced by a
2995          * suitable replacement character.  Except when (and only
2996          * when) ring buffer lost characters since last read, initial
2997          * continuation characters should be dropped.
2998          */
2999         read_data[size] = 0;
3000         data = (char *)read_data;
3001     }
3002
3003     return data;
3004 }
3005
3006 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3007 {
3008     char host[65], port[33], width[8], height[8];
3009     int pos;
3010     const char *p;
3011     QemuOpts *opts;
3012     Error *local_err = NULL;
3013
3014     opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3015     if (error_is_set(&local_err)) {
3016         qerror_report_err(local_err);
3017         error_free(local_err);
3018         return NULL;
3019     }
3020
3021     if (strstart(filename, "mon:", &p)) {
3022         filename = p;
3023         qemu_opt_set(opts, "mux", "on");
3024     }
3025
3026     if (strcmp(filename, "null")    == 0 ||
3027         strcmp(filename, "pty")     == 0 ||
3028         strcmp(filename, "msmouse") == 0 ||
3029         strcmp(filename, "braille") == 0 ||
3030         strcmp(filename, "stdio")   == 0) {
3031         qemu_opt_set(opts, "backend", filename);
3032         return opts;
3033     }
3034     if (strstart(filename, "vc", &p)) {
3035         qemu_opt_set(opts, "backend", "vc");
3036         if (*p == ':') {
3037             if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
3038                 /* pixels */
3039                 qemu_opt_set(opts, "width", width);
3040                 qemu_opt_set(opts, "height", height);
3041             } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
3042                 /* chars */
3043                 qemu_opt_set(opts, "cols", width);
3044                 qemu_opt_set(opts, "rows", height);
3045             } else {
3046                 goto fail;
3047             }
3048         }
3049         return opts;
3050     }
3051     if (strcmp(filename, "con:") == 0) {
3052         qemu_opt_set(opts, "backend", "console");
3053         return opts;
3054     }
3055     if (strstart(filename, "COM", NULL)) {
3056         qemu_opt_set(opts, "backend", "serial");
3057         qemu_opt_set(opts, "path", filename);
3058         return opts;
3059     }
3060     if (strstart(filename, "file:", &p)) {
3061         qemu_opt_set(opts, "backend", "file");
3062         qemu_opt_set(opts, "path", p);
3063         return opts;
3064     }
3065     if (strstart(filename, "pipe:", &p)) {
3066         qemu_opt_set(opts, "backend", "pipe");
3067         qemu_opt_set(opts, "path", p);
3068         return opts;
3069     }
3070     if (strstart(filename, "tcp:", &p) ||
3071         strstart(filename, "telnet:", &p)) {
3072         if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3073             host[0] = 0;
3074             if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3075                 goto fail;
3076         }
3077         qemu_opt_set(opts, "backend", "socket");
3078         qemu_opt_set(opts, "host", host);
3079         qemu_opt_set(opts, "port", port);
3080         if (p[pos] == ',') {
3081             if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3082                 goto fail;
3083         }
3084         if (strstart(filename, "telnet:", &p))
3085             qemu_opt_set(opts, "telnet", "on");
3086         return opts;
3087     }
3088     if (strstart(filename, "udp:", &p)) {
3089         qemu_opt_set(opts, "backend", "udp");
3090         if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3091             host[0] = 0;
3092             if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3093                 goto fail;
3094             }
3095         }
3096         qemu_opt_set(opts, "host", host);
3097         qemu_opt_set(opts, "port", port);
3098         if (p[pos] == '@') {
3099             p += pos + 1;
3100             if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3101                 host[0] = 0;
3102                 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3103                     goto fail;
3104                 }
3105             }
3106             qemu_opt_set(opts, "localaddr", host);
3107             qemu_opt_set(opts, "localport", port);
3108         }
3109         return opts;
3110     }
3111     if (strstart(filename, "unix:", &p)) {
3112         qemu_opt_set(opts, "backend", "socket");
3113         if (qemu_opts_do_parse(opts, p, "path") != 0)
3114             goto fail;
3115         return opts;
3116     }
3117     if (strstart(filename, "/dev/parport", NULL) ||
3118         strstart(filename, "/dev/ppi", NULL)) {
3119         qemu_opt_set(opts, "backend", "parport");
3120         qemu_opt_set(opts, "path", filename);
3121         return opts;
3122     }
3123     if (strstart(filename, "/dev/", NULL)) {
3124         qemu_opt_set(opts, "backend", "tty");
3125         qemu_opt_set(opts, "path", filename);
3126         return opts;
3127     }
3128
3129 fail:
3130     qemu_opts_del(opts);
3131     return NULL;
3132 }
3133
3134 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3135                                     Error **errp)
3136 {
3137     const char *path = qemu_opt_get(opts, "path");
3138
3139     if (path == NULL) {
3140         error_setg(errp, "chardev: file: no filename given");
3141         return;
3142     }
3143     backend->file = g_new0(ChardevFile, 1);
3144     backend->file->out = g_strdup(path);
3145 }
3146
3147 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3148                                  Error **errp)
3149 {
3150     backend->stdio = g_new0(ChardevStdio, 1);
3151     backend->stdio->has_signal = true;
3152     backend->stdio->signal =
3153         qemu_opt_get_bool(opts, "signal", display_type != DT_NOGRAPHIC);
3154 }
3155
3156 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3157                                   Error **errp)
3158 {
3159     const char *device = qemu_opt_get(opts, "path");
3160
3161     if (device == NULL) {
3162         error_setg(errp, "chardev: serial/tty: no device path given");
3163         return;
3164     }
3165     backend->serial = g_new0(ChardevHostdev, 1);
3166     backend->serial->device = g_strdup(device);
3167 }
3168
3169 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3170                                     Error **errp)
3171 {
3172     const char *device = qemu_opt_get(opts, "path");
3173
3174     if (device == NULL) {
3175         error_setg(errp, "chardev: parallel: no device path given");
3176         return;
3177     }
3178     backend->parallel = g_new0(ChardevHostdev, 1);
3179     backend->parallel->device = g_strdup(device);
3180 }
3181
3182 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3183                                 Error **errp)
3184 {
3185     const char *device = qemu_opt_get(opts, "path");
3186
3187     if (device == NULL) {
3188         error_setg(errp, "chardev: pipe: no device path given");
3189         return;
3190     }
3191     backend->pipe = g_new0(ChardevHostdev, 1);
3192     backend->pipe->device = g_strdup(device);
3193 }
3194
3195 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3196                                    Error **errp)
3197 {
3198     int val;
3199
3200     backend->memory = g_new0(ChardevRingbuf, 1);
3201
3202     val = qemu_opt_get_number(opts, "size", 0);
3203     if (val != 0) {
3204         backend->memory->has_size = true;
3205         backend->memory->size = val;
3206     }
3207 }
3208
3209 typedef struct CharDriver {
3210     const char *name;
3211     /* old, pre qapi */
3212     CharDriverState *(*open)(QemuOpts *opts);
3213     /* new, qapi-based */
3214     int kind;
3215     void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3216 } CharDriver;
3217
3218 static GSList *backends;
3219
3220 void register_char_driver(const char *name, CharDriverState *(*open)(QemuOpts *))
3221 {
3222     CharDriver *s;
3223
3224     s = g_malloc0(sizeof(*s));
3225     s->name = g_strdup(name);
3226     s->open = open;
3227
3228     backends = g_slist_append(backends, s);
3229 }
3230
3231 void register_char_driver_qapi(const char *name, int kind,
3232         void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3233 {
3234     CharDriver *s;
3235
3236     s = g_malloc0(sizeof(*s));
3237     s->name = g_strdup(name);
3238     s->kind = kind;
3239     s->parse = parse;
3240
3241     backends = g_slist_append(backends, s);
3242 }
3243
3244 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3245                                     void (*init)(struct CharDriverState *s),
3246                                     Error **errp)
3247 {
3248     CharDriver *cd;
3249     CharDriverState *chr;
3250     GSList *i;
3251
3252     if (qemu_opts_id(opts) == NULL) {
3253         error_setg(errp, "chardev: no id specified");
3254         goto err;
3255     }
3256
3257     if (qemu_opt_get(opts, "backend") == NULL) {
3258         error_setg(errp, "chardev: \"%s\" missing backend",
3259                    qemu_opts_id(opts));
3260         goto err;
3261     }
3262     for (i = backends; i; i = i->next) {
3263         cd = i->data;
3264
3265         if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3266             break;
3267         }
3268     }
3269     if (i == NULL) {
3270         error_setg(errp, "chardev: backend \"%s\" not found",
3271                    qemu_opt_get(opts, "backend"));
3272         return NULL;
3273     }
3274
3275     if (!cd->open) {
3276         /* using new, qapi init */
3277         ChardevBackend *backend = g_new0(ChardevBackend, 1);
3278         ChardevReturn *ret = NULL;
3279         const char *id = qemu_opts_id(opts);
3280         const char *bid = NULL;
3281
3282         if (qemu_opt_get_bool(opts, "mux", 0)) {
3283             bid = g_strdup_printf("%s-base", id);
3284         }
3285
3286         chr = NULL;
3287         backend->kind = cd->kind;
3288         if (cd->parse) {
3289             cd->parse(opts, backend, errp);
3290             if (error_is_set(errp)) {
3291                 goto qapi_out;
3292             }
3293         }
3294         ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3295         if (error_is_set(errp)) {
3296             goto qapi_out;
3297         }
3298
3299         if (bid) {
3300             qapi_free_ChardevBackend(backend);
3301             qapi_free_ChardevReturn(ret);
3302             backend = g_new0(ChardevBackend, 1);
3303             backend->mux = g_new0(ChardevMux, 1);
3304             backend->kind = CHARDEV_BACKEND_KIND_MUX;
3305             backend->mux->chardev = g_strdup(bid);
3306             ret = qmp_chardev_add(id, backend, errp);
3307             if (error_is_set(errp)) {
3308                 goto qapi_out;
3309             }
3310         }
3311
3312         chr = qemu_chr_find(id);
3313
3314     qapi_out:
3315         qapi_free_ChardevBackend(backend);
3316         qapi_free_ChardevReturn(ret);
3317         return chr;
3318     }
3319
3320     chr = cd->open(opts);
3321     if (!chr) {
3322         error_setg(errp, "chardev: opening backend \"%s\" failed",
3323                    qemu_opt_get(opts, "backend"));
3324         goto err;
3325     }
3326
3327     if (!chr->filename)
3328         chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3329     chr->init = init;
3330     QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3331
3332     if (qemu_opt_get_bool(opts, "mux", 0)) {
3333         CharDriverState *base = chr;
3334         int len = strlen(qemu_opts_id(opts)) + 6;
3335         base->label = g_malloc(len);
3336         snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3337         chr = qemu_chr_open_mux(base);
3338         chr->filename = base->filename;
3339         chr->avail_connections = MAX_MUX;
3340         QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3341     } else {
3342         chr->avail_connections = 1;
3343     }
3344     chr->label = g_strdup(qemu_opts_id(opts));
3345     chr->opts = opts;
3346     return chr;
3347
3348 err:
3349     qemu_opts_del(opts);
3350     return NULL;
3351 }
3352
3353 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3354 {
3355     const char *p;
3356     CharDriverState *chr;
3357     QemuOpts *opts;
3358     Error *err = NULL;
3359
3360     if (strstart(filename, "chardev:", &p)) {
3361         return qemu_chr_find(p);
3362     }
3363
3364     opts = qemu_chr_parse_compat(label, filename);
3365     if (!opts)
3366         return NULL;
3367
3368     chr = qemu_chr_new_from_opts(opts, init, &err);
3369     if (error_is_set(&err)) {
3370         fprintf(stderr, "%s\n", error_get_pretty(err));
3371         error_free(err);
3372     }
3373     if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3374         monitor_init(chr, MONITOR_USE_READLINE);
3375     }
3376     return chr;
3377 }
3378
3379 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3380 {
3381     if (chr->chr_set_echo) {
3382         chr->chr_set_echo(chr, echo);
3383     }
3384 }
3385
3386 void qemu_chr_fe_open(struct CharDriverState *chr)
3387 {
3388     if (chr->chr_guest_open) {
3389         chr->chr_guest_open(chr);
3390     }
3391 }
3392
3393 void qemu_chr_fe_close(struct CharDriverState *chr)
3394 {
3395     if (chr->chr_guest_close) {
3396         chr->chr_guest_close(chr);
3397     }
3398 }
3399
3400 guint qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3401                             GIOFunc func, void *user_data)
3402 {
3403     GSource *src;
3404     guint tag;
3405
3406     if (s->chr_add_watch == NULL) {
3407         return -ENOSYS;
3408     }
3409
3410     src = s->chr_add_watch(s, cond);
3411     g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3412     tag = g_source_attach(src, NULL);
3413     g_source_unref(src);
3414
3415     return tag;
3416 }
3417
3418 void qemu_chr_delete(CharDriverState *chr)
3419 {
3420     QTAILQ_REMOVE(&chardevs, chr, next);
3421     if (chr->chr_close) {
3422         chr->chr_close(chr);
3423     }
3424     g_free(chr->filename);
3425     g_free(chr->label);
3426     if (chr->opts) {
3427         qemu_opts_del(chr->opts);
3428     }
3429     g_free(chr);
3430 }
3431
3432 ChardevInfoList *qmp_query_chardev(Error **errp)
3433 {
3434     ChardevInfoList *chr_list = NULL;
3435     CharDriverState *chr;
3436
3437     QTAILQ_FOREACH(chr, &chardevs, next) {
3438         ChardevInfoList *info = g_malloc0(sizeof(*info));
3439         info->value = g_malloc0(sizeof(*info->value));
3440         info->value->label = g_strdup(chr->label);
3441         info->value->filename = g_strdup(chr->filename);
3442
3443         info->next = chr_list;
3444         chr_list = info;
3445     }
3446
3447     return chr_list;
3448 }
3449
3450 CharDriverState *qemu_chr_find(const char *name)
3451 {
3452     CharDriverState *chr;
3453
3454     QTAILQ_FOREACH(chr, &chardevs, next) {
3455         if (strcmp(chr->label, name) != 0)
3456             continue;
3457         return chr;
3458     }
3459     return NULL;
3460 }
3461
3462 /* Get a character (serial) device interface.  */
3463 CharDriverState *qemu_char_get_next_serial(void)
3464 {
3465     static int next_serial;
3466
3467     /* FIXME: This function needs to go away: use chardev properties!  */
3468     return serial_hds[next_serial++];
3469 }
3470
3471 QemuOptsList qemu_chardev_opts = {
3472     .name = "chardev",
3473     .implied_opt_name = "backend",
3474     .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3475     .desc = {
3476         {
3477             .name = "backend",
3478             .type = QEMU_OPT_STRING,
3479         },{
3480             .name = "path",
3481             .type = QEMU_OPT_STRING,
3482         },{
3483             .name = "host",
3484             .type = QEMU_OPT_STRING,
3485         },{
3486             .name = "port",
3487             .type = QEMU_OPT_STRING,
3488         },{
3489             .name = "localaddr",
3490             .type = QEMU_OPT_STRING,
3491         },{
3492             .name = "localport",
3493             .type = QEMU_OPT_STRING,
3494         },{
3495             .name = "to",
3496             .type = QEMU_OPT_NUMBER,
3497         },{
3498             .name = "ipv4",
3499             .type = QEMU_OPT_BOOL,
3500         },{
3501             .name = "ipv6",
3502             .type = QEMU_OPT_BOOL,
3503         },{
3504             .name = "wait",
3505             .type = QEMU_OPT_BOOL,
3506         },{
3507             .name = "server",
3508             .type = QEMU_OPT_BOOL,
3509         },{
3510             .name = "delay",
3511             .type = QEMU_OPT_BOOL,
3512         },{
3513             .name = "telnet",
3514             .type = QEMU_OPT_BOOL,
3515         },{
3516             .name = "width",
3517             .type = QEMU_OPT_NUMBER,
3518         },{
3519             .name = "height",
3520             .type = QEMU_OPT_NUMBER,
3521         },{
3522             .name = "cols",
3523             .type = QEMU_OPT_NUMBER,
3524         },{
3525             .name = "rows",
3526             .type = QEMU_OPT_NUMBER,
3527         },{
3528             .name = "mux",
3529             .type = QEMU_OPT_BOOL,
3530         },{
3531             .name = "signal",
3532             .type = QEMU_OPT_BOOL,
3533         },{
3534             .name = "name",
3535             .type = QEMU_OPT_STRING,
3536         },{
3537             .name = "debug",
3538             .type = QEMU_OPT_NUMBER,
3539         },{
3540             .name = "size",
3541             .type = QEMU_OPT_SIZE,
3542         },
3543         { /* end of list */ }
3544     },
3545 };
3546
3547 #ifdef _WIN32
3548
3549 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3550 {
3551     HANDLE out;
3552
3553     if (file->in) {
3554         error_setg(errp, "input file not supported");
3555         return NULL;
3556     }
3557
3558     out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3559                      OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3560     if (out == INVALID_HANDLE_VALUE) {
3561         error_setg(errp, "open %s failed", file->out);
3562         return NULL;
3563     }
3564     return qemu_chr_open_win_file(out);
3565 }
3566
3567 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3568                                                 Error **errp)
3569 {
3570     return qemu_chr_open_win_path(serial->device);
3571 }
3572
3573 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3574                                                   Error **errp)
3575 {
3576     error_setg(errp, "character device backend type 'parallel' not supported");
3577     return NULL;
3578 }
3579
3580 #else /* WIN32 */
3581
3582 static int qmp_chardev_open_file_source(char *src, int flags,
3583                                         Error **errp)
3584 {
3585     int fd = -1;
3586
3587     TFR(fd = qemu_open(src, flags, 0666));
3588     if (fd == -1) {
3589         error_setg(errp, "open %s: %s", src, strerror(errno));
3590     }
3591     return fd;
3592 }
3593
3594 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3595 {
3596     int flags, in = -1, out = -1;
3597
3598     flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3599     out = qmp_chardev_open_file_source(file->out, flags, errp);
3600     if (error_is_set(errp)) {
3601         return NULL;
3602     }
3603
3604     if (file->in) {
3605         flags = O_RDONLY;
3606         in = qmp_chardev_open_file_source(file->in, flags, errp);
3607         if (error_is_set(errp)) {
3608             qemu_close(out);
3609             return NULL;
3610         }
3611     }
3612
3613     return qemu_chr_open_fd(in, out);
3614 }
3615
3616 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3617                                                 Error **errp)
3618 {
3619 #ifdef HAVE_CHARDEV_TTY
3620     int fd;
3621
3622     fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3623     if (error_is_set(errp)) {
3624         return NULL;
3625     }
3626     socket_set_nonblock(fd);
3627     return qemu_chr_open_tty_fd(fd);
3628 #else
3629     error_setg(errp, "character device backend type 'serial' not supported");
3630     return NULL;
3631 #endif
3632 }
3633
3634 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3635                                                   Error **errp)
3636 {
3637 #ifdef HAVE_CHARDEV_PARPORT
3638     int fd;
3639
3640     fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3641     if (error_is_set(errp)) {
3642         return NULL;
3643     }
3644     return qemu_chr_open_pp_fd(fd);
3645 #else
3646     error_setg(errp, "character device backend type 'parallel' not supported");
3647     return NULL;
3648 #endif
3649 }
3650
3651 #endif /* WIN32 */
3652
3653 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3654                                                 Error **errp)
3655 {
3656     SocketAddress *addr = sock->addr;
3657     bool do_nodelay     = sock->has_nodelay ? sock->nodelay : false;
3658     bool is_listen      = sock->has_server  ? sock->server  : true;
3659     bool is_telnet      = sock->has_telnet  ? sock->telnet  : false;
3660     bool is_waitconnect = sock->has_wait    ? sock->wait    : false;
3661     int fd;
3662
3663     if (is_listen) {
3664         fd = socket_listen(addr, errp);
3665     } else {
3666         fd = socket_connect(addr, errp, NULL, NULL);
3667     }
3668     if (error_is_set(errp)) {
3669         return NULL;
3670     }
3671     return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3672                                    is_telnet, is_waitconnect, errp);
3673 }
3674
3675 static CharDriverState *qmp_chardev_open_dgram(ChardevDgram *dgram,
3676                                                Error **errp)
3677 {
3678     int fd;
3679
3680     fd = socket_dgram(dgram->remote, dgram->local, errp);
3681     if (error_is_set(errp)) {
3682         return NULL;
3683     }
3684     return qemu_chr_open_udp_fd(fd);
3685 }
3686
3687 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3688                                Error **errp)
3689 {
3690     ChardevReturn *ret = g_new0(ChardevReturn, 1);
3691     CharDriverState *base, *chr = NULL;
3692
3693     chr = qemu_chr_find(id);
3694     if (chr) {
3695         error_setg(errp, "Chardev '%s' already exists", id);
3696         g_free(ret);
3697         return NULL;
3698     }
3699
3700     switch (backend->kind) {
3701     case CHARDEV_BACKEND_KIND_FILE:
3702         chr = qmp_chardev_open_file(backend->file, errp);
3703         break;
3704     case CHARDEV_BACKEND_KIND_SERIAL:
3705         chr = qmp_chardev_open_serial(backend->serial, errp);
3706         break;
3707     case CHARDEV_BACKEND_KIND_PARALLEL:
3708         chr = qmp_chardev_open_parallel(backend->parallel, errp);
3709         break;
3710     case CHARDEV_BACKEND_KIND_PIPE:
3711         chr = qemu_chr_open_pipe(backend->pipe);
3712         break;
3713     case CHARDEV_BACKEND_KIND_SOCKET:
3714         chr = qmp_chardev_open_socket(backend->socket, errp);
3715         break;
3716     case CHARDEV_BACKEND_KIND_DGRAM:
3717         chr = qmp_chardev_open_dgram(backend->dgram, errp);
3718         break;
3719 #ifdef HAVE_CHARDEV_TTY
3720     case CHARDEV_BACKEND_KIND_PTY:
3721         chr = qemu_chr_open_pty(id, ret);
3722         break;
3723 #endif
3724     case CHARDEV_BACKEND_KIND_NULL:
3725         chr = qemu_chr_open_null();
3726         break;
3727     case CHARDEV_BACKEND_KIND_MUX:
3728         base = qemu_chr_find(backend->mux->chardev);
3729         if (base == NULL) {
3730             error_setg(errp, "mux: base chardev %s not found",
3731                        backend->mux->chardev);
3732             break;
3733         }
3734         chr = qemu_chr_open_mux(base);
3735         break;
3736     case CHARDEV_BACKEND_KIND_MSMOUSE:
3737         chr = qemu_chr_open_msmouse();
3738         break;
3739 #ifdef CONFIG_BRLAPI
3740     case CHARDEV_BACKEND_KIND_BRAILLE:
3741         chr = chr_baum_init();
3742         break;
3743 #endif
3744     case CHARDEV_BACKEND_KIND_STDIO:
3745         chr = qemu_chr_open_stdio(backend->stdio);
3746         break;
3747 #ifdef _WIN32
3748     case CHARDEV_BACKEND_KIND_CONSOLE:
3749         chr = qemu_chr_open_win_con();
3750         break;
3751 #endif
3752 #ifdef CONFIG_SPICE
3753     case CHARDEV_BACKEND_KIND_SPICEVMC:
3754         chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
3755         break;
3756     case CHARDEV_BACKEND_KIND_SPICEPORT:
3757         chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
3758         break;
3759 #endif
3760     case CHARDEV_BACKEND_KIND_VC:
3761         chr = vc_init(backend->vc);
3762         break;
3763     case CHARDEV_BACKEND_KIND_MEMORY:
3764         chr = qemu_chr_open_ringbuf(backend->memory, errp);
3765         break;
3766     default:
3767         error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3768         break;
3769     }
3770
3771     if (chr == NULL && !error_is_set(errp)) {
3772         error_setg(errp, "Failed to create chardev");
3773     }
3774     if (chr) {
3775         chr->label = g_strdup(id);
3776         chr->avail_connections =
3777             (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
3778         QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3779         return ret;
3780     } else {
3781         g_free(ret);
3782         return NULL;
3783     }
3784 }
3785
3786 void qmp_chardev_remove(const char *id, Error **errp)
3787 {
3788     CharDriverState *chr;
3789
3790     chr = qemu_chr_find(id);
3791     if (NULL == chr) {
3792         error_setg(errp, "Chardev '%s' not found", id);
3793         return;
3794     }
3795     if (chr->chr_can_read || chr->chr_read ||
3796         chr->chr_event || chr->handler_opaque) {
3797         error_setg(errp, "Chardev '%s' is busy", id);
3798         return;
3799     }
3800     qemu_chr_delete(chr);
3801 }
3802
3803 static void register_types(void)
3804 {
3805     register_char_driver_qapi("null", CHARDEV_BACKEND_KIND_NULL, NULL);
3806     register_char_driver("socket", qemu_chr_open_socket);
3807     register_char_driver("udp", qemu_chr_open_udp);
3808     register_char_driver_qapi("memory", CHARDEV_BACKEND_KIND_MEMORY,
3809                               qemu_chr_parse_ringbuf);
3810     register_char_driver_qapi("file", CHARDEV_BACKEND_KIND_FILE,
3811                               qemu_chr_parse_file_out);
3812     register_char_driver_qapi("stdio", CHARDEV_BACKEND_KIND_STDIO,
3813                               qemu_chr_parse_stdio);
3814     register_char_driver_qapi("serial", CHARDEV_BACKEND_KIND_SERIAL,
3815                               qemu_chr_parse_serial);
3816     register_char_driver_qapi("tty", CHARDEV_BACKEND_KIND_SERIAL,
3817                               qemu_chr_parse_serial);
3818     register_char_driver_qapi("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
3819                               qemu_chr_parse_parallel);
3820     register_char_driver_qapi("parport", CHARDEV_BACKEND_KIND_PARALLEL,
3821                               qemu_chr_parse_parallel);
3822     register_char_driver_qapi("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
3823     register_char_driver_qapi("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
3824     register_char_driver_qapi("pipe", CHARDEV_BACKEND_KIND_PIPE,
3825                               qemu_chr_parse_pipe);
3826 }
3827
3828 type_init(register_types);