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