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