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