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