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