sync with latest
[sdk/emulator/qemu.git] / qemu-char.c
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "qemu-common.h"
25 #include "net.h"
26 #include "monitor.h"
27 #include "console.h"
28 #include "sysemu.h"
29 #include "qemu-timer.h"
30 #include "qemu-char.h"
31 #include "hw/usb.h"
32 #include "hw/baum.h"
33 #include "hw/msmouse.h"
34 #include "qmp-commands.h"
35
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <time.h>
39 #include <errno.h>
40 #include <sys/time.h>
41 #include <zlib.h>
42
43 #ifndef _WIN32
44 #include <sys/times.h>
45 #include <sys/wait.h>
46 #include <termios.h>
47 #include <sys/mman.h>
48 #include <sys/ioctl.h>
49 #include <sys/resource.h>
50 #include <sys/socket.h>
51 #include <netinet/in.h>
52 #include <net/if.h>
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef CONFIG_BSD
58 #include <sys/stat.h>
59 #if defined(__GLIBC__)
60 #include <pty.h>
61 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
62 #include <libutil.h>
63 #else
64 #include <util.h>
65 #endif
66 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
67 #include <dev/ppbus/ppi.h>
68 #include <dev/ppbus/ppbconf.h>
69 #elif defined(__DragonFly__)
70 #include <dev/misc/ppi/ppi.h>
71 #include <bus/ppbus/ppbconf.h>
72 #endif
73 #else
74 #ifdef __linux__
75 #include <pty.h>
76
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
79 #endif
80 #ifdef __sun__
81 #include <sys/stat.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
91 #include <net/if.h>
92 #include <syslog.h>
93 #include <stropts.h>
94 #endif
95 #endif
96 #endif
97
98 #include "qemu_socket.h"
99 #include "ui/qemu-spice.h"
100
101 #define READ_BUF_LEN 4096
102
103 /***********************************************************/
104 /* character device */
105
106 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
107     QTAILQ_HEAD_INITIALIZER(chardevs);
108
109 void qemu_chr_be_event(CharDriverState *s, int event)
110 {
111     /* Keep track if the char device is open */
112     switch (event) {
113         case CHR_EVENT_OPENED:
114             s->opened = 1;
115             break;
116         case CHR_EVENT_CLOSED:
117             s->opened = 0;
118             break;
119     }
120
121     if (!s->chr_event)
122         return;
123     s->chr_event(s->handler_opaque, event);
124 }
125
126 static void qemu_chr_generic_open_bh(void *opaque)
127 {
128     CharDriverState *s = opaque;
129     qemu_chr_be_event(s, CHR_EVENT_OPENED);
130     qemu_bh_delete(s->bh);
131     s->bh = NULL;
132 }
133
134 void qemu_chr_generic_open(CharDriverState *s)
135 {
136     if (s->bh == NULL) {
137         s->bh = qemu_bh_new(qemu_chr_generic_open_bh, s);
138         qemu_bh_schedule(s->bh);
139     }
140 }
141
142 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
143 {
144     return s->chr_write(s, buf, len);
145 }
146
147 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
148 {
149     if (!s->chr_ioctl)
150         return -ENOTSUP;
151     return s->chr_ioctl(s, cmd, arg);
152 }
153
154 int qemu_chr_be_can_write(CharDriverState *s)
155 {
156     if (!s->chr_can_read)
157         return 0;
158     return s->chr_can_read(s->handler_opaque);
159 }
160
161 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
162 {
163     if (s->chr_read) {
164         s->chr_read(s->handler_opaque, buf, len);
165     }
166 }
167
168 int qemu_chr_fe_get_msgfd(CharDriverState *s)
169 {
170     return s->get_msgfd ? s->get_msgfd(s) : -1;
171 }
172
173 int qemu_chr_add_client(CharDriverState *s, int fd)
174 {
175     return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
176 }
177
178 void qemu_chr_accept_input(CharDriverState *s)
179 {
180     if (s->chr_accept_input)
181         s->chr_accept_input(s);
182     qemu_notify_event();
183 }
184
185 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
186 {
187     char buf[READ_BUF_LEN];
188     va_list ap;
189     va_start(ap, fmt);
190     vsnprintf(buf, sizeof(buf), fmt, ap);
191     qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
192     va_end(ap);
193 }
194
195 void qemu_chr_add_handlers(CharDriverState *s,
196                            IOCanReadHandler *fd_can_read,
197                            IOReadHandler *fd_read,
198                            IOEventHandler *fd_event,
199                            void *opaque)
200 {
201     if (!opaque && !fd_can_read && !fd_read && !fd_event) {
202         /* chr driver being released. */
203         ++s->avail_connections;
204     }
205     s->chr_can_read = fd_can_read;
206     s->chr_read = fd_read;
207     s->chr_event = fd_event;
208     s->handler_opaque = opaque;
209     if (s->chr_update_read_handler)
210         s->chr_update_read_handler(s);
211
212     /* We're connecting to an already opened device, so let's make sure we
213        also get the open event */
214     if (s->opened) {
215         qemu_chr_generic_open(s);
216     }
217 }
218
219 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
220 {
221     return len;
222 }
223
224 static CharDriverState *qemu_chr_open_null(QemuOpts *opts)
225 {
226     CharDriverState *chr;
227
228     chr = g_malloc0(sizeof(CharDriverState));
229     chr->chr_write = null_chr_write;
230     return chr;
231 }
232
233 /* MUX driver for serial I/O splitting */
234 #define MAX_MUX 4
235 #define MUX_BUFFER_SIZE 32      /* Must be a power of 2.  */
236 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
237 typedef struct {
238     IOCanReadHandler *chr_can_read[MAX_MUX];
239     IOReadHandler *chr_read[MAX_MUX];
240     IOEventHandler *chr_event[MAX_MUX];
241     void *ext_opaque[MAX_MUX];
242     CharDriverState *drv;
243     int focus;
244     int mux_cnt;
245     int term_got_escape;
246     int max_size;
247     /* Intermediate input buffer allows to catch escape sequences even if the
248        currently active device is not accepting any input - but only until it
249        is full as well. */
250     unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
251     int prod[MAX_MUX];
252     int cons[MAX_MUX];
253     int timestamps;
254     int linestart;
255     int64_t timestamps_start;
256 } MuxDriver;
257
258
259 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
260 {
261     MuxDriver *d = chr->opaque;
262     int ret;
263     if (!d->timestamps) {
264         ret = d->drv->chr_write(d->drv, buf, len);
265     } else {
266         int i;
267
268         ret = 0;
269         for (i = 0; i < len; i++) {
270             if (d->linestart) {
271                 char buf1[64];
272                 int64_t ti;
273                 int secs;
274
275                 ti = qemu_get_clock_ms(rt_clock);
276                 if (d->timestamps_start == -1)
277                     d->timestamps_start = ti;
278                 ti -= d->timestamps_start;
279                 secs = ti / 1000;
280                 snprintf(buf1, sizeof(buf1),
281                          "[%02d:%02d:%02d.%03d] ",
282                          secs / 3600,
283                          (secs / 60) % 60,
284                          secs % 60,
285                          (int)(ti % 1000));
286                 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
287                 d->linestart = 0;
288             }
289             ret += d->drv->chr_write(d->drv, buf+i, 1);
290             if (buf[i] == '\n') {
291                 d->linestart = 1;
292             }
293         }
294     }
295     return ret;
296 }
297
298 static const char * const mux_help[] = {
299     "% h    print this help\n\r",
300     "% x    exit emulator\n\r",
301     "% s    save disk data back to file (if -snapshot)\n\r",
302     "% t    toggle console timestamps\n\r"
303     "% b    send break (magic sysrq)\n\r",
304     "% c    switch between console and monitor\n\r",
305     "% %  sends %\n\r",
306     NULL
307 };
308
309 int term_escape_char = 0x01; /* ctrl-a is used for escape */
310 static void mux_print_help(CharDriverState *chr)
311 {
312     int i, j;
313     char ebuf[15] = "Escape-Char";
314     char cbuf[50] = "\n\r";
315
316     if (term_escape_char > 0 && term_escape_char < 26) {
317         snprintf(cbuf, sizeof(cbuf), "\n\r");
318         snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
319     } else {
320         snprintf(cbuf, sizeof(cbuf),
321                  "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
322                  term_escape_char);
323     }
324     chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
325     for (i = 0; mux_help[i] != NULL; i++) {
326         for (j=0; mux_help[i][j] != '\0'; j++) {
327             if (mux_help[i][j] == '%')
328                 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
329             else
330                 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
331         }
332     }
333 }
334
335 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
336 {
337     if (d->chr_event[mux_nr])
338         d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
339 }
340
341 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
342 {
343     if (d->term_got_escape) {
344         d->term_got_escape = 0;
345         if (ch == term_escape_char)
346             goto send_char;
347         switch(ch) {
348         case '?':
349         case 'h':
350             mux_print_help(chr);
351             break;
352         case 'x':
353             {
354                  const char *term =  "QEMU: Terminated\n\r";
355                  chr->chr_write(chr,(uint8_t *)term,strlen(term));
356                  exit(0);
357                  break;
358             }
359         case 's':
360             bdrv_commit_all();
361             break;
362         case 'b':
363             qemu_chr_be_event(chr, CHR_EVENT_BREAK);
364             break;
365         case 'c':
366             /* Switch to the next registered device */
367             mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
368             d->focus++;
369             if (d->focus >= d->mux_cnt)
370                 d->focus = 0;
371             mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
372             break;
373         case 't':
374             d->timestamps = !d->timestamps;
375             d->timestamps_start = -1;
376             d->linestart = 0;
377             break;
378         }
379     } else if (ch == term_escape_char) {
380         d->term_got_escape = 1;
381     } else {
382     send_char:
383         return 1;
384     }
385     return 0;
386 }
387
388 static void mux_chr_accept_input(CharDriverState *chr)
389 {
390     MuxDriver *d = chr->opaque;
391     int m = d->focus;
392
393     while (d->prod[m] != d->cons[m] &&
394            d->chr_can_read[m] &&
395            d->chr_can_read[m](d->ext_opaque[m])) {
396         d->chr_read[m](d->ext_opaque[m],
397                        &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
398     }
399 }
400
401 static int mux_chr_can_read(void *opaque)
402 {
403     CharDriverState *chr = opaque;
404     MuxDriver *d = chr->opaque;
405     int m = d->focus;
406
407     if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
408         return 1;
409     if (d->chr_can_read[m])
410         return d->chr_can_read[m](d->ext_opaque[m]);
411     return 0;
412 }
413
414 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
415 {
416     CharDriverState *chr = opaque;
417     MuxDriver *d = chr->opaque;
418     int m = d->focus;
419     int i;
420
421     mux_chr_accept_input (opaque);
422
423     for(i = 0; i < size; i++)
424         if (mux_proc_byte(chr, d, buf[i])) {
425             if (d->prod[m] == d->cons[m] &&
426                 d->chr_can_read[m] &&
427                 d->chr_can_read[m](d->ext_opaque[m]))
428                 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
429             else
430                 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
431         }
432 }
433
434 static void mux_chr_event(void *opaque, int event)
435 {
436     CharDriverState *chr = opaque;
437     MuxDriver *d = chr->opaque;
438     int i;
439
440     /* Send the event to all registered listeners */
441     for (i = 0; i < d->mux_cnt; i++)
442         mux_chr_send_event(d, i, event);
443 }
444
445 static void mux_chr_update_read_handler(CharDriverState *chr)
446 {
447     MuxDriver *d = chr->opaque;
448
449     if (d->mux_cnt >= MAX_MUX) {
450         fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
451         return;
452     }
453     d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
454     d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
455     d->chr_read[d->mux_cnt] = chr->chr_read;
456     d->chr_event[d->mux_cnt] = chr->chr_event;
457     /* Fix up the real driver with mux routines */
458     if (d->mux_cnt == 0) {
459         qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
460                               mux_chr_event, chr);
461     }
462     if (d->focus != -1) {
463         mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
464     }
465     d->focus = d->mux_cnt;
466     d->mux_cnt++;
467     mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
468 }
469
470 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
471 {
472     CharDriverState *chr;
473     MuxDriver *d;
474
475     chr = g_malloc0(sizeof(CharDriverState));
476     d = g_malloc0(sizeof(MuxDriver));
477
478     chr->opaque = d;
479     d->drv = drv;
480     d->focus = -1;
481     chr->chr_write = mux_chr_write;
482     chr->chr_update_read_handler = mux_chr_update_read_handler;
483     chr->chr_accept_input = mux_chr_accept_input;
484     /* Frontend guest-open / -close notification is not support with muxes */
485     chr->chr_guest_open = NULL;
486     chr->chr_guest_close = NULL;
487
488     /* Muxes are always open on creation */
489     qemu_chr_generic_open(chr);
490
491     return chr;
492 }
493
494
495 #ifdef _WIN32
496 int send_all(int fd, const void *buf, int len1)
497 {
498     int ret, len;
499
500     len = len1;
501     while (len > 0) {
502         ret = send(fd, buf, len, 0);
503         if (ret < 0) {
504             errno = WSAGetLastError();
505             if (errno != WSAEWOULDBLOCK) {
506                 return -1;
507             }
508         } else if (ret == 0) {
509             break;
510         } else {
511             buf += ret;
512             len -= ret;
513         }
514     }
515     return len1 - len;
516 }
517
518 #else
519
520 int send_all(int fd, const void *_buf, int len1)
521 {
522     int ret, len;
523     const uint8_t *buf = _buf;
524
525     len = len1;
526     while (len > 0) {
527         ret = write(fd, buf, len);
528         if (ret < 0) {
529             if (errno != EINTR && errno != EAGAIN)
530                 return -1;
531         } else if (ret == 0) {
532             break;
533         } else {
534             buf += ret;
535             len -= ret;
536         }
537     }
538     return len1 - len;
539 }
540 #endif /* !_WIN32 */
541
542 #define STDIO_MAX_CLIENTS 1
543 static int stdio_nb_clients;
544
545 #ifndef _WIN32
546
547 typedef struct {
548     int fd_in, fd_out;
549     int max_size;
550 } FDCharDriver;
551
552
553 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
554 {
555     FDCharDriver *s = chr->opaque;
556     return send_all(s->fd_out, buf, len);
557 }
558
559 static int fd_chr_read_poll(void *opaque)
560 {
561     CharDriverState *chr = opaque;
562     FDCharDriver *s = chr->opaque;
563
564     s->max_size = qemu_chr_be_can_write(chr);
565     return s->max_size;
566 }
567
568 static void fd_chr_read(void *opaque)
569 {
570     CharDriverState *chr = opaque;
571     FDCharDriver *s = chr->opaque;
572     int size, len;
573     uint8_t buf[READ_BUF_LEN];
574
575     len = sizeof(buf);
576     if (len > s->max_size)
577         len = s->max_size;
578     if (len == 0)
579         return;
580     size = read(s->fd_in, buf, len);
581     if (size == 0) {
582         /* FD has been closed. Remove it from the active list.  */
583         qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
584         qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
585         return;
586     }
587     if (size > 0) {
588         qemu_chr_be_write(chr, buf, size);
589     }
590 }
591
592 static void fd_chr_update_read_handler(CharDriverState *chr)
593 {
594     FDCharDriver *s = chr->opaque;
595
596     if (s->fd_in >= 0) {
597         if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
598         } else {
599             qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
600                                  fd_chr_read, NULL, chr);
601         }
602     }
603 }
604
605 static void fd_chr_close(struct CharDriverState *chr)
606 {
607     FDCharDriver *s = chr->opaque;
608
609     if (s->fd_in >= 0) {
610         if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
611         } else {
612             qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
613         }
614     }
615
616     g_free(s);
617     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
618 }
619
620 /* open a character device to a unix fd */
621 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
622 {
623     CharDriverState *chr;
624     FDCharDriver *s;
625
626     chr = g_malloc0(sizeof(CharDriverState));
627     s = g_malloc0(sizeof(FDCharDriver));
628     s->fd_in = fd_in;
629     s->fd_out = fd_out;
630     chr->opaque = s;
631     chr->chr_write = fd_chr_write;
632     chr->chr_update_read_handler = fd_chr_update_read_handler;
633     chr->chr_close = fd_chr_close;
634
635     qemu_chr_generic_open(chr);
636
637     return chr;
638 }
639
640 static CharDriverState *qemu_chr_open_file_out(QemuOpts *opts)
641 {
642     int fd_out;
643
644     TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
645                       O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
646     if (fd_out < 0) {
647         return NULL;
648     }
649     return qemu_chr_open_fd(-1, fd_out);
650 }
651
652 static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)
653 {
654     int fd_in, fd_out;
655     char filename_in[256], filename_out[256];
656     const char *filename = qemu_opt_get(opts, "path");
657
658     if (filename == NULL) {
659         fprintf(stderr, "chardev: pipe: no filename given\n");
660         return NULL;
661     }
662
663     snprintf(filename_in, 256, "%s.in", filename);
664     snprintf(filename_out, 256, "%s.out", filename);
665     TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
666     TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
667     if (fd_in < 0 || fd_out < 0) {
668         if (fd_in >= 0)
669             close(fd_in);
670         if (fd_out >= 0)
671             close(fd_out);
672         TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
673         if (fd_in < 0) {
674             return NULL;
675         }
676     }
677     return qemu_chr_open_fd(fd_in, fd_out);
678 }
679
680
681 /* for STDIO, we handle the case where several clients use it
682    (nographic mode) */
683
684 #define TERM_FIFO_MAX_SIZE 1
685
686 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
687 static int term_fifo_size;
688
689 static int stdio_read_poll(void *opaque)
690 {
691     CharDriverState *chr = opaque;
692
693     /* try to flush the queue if needed */
694     if (term_fifo_size != 0 && qemu_chr_be_can_write(chr) > 0) {
695         qemu_chr_be_write(chr, term_fifo, 1);
696         term_fifo_size = 0;
697     }
698     /* see if we can absorb more chars */
699     if (term_fifo_size == 0)
700         return 1;
701     else
702         return 0;
703 }
704
705 static void stdio_read(void *opaque)
706 {
707     int size;
708     uint8_t buf[1];
709     CharDriverState *chr = opaque;
710
711     size = read(0, buf, 1);
712     if (size == 0) {
713         /* stdin has been closed. Remove it from the active list.  */
714         qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
715         qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
716         return;
717     }
718     if (size > 0) {
719         if (qemu_chr_be_can_write(chr) > 0) {
720             qemu_chr_be_write(chr, buf, 1);
721         } else if (term_fifo_size == 0) {
722             term_fifo[term_fifo_size++] = buf[0];
723         }
724     }
725 }
726
727 /* init terminal so that we can grab keys */
728 static struct termios oldtty;
729 static int old_fd0_flags;
730 static bool stdio_allow_signal;
731
732 static void term_exit(void)
733 {
734     tcsetattr (0, TCSANOW, &oldtty);
735     fcntl(0, F_SETFL, old_fd0_flags);
736 }
737
738 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
739 {
740     struct termios tty;
741
742     tty = oldtty;
743     if (!echo) {
744         tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
745                           |INLCR|IGNCR|ICRNL|IXON);
746         tty.c_oflag |= OPOST;
747         tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
748         tty.c_cflag &= ~(CSIZE|PARENB);
749         tty.c_cflag |= CS8;
750         tty.c_cc[VMIN] = 1;
751         tty.c_cc[VTIME] = 0;
752     }
753     /* if graphical mode, we allow Ctrl-C handling */
754     if (!stdio_allow_signal)
755         tty.c_lflag &= ~ISIG;
756
757     tcsetattr (0, TCSANOW, &tty);
758 }
759
760 static void qemu_chr_close_stdio(struct CharDriverState *chr)
761 {
762     term_exit();
763     stdio_nb_clients--;
764     qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
765     fd_chr_close(chr);
766 }
767
768 static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)
769 {
770     CharDriverState *chr;
771
772     if (stdio_nb_clients >= STDIO_MAX_CLIENTS) {
773         return NULL;
774     }
775     if (stdio_nb_clients == 0) {
776         old_fd0_flags = fcntl(0, F_GETFL);
777         tcgetattr (0, &oldtty);
778         fcntl(0, F_SETFL, O_NONBLOCK);
779         atexit(term_exit);
780     }
781
782     chr = qemu_chr_open_fd(0, 1);
783     chr->chr_close = qemu_chr_close_stdio;
784     chr->chr_set_echo = qemu_chr_set_echo_stdio;
785     qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
786     stdio_nb_clients++;
787     stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
788                                            display_type != DT_NOGRAPHIC);
789     qemu_chr_fe_set_echo(chr, false);
790
791     return chr;
792 }
793
794 #ifdef __sun__
795 /* Once Solaris has openpty(), this is going to be removed. */
796 static int openpty(int *amaster, int *aslave, char *name,
797                    struct termios *termp, struct winsize *winp)
798 {
799         const char *slave;
800         int mfd = -1, sfd = -1;
801
802         *amaster = *aslave = -1;
803
804         mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
805         if (mfd < 0)
806                 goto err;
807
808         if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
809                 goto err;
810
811         if ((slave = ptsname(mfd)) == NULL)
812                 goto err;
813
814         if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
815                 goto err;
816
817         if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
818             (termp != NULL && tcgetattr(sfd, termp) < 0))
819                 goto err;
820
821         if (amaster)
822                 *amaster = mfd;
823         if (aslave)
824                 *aslave = sfd;
825         if (winp)
826                 ioctl(sfd, TIOCSWINSZ, winp);
827
828         return 0;
829
830 err:
831         if (sfd != -1)
832                 close(sfd);
833         close(mfd);
834         return -1;
835 }
836
837 static void cfmakeraw (struct termios *termios_p)
838 {
839         termios_p->c_iflag &=
840                 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
841         termios_p->c_oflag &= ~OPOST;
842         termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
843         termios_p->c_cflag &= ~(CSIZE|PARENB);
844         termios_p->c_cflag |= CS8;
845
846         termios_p->c_cc[VMIN] = 0;
847         termios_p->c_cc[VTIME] = 0;
848 }
849 #endif
850
851 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
852     || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
853     || defined(__GLIBC__)
854
855 typedef struct {
856     int fd;
857     int connected;
858     int polling;
859     int read_bytes;
860     QEMUTimer *timer;
861 } PtyCharDriver;
862
863 static void pty_chr_update_read_handler(CharDriverState *chr);
864 static void pty_chr_state(CharDriverState *chr, int connected);
865
866 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
867 {
868     PtyCharDriver *s = chr->opaque;
869
870     if (!s->connected) {
871         /* guest sends data, check for (re-)connect */
872         pty_chr_update_read_handler(chr);
873         return 0;
874     }
875     return send_all(s->fd, buf, len);
876 }
877
878 static int pty_chr_read_poll(void *opaque)
879 {
880     CharDriverState *chr = opaque;
881     PtyCharDriver *s = chr->opaque;
882
883     s->read_bytes = qemu_chr_be_can_write(chr);
884     return s->read_bytes;
885 }
886
887 static void pty_chr_read(void *opaque)
888 {
889     CharDriverState *chr = opaque;
890     PtyCharDriver *s = chr->opaque;
891     int size, len;
892     uint8_t buf[READ_BUF_LEN];
893
894     len = sizeof(buf);
895     if (len > s->read_bytes)
896         len = s->read_bytes;
897     if (len == 0)
898         return;
899     size = read(s->fd, buf, len);
900     if ((size == -1 && errno == EIO) ||
901         (size == 0)) {
902         pty_chr_state(chr, 0);
903         return;
904     }
905     if (size > 0) {
906         pty_chr_state(chr, 1);
907         qemu_chr_be_write(chr, buf, size);
908     }
909 }
910
911 static void pty_chr_update_read_handler(CharDriverState *chr)
912 {
913     PtyCharDriver *s = chr->opaque;
914
915     qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
916                          pty_chr_read, NULL, chr);
917     s->polling = 1;
918     /*
919      * Short timeout here: just need wait long enougth that qemu makes
920      * it through the poll loop once.  When reconnected we want a
921      * short timeout so we notice it almost instantly.  Otherwise
922      * read() gives us -EIO instantly, making pty_chr_state() reset the
923      * timeout to the normal (much longer) poll interval before the
924      * timer triggers.
925      */
926     qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 10);
927 }
928
929 static void pty_chr_state(CharDriverState *chr, int connected)
930 {
931     PtyCharDriver *s = chr->opaque;
932
933     if (!connected) {
934         qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
935         s->connected = 0;
936         s->polling = 0;
937         /* (re-)connect poll interval for idle guests: once per second.
938          * We check more frequently in case the guests sends data to
939          * the virtual device linked to our pty. */
940         qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 1000);
941     } else {
942         if (!s->connected)
943             qemu_chr_generic_open(chr);
944         s->connected = 1;
945     }
946 }
947
948 static void pty_chr_timer(void *opaque)
949 {
950     struct CharDriverState *chr = opaque;
951     PtyCharDriver *s = chr->opaque;
952
953     if (s->connected)
954         return;
955     if (s->polling) {
956         /* If we arrive here without polling being cleared due
957          * read returning -EIO, then we are (re-)connected */
958         pty_chr_state(chr, 1);
959         return;
960     }
961
962     /* Next poll ... */
963     pty_chr_update_read_handler(chr);
964 }
965
966 static void pty_chr_close(struct CharDriverState *chr)
967 {
968     PtyCharDriver *s = chr->opaque;
969
970     qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
971     close(s->fd);
972     qemu_del_timer(s->timer);
973     qemu_free_timer(s->timer);
974     g_free(s);
975     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
976 }
977
978 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
979 {
980     CharDriverState *chr;
981     PtyCharDriver *s;
982     struct termios tty;
983     int master_fd, slave_fd, len;
984 #if defined(__OpenBSD__) || defined(__DragonFly__)
985     char pty_name[PATH_MAX];
986 #define q_ptsname(x) pty_name
987 #else
988     char *pty_name = NULL;
989 #define q_ptsname(x) ptsname(x)
990 #endif
991
992     if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
993         return NULL;
994     }
995
996     /* Set raw attributes on the pty. */
997     tcgetattr(slave_fd, &tty);
998     cfmakeraw(&tty);
999     tcsetattr(slave_fd, TCSAFLUSH, &tty);
1000     close(slave_fd);
1001
1002     chr = g_malloc0(sizeof(CharDriverState));
1003
1004     len = strlen(q_ptsname(master_fd)) + 5;
1005     chr->filename = g_malloc(len);
1006     snprintf(chr->filename, len, "pty:%s", q_ptsname(master_fd));
1007     qemu_opt_set(opts, "path", q_ptsname(master_fd));
1008     fprintf(stderr, "char device redirected to %s\n", q_ptsname(master_fd));
1009
1010     s = g_malloc0(sizeof(PtyCharDriver));
1011     chr->opaque = s;
1012     chr->chr_write = pty_chr_write;
1013     chr->chr_update_read_handler = pty_chr_update_read_handler;
1014     chr->chr_close = pty_chr_close;
1015
1016     s->fd = master_fd;
1017     s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr);
1018
1019     return chr;
1020 }
1021
1022 static void tty_serial_init(int fd, int speed,
1023                             int parity, int data_bits, int stop_bits)
1024 {
1025     struct termios tty;
1026     speed_t spd;
1027
1028 #if 0
1029     printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1030            speed, parity, data_bits, stop_bits);
1031 #endif
1032     tcgetattr (fd, &tty);
1033
1034 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1035     speed = speed * 10 / 11;
1036     do {
1037         check_speed(50);
1038         check_speed(75);
1039         check_speed(110);
1040         check_speed(134);
1041         check_speed(150);
1042         check_speed(200);
1043         check_speed(300);
1044         check_speed(600);
1045         check_speed(1200);
1046         check_speed(1800);
1047         check_speed(2400);
1048         check_speed(4800);
1049         check_speed(9600);
1050         check_speed(19200);
1051         check_speed(38400);
1052         /* Non-Posix values follow. They may be unsupported on some systems. */
1053         check_speed(57600);
1054         check_speed(115200);
1055 #ifdef B230400
1056         check_speed(230400);
1057 #endif
1058 #ifdef B460800
1059         check_speed(460800);
1060 #endif
1061 #ifdef B500000
1062         check_speed(500000);
1063 #endif
1064 #ifdef B576000
1065         check_speed(576000);
1066 #endif
1067 #ifdef B921600
1068         check_speed(921600);
1069 #endif
1070 #ifdef B1000000
1071         check_speed(1000000);
1072 #endif
1073 #ifdef B1152000
1074         check_speed(1152000);
1075 #endif
1076 #ifdef B1500000
1077         check_speed(1500000);
1078 #endif
1079 #ifdef B2000000
1080         check_speed(2000000);
1081 #endif
1082 #ifdef B2500000
1083         check_speed(2500000);
1084 #endif
1085 #ifdef B3000000
1086         check_speed(3000000);
1087 #endif
1088 #ifdef B3500000
1089         check_speed(3500000);
1090 #endif
1091 #ifdef B4000000
1092         check_speed(4000000);
1093 #endif
1094         spd = B115200;
1095     } while (0);
1096
1097     cfsetispeed(&tty, spd);
1098     cfsetospeed(&tty, spd);
1099
1100     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1101                           |INLCR|IGNCR|ICRNL|IXON);
1102     tty.c_oflag |= OPOST;
1103     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1104     tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1105     switch(data_bits) {
1106     default:
1107     case 8:
1108         tty.c_cflag |= CS8;
1109         break;
1110     case 7:
1111         tty.c_cflag |= CS7;
1112         break;
1113     case 6:
1114         tty.c_cflag |= CS6;
1115         break;
1116     case 5:
1117         tty.c_cflag |= CS5;
1118         break;
1119     }
1120     switch(parity) {
1121     default:
1122     case 'N':
1123         break;
1124     case 'E':
1125         tty.c_cflag |= PARENB;
1126         break;
1127     case 'O':
1128         tty.c_cflag |= PARENB | PARODD;
1129         break;
1130     }
1131     if (stop_bits == 2)
1132         tty.c_cflag |= CSTOPB;
1133
1134     tcsetattr (fd, TCSANOW, &tty);
1135 }
1136
1137 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1138 {
1139     FDCharDriver *s = chr->opaque;
1140
1141     switch(cmd) {
1142     case CHR_IOCTL_SERIAL_SET_PARAMS:
1143         {
1144             QEMUSerialSetParams *ssp = arg;
1145             tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1146                             ssp->data_bits, ssp->stop_bits);
1147         }
1148         break;
1149     case CHR_IOCTL_SERIAL_SET_BREAK:
1150         {
1151             int enable = *(int *)arg;
1152             if (enable)
1153                 tcsendbreak(s->fd_in, 1);
1154         }
1155         break;
1156     case CHR_IOCTL_SERIAL_GET_TIOCM:
1157         {
1158             int sarg = 0;
1159             int *targ = (int *)arg;
1160             ioctl(s->fd_in, TIOCMGET, &sarg);
1161             *targ = 0;
1162             if (sarg & TIOCM_CTS)
1163                 *targ |= CHR_TIOCM_CTS;
1164             if (sarg & TIOCM_CAR)
1165                 *targ |= CHR_TIOCM_CAR;
1166             if (sarg & TIOCM_DSR)
1167                 *targ |= CHR_TIOCM_DSR;
1168             if (sarg & TIOCM_RI)
1169                 *targ |= CHR_TIOCM_RI;
1170             if (sarg & TIOCM_DTR)
1171                 *targ |= CHR_TIOCM_DTR;
1172             if (sarg & TIOCM_RTS)
1173                 *targ |= CHR_TIOCM_RTS;
1174         }
1175         break;
1176     case CHR_IOCTL_SERIAL_SET_TIOCM:
1177         {
1178             int sarg = *(int *)arg;
1179             int targ = 0;
1180             ioctl(s->fd_in, TIOCMGET, &targ);
1181             targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1182                      | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1183             if (sarg & CHR_TIOCM_CTS)
1184                 targ |= TIOCM_CTS;
1185             if (sarg & CHR_TIOCM_CAR)
1186                 targ |= TIOCM_CAR;
1187             if (sarg & CHR_TIOCM_DSR)
1188                 targ |= TIOCM_DSR;
1189             if (sarg & CHR_TIOCM_RI)
1190                 targ |= TIOCM_RI;
1191             if (sarg & CHR_TIOCM_DTR)
1192                 targ |= TIOCM_DTR;
1193             if (sarg & CHR_TIOCM_RTS)
1194                 targ |= TIOCM_RTS;
1195             ioctl(s->fd_in, TIOCMSET, &targ);
1196         }
1197         break;
1198     default:
1199         return -ENOTSUP;
1200     }
1201     return 0;
1202 }
1203
1204 static void qemu_chr_close_tty(CharDriverState *chr)
1205 {
1206     FDCharDriver *s = chr->opaque;
1207     int fd = -1;
1208
1209     if (s) {
1210         fd = s->fd_in;
1211     }
1212
1213     fd_chr_close(chr);
1214
1215     if (fd >= 0) {
1216         close(fd);
1217     }
1218 }
1219
1220 static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
1221 {
1222     const char *filename = qemu_opt_get(opts, "path");
1223     CharDriverState *chr;
1224     int fd;
1225
1226     TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
1227     if (fd < 0) {
1228         return NULL;
1229     }
1230     tty_serial_init(fd, 115200, 'N', 8, 1);
1231     chr = qemu_chr_open_fd(fd, fd);
1232     chr->chr_ioctl = tty_serial_ioctl;
1233     chr->chr_close = qemu_chr_close_tty;
1234     return chr;
1235 }
1236 #else  /* ! __linux__ && ! __sun__ */
1237 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
1238 {
1239     return NULL;
1240 }
1241 #endif /* __linux__ || __sun__ */
1242
1243 #if defined(__linux__)
1244 typedef struct {
1245     int fd;
1246     int mode;
1247 } ParallelCharDriver;
1248
1249 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1250 {
1251     if (s->mode != mode) {
1252         int m = mode;
1253         if (ioctl(s->fd, PPSETMODE, &m) < 0)
1254             return 0;
1255         s->mode = mode;
1256     }
1257     return 1;
1258 }
1259
1260 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1261 {
1262     ParallelCharDriver *drv = chr->opaque;
1263     int fd = drv->fd;
1264     uint8_t b;
1265
1266     switch(cmd) {
1267     case CHR_IOCTL_PP_READ_DATA:
1268         if (ioctl(fd, PPRDATA, &b) < 0)
1269             return -ENOTSUP;
1270         *(uint8_t *)arg = b;
1271         break;
1272     case CHR_IOCTL_PP_WRITE_DATA:
1273         b = *(uint8_t *)arg;
1274         if (ioctl(fd, PPWDATA, &b) < 0)
1275             return -ENOTSUP;
1276         break;
1277     case CHR_IOCTL_PP_READ_CONTROL:
1278         if (ioctl(fd, PPRCONTROL, &b) < 0)
1279             return -ENOTSUP;
1280         /* Linux gives only the lowest bits, and no way to know data
1281            direction! For better compatibility set the fixed upper
1282            bits. */
1283         *(uint8_t *)arg = b | 0xc0;
1284         break;
1285     case CHR_IOCTL_PP_WRITE_CONTROL:
1286         b = *(uint8_t *)arg;
1287         if (ioctl(fd, PPWCONTROL, &b) < 0)
1288             return -ENOTSUP;
1289         break;
1290     case CHR_IOCTL_PP_READ_STATUS:
1291         if (ioctl(fd, PPRSTATUS, &b) < 0)
1292             return -ENOTSUP;
1293         *(uint8_t *)arg = b;
1294         break;
1295     case CHR_IOCTL_PP_DATA_DIR:
1296         if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1297             return -ENOTSUP;
1298         break;
1299     case CHR_IOCTL_PP_EPP_READ_ADDR:
1300         if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1301             struct ParallelIOArg *parg = arg;
1302             int n = read(fd, parg->buffer, parg->count);
1303             if (n != parg->count) {
1304                 return -EIO;
1305             }
1306         }
1307         break;
1308     case CHR_IOCTL_PP_EPP_READ:
1309         if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1310             struct ParallelIOArg *parg = arg;
1311             int n = read(fd, parg->buffer, parg->count);
1312             if (n != parg->count) {
1313                 return -EIO;
1314             }
1315         }
1316         break;
1317     case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1318         if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1319             struct ParallelIOArg *parg = arg;
1320             int n = write(fd, parg->buffer, parg->count);
1321             if (n != parg->count) {
1322                 return -EIO;
1323             }
1324         }
1325         break;
1326     case CHR_IOCTL_PP_EPP_WRITE:
1327         if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1328             struct ParallelIOArg *parg = arg;
1329             int n = write(fd, parg->buffer, parg->count);
1330             if (n != parg->count) {
1331                 return -EIO;
1332             }
1333         }
1334         break;
1335     default:
1336         return -ENOTSUP;
1337     }
1338     return 0;
1339 }
1340
1341 static void pp_close(CharDriverState *chr)
1342 {
1343     ParallelCharDriver *drv = chr->opaque;
1344     int fd = drv->fd;
1345
1346     pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1347     ioctl(fd, PPRELEASE);
1348     close(fd);
1349     g_free(drv);
1350     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1351 }
1352
1353 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1354 {
1355     const char *filename = qemu_opt_get(opts, "path");
1356     CharDriverState *chr;
1357     ParallelCharDriver *drv;
1358     int fd;
1359
1360     TFR(fd = qemu_open(filename, O_RDWR));
1361     if (fd < 0) {
1362         return NULL;
1363     }
1364
1365     if (ioctl(fd, PPCLAIM) < 0) {
1366         close(fd);
1367         return NULL;
1368     }
1369
1370     drv = g_malloc0(sizeof(ParallelCharDriver));
1371     drv->fd = fd;
1372     drv->mode = IEEE1284_MODE_COMPAT;
1373
1374     chr = g_malloc0(sizeof(CharDriverState));
1375     chr->chr_write = null_chr_write;
1376     chr->chr_ioctl = pp_ioctl;
1377     chr->chr_close = pp_close;
1378     chr->opaque = drv;
1379
1380     qemu_chr_generic_open(chr);
1381
1382     return chr;
1383 }
1384 #endif /* __linux__ */
1385
1386 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1387 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1388 {
1389     int fd = (int)(intptr_t)chr->opaque;
1390     uint8_t b;
1391
1392     switch(cmd) {
1393     case CHR_IOCTL_PP_READ_DATA:
1394         if (ioctl(fd, PPIGDATA, &b) < 0)
1395             return -ENOTSUP;
1396         *(uint8_t *)arg = b;
1397         break;
1398     case CHR_IOCTL_PP_WRITE_DATA:
1399         b = *(uint8_t *)arg;
1400         if (ioctl(fd, PPISDATA, &b) < 0)
1401             return -ENOTSUP;
1402         break;
1403     case CHR_IOCTL_PP_READ_CONTROL:
1404         if (ioctl(fd, PPIGCTRL, &b) < 0)
1405             return -ENOTSUP;
1406         *(uint8_t *)arg = b;
1407         break;
1408     case CHR_IOCTL_PP_WRITE_CONTROL:
1409         b = *(uint8_t *)arg;
1410         if (ioctl(fd, PPISCTRL, &b) < 0)
1411             return -ENOTSUP;
1412         break;
1413     case CHR_IOCTL_PP_READ_STATUS:
1414         if (ioctl(fd, PPIGSTATUS, &b) < 0)
1415             return -ENOTSUP;
1416         *(uint8_t *)arg = b;
1417         break;
1418     default:
1419         return -ENOTSUP;
1420     }
1421     return 0;
1422 }
1423
1424 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1425 {
1426     const char *filename = qemu_opt_get(opts, "path");
1427     CharDriverState *chr;
1428     int fd;
1429
1430     fd = qemu_open(filename, O_RDWR);
1431     if (fd < 0) {
1432         return NULL;
1433     }
1434
1435     chr = g_malloc0(sizeof(CharDriverState));
1436     chr->opaque = (void *)(intptr_t)fd;
1437     chr->chr_write = null_chr_write;
1438     chr->chr_ioctl = pp_ioctl;
1439     return chr;
1440 }
1441 #endif
1442
1443 #else /* _WIN32 */
1444
1445 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1446
1447 typedef struct {
1448     int max_size;
1449     HANDLE hcom, hrecv, hsend;
1450     OVERLAPPED orecv, osend;
1451     BOOL fpipe;
1452     DWORD len;
1453 } WinCharState;
1454
1455 typedef struct {
1456     HANDLE  hStdIn;
1457     HANDLE  hInputReadyEvent;
1458     HANDLE  hInputDoneEvent;
1459     HANDLE  hInputThread;
1460     uint8_t win_stdio_buf;
1461 } WinStdioCharState;
1462
1463 #define NSENDBUF 2048
1464 #define NRECVBUF 2048
1465 #define MAXCONNECT 1
1466 #define NTIMEOUT 5000
1467
1468 static int win_chr_poll(void *opaque);
1469 static int win_chr_pipe_poll(void *opaque);
1470
1471 static void win_chr_close(CharDriverState *chr)
1472 {
1473     WinCharState *s = chr->opaque;
1474
1475     if (s->hsend) {
1476         CloseHandle(s->hsend);
1477         s->hsend = NULL;
1478     }
1479     if (s->hrecv) {
1480         CloseHandle(s->hrecv);
1481         s->hrecv = NULL;
1482     }
1483     if (s->hcom) {
1484         CloseHandle(s->hcom);
1485         s->hcom = NULL;
1486     }
1487     if (s->fpipe)
1488         qemu_del_polling_cb(win_chr_pipe_poll, chr);
1489     else
1490         qemu_del_polling_cb(win_chr_poll, chr);
1491
1492     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1493 }
1494
1495 static int win_chr_init(CharDriverState *chr, const char *filename)
1496 {
1497     WinCharState *s = chr->opaque;
1498     COMMCONFIG comcfg;
1499     COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1500     COMSTAT comstat;
1501     DWORD size;
1502     DWORD err;
1503
1504     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1505     if (!s->hsend) {
1506         fprintf(stderr, "Failed CreateEvent\n");
1507         goto fail;
1508     }
1509     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1510     if (!s->hrecv) {
1511         fprintf(stderr, "Failed CreateEvent\n");
1512         goto fail;
1513     }
1514 #ifndef CONFIG_MARU
1515     s->hcom = CreateFile(filename,
1516                       GENERIC_READ|GENERIC_WRITE, 0, NULL,
1517                       OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1518 #else
1519         int open_flags = O_BINARY | O_RDWR;
1520         // TODO : FILE_FLAG_OVERLAPPED
1521
1522         int ret = qemu_open(filename, open_flags, 0644);
1523         if (ret < 0) {
1524                 error_report("win_chr_init failed(%d) \n", ret);
1525                 return -errno;
1526         }
1527         s->hcom = (HANDLE)_get_osfhandle(ret);
1528
1529 #endif
1530     if (s->hcom == INVALID_HANDLE_VALUE) {
1531         fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1532         s->hcom = NULL;
1533         goto fail;
1534     }
1535
1536     if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1537         fprintf(stderr, "Failed SetupComm\n");
1538         goto fail;
1539     }
1540
1541     ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1542     size = sizeof(COMMCONFIG);
1543     GetDefaultCommConfig(filename, &comcfg, &size);
1544     comcfg.dcb.DCBlength = sizeof(DCB);
1545     CommConfigDialog(filename, NULL, &comcfg);
1546
1547     if (!SetCommState(s->hcom, &comcfg.dcb)) {
1548         fprintf(stderr, "Failed SetCommState\n");
1549         goto fail;
1550     }
1551
1552     if (!SetCommMask(s->hcom, EV_ERR)) {
1553         fprintf(stderr, "Failed SetCommMask\n");
1554         goto fail;
1555     }
1556
1557     cto.ReadIntervalTimeout = MAXDWORD;
1558     if (!SetCommTimeouts(s->hcom, &cto)) {
1559         fprintf(stderr, "Failed SetCommTimeouts\n");
1560         goto fail;
1561     }
1562
1563     if (!ClearCommError(s->hcom, &err, &comstat)) {
1564         fprintf(stderr, "Failed ClearCommError\n");
1565         goto fail;
1566     }
1567     qemu_add_polling_cb(win_chr_poll, chr);
1568     return 0;
1569
1570  fail:
1571     win_chr_close(chr);
1572     return -1;
1573 }
1574
1575 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1576 {
1577     WinCharState *s = chr->opaque;
1578     DWORD len, ret, size, err;
1579
1580     len = len1;
1581     ZeroMemory(&s->osend, sizeof(s->osend));
1582     s->osend.hEvent = s->hsend;
1583     while (len > 0) {
1584         if (s->hsend)
1585             ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1586         else
1587             ret = WriteFile(s->hcom, buf, len, &size, NULL);
1588         if (!ret) {
1589             err = GetLastError();
1590             if (err == ERROR_IO_PENDING) {
1591                 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1592                 if (ret) {
1593                     buf += size;
1594                     len -= size;
1595                 } else {
1596                     break;
1597                 }
1598             } else {
1599                 break;
1600             }
1601         } else {
1602             buf += size;
1603             len -= size;
1604         }
1605     }
1606     return len1 - len;
1607 }
1608
1609 static int win_chr_read_poll(CharDriverState *chr)
1610 {
1611     WinCharState *s = chr->opaque;
1612
1613     s->max_size = qemu_chr_be_can_write(chr);
1614     return s->max_size;
1615 }
1616
1617 static void win_chr_readfile(CharDriverState *chr)
1618 {
1619     WinCharState *s = chr->opaque;
1620     int ret, err;
1621     uint8_t buf[READ_BUF_LEN];
1622     DWORD size;
1623
1624     ZeroMemory(&s->orecv, sizeof(s->orecv));
1625     s->orecv.hEvent = s->hrecv;
1626     ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1627     if (!ret) {
1628         err = GetLastError();
1629         if (err == ERROR_IO_PENDING) {
1630             ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1631         }
1632     }
1633
1634     if (size > 0) {
1635         qemu_chr_be_write(chr, buf, size);
1636     }
1637 }
1638
1639 static void win_chr_read(CharDriverState *chr)
1640 {
1641     WinCharState *s = chr->opaque;
1642
1643     if (s->len > s->max_size)
1644         s->len = s->max_size;
1645     if (s->len == 0)
1646         return;
1647
1648     win_chr_readfile(chr);
1649 }
1650
1651 static int win_chr_poll(void *opaque)
1652 {
1653     CharDriverState *chr = opaque;
1654     WinCharState *s = chr->opaque;
1655     COMSTAT status;
1656     DWORD comerr;
1657
1658     ClearCommError(s->hcom, &comerr, &status);
1659     if (status.cbInQue > 0) {
1660         s->len = status.cbInQue;
1661         win_chr_read_poll(chr);
1662         win_chr_read(chr);
1663         return 1;
1664     }
1665     return 0;
1666 }
1667
1668 static CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1669 {
1670     const char *filename = qemu_opt_get(opts, "path");
1671     CharDriverState *chr;
1672     WinCharState *s;
1673
1674     chr = g_malloc0(sizeof(CharDriverState));
1675     s = g_malloc0(sizeof(WinCharState));
1676     chr->opaque = s;
1677     chr->chr_write = win_chr_write;
1678     chr->chr_close = win_chr_close;
1679
1680     if (win_chr_init(chr, filename) < 0) {
1681         g_free(s);
1682         g_free(chr);
1683         return NULL;
1684     }
1685     qemu_chr_generic_open(chr);
1686     return chr;
1687 }
1688
1689 static int win_chr_pipe_poll(void *opaque)
1690 {
1691     CharDriverState *chr = opaque;
1692     WinCharState *s = chr->opaque;
1693     DWORD size;
1694
1695     PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1696     if (size > 0) {
1697         s->len = size;
1698         win_chr_read_poll(chr);
1699         win_chr_read(chr);
1700         return 1;
1701     }
1702     return 0;
1703 }
1704
1705 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1706 {
1707     WinCharState *s = chr->opaque;
1708     OVERLAPPED ov;
1709     int ret;
1710     DWORD size;
1711     char openname[256];
1712
1713     s->fpipe = TRUE;
1714
1715     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1716     if (!s->hsend) {
1717         fprintf(stderr, "Failed CreateEvent\n");
1718         goto fail;
1719     }
1720     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1721     if (!s->hrecv) {
1722         fprintf(stderr, "Failed CreateEvent\n");
1723         goto fail;
1724     }
1725
1726     snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1727     s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1728                               PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1729                               PIPE_WAIT,
1730                               MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1731     if (s->hcom == INVALID_HANDLE_VALUE) {
1732         fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1733         s->hcom = NULL;
1734         goto fail;
1735     }
1736
1737     ZeroMemory(&ov, sizeof(ov));
1738     ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1739     ret = ConnectNamedPipe(s->hcom, &ov);
1740     if (ret) {
1741         fprintf(stderr, "Failed ConnectNamedPipe\n");
1742         goto fail;
1743     }
1744
1745     ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1746     if (!ret) {
1747         fprintf(stderr, "Failed GetOverlappedResult\n");
1748         if (ov.hEvent) {
1749             CloseHandle(ov.hEvent);
1750             ov.hEvent = NULL;
1751         }
1752         goto fail;
1753     }
1754
1755     if (ov.hEvent) {
1756         CloseHandle(ov.hEvent);
1757         ov.hEvent = NULL;
1758     }
1759     qemu_add_polling_cb(win_chr_pipe_poll, chr);
1760     return 0;
1761
1762  fail:
1763     win_chr_close(chr);
1764     return -1;
1765 }
1766
1767
1768 static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
1769 {
1770     const char *filename = qemu_opt_get(opts, "path");
1771     CharDriverState *chr;
1772     WinCharState *s;
1773
1774     chr = g_malloc0(sizeof(CharDriverState));
1775     s = g_malloc0(sizeof(WinCharState));
1776     chr->opaque = s;
1777     chr->chr_write = win_chr_write;
1778     chr->chr_close = win_chr_close;
1779
1780     if (win_chr_pipe_init(chr, filename) < 0) {
1781         g_free(s);
1782         g_free(chr);
1783         return NULL;
1784     }
1785     qemu_chr_generic_open(chr);
1786     return chr;
1787 }
1788
1789 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1790 {
1791     CharDriverState *chr;
1792     WinCharState *s;
1793
1794     chr = g_malloc0(sizeof(CharDriverState));
1795     s = g_malloc0(sizeof(WinCharState));
1796     s->hcom = fd_out;
1797     chr->opaque = s;
1798     chr->chr_write = win_chr_write;
1799     qemu_chr_generic_open(chr);
1800     return chr;
1801 }
1802
1803 static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
1804 {
1805     return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1806 }
1807
1808 static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
1809 {
1810     const char *file_out = qemu_opt_get(opts, "path");
1811     HANDLE fd_out;
1812
1813 #ifndef CONFIG_MARU
1814     fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1815                         OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1816 #else
1817         int open_flags = O_BINARY | O_RDWR | O_CREAT | O_TRUNC;
1818
1819         int ret = qemu_open(file_out, open_flags, 0644);
1820         if (ret < 0) {
1821                 error_report("qemu_chr_open_win_file_out failed(%d) \n", ret);
1822                 return -errno;
1823         }
1824         fd_out = (HANDLE)_get_osfhandle(ret);
1825
1826 #endif
1827
1828     if (fd_out == INVALID_HANDLE_VALUE) {
1829         return NULL;
1830     }
1831
1832     return qemu_chr_open_win_file(fd_out);
1833 }
1834
1835 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1836 {
1837     HANDLE  hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1838     DWORD   dwSize;
1839     int     len1;
1840
1841     len1 = len;
1842
1843     while (len1 > 0) {
1844         if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
1845             break;
1846         }
1847         buf  += dwSize;
1848         len1 -= dwSize;
1849     }
1850
1851     return len - len1;
1852 }
1853
1854 static void win_stdio_wait_func(void *opaque)
1855 {
1856     CharDriverState   *chr   = opaque;
1857     WinStdioCharState *stdio = chr->opaque;
1858     INPUT_RECORD       buf[4];
1859     int                ret;
1860     DWORD              dwSize;
1861     int                i;
1862
1863     ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
1864                            &dwSize);
1865
1866     if (!ret) {
1867         /* Avoid error storm */
1868         qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
1869         return;
1870     }
1871
1872     for (i = 0; i < dwSize; i++) {
1873         KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
1874
1875         if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
1876             int j;
1877             if (kev->uChar.AsciiChar != 0) {
1878                 for (j = 0; j < kev->wRepeatCount; j++) {
1879                     if (qemu_chr_be_can_write(chr)) {
1880                         uint8_t c = kev->uChar.AsciiChar;
1881                         qemu_chr_be_write(chr, &c, 1);
1882                     }
1883                 }
1884             }
1885         }
1886     }
1887 }
1888
1889 static DWORD WINAPI win_stdio_thread(LPVOID param)
1890 {
1891     CharDriverState   *chr   = param;
1892     WinStdioCharState *stdio = chr->opaque;
1893     int                ret;
1894     DWORD              dwSize;
1895
1896     while (1) {
1897
1898         /* Wait for one byte */
1899         ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
1900
1901         /* Exit in case of error, continue if nothing read */
1902         if (!ret) {
1903             break;
1904         }
1905         if (!dwSize) {
1906             continue;
1907         }
1908
1909         /* Some terminal emulator returns \r\n for Enter, just pass \n */
1910         if (stdio->win_stdio_buf == '\r') {
1911             continue;
1912         }
1913
1914         /* Signal the main thread and wait until the byte was eaten */
1915         if (!SetEvent(stdio->hInputReadyEvent)) {
1916             break;
1917         }
1918         if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
1919             != WAIT_OBJECT_0) {
1920             break;
1921         }
1922     }
1923
1924     qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
1925     return 0;
1926 }
1927
1928 static void win_stdio_thread_wait_func(void *opaque)
1929 {
1930     CharDriverState   *chr   = opaque;
1931     WinStdioCharState *stdio = chr->opaque;
1932
1933     if (qemu_chr_be_can_write(chr)) {
1934         qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
1935     }
1936
1937     SetEvent(stdio->hInputDoneEvent);
1938 }
1939
1940 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
1941 {
1942     WinStdioCharState *stdio  = chr->opaque;
1943     DWORD              dwMode = 0;
1944
1945     GetConsoleMode(stdio->hStdIn, &dwMode);
1946
1947     if (echo) {
1948         SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
1949     } else {
1950         SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
1951     }
1952 }
1953
1954 static void win_stdio_close(CharDriverState *chr)
1955 {
1956     WinStdioCharState *stdio = chr->opaque;
1957
1958     if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
1959         CloseHandle(stdio->hInputReadyEvent);
1960     }
1961     if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
1962         CloseHandle(stdio->hInputDoneEvent);
1963     }
1964     if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
1965         TerminateThread(stdio->hInputThread, 0);
1966     }
1967
1968     g_free(chr->opaque);
1969     g_free(chr);
1970     stdio_nb_clients--;
1971 }
1972
1973 static CharDriverState *qemu_chr_open_win_stdio(QemuOpts *opts)
1974 {
1975     CharDriverState   *chr;
1976     WinStdioCharState *stdio;
1977     DWORD              dwMode;
1978     int                is_console = 0;
1979
1980     if (stdio_nb_clients >= STDIO_MAX_CLIENTS
1981         || ((display_type != DT_NOGRAPHIC) && (stdio_nb_clients != 0))) {
1982         return NULL;
1983     }
1984
1985     chr   = g_malloc0(sizeof(CharDriverState));
1986     stdio = g_malloc0(sizeof(WinStdioCharState));
1987
1988     stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
1989     if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
1990         fprintf(stderr, "cannot open stdio: invalid handle\n");
1991         exit(1);
1992     }
1993
1994     is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
1995
1996     chr->opaque    = stdio;
1997     chr->chr_write = win_stdio_write;
1998     chr->chr_close = win_stdio_close;
1999
2000     if (stdio_nb_clients == 0) {
2001         if (is_console) {
2002             if (qemu_add_wait_object(stdio->hStdIn,
2003                                      win_stdio_wait_func, chr)) {
2004                 fprintf(stderr, "qemu_add_wait_object: failed\n");
2005             }
2006         } else {
2007             DWORD   dwId;
2008
2009             stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2010             stdio->hInputDoneEvent  = CreateEvent(NULL, FALSE, FALSE, NULL);
2011             stdio->hInputThread     = CreateThread(NULL, 0, win_stdio_thread,
2012                                             chr, 0, &dwId);
2013
2014             if (stdio->hInputThread == INVALID_HANDLE_VALUE
2015                 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2016                 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2017                 fprintf(stderr, "cannot create stdio thread or event\n");
2018                 exit(1);
2019             }
2020             if (qemu_add_wait_object(stdio->hInputReadyEvent,
2021                                      win_stdio_thread_wait_func, chr)) {
2022                 fprintf(stderr, "qemu_add_wait_object: failed\n");
2023             }
2024         }
2025     }
2026
2027     dwMode |= ENABLE_LINE_INPUT;
2028
2029     stdio_clients[stdio_nb_clients++] = chr;
2030     if (stdio_nb_clients == 1 && is_console) {
2031         /* set the terminal in raw mode */
2032         /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2033         dwMode |= ENABLE_PROCESSED_INPUT;
2034     }
2035
2036     SetConsoleMode(stdio->hStdIn, dwMode);
2037
2038     chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2039     qemu_chr_fe_set_echo(chr, false);
2040
2041     return chr;
2042 }
2043 #endif /* !_WIN32 */
2044
2045 /***********************************************************/
2046 /* UDP Net console */
2047
2048 typedef struct {
2049     int fd;
2050     uint8_t buf[READ_BUF_LEN];
2051     int bufcnt;
2052     int bufptr;
2053     int max_size;
2054 } NetCharDriver;
2055
2056 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2057 {
2058     NetCharDriver *s = chr->opaque;
2059
2060     return send(s->fd, (const void *)buf, len, 0);
2061 }
2062
2063 static int udp_chr_read_poll(void *opaque)
2064 {
2065     CharDriverState *chr = opaque;
2066     NetCharDriver *s = chr->opaque;
2067
2068     s->max_size = qemu_chr_be_can_write(chr);
2069
2070     /* If there were any stray characters in the queue process them
2071      * first
2072      */
2073     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2074         qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2075         s->bufptr++;
2076         s->max_size = qemu_chr_be_can_write(chr);
2077     }
2078     return s->max_size;
2079 }
2080
2081 static void udp_chr_read(void *opaque)
2082 {
2083     CharDriverState *chr = opaque;
2084     NetCharDriver *s = chr->opaque;
2085
2086     if (s->max_size == 0)
2087         return;
2088     s->bufcnt = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
2089     s->bufptr = s->bufcnt;
2090     if (s->bufcnt <= 0)
2091         return;
2092
2093     s->bufptr = 0;
2094     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2095         qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2096         s->bufptr++;
2097         s->max_size = qemu_chr_be_can_write(chr);
2098     }
2099 }
2100
2101 static void udp_chr_update_read_handler(CharDriverState *chr)
2102 {
2103     NetCharDriver *s = chr->opaque;
2104
2105     if (s->fd >= 0) {
2106         qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2107                              udp_chr_read, NULL, chr);
2108     }
2109 }
2110
2111 static void udp_chr_close(CharDriverState *chr)
2112 {
2113     NetCharDriver *s = chr->opaque;
2114     if (s->fd >= 0) {
2115         qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2116         closesocket(s->fd);
2117     }
2118     g_free(s);
2119     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2120 }
2121
2122 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2123 {
2124     CharDriverState *chr = NULL;
2125     NetCharDriver *s = NULL;
2126     int fd = -1;
2127
2128     chr = g_malloc0(sizeof(CharDriverState));
2129     s = g_malloc0(sizeof(NetCharDriver));
2130
2131     fd = inet_dgram_opts(opts);
2132     if (fd < 0) {
2133         fprintf(stderr, "inet_dgram_opts failed\n");
2134         goto return_err;
2135     }
2136
2137     s->fd = fd;
2138     s->bufcnt = 0;
2139     s->bufptr = 0;
2140     chr->opaque = s;
2141     chr->chr_write = udp_chr_write;
2142     chr->chr_update_read_handler = udp_chr_update_read_handler;
2143     chr->chr_close = udp_chr_close;
2144     return chr;
2145
2146 return_err:
2147     g_free(chr);
2148     g_free(s);
2149     if (fd >= 0) {
2150         closesocket(fd);
2151     }
2152     return NULL;
2153 }
2154
2155 /***********************************************************/
2156 /* TCP Net console */
2157
2158 typedef struct {
2159     int fd, listen_fd;
2160     int connected;
2161     int max_size;
2162     int do_telnetopt;
2163     int do_nodelay;
2164     int is_unix;
2165     int msgfd;
2166 } TCPCharDriver;
2167
2168 static void tcp_chr_accept(void *opaque);
2169
2170 static void tcp_chr_connect(void *opaque);
2171
2172 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2173 {
2174     TCPCharDriver *s = chr->opaque;
2175     if (s->connected) {
2176         return send_all(s->fd, buf, len);
2177     } else {
2178         /* (Re-)connect for unconnected writing */
2179         tcp_chr_connect(chr);
2180         return 0;
2181     }
2182 }
2183
2184 static int tcp_chr_read_poll(void *opaque)
2185 {
2186     CharDriverState *chr = opaque;
2187     TCPCharDriver *s = chr->opaque;
2188     if (!s->connected)
2189         return 0;
2190     s->max_size = qemu_chr_be_can_write(chr);
2191     return s->max_size;
2192 }
2193
2194 #define IAC 255
2195 #define IAC_BREAK 243
2196 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2197                                       TCPCharDriver *s,
2198                                       uint8_t *buf, int *size)
2199 {
2200     /* Handle any telnet client's basic IAC options to satisfy char by
2201      * char mode with no echo.  All IAC options will be removed from
2202      * the buf and the do_telnetopt variable will be used to track the
2203      * state of the width of the IAC information.
2204      *
2205      * IAC commands come in sets of 3 bytes with the exception of the
2206      * "IAC BREAK" command and the double IAC.
2207      */
2208
2209     int i;
2210     int j = 0;
2211
2212     for (i = 0; i < *size; i++) {
2213         if (s->do_telnetopt > 1) {
2214             if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2215                 /* Double IAC means send an IAC */
2216                 if (j != i)
2217                     buf[j] = buf[i];
2218                 j++;
2219                 s->do_telnetopt = 1;
2220             } else {
2221                 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2222                     /* Handle IAC break commands by sending a serial break */
2223                     qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2224                     s->do_telnetopt++;
2225                 }
2226                 s->do_telnetopt++;
2227             }
2228             if (s->do_telnetopt >= 4) {
2229                 s->do_telnetopt = 1;
2230             }
2231         } else {
2232             if ((unsigned char)buf[i] == IAC) {
2233                 s->do_telnetopt = 2;
2234             } else {
2235                 if (j != i)
2236                     buf[j] = buf[i];
2237                 j++;
2238             }
2239         }
2240     }
2241     *size = j;
2242 }
2243
2244 static int tcp_get_msgfd(CharDriverState *chr)
2245 {
2246     TCPCharDriver *s = chr->opaque;
2247     int fd = s->msgfd;
2248     s->msgfd = -1;
2249     return fd;
2250 }
2251
2252 #ifndef _WIN32
2253 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2254 {
2255     TCPCharDriver *s = chr->opaque;
2256     struct cmsghdr *cmsg;
2257
2258     for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2259         int fd;
2260
2261         if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2262             cmsg->cmsg_level != SOL_SOCKET ||
2263             cmsg->cmsg_type != SCM_RIGHTS)
2264             continue;
2265
2266         fd = *((int *)CMSG_DATA(cmsg));
2267         if (fd < 0)
2268             continue;
2269
2270 #ifndef MSG_CMSG_CLOEXEC
2271         qemu_set_cloexec(fd);
2272 #endif
2273         if (s->msgfd != -1)
2274             close(s->msgfd);
2275         s->msgfd = fd;
2276     }
2277 }
2278
2279 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2280 {
2281     TCPCharDriver *s = chr->opaque;
2282     struct msghdr msg = { NULL, };
2283     struct iovec iov[1];
2284     union {
2285         struct cmsghdr cmsg;
2286         char control[CMSG_SPACE(sizeof(int))];
2287     } msg_control;
2288     int flags = 0;
2289     ssize_t ret;
2290
2291     iov[0].iov_base = buf;
2292     iov[0].iov_len = len;
2293
2294     msg.msg_iov = iov;
2295     msg.msg_iovlen = 1;
2296     msg.msg_control = &msg_control;
2297     msg.msg_controllen = sizeof(msg_control);
2298
2299 #ifdef MSG_CMSG_CLOEXEC
2300     flags |= MSG_CMSG_CLOEXEC;
2301 #endif
2302     ret = recvmsg(s->fd, &msg, flags);
2303     if (ret > 0 && s->is_unix) {
2304         unix_process_msgfd(chr, &msg);
2305     }
2306
2307     return ret;
2308 }
2309 #else
2310 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2311 {
2312     TCPCharDriver *s = chr->opaque;
2313     return qemu_recv(s->fd, buf, len, 0);
2314 }
2315 #endif
2316
2317 static void tcp_chr_read(void *opaque)
2318 {
2319     CharDriverState *chr = opaque;
2320     TCPCharDriver *s = chr->opaque;
2321     uint8_t buf[READ_BUF_LEN];
2322     int len, size;
2323
2324     if (!s->connected || s->max_size <= 0)
2325         return;
2326     len = sizeof(buf);
2327     if (len > s->max_size)
2328         len = s->max_size;
2329     size = tcp_chr_recv(chr, (void *)buf, len);
2330     if (size == 0) {
2331         /* connection closed */
2332         s->connected = 0;
2333         if (s->listen_fd >= 0) {
2334             qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2335         }
2336         qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2337         closesocket(s->fd);
2338         s->fd = -1;
2339         qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2340     } else if (size > 0) {
2341         if (s->do_telnetopt)
2342             tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2343         if (size > 0)
2344             qemu_chr_be_write(chr, buf, size);
2345     }
2346 }
2347
2348 #ifndef _WIN32
2349 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2350 {
2351     return qemu_chr_open_fd(eventfd, eventfd);
2352 }
2353 #endif
2354
2355 static void tcp_chr_connect(void *opaque)
2356 {
2357     CharDriverState *chr = opaque;
2358     TCPCharDriver *s = chr->opaque;
2359
2360     s->connected = 1;
2361     qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2362                          tcp_chr_read, NULL, chr);
2363     qemu_chr_generic_open(chr);
2364 }
2365
2366 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2367 static void tcp_chr_telnet_init(int fd)
2368 {
2369     char buf[3];
2370     /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2371     IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2372     send(fd, (char *)buf, 3, 0);
2373     IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2374     send(fd, (char *)buf, 3, 0);
2375     IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2376     send(fd, (char *)buf, 3, 0);
2377     IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2378     send(fd, (char *)buf, 3, 0);
2379 }
2380
2381 static void socket_set_nodelay(int fd)
2382 {
2383     int val = 1;
2384     setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2385 }
2386
2387 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2388 {
2389     TCPCharDriver *s = chr->opaque;
2390     if (s->fd != -1)
2391         return -1;
2392
2393     socket_set_nonblock(fd);
2394     if (s->do_nodelay)
2395         socket_set_nodelay(fd);
2396     s->fd = fd;
2397     qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2398     tcp_chr_connect(chr);
2399
2400     return 0;
2401 }
2402
2403 static void tcp_chr_accept(void *opaque)
2404 {
2405     CharDriverState *chr = opaque;
2406     TCPCharDriver *s = chr->opaque;
2407     struct sockaddr_in saddr;
2408 #ifndef _WIN32
2409     struct sockaddr_un uaddr;
2410 #endif
2411     struct sockaddr *addr;
2412     socklen_t len;
2413     int fd;
2414
2415     for(;;) {
2416 #ifndef _WIN32
2417         if (s->is_unix) {
2418             len = sizeof(uaddr);
2419             addr = (struct sockaddr *)&uaddr;
2420         } else
2421 #endif
2422         {
2423             len = sizeof(saddr);
2424             addr = (struct sockaddr *)&saddr;
2425         }
2426         fd = qemu_accept(s->listen_fd, addr, &len);
2427         if (fd < 0 && errno != EINTR) {
2428             return;
2429         } else if (fd >= 0) {
2430             if (s->do_telnetopt)
2431                 tcp_chr_telnet_init(fd);
2432             break;
2433         }
2434     }
2435     if (tcp_chr_add_client(chr, fd) < 0)
2436         close(fd);
2437 }
2438
2439 static void tcp_chr_close(CharDriverState *chr)
2440 {
2441     TCPCharDriver *s = chr->opaque;
2442     if (s->fd >= 0) {
2443         qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2444         closesocket(s->fd);
2445     }
2446     if (s->listen_fd >= 0) {
2447         qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2448         closesocket(s->listen_fd);
2449     }
2450     g_free(s);
2451     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2452 }
2453
2454 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2455 {
2456     CharDriverState *chr = NULL;
2457     TCPCharDriver *s = NULL;
2458     int fd = -1;
2459     int is_listen;
2460     int is_waitconnect;
2461     int do_nodelay;
2462     int is_unix;
2463     int is_telnet;
2464
2465     is_listen      = qemu_opt_get_bool(opts, "server", 0);
2466     is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2467     is_telnet      = qemu_opt_get_bool(opts, "telnet", 0);
2468     do_nodelay     = !qemu_opt_get_bool(opts, "delay", 1);
2469     is_unix        = qemu_opt_get(opts, "path") != NULL;
2470     if (!is_listen)
2471         is_waitconnect = 0;
2472
2473     chr = g_malloc0(sizeof(CharDriverState));
2474     s = g_malloc0(sizeof(TCPCharDriver));
2475
2476     if (is_unix) {
2477         if (is_listen) {
2478             fd = unix_listen_opts(opts);
2479         } else {
2480             fd = unix_connect_opts(opts);
2481         }
2482     } else {
2483         if (is_listen) {
2484             fd = inet_listen_opts(opts, 0, NULL);
2485         } else {
2486             fd = inet_connect_opts(opts, NULL, NULL);
2487         }
2488     }
2489     if (fd < 0) {
2490         goto fail;
2491     }
2492
2493     if (!is_waitconnect)
2494         socket_set_nonblock(fd);
2495
2496     s->connected = 0;
2497     s->fd = -1;
2498     s->listen_fd = -1;
2499     s->msgfd = -1;
2500     s->is_unix = is_unix;
2501     s->do_nodelay = do_nodelay && !is_unix;
2502
2503     chr->opaque = s;
2504     chr->chr_write = tcp_chr_write;
2505     chr->chr_close = tcp_chr_close;
2506     chr->get_msgfd = tcp_get_msgfd;
2507     chr->chr_add_client = tcp_chr_add_client;
2508
2509     if (is_listen) {
2510         s->listen_fd = fd;
2511         qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2512         if (is_telnet)
2513             s->do_telnetopt = 1;
2514
2515     } else {
2516         s->connected = 1;
2517         s->fd = fd;
2518         socket_set_nodelay(fd);
2519         tcp_chr_connect(chr);
2520     }
2521
2522     /* for "info chardev" monitor command */
2523     chr->filename = g_malloc(256);
2524     if (is_unix) {
2525         snprintf(chr->filename, 256, "unix:%s%s",
2526                  qemu_opt_get(opts, "path"),
2527                  qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2528     } else if (is_telnet) {
2529         snprintf(chr->filename, 256, "telnet:%s:%s%s",
2530                  qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2531                  qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2532     } else {
2533         snprintf(chr->filename, 256, "tcp:%s:%s%s",
2534                  qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2535                  qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2536     }
2537
2538     if (is_listen && is_waitconnect) {
2539         printf("QEMU waiting for connection on: %s\n",
2540                chr->filename);
2541         tcp_chr_accept(chr);
2542         socket_set_nonblock(s->listen_fd);
2543     }
2544     return chr;
2545
2546  fail:
2547     if (fd >= 0)
2548         closesocket(fd);
2549     g_free(s);
2550     g_free(chr);
2551     return NULL;
2552 }
2553
2554 /***********************************************************/
2555 /* Memory chardev */
2556 typedef struct {
2557     size_t outbuf_size;
2558     size_t outbuf_capacity;
2559     uint8_t *outbuf;
2560 } MemoryDriver;
2561
2562 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2563 {
2564     MemoryDriver *d = chr->opaque;
2565
2566     /* TODO: the QString implementation has the same code, we should
2567      * introduce a generic way to do this in cutils.c */
2568     if (d->outbuf_capacity < d->outbuf_size + len) {
2569         /* grow outbuf */
2570         d->outbuf_capacity += len;
2571         d->outbuf_capacity *= 2;
2572         d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
2573     }
2574
2575     memcpy(d->outbuf + d->outbuf_size, buf, len);
2576     d->outbuf_size += len;
2577
2578     return len;
2579 }
2580
2581 void qemu_chr_init_mem(CharDriverState *chr)
2582 {
2583     MemoryDriver *d;
2584
2585     d = g_malloc(sizeof(*d));
2586     d->outbuf_size = 0;
2587     d->outbuf_capacity = 4096;
2588     d->outbuf = g_malloc0(d->outbuf_capacity);
2589
2590     memset(chr, 0, sizeof(*chr));
2591     chr->opaque = d;
2592     chr->chr_write = mem_chr_write;
2593 }
2594
2595 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2596 {
2597     MemoryDriver *d = chr->opaque;
2598     return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2599 }
2600
2601 /* NOTE: this driver can not be closed with qemu_chr_delete()! */
2602 void qemu_chr_close_mem(CharDriverState *chr)
2603 {
2604     MemoryDriver *d = chr->opaque;
2605
2606     g_free(d->outbuf);
2607     g_free(chr->opaque);
2608     chr->opaque = NULL;
2609     chr->chr_write = NULL;
2610 }
2611
2612 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2613 {
2614     const MemoryDriver *d = chr->opaque;
2615     return d->outbuf_size;
2616 }
2617
2618 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2619 {
2620     char host[65], port[33], width[8], height[8];
2621     int pos;
2622     const char *p;
2623     QemuOpts *opts;
2624     Error *local_err = NULL;
2625
2626     opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
2627     if (error_is_set(&local_err)) {
2628         qerror_report_err(local_err);
2629         error_free(local_err);
2630         return NULL;
2631     }
2632
2633     if (strstart(filename, "mon:", &p)) {
2634         filename = p;
2635         qemu_opt_set(opts, "mux", "on");
2636     }
2637
2638     if (strcmp(filename, "null")    == 0 ||
2639         strcmp(filename, "pty")     == 0 ||
2640         strcmp(filename, "msmouse") == 0 ||
2641         strcmp(filename, "braille") == 0 ||
2642         strcmp(filename, "stdio")   == 0) {
2643         qemu_opt_set(opts, "backend", filename);
2644         return opts;
2645     }
2646     if (strstart(filename, "vc", &p)) {
2647         qemu_opt_set(opts, "backend", "vc");
2648         if (*p == ':') {
2649             if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2650                 /* pixels */
2651                 qemu_opt_set(opts, "width", width);
2652                 qemu_opt_set(opts, "height", height);
2653             } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2654                 /* chars */
2655                 qemu_opt_set(opts, "cols", width);
2656                 qemu_opt_set(opts, "rows", height);
2657             } else {
2658                 goto fail;
2659             }
2660         }
2661         return opts;
2662     }
2663     if (strcmp(filename, "con:") == 0) {
2664         qemu_opt_set(opts, "backend", "console");
2665         return opts;
2666     }
2667     if (strstart(filename, "COM", NULL)) {
2668         qemu_opt_set(opts, "backend", "serial");
2669         qemu_opt_set(opts, "path", filename);
2670         return opts;
2671     }
2672     if (strstart(filename, "file:", &p)) {
2673         qemu_opt_set(opts, "backend", "file");
2674         qemu_opt_set(opts, "path", p);
2675         return opts;
2676     }
2677     if (strstart(filename, "pipe:", &p)) {
2678         qemu_opt_set(opts, "backend", "pipe");
2679         qemu_opt_set(opts, "path", p);
2680         return opts;
2681     }
2682     if (strstart(filename, "tcp:", &p) ||
2683         strstart(filename, "telnet:", &p)) {
2684         if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2685             host[0] = 0;
2686             if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2687                 goto fail;
2688         }
2689         qemu_opt_set(opts, "backend", "socket");
2690         qemu_opt_set(opts, "host", host);
2691         qemu_opt_set(opts, "port", port);
2692         if (p[pos] == ',') {
2693             if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2694                 goto fail;
2695         }
2696         if (strstart(filename, "telnet:", &p))
2697             qemu_opt_set(opts, "telnet", "on");
2698         return opts;
2699     }
2700     if (strstart(filename, "udp:", &p)) {
2701         qemu_opt_set(opts, "backend", "udp");
2702         if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2703             host[0] = 0;
2704             if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
2705                 goto fail;
2706             }
2707         }
2708         qemu_opt_set(opts, "host", host);
2709         qemu_opt_set(opts, "port", port);
2710         if (p[pos] == '@') {
2711             p += pos + 1;
2712             if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2713                 host[0] = 0;
2714                 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2715                     goto fail;
2716                 }
2717             }
2718             qemu_opt_set(opts, "localaddr", host);
2719             qemu_opt_set(opts, "localport", port);
2720         }
2721         return opts;
2722     }
2723     if (strstart(filename, "unix:", &p)) {
2724         qemu_opt_set(opts, "backend", "socket");
2725         if (qemu_opts_do_parse(opts, p, "path") != 0)
2726             goto fail;
2727         return opts;
2728     }
2729     if (strstart(filename, "/dev/parport", NULL) ||
2730         strstart(filename, "/dev/ppi", NULL)) {
2731         qemu_opt_set(opts, "backend", "parport");
2732         qemu_opt_set(opts, "path", filename);
2733         return opts;
2734     }
2735     if (strstart(filename, "/dev/", NULL)) {
2736         qemu_opt_set(opts, "backend", "tty");
2737         qemu_opt_set(opts, "path", filename);
2738         return opts;
2739     }
2740
2741 fail:
2742     qemu_opts_del(opts);
2743     return NULL;
2744 }
2745
2746 static const struct {
2747     const char *name;
2748     CharDriverState *(*open)(QemuOpts *opts);
2749 } backend_table[] = {
2750     { .name = "null",      .open = qemu_chr_open_null },
2751     { .name = "socket",    .open = qemu_chr_open_socket },
2752     { .name = "udp",       .open = qemu_chr_open_udp },
2753     { .name = "msmouse",   .open = qemu_chr_open_msmouse },
2754     { .name = "vc",        .open = text_console_init },
2755 #ifdef _WIN32
2756     { .name = "file",      .open = qemu_chr_open_win_file_out },
2757     { .name = "pipe",      .open = qemu_chr_open_win_pipe },
2758     { .name = "console",   .open = qemu_chr_open_win_con },
2759     { .name = "serial",    .open = qemu_chr_open_win },
2760     { .name = "stdio",     .open = qemu_chr_open_win_stdio },
2761 #else
2762     { .name = "file",      .open = qemu_chr_open_file_out },
2763     { .name = "pipe",      .open = qemu_chr_open_pipe },
2764     { .name = "pty",       .open = qemu_chr_open_pty },
2765     { .name = "stdio",     .open = qemu_chr_open_stdio },
2766 #endif
2767 #ifdef CONFIG_BRLAPI
2768     { .name = "braille",   .open = chr_baum_init },
2769 #endif
2770 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2771     || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
2772     || defined(__FreeBSD_kernel__)
2773     { .name = "tty",       .open = qemu_chr_open_tty },
2774 #endif
2775 #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) \
2776     || defined(__FreeBSD_kernel__)
2777     { .name = "parport",   .open = qemu_chr_open_pp },
2778 #endif
2779 #ifdef CONFIG_SPICE
2780     { .name = "spicevmc",     .open = qemu_chr_open_spice },
2781 #endif
2782 };
2783
2784 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
2785                                     void (*init)(struct CharDriverState *s))
2786 {
2787     CharDriverState *chr;
2788     int i;
2789
2790     if (qemu_opts_id(opts) == NULL) {
2791         fprintf(stderr, "chardev: no id specified\n");
2792         return NULL;
2793     }
2794
2795     if (qemu_opt_get(opts, "backend") == NULL) {
2796         fprintf(stderr, "chardev: \"%s\" missing backend\n",
2797                 qemu_opts_id(opts));
2798         return NULL;
2799     }
2800     for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
2801         if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
2802             break;
2803     }
2804     if (i == ARRAY_SIZE(backend_table)) {
2805         fprintf(stderr, "chardev: backend \"%s\" not found\n",
2806                 qemu_opt_get(opts, "backend"));
2807         return NULL;
2808     }
2809
2810     chr = backend_table[i].open(opts);
2811     if (!chr) {
2812         fprintf(stderr, "chardev: opening backend \"%s\" failed\n",
2813                 qemu_opt_get(opts, "backend"));
2814         return NULL;
2815     }
2816
2817     if (!chr->filename)
2818         chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
2819     chr->init = init;
2820     QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2821
2822     if (qemu_opt_get_bool(opts, "mux", 0)) {
2823         CharDriverState *base = chr;
2824         int len = strlen(qemu_opts_id(opts)) + 6;
2825         base->label = g_malloc(len);
2826         snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
2827         chr = qemu_chr_open_mux(base);
2828         chr->filename = base->filename;
2829         chr->avail_connections = MAX_MUX;
2830         QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2831     } else {
2832         chr->avail_connections = 1;
2833     }
2834     chr->label = g_strdup(qemu_opts_id(opts));
2835     return chr;
2836 }
2837
2838 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2839 {
2840     const char *p;
2841     CharDriverState *chr;
2842     QemuOpts *opts;
2843
2844     if (strstart(filename, "chardev:", &p)) {
2845         return qemu_chr_find(p);
2846     }
2847
2848     opts = qemu_chr_parse_compat(label, filename);
2849     if (!opts)
2850         return NULL;
2851
2852     chr = qemu_chr_new_from_opts(opts, init);
2853     if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
2854         monitor_init(chr, MONITOR_USE_READLINE);
2855     }
2856     qemu_opts_del(opts);
2857     return chr;
2858 }
2859
2860 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
2861 {
2862     if (chr->chr_set_echo) {
2863         chr->chr_set_echo(chr, echo);
2864     }
2865 }
2866
2867 void qemu_chr_fe_open(struct CharDriverState *chr)
2868 {
2869     if (chr->chr_guest_open) {
2870         chr->chr_guest_open(chr);
2871     }
2872 }
2873
2874 void qemu_chr_fe_close(struct CharDriverState *chr)
2875 {
2876     if (chr->chr_guest_close) {
2877         chr->chr_guest_close(chr);
2878     }
2879 }
2880
2881 void qemu_chr_delete(CharDriverState *chr)
2882 {
2883     QTAILQ_REMOVE(&chardevs, chr, next);
2884     if (chr->chr_close)
2885         chr->chr_close(chr);
2886     g_free(chr->filename);
2887     g_free(chr->label);
2888     g_free(chr);
2889 }
2890
2891 ChardevInfoList *qmp_query_chardev(Error **errp)
2892 {
2893     ChardevInfoList *chr_list = NULL;
2894     CharDriverState *chr;
2895
2896     QTAILQ_FOREACH(chr, &chardevs, next) {
2897         ChardevInfoList *info = g_malloc0(sizeof(*info));
2898         info->value = g_malloc0(sizeof(*info->value));
2899         info->value->label = g_strdup(chr->label);
2900         info->value->filename = g_strdup(chr->filename);
2901
2902         info->next = chr_list;
2903         chr_list = info;
2904     }
2905
2906     return chr_list;
2907 }
2908
2909 CharDriverState *qemu_chr_find(const char *name)
2910 {
2911     CharDriverState *chr;
2912
2913     QTAILQ_FOREACH(chr, &chardevs, next) {
2914         if (strcmp(chr->label, name) != 0)
2915             continue;
2916         return chr;
2917     }
2918     return NULL;
2919 }
2920
2921 /* Get a character (serial) device interface.  */
2922 CharDriverState *qemu_char_get_next_serial(void)
2923 {
2924     static int next_serial;
2925
2926     /* FIXME: This function needs to go away: use chardev properties!  */
2927     return serial_hds[next_serial++];
2928 }
2929