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