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