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