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