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