chardev: add file chardev support to chardev-add (qmp)
[sdk/emulator/qemu.git] / qemu-char.c
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "qemu-common.h"
25 #include "monitor/monitor.h"
26 #include "ui/console.h"
27 #include "sysemu/sysemu.h"
28 #include "qemu/timer.h"
29 #include "char/char.h"
30 #include "hw/usb.h"
31 #include "hw/baum.h"
32 #include "hw/msmouse.h"
33 #include "qmp-commands.h"
34
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <time.h>
38 #include <errno.h>
39 #include <sys/time.h>
40 #include <zlib.h>
41
42 #ifndef _WIN32
43 #include <sys/times.h>
44 #include <sys/wait.h>
45 #include <termios.h>
46 #include <sys/mman.h>
47 #include <sys/ioctl.h>
48 #include <sys/resource.h>
49 #include <sys/socket.h>
50 #include <netinet/in.h>
51 #include <net/if.h>
52 #include <arpa/inet.h>
53 #include <dirent.h>
54 #include <netdb.h>
55 #include <sys/select.h>
56 #ifdef CONFIG_BSD
57 #include <sys/stat.h>
58 #if defined(__GLIBC__)
59 #include <pty.h>
60 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
61 #include <libutil.h>
62 #else
63 #include <util.h>
64 #endif
65 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
66 #include <dev/ppbus/ppi.h>
67 #include <dev/ppbus/ppbconf.h>
68 #elif defined(__DragonFly__)
69 #include <dev/misc/ppi/ppi.h>
70 #include <bus/ppbus/ppbconf.h>
71 #endif
72 #else
73 #ifdef __linux__
74 #include <pty.h>
75
76 #include <linux/ppdev.h>
77 #include <linux/parport.h>
78 #endif
79 #ifdef __sun__
80 #include <sys/stat.h>
81 #include <sys/ethernet.h>
82 #include <sys/sockio.h>
83 #include <netinet/arp.h>
84 #include <netinet/in.h>
85 #include <netinet/in_systm.h>
86 #include <netinet/ip.h>
87 #include <netinet/ip_icmp.h> // must come after ip.h
88 #include <netinet/udp.h>
89 #include <netinet/tcp.h>
90 #include <net/if.h>
91 #include <syslog.h>
92 #include <stropts.h>
93 #endif
94 #endif
95 #endif
96
97 #include "qemu/sockets.h"
98 #include "ui/qemu-spice.h"
99
100 #define READ_BUF_LEN 4096
101
102 /***********************************************************/
103 /* character device */
104
105 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
106     QTAILQ_HEAD_INITIALIZER(chardevs);
107
108 void qemu_chr_be_event(CharDriverState *s, int event)
109 {
110     /* Keep track if the char device is open */
111     switch (event) {
112         case CHR_EVENT_OPENED:
113             s->opened = 1;
114             break;
115         case CHR_EVENT_CLOSED:
116             s->opened = 0;
117             break;
118     }
119
120     if (!s->chr_event)
121         return;
122     s->chr_event(s->handler_opaque, event);
123 }
124
125 static void qemu_chr_fire_open_event(void *opaque)
126 {
127     CharDriverState *s = opaque;
128     qemu_chr_be_event(s, CHR_EVENT_OPENED);
129     qemu_free_timer(s->open_timer);
130     s->open_timer = NULL;
131 }
132
133 void qemu_chr_generic_open(CharDriverState *s)
134 {
135     if (s->open_timer == NULL) {
136         s->open_timer = qemu_new_timer_ms(rt_clock,
137                                           qemu_chr_fire_open_event, s);
138         qemu_mod_timer(s->open_timer, qemu_get_clock_ms(rt_clock) - 1);
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 (is_daemonized()) {
776         error_report("cannot use stdio with -daemonize");
777         return NULL;
778     }
779     if (stdio_nb_clients == 0) {
780         old_fd0_flags = fcntl(0, F_GETFL);
781         tcgetattr (0, &oldtty);
782         fcntl(0, F_SETFL, O_NONBLOCK);
783         atexit(term_exit);
784     }
785
786     chr = qemu_chr_open_fd(0, 1);
787     chr->chr_close = qemu_chr_close_stdio;
788     chr->chr_set_echo = qemu_chr_set_echo_stdio;
789     qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
790     stdio_nb_clients++;
791     stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
792                                            display_type != DT_NOGRAPHIC);
793     qemu_chr_fe_set_echo(chr, false);
794
795     return chr;
796 }
797
798 #ifdef __sun__
799 /* Once Solaris has openpty(), this is going to be removed. */
800 static int openpty(int *amaster, int *aslave, char *name,
801                    struct termios *termp, struct winsize *winp)
802 {
803         const char *slave;
804         int mfd = -1, sfd = -1;
805
806         *amaster = *aslave = -1;
807
808         mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
809         if (mfd < 0)
810                 goto err;
811
812         if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
813                 goto err;
814
815         if ((slave = ptsname(mfd)) == NULL)
816                 goto err;
817
818         if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
819                 goto err;
820
821         if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
822             (termp != NULL && tcgetattr(sfd, termp) < 0))
823                 goto err;
824
825         if (amaster)
826                 *amaster = mfd;
827         if (aslave)
828                 *aslave = sfd;
829         if (winp)
830                 ioctl(sfd, TIOCSWINSZ, winp);
831
832         return 0;
833
834 err:
835         if (sfd != -1)
836                 close(sfd);
837         close(mfd);
838         return -1;
839 }
840
841 static void cfmakeraw (struct termios *termios_p)
842 {
843         termios_p->c_iflag &=
844                 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
845         termios_p->c_oflag &= ~OPOST;
846         termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
847         termios_p->c_cflag &= ~(CSIZE|PARENB);
848         termios_p->c_cflag |= CS8;
849
850         termios_p->c_cc[VMIN] = 0;
851         termios_p->c_cc[VTIME] = 0;
852 }
853 #endif
854
855 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
856     || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
857     || defined(__GLIBC__)
858
859 #define HAVE_CHARDEV_TTY 1
860
861 typedef struct {
862     int fd;
863     int connected;
864     int polling;
865     int read_bytes;
866     QEMUTimer *timer;
867 } PtyCharDriver;
868
869 static void pty_chr_update_read_handler(CharDriverState *chr);
870 static void pty_chr_state(CharDriverState *chr, int connected);
871
872 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
873 {
874     PtyCharDriver *s = chr->opaque;
875
876     if (!s->connected) {
877         /* guest sends data, check for (re-)connect */
878         pty_chr_update_read_handler(chr);
879         return 0;
880     }
881     return send_all(s->fd, buf, len);
882 }
883
884 static int pty_chr_read_poll(void *opaque)
885 {
886     CharDriverState *chr = opaque;
887     PtyCharDriver *s = chr->opaque;
888
889     s->read_bytes = qemu_chr_be_can_write(chr);
890     return s->read_bytes;
891 }
892
893 static void pty_chr_read(void *opaque)
894 {
895     CharDriverState *chr = opaque;
896     PtyCharDriver *s = chr->opaque;
897     int size, len;
898     uint8_t buf[READ_BUF_LEN];
899
900     len = sizeof(buf);
901     if (len > s->read_bytes)
902         len = s->read_bytes;
903     if (len == 0)
904         return;
905     size = read(s->fd, buf, len);
906     if ((size == -1 && errno == EIO) ||
907         (size == 0)) {
908         pty_chr_state(chr, 0);
909         return;
910     }
911     if (size > 0) {
912         pty_chr_state(chr, 1);
913         qemu_chr_be_write(chr, buf, size);
914     }
915 }
916
917 static void pty_chr_update_read_handler(CharDriverState *chr)
918 {
919     PtyCharDriver *s = chr->opaque;
920
921     qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
922                          pty_chr_read, NULL, chr);
923     s->polling = 1;
924     /*
925      * Short timeout here: just need wait long enougth that qemu makes
926      * it through the poll loop once.  When reconnected we want a
927      * short timeout so we notice it almost instantly.  Otherwise
928      * read() gives us -EIO instantly, making pty_chr_state() reset the
929      * timeout to the normal (much longer) poll interval before the
930      * timer triggers.
931      */
932     qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 10);
933 }
934
935 static void pty_chr_state(CharDriverState *chr, int connected)
936 {
937     PtyCharDriver *s = chr->opaque;
938
939     if (!connected) {
940         qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
941         s->connected = 0;
942         s->polling = 0;
943         /* (re-)connect poll interval for idle guests: once per second.
944          * We check more frequently in case the guests sends data to
945          * the virtual device linked to our pty. */
946         qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 1000);
947     } else {
948         if (!s->connected)
949             qemu_chr_generic_open(chr);
950         s->connected = 1;
951     }
952 }
953
954 static void pty_chr_timer(void *opaque)
955 {
956     struct CharDriverState *chr = opaque;
957     PtyCharDriver *s = chr->opaque;
958
959     if (s->connected)
960         return;
961     if (s->polling) {
962         /* If we arrive here without polling being cleared due
963          * read returning -EIO, then we are (re-)connected */
964         pty_chr_state(chr, 1);
965         return;
966     }
967
968     /* Next poll ... */
969     pty_chr_update_read_handler(chr);
970 }
971
972 static void pty_chr_close(struct CharDriverState *chr)
973 {
974     PtyCharDriver *s = chr->opaque;
975
976     qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
977     close(s->fd);
978     qemu_del_timer(s->timer);
979     qemu_free_timer(s->timer);
980     g_free(s);
981     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
982 }
983
984 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
985 {
986     CharDriverState *chr;
987     PtyCharDriver *s;
988     struct termios tty;
989     const char *label;
990     int master_fd, slave_fd, len;
991 #if defined(__OpenBSD__) || defined(__DragonFly__)
992     char pty_name[PATH_MAX];
993 #define q_ptsname(x) pty_name
994 #else
995     char *pty_name = NULL;
996 #define q_ptsname(x) ptsname(x)
997 #endif
998
999     if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1000         return NULL;
1001     }
1002
1003     /* Set raw attributes on the pty. */
1004     tcgetattr(slave_fd, &tty);
1005     cfmakeraw(&tty);
1006     tcsetattr(slave_fd, TCSAFLUSH, &tty);
1007     close(slave_fd);
1008
1009     chr = g_malloc0(sizeof(CharDriverState));
1010
1011     len = strlen(q_ptsname(master_fd)) + 5;
1012     chr->filename = g_malloc(len);
1013     snprintf(chr->filename, len, "pty:%s", q_ptsname(master_fd));
1014     qemu_opt_set(opts, "path", q_ptsname(master_fd));
1015
1016     label = qemu_opts_id(opts);
1017     fprintf(stderr, "char device redirected to %s%s%s%s\n",
1018             q_ptsname(master_fd),
1019             label ? " (label " : "",
1020             label ? label      : "",
1021             label ? ")"        : "");
1022
1023     s = g_malloc0(sizeof(PtyCharDriver));
1024     chr->opaque = s;
1025     chr->chr_write = pty_chr_write;
1026     chr->chr_update_read_handler = pty_chr_update_read_handler;
1027     chr->chr_close = pty_chr_close;
1028
1029     s->fd = master_fd;
1030     s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr);
1031
1032     return chr;
1033 }
1034
1035 static void tty_serial_init(int fd, int speed,
1036                             int parity, int data_bits, int stop_bits)
1037 {
1038     struct termios tty;
1039     speed_t spd;
1040
1041 #if 0
1042     printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1043            speed, parity, data_bits, stop_bits);
1044 #endif
1045     tcgetattr (fd, &tty);
1046
1047 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1048     speed = speed * 10 / 11;
1049     do {
1050         check_speed(50);
1051         check_speed(75);
1052         check_speed(110);
1053         check_speed(134);
1054         check_speed(150);
1055         check_speed(200);
1056         check_speed(300);
1057         check_speed(600);
1058         check_speed(1200);
1059         check_speed(1800);
1060         check_speed(2400);
1061         check_speed(4800);
1062         check_speed(9600);
1063         check_speed(19200);
1064         check_speed(38400);
1065         /* Non-Posix values follow. They may be unsupported on some systems. */
1066         check_speed(57600);
1067         check_speed(115200);
1068 #ifdef B230400
1069         check_speed(230400);
1070 #endif
1071 #ifdef B460800
1072         check_speed(460800);
1073 #endif
1074 #ifdef B500000
1075         check_speed(500000);
1076 #endif
1077 #ifdef B576000
1078         check_speed(576000);
1079 #endif
1080 #ifdef B921600
1081         check_speed(921600);
1082 #endif
1083 #ifdef B1000000
1084         check_speed(1000000);
1085 #endif
1086 #ifdef B1152000
1087         check_speed(1152000);
1088 #endif
1089 #ifdef B1500000
1090         check_speed(1500000);
1091 #endif
1092 #ifdef B2000000
1093         check_speed(2000000);
1094 #endif
1095 #ifdef B2500000
1096         check_speed(2500000);
1097 #endif
1098 #ifdef B3000000
1099         check_speed(3000000);
1100 #endif
1101 #ifdef B3500000
1102         check_speed(3500000);
1103 #endif
1104 #ifdef B4000000
1105         check_speed(4000000);
1106 #endif
1107         spd = B115200;
1108     } while (0);
1109
1110     cfsetispeed(&tty, spd);
1111     cfsetospeed(&tty, spd);
1112
1113     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1114                           |INLCR|IGNCR|ICRNL|IXON);
1115     tty.c_oflag |= OPOST;
1116     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1117     tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1118     switch(data_bits) {
1119     default:
1120     case 8:
1121         tty.c_cflag |= CS8;
1122         break;
1123     case 7:
1124         tty.c_cflag |= CS7;
1125         break;
1126     case 6:
1127         tty.c_cflag |= CS6;
1128         break;
1129     case 5:
1130         tty.c_cflag |= CS5;
1131         break;
1132     }
1133     switch(parity) {
1134     default:
1135     case 'N':
1136         break;
1137     case 'E':
1138         tty.c_cflag |= PARENB;
1139         break;
1140     case 'O':
1141         tty.c_cflag |= PARENB | PARODD;
1142         break;
1143     }
1144     if (stop_bits == 2)
1145         tty.c_cflag |= CSTOPB;
1146
1147     tcsetattr (fd, TCSANOW, &tty);
1148 }
1149
1150 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1151 {
1152     FDCharDriver *s = chr->opaque;
1153
1154     switch(cmd) {
1155     case CHR_IOCTL_SERIAL_SET_PARAMS:
1156         {
1157             QEMUSerialSetParams *ssp = arg;
1158             tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1159                             ssp->data_bits, ssp->stop_bits);
1160         }
1161         break;
1162     case CHR_IOCTL_SERIAL_SET_BREAK:
1163         {
1164             int enable = *(int *)arg;
1165             if (enable)
1166                 tcsendbreak(s->fd_in, 1);
1167         }
1168         break;
1169     case CHR_IOCTL_SERIAL_GET_TIOCM:
1170         {
1171             int sarg = 0;
1172             int *targ = (int *)arg;
1173             ioctl(s->fd_in, TIOCMGET, &sarg);
1174             *targ = 0;
1175             if (sarg & TIOCM_CTS)
1176                 *targ |= CHR_TIOCM_CTS;
1177             if (sarg & TIOCM_CAR)
1178                 *targ |= CHR_TIOCM_CAR;
1179             if (sarg & TIOCM_DSR)
1180                 *targ |= CHR_TIOCM_DSR;
1181             if (sarg & TIOCM_RI)
1182                 *targ |= CHR_TIOCM_RI;
1183             if (sarg & TIOCM_DTR)
1184                 *targ |= CHR_TIOCM_DTR;
1185             if (sarg & TIOCM_RTS)
1186                 *targ |= CHR_TIOCM_RTS;
1187         }
1188         break;
1189     case CHR_IOCTL_SERIAL_SET_TIOCM:
1190         {
1191             int sarg = *(int *)arg;
1192             int targ = 0;
1193             ioctl(s->fd_in, TIOCMGET, &targ);
1194             targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1195                      | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1196             if (sarg & CHR_TIOCM_CTS)
1197                 targ |= TIOCM_CTS;
1198             if (sarg & CHR_TIOCM_CAR)
1199                 targ |= TIOCM_CAR;
1200             if (sarg & CHR_TIOCM_DSR)
1201                 targ |= TIOCM_DSR;
1202             if (sarg & CHR_TIOCM_RI)
1203                 targ |= TIOCM_RI;
1204             if (sarg & CHR_TIOCM_DTR)
1205                 targ |= TIOCM_DTR;
1206             if (sarg & CHR_TIOCM_RTS)
1207                 targ |= TIOCM_RTS;
1208             ioctl(s->fd_in, TIOCMSET, &targ);
1209         }
1210         break;
1211     default:
1212         return -ENOTSUP;
1213     }
1214     return 0;
1215 }
1216
1217 static void qemu_chr_close_tty(CharDriverState *chr)
1218 {
1219     FDCharDriver *s = chr->opaque;
1220     int fd = -1;
1221
1222     if (s) {
1223         fd = s->fd_in;
1224     }
1225
1226     fd_chr_close(chr);
1227
1228     if (fd >= 0) {
1229         close(fd);
1230     }
1231 }
1232
1233 static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
1234 {
1235     const char *filename = qemu_opt_get(opts, "path");
1236     CharDriverState *chr;
1237     int fd;
1238
1239     TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
1240     if (fd < 0) {
1241         return NULL;
1242     }
1243     tty_serial_init(fd, 115200, 'N', 8, 1);
1244     chr = qemu_chr_open_fd(fd, fd);
1245     chr->chr_ioctl = tty_serial_ioctl;
1246     chr->chr_close = qemu_chr_close_tty;
1247     return chr;
1248 }
1249 #endif /* __linux__ || __sun__ */
1250
1251 #if defined(__linux__)
1252
1253 #define HAVE_CHARDEV_PARPORT 1
1254
1255 typedef struct {
1256     int fd;
1257     int mode;
1258 } ParallelCharDriver;
1259
1260 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1261 {
1262     if (s->mode != mode) {
1263         int m = mode;
1264         if (ioctl(s->fd, PPSETMODE, &m) < 0)
1265             return 0;
1266         s->mode = mode;
1267     }
1268     return 1;
1269 }
1270
1271 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1272 {
1273     ParallelCharDriver *drv = chr->opaque;
1274     int fd = drv->fd;
1275     uint8_t b;
1276
1277     switch(cmd) {
1278     case CHR_IOCTL_PP_READ_DATA:
1279         if (ioctl(fd, PPRDATA, &b) < 0)
1280             return -ENOTSUP;
1281         *(uint8_t *)arg = b;
1282         break;
1283     case CHR_IOCTL_PP_WRITE_DATA:
1284         b = *(uint8_t *)arg;
1285         if (ioctl(fd, PPWDATA, &b) < 0)
1286             return -ENOTSUP;
1287         break;
1288     case CHR_IOCTL_PP_READ_CONTROL:
1289         if (ioctl(fd, PPRCONTROL, &b) < 0)
1290             return -ENOTSUP;
1291         /* Linux gives only the lowest bits, and no way to know data
1292            direction! For better compatibility set the fixed upper
1293            bits. */
1294         *(uint8_t *)arg = b | 0xc0;
1295         break;
1296     case CHR_IOCTL_PP_WRITE_CONTROL:
1297         b = *(uint8_t *)arg;
1298         if (ioctl(fd, PPWCONTROL, &b) < 0)
1299             return -ENOTSUP;
1300         break;
1301     case CHR_IOCTL_PP_READ_STATUS:
1302         if (ioctl(fd, PPRSTATUS, &b) < 0)
1303             return -ENOTSUP;
1304         *(uint8_t *)arg = b;
1305         break;
1306     case CHR_IOCTL_PP_DATA_DIR:
1307         if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1308             return -ENOTSUP;
1309         break;
1310     case CHR_IOCTL_PP_EPP_READ_ADDR:
1311         if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1312             struct ParallelIOArg *parg = arg;
1313             int n = read(fd, parg->buffer, parg->count);
1314             if (n != parg->count) {
1315                 return -EIO;
1316             }
1317         }
1318         break;
1319     case CHR_IOCTL_PP_EPP_READ:
1320         if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1321             struct ParallelIOArg *parg = arg;
1322             int n = read(fd, parg->buffer, parg->count);
1323             if (n != parg->count) {
1324                 return -EIO;
1325             }
1326         }
1327         break;
1328     case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1329         if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1330             struct ParallelIOArg *parg = arg;
1331             int n = write(fd, parg->buffer, parg->count);
1332             if (n != parg->count) {
1333                 return -EIO;
1334             }
1335         }
1336         break;
1337     case CHR_IOCTL_PP_EPP_WRITE:
1338         if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1339             struct ParallelIOArg *parg = arg;
1340             int n = write(fd, parg->buffer, parg->count);
1341             if (n != parg->count) {
1342                 return -EIO;
1343             }
1344         }
1345         break;
1346     default:
1347         return -ENOTSUP;
1348     }
1349     return 0;
1350 }
1351
1352 static void pp_close(CharDriverState *chr)
1353 {
1354     ParallelCharDriver *drv = chr->opaque;
1355     int fd = drv->fd;
1356
1357     pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1358     ioctl(fd, PPRELEASE);
1359     close(fd);
1360     g_free(drv);
1361     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1362 }
1363
1364 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1365 {
1366     const char *filename = qemu_opt_get(opts, "path");
1367     CharDriverState *chr;
1368     ParallelCharDriver *drv;
1369     int fd;
1370
1371     TFR(fd = qemu_open(filename, O_RDWR));
1372     if (fd < 0) {
1373         return NULL;
1374     }
1375
1376     if (ioctl(fd, PPCLAIM) < 0) {
1377         close(fd);
1378         return NULL;
1379     }
1380
1381     drv = g_malloc0(sizeof(ParallelCharDriver));
1382     drv->fd = fd;
1383     drv->mode = IEEE1284_MODE_COMPAT;
1384
1385     chr = g_malloc0(sizeof(CharDriverState));
1386     chr->chr_write = null_chr_write;
1387     chr->chr_ioctl = pp_ioctl;
1388     chr->chr_close = pp_close;
1389     chr->opaque = drv;
1390
1391     qemu_chr_generic_open(chr);
1392
1393     return chr;
1394 }
1395 #endif /* __linux__ */
1396
1397 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1398
1399 #define HAVE_CHARDEV_PARPORT 1
1400
1401 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1402 {
1403     int fd = (int)(intptr_t)chr->opaque;
1404     uint8_t b;
1405
1406     switch(cmd) {
1407     case CHR_IOCTL_PP_READ_DATA:
1408         if (ioctl(fd, PPIGDATA, &b) < 0)
1409             return -ENOTSUP;
1410         *(uint8_t *)arg = b;
1411         break;
1412     case CHR_IOCTL_PP_WRITE_DATA:
1413         b = *(uint8_t *)arg;
1414         if (ioctl(fd, PPISDATA, &b) < 0)
1415             return -ENOTSUP;
1416         break;
1417     case CHR_IOCTL_PP_READ_CONTROL:
1418         if (ioctl(fd, PPIGCTRL, &b) < 0)
1419             return -ENOTSUP;
1420         *(uint8_t *)arg = b;
1421         break;
1422     case CHR_IOCTL_PP_WRITE_CONTROL:
1423         b = *(uint8_t *)arg;
1424         if (ioctl(fd, PPISCTRL, &b) < 0)
1425             return -ENOTSUP;
1426         break;
1427     case CHR_IOCTL_PP_READ_STATUS:
1428         if (ioctl(fd, PPIGSTATUS, &b) < 0)
1429             return -ENOTSUP;
1430         *(uint8_t *)arg = b;
1431         break;
1432     default:
1433         return -ENOTSUP;
1434     }
1435     return 0;
1436 }
1437
1438 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1439 {
1440     const char *filename = qemu_opt_get(opts, "path");
1441     CharDriverState *chr;
1442     int fd;
1443
1444     fd = qemu_open(filename, O_RDWR);
1445     if (fd < 0) {
1446         return NULL;
1447     }
1448
1449     chr = g_malloc0(sizeof(CharDriverState));
1450     chr->opaque = (void *)(intptr_t)fd;
1451     chr->chr_write = null_chr_write;
1452     chr->chr_ioctl = pp_ioctl;
1453     return chr;
1454 }
1455 #endif
1456
1457 #else /* _WIN32 */
1458
1459 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1460
1461 typedef struct {
1462     int max_size;
1463     HANDLE hcom, hrecv, hsend;
1464     OVERLAPPED orecv, osend;
1465     BOOL fpipe;
1466     DWORD len;
1467 } WinCharState;
1468
1469 typedef struct {
1470     HANDLE  hStdIn;
1471     HANDLE  hInputReadyEvent;
1472     HANDLE  hInputDoneEvent;
1473     HANDLE  hInputThread;
1474     uint8_t win_stdio_buf;
1475 } WinStdioCharState;
1476
1477 #define NSENDBUF 2048
1478 #define NRECVBUF 2048
1479 #define MAXCONNECT 1
1480 #define NTIMEOUT 5000
1481
1482 static int win_chr_poll(void *opaque);
1483 static int win_chr_pipe_poll(void *opaque);
1484
1485 static void win_chr_close(CharDriverState *chr)
1486 {
1487     WinCharState *s = chr->opaque;
1488
1489     if (s->hsend) {
1490         CloseHandle(s->hsend);
1491         s->hsend = NULL;
1492     }
1493     if (s->hrecv) {
1494         CloseHandle(s->hrecv);
1495         s->hrecv = NULL;
1496     }
1497     if (s->hcom) {
1498         CloseHandle(s->hcom);
1499         s->hcom = NULL;
1500     }
1501     if (s->fpipe)
1502         qemu_del_polling_cb(win_chr_pipe_poll, chr);
1503     else
1504         qemu_del_polling_cb(win_chr_poll, chr);
1505
1506     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1507 }
1508
1509 static int win_chr_init(CharDriverState *chr, const char *filename)
1510 {
1511     WinCharState *s = chr->opaque;
1512     COMMCONFIG comcfg;
1513     COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1514     COMSTAT comstat;
1515     DWORD size;
1516     DWORD err;
1517
1518     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1519     if (!s->hsend) {
1520         fprintf(stderr, "Failed CreateEvent\n");
1521         goto fail;
1522     }
1523     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1524     if (!s->hrecv) {
1525         fprintf(stderr, "Failed CreateEvent\n");
1526         goto fail;
1527     }
1528
1529     s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1530                       OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1531     if (s->hcom == INVALID_HANDLE_VALUE) {
1532         fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1533         s->hcom = NULL;
1534         goto fail;
1535     }
1536
1537     if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1538         fprintf(stderr, "Failed SetupComm\n");
1539         goto fail;
1540     }
1541
1542     ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1543     size = sizeof(COMMCONFIG);
1544     GetDefaultCommConfig(filename, &comcfg, &size);
1545     comcfg.dcb.DCBlength = sizeof(DCB);
1546     CommConfigDialog(filename, NULL, &comcfg);
1547
1548     if (!SetCommState(s->hcom, &comcfg.dcb)) {
1549         fprintf(stderr, "Failed SetCommState\n");
1550         goto fail;
1551     }
1552
1553     if (!SetCommMask(s->hcom, EV_ERR)) {
1554         fprintf(stderr, "Failed SetCommMask\n");
1555         goto fail;
1556     }
1557
1558     cto.ReadIntervalTimeout = MAXDWORD;
1559     if (!SetCommTimeouts(s->hcom, &cto)) {
1560         fprintf(stderr, "Failed SetCommTimeouts\n");
1561         goto fail;
1562     }
1563
1564     if (!ClearCommError(s->hcom, &err, &comstat)) {
1565         fprintf(stderr, "Failed ClearCommError\n");
1566         goto fail;
1567     }
1568     qemu_add_polling_cb(win_chr_poll, chr);
1569     return 0;
1570
1571  fail:
1572     win_chr_close(chr);
1573     return -1;
1574 }
1575
1576 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1577 {
1578     WinCharState *s = chr->opaque;
1579     DWORD len, ret, size, err;
1580
1581     len = len1;
1582     ZeroMemory(&s->osend, sizeof(s->osend));
1583     s->osend.hEvent = s->hsend;
1584     while (len > 0) {
1585         if (s->hsend)
1586             ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1587         else
1588             ret = WriteFile(s->hcom, buf, len, &size, NULL);
1589         if (!ret) {
1590             err = GetLastError();
1591             if (err == ERROR_IO_PENDING) {
1592                 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1593                 if (ret) {
1594                     buf += size;
1595                     len -= size;
1596                 } else {
1597                     break;
1598                 }
1599             } else {
1600                 break;
1601             }
1602         } else {
1603             buf += size;
1604             len -= size;
1605         }
1606     }
1607     return len1 - len;
1608 }
1609
1610 static int win_chr_read_poll(CharDriverState *chr)
1611 {
1612     WinCharState *s = chr->opaque;
1613
1614     s->max_size = qemu_chr_be_can_write(chr);
1615     return s->max_size;
1616 }
1617
1618 static void win_chr_readfile(CharDriverState *chr)
1619 {
1620     WinCharState *s = chr->opaque;
1621     int ret, err;
1622     uint8_t buf[READ_BUF_LEN];
1623     DWORD size;
1624
1625     ZeroMemory(&s->orecv, sizeof(s->orecv));
1626     s->orecv.hEvent = s->hrecv;
1627     ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1628     if (!ret) {
1629         err = GetLastError();
1630         if (err == ERROR_IO_PENDING) {
1631             ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1632         }
1633     }
1634
1635     if (size > 0) {
1636         qemu_chr_be_write(chr, buf, size);
1637     }
1638 }
1639
1640 static void win_chr_read(CharDriverState *chr)
1641 {
1642     WinCharState *s = chr->opaque;
1643
1644     if (s->len > s->max_size)
1645         s->len = s->max_size;
1646     if (s->len == 0)
1647         return;
1648
1649     win_chr_readfile(chr);
1650 }
1651
1652 static int win_chr_poll(void *opaque)
1653 {
1654     CharDriverState *chr = opaque;
1655     WinCharState *s = chr->opaque;
1656     COMSTAT status;
1657     DWORD comerr;
1658
1659     ClearCommError(s->hcom, &comerr, &status);
1660     if (status.cbInQue > 0) {
1661         s->len = status.cbInQue;
1662         win_chr_read_poll(chr);
1663         win_chr_read(chr);
1664         return 1;
1665     }
1666     return 0;
1667 }
1668
1669 static CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1670 {
1671     const char *filename = qemu_opt_get(opts, "path");
1672     CharDriverState *chr;
1673     WinCharState *s;
1674
1675     chr = g_malloc0(sizeof(CharDriverState));
1676     s = g_malloc0(sizeof(WinCharState));
1677     chr->opaque = s;
1678     chr->chr_write = win_chr_write;
1679     chr->chr_close = win_chr_close;
1680
1681     if (win_chr_init(chr, filename) < 0) {
1682         g_free(s);
1683         g_free(chr);
1684         return NULL;
1685     }
1686     qemu_chr_generic_open(chr);
1687     return chr;
1688 }
1689
1690 static int win_chr_pipe_poll(void *opaque)
1691 {
1692     CharDriverState *chr = opaque;
1693     WinCharState *s = chr->opaque;
1694     DWORD size;
1695
1696     PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1697     if (size > 0) {
1698         s->len = size;
1699         win_chr_read_poll(chr);
1700         win_chr_read(chr);
1701         return 1;
1702     }
1703     return 0;
1704 }
1705
1706 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1707 {
1708     WinCharState *s = chr->opaque;
1709     OVERLAPPED ov;
1710     int ret;
1711     DWORD size;
1712     char openname[256];
1713
1714     s->fpipe = TRUE;
1715
1716     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1717     if (!s->hsend) {
1718         fprintf(stderr, "Failed CreateEvent\n");
1719         goto fail;
1720     }
1721     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1722     if (!s->hrecv) {
1723         fprintf(stderr, "Failed CreateEvent\n");
1724         goto fail;
1725     }
1726
1727     snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1728     s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1729                               PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1730                               PIPE_WAIT,
1731                               MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1732     if (s->hcom == INVALID_HANDLE_VALUE) {
1733         fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1734         s->hcom = NULL;
1735         goto fail;
1736     }
1737
1738     ZeroMemory(&ov, sizeof(ov));
1739     ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1740     ret = ConnectNamedPipe(s->hcom, &ov);
1741     if (ret) {
1742         fprintf(stderr, "Failed ConnectNamedPipe\n");
1743         goto fail;
1744     }
1745
1746     ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1747     if (!ret) {
1748         fprintf(stderr, "Failed GetOverlappedResult\n");
1749         if (ov.hEvent) {
1750             CloseHandle(ov.hEvent);
1751             ov.hEvent = NULL;
1752         }
1753         goto fail;
1754     }
1755
1756     if (ov.hEvent) {
1757         CloseHandle(ov.hEvent);
1758         ov.hEvent = NULL;
1759     }
1760     qemu_add_polling_cb(win_chr_pipe_poll, chr);
1761     return 0;
1762
1763  fail:
1764     win_chr_close(chr);
1765     return -1;
1766 }
1767
1768
1769 static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
1770 {
1771     const char *filename = qemu_opt_get(opts, "path");
1772     CharDriverState *chr;
1773     WinCharState *s;
1774
1775     chr = g_malloc0(sizeof(CharDriverState));
1776     s = g_malloc0(sizeof(WinCharState));
1777     chr->opaque = s;
1778     chr->chr_write = win_chr_write;
1779     chr->chr_close = win_chr_close;
1780
1781     if (win_chr_pipe_init(chr, filename) < 0) {
1782         g_free(s);
1783         g_free(chr);
1784         return NULL;
1785     }
1786     qemu_chr_generic_open(chr);
1787     return chr;
1788 }
1789
1790 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1791 {
1792     CharDriverState *chr;
1793     WinCharState *s;
1794
1795     chr = g_malloc0(sizeof(CharDriverState));
1796     s = g_malloc0(sizeof(WinCharState));
1797     s->hcom = fd_out;
1798     chr->opaque = s;
1799     chr->chr_write = win_chr_write;
1800     qemu_chr_generic_open(chr);
1801     return chr;
1802 }
1803
1804 static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
1805 {
1806     return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1807 }
1808
1809 static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
1810 {
1811     const char *file_out = qemu_opt_get(opts, "path");
1812     HANDLE fd_out;
1813
1814     fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1815                         OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1816     if (fd_out == INVALID_HANDLE_VALUE) {
1817         return NULL;
1818     }
1819
1820     return qemu_chr_open_win_file(fd_out);
1821 }
1822
1823 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1824 {
1825     HANDLE  hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1826     DWORD   dwSize;
1827     int     len1;
1828
1829     len1 = len;
1830
1831     while (len1 > 0) {
1832         if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
1833             break;
1834         }
1835         buf  += dwSize;
1836         len1 -= dwSize;
1837     }
1838
1839     return len - len1;
1840 }
1841
1842 static void win_stdio_wait_func(void *opaque)
1843 {
1844     CharDriverState   *chr   = opaque;
1845     WinStdioCharState *stdio = chr->opaque;
1846     INPUT_RECORD       buf[4];
1847     int                ret;
1848     DWORD              dwSize;
1849     int                i;
1850
1851     ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
1852                            &dwSize);
1853
1854     if (!ret) {
1855         /* Avoid error storm */
1856         qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
1857         return;
1858     }
1859
1860     for (i = 0; i < dwSize; i++) {
1861         KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
1862
1863         if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
1864             int j;
1865             if (kev->uChar.AsciiChar != 0) {
1866                 for (j = 0; j < kev->wRepeatCount; j++) {
1867                     if (qemu_chr_be_can_write(chr)) {
1868                         uint8_t c = kev->uChar.AsciiChar;
1869                         qemu_chr_be_write(chr, &c, 1);
1870                     }
1871                 }
1872             }
1873         }
1874     }
1875 }
1876
1877 static DWORD WINAPI win_stdio_thread(LPVOID param)
1878 {
1879     CharDriverState   *chr   = param;
1880     WinStdioCharState *stdio = chr->opaque;
1881     int                ret;
1882     DWORD              dwSize;
1883
1884     while (1) {
1885
1886         /* Wait for one byte */
1887         ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
1888
1889         /* Exit in case of error, continue if nothing read */
1890         if (!ret) {
1891             break;
1892         }
1893         if (!dwSize) {
1894             continue;
1895         }
1896
1897         /* Some terminal emulator returns \r\n for Enter, just pass \n */
1898         if (stdio->win_stdio_buf == '\r') {
1899             continue;
1900         }
1901
1902         /* Signal the main thread and wait until the byte was eaten */
1903         if (!SetEvent(stdio->hInputReadyEvent)) {
1904             break;
1905         }
1906         if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
1907             != WAIT_OBJECT_0) {
1908             break;
1909         }
1910     }
1911
1912     qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
1913     return 0;
1914 }
1915
1916 static void win_stdio_thread_wait_func(void *opaque)
1917 {
1918     CharDriverState   *chr   = opaque;
1919     WinStdioCharState *stdio = chr->opaque;
1920
1921     if (qemu_chr_be_can_write(chr)) {
1922         qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
1923     }
1924
1925     SetEvent(stdio->hInputDoneEvent);
1926 }
1927
1928 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
1929 {
1930     WinStdioCharState *stdio  = chr->opaque;
1931     DWORD              dwMode = 0;
1932
1933     GetConsoleMode(stdio->hStdIn, &dwMode);
1934
1935     if (echo) {
1936         SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
1937     } else {
1938         SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
1939     }
1940 }
1941
1942 static void win_stdio_close(CharDriverState *chr)
1943 {
1944     WinStdioCharState *stdio = chr->opaque;
1945
1946     if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
1947         CloseHandle(stdio->hInputReadyEvent);
1948     }
1949     if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
1950         CloseHandle(stdio->hInputDoneEvent);
1951     }
1952     if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
1953         TerminateThread(stdio->hInputThread, 0);
1954     }
1955
1956     g_free(chr->opaque);
1957     g_free(chr);
1958     stdio_nb_clients--;
1959 }
1960
1961 static CharDriverState *qemu_chr_open_win_stdio(QemuOpts *opts)
1962 {
1963     CharDriverState   *chr;
1964     WinStdioCharState *stdio;
1965     DWORD              dwMode;
1966     int                is_console = 0;
1967
1968     if (stdio_nb_clients >= STDIO_MAX_CLIENTS
1969         || ((display_type != DT_NOGRAPHIC) && (stdio_nb_clients != 0))) {
1970         return NULL;
1971     }
1972
1973     chr   = g_malloc0(sizeof(CharDriverState));
1974     stdio = g_malloc0(sizeof(WinStdioCharState));
1975
1976     stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
1977     if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
1978         fprintf(stderr, "cannot open stdio: invalid handle\n");
1979         exit(1);
1980     }
1981
1982     is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
1983
1984     chr->opaque    = stdio;
1985     chr->chr_write = win_stdio_write;
1986     chr->chr_close = win_stdio_close;
1987
1988     if (stdio_nb_clients == 0) {
1989         if (is_console) {
1990             if (qemu_add_wait_object(stdio->hStdIn,
1991                                      win_stdio_wait_func, chr)) {
1992                 fprintf(stderr, "qemu_add_wait_object: failed\n");
1993             }
1994         } else {
1995             DWORD   dwId;
1996
1997             stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
1998             stdio->hInputDoneEvent  = CreateEvent(NULL, FALSE, FALSE, NULL);
1999             stdio->hInputThread     = CreateThread(NULL, 0, win_stdio_thread,
2000                                             chr, 0, &dwId);
2001
2002             if (stdio->hInputThread == INVALID_HANDLE_VALUE
2003                 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2004                 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2005                 fprintf(stderr, "cannot create stdio thread or event\n");
2006                 exit(1);
2007             }
2008             if (qemu_add_wait_object(stdio->hInputReadyEvent,
2009                                      win_stdio_thread_wait_func, chr)) {
2010                 fprintf(stderr, "qemu_add_wait_object: failed\n");
2011             }
2012         }
2013     }
2014
2015     dwMode |= ENABLE_LINE_INPUT;
2016
2017     stdio_clients[stdio_nb_clients++] = chr;
2018     if (stdio_nb_clients == 1 && is_console) {
2019         /* set the terminal in raw mode */
2020         /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2021         dwMode |= ENABLE_PROCESSED_INPUT;
2022     }
2023
2024     SetConsoleMode(stdio->hStdIn, dwMode);
2025
2026     chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2027     qemu_chr_fe_set_echo(chr, false);
2028
2029     return chr;
2030 }
2031 #endif /* !_WIN32 */
2032
2033 /***********************************************************/
2034 /* UDP Net console */
2035
2036 typedef struct {
2037     int fd;
2038     uint8_t buf[READ_BUF_LEN];
2039     int bufcnt;
2040     int bufptr;
2041     int max_size;
2042 } NetCharDriver;
2043
2044 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2045 {
2046     NetCharDriver *s = chr->opaque;
2047
2048     return send(s->fd, (const void *)buf, len, 0);
2049 }
2050
2051 static int udp_chr_read_poll(void *opaque)
2052 {
2053     CharDriverState *chr = opaque;
2054     NetCharDriver *s = chr->opaque;
2055
2056     s->max_size = qemu_chr_be_can_write(chr);
2057
2058     /* If there were any stray characters in the queue process them
2059      * first
2060      */
2061     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2062         qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2063         s->bufptr++;
2064         s->max_size = qemu_chr_be_can_write(chr);
2065     }
2066     return s->max_size;
2067 }
2068
2069 static void udp_chr_read(void *opaque)
2070 {
2071     CharDriverState *chr = opaque;
2072     NetCharDriver *s = chr->opaque;
2073
2074     if (s->max_size == 0)
2075         return;
2076     s->bufcnt = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
2077     s->bufptr = s->bufcnt;
2078     if (s->bufcnt <= 0)
2079         return;
2080
2081     s->bufptr = 0;
2082     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2083         qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2084         s->bufptr++;
2085         s->max_size = qemu_chr_be_can_write(chr);
2086     }
2087 }
2088
2089 static void udp_chr_update_read_handler(CharDriverState *chr)
2090 {
2091     NetCharDriver *s = chr->opaque;
2092
2093     if (s->fd >= 0) {
2094         qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2095                              udp_chr_read, NULL, chr);
2096     }
2097 }
2098
2099 static void udp_chr_close(CharDriverState *chr)
2100 {
2101     NetCharDriver *s = chr->opaque;
2102     if (s->fd >= 0) {
2103         qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2104         closesocket(s->fd);
2105     }
2106     g_free(s);
2107     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2108 }
2109
2110 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2111 {
2112     CharDriverState *chr = NULL;
2113     NetCharDriver *s = NULL;
2114     Error *local_err = NULL;
2115     int fd = -1;
2116
2117     chr = g_malloc0(sizeof(CharDriverState));
2118     s = g_malloc0(sizeof(NetCharDriver));
2119
2120     fd = inet_dgram_opts(opts, &local_err);
2121     if (fd < 0) {
2122         goto return_err;
2123     }
2124
2125     s->fd = fd;
2126     s->bufcnt = 0;
2127     s->bufptr = 0;
2128     chr->opaque = s;
2129     chr->chr_write = udp_chr_write;
2130     chr->chr_update_read_handler = udp_chr_update_read_handler;
2131     chr->chr_close = udp_chr_close;
2132     return chr;
2133
2134 return_err:
2135     if (local_err) {
2136         qerror_report_err(local_err);
2137         error_free(local_err);
2138     }
2139     g_free(chr);
2140     g_free(s);
2141     if (fd >= 0) {
2142         closesocket(fd);
2143     }
2144     return NULL;
2145 }
2146
2147 /***********************************************************/
2148 /* TCP Net console */
2149
2150 typedef struct {
2151     int fd, listen_fd;
2152     int connected;
2153     int max_size;
2154     int do_telnetopt;
2155     int do_nodelay;
2156     int is_unix;
2157     int msgfd;
2158 } TCPCharDriver;
2159
2160 static void tcp_chr_accept(void *opaque);
2161
2162 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2163 {
2164     TCPCharDriver *s = chr->opaque;
2165     if (s->connected) {
2166         return send_all(s->fd, buf, len);
2167     } else {
2168         /* XXX: indicate an error ? */
2169         return len;
2170     }
2171 }
2172
2173 static int tcp_chr_read_poll(void *opaque)
2174 {
2175     CharDriverState *chr = opaque;
2176     TCPCharDriver *s = chr->opaque;
2177     if (!s->connected)
2178         return 0;
2179     s->max_size = qemu_chr_be_can_write(chr);
2180     return s->max_size;
2181 }
2182
2183 #define IAC 255
2184 #define IAC_BREAK 243
2185 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2186                                       TCPCharDriver *s,
2187                                       uint8_t *buf, int *size)
2188 {
2189     /* Handle any telnet client's basic IAC options to satisfy char by
2190      * char mode with no echo.  All IAC options will be removed from
2191      * the buf and the do_telnetopt variable will be used to track the
2192      * state of the width of the IAC information.
2193      *
2194      * IAC commands come in sets of 3 bytes with the exception of the
2195      * "IAC BREAK" command and the double IAC.
2196      */
2197
2198     int i;
2199     int j = 0;
2200
2201     for (i = 0; i < *size; i++) {
2202         if (s->do_telnetopt > 1) {
2203             if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2204                 /* Double IAC means send an IAC */
2205                 if (j != i)
2206                     buf[j] = buf[i];
2207                 j++;
2208                 s->do_telnetopt = 1;
2209             } else {
2210                 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2211                     /* Handle IAC break commands by sending a serial break */
2212                     qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2213                     s->do_telnetopt++;
2214                 }
2215                 s->do_telnetopt++;
2216             }
2217             if (s->do_telnetopt >= 4) {
2218                 s->do_telnetopt = 1;
2219             }
2220         } else {
2221             if ((unsigned char)buf[i] == IAC) {
2222                 s->do_telnetopt = 2;
2223             } else {
2224                 if (j != i)
2225                     buf[j] = buf[i];
2226                 j++;
2227             }
2228         }
2229     }
2230     *size = j;
2231 }
2232
2233 static int tcp_get_msgfd(CharDriverState *chr)
2234 {
2235     TCPCharDriver *s = chr->opaque;
2236     int fd = s->msgfd;
2237     s->msgfd = -1;
2238     return fd;
2239 }
2240
2241 #ifndef _WIN32
2242 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2243 {
2244     TCPCharDriver *s = chr->opaque;
2245     struct cmsghdr *cmsg;
2246
2247     for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2248         int fd;
2249
2250         if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2251             cmsg->cmsg_level != SOL_SOCKET ||
2252             cmsg->cmsg_type != SCM_RIGHTS)
2253             continue;
2254
2255         fd = *((int *)CMSG_DATA(cmsg));
2256         if (fd < 0)
2257             continue;
2258
2259 #ifndef MSG_CMSG_CLOEXEC
2260         qemu_set_cloexec(fd);
2261 #endif
2262         if (s->msgfd != -1)
2263             close(s->msgfd);
2264         s->msgfd = fd;
2265     }
2266 }
2267
2268 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2269 {
2270     TCPCharDriver *s = chr->opaque;
2271     struct msghdr msg = { NULL, };
2272     struct iovec iov[1];
2273     union {
2274         struct cmsghdr cmsg;
2275         char control[CMSG_SPACE(sizeof(int))];
2276     } msg_control;
2277     int flags = 0;
2278     ssize_t ret;
2279
2280     iov[0].iov_base = buf;
2281     iov[0].iov_len = len;
2282
2283     msg.msg_iov = iov;
2284     msg.msg_iovlen = 1;
2285     msg.msg_control = &msg_control;
2286     msg.msg_controllen = sizeof(msg_control);
2287
2288 #ifdef MSG_CMSG_CLOEXEC
2289     flags |= MSG_CMSG_CLOEXEC;
2290 #endif
2291     ret = recvmsg(s->fd, &msg, flags);
2292     if (ret > 0 && s->is_unix) {
2293         unix_process_msgfd(chr, &msg);
2294     }
2295
2296     return ret;
2297 }
2298 #else
2299 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2300 {
2301     TCPCharDriver *s = chr->opaque;
2302     return qemu_recv(s->fd, buf, len, 0);
2303 }
2304 #endif
2305
2306 static void tcp_chr_read(void *opaque)
2307 {
2308     CharDriverState *chr = opaque;
2309     TCPCharDriver *s = chr->opaque;
2310     uint8_t buf[READ_BUF_LEN];
2311     int len, size;
2312
2313     if (!s->connected || s->max_size <= 0)
2314         return;
2315     len = sizeof(buf);
2316     if (len > s->max_size)
2317         len = s->max_size;
2318     size = tcp_chr_recv(chr, (void *)buf, len);
2319     if (size == 0) {
2320         /* connection closed */
2321         s->connected = 0;
2322         if (s->listen_fd >= 0) {
2323             qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2324         }
2325         qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2326         closesocket(s->fd);
2327         s->fd = -1;
2328         qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2329     } else if (size > 0) {
2330         if (s->do_telnetopt)
2331             tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2332         if (size > 0)
2333             qemu_chr_be_write(chr, buf, size);
2334     }
2335 }
2336
2337 #ifndef _WIN32
2338 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2339 {
2340     return qemu_chr_open_fd(eventfd, eventfd);
2341 }
2342 #endif
2343
2344 static void tcp_chr_connect(void *opaque)
2345 {
2346     CharDriverState *chr = opaque;
2347     TCPCharDriver *s = chr->opaque;
2348
2349     s->connected = 1;
2350     if (s->fd >= 0) {
2351         qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2352                              tcp_chr_read, NULL, chr);
2353     }
2354     qemu_chr_generic_open(chr);
2355 }
2356
2357 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2358 static void tcp_chr_telnet_init(int fd)
2359 {
2360     char buf[3];
2361     /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2362     IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2363     send(fd, (char *)buf, 3, 0);
2364     IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2365     send(fd, (char *)buf, 3, 0);
2366     IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2367     send(fd, (char *)buf, 3, 0);
2368     IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2369     send(fd, (char *)buf, 3, 0);
2370 }
2371
2372 static void socket_set_nodelay(int fd)
2373 {
2374     int val = 1;
2375     setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2376 }
2377
2378 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2379 {
2380     TCPCharDriver *s = chr->opaque;
2381     if (s->fd != -1)
2382         return -1;
2383
2384     socket_set_nonblock(fd);
2385     if (s->do_nodelay)
2386         socket_set_nodelay(fd);
2387     s->fd = fd;
2388     qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2389     tcp_chr_connect(chr);
2390
2391     return 0;
2392 }
2393
2394 static void tcp_chr_accept(void *opaque)
2395 {
2396     CharDriverState *chr = opaque;
2397     TCPCharDriver *s = chr->opaque;
2398     struct sockaddr_in saddr;
2399 #ifndef _WIN32
2400     struct sockaddr_un uaddr;
2401 #endif
2402     struct sockaddr *addr;
2403     socklen_t len;
2404     int fd;
2405
2406     for(;;) {
2407 #ifndef _WIN32
2408         if (s->is_unix) {
2409             len = sizeof(uaddr);
2410             addr = (struct sockaddr *)&uaddr;
2411         } else
2412 #endif
2413         {
2414             len = sizeof(saddr);
2415             addr = (struct sockaddr *)&saddr;
2416         }
2417         fd = qemu_accept(s->listen_fd, addr, &len);
2418         if (fd < 0 && errno != EINTR) {
2419             return;
2420         } else if (fd >= 0) {
2421             if (s->do_telnetopt)
2422                 tcp_chr_telnet_init(fd);
2423             break;
2424         }
2425     }
2426     if (tcp_chr_add_client(chr, fd) < 0)
2427         close(fd);
2428 }
2429
2430 static void tcp_chr_close(CharDriverState *chr)
2431 {
2432     TCPCharDriver *s = chr->opaque;
2433     if (s->fd >= 0) {
2434         qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2435         closesocket(s->fd);
2436     }
2437     if (s->listen_fd >= 0) {
2438         qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2439         closesocket(s->listen_fd);
2440     }
2441     g_free(s);
2442     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2443 }
2444
2445 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2446 {
2447     CharDriverState *chr = NULL;
2448     TCPCharDriver *s = NULL;
2449     Error *local_err = NULL;
2450     int fd = -1;
2451     int is_listen;
2452     int is_waitconnect;
2453     int do_nodelay;
2454     int is_unix;
2455     int is_telnet;
2456
2457     is_listen      = qemu_opt_get_bool(opts, "server", 0);
2458     is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2459     is_telnet      = qemu_opt_get_bool(opts, "telnet", 0);
2460     do_nodelay     = !qemu_opt_get_bool(opts, "delay", 1);
2461     is_unix        = qemu_opt_get(opts, "path") != NULL;
2462     if (!is_listen)
2463         is_waitconnect = 0;
2464
2465     chr = g_malloc0(sizeof(CharDriverState));
2466     s = g_malloc0(sizeof(TCPCharDriver));
2467
2468     if (is_unix) {
2469         if (is_listen) {
2470             fd = unix_listen_opts(opts, &local_err);
2471         } else {
2472             fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2473         }
2474     } else {
2475         if (is_listen) {
2476             fd = inet_listen_opts(opts, 0, &local_err);
2477         } else {
2478             fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2479         }
2480     }
2481     if (fd < 0) {
2482         goto fail;
2483     }
2484
2485     if (!is_waitconnect)
2486         socket_set_nonblock(fd);
2487
2488     s->connected = 0;
2489     s->fd = -1;
2490     s->listen_fd = -1;
2491     s->msgfd = -1;
2492     s->is_unix = is_unix;
2493     s->do_nodelay = do_nodelay && !is_unix;
2494
2495     chr->opaque = s;
2496     chr->chr_write = tcp_chr_write;
2497     chr->chr_close = tcp_chr_close;
2498     chr->get_msgfd = tcp_get_msgfd;
2499     chr->chr_add_client = tcp_chr_add_client;
2500
2501     if (is_listen) {
2502         s->listen_fd = fd;
2503         qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2504         if (is_telnet)
2505             s->do_telnetopt = 1;
2506
2507     } else {
2508         s->connected = 1;
2509         s->fd = fd;
2510         socket_set_nodelay(fd);
2511         tcp_chr_connect(chr);
2512     }
2513
2514     /* for "info chardev" monitor command */
2515     chr->filename = g_malloc(256);
2516     if (is_unix) {
2517         snprintf(chr->filename, 256, "unix:%s%s",
2518                  qemu_opt_get(opts, "path"),
2519                  qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2520     } else if (is_telnet) {
2521         snprintf(chr->filename, 256, "telnet:%s:%s%s",
2522                  qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2523                  qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2524     } else {
2525         snprintf(chr->filename, 256, "tcp:%s:%s%s",
2526                  qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2527                  qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2528     }
2529
2530     if (is_listen && is_waitconnect) {
2531         printf("QEMU waiting for connection on: %s\n",
2532                chr->filename);
2533         tcp_chr_accept(chr);
2534         socket_set_nonblock(s->listen_fd);
2535     }
2536     return chr;
2537
2538  fail:
2539     if (local_err) {
2540         qerror_report_err(local_err);
2541         error_free(local_err);
2542     }
2543     if (fd >= 0) {
2544         closesocket(fd);
2545     }
2546     g_free(s);
2547     g_free(chr);
2548     return NULL;
2549 }
2550
2551 /***********************************************************/
2552 /* Memory chardev */
2553 typedef struct {
2554     size_t outbuf_size;
2555     size_t outbuf_capacity;
2556     uint8_t *outbuf;
2557 } MemoryDriver;
2558
2559 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2560 {
2561     MemoryDriver *d = chr->opaque;
2562
2563     /* TODO: the QString implementation has the same code, we should
2564      * introduce a generic way to do this in cutils.c */
2565     if (d->outbuf_capacity < d->outbuf_size + len) {
2566         /* grow outbuf */
2567         d->outbuf_capacity += len;
2568         d->outbuf_capacity *= 2;
2569         d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
2570     }
2571
2572     memcpy(d->outbuf + d->outbuf_size, buf, len);
2573     d->outbuf_size += len;
2574
2575     return len;
2576 }
2577
2578 void qemu_chr_init_mem(CharDriverState *chr)
2579 {
2580     MemoryDriver *d;
2581
2582     d = g_malloc(sizeof(*d));
2583     d->outbuf_size = 0;
2584     d->outbuf_capacity = 4096;
2585     d->outbuf = g_malloc0(d->outbuf_capacity);
2586
2587     memset(chr, 0, sizeof(*chr));
2588     chr->opaque = d;
2589     chr->chr_write = mem_chr_write;
2590 }
2591
2592 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2593 {
2594     MemoryDriver *d = chr->opaque;
2595     return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2596 }
2597
2598 /* NOTE: this driver can not be closed with qemu_chr_delete()! */
2599 void qemu_chr_close_mem(CharDriverState *chr)
2600 {
2601     MemoryDriver *d = chr->opaque;
2602
2603     g_free(d->outbuf);
2604     g_free(chr->opaque);
2605     chr->opaque = NULL;
2606     chr->chr_write = NULL;
2607 }
2608
2609 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2610 {
2611     const MemoryDriver *d = chr->opaque;
2612     return d->outbuf_size;
2613 }
2614
2615 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2616 {
2617     char host[65], port[33], width[8], height[8];
2618     int pos;
2619     const char *p;
2620     QemuOpts *opts;
2621     Error *local_err = NULL;
2622
2623     opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
2624     if (error_is_set(&local_err)) {
2625         qerror_report_err(local_err);
2626         error_free(local_err);
2627         return NULL;
2628     }
2629
2630     if (strstart(filename, "mon:", &p)) {
2631         filename = p;
2632         qemu_opt_set(opts, "mux", "on");
2633     }
2634
2635     if (strcmp(filename, "null")    == 0 ||
2636         strcmp(filename, "pty")     == 0 ||
2637         strcmp(filename, "msmouse") == 0 ||
2638         strcmp(filename, "braille") == 0 ||
2639         strcmp(filename, "stdio")   == 0) {
2640         qemu_opt_set(opts, "backend", filename);
2641         return opts;
2642     }
2643     if (strstart(filename, "vc", &p)) {
2644         qemu_opt_set(opts, "backend", "vc");
2645         if (*p == ':') {
2646             if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2647                 /* pixels */
2648                 qemu_opt_set(opts, "width", width);
2649                 qemu_opt_set(opts, "height", height);
2650             } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2651                 /* chars */
2652                 qemu_opt_set(opts, "cols", width);
2653                 qemu_opt_set(opts, "rows", height);
2654             } else {
2655                 goto fail;
2656             }
2657         }
2658         return opts;
2659     }
2660     if (strcmp(filename, "con:") == 0) {
2661         qemu_opt_set(opts, "backend", "console");
2662         return opts;
2663     }
2664     if (strstart(filename, "COM", NULL)) {
2665         qemu_opt_set(opts, "backend", "serial");
2666         qemu_opt_set(opts, "path", filename);
2667         return opts;
2668     }
2669     if (strstart(filename, "file:", &p)) {
2670         qemu_opt_set(opts, "backend", "file");
2671         qemu_opt_set(opts, "path", p);
2672         return opts;
2673     }
2674     if (strstart(filename, "pipe:", &p)) {
2675         qemu_opt_set(opts, "backend", "pipe");
2676         qemu_opt_set(opts, "path", p);
2677         return opts;
2678     }
2679     if (strstart(filename, "tcp:", &p) ||
2680         strstart(filename, "telnet:", &p)) {
2681         if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2682             host[0] = 0;
2683             if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2684                 goto fail;
2685         }
2686         qemu_opt_set(opts, "backend", "socket");
2687         qemu_opt_set(opts, "host", host);
2688         qemu_opt_set(opts, "port", port);
2689         if (p[pos] == ',') {
2690             if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2691                 goto fail;
2692         }
2693         if (strstart(filename, "telnet:", &p))
2694             qemu_opt_set(opts, "telnet", "on");
2695         return opts;
2696     }
2697     if (strstart(filename, "udp:", &p)) {
2698         qemu_opt_set(opts, "backend", "udp");
2699         if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2700             host[0] = 0;
2701             if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
2702                 goto fail;
2703             }
2704         }
2705         qemu_opt_set(opts, "host", host);
2706         qemu_opt_set(opts, "port", port);
2707         if (p[pos] == '@') {
2708             p += pos + 1;
2709             if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2710                 host[0] = 0;
2711                 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2712                     goto fail;
2713                 }
2714             }
2715             qemu_opt_set(opts, "localaddr", host);
2716             qemu_opt_set(opts, "localport", port);
2717         }
2718         return opts;
2719     }
2720     if (strstart(filename, "unix:", &p)) {
2721         qemu_opt_set(opts, "backend", "socket");
2722         if (qemu_opts_do_parse(opts, p, "path") != 0)
2723             goto fail;
2724         return opts;
2725     }
2726     if (strstart(filename, "/dev/parport", NULL) ||
2727         strstart(filename, "/dev/ppi", NULL)) {
2728         qemu_opt_set(opts, "backend", "parport");
2729         qemu_opt_set(opts, "path", filename);
2730         return opts;
2731     }
2732     if (strstart(filename, "/dev/", NULL)) {
2733         qemu_opt_set(opts, "backend", "tty");
2734         qemu_opt_set(opts, "path", filename);
2735         return opts;
2736     }
2737
2738 fail:
2739     qemu_opts_del(opts);
2740     return NULL;
2741 }
2742
2743 static const struct {
2744     const char *name;
2745     CharDriverState *(*open)(QemuOpts *opts);
2746 } backend_table[] = {
2747     { .name = "null",      .open = qemu_chr_open_null },
2748     { .name = "socket",    .open = qemu_chr_open_socket },
2749     { .name = "udp",       .open = qemu_chr_open_udp },
2750     { .name = "msmouse",   .open = qemu_chr_open_msmouse },
2751     { .name = "vc",        .open = text_console_init },
2752 #ifdef _WIN32
2753     { .name = "file",      .open = qemu_chr_open_win_file_out },
2754     { .name = "pipe",      .open = qemu_chr_open_win_pipe },
2755     { .name = "console",   .open = qemu_chr_open_win_con },
2756     { .name = "serial",    .open = qemu_chr_open_win },
2757     { .name = "stdio",     .open = qemu_chr_open_win_stdio },
2758 #else
2759     { .name = "file",      .open = qemu_chr_open_file_out },
2760     { .name = "pipe",      .open = qemu_chr_open_pipe },
2761     { .name = "stdio",     .open = qemu_chr_open_stdio },
2762 #endif
2763 #ifdef CONFIG_BRLAPI
2764     { .name = "braille",   .open = chr_baum_init },
2765 #endif
2766 #ifdef HAVE_CHARDEV_TTY
2767     { .name = "tty",       .open = qemu_chr_open_tty },
2768     { .name = "pty",       .open = qemu_chr_open_pty },
2769 #endif
2770 #ifdef HAVE_CHARDEV_PARPORT
2771     { .name = "parport",   .open = qemu_chr_open_pp },
2772 #endif
2773 #ifdef CONFIG_SPICE
2774     { .name = "spicevmc",     .open = qemu_chr_open_spice },
2775 #if SPICE_SERVER_VERSION >= 0x000c02
2776     { .name = "spiceport",    .open = qemu_chr_open_spice_port },
2777 #endif
2778 #endif
2779 };
2780
2781 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
2782                                     void (*init)(struct CharDriverState *s),
2783                                     Error **errp)
2784 {
2785     CharDriverState *chr;
2786     int i;
2787
2788     if (qemu_opts_id(opts) == NULL) {
2789         error_setg(errp, "chardev: no id specified\n");
2790         goto err;
2791     }
2792
2793     if (qemu_opt_get(opts, "backend") == NULL) {
2794         error_setg(errp, "chardev: \"%s\" missing backend\n",
2795                    qemu_opts_id(opts));
2796         goto err;
2797     }
2798     for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
2799         if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
2800             break;
2801     }
2802     if (i == ARRAY_SIZE(backend_table)) {
2803         error_setg(errp, "chardev: backend \"%s\" not found\n",
2804                    qemu_opt_get(opts, "backend"));
2805         goto err;
2806     }
2807
2808     chr = backend_table[i].open(opts);
2809     if (!chr) {
2810         error_setg(errp, "chardev: opening backend \"%s\" failed\n",
2811                    qemu_opt_get(opts, "backend"));
2812         goto err;
2813     }
2814
2815     if (!chr->filename)
2816         chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
2817     chr->init = init;
2818     QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2819
2820     if (qemu_opt_get_bool(opts, "mux", 0)) {
2821         CharDriverState *base = chr;
2822         int len = strlen(qemu_opts_id(opts)) + 6;
2823         base->label = g_malloc(len);
2824         snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
2825         chr = qemu_chr_open_mux(base);
2826         chr->filename = base->filename;
2827         chr->avail_connections = MAX_MUX;
2828         QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2829     } else {
2830         chr->avail_connections = 1;
2831     }
2832     chr->label = g_strdup(qemu_opts_id(opts));
2833     chr->opts = opts;
2834     return chr;
2835
2836 err:
2837     qemu_opts_del(opts);
2838     return NULL;
2839 }
2840
2841 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2842 {
2843     const char *p;
2844     CharDriverState *chr;
2845     QemuOpts *opts;
2846     Error *err = NULL;
2847
2848     if (strstart(filename, "chardev:", &p)) {
2849         return qemu_chr_find(p);
2850     }
2851
2852     opts = qemu_chr_parse_compat(label, filename);
2853     if (!opts)
2854         return NULL;
2855
2856     chr = qemu_chr_new_from_opts(opts, init, &err);
2857     if (error_is_set(&err)) {
2858         fprintf(stderr, "%s\n", error_get_pretty(err));
2859         error_free(err);
2860     }
2861     if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
2862         monitor_init(chr, MONITOR_USE_READLINE);
2863     }
2864     return chr;
2865 }
2866
2867 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
2868 {
2869     if (chr->chr_set_echo) {
2870         chr->chr_set_echo(chr, echo);
2871     }
2872 }
2873
2874 void qemu_chr_fe_open(struct CharDriverState *chr)
2875 {
2876     if (chr->chr_guest_open) {
2877         chr->chr_guest_open(chr);
2878     }
2879 }
2880
2881 void qemu_chr_fe_close(struct CharDriverState *chr)
2882 {
2883     if (chr->chr_guest_close) {
2884         chr->chr_guest_close(chr);
2885     }
2886 }
2887
2888 void qemu_chr_delete(CharDriverState *chr)
2889 {
2890     QTAILQ_REMOVE(&chardevs, chr, next);
2891     if (chr->chr_close) {
2892         chr->chr_close(chr);
2893     }
2894     g_free(chr->filename);
2895     g_free(chr->label);
2896     if (chr->opts) {
2897         qemu_opts_del(chr->opts);
2898     }
2899     g_free(chr);
2900 }
2901
2902 ChardevInfoList *qmp_query_chardev(Error **errp)
2903 {
2904     ChardevInfoList *chr_list = NULL;
2905     CharDriverState *chr;
2906
2907     QTAILQ_FOREACH(chr, &chardevs, next) {
2908         ChardevInfoList *info = g_malloc0(sizeof(*info));
2909         info->value = g_malloc0(sizeof(*info->value));
2910         info->value->label = g_strdup(chr->label);
2911         info->value->filename = g_strdup(chr->filename);
2912
2913         info->next = chr_list;
2914         chr_list = info;
2915     }
2916
2917     return chr_list;
2918 }
2919
2920 CharDriverState *qemu_chr_find(const char *name)
2921 {
2922     CharDriverState *chr;
2923
2924     QTAILQ_FOREACH(chr, &chardevs, next) {
2925         if (strcmp(chr->label, name) != 0)
2926             continue;
2927         return chr;
2928     }
2929     return NULL;
2930 }
2931
2932 /* Get a character (serial) device interface.  */
2933 CharDriverState *qemu_char_get_next_serial(void)
2934 {
2935     static int next_serial;
2936
2937     /* FIXME: This function needs to go away: use chardev properties!  */
2938     return serial_hds[next_serial++];
2939 }
2940
2941 QemuOptsList qemu_chardev_opts = {
2942     .name = "chardev",
2943     .implied_opt_name = "backend",
2944     .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
2945     .desc = {
2946         {
2947             .name = "backend",
2948             .type = QEMU_OPT_STRING,
2949         },{
2950             .name = "path",
2951             .type = QEMU_OPT_STRING,
2952         },{
2953             .name = "host",
2954             .type = QEMU_OPT_STRING,
2955         },{
2956             .name = "port",
2957             .type = QEMU_OPT_STRING,
2958         },{
2959             .name = "localaddr",
2960             .type = QEMU_OPT_STRING,
2961         },{
2962             .name = "localport",
2963             .type = QEMU_OPT_STRING,
2964         },{
2965             .name = "to",
2966             .type = QEMU_OPT_NUMBER,
2967         },{
2968             .name = "ipv4",
2969             .type = QEMU_OPT_BOOL,
2970         },{
2971             .name = "ipv6",
2972             .type = QEMU_OPT_BOOL,
2973         },{
2974             .name = "wait",
2975             .type = QEMU_OPT_BOOL,
2976         },{
2977             .name = "server",
2978             .type = QEMU_OPT_BOOL,
2979         },{
2980             .name = "delay",
2981             .type = QEMU_OPT_BOOL,
2982         },{
2983             .name = "telnet",
2984             .type = QEMU_OPT_BOOL,
2985         },{
2986             .name = "width",
2987             .type = QEMU_OPT_NUMBER,
2988         },{
2989             .name = "height",
2990             .type = QEMU_OPT_NUMBER,
2991         },{
2992             .name = "cols",
2993             .type = QEMU_OPT_NUMBER,
2994         },{
2995             .name = "rows",
2996             .type = QEMU_OPT_NUMBER,
2997         },{
2998             .name = "mux",
2999             .type = QEMU_OPT_BOOL,
3000         },{
3001             .name = "signal",
3002             .type = QEMU_OPT_BOOL,
3003         },{
3004             .name = "name",
3005             .type = QEMU_OPT_STRING,
3006         },{
3007             .name = "debug",
3008             .type = QEMU_OPT_NUMBER,
3009         },
3010         { /* end of list */ }
3011     },
3012 };
3013
3014 #ifdef _WIN32
3015
3016 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3017 {
3018     HANDLE out;
3019
3020     if (file->in) {
3021         error_setg(errp, "input file not supported");
3022         return NULL;
3023     }
3024
3025     out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3026                      OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3027     if (out == INVALID_HANDLE_VALUE) {
3028         error_setg(errp, "open %s failed", file->out);
3029         return NULL;
3030     }
3031     return qemu_chr_open_win_file(out);
3032 }
3033
3034 #else /* WIN32 */
3035
3036 static int qmp_chardev_open_file_source(char *src, int flags,
3037                                         Error **errp)
3038 {
3039     int fd = -1;
3040
3041     TFR(fd = qemu_open(src, flags, 0666));
3042     if (fd == -1) {
3043         error_setg(errp, "open %s: %s", src, strerror(errno));
3044     }
3045     return fd;
3046 }
3047
3048 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3049 {
3050     int flags, in = -1, out = -1;
3051
3052     flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3053     out = qmp_chardev_open_file_source(file->out, flags, errp);
3054     if (error_is_set(errp)) {
3055         return NULL;
3056     }
3057
3058     if (file->in) {
3059         flags = O_RDONLY;
3060         in = qmp_chardev_open_file_source(file->in, flags, errp);
3061         if (error_is_set(errp)) {
3062             qemu_close(out);
3063             return NULL;
3064         }
3065     }
3066
3067     return qemu_chr_open_fd(in, out);
3068 }
3069
3070 #endif /* WIN32 */
3071
3072 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3073                                Error **errp)
3074 {
3075     ChardevReturn *ret = g_new0(ChardevReturn, 1);
3076     CharDriverState *chr = NULL;
3077
3078     chr = qemu_chr_find(id);
3079     if (chr) {
3080         error_setg(errp, "Chardev '%s' already exists", id);
3081         g_free(ret);
3082         return NULL;
3083     }
3084
3085     switch (backend->kind) {
3086     case CHARDEV_BACKEND_KIND_FILE:
3087         chr = qmp_chardev_open_file(backend->file, errp);
3088         break;
3089     case CHARDEV_BACKEND_KIND_NULL:
3090         chr = qemu_chr_open_null(NULL);
3091         break;
3092     default:
3093         error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3094         break;
3095     }
3096
3097     if (chr == NULL && !error_is_set(errp)) {
3098         error_setg(errp, "Failed to create chardev");
3099     }
3100     if (chr) {
3101         chr->label = g_strdup(id);
3102         chr->avail_connections = 1;
3103         QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3104         return ret;
3105     } else {
3106         g_free(ret);
3107         return NULL;
3108     }
3109 }
3110
3111 void qmp_chardev_remove(const char *id, Error **errp)
3112 {
3113     CharDriverState *chr;
3114
3115     chr = qemu_chr_find(id);
3116     if (NULL == chr) {
3117         error_setg(errp, "Chardev '%s' not found", id);
3118         return;
3119     }
3120     if (chr->chr_can_read || chr->chr_read ||
3121         chr->chr_event || chr->handler_opaque) {
3122         error_setg(errp, "Chardev '%s' is busy", id);
3123         return;
3124     }
3125     qemu_chr_delete(chr);
3126 }