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