chardev: add vc support to qapi
[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(QemuOpts *opts)
2265 {
2266     CharDriverState *chr = NULL;
2267     NetCharDriver *s = NULL;
2268     Error *local_err = NULL;
2269     int fd = -1;
2270
2271     chr = g_malloc0(sizeof(CharDriverState));
2272     s = g_malloc0(sizeof(NetCharDriver));
2273
2274     fd = inet_dgram_opts(opts, &local_err);
2275     if (fd < 0) {
2276         goto return_err;
2277     }
2278
2279     s->fd = fd;
2280     s->chan = io_channel_from_socket(s->fd);
2281     s->bufcnt = 0;
2282     s->bufptr = 0;
2283     chr->opaque = s;
2284     chr->chr_write = udp_chr_write;
2285     chr->chr_update_read_handler = udp_chr_update_read_handler;
2286     chr->chr_close = udp_chr_close;
2287     return chr;
2288
2289 return_err:
2290     if (local_err) {
2291         qerror_report_err(local_err);
2292         error_free(local_err);
2293     }
2294     g_free(chr);
2295     g_free(s);
2296     if (fd >= 0) {
2297         closesocket(fd);
2298     }
2299     return NULL;
2300 }
2301
2302 /***********************************************************/
2303 /* TCP Net console */
2304
2305 typedef struct {
2306
2307     GIOChannel *chan, *listen_chan;
2308     guint tag, listen_tag;
2309     int fd, listen_fd;
2310     int connected;
2311     int max_size;
2312     int do_telnetopt;
2313     int do_nodelay;
2314     int is_unix;
2315     int msgfd;
2316 } TCPCharDriver;
2317
2318 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2319
2320 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2321 {
2322     TCPCharDriver *s = chr->opaque;
2323     if (s->connected) {
2324         return io_channel_send_all(s->chan, buf, len);
2325     } else {
2326         /* XXX: indicate an error ? */
2327         return len;
2328     }
2329 }
2330
2331 static int tcp_chr_read_poll(void *opaque)
2332 {
2333     CharDriverState *chr = opaque;
2334     TCPCharDriver *s = chr->opaque;
2335     if (!s->connected)
2336         return 0;
2337     s->max_size = qemu_chr_be_can_write(chr);
2338     return s->max_size;
2339 }
2340
2341 #define IAC 255
2342 #define IAC_BREAK 243
2343 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2344                                       TCPCharDriver *s,
2345                                       uint8_t *buf, int *size)
2346 {
2347     /* Handle any telnet client's basic IAC options to satisfy char by
2348      * char mode with no echo.  All IAC options will be removed from
2349      * the buf and the do_telnetopt variable will be used to track the
2350      * state of the width of the IAC information.
2351      *
2352      * IAC commands come in sets of 3 bytes with the exception of the
2353      * "IAC BREAK" command and the double IAC.
2354      */
2355
2356     int i;
2357     int j = 0;
2358
2359     for (i = 0; i < *size; i++) {
2360         if (s->do_telnetopt > 1) {
2361             if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2362                 /* Double IAC means send an IAC */
2363                 if (j != i)
2364                     buf[j] = buf[i];
2365                 j++;
2366                 s->do_telnetopt = 1;
2367             } else {
2368                 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2369                     /* Handle IAC break commands by sending a serial break */
2370                     qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2371                     s->do_telnetopt++;
2372                 }
2373                 s->do_telnetopt++;
2374             }
2375             if (s->do_telnetopt >= 4) {
2376                 s->do_telnetopt = 1;
2377             }
2378         } else {
2379             if ((unsigned char)buf[i] == IAC) {
2380                 s->do_telnetopt = 2;
2381             } else {
2382                 if (j != i)
2383                     buf[j] = buf[i];
2384                 j++;
2385             }
2386         }
2387     }
2388     *size = j;
2389 }
2390
2391 static int tcp_get_msgfd(CharDriverState *chr)
2392 {
2393     TCPCharDriver *s = chr->opaque;
2394     int fd = s->msgfd;
2395     s->msgfd = -1;
2396     return fd;
2397 }
2398
2399 #ifndef _WIN32
2400 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2401 {
2402     TCPCharDriver *s = chr->opaque;
2403     struct cmsghdr *cmsg;
2404
2405     for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2406         int fd;
2407
2408         if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2409             cmsg->cmsg_level != SOL_SOCKET ||
2410             cmsg->cmsg_type != SCM_RIGHTS)
2411             continue;
2412
2413         fd = *((int *)CMSG_DATA(cmsg));
2414         if (fd < 0)
2415             continue;
2416
2417 #ifndef MSG_CMSG_CLOEXEC
2418         qemu_set_cloexec(fd);
2419 #endif
2420         if (s->msgfd != -1)
2421             close(s->msgfd);
2422         s->msgfd = fd;
2423     }
2424 }
2425
2426 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2427 {
2428     TCPCharDriver *s = chr->opaque;
2429     struct msghdr msg = { NULL, };
2430     struct iovec iov[1];
2431     union {
2432         struct cmsghdr cmsg;
2433         char control[CMSG_SPACE(sizeof(int))];
2434     } msg_control;
2435     int flags = 0;
2436     ssize_t ret;
2437
2438     iov[0].iov_base = buf;
2439     iov[0].iov_len = len;
2440
2441     msg.msg_iov = iov;
2442     msg.msg_iovlen = 1;
2443     msg.msg_control = &msg_control;
2444     msg.msg_controllen = sizeof(msg_control);
2445
2446 #ifdef MSG_CMSG_CLOEXEC
2447     flags |= MSG_CMSG_CLOEXEC;
2448 #endif
2449     ret = recvmsg(s->fd, &msg, flags);
2450     if (ret > 0 && s->is_unix) {
2451         unix_process_msgfd(chr, &msg);
2452     }
2453
2454     return ret;
2455 }
2456 #else
2457 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2458 {
2459     TCPCharDriver *s = chr->opaque;
2460     return qemu_recv(s->fd, buf, len, 0);
2461 }
2462 #endif
2463
2464 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2465 {
2466     TCPCharDriver *s = chr->opaque;
2467     return g_io_create_watch(s->chan, cond);
2468 }
2469
2470 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2471 {
2472     CharDriverState *chr = opaque;
2473     TCPCharDriver *s = chr->opaque;
2474     uint8_t buf[READ_BUF_LEN];
2475     int len, size;
2476
2477     if (!s->connected || s->max_size <= 0) {
2478         return FALSE;
2479     }
2480     len = sizeof(buf);
2481     if (len > s->max_size)
2482         len = s->max_size;
2483     size = tcp_chr_recv(chr, (void *)buf, len);
2484     if (size == 0) {
2485         /* connection closed */
2486         s->connected = 0;
2487         if (s->listen_chan) {
2488             s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2489         }
2490         g_source_remove(s->tag);
2491         s->tag = 0;
2492         g_io_channel_unref(s->chan);
2493         s->chan = NULL;
2494         closesocket(s->fd);
2495         s->fd = -1;
2496         qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2497     } else if (size > 0) {
2498         if (s->do_telnetopt)
2499             tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2500         if (size > 0)
2501             qemu_chr_be_write(chr, buf, size);
2502     }
2503
2504     return TRUE;
2505 }
2506
2507 #ifndef _WIN32
2508 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2509 {
2510     return qemu_chr_open_fd(eventfd, eventfd);
2511 }
2512 #endif
2513
2514 static void tcp_chr_connect(void *opaque)
2515 {
2516     CharDriverState *chr = opaque;
2517     TCPCharDriver *s = chr->opaque;
2518
2519     s->connected = 1;
2520     if (s->chan) {
2521         s->tag = io_add_watch_poll(s->chan, tcp_chr_read_poll, tcp_chr_read, chr);
2522     }
2523     qemu_chr_generic_open(chr);
2524 }
2525
2526 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2527 static void tcp_chr_telnet_init(int fd)
2528 {
2529     char buf[3];
2530     /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2531     IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2532     send(fd, (char *)buf, 3, 0);
2533     IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2534     send(fd, (char *)buf, 3, 0);
2535     IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2536     send(fd, (char *)buf, 3, 0);
2537     IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2538     send(fd, (char *)buf, 3, 0);
2539 }
2540
2541 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2542 {
2543     TCPCharDriver *s = chr->opaque;
2544     if (s->fd != -1)
2545         return -1;
2546
2547     socket_set_nonblock(fd);
2548     if (s->do_nodelay)
2549         socket_set_nodelay(fd);
2550     s->fd = fd;
2551     s->chan = io_channel_from_socket(fd);
2552     g_source_remove(s->listen_tag);
2553     s->listen_tag = 0;
2554     tcp_chr_connect(chr);
2555
2556     return 0;
2557 }
2558
2559 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2560 {
2561     CharDriverState *chr = opaque;
2562     TCPCharDriver *s = chr->opaque;
2563     struct sockaddr_in saddr;
2564 #ifndef _WIN32
2565     struct sockaddr_un uaddr;
2566 #endif
2567     struct sockaddr *addr;
2568     socklen_t len;
2569     int fd;
2570
2571     for(;;) {
2572 #ifndef _WIN32
2573         if (s->is_unix) {
2574             len = sizeof(uaddr);
2575             addr = (struct sockaddr *)&uaddr;
2576         } else
2577 #endif
2578         {
2579             len = sizeof(saddr);
2580             addr = (struct sockaddr *)&saddr;
2581         }
2582         fd = qemu_accept(s->listen_fd, addr, &len);
2583         if (fd < 0 && errno != EINTR) {
2584             return FALSE;
2585         } else if (fd >= 0) {
2586             if (s->do_telnetopt)
2587                 tcp_chr_telnet_init(fd);
2588             break;
2589         }
2590     }
2591     if (tcp_chr_add_client(chr, fd) < 0)
2592         close(fd);
2593
2594     return TRUE;
2595 }
2596
2597 static void tcp_chr_close(CharDriverState *chr)
2598 {
2599     TCPCharDriver *s = chr->opaque;
2600     if (s->fd >= 0) {
2601         if (s->tag) {
2602             g_source_remove(s->tag);
2603         }
2604         if (s->chan) {
2605             g_io_channel_unref(s->chan);
2606         }
2607         closesocket(s->fd);
2608     }
2609     if (s->listen_fd >= 0) {
2610         if (s->listen_tag) {
2611             g_source_remove(s->listen_tag);
2612         }
2613         if (s->listen_chan) {
2614             g_io_channel_unref(s->listen_chan);
2615         }
2616         closesocket(s->listen_fd);
2617     }
2618     g_free(s);
2619     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2620 }
2621
2622 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2623                                                 bool is_listen, bool is_telnet,
2624                                                 bool is_waitconnect,
2625                                                 Error **errp)
2626 {
2627     CharDriverState *chr = NULL;
2628     TCPCharDriver *s = NULL;
2629     char host[NI_MAXHOST], serv[NI_MAXSERV];
2630     const char *left = "", *right = "";
2631     struct sockaddr_storage ss;
2632     socklen_t ss_len = sizeof(ss);
2633
2634     memset(&ss, 0, ss_len);
2635     if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2636         error_setg(errp, "getsockname: %s", strerror(errno));
2637         return NULL;
2638     }
2639
2640     chr = g_malloc0(sizeof(CharDriverState));
2641     s = g_malloc0(sizeof(TCPCharDriver));
2642
2643     s->connected = 0;
2644     s->fd = -1;
2645     s->listen_fd = -1;
2646     s->msgfd = -1;
2647
2648     chr->filename = g_malloc(256);
2649     switch (ss.ss_family) {
2650 #ifndef _WIN32
2651     case AF_UNIX:
2652         s->is_unix = 1;
2653         snprintf(chr->filename, 256, "unix:%s%s",
2654                  ((struct sockaddr_un *)(&ss))->sun_path,
2655                  is_listen ? ",server" : "");
2656         break;
2657 #endif
2658     case AF_INET6:
2659         left  = "[";
2660         right = "]";
2661         /* fall through */
2662     case AF_INET:
2663         s->do_nodelay = do_nodelay;
2664         getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2665                     serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2666         snprintf(chr->filename, 256, "%s:%s:%s%s%s%s",
2667                  is_telnet ? "telnet" : "tcp",
2668                  left, host, right, serv,
2669                  is_listen ? ",server" : "");
2670         break;
2671     }
2672
2673     chr->opaque = s;
2674     chr->chr_write = tcp_chr_write;
2675     chr->chr_close = tcp_chr_close;
2676     chr->get_msgfd = tcp_get_msgfd;
2677     chr->chr_add_client = tcp_chr_add_client;
2678     chr->chr_add_watch = tcp_chr_add_watch;
2679
2680     if (is_listen) {
2681         s->listen_fd = fd;
2682         s->listen_chan = io_channel_from_socket(s->listen_fd);
2683         s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2684         if (is_telnet) {
2685             s->do_telnetopt = 1;
2686         }
2687     } else {
2688         s->connected = 1;
2689         s->fd = fd;
2690         socket_set_nodelay(fd);
2691         s->chan = io_channel_from_socket(s->fd);
2692         tcp_chr_connect(chr);
2693     }
2694
2695     if (is_listen && is_waitconnect) {
2696         printf("QEMU waiting for connection on: %s\n",
2697                chr->filename);
2698         tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2699         socket_set_nonblock(s->listen_fd);
2700     }
2701     return chr;
2702 }
2703
2704 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2705 {
2706     CharDriverState *chr = NULL;
2707     Error *local_err = NULL;
2708     int fd = -1;
2709     int is_listen;
2710     int is_waitconnect;
2711     int do_nodelay;
2712     int is_unix;
2713     int is_telnet;
2714
2715     is_listen      = qemu_opt_get_bool(opts, "server", 0);
2716     is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2717     is_telnet      = qemu_opt_get_bool(opts, "telnet", 0);
2718     do_nodelay     = !qemu_opt_get_bool(opts, "delay", 1);
2719     is_unix        = qemu_opt_get(opts, "path") != NULL;
2720     if (!is_listen)
2721         is_waitconnect = 0;
2722
2723     if (is_unix) {
2724         if (is_listen) {
2725             fd = unix_listen_opts(opts, &local_err);
2726         } else {
2727             fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2728         }
2729     } else {
2730         if (is_listen) {
2731             fd = inet_listen_opts(opts, 0, &local_err);
2732         } else {
2733             fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2734         }
2735     }
2736     if (fd < 0) {
2737         goto fail;
2738     }
2739
2740     if (!is_waitconnect)
2741         socket_set_nonblock(fd);
2742
2743     chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2744                                   is_waitconnect, &local_err);
2745     if (error_is_set(&local_err)) {
2746         goto fail;
2747     }
2748     return chr;
2749
2750
2751  fail:
2752     if (local_err) {
2753         qerror_report_err(local_err);
2754         error_free(local_err);
2755     }
2756     if (fd >= 0) {
2757         closesocket(fd);
2758     }
2759     if (chr) {
2760         g_free(chr->opaque);
2761         g_free(chr);
2762     }
2763     return NULL;
2764 }
2765
2766 /***********************************************************/
2767 /* Memory chardev */
2768 typedef struct {
2769     size_t outbuf_size;
2770     size_t outbuf_capacity;
2771     uint8_t *outbuf;
2772 } MemoryDriver;
2773
2774 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2775 {
2776     MemoryDriver *d = chr->opaque;
2777
2778     /* TODO: the QString implementation has the same code, we should
2779      * introduce a generic way to do this in cutils.c */
2780     if (d->outbuf_capacity < d->outbuf_size + len) {
2781         /* grow outbuf */
2782         d->outbuf_capacity += len;
2783         d->outbuf_capacity *= 2;
2784         d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
2785     }
2786
2787     memcpy(d->outbuf + d->outbuf_size, buf, len);
2788     d->outbuf_size += len;
2789
2790     return len;
2791 }
2792
2793 void qemu_chr_init_mem(CharDriverState *chr)
2794 {
2795     MemoryDriver *d;
2796
2797     d = g_malloc(sizeof(*d));
2798     d->outbuf_size = 0;
2799     d->outbuf_capacity = 4096;
2800     d->outbuf = g_malloc0(d->outbuf_capacity);
2801
2802     memset(chr, 0, sizeof(*chr));
2803     chr->opaque = d;
2804     chr->chr_write = mem_chr_write;
2805 }
2806
2807 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2808 {
2809     MemoryDriver *d = chr->opaque;
2810     return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2811 }
2812
2813 /* NOTE: this driver can not be closed with qemu_chr_delete()! */
2814 void qemu_chr_close_mem(CharDriverState *chr)
2815 {
2816     MemoryDriver *d = chr->opaque;
2817
2818     g_free(d->outbuf);
2819     g_free(chr->opaque);
2820     chr->opaque = NULL;
2821     chr->chr_write = NULL;
2822 }
2823
2824 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2825 {
2826     const MemoryDriver *d = chr->opaque;
2827     return d->outbuf_size;
2828 }
2829
2830 /*********************************************************/
2831 /* Ring buffer chardev */
2832
2833 typedef struct {
2834     size_t size;
2835     size_t prod;
2836     size_t cons;
2837     uint8_t *cbuf;
2838 } RingBufCharDriver;
2839
2840 static size_t ringbuf_count(const CharDriverState *chr)
2841 {
2842     const RingBufCharDriver *d = chr->opaque;
2843
2844     return d->prod - d->cons;
2845 }
2846
2847 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2848 {
2849     RingBufCharDriver *d = chr->opaque;
2850     int i;
2851
2852     if (!buf || (len < 0)) {
2853         return -1;
2854     }
2855
2856     for (i = 0; i < len; i++ ) {
2857         d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2858         if (d->prod - d->cons > d->size) {
2859             d->cons = d->prod - d->size;
2860         }
2861     }
2862
2863     return 0;
2864 }
2865
2866 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2867 {
2868     RingBufCharDriver *d = chr->opaque;
2869     int i;
2870
2871     for (i = 0; i < len && d->cons != d->prod; i++) {
2872         buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2873     }
2874
2875     return i;
2876 }
2877
2878 static void ringbuf_chr_close(struct CharDriverState *chr)
2879 {
2880     RingBufCharDriver *d = chr->opaque;
2881
2882     g_free(d->cbuf);
2883     g_free(d);
2884     chr->opaque = NULL;
2885 }
2886
2887 static CharDriverState *qemu_chr_open_ringbuf(QemuOpts *opts)
2888 {
2889     CharDriverState *chr;
2890     RingBufCharDriver *d;
2891
2892     chr = g_malloc0(sizeof(CharDriverState));
2893     d = g_malloc(sizeof(*d));
2894
2895     d->size = qemu_opt_get_size(opts, "size", 0);
2896     if (d->size == 0) {
2897         d->size = 65536;
2898     }
2899
2900     /* The size must be power of 2 */
2901     if (d->size & (d->size - 1)) {
2902         error_report("size of ringbuf device must be power of two");
2903         goto fail;
2904     }
2905
2906     d->prod = 0;
2907     d->cons = 0;
2908     d->cbuf = g_malloc0(d->size);
2909
2910     chr->opaque = d;
2911     chr->chr_write = ringbuf_chr_write;
2912     chr->chr_close = ringbuf_chr_close;
2913
2914     return chr;
2915
2916 fail:
2917     g_free(d);
2918     g_free(chr);
2919     return NULL;
2920 }
2921
2922 static bool chr_is_ringbuf(const CharDriverState *chr)
2923 {
2924     return chr->chr_write == ringbuf_chr_write;
2925 }
2926
2927 void qmp_ringbuf_write(const char *device, const char *data,
2928                        bool has_format, enum DataFormat format,
2929                        Error **errp)
2930 {
2931     CharDriverState *chr;
2932     const uint8_t *write_data;
2933     int ret;
2934     size_t write_count;
2935
2936     chr = qemu_chr_find(device);
2937     if (!chr) {
2938         error_setg(errp, "Device '%s' not found", device);
2939         return;
2940     }
2941
2942     if (!chr_is_ringbuf(chr)) {
2943         error_setg(errp,"%s is not a ringbuf device", device);
2944         return;
2945     }
2946
2947     if (has_format && (format == DATA_FORMAT_BASE64)) {
2948         write_data = g_base64_decode(data, &write_count);
2949     } else {
2950         write_data = (uint8_t *)data;
2951         write_count = strlen(data);
2952     }
2953
2954     ret = ringbuf_chr_write(chr, write_data, write_count);
2955
2956     if (write_data != (uint8_t *)data) {
2957         g_free((void *)write_data);
2958     }
2959
2960     if (ret < 0) {
2961         error_setg(errp, "Failed to write to device %s", device);
2962         return;
2963     }
2964 }
2965
2966 char *qmp_ringbuf_read(const char *device, int64_t size,
2967                        bool has_format, enum DataFormat format,
2968                        Error **errp)
2969 {
2970     CharDriverState *chr;
2971     uint8_t *read_data;
2972     size_t count;
2973     char *data;
2974
2975     chr = qemu_chr_find(device);
2976     if (!chr) {
2977         error_setg(errp, "Device '%s' not found", device);
2978         return NULL;
2979     }
2980
2981     if (!chr_is_ringbuf(chr)) {
2982         error_setg(errp,"%s is not a ringbuf device", device);
2983         return NULL;
2984     }
2985
2986     if (size <= 0) {
2987         error_setg(errp, "size must be greater than zero");
2988         return NULL;
2989     }
2990
2991     count = ringbuf_count(chr);
2992     size = size > count ? count : size;
2993     read_data = g_malloc(size + 1);
2994
2995     ringbuf_chr_read(chr, read_data, size);
2996
2997     if (has_format && (format == DATA_FORMAT_BASE64)) {
2998         data = g_base64_encode(read_data, size);
2999         g_free(read_data);
3000     } else {
3001         /*
3002          * FIXME should read only complete, valid UTF-8 characters up
3003          * to @size bytes.  Invalid sequences should be replaced by a
3004          * suitable replacement character.  Except when (and only
3005          * when) ring buffer lost characters since last read, initial
3006          * continuation characters should be dropped.
3007          */
3008         read_data[size] = 0;
3009         data = (char *)read_data;
3010     }
3011
3012     return data;
3013 }
3014
3015 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3016 {
3017     char host[65], port[33], width[8], height[8];
3018     int pos;
3019     const char *p;
3020     QemuOpts *opts;
3021     Error *local_err = NULL;
3022
3023     opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3024     if (error_is_set(&local_err)) {
3025         qerror_report_err(local_err);
3026         error_free(local_err);
3027         return NULL;
3028     }
3029
3030     if (strstart(filename, "mon:", &p)) {
3031         filename = p;
3032         qemu_opt_set(opts, "mux", "on");
3033     }
3034
3035     if (strcmp(filename, "null")    == 0 ||
3036         strcmp(filename, "pty")     == 0 ||
3037         strcmp(filename, "msmouse") == 0 ||
3038         strcmp(filename, "braille") == 0 ||
3039         strcmp(filename, "stdio")   == 0) {
3040         qemu_opt_set(opts, "backend", filename);
3041         return opts;
3042     }
3043     if (strstart(filename, "vc", &p)) {
3044         qemu_opt_set(opts, "backend", "vc");
3045         if (*p == ':') {
3046             if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
3047                 /* pixels */
3048                 qemu_opt_set(opts, "width", width);
3049                 qemu_opt_set(opts, "height", height);
3050             } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
3051                 /* chars */
3052                 qemu_opt_set(opts, "cols", width);
3053                 qemu_opt_set(opts, "rows", height);
3054             } else {
3055                 goto fail;
3056             }
3057         }
3058         return opts;
3059     }
3060     if (strcmp(filename, "con:") == 0) {
3061         qemu_opt_set(opts, "backend", "console");
3062         return opts;
3063     }
3064     if (strstart(filename, "COM", NULL)) {
3065         qemu_opt_set(opts, "backend", "serial");
3066         qemu_opt_set(opts, "path", filename);
3067         return opts;
3068     }
3069     if (strstart(filename, "file:", &p)) {
3070         qemu_opt_set(opts, "backend", "file");
3071         qemu_opt_set(opts, "path", p);
3072         return opts;
3073     }
3074     if (strstart(filename, "pipe:", &p)) {
3075         qemu_opt_set(opts, "backend", "pipe");
3076         qemu_opt_set(opts, "path", p);
3077         return opts;
3078     }
3079     if (strstart(filename, "tcp:", &p) ||
3080         strstart(filename, "telnet:", &p)) {
3081         if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3082             host[0] = 0;
3083             if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3084                 goto fail;
3085         }
3086         qemu_opt_set(opts, "backend", "socket");
3087         qemu_opt_set(opts, "host", host);
3088         qemu_opt_set(opts, "port", port);
3089         if (p[pos] == ',') {
3090             if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3091                 goto fail;
3092         }
3093         if (strstart(filename, "telnet:", &p))
3094             qemu_opt_set(opts, "telnet", "on");
3095         return opts;
3096     }
3097     if (strstart(filename, "udp:", &p)) {
3098         qemu_opt_set(opts, "backend", "udp");
3099         if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3100             host[0] = 0;
3101             if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3102                 goto fail;
3103             }
3104         }
3105         qemu_opt_set(opts, "host", host);
3106         qemu_opt_set(opts, "port", port);
3107         if (p[pos] == '@') {
3108             p += pos + 1;
3109             if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3110                 host[0] = 0;
3111                 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3112                     goto fail;
3113                 }
3114             }
3115             qemu_opt_set(opts, "localaddr", host);
3116             qemu_opt_set(opts, "localport", port);
3117         }
3118         return opts;
3119     }
3120     if (strstart(filename, "unix:", &p)) {
3121         qemu_opt_set(opts, "backend", "socket");
3122         if (qemu_opts_do_parse(opts, p, "path") != 0)
3123             goto fail;
3124         return opts;
3125     }
3126     if (strstart(filename, "/dev/parport", NULL) ||
3127         strstart(filename, "/dev/ppi", NULL)) {
3128         qemu_opt_set(opts, "backend", "parport");
3129         qemu_opt_set(opts, "path", filename);
3130         return opts;
3131     }
3132     if (strstart(filename, "/dev/", NULL)) {
3133         qemu_opt_set(opts, "backend", "tty");
3134         qemu_opt_set(opts, "path", filename);
3135         return opts;
3136     }
3137
3138 fail:
3139     qemu_opts_del(opts);
3140     return NULL;
3141 }
3142
3143 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3144                                     Error **errp)
3145 {
3146     const char *path = qemu_opt_get(opts, "path");
3147
3148     if (path == NULL) {
3149         error_setg(errp, "chardev: file: no filename given");
3150         return;
3151     }
3152     backend->file = g_new0(ChardevFile, 1);
3153     backend->file->out = g_strdup(path);
3154 }
3155
3156 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3157                                  Error **errp)
3158 {
3159     backend->stdio = g_new0(ChardevStdio, 1);
3160     backend->stdio->has_signal = true;
3161     backend->stdio->signal =
3162         qemu_opt_get_bool(opts, "signal", display_type != DT_NOGRAPHIC);
3163 }
3164
3165 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3166                                   Error **errp)
3167 {
3168     const char *device = qemu_opt_get(opts, "path");
3169
3170     if (device == NULL) {
3171         error_setg(errp, "chardev: serial/tty: no device path given");
3172         return;
3173     }
3174     backend->serial = g_new0(ChardevHostdev, 1);
3175     backend->serial->device = g_strdup(device);
3176 }
3177
3178 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3179                                     Error **errp)
3180 {
3181     const char *device = qemu_opt_get(opts, "path");
3182
3183     if (device == NULL) {
3184         error_setg(errp, "chardev: parallel: no device path given");
3185         return;
3186     }
3187     backend->parallel = g_new0(ChardevHostdev, 1);
3188     backend->parallel->device = g_strdup(device);
3189 }
3190
3191 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3192                                 Error **errp)
3193 {
3194     const char *device = qemu_opt_get(opts, "path");
3195
3196     if (device == NULL) {
3197         error_setg(errp, "chardev: pipe: no device path given");
3198         return;
3199     }
3200     backend->pipe = g_new0(ChardevHostdev, 1);
3201     backend->pipe->device = g_strdup(device);
3202 }
3203
3204 typedef struct CharDriver {
3205     const char *name;
3206     /* old, pre qapi */
3207     CharDriverState *(*open)(QemuOpts *opts);
3208     /* new, qapi-based */
3209     int kind;
3210     void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3211 } CharDriver;
3212
3213 static GSList *backends;
3214
3215 void register_char_driver(const char *name, CharDriverState *(*open)(QemuOpts *))
3216 {
3217     CharDriver *s;
3218
3219     s = g_malloc0(sizeof(*s));
3220     s->name = g_strdup(name);
3221     s->open = open;
3222
3223     backends = g_slist_append(backends, s);
3224 }
3225
3226 void register_char_driver_qapi(const char *name, int kind,
3227         void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3228 {
3229     CharDriver *s;
3230
3231     s = g_malloc0(sizeof(*s));
3232     s->name = g_strdup(name);
3233     s->kind = kind;
3234     s->parse = parse;
3235
3236     backends = g_slist_append(backends, s);
3237 }
3238
3239 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3240                                     void (*init)(struct CharDriverState *s),
3241                                     Error **errp)
3242 {
3243     CharDriver *cd;
3244     CharDriverState *chr;
3245     GSList *i;
3246
3247     if (qemu_opts_id(opts) == NULL) {
3248         error_setg(errp, "chardev: no id specified");
3249         goto err;
3250     }
3251
3252     if (qemu_opt_get(opts, "backend") == NULL) {
3253         error_setg(errp, "chardev: \"%s\" missing backend",
3254                    qemu_opts_id(opts));
3255         goto err;
3256     }
3257     for (i = backends; i; i = i->next) {
3258         cd = i->data;
3259
3260         if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3261             break;
3262         }
3263     }
3264     if (i == NULL) {
3265         error_setg(errp, "chardev: backend \"%s\" not found",
3266                    qemu_opt_get(opts, "backend"));
3267         return NULL;
3268     }
3269
3270     if (!cd->open) {
3271         /* using new, qapi init */
3272         ChardevBackend *backend = g_new0(ChardevBackend, 1);
3273         ChardevReturn *ret = NULL;
3274         const char *id = qemu_opts_id(opts);
3275         const char *bid = NULL;
3276
3277         if (qemu_opt_get_bool(opts, "mux", 0)) {
3278             bid = g_strdup_printf("%s-base", id);
3279         }
3280
3281         chr = NULL;
3282         backend->kind = cd->kind;
3283         if (cd->parse) {
3284             cd->parse(opts, backend, errp);
3285             if (error_is_set(errp)) {
3286                 goto qapi_out;
3287             }
3288         }
3289         ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3290         if (error_is_set(errp)) {
3291             goto qapi_out;
3292         }
3293
3294         if (bid) {
3295             qapi_free_ChardevBackend(backend);
3296             qapi_free_ChardevReturn(ret);
3297             backend = g_new0(ChardevBackend, 1);
3298             backend->mux = g_new0(ChardevMux, 1);
3299             backend->kind = CHARDEV_BACKEND_KIND_MUX;
3300             backend->mux->chardev = g_strdup(bid);
3301             ret = qmp_chardev_add(id, backend, errp);
3302             if (error_is_set(errp)) {
3303                 goto qapi_out;
3304             }
3305         }
3306
3307         chr = qemu_chr_find(id);
3308
3309     qapi_out:
3310         qapi_free_ChardevBackend(backend);
3311         qapi_free_ChardevReturn(ret);
3312         return chr;
3313     }
3314
3315     chr = cd->open(opts);
3316     if (!chr) {
3317         error_setg(errp, "chardev: opening backend \"%s\" failed",
3318                    qemu_opt_get(opts, "backend"));
3319         goto err;
3320     }
3321
3322     if (!chr->filename)
3323         chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3324     chr->init = init;
3325     QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3326
3327     if (qemu_opt_get_bool(opts, "mux", 0)) {
3328         CharDriverState *base = chr;
3329         int len = strlen(qemu_opts_id(opts)) + 6;
3330         base->label = g_malloc(len);
3331         snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3332         chr = qemu_chr_open_mux(base);
3333         chr->filename = base->filename;
3334         chr->avail_connections = MAX_MUX;
3335         QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3336     } else {
3337         chr->avail_connections = 1;
3338     }
3339     chr->label = g_strdup(qemu_opts_id(opts));
3340     chr->opts = opts;
3341     return chr;
3342
3343 err:
3344     qemu_opts_del(opts);
3345     return NULL;
3346 }
3347
3348 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3349 {
3350     const char *p;
3351     CharDriverState *chr;
3352     QemuOpts *opts;
3353     Error *err = NULL;
3354
3355     if (strstart(filename, "chardev:", &p)) {
3356         return qemu_chr_find(p);
3357     }
3358
3359     opts = qemu_chr_parse_compat(label, filename);
3360     if (!opts)
3361         return NULL;
3362
3363     chr = qemu_chr_new_from_opts(opts, init, &err);
3364     if (error_is_set(&err)) {
3365         fprintf(stderr, "%s\n", error_get_pretty(err));
3366         error_free(err);
3367     }
3368     if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3369         monitor_init(chr, MONITOR_USE_READLINE);
3370     }
3371     return chr;
3372 }
3373
3374 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3375 {
3376     if (chr->chr_set_echo) {
3377         chr->chr_set_echo(chr, echo);
3378     }
3379 }
3380
3381 void qemu_chr_fe_open(struct CharDriverState *chr)
3382 {
3383     if (chr->chr_guest_open) {
3384         chr->chr_guest_open(chr);
3385     }
3386 }
3387
3388 void qemu_chr_fe_close(struct CharDriverState *chr)
3389 {
3390     if (chr->chr_guest_close) {
3391         chr->chr_guest_close(chr);
3392     }
3393 }
3394
3395 guint qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3396                             GIOFunc func, void *user_data)
3397 {
3398     GSource *src;
3399     guint tag;
3400
3401     if (s->chr_add_watch == NULL) {
3402         return -ENOSYS;
3403     }
3404
3405     src = s->chr_add_watch(s, cond);
3406     g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3407     tag = g_source_attach(src, NULL);
3408     g_source_unref(src);
3409
3410     return tag;
3411 }
3412
3413 void qemu_chr_delete(CharDriverState *chr)
3414 {
3415     QTAILQ_REMOVE(&chardevs, chr, next);
3416     if (chr->chr_close) {
3417         chr->chr_close(chr);
3418     }
3419     g_free(chr->filename);
3420     g_free(chr->label);
3421     if (chr->opts) {
3422         qemu_opts_del(chr->opts);
3423     }
3424     g_free(chr);
3425 }
3426
3427 ChardevInfoList *qmp_query_chardev(Error **errp)
3428 {
3429     ChardevInfoList *chr_list = NULL;
3430     CharDriverState *chr;
3431
3432     QTAILQ_FOREACH(chr, &chardevs, next) {
3433         ChardevInfoList *info = g_malloc0(sizeof(*info));
3434         info->value = g_malloc0(sizeof(*info->value));
3435         info->value->label = g_strdup(chr->label);
3436         info->value->filename = g_strdup(chr->filename);
3437
3438         info->next = chr_list;
3439         chr_list = info;
3440     }
3441
3442     return chr_list;
3443 }
3444
3445 CharDriverState *qemu_chr_find(const char *name)
3446 {
3447     CharDriverState *chr;
3448
3449     QTAILQ_FOREACH(chr, &chardevs, next) {
3450         if (strcmp(chr->label, name) != 0)
3451             continue;
3452         return chr;
3453     }
3454     return NULL;
3455 }
3456
3457 /* Get a character (serial) device interface.  */
3458 CharDriverState *qemu_char_get_next_serial(void)
3459 {
3460     static int next_serial;
3461
3462     /* FIXME: This function needs to go away: use chardev properties!  */
3463     return serial_hds[next_serial++];
3464 }
3465
3466 QemuOptsList qemu_chardev_opts = {
3467     .name = "chardev",
3468     .implied_opt_name = "backend",
3469     .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3470     .desc = {
3471         {
3472             .name = "backend",
3473             .type = QEMU_OPT_STRING,
3474         },{
3475             .name = "path",
3476             .type = QEMU_OPT_STRING,
3477         },{
3478             .name = "host",
3479             .type = QEMU_OPT_STRING,
3480         },{
3481             .name = "port",
3482             .type = QEMU_OPT_STRING,
3483         },{
3484             .name = "localaddr",
3485             .type = QEMU_OPT_STRING,
3486         },{
3487             .name = "localport",
3488             .type = QEMU_OPT_STRING,
3489         },{
3490             .name = "to",
3491             .type = QEMU_OPT_NUMBER,
3492         },{
3493             .name = "ipv4",
3494             .type = QEMU_OPT_BOOL,
3495         },{
3496             .name = "ipv6",
3497             .type = QEMU_OPT_BOOL,
3498         },{
3499             .name = "wait",
3500             .type = QEMU_OPT_BOOL,
3501         },{
3502             .name = "server",
3503             .type = QEMU_OPT_BOOL,
3504         },{
3505             .name = "delay",
3506             .type = QEMU_OPT_BOOL,
3507         },{
3508             .name = "telnet",
3509             .type = QEMU_OPT_BOOL,
3510         },{
3511             .name = "width",
3512             .type = QEMU_OPT_NUMBER,
3513         },{
3514             .name = "height",
3515             .type = QEMU_OPT_NUMBER,
3516         },{
3517             .name = "cols",
3518             .type = QEMU_OPT_NUMBER,
3519         },{
3520             .name = "rows",
3521             .type = QEMU_OPT_NUMBER,
3522         },{
3523             .name = "mux",
3524             .type = QEMU_OPT_BOOL,
3525         },{
3526             .name = "signal",
3527             .type = QEMU_OPT_BOOL,
3528         },{
3529             .name = "name",
3530             .type = QEMU_OPT_STRING,
3531         },{
3532             .name = "debug",
3533             .type = QEMU_OPT_NUMBER,
3534         },{
3535             .name = "size",
3536             .type = QEMU_OPT_SIZE,
3537         },
3538         { /* end of list */ }
3539     },
3540 };
3541
3542 #ifdef _WIN32
3543
3544 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3545 {
3546     HANDLE out;
3547
3548     if (file->in) {
3549         error_setg(errp, "input file not supported");
3550         return NULL;
3551     }
3552
3553     out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3554                      OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3555     if (out == INVALID_HANDLE_VALUE) {
3556         error_setg(errp, "open %s failed", file->out);
3557         return NULL;
3558     }
3559     return qemu_chr_open_win_file(out);
3560 }
3561
3562 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3563                                                 Error **errp)
3564 {
3565     return qemu_chr_open_win_path(serial->device);
3566 }
3567
3568 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3569                                                   Error **errp)
3570 {
3571     error_setg(errp, "character device backend type 'parallel' not supported");
3572     return NULL;
3573 }
3574
3575 #else /* WIN32 */
3576
3577 static int qmp_chardev_open_file_source(char *src, int flags,
3578                                         Error **errp)
3579 {
3580     int fd = -1;
3581
3582     TFR(fd = qemu_open(src, flags, 0666));
3583     if (fd == -1) {
3584         error_setg(errp, "open %s: %s", src, strerror(errno));
3585     }
3586     return fd;
3587 }
3588
3589 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3590 {
3591     int flags, in = -1, out = -1;
3592
3593     flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3594     out = qmp_chardev_open_file_source(file->out, flags, errp);
3595     if (error_is_set(errp)) {
3596         return NULL;
3597     }
3598
3599     if (file->in) {
3600         flags = O_RDONLY;
3601         in = qmp_chardev_open_file_source(file->in, flags, errp);
3602         if (error_is_set(errp)) {
3603             qemu_close(out);
3604             return NULL;
3605         }
3606     }
3607
3608     return qemu_chr_open_fd(in, out);
3609 }
3610
3611 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3612                                                 Error **errp)
3613 {
3614 #ifdef HAVE_CHARDEV_TTY
3615     int fd;
3616
3617     fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3618     if (error_is_set(errp)) {
3619         return NULL;
3620     }
3621     socket_set_nonblock(fd);
3622     return qemu_chr_open_tty_fd(fd);
3623 #else
3624     error_setg(errp, "character device backend type 'serial' not supported");
3625     return NULL;
3626 #endif
3627 }
3628
3629 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3630                                                   Error **errp)
3631 {
3632 #ifdef HAVE_CHARDEV_PARPORT
3633     int fd;
3634
3635     fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3636     if (error_is_set(errp)) {
3637         return NULL;
3638     }
3639     return qemu_chr_open_pp_fd(fd);
3640 #else
3641     error_setg(errp, "character device backend type 'parallel' not supported");
3642     return NULL;
3643 #endif
3644 }
3645
3646 #endif /* WIN32 */
3647
3648 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3649                                                 Error **errp)
3650 {
3651     SocketAddress *addr = sock->addr;
3652     bool do_nodelay     = sock->has_nodelay ? sock->nodelay : false;
3653     bool is_listen      = sock->has_server  ? sock->server  : true;
3654     bool is_telnet      = sock->has_telnet  ? sock->telnet  : false;
3655     bool is_waitconnect = sock->has_wait    ? sock->wait    : false;
3656     int fd;
3657
3658     if (is_listen) {
3659         fd = socket_listen(addr, errp);
3660     } else {
3661         fd = socket_connect(addr, errp, NULL, NULL);
3662     }
3663     if (error_is_set(errp)) {
3664         return NULL;
3665     }
3666     return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3667                                    is_telnet, is_waitconnect, errp);
3668 }
3669
3670 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3671                                Error **errp)
3672 {
3673     ChardevReturn *ret = g_new0(ChardevReturn, 1);
3674     CharDriverState *base, *chr = NULL;
3675
3676     chr = qemu_chr_find(id);
3677     if (chr) {
3678         error_setg(errp, "Chardev '%s' already exists", id);
3679         g_free(ret);
3680         return NULL;
3681     }
3682
3683     switch (backend->kind) {
3684     case CHARDEV_BACKEND_KIND_FILE:
3685         chr = qmp_chardev_open_file(backend->file, errp);
3686         break;
3687     case CHARDEV_BACKEND_KIND_SERIAL:
3688         chr = qmp_chardev_open_serial(backend->serial, errp);
3689         break;
3690     case CHARDEV_BACKEND_KIND_PARALLEL:
3691         chr = qmp_chardev_open_parallel(backend->parallel, errp);
3692         break;
3693     case CHARDEV_BACKEND_KIND_PIPE:
3694         chr = qemu_chr_open_pipe(backend->pipe);
3695         break;
3696     case CHARDEV_BACKEND_KIND_SOCKET:
3697         chr = qmp_chardev_open_socket(backend->socket, errp);
3698         break;
3699 #ifdef HAVE_CHARDEV_TTY
3700     case CHARDEV_BACKEND_KIND_PTY:
3701         chr = qemu_chr_open_pty(id, ret);
3702         break;
3703 #endif
3704     case CHARDEV_BACKEND_KIND_NULL:
3705         chr = qemu_chr_open_null();
3706         break;
3707     case CHARDEV_BACKEND_KIND_MUX:
3708         base = qemu_chr_find(backend->mux->chardev);
3709         if (base == NULL) {
3710             error_setg(errp, "mux: base chardev %s not found",
3711                        backend->mux->chardev);
3712             break;
3713         }
3714         chr = qemu_chr_open_mux(base);
3715         break;
3716     case CHARDEV_BACKEND_KIND_MSMOUSE:
3717         chr = qemu_chr_open_msmouse();
3718         break;
3719 #ifdef CONFIG_BRLAPI
3720     case CHARDEV_BACKEND_KIND_BRAILLE:
3721         chr = chr_baum_init();
3722         break;
3723 #endif
3724     case CHARDEV_BACKEND_KIND_STDIO:
3725         chr = qemu_chr_open_stdio(backend->stdio);
3726         break;
3727 #ifdef _WIN32
3728     case CHARDEV_BACKEND_KIND_CONSOLE:
3729         chr = qemu_chr_open_win_con();
3730         break;
3731 #endif
3732 #ifdef CONFIG_SPICE
3733     case CHARDEV_BACKEND_KIND_SPICEVMC:
3734         chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
3735         break;
3736     case CHARDEV_BACKEND_KIND_SPICEPORT:
3737         chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
3738         break;
3739 #endif
3740     case CHARDEV_BACKEND_KIND_VC:
3741         chr = vc_init(backend->vc);
3742         break;
3743     default:
3744         error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3745         break;
3746     }
3747
3748     if (chr == NULL && !error_is_set(errp)) {
3749         error_setg(errp, "Failed to create chardev");
3750     }
3751     if (chr) {
3752         chr->label = g_strdup(id);
3753         chr->avail_connections =
3754             (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
3755         QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3756         return ret;
3757     } else {
3758         g_free(ret);
3759         return NULL;
3760     }
3761 }
3762
3763 void qmp_chardev_remove(const char *id, Error **errp)
3764 {
3765     CharDriverState *chr;
3766
3767     chr = qemu_chr_find(id);
3768     if (NULL == chr) {
3769         error_setg(errp, "Chardev '%s' not found", id);
3770         return;
3771     }
3772     if (chr->chr_can_read || chr->chr_read ||
3773         chr->chr_event || chr->handler_opaque) {
3774         error_setg(errp, "Chardev '%s' is busy", id);
3775         return;
3776     }
3777     qemu_chr_delete(chr);
3778 }
3779
3780 static void register_types(void)
3781 {
3782     register_char_driver_qapi("null", CHARDEV_BACKEND_KIND_NULL, NULL);
3783     register_char_driver("socket", qemu_chr_open_socket);
3784     register_char_driver("udp", qemu_chr_open_udp);
3785     register_char_driver("memory", qemu_chr_open_ringbuf);
3786     register_char_driver_qapi("file", CHARDEV_BACKEND_KIND_FILE,
3787                               qemu_chr_parse_file_out);
3788     register_char_driver_qapi("stdio", CHARDEV_BACKEND_KIND_STDIO,
3789                               qemu_chr_parse_stdio);
3790     register_char_driver_qapi("serial", CHARDEV_BACKEND_KIND_SERIAL,
3791                               qemu_chr_parse_serial);
3792     register_char_driver_qapi("tty", CHARDEV_BACKEND_KIND_SERIAL,
3793                               qemu_chr_parse_serial);
3794     register_char_driver_qapi("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
3795                               qemu_chr_parse_parallel);
3796     register_char_driver_qapi("parport", CHARDEV_BACKEND_KIND_PARALLEL,
3797                               qemu_chr_parse_parallel);
3798     register_char_driver_qapi("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
3799     register_char_driver_qapi("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
3800     register_char_driver_qapi("pipe", CHARDEV_BACKEND_KIND_PIPE,
3801                               qemu_chr_parse_pipe);
3802 }
3803
3804 type_init(register_types);