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