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