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