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