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