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