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