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