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