net: Fix -net socket,listen (Jan Kiszka)
[qemu-kvm/fedora.git] / qemu-char.c
blob64d41d0d0377b0e79edfa42d15c464cd4a39b88b
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
24 #include "qemu-common.h"
25 #include "net.h"
26 #include "console.h"
27 #include "sysemu.h"
28 #include "qemu-timer.h"
29 #include "qemu-char.h"
30 #include "block.h"
31 #include "hw/usb.h"
32 #include "hw/baum.h"
33 #include "hw/msmouse.h"
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <signal.h>
38 #include <time.h>
39 #include <errno.h>
40 #include <sys/time.h>
41 #include <zlib.h>
43 #ifndef _WIN32
44 #include <sys/times.h>
45 #include <sys/wait.h>
46 #include <termios.h>
47 #include <sys/mman.h>
48 #include <sys/ioctl.h>
49 #include <sys/resource.h>
50 #include <sys/socket.h>
51 #include <netinet/in.h>
52 #include <net/if.h>
53 #ifdef __NetBSD__
54 #include <net/if_tap.h>
55 #endif
56 #ifdef __linux__
57 #include <linux/if_tun.h>
58 #endif
59 #include <arpa/inet.h>
60 #include <dirent.h>
61 #include <netdb.h>
62 #include <sys/select.h>
63 #ifdef _BSD
64 #include <sys/stat.h>
65 #ifdef __FreeBSD__
66 #include <libutil.h>
67 #include <dev/ppbus/ppi.h>
68 #include <dev/ppbus/ppbconf.h>
69 #else
70 #include <util.h>
71 #endif
72 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
73 #include <freebsd/stdlib.h>
74 #else
75 #ifdef __linux__
76 #include <pty.h>
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
99 #include "qemu_socket.h"
101 /***********************************************************/
102 /* character device */
104 static TAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
105 TAILQ_HEAD_INITIALIZER(chardevs);
106 static int initial_reset_issued;
108 static void qemu_chr_event(CharDriverState *s, int event)
110 if (!s->chr_event)
111 return;
112 s->chr_event(s->handler_opaque, event);
115 static void qemu_chr_reset_bh(void *opaque)
117 CharDriverState *s = opaque;
118 qemu_chr_event(s, CHR_EVENT_RESET);
119 qemu_bh_delete(s->bh);
120 s->bh = NULL;
123 void qemu_chr_reset(CharDriverState *s)
125 if (s->bh == NULL && initial_reset_issued) {
126 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
127 qemu_bh_schedule(s->bh);
131 void qemu_chr_initial_reset(void)
133 CharDriverState *chr;
135 initial_reset_issued = 1;
137 TAILQ_FOREACH(chr, &chardevs, next) {
138 qemu_chr_reset(chr);
142 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
144 return s->chr_write(s, buf, len);
147 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
149 if (!s->chr_ioctl)
150 return -ENOTSUP;
151 return s->chr_ioctl(s, cmd, arg);
154 int qemu_chr_can_read(CharDriverState *s)
156 if (!s->chr_can_read)
157 return 0;
158 return s->chr_can_read(s->handler_opaque);
161 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
163 s->chr_read(s->handler_opaque, buf, len);
166 void qemu_chr_accept_input(CharDriverState *s)
168 if (s->chr_accept_input)
169 s->chr_accept_input(s);
172 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
174 char buf[4096];
175 va_list ap;
176 va_start(ap, fmt);
177 vsnprintf(buf, sizeof(buf), fmt, ap);
178 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
179 va_end(ap);
182 void qemu_chr_send_event(CharDriverState *s, int event)
184 if (s->chr_send_event)
185 s->chr_send_event(s, event);
188 void qemu_chr_add_handlers(CharDriverState *s,
189 IOCanRWHandler *fd_can_read,
190 IOReadHandler *fd_read,
191 IOEventHandler *fd_event,
192 void *opaque)
194 s->chr_can_read = fd_can_read;
195 s->chr_read = fd_read;
196 s->chr_event = fd_event;
197 s->handler_opaque = opaque;
198 if (s->chr_update_read_handler)
199 s->chr_update_read_handler(s);
202 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
204 return len;
207 static CharDriverState *qemu_chr_open_null(void)
209 CharDriverState *chr;
211 chr = qemu_mallocz(sizeof(CharDriverState));
212 chr->chr_write = null_chr_write;
213 return chr;
216 /* MUX driver for serial I/O splitting */
217 static int term_timestamps;
218 static int64_t term_timestamps_start;
219 #define MAX_MUX 4
220 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
221 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
222 typedef struct {
223 IOCanRWHandler *chr_can_read[MAX_MUX];
224 IOReadHandler *chr_read[MAX_MUX];
225 IOEventHandler *chr_event[MAX_MUX];
226 void *ext_opaque[MAX_MUX];
227 CharDriverState *drv;
228 int mux_cnt;
229 int term_got_escape;
230 int max_size;
231 /* Intermediate input buffer allows to catch escape sequences even if the
232 currently active device is not accepting any input - but only until it
233 is full as well. */
234 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
235 int prod[MAX_MUX];
236 int cons[MAX_MUX];
237 } MuxDriver;
240 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
242 MuxDriver *d = chr->opaque;
243 int ret;
244 if (!term_timestamps) {
245 ret = d->drv->chr_write(d->drv, buf, len);
246 } else {
247 int i;
249 ret = 0;
250 for(i = 0; i < len; i++) {
251 ret += d->drv->chr_write(d->drv, buf+i, 1);
252 if (buf[i] == '\n') {
253 char buf1[64];
254 int64_t ti;
255 int secs;
257 ti = qemu_get_clock(rt_clock);
258 if (term_timestamps_start == -1)
259 term_timestamps_start = ti;
260 ti -= term_timestamps_start;
261 secs = ti / 1000;
262 snprintf(buf1, sizeof(buf1),
263 "[%02d:%02d:%02d.%03d] ",
264 secs / 3600,
265 (secs / 60) % 60,
266 secs % 60,
267 (int)(ti % 1000));
268 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
272 return ret;
275 static const char * const mux_help[] = {
276 "% h print this help\n\r",
277 "% x exit emulator\n\r",
278 "% s save disk data back to file (if -snapshot)\n\r",
279 "% t toggle console timestamps\n\r"
280 "% b send break (magic sysrq)\n\r",
281 "% c switch between console and monitor\n\r",
282 "% % sends %\n\r",
283 NULL
286 int term_escape_char = 0x01; /* ctrl-a is used for escape */
287 static void mux_print_help(CharDriverState *chr)
289 int i, j;
290 char ebuf[15] = "Escape-Char";
291 char cbuf[50] = "\n\r";
293 if (term_escape_char > 0 && term_escape_char < 26) {
294 snprintf(cbuf, sizeof(cbuf), "\n\r");
295 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
296 } else {
297 snprintf(cbuf, sizeof(cbuf),
298 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
299 term_escape_char);
301 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
302 for (i = 0; mux_help[i] != NULL; i++) {
303 for (j=0; mux_help[i][j] != '\0'; j++) {
304 if (mux_help[i][j] == '%')
305 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
306 else
307 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
312 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
314 if (d->term_got_escape) {
315 d->term_got_escape = 0;
316 if (ch == term_escape_char)
317 goto send_char;
318 switch(ch) {
319 case '?':
320 case 'h':
321 mux_print_help(chr);
322 break;
323 case 'x':
325 const char *term = "QEMU: Terminated\n\r";
326 chr->chr_write(chr,(uint8_t *)term,strlen(term));
327 exit(0);
328 break;
330 case 's':
332 int i;
333 for (i = 0; i < nb_drives; i++) {
334 bdrv_commit(drives_table[i].bdrv);
337 break;
338 case 'b':
339 qemu_chr_event(chr, CHR_EVENT_BREAK);
340 break;
341 case 'c':
342 /* Switch to the next registered device */
343 chr->focus++;
344 if (chr->focus >= d->mux_cnt)
345 chr->focus = 0;
346 break;
347 case 't':
348 term_timestamps = !term_timestamps;
349 term_timestamps_start = -1;
350 break;
352 } else if (ch == term_escape_char) {
353 d->term_got_escape = 1;
354 } else {
355 send_char:
356 return 1;
358 return 0;
361 static void mux_chr_accept_input(CharDriverState *chr)
363 int m = chr->focus;
364 MuxDriver *d = chr->opaque;
366 while (d->prod[m] != d->cons[m] &&
367 d->chr_can_read[m] &&
368 d->chr_can_read[m](d->ext_opaque[m])) {
369 d->chr_read[m](d->ext_opaque[m],
370 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
374 static int mux_chr_can_read(void *opaque)
376 CharDriverState *chr = opaque;
377 MuxDriver *d = chr->opaque;
378 int m = chr->focus;
380 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
381 return 1;
382 if (d->chr_can_read[m])
383 return d->chr_can_read[m](d->ext_opaque[m]);
384 return 0;
387 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
389 CharDriverState *chr = opaque;
390 MuxDriver *d = chr->opaque;
391 int m = chr->focus;
392 int i;
394 mux_chr_accept_input (opaque);
396 for(i = 0; i < size; i++)
397 if (mux_proc_byte(chr, d, buf[i])) {
398 if (d->prod[m] == d->cons[m] &&
399 d->chr_can_read[m] &&
400 d->chr_can_read[m](d->ext_opaque[m]))
401 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
402 else
403 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
407 static void mux_chr_event(void *opaque, int event)
409 CharDriverState *chr = opaque;
410 MuxDriver *d = chr->opaque;
411 int i;
413 /* Send the event to all registered listeners */
414 for (i = 0; i < d->mux_cnt; i++)
415 if (d->chr_event[i])
416 d->chr_event[i](d->ext_opaque[i], event);
419 static void mux_chr_update_read_handler(CharDriverState *chr)
421 MuxDriver *d = chr->opaque;
423 if (d->mux_cnt >= MAX_MUX) {
424 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
425 return;
427 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
428 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
429 d->chr_read[d->mux_cnt] = chr->chr_read;
430 d->chr_event[d->mux_cnt] = chr->chr_event;
431 /* Fix up the real driver with mux routines */
432 if (d->mux_cnt == 0) {
433 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
434 mux_chr_event, chr);
436 chr->focus = d->mux_cnt;
437 d->mux_cnt++;
440 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
442 CharDriverState *chr;
443 MuxDriver *d;
445 chr = qemu_mallocz(sizeof(CharDriverState));
446 d = qemu_mallocz(sizeof(MuxDriver));
448 chr->opaque = d;
449 d->drv = drv;
450 chr->focus = -1;
451 chr->chr_write = mux_chr_write;
452 chr->chr_update_read_handler = mux_chr_update_read_handler;
453 chr->chr_accept_input = mux_chr_accept_input;
454 return chr;
458 #ifdef _WIN32
459 int send_all(int fd, const void *buf, int len1)
461 int ret, len;
463 len = len1;
464 while (len > 0) {
465 ret = send(fd, buf, len, 0);
466 if (ret < 0) {
467 errno = WSAGetLastError();
468 if (errno != WSAEWOULDBLOCK) {
469 return -1;
471 } else if (ret == 0) {
472 break;
473 } else {
474 buf += ret;
475 len -= ret;
478 return len1 - len;
481 #else
483 static int unix_write(int fd, const uint8_t *buf, int len1)
485 int ret, len;
487 len = len1;
488 while (len > 0) {
489 ret = write(fd, buf, len);
490 if (ret < 0) {
491 if (errno != EINTR && errno != EAGAIN)
492 return -1;
493 } else if (ret == 0) {
494 break;
495 } else {
496 buf += ret;
497 len -= ret;
500 return len1 - len;
503 int send_all(int fd, const void *buf, int len1)
505 return unix_write(fd, buf, len1);
507 #endif /* !_WIN32 */
509 #ifndef _WIN32
511 typedef struct {
512 int fd_in, fd_out;
513 int max_size;
514 } FDCharDriver;
516 #define STDIO_MAX_CLIENTS 1
517 static int stdio_nb_clients = 0;
519 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
521 FDCharDriver *s = chr->opaque;
522 return send_all(s->fd_out, buf, len);
525 static int fd_chr_read_poll(void *opaque)
527 CharDriverState *chr = opaque;
528 FDCharDriver *s = chr->opaque;
530 s->max_size = qemu_chr_can_read(chr);
531 return s->max_size;
534 static void fd_chr_read(void *opaque)
536 CharDriverState *chr = opaque;
537 FDCharDriver *s = chr->opaque;
538 int size, len;
539 uint8_t buf[1024];
541 len = sizeof(buf);
542 if (len > s->max_size)
543 len = s->max_size;
544 if (len == 0)
545 return;
546 size = read(s->fd_in, buf, len);
547 if (size == 0) {
548 /* FD has been closed. Remove it from the active list. */
549 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
550 return;
552 if (size > 0) {
553 qemu_chr_read(chr, buf, size);
557 static void fd_chr_update_read_handler(CharDriverState *chr)
559 FDCharDriver *s = chr->opaque;
561 if (s->fd_in >= 0) {
562 if (nographic && s->fd_in == 0) {
563 } else {
564 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
565 fd_chr_read, NULL, chr);
570 static void fd_chr_close(struct CharDriverState *chr)
572 FDCharDriver *s = chr->opaque;
574 if (s->fd_in >= 0) {
575 if (nographic && s->fd_in == 0) {
576 } else {
577 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
581 qemu_free(s);
584 /* open a character device to a unix fd */
585 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
587 CharDriverState *chr;
588 FDCharDriver *s;
590 chr = qemu_mallocz(sizeof(CharDriverState));
591 s = qemu_mallocz(sizeof(FDCharDriver));
592 s->fd_in = fd_in;
593 s->fd_out = fd_out;
594 chr->opaque = s;
595 chr->chr_write = fd_chr_write;
596 chr->chr_update_read_handler = fd_chr_update_read_handler;
597 chr->chr_close = fd_chr_close;
599 qemu_chr_reset(chr);
601 return chr;
604 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
606 int fd_out;
608 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
609 if (fd_out < 0)
610 return NULL;
611 return qemu_chr_open_fd(-1, fd_out);
614 static CharDriverState *qemu_chr_open_pipe(const char *filename)
616 int fd_in, fd_out;
617 char filename_in[256], filename_out[256];
619 snprintf(filename_in, 256, "%s.in", filename);
620 snprintf(filename_out, 256, "%s.out", filename);
621 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
622 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
623 if (fd_in < 0 || fd_out < 0) {
624 if (fd_in >= 0)
625 close(fd_in);
626 if (fd_out >= 0)
627 close(fd_out);
628 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
629 if (fd_in < 0)
630 return NULL;
632 return qemu_chr_open_fd(fd_in, fd_out);
636 /* for STDIO, we handle the case where several clients use it
637 (nographic mode) */
639 #define TERM_FIFO_MAX_SIZE 1
641 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
642 static int term_fifo_size;
644 static int stdio_read_poll(void *opaque)
646 CharDriverState *chr = opaque;
648 /* try to flush the queue if needed */
649 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
650 qemu_chr_read(chr, term_fifo, 1);
651 term_fifo_size = 0;
653 /* see if we can absorb more chars */
654 if (term_fifo_size == 0)
655 return 1;
656 else
657 return 0;
660 static void stdio_read(void *opaque)
662 int size;
663 uint8_t buf[1];
664 CharDriverState *chr = opaque;
666 size = read(0, buf, 1);
667 if (size == 0) {
668 /* stdin has been closed. Remove it from the active list. */
669 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
670 return;
672 if (size > 0) {
673 if (qemu_chr_can_read(chr) > 0) {
674 qemu_chr_read(chr, buf, 1);
675 } else if (term_fifo_size == 0) {
676 term_fifo[term_fifo_size++] = buf[0];
681 /* init terminal so that we can grab keys */
682 static struct termios oldtty;
683 static int old_fd0_flags;
684 static int term_atexit_done;
686 static void term_exit(void)
688 tcsetattr (0, TCSANOW, &oldtty);
689 fcntl(0, F_SETFL, old_fd0_flags);
692 static void term_init(void)
694 struct termios tty;
696 tcgetattr (0, &tty);
697 oldtty = tty;
698 old_fd0_flags = fcntl(0, F_GETFL);
700 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
701 |INLCR|IGNCR|ICRNL|IXON);
702 tty.c_oflag |= OPOST;
703 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
704 /* if graphical mode, we allow Ctrl-C handling */
705 if (nographic)
706 tty.c_lflag &= ~ISIG;
707 tty.c_cflag &= ~(CSIZE|PARENB);
708 tty.c_cflag |= CS8;
709 tty.c_cc[VMIN] = 1;
710 tty.c_cc[VTIME] = 0;
712 tcsetattr (0, TCSANOW, &tty);
714 if (!term_atexit_done++)
715 atexit(term_exit);
717 fcntl(0, F_SETFL, O_NONBLOCK);
720 static void qemu_chr_close_stdio(struct CharDriverState *chr)
722 term_exit();
723 stdio_nb_clients--;
724 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
725 fd_chr_close(chr);
728 static CharDriverState *qemu_chr_open_stdio(void)
730 CharDriverState *chr;
732 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
733 return NULL;
734 chr = qemu_chr_open_fd(0, 1);
735 chr->chr_close = qemu_chr_close_stdio;
736 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
737 stdio_nb_clients++;
738 term_init();
740 return chr;
743 #ifdef __sun__
744 /* Once Solaris has openpty(), this is going to be removed. */
745 int openpty(int *amaster, int *aslave, char *name,
746 struct termios *termp, struct winsize *winp)
748 const char *slave;
749 int mfd = -1, sfd = -1;
751 *amaster = *aslave = -1;
753 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
754 if (mfd < 0)
755 goto err;
757 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
758 goto err;
760 if ((slave = ptsname(mfd)) == NULL)
761 goto err;
763 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
764 goto err;
766 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
767 (termp != NULL && tcgetattr(sfd, termp) < 0))
768 goto err;
770 if (amaster)
771 *amaster = mfd;
772 if (aslave)
773 *aslave = sfd;
774 if (winp)
775 ioctl(sfd, TIOCSWINSZ, winp);
777 return 0;
779 err:
780 if (sfd != -1)
781 close(sfd);
782 close(mfd);
783 return -1;
786 void cfmakeraw (struct termios *termios_p)
788 termios_p->c_iflag &=
789 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
790 termios_p->c_oflag &= ~OPOST;
791 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
792 termios_p->c_cflag &= ~(CSIZE|PARENB);
793 termios_p->c_cflag |= CS8;
795 termios_p->c_cc[VMIN] = 0;
796 termios_p->c_cc[VTIME] = 0;
798 #endif
800 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
801 || defined(__NetBSD__) || defined(__OpenBSD__)
803 typedef struct {
804 int fd;
805 int connected;
806 int polling;
807 int read_bytes;
808 QEMUTimer *timer;
809 } PtyCharDriver;
811 static void pty_chr_update_read_handler(CharDriverState *chr);
812 static void pty_chr_state(CharDriverState *chr, int connected);
814 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
816 PtyCharDriver *s = chr->opaque;
818 if (!s->connected) {
819 /* guest sends data, check for (re-)connect */
820 pty_chr_update_read_handler(chr);
821 return 0;
823 return send_all(s->fd, buf, len);
826 static int pty_chr_read_poll(void *opaque)
828 CharDriverState *chr = opaque;
829 PtyCharDriver *s = chr->opaque;
831 s->read_bytes = qemu_chr_can_read(chr);
832 return s->read_bytes;
835 static void pty_chr_read(void *opaque)
837 CharDriverState *chr = opaque;
838 PtyCharDriver *s = chr->opaque;
839 int size, len;
840 uint8_t buf[1024];
842 len = sizeof(buf);
843 if (len > s->read_bytes)
844 len = s->read_bytes;
845 if (len == 0)
846 return;
847 size = read(s->fd, buf, len);
848 if ((size == -1 && errno == EIO) ||
849 (size == 0)) {
850 pty_chr_state(chr, 0);
851 return;
853 if (size > 0) {
854 pty_chr_state(chr, 1);
855 qemu_chr_read(chr, buf, size);
859 static void pty_chr_update_read_handler(CharDriverState *chr)
861 PtyCharDriver *s = chr->opaque;
863 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
864 pty_chr_read, NULL, chr);
865 s->polling = 1;
867 * Short timeout here: just need wait long enougth that qemu makes
868 * it through the poll loop once. When reconnected we want a
869 * short timeout so we notice it almost instantly. Otherwise
870 * read() gives us -EIO instantly, making pty_chr_state() reset the
871 * timeout to the normal (much longer) poll interval before the
872 * timer triggers.
874 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
877 static void pty_chr_state(CharDriverState *chr, int connected)
879 PtyCharDriver *s = chr->opaque;
881 if (!connected) {
882 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
883 s->connected = 0;
884 s->polling = 0;
885 /* (re-)connect poll interval for idle guests: once per second.
886 * We check more frequently in case the guests sends data to
887 * the virtual device linked to our pty. */
888 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
889 } else {
890 if (!s->connected)
891 qemu_chr_reset(chr);
892 s->connected = 1;
896 static void pty_chr_timer(void *opaque)
898 struct CharDriverState *chr = opaque;
899 PtyCharDriver *s = chr->opaque;
901 if (s->connected)
902 return;
903 if (s->polling) {
904 /* If we arrive here without polling being cleared due
905 * read returning -EIO, then we are (re-)connected */
906 pty_chr_state(chr, 1);
907 return;
910 /* Next poll ... */
911 pty_chr_update_read_handler(chr);
914 static void pty_chr_close(struct CharDriverState *chr)
916 PtyCharDriver *s = chr->opaque;
918 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
919 close(s->fd);
920 qemu_del_timer(s->timer);
921 qemu_free_timer(s->timer);
922 qemu_free(s);
925 static CharDriverState *qemu_chr_open_pty(void)
927 CharDriverState *chr;
928 PtyCharDriver *s;
929 struct termios tty;
930 int slave_fd, len;
931 #if defined(__OpenBSD__)
932 char pty_name[PATH_MAX];
933 #define q_ptsname(x) pty_name
934 #else
935 char *pty_name = NULL;
936 #define q_ptsname(x) ptsname(x)
937 #endif
939 chr = qemu_mallocz(sizeof(CharDriverState));
940 s = qemu_mallocz(sizeof(PtyCharDriver));
942 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
943 return NULL;
946 /* Set raw attributes on the pty. */
947 tcgetattr(slave_fd, &tty);
948 cfmakeraw(&tty);
949 tcsetattr(slave_fd, TCSAFLUSH, &tty);
950 close(slave_fd);
952 len = strlen(q_ptsname(s->fd)) + 5;
953 chr->filename = qemu_malloc(len);
954 snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
955 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
957 chr->opaque = s;
958 chr->chr_write = pty_chr_write;
959 chr->chr_update_read_handler = pty_chr_update_read_handler;
960 chr->chr_close = pty_chr_close;
962 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
964 return chr;
967 static void tty_serial_init(int fd, int speed,
968 int parity, int data_bits, int stop_bits)
970 struct termios tty;
971 speed_t spd;
973 #if 0
974 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
975 speed, parity, data_bits, stop_bits);
976 #endif
977 tcgetattr (fd, &tty);
979 #define MARGIN 1.1
980 if (speed <= 50 * MARGIN)
981 spd = B50;
982 else if (speed <= 75 * MARGIN)
983 spd = B75;
984 else if (speed <= 300 * MARGIN)
985 spd = B300;
986 else if (speed <= 600 * MARGIN)
987 spd = B600;
988 else if (speed <= 1200 * MARGIN)
989 spd = B1200;
990 else if (speed <= 2400 * MARGIN)
991 spd = B2400;
992 else if (speed <= 4800 * MARGIN)
993 spd = B4800;
994 else if (speed <= 9600 * MARGIN)
995 spd = B9600;
996 else if (speed <= 19200 * MARGIN)
997 spd = B19200;
998 else if (speed <= 38400 * MARGIN)
999 spd = B38400;
1000 else if (speed <= 57600 * MARGIN)
1001 spd = B57600;
1002 else if (speed <= 115200 * MARGIN)
1003 spd = B115200;
1004 else
1005 spd = B115200;
1007 cfsetispeed(&tty, spd);
1008 cfsetospeed(&tty, spd);
1010 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1011 |INLCR|IGNCR|ICRNL|IXON);
1012 tty.c_oflag |= OPOST;
1013 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1014 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1015 switch(data_bits) {
1016 default:
1017 case 8:
1018 tty.c_cflag |= CS8;
1019 break;
1020 case 7:
1021 tty.c_cflag |= CS7;
1022 break;
1023 case 6:
1024 tty.c_cflag |= CS6;
1025 break;
1026 case 5:
1027 tty.c_cflag |= CS5;
1028 break;
1030 switch(parity) {
1031 default:
1032 case 'N':
1033 break;
1034 case 'E':
1035 tty.c_cflag |= PARENB;
1036 break;
1037 case 'O':
1038 tty.c_cflag |= PARENB | PARODD;
1039 break;
1041 if (stop_bits == 2)
1042 tty.c_cflag |= CSTOPB;
1044 tcsetattr (fd, TCSANOW, &tty);
1047 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1049 FDCharDriver *s = chr->opaque;
1051 switch(cmd) {
1052 case CHR_IOCTL_SERIAL_SET_PARAMS:
1054 QEMUSerialSetParams *ssp = arg;
1055 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1056 ssp->data_bits, ssp->stop_bits);
1058 break;
1059 case CHR_IOCTL_SERIAL_SET_BREAK:
1061 int enable = *(int *)arg;
1062 if (enable)
1063 tcsendbreak(s->fd_in, 1);
1065 break;
1066 case CHR_IOCTL_SERIAL_GET_TIOCM:
1068 int sarg = 0;
1069 int *targ = (int *)arg;
1070 ioctl(s->fd_in, TIOCMGET, &sarg);
1071 *targ = 0;
1072 if (sarg & TIOCM_CTS)
1073 *targ |= CHR_TIOCM_CTS;
1074 if (sarg & TIOCM_CAR)
1075 *targ |= CHR_TIOCM_CAR;
1076 if (sarg & TIOCM_DSR)
1077 *targ |= CHR_TIOCM_DSR;
1078 if (sarg & TIOCM_RI)
1079 *targ |= CHR_TIOCM_RI;
1080 if (sarg & TIOCM_DTR)
1081 *targ |= CHR_TIOCM_DTR;
1082 if (sarg & TIOCM_RTS)
1083 *targ |= CHR_TIOCM_RTS;
1085 break;
1086 case CHR_IOCTL_SERIAL_SET_TIOCM:
1088 int sarg = *(int *)arg;
1089 int targ = 0;
1090 ioctl(s->fd_in, TIOCMGET, &targ);
1091 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1092 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1093 if (sarg & CHR_TIOCM_CTS)
1094 targ |= TIOCM_CTS;
1095 if (sarg & CHR_TIOCM_CAR)
1096 targ |= TIOCM_CAR;
1097 if (sarg & CHR_TIOCM_DSR)
1098 targ |= TIOCM_DSR;
1099 if (sarg & CHR_TIOCM_RI)
1100 targ |= TIOCM_RI;
1101 if (sarg & CHR_TIOCM_DTR)
1102 targ |= TIOCM_DTR;
1103 if (sarg & CHR_TIOCM_RTS)
1104 targ |= TIOCM_RTS;
1105 ioctl(s->fd_in, TIOCMSET, &targ);
1107 break;
1108 default:
1109 return -ENOTSUP;
1111 return 0;
1114 static CharDriverState *qemu_chr_open_tty(const char *filename)
1116 CharDriverState *chr;
1117 int fd;
1119 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
1120 tty_serial_init(fd, 115200, 'N', 8, 1);
1121 chr = qemu_chr_open_fd(fd, fd);
1122 if (!chr) {
1123 close(fd);
1124 return NULL;
1126 chr->chr_ioctl = tty_serial_ioctl;
1127 qemu_chr_reset(chr);
1128 return chr;
1130 #else /* ! __linux__ && ! __sun__ */
1131 static CharDriverState *qemu_chr_open_pty(void)
1133 return NULL;
1135 #endif /* __linux__ || __sun__ */
1137 #if defined(__linux__)
1138 typedef struct {
1139 int fd;
1140 int mode;
1141 } ParallelCharDriver;
1143 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1145 if (s->mode != mode) {
1146 int m = mode;
1147 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1148 return 0;
1149 s->mode = mode;
1151 return 1;
1154 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1156 ParallelCharDriver *drv = chr->opaque;
1157 int fd = drv->fd;
1158 uint8_t b;
1160 switch(cmd) {
1161 case CHR_IOCTL_PP_READ_DATA:
1162 if (ioctl(fd, PPRDATA, &b) < 0)
1163 return -ENOTSUP;
1164 *(uint8_t *)arg = b;
1165 break;
1166 case CHR_IOCTL_PP_WRITE_DATA:
1167 b = *(uint8_t *)arg;
1168 if (ioctl(fd, PPWDATA, &b) < 0)
1169 return -ENOTSUP;
1170 break;
1171 case CHR_IOCTL_PP_READ_CONTROL:
1172 if (ioctl(fd, PPRCONTROL, &b) < 0)
1173 return -ENOTSUP;
1174 /* Linux gives only the lowest bits, and no way to know data
1175 direction! For better compatibility set the fixed upper
1176 bits. */
1177 *(uint8_t *)arg = b | 0xc0;
1178 break;
1179 case CHR_IOCTL_PP_WRITE_CONTROL:
1180 b = *(uint8_t *)arg;
1181 if (ioctl(fd, PPWCONTROL, &b) < 0)
1182 return -ENOTSUP;
1183 break;
1184 case CHR_IOCTL_PP_READ_STATUS:
1185 if (ioctl(fd, PPRSTATUS, &b) < 0)
1186 return -ENOTSUP;
1187 *(uint8_t *)arg = b;
1188 break;
1189 case CHR_IOCTL_PP_DATA_DIR:
1190 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1191 return -ENOTSUP;
1192 break;
1193 case CHR_IOCTL_PP_EPP_READ_ADDR:
1194 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1195 struct ParallelIOArg *parg = arg;
1196 int n = read(fd, parg->buffer, parg->count);
1197 if (n != parg->count) {
1198 return -EIO;
1201 break;
1202 case CHR_IOCTL_PP_EPP_READ:
1203 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1204 struct ParallelIOArg *parg = arg;
1205 int n = read(fd, parg->buffer, parg->count);
1206 if (n != parg->count) {
1207 return -EIO;
1210 break;
1211 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1212 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1213 struct ParallelIOArg *parg = arg;
1214 int n = write(fd, parg->buffer, parg->count);
1215 if (n != parg->count) {
1216 return -EIO;
1219 break;
1220 case CHR_IOCTL_PP_EPP_WRITE:
1221 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1222 struct ParallelIOArg *parg = arg;
1223 int n = write(fd, parg->buffer, parg->count);
1224 if (n != parg->count) {
1225 return -EIO;
1228 break;
1229 default:
1230 return -ENOTSUP;
1232 return 0;
1235 static void pp_close(CharDriverState *chr)
1237 ParallelCharDriver *drv = chr->opaque;
1238 int fd = drv->fd;
1240 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1241 ioctl(fd, PPRELEASE);
1242 close(fd);
1243 qemu_free(drv);
1246 static CharDriverState *qemu_chr_open_pp(const char *filename)
1248 CharDriverState *chr;
1249 ParallelCharDriver *drv;
1250 int fd;
1252 TFR(fd = open(filename, O_RDWR));
1253 if (fd < 0)
1254 return NULL;
1256 if (ioctl(fd, PPCLAIM) < 0) {
1257 close(fd);
1258 return NULL;
1261 drv = qemu_mallocz(sizeof(ParallelCharDriver));
1262 drv->fd = fd;
1263 drv->mode = IEEE1284_MODE_COMPAT;
1265 chr = qemu_mallocz(sizeof(CharDriverState));
1266 chr->chr_write = null_chr_write;
1267 chr->chr_ioctl = pp_ioctl;
1268 chr->chr_close = pp_close;
1269 chr->opaque = drv;
1271 qemu_chr_reset(chr);
1273 return chr;
1275 #endif /* __linux__ */
1277 #if defined(__FreeBSD__)
1278 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1280 int fd = (int)chr->opaque;
1281 uint8_t b;
1283 switch(cmd) {
1284 case CHR_IOCTL_PP_READ_DATA:
1285 if (ioctl(fd, PPIGDATA, &b) < 0)
1286 return -ENOTSUP;
1287 *(uint8_t *)arg = b;
1288 break;
1289 case CHR_IOCTL_PP_WRITE_DATA:
1290 b = *(uint8_t *)arg;
1291 if (ioctl(fd, PPISDATA, &b) < 0)
1292 return -ENOTSUP;
1293 break;
1294 case CHR_IOCTL_PP_READ_CONTROL:
1295 if (ioctl(fd, PPIGCTRL, &b) < 0)
1296 return -ENOTSUP;
1297 *(uint8_t *)arg = b;
1298 break;
1299 case CHR_IOCTL_PP_WRITE_CONTROL:
1300 b = *(uint8_t *)arg;
1301 if (ioctl(fd, PPISCTRL, &b) < 0)
1302 return -ENOTSUP;
1303 break;
1304 case CHR_IOCTL_PP_READ_STATUS:
1305 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1306 return -ENOTSUP;
1307 *(uint8_t *)arg = b;
1308 break;
1309 default:
1310 return -ENOTSUP;
1312 return 0;
1315 static CharDriverState *qemu_chr_open_pp(const char *filename)
1317 CharDriverState *chr;
1318 int fd;
1320 fd = open(filename, O_RDWR);
1321 if (fd < 0)
1322 return NULL;
1324 chr = qemu_mallocz(sizeof(CharDriverState));
1325 chr->opaque = (void *)fd;
1326 chr->chr_write = null_chr_write;
1327 chr->chr_ioctl = pp_ioctl;
1328 return chr;
1330 #endif
1332 #else /* _WIN32 */
1334 typedef struct {
1335 int max_size;
1336 HANDLE hcom, hrecv, hsend;
1337 OVERLAPPED orecv, osend;
1338 BOOL fpipe;
1339 DWORD len;
1340 } WinCharState;
1342 #define NSENDBUF 2048
1343 #define NRECVBUF 2048
1344 #define MAXCONNECT 1
1345 #define NTIMEOUT 5000
1347 static int win_chr_poll(void *opaque);
1348 static int win_chr_pipe_poll(void *opaque);
1350 static void win_chr_close(CharDriverState *chr)
1352 WinCharState *s = chr->opaque;
1354 if (s->hsend) {
1355 CloseHandle(s->hsend);
1356 s->hsend = NULL;
1358 if (s->hrecv) {
1359 CloseHandle(s->hrecv);
1360 s->hrecv = NULL;
1362 if (s->hcom) {
1363 CloseHandle(s->hcom);
1364 s->hcom = NULL;
1366 if (s->fpipe)
1367 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1368 else
1369 qemu_del_polling_cb(win_chr_poll, chr);
1372 static int win_chr_init(CharDriverState *chr, const char *filename)
1374 WinCharState *s = chr->opaque;
1375 COMMCONFIG comcfg;
1376 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1377 COMSTAT comstat;
1378 DWORD size;
1379 DWORD err;
1381 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1382 if (!s->hsend) {
1383 fprintf(stderr, "Failed CreateEvent\n");
1384 goto fail;
1386 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1387 if (!s->hrecv) {
1388 fprintf(stderr, "Failed CreateEvent\n");
1389 goto fail;
1392 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1393 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1394 if (s->hcom == INVALID_HANDLE_VALUE) {
1395 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1396 s->hcom = NULL;
1397 goto fail;
1400 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1401 fprintf(stderr, "Failed SetupComm\n");
1402 goto fail;
1405 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1406 size = sizeof(COMMCONFIG);
1407 GetDefaultCommConfig(filename, &comcfg, &size);
1408 comcfg.dcb.DCBlength = sizeof(DCB);
1409 CommConfigDialog(filename, NULL, &comcfg);
1411 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1412 fprintf(stderr, "Failed SetCommState\n");
1413 goto fail;
1416 if (!SetCommMask(s->hcom, EV_ERR)) {
1417 fprintf(stderr, "Failed SetCommMask\n");
1418 goto fail;
1421 cto.ReadIntervalTimeout = MAXDWORD;
1422 if (!SetCommTimeouts(s->hcom, &cto)) {
1423 fprintf(stderr, "Failed SetCommTimeouts\n");
1424 goto fail;
1427 if (!ClearCommError(s->hcom, &err, &comstat)) {
1428 fprintf(stderr, "Failed ClearCommError\n");
1429 goto fail;
1431 qemu_add_polling_cb(win_chr_poll, chr);
1432 return 0;
1434 fail:
1435 win_chr_close(chr);
1436 return -1;
1439 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1441 WinCharState *s = chr->opaque;
1442 DWORD len, ret, size, err;
1444 len = len1;
1445 ZeroMemory(&s->osend, sizeof(s->osend));
1446 s->osend.hEvent = s->hsend;
1447 while (len > 0) {
1448 if (s->hsend)
1449 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1450 else
1451 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1452 if (!ret) {
1453 err = GetLastError();
1454 if (err == ERROR_IO_PENDING) {
1455 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1456 if (ret) {
1457 buf += size;
1458 len -= size;
1459 } else {
1460 break;
1462 } else {
1463 break;
1465 } else {
1466 buf += size;
1467 len -= size;
1470 return len1 - len;
1473 static int win_chr_read_poll(CharDriverState *chr)
1475 WinCharState *s = chr->opaque;
1477 s->max_size = qemu_chr_can_read(chr);
1478 return s->max_size;
1481 static void win_chr_readfile(CharDriverState *chr)
1483 WinCharState *s = chr->opaque;
1484 int ret, err;
1485 uint8_t buf[1024];
1486 DWORD size;
1488 ZeroMemory(&s->orecv, sizeof(s->orecv));
1489 s->orecv.hEvent = s->hrecv;
1490 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1491 if (!ret) {
1492 err = GetLastError();
1493 if (err == ERROR_IO_PENDING) {
1494 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1498 if (size > 0) {
1499 qemu_chr_read(chr, buf, size);
1503 static void win_chr_read(CharDriverState *chr)
1505 WinCharState *s = chr->opaque;
1507 if (s->len > s->max_size)
1508 s->len = s->max_size;
1509 if (s->len == 0)
1510 return;
1512 win_chr_readfile(chr);
1515 static int win_chr_poll(void *opaque)
1517 CharDriverState *chr = opaque;
1518 WinCharState *s = chr->opaque;
1519 COMSTAT status;
1520 DWORD comerr;
1522 ClearCommError(s->hcom, &comerr, &status);
1523 if (status.cbInQue > 0) {
1524 s->len = status.cbInQue;
1525 win_chr_read_poll(chr);
1526 win_chr_read(chr);
1527 return 1;
1529 return 0;
1532 static CharDriverState *qemu_chr_open_win(const char *filename)
1534 CharDriverState *chr;
1535 WinCharState *s;
1537 chr = qemu_mallocz(sizeof(CharDriverState));
1538 s = qemu_mallocz(sizeof(WinCharState));
1539 chr->opaque = s;
1540 chr->chr_write = win_chr_write;
1541 chr->chr_close = win_chr_close;
1543 if (win_chr_init(chr, filename) < 0) {
1544 free(s);
1545 free(chr);
1546 return NULL;
1548 qemu_chr_reset(chr);
1549 return chr;
1552 static int win_chr_pipe_poll(void *opaque)
1554 CharDriverState *chr = opaque;
1555 WinCharState *s = chr->opaque;
1556 DWORD size;
1558 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1559 if (size > 0) {
1560 s->len = size;
1561 win_chr_read_poll(chr);
1562 win_chr_read(chr);
1563 return 1;
1565 return 0;
1568 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1570 WinCharState *s = chr->opaque;
1571 OVERLAPPED ov;
1572 int ret;
1573 DWORD size;
1574 char openname[256];
1576 s->fpipe = TRUE;
1578 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1579 if (!s->hsend) {
1580 fprintf(stderr, "Failed CreateEvent\n");
1581 goto fail;
1583 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1584 if (!s->hrecv) {
1585 fprintf(stderr, "Failed CreateEvent\n");
1586 goto fail;
1589 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1590 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1591 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1592 PIPE_WAIT,
1593 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1594 if (s->hcom == INVALID_HANDLE_VALUE) {
1595 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1596 s->hcom = NULL;
1597 goto fail;
1600 ZeroMemory(&ov, sizeof(ov));
1601 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1602 ret = ConnectNamedPipe(s->hcom, &ov);
1603 if (ret) {
1604 fprintf(stderr, "Failed ConnectNamedPipe\n");
1605 goto fail;
1608 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1609 if (!ret) {
1610 fprintf(stderr, "Failed GetOverlappedResult\n");
1611 if (ov.hEvent) {
1612 CloseHandle(ov.hEvent);
1613 ov.hEvent = NULL;
1615 goto fail;
1618 if (ov.hEvent) {
1619 CloseHandle(ov.hEvent);
1620 ov.hEvent = NULL;
1622 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1623 return 0;
1625 fail:
1626 win_chr_close(chr);
1627 return -1;
1631 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
1633 CharDriverState *chr;
1634 WinCharState *s;
1636 chr = qemu_mallocz(sizeof(CharDriverState));
1637 s = qemu_mallocz(sizeof(WinCharState));
1638 chr->opaque = s;
1639 chr->chr_write = win_chr_write;
1640 chr->chr_close = win_chr_close;
1642 if (win_chr_pipe_init(chr, filename) < 0) {
1643 free(s);
1644 free(chr);
1645 return NULL;
1647 qemu_chr_reset(chr);
1648 return chr;
1651 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1653 CharDriverState *chr;
1654 WinCharState *s;
1656 chr = qemu_mallocz(sizeof(CharDriverState));
1657 s = qemu_mallocz(sizeof(WinCharState));
1658 s->hcom = fd_out;
1659 chr->opaque = s;
1660 chr->chr_write = win_chr_write;
1661 qemu_chr_reset(chr);
1662 return chr;
1665 static CharDriverState *qemu_chr_open_win_con(const char *filename)
1667 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1670 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
1672 HANDLE fd_out;
1674 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1675 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1676 if (fd_out == INVALID_HANDLE_VALUE)
1677 return NULL;
1679 return qemu_chr_open_win_file(fd_out);
1681 #endif /* !_WIN32 */
1683 /***********************************************************/
1684 /* UDP Net console */
1686 typedef struct {
1687 int fd;
1688 struct sockaddr_in daddr;
1689 uint8_t buf[1024];
1690 int bufcnt;
1691 int bufptr;
1692 int max_size;
1693 } NetCharDriver;
1695 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1697 NetCharDriver *s = chr->opaque;
1699 return sendto(s->fd, buf, len, 0,
1700 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
1703 static int udp_chr_read_poll(void *opaque)
1705 CharDriverState *chr = opaque;
1706 NetCharDriver *s = chr->opaque;
1708 s->max_size = qemu_chr_can_read(chr);
1710 /* If there were any stray characters in the queue process them
1711 * first
1713 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1714 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1715 s->bufptr++;
1716 s->max_size = qemu_chr_can_read(chr);
1718 return s->max_size;
1721 static void udp_chr_read(void *opaque)
1723 CharDriverState *chr = opaque;
1724 NetCharDriver *s = chr->opaque;
1726 if (s->max_size == 0)
1727 return;
1728 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
1729 s->bufptr = s->bufcnt;
1730 if (s->bufcnt <= 0)
1731 return;
1733 s->bufptr = 0;
1734 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1735 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1736 s->bufptr++;
1737 s->max_size = qemu_chr_can_read(chr);
1741 static void udp_chr_update_read_handler(CharDriverState *chr)
1743 NetCharDriver *s = chr->opaque;
1745 if (s->fd >= 0) {
1746 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
1747 udp_chr_read, NULL, chr);
1751 static void udp_chr_close(CharDriverState *chr)
1753 NetCharDriver *s = chr->opaque;
1754 if (s->fd >= 0) {
1755 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1756 closesocket(s->fd);
1758 qemu_free(s);
1761 static CharDriverState *qemu_chr_open_udp(const char *def)
1763 CharDriverState *chr = NULL;
1764 NetCharDriver *s = NULL;
1765 int fd = -1;
1766 struct sockaddr_in saddr;
1768 chr = qemu_mallocz(sizeof(CharDriverState));
1769 s = qemu_mallocz(sizeof(NetCharDriver));
1771 fd = socket(PF_INET, SOCK_DGRAM, 0);
1772 if (fd < 0) {
1773 perror("socket(PF_INET, SOCK_DGRAM)");
1774 goto return_err;
1777 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
1778 printf("Could not parse: %s\n", def);
1779 goto return_err;
1782 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
1784 perror("bind");
1785 goto return_err;
1788 s->fd = fd;
1789 s->bufcnt = 0;
1790 s->bufptr = 0;
1791 chr->opaque = s;
1792 chr->chr_write = udp_chr_write;
1793 chr->chr_update_read_handler = udp_chr_update_read_handler;
1794 chr->chr_close = udp_chr_close;
1795 return chr;
1797 return_err:
1798 if (chr)
1799 free(chr);
1800 if (s)
1801 free(s);
1802 if (fd >= 0)
1803 closesocket(fd);
1804 return NULL;
1807 /***********************************************************/
1808 /* TCP Net console */
1810 typedef struct {
1811 int fd, listen_fd;
1812 int connected;
1813 int max_size;
1814 int do_telnetopt;
1815 int do_nodelay;
1816 int is_unix;
1817 } TCPCharDriver;
1819 static void tcp_chr_accept(void *opaque);
1821 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1823 TCPCharDriver *s = chr->opaque;
1824 if (s->connected) {
1825 return send_all(s->fd, buf, len);
1826 } else {
1827 /* XXX: indicate an error ? */
1828 return len;
1832 static int tcp_chr_read_poll(void *opaque)
1834 CharDriverState *chr = opaque;
1835 TCPCharDriver *s = chr->opaque;
1836 if (!s->connected)
1837 return 0;
1838 s->max_size = qemu_chr_can_read(chr);
1839 return s->max_size;
1842 #define IAC 255
1843 #define IAC_BREAK 243
1844 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
1845 TCPCharDriver *s,
1846 uint8_t *buf, int *size)
1848 /* Handle any telnet client's basic IAC options to satisfy char by
1849 * char mode with no echo. All IAC options will be removed from
1850 * the buf and the do_telnetopt variable will be used to track the
1851 * state of the width of the IAC information.
1853 * IAC commands come in sets of 3 bytes with the exception of the
1854 * "IAC BREAK" command and the double IAC.
1857 int i;
1858 int j = 0;
1860 for (i = 0; i < *size; i++) {
1861 if (s->do_telnetopt > 1) {
1862 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
1863 /* Double IAC means send an IAC */
1864 if (j != i)
1865 buf[j] = buf[i];
1866 j++;
1867 s->do_telnetopt = 1;
1868 } else {
1869 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
1870 /* Handle IAC break commands by sending a serial break */
1871 qemu_chr_event(chr, CHR_EVENT_BREAK);
1872 s->do_telnetopt++;
1874 s->do_telnetopt++;
1876 if (s->do_telnetopt >= 4) {
1877 s->do_telnetopt = 1;
1879 } else {
1880 if ((unsigned char)buf[i] == IAC) {
1881 s->do_telnetopt = 2;
1882 } else {
1883 if (j != i)
1884 buf[j] = buf[i];
1885 j++;
1889 *size = j;
1892 static void tcp_chr_read(void *opaque)
1894 CharDriverState *chr = opaque;
1895 TCPCharDriver *s = chr->opaque;
1896 uint8_t buf[1024];
1897 int len, size;
1899 if (!s->connected || s->max_size <= 0)
1900 return;
1901 len = sizeof(buf);
1902 if (len > s->max_size)
1903 len = s->max_size;
1904 size = recv(s->fd, buf, len, 0);
1905 if (size == 0) {
1906 /* connection closed */
1907 s->connected = 0;
1908 if (s->listen_fd >= 0) {
1909 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
1911 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1912 closesocket(s->fd);
1913 s->fd = -1;
1914 } else if (size > 0) {
1915 if (s->do_telnetopt)
1916 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
1917 if (size > 0)
1918 qemu_chr_read(chr, buf, size);
1922 static void tcp_chr_connect(void *opaque)
1924 CharDriverState *chr = opaque;
1925 TCPCharDriver *s = chr->opaque;
1927 s->connected = 1;
1928 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
1929 tcp_chr_read, NULL, chr);
1930 qemu_chr_reset(chr);
1933 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
1934 static void tcp_chr_telnet_init(int fd)
1936 char buf[3];
1937 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
1938 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
1939 send(fd, (char *)buf, 3, 0);
1940 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
1941 send(fd, (char *)buf, 3, 0);
1942 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
1943 send(fd, (char *)buf, 3, 0);
1944 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
1945 send(fd, (char *)buf, 3, 0);
1948 static void socket_set_nodelay(int fd)
1950 int val = 1;
1951 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1954 static void tcp_chr_accept(void *opaque)
1956 CharDriverState *chr = opaque;
1957 TCPCharDriver *s = chr->opaque;
1958 struct sockaddr_in saddr;
1959 #ifndef _WIN32
1960 struct sockaddr_un uaddr;
1961 #endif
1962 struct sockaddr *addr;
1963 socklen_t len;
1964 int fd;
1966 for(;;) {
1967 #ifndef _WIN32
1968 if (s->is_unix) {
1969 len = sizeof(uaddr);
1970 addr = (struct sockaddr *)&uaddr;
1971 } else
1972 #endif
1974 len = sizeof(saddr);
1975 addr = (struct sockaddr *)&saddr;
1977 fd = accept(s->listen_fd, addr, &len);
1978 if (fd < 0 && errno != EINTR) {
1979 return;
1980 } else if (fd >= 0) {
1981 if (s->do_telnetopt)
1982 tcp_chr_telnet_init(fd);
1983 break;
1986 socket_set_nonblock(fd);
1987 if (s->do_nodelay)
1988 socket_set_nodelay(fd);
1989 s->fd = fd;
1990 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
1991 tcp_chr_connect(chr);
1994 static void tcp_chr_close(CharDriverState *chr)
1996 TCPCharDriver *s = chr->opaque;
1997 if (s->fd >= 0) {
1998 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1999 closesocket(s->fd);
2001 if (s->listen_fd >= 0) {
2002 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2003 closesocket(s->listen_fd);
2005 qemu_free(s);
2008 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2009 int is_telnet,
2010 int is_unix)
2012 CharDriverState *chr = NULL;
2013 TCPCharDriver *s = NULL;
2014 int fd = -1, offset = 0;
2015 int is_listen = 0;
2016 int is_waitconnect = 1;
2017 int do_nodelay = 0;
2018 const char *ptr;
2020 ptr = host_str;
2021 while((ptr = strchr(ptr,','))) {
2022 ptr++;
2023 if (!strncmp(ptr,"server",6)) {
2024 is_listen = 1;
2025 } else if (!strncmp(ptr,"nowait",6)) {
2026 is_waitconnect = 0;
2027 } else if (!strncmp(ptr,"nodelay",6)) {
2028 do_nodelay = 1;
2029 } else if (!strncmp(ptr,"to=",3)) {
2030 /* nothing, inet_listen() parses this one */;
2031 } else if (!strncmp(ptr,"ipv4",4)) {
2032 /* nothing, inet_connect() and inet_listen() parse this one */;
2033 } else if (!strncmp(ptr,"ipv6",4)) {
2034 /* nothing, inet_connect() and inet_listen() parse this one */;
2035 } else {
2036 printf("Unknown option: %s\n", ptr);
2037 goto fail;
2040 if (!is_listen)
2041 is_waitconnect = 0;
2043 chr = qemu_mallocz(sizeof(CharDriverState));
2044 s = qemu_mallocz(sizeof(TCPCharDriver));
2046 if (is_listen) {
2047 chr->filename = qemu_malloc(256);
2048 if (is_unix) {
2049 pstrcpy(chr->filename, 256, "unix:");
2050 } else if (is_telnet) {
2051 pstrcpy(chr->filename, 256, "telnet:");
2052 } else {
2053 pstrcpy(chr->filename, 256, "tcp:");
2055 offset = strlen(chr->filename);
2057 if (is_unix) {
2058 if (is_listen) {
2059 fd = unix_listen(host_str, chr->filename + offset, 256 - offset);
2060 } else {
2061 fd = unix_connect(host_str);
2063 } else {
2064 if (is_listen) {
2065 fd = inet_listen(host_str, chr->filename + offset, 256 - offset,
2066 SOCK_STREAM, 0);
2067 } else {
2068 fd = inet_connect(host_str, SOCK_STREAM);
2071 if (fd < 0)
2072 goto fail;
2074 if (!is_waitconnect)
2075 socket_set_nonblock(fd);
2077 s->connected = 0;
2078 s->fd = -1;
2079 s->listen_fd = -1;
2080 s->is_unix = is_unix;
2081 s->do_nodelay = do_nodelay && !is_unix;
2083 chr->opaque = s;
2084 chr->chr_write = tcp_chr_write;
2085 chr->chr_close = tcp_chr_close;
2087 if (is_listen) {
2088 s->listen_fd = fd;
2089 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2090 if (is_telnet)
2091 s->do_telnetopt = 1;
2092 } else {
2093 s->connected = 1;
2094 s->fd = fd;
2095 socket_set_nodelay(fd);
2096 tcp_chr_connect(chr);
2099 if (is_listen && is_waitconnect) {
2100 printf("QEMU waiting for connection on: %s\n",
2101 chr->filename ? chr->filename : host_str);
2102 tcp_chr_accept(chr);
2103 socket_set_nonblock(s->listen_fd);
2106 return chr;
2107 fail:
2108 if (fd >= 0)
2109 closesocket(fd);
2110 qemu_free(s);
2111 qemu_free(chr);
2112 return NULL;
2115 CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2117 const char *p;
2118 CharDriverState *chr;
2120 if (!strcmp(filename, "vc")) {
2121 chr = text_console_init(0);
2122 } else
2123 if (strstart(filename, "vc:", &p)) {
2124 chr = text_console_init(p);
2125 } else
2126 if (!strcmp(filename, "null")) {
2127 chr = qemu_chr_open_null();
2128 } else
2129 if (strstart(filename, "tcp:", &p)) {
2130 chr = qemu_chr_open_tcp(p, 0, 0);
2131 } else
2132 if (strstart(filename, "telnet:", &p)) {
2133 chr = qemu_chr_open_tcp(p, 1, 0);
2134 } else
2135 if (strstart(filename, "udp:", &p)) {
2136 chr = qemu_chr_open_udp(p);
2137 } else
2138 if (strstart(filename, "mon:", &p)) {
2139 chr = qemu_chr_open(label, p, NULL);
2140 if (chr) {
2141 chr = qemu_chr_open_mux(chr);
2142 monitor_init(chr, !nographic);
2143 } else {
2144 printf("Unable to open driver: %s\n", p);
2146 } else if (!strcmp(filename, "msmouse")) {
2147 chr = qemu_chr_open_msmouse();
2148 } else
2149 #ifndef _WIN32
2150 if (strstart(filename, "unix:", &p)) {
2151 chr = qemu_chr_open_tcp(p, 0, 1);
2152 } else if (strstart(filename, "file:", &p)) {
2153 chr = qemu_chr_open_file_out(p);
2154 } else if (strstart(filename, "pipe:", &p)) {
2155 chr = qemu_chr_open_pipe(p);
2156 } else if (!strcmp(filename, "pty")) {
2157 chr = qemu_chr_open_pty();
2158 } else if (!strcmp(filename, "stdio")) {
2159 chr = qemu_chr_open_stdio();
2160 } else
2161 #if defined(__linux__)
2162 if (strstart(filename, "/dev/parport", NULL)) {
2163 chr = qemu_chr_open_pp(filename);
2164 } else
2165 #elif defined(__FreeBSD__)
2166 if (strstart(filename, "/dev/ppi", NULL)) {
2167 chr = qemu_chr_open_pp(filename);
2168 } else
2169 #endif
2170 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2171 || defined(__NetBSD__) || defined(__OpenBSD__)
2172 if (strstart(filename, "/dev/", NULL)) {
2173 chr = qemu_chr_open_tty(filename);
2174 } else
2175 #endif
2176 #else /* !_WIN32 */
2177 if (strstart(filename, "COM", NULL)) {
2178 chr = qemu_chr_open_win(filename);
2179 } else
2180 if (strstart(filename, "pipe:", &p)) {
2181 chr = qemu_chr_open_win_pipe(p);
2182 } else
2183 if (strstart(filename, "con:", NULL)) {
2184 chr = qemu_chr_open_win_con(filename);
2185 } else
2186 if (strstart(filename, "file:", &p)) {
2187 chr = qemu_chr_open_win_file_out(p);
2188 } else
2189 #endif
2190 #ifdef CONFIG_BRLAPI
2191 if (!strcmp(filename, "braille")) {
2192 chr = chr_baum_init();
2193 } else
2194 #endif
2196 chr = NULL;
2199 if (chr) {
2200 if (!chr->filename)
2201 chr->filename = qemu_strdup(filename);
2202 chr->init = init;
2203 chr->label = qemu_strdup(label);
2204 TAILQ_INSERT_TAIL(&chardevs, chr, next);
2206 return chr;
2209 void qemu_chr_close(CharDriverState *chr)
2211 TAILQ_REMOVE(&chardevs, chr, next);
2212 if (chr->chr_close)
2213 chr->chr_close(chr);
2214 qemu_free(chr->filename);
2215 qemu_free(chr->label);
2216 qemu_free(chr);
2219 void qemu_chr_info(void)
2221 CharDriverState *chr;
2223 TAILQ_FOREACH(chr, &chardevs, next) {
2224 term_printf("%s: filename=%s\n", chr->label, chr->filename);