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