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