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