monitor: Introduce MONITOR_USE_READLINE flag (Jan Kiszka)
[qemu] / qemu-char.c
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "qemu-common.h"
25 #include "net.h"
26 #include "monitor.h"
27 #include "console.h"
28 #include "sysemu.h"
29 #include "qemu-timer.h"
30 #include "qemu-char.h"
31 #include "block.h"
32 #include "hw/usb.h"
33 #include "hw/baum.h"
34 #include "hw/msmouse.h"
35
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <signal.h>
39 #include <time.h>
40 #include <errno.h>
41 #include <sys/time.h>
42 #include <zlib.h>
43
44 #ifndef _WIN32
45 #include <sys/times.h>
46 #include <sys/wait.h>
47 #include <termios.h>
48 #include <sys/mman.h>
49 #include <sys/ioctl.h>
50 #include <sys/resource.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <net/if.h>
54 #ifdef __NetBSD__
55 #include <net/if_tap.h>
56 #endif
57 #ifdef __linux__
58 #include <linux/if_tun.h>
59 #endif
60 #include <arpa/inet.h>
61 #include <dirent.h>
62 #include <netdb.h>
63 #include <sys/select.h>
64 #ifdef _BSD
65 #include <sys/stat.h>
66 #ifdef __FreeBSD__
67 #include <libutil.h>
68 #include <dev/ppbus/ppi.h>
69 #include <dev/ppbus/ppbconf.h>
70 #else
71 #include <util.h>
72 #endif
73 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
74 #include <freebsd/stdlib.h>
75 #else
76 #ifdef __linux__
77 #include <pty.h>
78
79 #include <linux/ppdev.h>
80 #include <linux/parport.h>
81 #endif
82 #ifdef __sun__
83 #include <sys/stat.h>
84 #include <sys/ethernet.h>
85 #include <sys/sockio.h>
86 #include <netinet/arp.h>
87 #include <netinet/in.h>
88 #include <netinet/in_systm.h>
89 #include <netinet/ip.h>
90 #include <netinet/ip_icmp.h> // must come after ip.h
91 #include <netinet/udp.h>
92 #include <netinet/tcp.h>
93 #include <net/if.h>
94 #include <syslog.h>
95 #include <stropts.h>
96 #endif
97 #endif
98 #endif
99
100 #include "qemu_socket.h"
101
102 /***********************************************************/
103 /* character device */
104
105 static TAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
106     TAILQ_HEAD_INITIALIZER(chardevs);
107 static int initial_reset_issued;
108
109 static void qemu_chr_event(CharDriverState *s, int event)
110 {
111     if (!s->chr_event)
112         return;
113     s->chr_event(s->handler_opaque, event);
114 }
115
116 static void qemu_chr_reset_bh(void *opaque)
117 {
118     CharDriverState *s = opaque;
119     qemu_chr_event(s, CHR_EVENT_RESET);
120     qemu_bh_delete(s->bh);
121     s->bh = NULL;
122 }
123
124 void qemu_chr_reset(CharDriverState *s)
125 {
126     if (s->bh == NULL && initial_reset_issued) {
127         s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
128         qemu_bh_schedule(s->bh);
129     }
130 }
131
132 void qemu_chr_initial_reset(void)
133 {
134     CharDriverState *chr;
135
136     initial_reset_issued = 1;
137
138     TAILQ_FOREACH(chr, &chardevs, next) {
139         qemu_chr_reset(chr);
140     }
141 }
142
143 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
144 {
145     return s->chr_write(s, buf, len);
146 }
147
148 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
149 {
150     if (!s->chr_ioctl)
151         return -ENOTSUP;
152     return s->chr_ioctl(s, cmd, arg);
153 }
154
155 int qemu_chr_can_read(CharDriverState *s)
156 {
157     if (!s->chr_can_read)
158         return 0;
159     return s->chr_can_read(s->handler_opaque);
160 }
161
162 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
163 {
164     s->chr_read(s->handler_opaque, buf, len);
165 }
166
167 void qemu_chr_accept_input(CharDriverState *s)
168 {
169     if (s->chr_accept_input)
170         s->chr_accept_input(s);
171 }
172
173 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
174 {
175     char buf[4096];
176     va_list ap;
177     va_start(ap, fmt);
178     vsnprintf(buf, sizeof(buf), fmt, ap);
179     qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
180     va_end(ap);
181 }
182
183 void qemu_chr_send_event(CharDriverState *s, int event)
184 {
185     if (s->chr_send_event)
186         s->chr_send_event(s, event);
187 }
188
189 void qemu_chr_add_handlers(CharDriverState *s,
190                            IOCanRWHandler *fd_can_read,
191                            IOReadHandler *fd_read,
192                            IOEventHandler *fd_event,
193                            void *opaque)
194 {
195     s->chr_can_read = fd_can_read;
196     s->chr_read = fd_read;
197     s->chr_event = fd_event;
198     s->handler_opaque = opaque;
199     if (s->chr_update_read_handler)
200         s->chr_update_read_handler(s);
201 }
202
203 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
204 {
205     return len;
206 }
207
208 static CharDriverState *qemu_chr_open_null(void)
209 {
210     CharDriverState *chr;
211
212     chr = qemu_mallocz(sizeof(CharDriverState));
213     chr->chr_write = null_chr_write;
214     return chr;
215 }
216
217 /* MUX driver for serial I/O splitting */
218 static int term_timestamps;
219 static int64_t term_timestamps_start;
220 #define MAX_MUX 4
221 #define MUX_BUFFER_SIZE 32      /* Must be a power of 2.  */
222 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
223 typedef struct {
224     IOCanRWHandler *chr_can_read[MAX_MUX];
225     IOReadHandler *chr_read[MAX_MUX];
226     IOEventHandler *chr_event[MAX_MUX];
227     void *ext_opaque[MAX_MUX];
228     CharDriverState *drv;
229     int mux_cnt;
230     int term_got_escape;
231     int max_size;
232     /* Intermediate input buffer allows to catch escape sequences even if the
233        currently active device is not accepting any input - but only until it
234        is full as well. */
235     unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
236     int prod[MAX_MUX];
237     int cons[MAX_MUX];
238 } MuxDriver;
239
240
241 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
242 {
243     MuxDriver *d = chr->opaque;
244     int ret;
245     if (!term_timestamps) {
246         ret = d->drv->chr_write(d->drv, buf, len);
247     } else {
248         int i;
249
250         ret = 0;
251         for(i = 0; i < len; i++) {
252             ret += d->drv->chr_write(d->drv, buf+i, 1);
253             if (buf[i] == '\n') {
254                 char buf1[64];
255                 int64_t ti;
256                 int secs;
257
258                 ti = qemu_get_clock(rt_clock);
259                 if (term_timestamps_start == -1)
260                     term_timestamps_start = ti;
261                 ti -= term_timestamps_start;
262                 secs = ti / 1000;
263                 snprintf(buf1, sizeof(buf1),
264                          "[%02d:%02d:%02d.%03d] ",
265                          secs / 3600,
266                          (secs / 60) % 60,
267                          secs % 60,
268                          (int)(ti % 1000));
269                 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
270             }
271         }
272     }
273     return ret;
274 }
275
276 static const char * const mux_help[] = {
277     "% h    print this help\n\r",
278     "% x    exit emulator\n\r",
279     "% s    save disk data back to file (if -snapshot)\n\r",
280     "% t    toggle console timestamps\n\r"
281     "% b    send break (magic sysrq)\n\r",
282     "% c    switch between console and monitor\n\r",
283     "% %  sends %\n\r",
284     NULL
285 };
286
287 int term_escape_char = 0x01; /* ctrl-a is used for escape */
288 static void mux_print_help(CharDriverState *chr)
289 {
290     int i, j;
291     char ebuf[15] = "Escape-Char";
292     char cbuf[50] = "\n\r";
293
294     if (term_escape_char > 0 && term_escape_char < 26) {
295         snprintf(cbuf, sizeof(cbuf), "\n\r");
296         snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
297     } else {
298         snprintf(cbuf, sizeof(cbuf),
299                  "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
300                  term_escape_char);
301     }
302     chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
303     for (i = 0; mux_help[i] != NULL; i++) {
304         for (j=0; mux_help[i][j] != '\0'; j++) {
305             if (mux_help[i][j] == '%')
306                 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
307             else
308                 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
309         }
310     }
311 }
312
313 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
314 {
315     if (d->chr_event[mux_nr])
316         d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
317 }
318
319 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
320 {
321     if (d->term_got_escape) {
322         d->term_got_escape = 0;
323         if (ch == term_escape_char)
324             goto send_char;
325         switch(ch) {
326         case '?':
327         case 'h':
328             mux_print_help(chr);
329             break;
330         case 'x':
331             {
332                  const char *term =  "QEMU: Terminated\n\r";
333                  chr->chr_write(chr,(uint8_t *)term,strlen(term));
334                  exit(0);
335                  break;
336             }
337         case 's':
338             {
339                 int i;
340                 for (i = 0; i < nb_drives; i++) {
341                         bdrv_commit(drives_table[i].bdrv);
342                 }
343             }
344             break;
345         case 'b':
346             qemu_chr_event(chr, CHR_EVENT_BREAK);
347             break;
348         case 'c':
349             /* Switch to the next registered device */
350             mux_chr_send_event(d, chr->focus, CHR_EVENT_MUX_OUT);
351             chr->focus++;
352             if (chr->focus >= d->mux_cnt)
353                 chr->focus = 0;
354             mux_chr_send_event(d, chr->focus, CHR_EVENT_MUX_IN);
355             break;
356        case 't':
357            term_timestamps = !term_timestamps;
358            term_timestamps_start = -1;
359            break;
360         }
361     } else if (ch == term_escape_char) {
362         d->term_got_escape = 1;
363     } else {
364     send_char:
365         return 1;
366     }
367     return 0;
368 }
369
370 static void mux_chr_accept_input(CharDriverState *chr)
371 {
372     int m = chr->focus;
373     MuxDriver *d = chr->opaque;
374
375     while (d->prod[m] != d->cons[m] &&
376            d->chr_can_read[m] &&
377            d->chr_can_read[m](d->ext_opaque[m])) {
378         d->chr_read[m](d->ext_opaque[m],
379                        &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
380     }
381 }
382
383 static int mux_chr_can_read(void *opaque)
384 {
385     CharDriverState *chr = opaque;
386     MuxDriver *d = chr->opaque;
387     int m = chr->focus;
388
389     if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
390         return 1;
391     if (d->chr_can_read[m])
392         return d->chr_can_read[m](d->ext_opaque[m]);
393     return 0;
394 }
395
396 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
397 {
398     CharDriverState *chr = opaque;
399     MuxDriver *d = chr->opaque;
400     int m = chr->focus;
401     int i;
402
403     mux_chr_accept_input (opaque);
404
405     for(i = 0; i < size; i++)
406         if (mux_proc_byte(chr, d, buf[i])) {
407             if (d->prod[m] == d->cons[m] &&
408                 d->chr_can_read[m] &&
409                 d->chr_can_read[m](d->ext_opaque[m]))
410                 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
411             else
412                 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
413         }
414 }
415
416 static void mux_chr_event(void *opaque, int event)
417 {
418     CharDriverState *chr = opaque;
419     MuxDriver *d = chr->opaque;
420     int i;
421
422     /* Send the event to all registered listeners */
423     for (i = 0; i < d->mux_cnt; i++)
424         mux_chr_send_event(d, i, event);
425 }
426
427 static void mux_chr_update_read_handler(CharDriverState *chr)
428 {
429     MuxDriver *d = chr->opaque;
430
431     if (d->mux_cnt >= MAX_MUX) {
432         fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
433         return;
434     }
435     d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
436     d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
437     d->chr_read[d->mux_cnt] = chr->chr_read;
438     d->chr_event[d->mux_cnt] = chr->chr_event;
439     /* Fix up the real driver with mux routines */
440     if (d->mux_cnt == 0) {
441         qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
442                               mux_chr_event, chr);
443     }
444     chr->focus = d->mux_cnt;
445     d->mux_cnt++;
446 }
447
448 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
449 {
450     CharDriverState *chr;
451     MuxDriver *d;
452
453     chr = qemu_mallocz(sizeof(CharDriverState));
454     d = qemu_mallocz(sizeof(MuxDriver));
455
456     chr->opaque = d;
457     d->drv = drv;
458     chr->focus = -1;
459     chr->chr_write = mux_chr_write;
460     chr->chr_update_read_handler = mux_chr_update_read_handler;
461     chr->chr_accept_input = mux_chr_accept_input;
462     return chr;
463 }
464
465
466 #ifdef _WIN32
467 int send_all(int fd, const void *buf, int len1)
468 {
469     int ret, len;
470
471     len = len1;
472     while (len > 0) {
473         ret = send(fd, buf, len, 0);
474         if (ret < 0) {
475             errno = WSAGetLastError();
476             if (errno != WSAEWOULDBLOCK) {
477                 return -1;
478             }
479         } else if (ret == 0) {
480             break;
481         } else {
482             buf += ret;
483             len -= ret;
484         }
485     }
486     return len1 - len;
487 }
488
489 #else
490
491 static int unix_write(int fd, const uint8_t *buf, int len1)
492 {
493     int ret, len;
494
495     len = len1;
496     while (len > 0) {
497         ret = write(fd, buf, len);
498         if (ret < 0) {
499             if (errno != EINTR && errno != EAGAIN)
500                 return -1;
501         } else if (ret == 0) {
502             break;
503         } else {
504             buf += ret;
505             len -= ret;
506         }
507     }
508     return len1 - len;
509 }
510
511 int send_all(int fd, const void *buf, int len1)
512 {
513     return unix_write(fd, buf, len1);
514 }
515 #endif /* !_WIN32 */
516
517 #ifndef _WIN32
518
519 typedef struct {
520     int fd_in, fd_out;
521     int max_size;
522 } FDCharDriver;
523
524 #define STDIO_MAX_CLIENTS 1
525 static int stdio_nb_clients = 0;
526
527 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
528 {
529     FDCharDriver *s = chr->opaque;
530     return send_all(s->fd_out, buf, len);
531 }
532
533 static int fd_chr_read_poll(void *opaque)
534 {
535     CharDriverState *chr = opaque;
536     FDCharDriver *s = chr->opaque;
537
538     s->max_size = qemu_chr_can_read(chr);
539     return s->max_size;
540 }
541
542 static void fd_chr_read(void *opaque)
543 {
544     CharDriverState *chr = opaque;
545     FDCharDriver *s = chr->opaque;
546     int size, len;
547     uint8_t buf[1024];
548
549     len = sizeof(buf);
550     if (len > s->max_size)
551         len = s->max_size;
552     if (len == 0)
553         return;
554     size = read(s->fd_in, buf, len);
555     if (size == 0) {
556         /* FD has been closed. Remove it from the active list.  */
557         qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
558         return;
559     }
560     if (size > 0) {
561         qemu_chr_read(chr, buf, size);
562     }
563 }
564
565 static void fd_chr_update_read_handler(CharDriverState *chr)
566 {
567     FDCharDriver *s = chr->opaque;
568
569     if (s->fd_in >= 0) {
570         if (nographic && s->fd_in == 0) {
571         } else {
572             qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
573                                  fd_chr_read, NULL, chr);
574         }
575     }
576 }
577
578 static void fd_chr_close(struct CharDriverState *chr)
579 {
580     FDCharDriver *s = chr->opaque;
581
582     if (s->fd_in >= 0) {
583         if (nographic && s->fd_in == 0) {
584         } else {
585             qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
586         }
587     }
588
589     qemu_free(s);
590 }
591
592 /* open a character device to a unix fd */
593 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
594 {
595     CharDriverState *chr;
596     FDCharDriver *s;
597
598     chr = qemu_mallocz(sizeof(CharDriverState));
599     s = qemu_mallocz(sizeof(FDCharDriver));
600     s->fd_in = fd_in;
601     s->fd_out = fd_out;
602     chr->opaque = s;
603     chr->chr_write = fd_chr_write;
604     chr->chr_update_read_handler = fd_chr_update_read_handler;
605     chr->chr_close = fd_chr_close;
606
607     qemu_chr_reset(chr);
608
609     return chr;
610 }
611
612 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
613 {
614     int fd_out;
615
616     TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
617     if (fd_out < 0)
618         return NULL;
619     return qemu_chr_open_fd(-1, fd_out);
620 }
621
622 static CharDriverState *qemu_chr_open_pipe(const char *filename)
623 {
624     int fd_in, fd_out;
625     char filename_in[256], filename_out[256];
626
627     snprintf(filename_in, 256, "%s.in", filename);
628     snprintf(filename_out, 256, "%s.out", filename);
629     TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
630     TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
631     if (fd_in < 0 || fd_out < 0) {
632         if (fd_in >= 0)
633             close(fd_in);
634         if (fd_out >= 0)
635             close(fd_out);
636         TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
637         if (fd_in < 0)
638             return NULL;
639     }
640     return qemu_chr_open_fd(fd_in, fd_out);
641 }
642
643
644 /* for STDIO, we handle the case where several clients use it
645    (nographic mode) */
646
647 #define TERM_FIFO_MAX_SIZE 1
648
649 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
650 static int term_fifo_size;
651
652 static int stdio_read_poll(void *opaque)
653 {
654     CharDriverState *chr = opaque;
655
656     /* try to flush the queue if needed */
657     if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
658         qemu_chr_read(chr, term_fifo, 1);
659         term_fifo_size = 0;
660     }
661     /* see if we can absorb more chars */
662     if (term_fifo_size == 0)
663         return 1;
664     else
665         return 0;
666 }
667
668 static void stdio_read(void *opaque)
669 {
670     int size;
671     uint8_t buf[1];
672     CharDriverState *chr = opaque;
673
674     size = read(0, buf, 1);
675     if (size == 0) {
676         /* stdin has been closed. Remove it from the active list.  */
677         qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
678         return;
679     }
680     if (size > 0) {
681         if (qemu_chr_can_read(chr) > 0) {
682             qemu_chr_read(chr, buf, 1);
683         } else if (term_fifo_size == 0) {
684             term_fifo[term_fifo_size++] = buf[0];
685         }
686     }
687 }
688
689 /* init terminal so that we can grab keys */
690 static struct termios oldtty;
691 static int old_fd0_flags;
692 static int term_atexit_done;
693
694 static void term_exit(void)
695 {
696     tcsetattr (0, TCSANOW, &oldtty);
697     fcntl(0, F_SETFL, old_fd0_flags);
698 }
699
700 static void term_init(void)
701 {
702     struct termios tty;
703
704     tcgetattr (0, &tty);
705     oldtty = tty;
706     old_fd0_flags = fcntl(0, F_GETFL);
707
708     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
709                           |INLCR|IGNCR|ICRNL|IXON);
710     tty.c_oflag |= OPOST;
711     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
712     /* if graphical mode, we allow Ctrl-C handling */
713     if (nographic)
714         tty.c_lflag &= ~ISIG;
715     tty.c_cflag &= ~(CSIZE|PARENB);
716     tty.c_cflag |= CS8;
717     tty.c_cc[VMIN] = 1;
718     tty.c_cc[VTIME] = 0;
719
720     tcsetattr (0, TCSANOW, &tty);
721
722     if (!term_atexit_done++)
723         atexit(term_exit);
724
725     fcntl(0, F_SETFL, O_NONBLOCK);
726 }
727
728 static void qemu_chr_close_stdio(struct CharDriverState *chr)
729 {
730     term_exit();
731     stdio_nb_clients--;
732     qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
733     fd_chr_close(chr);
734 }
735
736 static CharDriverState *qemu_chr_open_stdio(void)
737 {
738     CharDriverState *chr;
739
740     if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
741         return NULL;
742     chr = qemu_chr_open_fd(0, 1);
743     chr->chr_close = qemu_chr_close_stdio;
744     qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
745     stdio_nb_clients++;
746     term_init();
747
748     return chr;
749 }
750
751 #ifdef __sun__
752 /* Once Solaris has openpty(), this is going to be removed. */
753 int openpty(int *amaster, int *aslave, char *name,
754             struct termios *termp, struct winsize *winp)
755 {
756         const char *slave;
757         int mfd = -1, sfd = -1;
758
759         *amaster = *aslave = -1;
760
761         mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
762         if (mfd < 0)
763                 goto err;
764
765         if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
766                 goto err;
767
768         if ((slave = ptsname(mfd)) == NULL)
769                 goto err;
770
771         if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
772                 goto err;
773
774         if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
775             (termp != NULL && tcgetattr(sfd, termp) < 0))
776                 goto err;
777
778         if (amaster)
779                 *amaster = mfd;
780         if (aslave)
781                 *aslave = sfd;
782         if (winp)
783                 ioctl(sfd, TIOCSWINSZ, winp);
784
785         return 0;
786
787 err:
788         if (sfd != -1)
789                 close(sfd);
790         close(mfd);
791         return -1;
792 }
793
794 void cfmakeraw (struct termios *termios_p)
795 {
796         termios_p->c_iflag &=
797                 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
798         termios_p->c_oflag &= ~OPOST;
799         termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
800         termios_p->c_cflag &= ~(CSIZE|PARENB);
801         termios_p->c_cflag |= CS8;
802
803         termios_p->c_cc[VMIN] = 0;
804         termios_p->c_cc[VTIME] = 0;
805 }
806 #endif
807
808 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
809     || defined(__NetBSD__) || defined(__OpenBSD__)
810
811 typedef struct {
812     int fd;
813     int connected;
814     int polling;
815     int read_bytes;
816     QEMUTimer *timer;
817 } PtyCharDriver;
818
819 static void pty_chr_update_read_handler(CharDriverState *chr);
820 static void pty_chr_state(CharDriverState *chr, int connected);
821
822 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
823 {
824     PtyCharDriver *s = chr->opaque;
825
826     if (!s->connected) {
827         /* guest sends data, check for (re-)connect */
828         pty_chr_update_read_handler(chr);
829         return 0;
830     }
831     return send_all(s->fd, buf, len);
832 }
833
834 static int pty_chr_read_poll(void *opaque)
835 {
836     CharDriverState *chr = opaque;
837     PtyCharDriver *s = chr->opaque;
838
839     s->read_bytes = qemu_chr_can_read(chr);
840     return s->read_bytes;
841 }
842
843 static void pty_chr_read(void *opaque)
844 {
845     CharDriverState *chr = opaque;
846     PtyCharDriver *s = chr->opaque;
847     int size, len;
848     uint8_t buf[1024];
849
850     len = sizeof(buf);
851     if (len > s->read_bytes)
852         len = s->read_bytes;
853     if (len == 0)
854         return;
855     size = read(s->fd, buf, len);
856     if ((size == -1 && errno == EIO) ||
857         (size == 0)) {
858         pty_chr_state(chr, 0);
859         return;
860     }
861     if (size > 0) {
862         pty_chr_state(chr, 1);
863         qemu_chr_read(chr, buf, size);
864     }
865 }
866
867 static void pty_chr_update_read_handler(CharDriverState *chr)
868 {
869     PtyCharDriver *s = chr->opaque;
870
871     qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
872                          pty_chr_read, NULL, chr);
873     s->polling = 1;
874     /*
875      * Short timeout here: just need wait long enougth that qemu makes
876      * it through the poll loop once.  When reconnected we want a
877      * short timeout so we notice it almost instantly.  Otherwise
878      * read() gives us -EIO instantly, making pty_chr_state() reset the
879      * timeout to the normal (much longer) poll interval before the
880      * timer triggers.
881      */
882     qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
883 }
884
885 static void pty_chr_state(CharDriverState *chr, int connected)
886 {
887     PtyCharDriver *s = chr->opaque;
888
889     if (!connected) {
890         qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
891         s->connected = 0;
892         s->polling = 0;
893         /* (re-)connect poll interval for idle guests: once per second.
894          * We check more frequently in case the guests sends data to
895          * the virtual device linked to our pty. */
896         qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
897     } else {
898         if (!s->connected)
899             qemu_chr_reset(chr);
900         s->connected = 1;
901     }
902 }
903
904 static void pty_chr_timer(void *opaque)
905 {
906     struct CharDriverState *chr = opaque;
907     PtyCharDriver *s = chr->opaque;
908
909     if (s->connected)
910         return;
911     if (s->polling) {
912         /* If we arrive here without polling being cleared due
913          * read returning -EIO, then we are (re-)connected */
914         pty_chr_state(chr, 1);
915         return;
916     }
917
918     /* Next poll ... */
919     pty_chr_update_read_handler(chr);
920 }
921
922 static void pty_chr_close(struct CharDriverState *chr)
923 {
924     PtyCharDriver *s = chr->opaque;
925
926     qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
927     close(s->fd);
928     qemu_free(s);
929 }
930
931 static CharDriverState *qemu_chr_open_pty(void)
932 {
933     CharDriverState *chr;
934     PtyCharDriver *s;
935     struct termios tty;
936     int slave_fd, len;
937 #if defined(__OpenBSD__)
938     char pty_name[PATH_MAX];
939 #define q_ptsname(x) pty_name
940 #else
941     char *pty_name = NULL;
942 #define q_ptsname(x) ptsname(x)
943 #endif
944
945     chr = qemu_mallocz(sizeof(CharDriverState));
946     s = qemu_mallocz(sizeof(PtyCharDriver));
947
948     if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
949         return NULL;
950     }
951
952     /* Set raw attributes on the pty. */
953     tcgetattr(slave_fd, &tty);
954     cfmakeraw(&tty);
955     tcsetattr(slave_fd, TCSAFLUSH, &tty);
956     close(slave_fd);
957
958     len = strlen(q_ptsname(s->fd)) + 5;
959     chr->filename = qemu_malloc(len);
960     snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
961     fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
962
963     chr->opaque = s;
964     chr->chr_write = pty_chr_write;
965     chr->chr_update_read_handler = pty_chr_update_read_handler;
966     chr->chr_close = pty_chr_close;
967
968     s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
969
970     return chr;
971 }
972
973 static void tty_serial_init(int fd, int speed,
974                             int parity, int data_bits, int stop_bits)
975 {
976     struct termios tty;
977     speed_t spd;
978
979 #if 0
980     printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
981            speed, parity, data_bits, stop_bits);
982 #endif
983     tcgetattr (fd, &tty);
984
985 #define MARGIN 1.1
986     if (speed <= 50 * MARGIN)
987         spd = B50;
988     else if (speed <= 75 * MARGIN)
989         spd = B75;
990     else if (speed <= 300 * MARGIN)
991         spd = B300;
992     else if (speed <= 600 * MARGIN)
993         spd = B600;
994     else if (speed <= 1200 * MARGIN)
995         spd = B1200;
996     else if (speed <= 2400 * MARGIN)
997         spd = B2400;
998     else if (speed <= 4800 * MARGIN)
999         spd = B4800;
1000     else if (speed <= 9600 * MARGIN)
1001         spd = B9600;
1002     else if (speed <= 19200 * MARGIN)
1003         spd = B19200;
1004     else if (speed <= 38400 * MARGIN)
1005         spd = B38400;
1006     else if (speed <= 57600 * MARGIN)
1007         spd = B57600;
1008     else if (speed <= 115200 * MARGIN)
1009         spd = B115200;
1010     else
1011         spd = B115200;
1012
1013     cfsetispeed(&tty, spd);
1014     cfsetospeed(&tty, spd);
1015
1016     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1017                           |INLCR|IGNCR|ICRNL|IXON);
1018     tty.c_oflag |= OPOST;
1019     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1020     tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1021     switch(data_bits) {
1022     default:
1023     case 8:
1024         tty.c_cflag |= CS8;
1025         break;
1026     case 7:
1027         tty.c_cflag |= CS7;
1028         break;
1029     case 6:
1030         tty.c_cflag |= CS6;
1031         break;
1032     case 5:
1033         tty.c_cflag |= CS5;
1034         break;
1035     }
1036     switch(parity) {
1037     default:
1038     case 'N':
1039         break;
1040     case 'E':
1041         tty.c_cflag |= PARENB;
1042         break;
1043     case 'O':
1044         tty.c_cflag |= PARENB | PARODD;
1045         break;
1046     }
1047     if (stop_bits == 2)
1048         tty.c_cflag |= CSTOPB;
1049
1050     tcsetattr (fd, TCSANOW, &tty);
1051 }
1052
1053 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1054 {
1055     FDCharDriver *s = chr->opaque;
1056
1057     switch(cmd) {
1058     case CHR_IOCTL_SERIAL_SET_PARAMS:
1059         {
1060             QEMUSerialSetParams *ssp = arg;
1061             tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1062                             ssp->data_bits, ssp->stop_bits);
1063         }
1064         break;
1065     case CHR_IOCTL_SERIAL_SET_BREAK:
1066         {
1067             int enable = *(int *)arg;
1068             if (enable)
1069                 tcsendbreak(s->fd_in, 1);
1070         }
1071         break;
1072     case CHR_IOCTL_SERIAL_GET_TIOCM:
1073         {
1074             int sarg = 0;
1075             int *targ = (int *)arg;
1076             ioctl(s->fd_in, TIOCMGET, &sarg);
1077             *targ = 0;
1078             if (sarg & TIOCM_CTS)
1079                 *targ |= CHR_TIOCM_CTS;
1080             if (sarg & TIOCM_CAR)
1081                 *targ |= CHR_TIOCM_CAR;
1082             if (sarg & TIOCM_DSR)
1083                 *targ |= CHR_TIOCM_DSR;
1084             if (sarg & TIOCM_RI)
1085                 *targ |= CHR_TIOCM_RI;
1086             if (sarg & TIOCM_DTR)
1087                 *targ |= CHR_TIOCM_DTR;
1088             if (sarg & TIOCM_RTS)
1089                 *targ |= CHR_TIOCM_RTS;
1090         }
1091         break;
1092     case CHR_IOCTL_SERIAL_SET_TIOCM:
1093         {
1094             int sarg = *(int *)arg;
1095             int targ = 0;
1096             ioctl(s->fd_in, TIOCMGET, &targ);
1097             targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1098                      | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1099             if (sarg & CHR_TIOCM_CTS)
1100                 targ |= TIOCM_CTS;
1101             if (sarg & CHR_TIOCM_CAR)
1102                 targ |= TIOCM_CAR;
1103             if (sarg & CHR_TIOCM_DSR)
1104                 targ |= TIOCM_DSR;
1105             if (sarg & CHR_TIOCM_RI)
1106                 targ |= TIOCM_RI;
1107             if (sarg & CHR_TIOCM_DTR)
1108                 targ |= TIOCM_DTR;
1109             if (sarg & CHR_TIOCM_RTS)
1110                 targ |= TIOCM_RTS;
1111             ioctl(s->fd_in, TIOCMSET, &targ);
1112         }
1113         break;
1114     default:
1115         return -ENOTSUP;
1116     }
1117     return 0;
1118 }
1119
1120 static CharDriverState *qemu_chr_open_tty(const char *filename)
1121 {
1122     CharDriverState *chr;
1123     int fd;
1124
1125     TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
1126     tty_serial_init(fd, 115200, 'N', 8, 1);
1127     chr = qemu_chr_open_fd(fd, fd);
1128     if (!chr) {
1129         close(fd);
1130         return NULL;
1131     }
1132     chr->chr_ioctl = tty_serial_ioctl;
1133     qemu_chr_reset(chr);
1134     return chr;
1135 }
1136 #else  /* ! __linux__ && ! __sun__ */
1137 static CharDriverState *qemu_chr_open_pty(void)
1138 {
1139     return NULL;
1140 }
1141 #endif /* __linux__ || __sun__ */
1142
1143 #if defined(__linux__)
1144 typedef struct {
1145     int fd;
1146     int mode;
1147 } ParallelCharDriver;
1148
1149 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1150 {
1151     if (s->mode != mode) {
1152         int m = mode;
1153         if (ioctl(s->fd, PPSETMODE, &m) < 0)
1154             return 0;
1155         s->mode = mode;
1156     }
1157     return 1;
1158 }
1159
1160 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1161 {
1162     ParallelCharDriver *drv = chr->opaque;
1163     int fd = drv->fd;
1164     uint8_t b;
1165
1166     switch(cmd) {
1167     case CHR_IOCTL_PP_READ_DATA:
1168         if (ioctl(fd, PPRDATA, &b) < 0)
1169             return -ENOTSUP;
1170         *(uint8_t *)arg = b;
1171         break;
1172     case CHR_IOCTL_PP_WRITE_DATA:
1173         b = *(uint8_t *)arg;
1174         if (ioctl(fd, PPWDATA, &b) < 0)
1175             return -ENOTSUP;
1176         break;
1177     case CHR_IOCTL_PP_READ_CONTROL:
1178         if (ioctl(fd, PPRCONTROL, &b) < 0)
1179             return -ENOTSUP;
1180         /* Linux gives only the lowest bits, and no way to know data
1181            direction! For better compatibility set the fixed upper
1182            bits. */
1183         *(uint8_t *)arg = b | 0xc0;
1184         break;
1185     case CHR_IOCTL_PP_WRITE_CONTROL:
1186         b = *(uint8_t *)arg;
1187         if (ioctl(fd, PPWCONTROL, &b) < 0)
1188             return -ENOTSUP;
1189         break;
1190     case CHR_IOCTL_PP_READ_STATUS:
1191         if (ioctl(fd, PPRSTATUS, &b) < 0)
1192             return -ENOTSUP;
1193         *(uint8_t *)arg = b;
1194         break;
1195     case CHR_IOCTL_PP_DATA_DIR:
1196         if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1197             return -ENOTSUP;
1198         break;
1199     case CHR_IOCTL_PP_EPP_READ_ADDR:
1200         if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1201             struct ParallelIOArg *parg = arg;
1202             int n = read(fd, parg->buffer, parg->count);
1203             if (n != parg->count) {
1204                 return -EIO;
1205             }
1206         }
1207         break;
1208     case CHR_IOCTL_PP_EPP_READ:
1209         if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1210             struct ParallelIOArg *parg = arg;
1211             int n = read(fd, parg->buffer, parg->count);
1212             if (n != parg->count) {
1213                 return -EIO;
1214             }
1215         }
1216         break;
1217     case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1218         if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1219             struct ParallelIOArg *parg = arg;
1220             int n = write(fd, parg->buffer, parg->count);
1221             if (n != parg->count) {
1222                 return -EIO;
1223             }
1224         }
1225         break;
1226     case CHR_IOCTL_PP_EPP_WRITE:
1227         if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1228             struct ParallelIOArg *parg = arg;
1229             int n = write(fd, parg->buffer, parg->count);
1230             if (n != parg->count) {
1231                 return -EIO;
1232             }
1233         }
1234         break;
1235     default:
1236         return -ENOTSUP;
1237     }
1238     return 0;
1239 }
1240
1241 static void pp_close(CharDriverState *chr)
1242 {
1243     ParallelCharDriver *drv = chr->opaque;
1244     int fd = drv->fd;
1245
1246     pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1247     ioctl(fd, PPRELEASE);
1248     close(fd);
1249     qemu_free(drv);
1250 }
1251
1252 static CharDriverState *qemu_chr_open_pp(const char *filename)
1253 {
1254     CharDriverState *chr;
1255     ParallelCharDriver *drv;
1256     int fd;
1257
1258     TFR(fd = open(filename, O_RDWR));
1259     if (fd < 0)
1260         return NULL;
1261
1262     if (ioctl(fd, PPCLAIM) < 0) {
1263         close(fd);
1264         return NULL;
1265     }
1266
1267     drv = qemu_mallocz(sizeof(ParallelCharDriver));
1268     drv->fd = fd;
1269     drv->mode = IEEE1284_MODE_COMPAT;
1270
1271     chr = qemu_mallocz(sizeof(CharDriverState));
1272     chr->chr_write = null_chr_write;
1273     chr->chr_ioctl = pp_ioctl;
1274     chr->chr_close = pp_close;
1275     chr->opaque = drv;
1276
1277     qemu_chr_reset(chr);
1278
1279     return chr;
1280 }
1281 #endif /* __linux__ */
1282
1283 #if defined(__FreeBSD__)
1284 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1285 {
1286     int fd = (int)chr->opaque;
1287     uint8_t b;
1288
1289     switch(cmd) {
1290     case CHR_IOCTL_PP_READ_DATA:
1291         if (ioctl(fd, PPIGDATA, &b) < 0)
1292             return -ENOTSUP;
1293         *(uint8_t *)arg = b;
1294         break;
1295     case CHR_IOCTL_PP_WRITE_DATA:
1296         b = *(uint8_t *)arg;
1297         if (ioctl(fd, PPISDATA, &b) < 0)
1298             return -ENOTSUP;
1299         break;
1300     case CHR_IOCTL_PP_READ_CONTROL:
1301         if (ioctl(fd, PPIGCTRL, &b) < 0)
1302             return -ENOTSUP;
1303         *(uint8_t *)arg = b;
1304         break;
1305     case CHR_IOCTL_PP_WRITE_CONTROL:
1306         b = *(uint8_t *)arg;
1307         if (ioctl(fd, PPISCTRL, &b) < 0)
1308             return -ENOTSUP;
1309         break;
1310     case CHR_IOCTL_PP_READ_STATUS:
1311         if (ioctl(fd, PPIGSTATUS, &b) < 0)
1312             return -ENOTSUP;
1313         *(uint8_t *)arg = b;
1314         break;
1315     default:
1316         return -ENOTSUP;
1317     }
1318     return 0;
1319 }
1320
1321 static CharDriverState *qemu_chr_open_pp(const char *filename)
1322 {
1323     CharDriverState *chr;
1324     int fd;
1325
1326     fd = open(filename, O_RDWR);
1327     if (fd < 0)
1328         return NULL;
1329
1330     chr = qemu_mallocz(sizeof(CharDriverState));
1331     chr->opaque = (void *)fd;
1332     chr->chr_write = null_chr_write;
1333     chr->chr_ioctl = pp_ioctl;
1334     return chr;
1335 }
1336 #endif
1337
1338 #else /* _WIN32 */
1339
1340 typedef struct {
1341     int max_size;
1342     HANDLE hcom, hrecv, hsend;
1343     OVERLAPPED orecv, osend;
1344     BOOL fpipe;
1345     DWORD len;
1346 } WinCharState;
1347
1348 #define NSENDBUF 2048
1349 #define NRECVBUF 2048
1350 #define MAXCONNECT 1
1351 #define NTIMEOUT 5000
1352
1353 static int win_chr_poll(void *opaque);
1354 static int win_chr_pipe_poll(void *opaque);
1355
1356 static void win_chr_close(CharDriverState *chr)
1357 {
1358     WinCharState *s = chr->opaque;
1359
1360     if (s->hsend) {
1361         CloseHandle(s->hsend);
1362         s->hsend = NULL;
1363     }
1364     if (s->hrecv) {
1365         CloseHandle(s->hrecv);
1366         s->hrecv = NULL;
1367     }
1368     if (s->hcom) {
1369         CloseHandle(s->hcom);
1370         s->hcom = NULL;
1371     }
1372     if (s->fpipe)
1373         qemu_del_polling_cb(win_chr_pipe_poll, chr);
1374     else
1375         qemu_del_polling_cb(win_chr_poll, chr);
1376 }
1377
1378 static int win_chr_init(CharDriverState *chr, const char *filename)
1379 {
1380     WinCharState *s = chr->opaque;
1381     COMMCONFIG comcfg;
1382     COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1383     COMSTAT comstat;
1384     DWORD size;
1385     DWORD err;
1386
1387     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1388     if (!s->hsend) {
1389         fprintf(stderr, "Failed CreateEvent\n");
1390         goto fail;
1391     }
1392     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1393     if (!s->hrecv) {
1394         fprintf(stderr, "Failed CreateEvent\n");
1395         goto fail;
1396     }
1397
1398     s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1399                       OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1400     if (s->hcom == INVALID_HANDLE_VALUE) {
1401         fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1402         s->hcom = NULL;
1403         goto fail;
1404     }
1405
1406     if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1407         fprintf(stderr, "Failed SetupComm\n");
1408         goto fail;
1409     }
1410
1411     ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1412     size = sizeof(COMMCONFIG);
1413     GetDefaultCommConfig(filename, &comcfg, &size);
1414     comcfg.dcb.DCBlength = sizeof(DCB);
1415     CommConfigDialog(filename, NULL, &comcfg);
1416
1417     if (!SetCommState(s->hcom, &comcfg.dcb)) {
1418         fprintf(stderr, "Failed SetCommState\n");
1419         goto fail;
1420     }
1421
1422     if (!SetCommMask(s->hcom, EV_ERR)) {
1423         fprintf(stderr, "Failed SetCommMask\n");
1424         goto fail;
1425     }
1426
1427     cto.ReadIntervalTimeout = MAXDWORD;
1428     if (!SetCommTimeouts(s->hcom, &cto)) {
1429         fprintf(stderr, "Failed SetCommTimeouts\n");
1430         goto fail;
1431     }
1432
1433     if (!ClearCommError(s->hcom, &err, &comstat)) {
1434         fprintf(stderr, "Failed ClearCommError\n");
1435         goto fail;
1436     }
1437     qemu_add_polling_cb(win_chr_poll, chr);
1438     return 0;
1439
1440  fail:
1441     win_chr_close(chr);
1442     return -1;
1443 }
1444
1445 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1446 {
1447     WinCharState *s = chr->opaque;
1448     DWORD len, ret, size, err;
1449
1450     len = len1;
1451     ZeroMemory(&s->osend, sizeof(s->osend));
1452     s->osend.hEvent = s->hsend;
1453     while (len > 0) {
1454         if (s->hsend)
1455             ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1456         else
1457             ret = WriteFile(s->hcom, buf, len, &size, NULL);
1458         if (!ret) {
1459             err = GetLastError();
1460             if (err == ERROR_IO_PENDING) {
1461                 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1462                 if (ret) {
1463                     buf += size;
1464                     len -= size;
1465                 } else {
1466                     break;
1467                 }
1468             } else {
1469                 break;
1470             }
1471         } else {
1472             buf += size;
1473             len -= size;
1474         }
1475     }
1476     return len1 - len;
1477 }
1478
1479 static int win_chr_read_poll(CharDriverState *chr)
1480 {
1481     WinCharState *s = chr->opaque;
1482
1483     s->max_size = qemu_chr_can_read(chr);
1484     return s->max_size;
1485 }
1486
1487 static void win_chr_readfile(CharDriverState *chr)
1488 {
1489     WinCharState *s = chr->opaque;
1490     int ret, err;
1491     uint8_t buf[1024];
1492     DWORD size;
1493
1494     ZeroMemory(&s->orecv, sizeof(s->orecv));
1495     s->orecv.hEvent = s->hrecv;
1496     ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1497     if (!ret) {
1498         err = GetLastError();
1499         if (err == ERROR_IO_PENDING) {
1500             ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1501         }
1502     }
1503
1504     if (size > 0) {
1505         qemu_chr_read(chr, buf, size);
1506     }
1507 }
1508
1509 static void win_chr_read(CharDriverState *chr)
1510 {
1511     WinCharState *s = chr->opaque;
1512
1513     if (s->len > s->max_size)
1514         s->len = s->max_size;
1515     if (s->len == 0)
1516         return;
1517
1518     win_chr_readfile(chr);
1519 }
1520
1521 static int win_chr_poll(void *opaque)
1522 {
1523     CharDriverState *chr = opaque;
1524     WinCharState *s = chr->opaque;
1525     COMSTAT status;
1526     DWORD comerr;
1527
1528     ClearCommError(s->hcom, &comerr, &status);
1529     if (status.cbInQue > 0) {
1530         s->len = status.cbInQue;
1531         win_chr_read_poll(chr);
1532         win_chr_read(chr);
1533         return 1;
1534     }
1535     return 0;
1536 }
1537
1538 static CharDriverState *qemu_chr_open_win(const char *filename)
1539 {
1540     CharDriverState *chr;
1541     WinCharState *s;
1542
1543     chr = qemu_mallocz(sizeof(CharDriverState));
1544     s = qemu_mallocz(sizeof(WinCharState));
1545     chr->opaque = s;
1546     chr->chr_write = win_chr_write;
1547     chr->chr_close = win_chr_close;
1548
1549     if (win_chr_init(chr, filename) < 0) {
1550         free(s);
1551         free(chr);
1552         return NULL;
1553     }
1554     qemu_chr_reset(chr);
1555     return chr;
1556 }
1557
1558 static int win_chr_pipe_poll(void *opaque)
1559 {
1560     CharDriverState *chr = opaque;
1561     WinCharState *s = chr->opaque;
1562     DWORD size;
1563
1564     PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1565     if (size > 0) {
1566         s->len = size;
1567         win_chr_read_poll(chr);
1568         win_chr_read(chr);
1569         return 1;
1570     }
1571     return 0;
1572 }
1573
1574 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1575 {
1576     WinCharState *s = chr->opaque;
1577     OVERLAPPED ov;
1578     int ret;
1579     DWORD size;
1580     char openname[256];
1581
1582     s->fpipe = TRUE;
1583
1584     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1585     if (!s->hsend) {
1586         fprintf(stderr, "Failed CreateEvent\n");
1587         goto fail;
1588     }
1589     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1590     if (!s->hrecv) {
1591         fprintf(stderr, "Failed CreateEvent\n");
1592         goto fail;
1593     }
1594
1595     snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1596     s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1597                               PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1598                               PIPE_WAIT,
1599                               MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1600     if (s->hcom == INVALID_HANDLE_VALUE) {
1601         fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1602         s->hcom = NULL;
1603         goto fail;
1604     }
1605
1606     ZeroMemory(&ov, sizeof(ov));
1607     ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1608     ret = ConnectNamedPipe(s->hcom, &ov);
1609     if (ret) {
1610         fprintf(stderr, "Failed ConnectNamedPipe\n");
1611         goto fail;
1612     }
1613
1614     ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1615     if (!ret) {
1616         fprintf(stderr, "Failed GetOverlappedResult\n");
1617         if (ov.hEvent) {
1618             CloseHandle(ov.hEvent);
1619             ov.hEvent = NULL;
1620         }
1621         goto fail;
1622     }
1623
1624     if (ov.hEvent) {
1625         CloseHandle(ov.hEvent);
1626         ov.hEvent = NULL;
1627     }
1628     qemu_add_polling_cb(win_chr_pipe_poll, chr);
1629     return 0;
1630
1631  fail:
1632     win_chr_close(chr);
1633     return -1;
1634 }
1635
1636
1637 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
1638 {
1639     CharDriverState *chr;
1640     WinCharState *s;
1641
1642     chr = qemu_mallocz(sizeof(CharDriverState));
1643     s = qemu_mallocz(sizeof(WinCharState));
1644     chr->opaque = s;
1645     chr->chr_write = win_chr_write;
1646     chr->chr_close = win_chr_close;
1647
1648     if (win_chr_pipe_init(chr, filename) < 0) {
1649         free(s);
1650         free(chr);
1651         return NULL;
1652     }
1653     qemu_chr_reset(chr);
1654     return chr;
1655 }
1656
1657 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1658 {
1659     CharDriverState *chr;
1660     WinCharState *s;
1661
1662     chr = qemu_mallocz(sizeof(CharDriverState));
1663     s = qemu_mallocz(sizeof(WinCharState));
1664     s->hcom = fd_out;
1665     chr->opaque = s;
1666     chr->chr_write = win_chr_write;
1667     qemu_chr_reset(chr);
1668     return chr;
1669 }
1670
1671 static CharDriverState *qemu_chr_open_win_con(const char *filename)
1672 {
1673     return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1674 }
1675
1676 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
1677 {
1678     HANDLE fd_out;
1679
1680     fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1681                         OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1682     if (fd_out == INVALID_HANDLE_VALUE)
1683         return NULL;
1684
1685     return qemu_chr_open_win_file(fd_out);
1686 }
1687 #endif /* !_WIN32 */
1688
1689 /***********************************************************/
1690 /* UDP Net console */
1691
1692 typedef struct {
1693     int fd;
1694     struct sockaddr_in daddr;
1695     uint8_t buf[1024];
1696     int bufcnt;
1697     int bufptr;
1698     int max_size;
1699 } NetCharDriver;
1700
1701 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1702 {
1703     NetCharDriver *s = chr->opaque;
1704
1705     return sendto(s->fd, buf, len, 0,
1706                   (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
1707 }
1708
1709 static int udp_chr_read_poll(void *opaque)
1710 {
1711     CharDriverState *chr = opaque;
1712     NetCharDriver *s = chr->opaque;
1713
1714     s->max_size = qemu_chr_can_read(chr);
1715
1716     /* If there were any stray characters in the queue process them
1717      * first
1718      */
1719     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1720         qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1721         s->bufptr++;
1722         s->max_size = qemu_chr_can_read(chr);
1723     }
1724     return s->max_size;
1725 }
1726
1727 static void udp_chr_read(void *opaque)
1728 {
1729     CharDriverState *chr = opaque;
1730     NetCharDriver *s = chr->opaque;
1731
1732     if (s->max_size == 0)
1733         return;
1734     s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
1735     s->bufptr = s->bufcnt;
1736     if (s->bufcnt <= 0)
1737         return;
1738
1739     s->bufptr = 0;
1740     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1741         qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1742         s->bufptr++;
1743         s->max_size = qemu_chr_can_read(chr);
1744     }
1745 }
1746
1747 static void udp_chr_update_read_handler(CharDriverState *chr)
1748 {
1749     NetCharDriver *s = chr->opaque;
1750
1751     if (s->fd >= 0) {
1752         qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
1753                              udp_chr_read, NULL, chr);
1754     }
1755 }
1756
1757 static CharDriverState *qemu_chr_open_udp(const char *def)
1758 {
1759     CharDriverState *chr = NULL;
1760     NetCharDriver *s = NULL;
1761     int fd = -1;
1762     struct sockaddr_in saddr;
1763
1764     chr = qemu_mallocz(sizeof(CharDriverState));
1765     s = qemu_mallocz(sizeof(NetCharDriver));
1766
1767     fd = socket(PF_INET, SOCK_DGRAM, 0);
1768     if (fd < 0) {
1769         perror("socket(PF_INET, SOCK_DGRAM)");
1770         goto return_err;
1771     }
1772
1773     if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
1774         printf("Could not parse: %s\n", def);
1775         goto return_err;
1776     }
1777
1778     if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
1779     {
1780         perror("bind");
1781         goto return_err;
1782     }
1783
1784     s->fd = fd;
1785     s->bufcnt = 0;
1786     s->bufptr = 0;
1787     chr->opaque = s;
1788     chr->chr_write = udp_chr_write;
1789     chr->chr_update_read_handler = udp_chr_update_read_handler;
1790     return chr;
1791
1792 return_err:
1793     if (chr)
1794         free(chr);
1795     if (s)
1796         free(s);
1797     if (fd >= 0)
1798         closesocket(fd);
1799     return NULL;
1800 }
1801
1802 /***********************************************************/
1803 /* TCP Net console */
1804
1805 typedef struct {
1806     int fd, listen_fd;
1807     int connected;
1808     int max_size;
1809     int do_telnetopt;
1810     int do_nodelay;
1811     int is_unix;
1812 } TCPCharDriver;
1813
1814 static void tcp_chr_accept(void *opaque);
1815
1816 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1817 {
1818     TCPCharDriver *s = chr->opaque;
1819     if (s->connected) {
1820         return send_all(s->fd, buf, len);
1821     } else {
1822         /* XXX: indicate an error ? */
1823         return len;
1824     }
1825 }
1826
1827 static int tcp_chr_read_poll(void *opaque)
1828 {
1829     CharDriverState *chr = opaque;
1830     TCPCharDriver *s = chr->opaque;
1831     if (!s->connected)
1832         return 0;
1833     s->max_size = qemu_chr_can_read(chr);
1834     return s->max_size;
1835 }
1836
1837 #define IAC 255
1838 #define IAC_BREAK 243
1839 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
1840                                       TCPCharDriver *s,
1841                                       uint8_t *buf, int *size)
1842 {
1843     /* Handle any telnet client's basic IAC options to satisfy char by
1844      * char mode with no echo.  All IAC options will be removed from
1845      * the buf and the do_telnetopt variable will be used to track the
1846      * state of the width of the IAC information.
1847      *
1848      * IAC commands come in sets of 3 bytes with the exception of the
1849      * "IAC BREAK" command and the double IAC.
1850      */
1851
1852     int i;
1853     int j = 0;
1854
1855     for (i = 0; i < *size; i++) {
1856         if (s->do_telnetopt > 1) {
1857             if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
1858                 /* Double IAC means send an IAC */
1859                 if (j != i)
1860                     buf[j] = buf[i];
1861                 j++;
1862                 s->do_telnetopt = 1;
1863             } else {
1864                 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
1865                     /* Handle IAC break commands by sending a serial break */
1866                     qemu_chr_event(chr, CHR_EVENT_BREAK);
1867                     s->do_telnetopt++;
1868                 }
1869                 s->do_telnetopt++;
1870             }
1871             if (s->do_telnetopt >= 4) {
1872                 s->do_telnetopt = 1;
1873             }
1874         } else {
1875             if ((unsigned char)buf[i] == IAC) {
1876                 s->do_telnetopt = 2;
1877             } else {
1878                 if (j != i)
1879                     buf[j] = buf[i];
1880                 j++;
1881             }
1882         }
1883     }
1884     *size = j;
1885 }
1886
1887 static void tcp_chr_read(void *opaque)
1888 {
1889     CharDriverState *chr = opaque;
1890     TCPCharDriver *s = chr->opaque;
1891     uint8_t buf[1024];
1892     int len, size;
1893
1894     if (!s->connected || s->max_size <= 0)
1895         return;
1896     len = sizeof(buf);
1897     if (len > s->max_size)
1898         len = s->max_size;
1899     size = recv(s->fd, buf, len, 0);
1900     if (size == 0) {
1901         /* connection closed */
1902         s->connected = 0;
1903         if (s->listen_fd >= 0) {
1904             qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
1905         }
1906         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1907         closesocket(s->fd);
1908         s->fd = -1;
1909     } else if (size > 0) {
1910         if (s->do_telnetopt)
1911             tcp_chr_process_IAC_bytes(chr, s, buf, &size);
1912         if (size > 0)
1913             qemu_chr_read(chr, buf, size);
1914     }
1915 }
1916
1917 static void tcp_chr_connect(void *opaque)
1918 {
1919     CharDriverState *chr = opaque;
1920     TCPCharDriver *s = chr->opaque;
1921
1922     s->connected = 1;
1923     qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
1924                          tcp_chr_read, NULL, chr);
1925     qemu_chr_reset(chr);
1926 }
1927
1928 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
1929 static void tcp_chr_telnet_init(int fd)
1930 {
1931     char buf[3];
1932     /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
1933     IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
1934     send(fd, (char *)buf, 3, 0);
1935     IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
1936     send(fd, (char *)buf, 3, 0);
1937     IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
1938     send(fd, (char *)buf, 3, 0);
1939     IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
1940     send(fd, (char *)buf, 3, 0);
1941 }
1942
1943 static void socket_set_nodelay(int fd)
1944 {
1945     int val = 1;
1946     setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1947 }
1948
1949 static void tcp_chr_accept(void *opaque)
1950 {
1951     CharDriverState *chr = opaque;
1952     TCPCharDriver *s = chr->opaque;
1953     struct sockaddr_in saddr;
1954 #ifndef _WIN32
1955     struct sockaddr_un uaddr;
1956 #endif
1957     struct sockaddr *addr;
1958     socklen_t len;
1959     int fd;
1960
1961     for(;;) {
1962 #ifndef _WIN32
1963         if (s->is_unix) {
1964             len = sizeof(uaddr);
1965             addr = (struct sockaddr *)&uaddr;
1966         } else
1967 #endif
1968         {
1969             len = sizeof(saddr);
1970             addr = (struct sockaddr *)&saddr;
1971         }
1972         fd = accept(s->listen_fd, addr, &len);
1973         if (fd < 0 && errno != EINTR) {
1974             return;
1975         } else if (fd >= 0) {
1976             if (s->do_telnetopt)
1977                 tcp_chr_telnet_init(fd);
1978             break;
1979         }
1980     }
1981     socket_set_nonblock(fd);
1982     if (s->do_nodelay)
1983         socket_set_nodelay(fd);
1984     s->fd = fd;
1985     qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
1986     tcp_chr_connect(chr);
1987 }
1988
1989 static void tcp_chr_close(CharDriverState *chr)
1990 {
1991     TCPCharDriver *s = chr->opaque;
1992     if (s->fd >= 0)
1993         closesocket(s->fd);
1994     if (s->listen_fd >= 0)
1995         closesocket(s->listen_fd);
1996     qemu_free(s);
1997 }
1998
1999 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2000                                           int is_telnet,
2001                                           int is_unix)
2002 {
2003     CharDriverState *chr = NULL;
2004     TCPCharDriver *s = NULL;
2005     int fd = -1, offset = 0;
2006     int is_listen = 0;
2007     int is_waitconnect = 1;
2008     int do_nodelay = 0;
2009     const char *ptr;
2010
2011     ptr = host_str;
2012     while((ptr = strchr(ptr,','))) {
2013         ptr++;
2014         if (!strncmp(ptr,"server",6)) {
2015             is_listen = 1;
2016         } else if (!strncmp(ptr,"nowait",6)) {
2017             is_waitconnect = 0;
2018         } else if (!strncmp(ptr,"nodelay",6)) {
2019             do_nodelay = 1;
2020         } else if (!strncmp(ptr,"to=",3)) {
2021             /* nothing, inet_listen() parses this one */;
2022         } else if (!strncmp(ptr,"ipv4",4)) {
2023             /* nothing, inet_connect() and inet_listen() parse this one */;
2024         } else if (!strncmp(ptr,"ipv6",4)) {
2025             /* nothing, inet_connect() and inet_listen() parse this one */;
2026         } else {
2027             printf("Unknown option: %s\n", ptr);
2028             goto fail;
2029         }
2030     }
2031     if (!is_listen)
2032         is_waitconnect = 0;
2033
2034     chr = qemu_mallocz(sizeof(CharDriverState));
2035     s = qemu_mallocz(sizeof(TCPCharDriver));
2036
2037     if (is_listen) {
2038         chr->filename = qemu_malloc(256);
2039         if (is_unix) {
2040             pstrcpy(chr->filename, 256, "unix:");
2041         } else if (is_telnet) {
2042             pstrcpy(chr->filename, 256, "telnet:");
2043         } else {
2044             pstrcpy(chr->filename, 256, "tcp:");
2045         }
2046         offset = strlen(chr->filename);
2047     }
2048     if (is_unix) {
2049         if (is_listen) {
2050             fd = unix_listen(host_str, chr->filename + offset, 256 - offset);
2051         } else {
2052             fd = unix_connect(host_str);
2053         }
2054     } else {
2055         if (is_listen) {
2056             fd = inet_listen(host_str, chr->filename + offset, 256 - offset,
2057                              SOCK_STREAM, 0);
2058         } else {
2059             fd = inet_connect(host_str, SOCK_STREAM);
2060         }
2061     }
2062     if (fd < 0)
2063         goto fail;
2064
2065     if (!is_waitconnect)
2066         socket_set_nonblock(fd);
2067
2068     s->connected = 0;
2069     s->fd = -1;
2070     s->listen_fd = -1;
2071     s->is_unix = is_unix;
2072     s->do_nodelay = do_nodelay && !is_unix;
2073
2074     chr->opaque = s;
2075     chr->chr_write = tcp_chr_write;
2076     chr->chr_close = tcp_chr_close;
2077
2078     if (is_listen) {
2079         s->listen_fd = fd;
2080         qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2081         if (is_telnet)
2082             s->do_telnetopt = 1;
2083     } else {
2084         s->connected = 1;
2085         s->fd = fd;
2086         socket_set_nodelay(fd);
2087         tcp_chr_connect(chr);
2088     }
2089
2090     if (is_listen && is_waitconnect) {
2091         printf("QEMU waiting for connection on: %s\n",
2092                chr->filename ? chr->filename : host_str);
2093         tcp_chr_accept(chr);
2094         socket_set_nonblock(s->listen_fd);
2095     }
2096
2097     return chr;
2098  fail:
2099     if (fd >= 0)
2100         closesocket(fd);
2101     qemu_free(s);
2102     qemu_free(chr);
2103     return NULL;
2104 }
2105
2106 CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2107 {
2108     const char *p;
2109     CharDriverState *chr;
2110
2111     if (!strcmp(filename, "vc")) {
2112         chr = text_console_init(0);
2113     } else
2114     if (strstart(filename, "vc:", &p)) {
2115         chr = text_console_init(p);
2116     } else
2117     if (!strcmp(filename, "null")) {
2118         chr = qemu_chr_open_null();
2119     } else
2120     if (strstart(filename, "tcp:", &p)) {
2121         chr = qemu_chr_open_tcp(p, 0, 0);
2122     } else
2123     if (strstart(filename, "telnet:", &p)) {
2124         chr = qemu_chr_open_tcp(p, 1, 0);
2125     } else
2126     if (strstart(filename, "udp:", &p)) {
2127         chr = qemu_chr_open_udp(p);
2128     } else
2129     if (strstart(filename, "mon:", &p)) {
2130         chr = qemu_chr_open(label, p, NULL);
2131         if (chr) {
2132             chr = qemu_chr_open_mux(chr);
2133             monitor_init(chr, MONITOR_USE_READLINE);
2134         } else {
2135             printf("Unable to open driver: %s\n", p);
2136         }
2137     } else if (!strcmp(filename, "msmouse")) {
2138         chr = qemu_chr_open_msmouse();
2139     } else
2140 #ifndef _WIN32
2141     if (strstart(filename, "unix:", &p)) {
2142         chr = qemu_chr_open_tcp(p, 0, 1);
2143     } else if (strstart(filename, "file:", &p)) {
2144         chr = qemu_chr_open_file_out(p);
2145     } else if (strstart(filename, "pipe:", &p)) {
2146         chr = qemu_chr_open_pipe(p);
2147     } else if (!strcmp(filename, "pty")) {
2148         chr = qemu_chr_open_pty();
2149     } else if (!strcmp(filename, "stdio")) {
2150         chr = qemu_chr_open_stdio();
2151     } else
2152 #if defined(__linux__)
2153     if (strstart(filename, "/dev/parport", NULL)) {
2154         chr = qemu_chr_open_pp(filename);
2155     } else
2156 #elif defined(__FreeBSD__)
2157     if (strstart(filename, "/dev/ppi", NULL)) {
2158         chr = qemu_chr_open_pp(filename);
2159     } else
2160 #endif
2161 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2162     || defined(__NetBSD__) || defined(__OpenBSD__)
2163     if (strstart(filename, "/dev/", NULL)) {
2164         chr = qemu_chr_open_tty(filename);
2165     } else
2166 #endif
2167 #else /* !_WIN32 */
2168     if (strstart(filename, "COM", NULL)) {
2169         chr = qemu_chr_open_win(filename);
2170     } else
2171     if (strstart(filename, "pipe:", &p)) {
2172         chr = qemu_chr_open_win_pipe(p);
2173     } else
2174     if (strstart(filename, "con:", NULL)) {
2175         chr = qemu_chr_open_win_con(filename);
2176     } else
2177     if (strstart(filename, "file:", &p)) {
2178         chr = qemu_chr_open_win_file_out(p);
2179     } else
2180 #endif
2181 #ifdef CONFIG_BRLAPI
2182     if (!strcmp(filename, "braille")) {
2183         chr = chr_baum_init();
2184     } else
2185 #endif
2186     {
2187         chr = NULL;
2188     }
2189
2190     if (chr) {
2191         if (!chr->filename)
2192             chr->filename = qemu_strdup(filename);
2193         chr->init = init;
2194         chr->label = qemu_strdup(label);
2195         TAILQ_INSERT_TAIL(&chardevs, chr, next);
2196     }
2197     return chr;
2198 }
2199
2200 void qemu_chr_close(CharDriverState *chr)
2201 {
2202     TAILQ_REMOVE(&chardevs, chr, next);
2203     if (chr->chr_close)
2204         chr->chr_close(chr);
2205     qemu_free(chr->filename);
2206     qemu_free(chr->label);
2207     qemu_free(chr);
2208 }
2209
2210 void qemu_chr_info(Monitor *mon)
2211 {
2212     CharDriverState *chr;
2213
2214     TAILQ_FOREACH(chr, &chardevs, next) {
2215         monitor_printf(mon, "%s: filename=%s\n", chr->label, chr->filename);
2216     }
2217 }