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