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