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