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