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