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