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