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