Revert r6408
[sniper_test.git] / qemu-char.c
blobc92507b39e26dc3a3c2112d33a94f1ca9896fc9e
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 "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"
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <signal.h>
39 #include <time.h>
40 #include <errno.h>
41 #include <sys/time.h>
42 #include <zlib.h>
44 #ifndef _WIN32
45 #include <sys/times.h>
46 #include <sys/wait.h>
47 #include <termios.h>
48 #include <sys/mman.h>
49 #include <sys/ioctl.h>
50 #include <sys/resource.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <net/if.h>
54 #ifdef __NetBSD__
55 #include <net/if_tap.h>
56 #endif
57 #ifdef __linux__
58 #include <linux/if_tun.h>
59 #endif
60 #include <arpa/inet.h>
61 #include <dirent.h>
62 #include <netdb.h>
63 #include <sys/select.h>
64 #ifdef HOST_BSD
65 #include <sys/stat.h>
66 #ifdef __FreeBSD__
67 #include <libutil.h>
68 #include <dev/ppbus/ppi.h>
69 #include <dev/ppbus/ppbconf.h>
70 #elif defined(__DragonFly__)
71 #include <libutil.h>
72 #include <dev/misc/ppi/ppi.h>
73 #include <bus/ppbus/ppbconf.h>
74 #else
75 #include <util.h>
76 #endif
77 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
78 #include <freebsd/stdlib.h>
79 #else
80 #ifdef __linux__
81 #include <pty.h>
83 #include <linux/ppdev.h>
84 #include <linux/parport.h>
85 #endif
86 #ifdef __sun__
87 #include <sys/stat.h>
88 #include <sys/ethernet.h>
89 #include <sys/sockio.h>
90 #include <netinet/arp.h>
91 #include <netinet/in.h>
92 #include <netinet/in_systm.h>
93 #include <netinet/ip.h>
94 #include <netinet/ip_icmp.h> // must come after ip.h
95 #include <netinet/udp.h>
96 #include <netinet/tcp.h>
97 #include <net/if.h>
98 #include <syslog.h>
99 #include <stropts.h>
100 #endif
101 #endif
102 #endif
104 #include "qemu_socket.h"
106 /***********************************************************/
107 /* character device */
109 static TAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
110 TAILQ_HEAD_INITIALIZER(chardevs);
111 static int initial_reset_issued;
113 static void qemu_chr_event(CharDriverState *s, int event)
115 if (!s->chr_event)
116 return;
117 s->chr_event(s->handler_opaque, event);
120 static void qemu_chr_reset_bh(void *opaque)
122 CharDriverState *s = opaque;
123 qemu_chr_event(s, CHR_EVENT_RESET);
124 qemu_bh_delete(s->bh);
125 s->bh = NULL;
128 void qemu_chr_reset(CharDriverState *s)
130 if (s->bh == NULL && initial_reset_issued) {
131 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
132 qemu_bh_schedule(s->bh);
136 void qemu_chr_initial_reset(void)
138 CharDriverState *chr;
140 initial_reset_issued = 1;
142 TAILQ_FOREACH(chr, &chardevs, next) {
143 qemu_chr_reset(chr);
147 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
149 return s->chr_write(s, buf, len);
152 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
154 if (!s->chr_ioctl)
155 return -ENOTSUP;
156 return s->chr_ioctl(s, cmd, arg);
159 int qemu_chr_can_read(CharDriverState *s)
161 if (!s->chr_can_read)
162 return 0;
163 return s->chr_can_read(s->handler_opaque);
166 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
168 s->chr_read(s->handler_opaque, buf, len);
171 void qemu_chr_accept_input(CharDriverState *s)
173 if (s->chr_accept_input)
174 s->chr_accept_input(s);
177 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
179 char buf[4096];
180 va_list ap;
181 va_start(ap, fmt);
182 vsnprintf(buf, sizeof(buf), fmt, ap);
183 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
184 va_end(ap);
187 void qemu_chr_send_event(CharDriverState *s, int event)
189 if (s->chr_send_event)
190 s->chr_send_event(s, event);
193 void qemu_chr_add_handlers(CharDriverState *s,
194 IOCanRWHandler *fd_can_read,
195 IOReadHandler *fd_read,
196 IOEventHandler *fd_event,
197 void *opaque)
199 s->chr_can_read = fd_can_read;
200 s->chr_read = fd_read;
201 s->chr_event = fd_event;
202 s->handler_opaque = opaque;
203 if (s->chr_update_read_handler)
204 s->chr_update_read_handler(s);
207 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
209 return len;
212 static CharDriverState *qemu_chr_open_null(void)
214 CharDriverState *chr;
216 chr = qemu_mallocz(sizeof(CharDriverState));
217 chr->chr_write = null_chr_write;
218 return chr;
221 /* MUX driver for serial I/O splitting */
222 static int term_timestamps;
223 static int64_t term_timestamps_start;
224 #define MAX_MUX 4
225 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
226 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
227 typedef struct {
228 IOCanRWHandler *chr_can_read[MAX_MUX];
229 IOReadHandler *chr_read[MAX_MUX];
230 IOEventHandler *chr_event[MAX_MUX];
231 void *ext_opaque[MAX_MUX];
232 CharDriverState *drv;
233 int mux_cnt;
234 int term_got_escape;
235 int max_size;
236 /* Intermediate input buffer allows to catch escape sequences even if the
237 currently active device is not accepting any input - but only until it
238 is full as well. */
239 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
240 int prod[MAX_MUX];
241 int cons[MAX_MUX];
242 } MuxDriver;
245 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
247 MuxDriver *d = chr->opaque;
248 int ret;
249 if (!term_timestamps) {
250 ret = d->drv->chr_write(d->drv, buf, len);
251 } else {
252 int i;
254 ret = 0;
255 for(i = 0; i < len; i++) {
256 ret += d->drv->chr_write(d->drv, buf+i, 1);
257 if (buf[i] == '\n') {
258 char buf1[64];
259 int64_t ti;
260 int secs;
262 ti = qemu_get_clock(rt_clock);
263 if (term_timestamps_start == -1)
264 term_timestamps_start = ti;
265 ti -= term_timestamps_start;
266 secs = ti / 1000;
267 snprintf(buf1, sizeof(buf1),
268 "[%02d:%02d:%02d.%03d] ",
269 secs / 3600,
270 (secs / 60) % 60,
271 secs % 60,
272 (int)(ti % 1000));
273 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
277 return ret;
280 static const char * const mux_help[] = {
281 "% h print this help\n\r",
282 "% x exit emulator\n\r",
283 "% s save disk data back to file (if -snapshot)\n\r",
284 "% t toggle console timestamps\n\r"
285 "% b send break (magic sysrq)\n\r",
286 "% c switch between console and monitor\n\r",
287 "% % sends %\n\r",
288 NULL
291 int term_escape_char = 0x01; /* ctrl-a is used for escape */
292 static void mux_print_help(CharDriverState *chr)
294 int i, j;
295 char ebuf[15] = "Escape-Char";
296 char cbuf[50] = "\n\r";
298 if (term_escape_char > 0 && term_escape_char < 26) {
299 snprintf(cbuf, sizeof(cbuf), "\n\r");
300 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
301 } else {
302 snprintf(cbuf, sizeof(cbuf),
303 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
304 term_escape_char);
306 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
307 for (i = 0; mux_help[i] != NULL; i++) {
308 for (j=0; mux_help[i][j] != '\0'; j++) {
309 if (mux_help[i][j] == '%')
310 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
311 else
312 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
317 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
319 if (d->chr_event[mux_nr])
320 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
323 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
325 if (d->term_got_escape) {
326 d->term_got_escape = 0;
327 if (ch == term_escape_char)
328 goto send_char;
329 switch(ch) {
330 case '?':
331 case 'h':
332 mux_print_help(chr);
333 break;
334 case 'x':
336 const char *term = "QEMU: Terminated\n\r";
337 chr->chr_write(chr,(uint8_t *)term,strlen(term));
338 exit(0);
339 break;
341 case 's':
343 int i;
344 for (i = 0; i < nb_drives; i++) {
345 bdrv_commit(drives_table[i].bdrv);
348 break;
349 case 'b':
350 qemu_chr_event(chr, CHR_EVENT_BREAK);
351 break;
352 case 'c':
353 /* Switch to the next registered device */
354 mux_chr_send_event(d, chr->focus, CHR_EVENT_MUX_OUT);
355 chr->focus++;
356 if (chr->focus >= d->mux_cnt)
357 chr->focus = 0;
358 mux_chr_send_event(d, chr->focus, CHR_EVENT_MUX_IN);
359 break;
360 case 't':
361 term_timestamps = !term_timestamps;
362 term_timestamps_start = -1;
363 break;
365 } else if (ch == term_escape_char) {
366 d->term_got_escape = 1;
367 } else {
368 send_char:
369 return 1;
371 return 0;
374 static void mux_chr_accept_input(CharDriverState *chr)
376 int m = chr->focus;
377 MuxDriver *d = chr->opaque;
379 while (d->prod[m] != d->cons[m] &&
380 d->chr_can_read[m] &&
381 d->chr_can_read[m](d->ext_opaque[m])) {
382 d->chr_read[m](d->ext_opaque[m],
383 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
387 static int mux_chr_can_read(void *opaque)
389 CharDriverState *chr = opaque;
390 MuxDriver *d = chr->opaque;
391 int m = chr->focus;
393 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
394 return 1;
395 if (d->chr_can_read[m])
396 return d->chr_can_read[m](d->ext_opaque[m]);
397 return 0;
400 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
402 CharDriverState *chr = opaque;
403 MuxDriver *d = chr->opaque;
404 int m = chr->focus;
405 int i;
407 mux_chr_accept_input (opaque);
409 for(i = 0; i < size; i++)
410 if (mux_proc_byte(chr, d, buf[i])) {
411 if (d->prod[m] == d->cons[m] &&
412 d->chr_can_read[m] &&
413 d->chr_can_read[m](d->ext_opaque[m]))
414 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
415 else
416 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
420 static void mux_chr_event(void *opaque, int event)
422 CharDriverState *chr = opaque;
423 MuxDriver *d = chr->opaque;
424 int i;
426 /* Send the event to all registered listeners */
427 for (i = 0; i < d->mux_cnt; i++)
428 mux_chr_send_event(d, i, event);
431 static void mux_chr_update_read_handler(CharDriverState *chr)
433 MuxDriver *d = chr->opaque;
435 if (d->mux_cnt >= MAX_MUX) {
436 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
437 return;
439 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
440 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
441 d->chr_read[d->mux_cnt] = chr->chr_read;
442 d->chr_event[d->mux_cnt] = chr->chr_event;
443 /* Fix up the real driver with mux routines */
444 if (d->mux_cnt == 0) {
445 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
446 mux_chr_event, chr);
448 chr->focus = d->mux_cnt;
449 d->mux_cnt++;
452 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
454 CharDriverState *chr;
455 MuxDriver *d;
457 chr = qemu_mallocz(sizeof(CharDriverState));
458 d = qemu_mallocz(sizeof(MuxDriver));
460 chr->opaque = d;
461 d->drv = drv;
462 chr->focus = -1;
463 chr->chr_write = mux_chr_write;
464 chr->chr_update_read_handler = mux_chr_update_read_handler;
465 chr->chr_accept_input = mux_chr_accept_input;
466 return chr;
470 #ifdef _WIN32
471 int send_all(int fd, const void *buf, int len1)
473 int ret, len;
475 len = len1;
476 while (len > 0) {
477 ret = send(fd, buf, len, 0);
478 if (ret < 0) {
479 errno = WSAGetLastError();
480 if (errno != WSAEWOULDBLOCK) {
481 return -1;
483 } else if (ret == 0) {
484 break;
485 } else {
486 buf += ret;
487 len -= ret;
490 return len1 - len;
493 #else
495 static int unix_write(int fd, const uint8_t *buf, int len1)
497 int ret, len;
499 len = len1;
500 while (len > 0) {
501 ret = write(fd, buf, len);
502 if (ret < 0) {
503 if (errno != EINTR && errno != EAGAIN)
504 return -1;
505 } else if (ret == 0) {
506 break;
507 } else {
508 buf += ret;
509 len -= ret;
512 return len1 - len;
515 int send_all(int fd, const void *buf, int len1)
517 return unix_write(fd, buf, len1);
519 #endif /* !_WIN32 */
521 #ifndef _WIN32
523 typedef struct {
524 int fd_in, fd_out;
525 int max_size;
526 } FDCharDriver;
528 #define STDIO_MAX_CLIENTS 1
529 static int stdio_nb_clients = 0;
531 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
533 FDCharDriver *s = chr->opaque;
534 return send_all(s->fd_out, buf, len);
537 static int fd_chr_read_poll(void *opaque)
539 CharDriverState *chr = opaque;
540 FDCharDriver *s = chr->opaque;
542 s->max_size = qemu_chr_can_read(chr);
543 return s->max_size;
546 static void fd_chr_read(void *opaque)
548 CharDriverState *chr = opaque;
549 FDCharDriver *s = chr->opaque;
550 int size, len;
551 uint8_t buf[1024];
553 len = sizeof(buf);
554 if (len > s->max_size)
555 len = s->max_size;
556 if (len == 0)
557 return;
558 size = read(s->fd_in, buf, len);
559 if (size == 0) {
560 /* FD has been closed. Remove it from the active list. */
561 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
562 return;
564 if (size > 0) {
565 qemu_chr_read(chr, buf, size);
569 static void fd_chr_update_read_handler(CharDriverState *chr)
571 FDCharDriver *s = chr->opaque;
573 if (s->fd_in >= 0) {
574 if (nographic && s->fd_in == 0) {
575 } else {
576 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
577 fd_chr_read, NULL, chr);
582 static void fd_chr_close(struct CharDriverState *chr)
584 FDCharDriver *s = chr->opaque;
586 if (s->fd_in >= 0) {
587 if (nographic && s->fd_in == 0) {
588 } else {
589 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
593 qemu_free(s);
596 /* open a character device to a unix fd */
597 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
599 CharDriverState *chr;
600 FDCharDriver *s;
602 chr = qemu_mallocz(sizeof(CharDriverState));
603 s = qemu_mallocz(sizeof(FDCharDriver));
604 s->fd_in = fd_in;
605 s->fd_out = fd_out;
606 chr->opaque = s;
607 chr->chr_write = fd_chr_write;
608 chr->chr_update_read_handler = fd_chr_update_read_handler;
609 chr->chr_close = fd_chr_close;
611 qemu_chr_reset(chr);
613 return chr;
616 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
618 int fd_out;
620 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
621 if (fd_out < 0)
622 return NULL;
623 return qemu_chr_open_fd(-1, fd_out);
626 static CharDriverState *qemu_chr_open_pipe(const char *filename)
628 int fd_in, fd_out;
629 char filename_in[256], filename_out[256];
631 snprintf(filename_in, 256, "%s.in", filename);
632 snprintf(filename_out, 256, "%s.out", filename);
633 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
634 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
635 if (fd_in < 0 || fd_out < 0) {
636 if (fd_in >= 0)
637 close(fd_in);
638 if (fd_out >= 0)
639 close(fd_out);
640 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
641 if (fd_in < 0)
642 return NULL;
644 return qemu_chr_open_fd(fd_in, fd_out);
648 /* for STDIO, we handle the case where several clients use it
649 (nographic mode) */
651 #define TERM_FIFO_MAX_SIZE 1
653 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
654 static int term_fifo_size;
656 static int stdio_read_poll(void *opaque)
658 CharDriverState *chr = opaque;
660 /* try to flush the queue if needed */
661 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
662 qemu_chr_read(chr, term_fifo, 1);
663 term_fifo_size = 0;
665 /* see if we can absorb more chars */
666 if (term_fifo_size == 0)
667 return 1;
668 else
669 return 0;
672 static void stdio_read(void *opaque)
674 int size;
675 uint8_t buf[1];
676 CharDriverState *chr = opaque;
678 size = read(0, buf, 1);
679 if (size == 0) {
680 /* stdin has been closed. Remove it from the active list. */
681 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
682 return;
684 if (size > 0) {
685 if (qemu_chr_can_read(chr) > 0) {
686 qemu_chr_read(chr, buf, 1);
687 } else if (term_fifo_size == 0) {
688 term_fifo[term_fifo_size++] = buf[0];
693 /* init terminal so that we can grab keys */
694 static struct termios oldtty;
695 static int old_fd0_flags;
696 static int term_atexit_done;
698 static void term_exit(void)
700 tcsetattr (0, TCSANOW, &oldtty);
701 fcntl(0, F_SETFL, old_fd0_flags);
704 static void term_init(void)
706 struct termios tty;
708 tcgetattr (0, &tty);
709 oldtty = tty;
710 old_fd0_flags = fcntl(0, F_GETFL);
712 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
713 |INLCR|IGNCR|ICRNL|IXON);
714 tty.c_oflag |= OPOST;
715 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
716 /* if graphical mode, we allow Ctrl-C handling */
717 if (nographic)
718 tty.c_lflag &= ~ISIG;
719 tty.c_cflag &= ~(CSIZE|PARENB);
720 tty.c_cflag |= CS8;
721 tty.c_cc[VMIN] = 1;
722 tty.c_cc[VTIME] = 0;
724 tcsetattr (0, TCSANOW, &tty);
726 if (!term_atexit_done++)
727 atexit(term_exit);
729 fcntl(0, F_SETFL, O_NONBLOCK);
732 static void qemu_chr_close_stdio(struct CharDriverState *chr)
734 term_exit();
735 stdio_nb_clients--;
736 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
737 fd_chr_close(chr);
740 static CharDriverState *qemu_chr_open_stdio(void)
742 CharDriverState *chr;
744 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
745 return NULL;
746 chr = qemu_chr_open_fd(0, 1);
747 chr->chr_close = qemu_chr_close_stdio;
748 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
749 stdio_nb_clients++;
750 term_init();
752 return chr;
755 #ifdef __sun__
756 /* Once Solaris has openpty(), this is going to be removed. */
757 int openpty(int *amaster, int *aslave, char *name,
758 struct termios *termp, struct winsize *winp)
760 const char *slave;
761 int mfd = -1, sfd = -1;
763 *amaster = *aslave = -1;
765 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
766 if (mfd < 0)
767 goto err;
769 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
770 goto err;
772 if ((slave = ptsname(mfd)) == NULL)
773 goto err;
775 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
776 goto err;
778 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
779 (termp != NULL && tcgetattr(sfd, termp) < 0))
780 goto err;
782 if (amaster)
783 *amaster = mfd;
784 if (aslave)
785 *aslave = sfd;
786 if (winp)
787 ioctl(sfd, TIOCSWINSZ, winp);
789 return 0;
791 err:
792 if (sfd != -1)
793 close(sfd);
794 close(mfd);
795 return -1;
798 void cfmakeraw (struct termios *termios_p)
800 termios_p->c_iflag &=
801 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
802 termios_p->c_oflag &= ~OPOST;
803 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
804 termios_p->c_cflag &= ~(CSIZE|PARENB);
805 termios_p->c_cflag |= CS8;
807 termios_p->c_cc[VMIN] = 0;
808 termios_p->c_cc[VTIME] = 0;
810 #endif
812 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
813 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
815 typedef struct {
816 int fd;
817 int connected;
818 int polling;
819 int read_bytes;
820 QEMUTimer *timer;
821 } PtyCharDriver;
823 static void pty_chr_update_read_handler(CharDriverState *chr);
824 static void pty_chr_state(CharDriverState *chr, int connected);
826 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
828 PtyCharDriver *s = chr->opaque;
830 if (!s->connected) {
831 /* guest sends data, check for (re-)connect */
832 pty_chr_update_read_handler(chr);
833 return 0;
835 return send_all(s->fd, buf, len);
838 static int pty_chr_read_poll(void *opaque)
840 CharDriverState *chr = opaque;
841 PtyCharDriver *s = chr->opaque;
843 s->read_bytes = qemu_chr_can_read(chr);
844 return s->read_bytes;
847 static void pty_chr_read(void *opaque)
849 CharDriverState *chr = opaque;
850 PtyCharDriver *s = chr->opaque;
851 int size, len;
852 uint8_t buf[1024];
854 len = sizeof(buf);
855 if (len > s->read_bytes)
856 len = s->read_bytes;
857 if (len == 0)
858 return;
859 size = read(s->fd, buf, len);
860 if ((size == -1 && errno == EIO) ||
861 (size == 0)) {
862 pty_chr_state(chr, 0);
863 return;
865 if (size > 0) {
866 pty_chr_state(chr, 1);
867 qemu_chr_read(chr, buf, size);
871 static void pty_chr_update_read_handler(CharDriverState *chr)
873 PtyCharDriver *s = chr->opaque;
875 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
876 pty_chr_read, NULL, chr);
877 s->polling = 1;
879 * Short timeout here: just need wait long enougth that qemu makes
880 * it through the poll loop once. When reconnected we want a
881 * short timeout so we notice it almost instantly. Otherwise
882 * read() gives us -EIO instantly, making pty_chr_state() reset the
883 * timeout to the normal (much longer) poll interval before the
884 * timer triggers.
886 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
889 static void pty_chr_state(CharDriverState *chr, int connected)
891 PtyCharDriver *s = chr->opaque;
893 if (!connected) {
894 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
895 s->connected = 0;
896 s->polling = 0;
897 /* (re-)connect poll interval for idle guests: once per second.
898 * We check more frequently in case the guests sends data to
899 * the virtual device linked to our pty. */
900 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
901 } else {
902 if (!s->connected)
903 qemu_chr_reset(chr);
904 s->connected = 1;
908 static void pty_chr_timer(void *opaque)
910 struct CharDriverState *chr = opaque;
911 PtyCharDriver *s = chr->opaque;
913 if (s->connected)
914 return;
915 if (s->polling) {
916 /* If we arrive here without polling being cleared due
917 * read returning -EIO, then we are (re-)connected */
918 pty_chr_state(chr, 1);
919 return;
922 /* Next poll ... */
923 pty_chr_update_read_handler(chr);
926 static void pty_chr_close(struct CharDriverState *chr)
928 PtyCharDriver *s = chr->opaque;
930 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
931 close(s->fd);
932 qemu_free(s);
935 static CharDriverState *qemu_chr_open_pty(void)
937 CharDriverState *chr;
938 PtyCharDriver *s;
939 struct termios tty;
940 int slave_fd, len;
941 #if defined(__OpenBSD__) || defined(__DragonFly__)
942 char pty_name[PATH_MAX];
943 #define q_ptsname(x) pty_name
944 #else
945 char *pty_name = NULL;
946 #define q_ptsname(x) ptsname(x)
947 #endif
949 chr = qemu_mallocz(sizeof(CharDriverState));
950 s = qemu_mallocz(sizeof(PtyCharDriver));
952 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
953 return NULL;
956 /* Set raw attributes on the pty. */
957 tcgetattr(slave_fd, &tty);
958 cfmakeraw(&tty);
959 tcsetattr(slave_fd, TCSAFLUSH, &tty);
960 close(slave_fd);
962 len = strlen(q_ptsname(s->fd)) + 5;
963 chr->filename = qemu_malloc(len);
964 snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
965 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
967 chr->opaque = s;
968 chr->chr_write = pty_chr_write;
969 chr->chr_update_read_handler = pty_chr_update_read_handler;
970 chr->chr_close = pty_chr_close;
972 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
974 return chr;
977 static void tty_serial_init(int fd, int speed,
978 int parity, int data_bits, int stop_bits)
980 struct termios tty;
981 speed_t spd;
983 #if 0
984 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
985 speed, parity, data_bits, stop_bits);
986 #endif
987 tcgetattr (fd, &tty);
989 #define MARGIN 1.1
990 if (speed <= 50 * MARGIN)
991 spd = B50;
992 else if (speed <= 75 * MARGIN)
993 spd = B75;
994 else if (speed <= 300 * MARGIN)
995 spd = B300;
996 else if (speed <= 600 * MARGIN)
997 spd = B600;
998 else if (speed <= 1200 * MARGIN)
999 spd = B1200;
1000 else if (speed <= 2400 * MARGIN)
1001 spd = B2400;
1002 else if (speed <= 4800 * MARGIN)
1003 spd = B4800;
1004 else if (speed <= 9600 * MARGIN)
1005 spd = B9600;
1006 else if (speed <= 19200 * MARGIN)
1007 spd = B19200;
1008 else if (speed <= 38400 * MARGIN)
1009 spd = B38400;
1010 else if (speed <= 57600 * MARGIN)
1011 spd = B57600;
1012 else if (speed <= 115200 * MARGIN)
1013 spd = B115200;
1014 else
1015 spd = B115200;
1017 cfsetispeed(&tty, spd);
1018 cfsetospeed(&tty, spd);
1020 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1021 |INLCR|IGNCR|ICRNL|IXON);
1022 tty.c_oflag |= OPOST;
1023 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1024 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1025 switch(data_bits) {
1026 default:
1027 case 8:
1028 tty.c_cflag |= CS8;
1029 break;
1030 case 7:
1031 tty.c_cflag |= CS7;
1032 break;
1033 case 6:
1034 tty.c_cflag |= CS6;
1035 break;
1036 case 5:
1037 tty.c_cflag |= CS5;
1038 break;
1040 switch(parity) {
1041 default:
1042 case 'N':
1043 break;
1044 case 'E':
1045 tty.c_cflag |= PARENB;
1046 break;
1047 case 'O':
1048 tty.c_cflag |= PARENB | PARODD;
1049 break;
1051 if (stop_bits == 2)
1052 tty.c_cflag |= CSTOPB;
1054 tcsetattr (fd, TCSANOW, &tty);
1057 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1059 FDCharDriver *s = chr->opaque;
1061 switch(cmd) {
1062 case CHR_IOCTL_SERIAL_SET_PARAMS:
1064 QEMUSerialSetParams *ssp = arg;
1065 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1066 ssp->data_bits, ssp->stop_bits);
1068 break;
1069 case CHR_IOCTL_SERIAL_SET_BREAK:
1071 int enable = *(int *)arg;
1072 if (enable)
1073 tcsendbreak(s->fd_in, 1);
1075 break;
1076 case CHR_IOCTL_SERIAL_GET_TIOCM:
1078 int sarg = 0;
1079 int *targ = (int *)arg;
1080 ioctl(s->fd_in, TIOCMGET, &sarg);
1081 *targ = 0;
1082 if (sarg & TIOCM_CTS)
1083 *targ |= CHR_TIOCM_CTS;
1084 if (sarg & TIOCM_CAR)
1085 *targ |= CHR_TIOCM_CAR;
1086 if (sarg & TIOCM_DSR)
1087 *targ |= CHR_TIOCM_DSR;
1088 if (sarg & TIOCM_RI)
1089 *targ |= CHR_TIOCM_RI;
1090 if (sarg & TIOCM_DTR)
1091 *targ |= CHR_TIOCM_DTR;
1092 if (sarg & TIOCM_RTS)
1093 *targ |= CHR_TIOCM_RTS;
1095 break;
1096 case CHR_IOCTL_SERIAL_SET_TIOCM:
1098 int sarg = *(int *)arg;
1099 int targ = 0;
1100 ioctl(s->fd_in, TIOCMGET, &targ);
1101 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1102 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1103 if (sarg & CHR_TIOCM_CTS)
1104 targ |= TIOCM_CTS;
1105 if (sarg & CHR_TIOCM_CAR)
1106 targ |= TIOCM_CAR;
1107 if (sarg & CHR_TIOCM_DSR)
1108 targ |= TIOCM_DSR;
1109 if (sarg & CHR_TIOCM_RI)
1110 targ |= TIOCM_RI;
1111 if (sarg & CHR_TIOCM_DTR)
1112 targ |= TIOCM_DTR;
1113 if (sarg & CHR_TIOCM_RTS)
1114 targ |= TIOCM_RTS;
1115 ioctl(s->fd_in, TIOCMSET, &targ);
1117 break;
1118 default:
1119 return -ENOTSUP;
1121 return 0;
1124 static CharDriverState *qemu_chr_open_tty(const char *filename)
1126 CharDriverState *chr;
1127 int fd;
1129 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
1130 tty_serial_init(fd, 115200, 'N', 8, 1);
1131 chr = qemu_chr_open_fd(fd, fd);
1132 if (!chr) {
1133 close(fd);
1134 return NULL;
1136 chr->chr_ioctl = tty_serial_ioctl;
1137 qemu_chr_reset(chr);
1138 return chr;
1140 #else /* ! __linux__ && ! __sun__ */
1141 static CharDriverState *qemu_chr_open_pty(void)
1143 return NULL;
1145 #endif /* __linux__ || __sun__ */
1147 #if defined(__linux__)
1148 typedef struct {
1149 int fd;
1150 int mode;
1151 } ParallelCharDriver;
1153 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1155 if (s->mode != mode) {
1156 int m = mode;
1157 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1158 return 0;
1159 s->mode = mode;
1161 return 1;
1164 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1166 ParallelCharDriver *drv = chr->opaque;
1167 int fd = drv->fd;
1168 uint8_t b;
1170 switch(cmd) {
1171 case CHR_IOCTL_PP_READ_DATA:
1172 if (ioctl(fd, PPRDATA, &b) < 0)
1173 return -ENOTSUP;
1174 *(uint8_t *)arg = b;
1175 break;
1176 case CHR_IOCTL_PP_WRITE_DATA:
1177 b = *(uint8_t *)arg;
1178 if (ioctl(fd, PPWDATA, &b) < 0)
1179 return -ENOTSUP;
1180 break;
1181 case CHR_IOCTL_PP_READ_CONTROL:
1182 if (ioctl(fd, PPRCONTROL, &b) < 0)
1183 return -ENOTSUP;
1184 /* Linux gives only the lowest bits, and no way to know data
1185 direction! For better compatibility set the fixed upper
1186 bits. */
1187 *(uint8_t *)arg = b | 0xc0;
1188 break;
1189 case CHR_IOCTL_PP_WRITE_CONTROL:
1190 b = *(uint8_t *)arg;
1191 if (ioctl(fd, PPWCONTROL, &b) < 0)
1192 return -ENOTSUP;
1193 break;
1194 case CHR_IOCTL_PP_READ_STATUS:
1195 if (ioctl(fd, PPRSTATUS, &b) < 0)
1196 return -ENOTSUP;
1197 *(uint8_t *)arg = b;
1198 break;
1199 case CHR_IOCTL_PP_DATA_DIR:
1200 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1201 return -ENOTSUP;
1202 break;
1203 case CHR_IOCTL_PP_EPP_READ_ADDR:
1204 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1205 struct ParallelIOArg *parg = arg;
1206 int n = read(fd, parg->buffer, parg->count);
1207 if (n != parg->count) {
1208 return -EIO;
1211 break;
1212 case CHR_IOCTL_PP_EPP_READ:
1213 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1214 struct ParallelIOArg *parg = arg;
1215 int n = read(fd, parg->buffer, parg->count);
1216 if (n != parg->count) {
1217 return -EIO;
1220 break;
1221 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1222 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1223 struct ParallelIOArg *parg = arg;
1224 int n = write(fd, parg->buffer, parg->count);
1225 if (n != parg->count) {
1226 return -EIO;
1229 break;
1230 case CHR_IOCTL_PP_EPP_WRITE:
1231 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1232 struct ParallelIOArg *parg = arg;
1233 int n = write(fd, parg->buffer, parg->count);
1234 if (n != parg->count) {
1235 return -EIO;
1238 break;
1239 default:
1240 return -ENOTSUP;
1242 return 0;
1245 static void pp_close(CharDriverState *chr)
1247 ParallelCharDriver *drv = chr->opaque;
1248 int fd = drv->fd;
1250 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1251 ioctl(fd, PPRELEASE);
1252 close(fd);
1253 qemu_free(drv);
1256 static CharDriverState *qemu_chr_open_pp(const char *filename)
1258 CharDriverState *chr;
1259 ParallelCharDriver *drv;
1260 int fd;
1262 TFR(fd = open(filename, O_RDWR));
1263 if (fd < 0)
1264 return NULL;
1266 if (ioctl(fd, PPCLAIM) < 0) {
1267 close(fd);
1268 return NULL;
1271 drv = qemu_mallocz(sizeof(ParallelCharDriver));
1272 drv->fd = fd;
1273 drv->mode = IEEE1284_MODE_COMPAT;
1275 chr = qemu_mallocz(sizeof(CharDriverState));
1276 chr->chr_write = null_chr_write;
1277 chr->chr_ioctl = pp_ioctl;
1278 chr->chr_close = pp_close;
1279 chr->opaque = drv;
1281 qemu_chr_reset(chr);
1283 return chr;
1285 #endif /* __linux__ */
1287 #if defined(__FreeBSD__) || defined(__DragonFly__)
1288 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1290 int fd = (int)chr->opaque;
1291 uint8_t b;
1293 switch(cmd) {
1294 case CHR_IOCTL_PP_READ_DATA:
1295 if (ioctl(fd, PPIGDATA, &b) < 0)
1296 return -ENOTSUP;
1297 *(uint8_t *)arg = b;
1298 break;
1299 case CHR_IOCTL_PP_WRITE_DATA:
1300 b = *(uint8_t *)arg;
1301 if (ioctl(fd, PPISDATA, &b) < 0)
1302 return -ENOTSUP;
1303 break;
1304 case CHR_IOCTL_PP_READ_CONTROL:
1305 if (ioctl(fd, PPIGCTRL, &b) < 0)
1306 return -ENOTSUP;
1307 *(uint8_t *)arg = b;
1308 break;
1309 case CHR_IOCTL_PP_WRITE_CONTROL:
1310 b = *(uint8_t *)arg;
1311 if (ioctl(fd, PPISCTRL, &b) < 0)
1312 return -ENOTSUP;
1313 break;
1314 case CHR_IOCTL_PP_READ_STATUS:
1315 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1316 return -ENOTSUP;
1317 *(uint8_t *)arg = b;
1318 break;
1319 default:
1320 return -ENOTSUP;
1322 return 0;
1325 static CharDriverState *qemu_chr_open_pp(const char *filename)
1327 CharDriverState *chr;
1328 int fd;
1330 fd = open(filename, O_RDWR);
1331 if (fd < 0)
1332 return NULL;
1334 chr = qemu_mallocz(sizeof(CharDriverState));
1335 chr->opaque = (void *)fd;
1336 chr->chr_write = null_chr_write;
1337 chr->chr_ioctl = pp_ioctl;
1338 return chr;
1340 #endif
1342 #else /* _WIN32 */
1344 typedef struct {
1345 int max_size;
1346 HANDLE hcom, hrecv, hsend;
1347 OVERLAPPED orecv, osend;
1348 BOOL fpipe;
1349 DWORD len;
1350 } WinCharState;
1352 #define NSENDBUF 2048
1353 #define NRECVBUF 2048
1354 #define MAXCONNECT 1
1355 #define NTIMEOUT 5000
1357 static int win_chr_poll(void *opaque);
1358 static int win_chr_pipe_poll(void *opaque);
1360 static void win_chr_close(CharDriverState *chr)
1362 WinCharState *s = chr->opaque;
1364 if (s->hsend) {
1365 CloseHandle(s->hsend);
1366 s->hsend = NULL;
1368 if (s->hrecv) {
1369 CloseHandle(s->hrecv);
1370 s->hrecv = NULL;
1372 if (s->hcom) {
1373 CloseHandle(s->hcom);
1374 s->hcom = NULL;
1376 if (s->fpipe)
1377 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1378 else
1379 qemu_del_polling_cb(win_chr_poll, chr);
1382 static int win_chr_init(CharDriverState *chr, const char *filename)
1384 WinCharState *s = chr->opaque;
1385 COMMCONFIG comcfg;
1386 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1387 COMSTAT comstat;
1388 DWORD size;
1389 DWORD err;
1391 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1392 if (!s->hsend) {
1393 fprintf(stderr, "Failed CreateEvent\n");
1394 goto fail;
1396 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1397 if (!s->hrecv) {
1398 fprintf(stderr, "Failed CreateEvent\n");
1399 goto fail;
1402 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1403 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1404 if (s->hcom == INVALID_HANDLE_VALUE) {
1405 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1406 s->hcom = NULL;
1407 goto fail;
1410 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1411 fprintf(stderr, "Failed SetupComm\n");
1412 goto fail;
1415 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1416 size = sizeof(COMMCONFIG);
1417 GetDefaultCommConfig(filename, &comcfg, &size);
1418 comcfg.dcb.DCBlength = sizeof(DCB);
1419 CommConfigDialog(filename, NULL, &comcfg);
1421 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1422 fprintf(stderr, "Failed SetCommState\n");
1423 goto fail;
1426 if (!SetCommMask(s->hcom, EV_ERR)) {
1427 fprintf(stderr, "Failed SetCommMask\n");
1428 goto fail;
1431 cto.ReadIntervalTimeout = MAXDWORD;
1432 if (!SetCommTimeouts(s->hcom, &cto)) {
1433 fprintf(stderr, "Failed SetCommTimeouts\n");
1434 goto fail;
1437 if (!ClearCommError(s->hcom, &err, &comstat)) {
1438 fprintf(stderr, "Failed ClearCommError\n");
1439 goto fail;
1441 qemu_add_polling_cb(win_chr_poll, chr);
1442 return 0;
1444 fail:
1445 win_chr_close(chr);
1446 return -1;
1449 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1451 WinCharState *s = chr->opaque;
1452 DWORD len, ret, size, err;
1454 len = len1;
1455 ZeroMemory(&s->osend, sizeof(s->osend));
1456 s->osend.hEvent = s->hsend;
1457 while (len > 0) {
1458 if (s->hsend)
1459 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1460 else
1461 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1462 if (!ret) {
1463 err = GetLastError();
1464 if (err == ERROR_IO_PENDING) {
1465 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1466 if (ret) {
1467 buf += size;
1468 len -= size;
1469 } else {
1470 break;
1472 } else {
1473 break;
1475 } else {
1476 buf += size;
1477 len -= size;
1480 return len1 - len;
1483 static int win_chr_read_poll(CharDriverState *chr)
1485 WinCharState *s = chr->opaque;
1487 s->max_size = qemu_chr_can_read(chr);
1488 return s->max_size;
1491 static void win_chr_readfile(CharDriverState *chr)
1493 WinCharState *s = chr->opaque;
1494 int ret, err;
1495 uint8_t buf[1024];
1496 DWORD size;
1498 ZeroMemory(&s->orecv, sizeof(s->orecv));
1499 s->orecv.hEvent = s->hrecv;
1500 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1501 if (!ret) {
1502 err = GetLastError();
1503 if (err == ERROR_IO_PENDING) {
1504 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1508 if (size > 0) {
1509 qemu_chr_read(chr, buf, size);
1513 static void win_chr_read(CharDriverState *chr)
1515 WinCharState *s = chr->opaque;
1517 if (s->len > s->max_size)
1518 s->len = s->max_size;
1519 if (s->len == 0)
1520 return;
1522 win_chr_readfile(chr);
1525 static int win_chr_poll(void *opaque)
1527 CharDriverState *chr = opaque;
1528 WinCharState *s = chr->opaque;
1529 COMSTAT status;
1530 DWORD comerr;
1532 ClearCommError(s->hcom, &comerr, &status);
1533 if (status.cbInQue > 0) {
1534 s->len = status.cbInQue;
1535 win_chr_read_poll(chr);
1536 win_chr_read(chr);
1537 return 1;
1539 return 0;
1542 static CharDriverState *qemu_chr_open_win(const char *filename)
1544 CharDriverState *chr;
1545 WinCharState *s;
1547 chr = qemu_mallocz(sizeof(CharDriverState));
1548 s = qemu_mallocz(sizeof(WinCharState));
1549 chr->opaque = s;
1550 chr->chr_write = win_chr_write;
1551 chr->chr_close = win_chr_close;
1553 if (win_chr_init(chr, filename) < 0) {
1554 free(s);
1555 free(chr);
1556 return NULL;
1558 qemu_chr_reset(chr);
1559 return chr;
1562 static int win_chr_pipe_poll(void *opaque)
1564 CharDriverState *chr = opaque;
1565 WinCharState *s = chr->opaque;
1566 DWORD size;
1568 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1569 if (size > 0) {
1570 s->len = size;
1571 win_chr_read_poll(chr);
1572 win_chr_read(chr);
1573 return 1;
1575 return 0;
1578 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1580 WinCharState *s = chr->opaque;
1581 OVERLAPPED ov;
1582 int ret;
1583 DWORD size;
1584 char openname[256];
1586 s->fpipe = TRUE;
1588 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1589 if (!s->hsend) {
1590 fprintf(stderr, "Failed CreateEvent\n");
1591 goto fail;
1593 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1594 if (!s->hrecv) {
1595 fprintf(stderr, "Failed CreateEvent\n");
1596 goto fail;
1599 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1600 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1601 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1602 PIPE_WAIT,
1603 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1604 if (s->hcom == INVALID_HANDLE_VALUE) {
1605 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1606 s->hcom = NULL;
1607 goto fail;
1610 ZeroMemory(&ov, sizeof(ov));
1611 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1612 ret = ConnectNamedPipe(s->hcom, &ov);
1613 if (ret) {
1614 fprintf(stderr, "Failed ConnectNamedPipe\n");
1615 goto fail;
1618 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1619 if (!ret) {
1620 fprintf(stderr, "Failed GetOverlappedResult\n");
1621 if (ov.hEvent) {
1622 CloseHandle(ov.hEvent);
1623 ov.hEvent = NULL;
1625 goto fail;
1628 if (ov.hEvent) {
1629 CloseHandle(ov.hEvent);
1630 ov.hEvent = NULL;
1632 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1633 return 0;
1635 fail:
1636 win_chr_close(chr);
1637 return -1;
1641 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
1643 CharDriverState *chr;
1644 WinCharState *s;
1646 chr = qemu_mallocz(sizeof(CharDriverState));
1647 s = qemu_mallocz(sizeof(WinCharState));
1648 chr->opaque = s;
1649 chr->chr_write = win_chr_write;
1650 chr->chr_close = win_chr_close;
1652 if (win_chr_pipe_init(chr, filename) < 0) {
1653 free(s);
1654 free(chr);
1655 return NULL;
1657 qemu_chr_reset(chr);
1658 return chr;
1661 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1663 CharDriverState *chr;
1664 WinCharState *s;
1666 chr = qemu_mallocz(sizeof(CharDriverState));
1667 s = qemu_mallocz(sizeof(WinCharState));
1668 s->hcom = fd_out;
1669 chr->opaque = s;
1670 chr->chr_write = win_chr_write;
1671 qemu_chr_reset(chr);
1672 return chr;
1675 static CharDriverState *qemu_chr_open_win_con(const char *filename)
1677 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1680 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
1682 HANDLE fd_out;
1684 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1685 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1686 if (fd_out == INVALID_HANDLE_VALUE)
1687 return NULL;
1689 return qemu_chr_open_win_file(fd_out);
1691 #endif /* !_WIN32 */
1693 /***********************************************************/
1694 /* UDP Net console */
1696 typedef struct {
1697 int fd;
1698 struct sockaddr_in daddr;
1699 uint8_t buf[1024];
1700 int bufcnt;
1701 int bufptr;
1702 int max_size;
1703 } NetCharDriver;
1705 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1707 NetCharDriver *s = chr->opaque;
1709 return sendto(s->fd, buf, len, 0,
1710 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
1713 static int udp_chr_read_poll(void *opaque)
1715 CharDriverState *chr = opaque;
1716 NetCharDriver *s = chr->opaque;
1718 s->max_size = qemu_chr_can_read(chr);
1720 /* If there were any stray characters in the queue process them
1721 * first
1723 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1724 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1725 s->bufptr++;
1726 s->max_size = qemu_chr_can_read(chr);
1728 return s->max_size;
1731 static void udp_chr_read(void *opaque)
1733 CharDriverState *chr = opaque;
1734 NetCharDriver *s = chr->opaque;
1736 if (s->max_size == 0)
1737 return;
1738 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
1739 s->bufptr = s->bufcnt;
1740 if (s->bufcnt <= 0)
1741 return;
1743 s->bufptr = 0;
1744 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1745 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1746 s->bufptr++;
1747 s->max_size = qemu_chr_can_read(chr);
1751 static void udp_chr_update_read_handler(CharDriverState *chr)
1753 NetCharDriver *s = chr->opaque;
1755 if (s->fd >= 0) {
1756 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
1757 udp_chr_read, NULL, chr);
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 return chr;
1796 return_err:
1797 if (chr)
1798 free(chr);
1799 if (s)
1800 free(s);
1801 if (fd >= 0)
1802 closesocket(fd);
1803 return NULL;
1806 /***********************************************************/
1807 /* TCP Net console */
1809 typedef struct {
1810 int fd, listen_fd;
1811 int connected;
1812 int max_size;
1813 int do_telnetopt;
1814 int do_nodelay;
1815 int is_unix;
1816 } TCPCharDriver;
1818 static void tcp_chr_accept(void *opaque);
1820 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1822 TCPCharDriver *s = chr->opaque;
1823 if (s->connected) {
1824 return send_all(s->fd, buf, len);
1825 } else {
1826 /* XXX: indicate an error ? */
1827 return len;
1831 static int tcp_chr_read_poll(void *opaque)
1833 CharDriverState *chr = opaque;
1834 TCPCharDriver *s = chr->opaque;
1835 if (!s->connected)
1836 return 0;
1837 s->max_size = qemu_chr_can_read(chr);
1838 return s->max_size;
1841 #define IAC 255
1842 #define IAC_BREAK 243
1843 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
1844 TCPCharDriver *s,
1845 uint8_t *buf, int *size)
1847 /* Handle any telnet client's basic IAC options to satisfy char by
1848 * char mode with no echo. All IAC options will be removed from
1849 * the buf and the do_telnetopt variable will be used to track the
1850 * state of the width of the IAC information.
1852 * IAC commands come in sets of 3 bytes with the exception of the
1853 * "IAC BREAK" command and the double IAC.
1856 int i;
1857 int j = 0;
1859 for (i = 0; i < *size; i++) {
1860 if (s->do_telnetopt > 1) {
1861 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
1862 /* Double IAC means send an IAC */
1863 if (j != i)
1864 buf[j] = buf[i];
1865 j++;
1866 s->do_telnetopt = 1;
1867 } else {
1868 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
1869 /* Handle IAC break commands by sending a serial break */
1870 qemu_chr_event(chr, CHR_EVENT_BREAK);
1871 s->do_telnetopt++;
1873 s->do_telnetopt++;
1875 if (s->do_telnetopt >= 4) {
1876 s->do_telnetopt = 1;
1878 } else {
1879 if ((unsigned char)buf[i] == IAC) {
1880 s->do_telnetopt = 2;
1881 } else {
1882 if (j != i)
1883 buf[j] = buf[i];
1884 j++;
1888 *size = j;
1891 static void tcp_chr_read(void *opaque)
1893 CharDriverState *chr = opaque;
1894 TCPCharDriver *s = chr->opaque;
1895 uint8_t buf[1024];
1896 int len, size;
1898 if (!s->connected || s->max_size <= 0)
1899 return;
1900 len = sizeof(buf);
1901 if (len > s->max_size)
1902 len = s->max_size;
1903 size = recv(s->fd, buf, len, 0);
1904 if (size == 0) {
1905 /* connection closed */
1906 s->connected = 0;
1907 if (s->listen_fd >= 0) {
1908 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
1910 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1911 closesocket(s->fd);
1912 s->fd = -1;
1913 } else if (size > 0) {
1914 if (s->do_telnetopt)
1915 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
1916 if (size > 0)
1917 qemu_chr_read(chr, buf, size);
1921 static void tcp_chr_connect(void *opaque)
1923 CharDriverState *chr = opaque;
1924 TCPCharDriver *s = chr->opaque;
1926 s->connected = 1;
1927 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
1928 tcp_chr_read, NULL, chr);
1929 qemu_chr_reset(chr);
1932 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
1933 static void tcp_chr_telnet_init(int fd)
1935 char buf[3];
1936 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
1937 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
1938 send(fd, (char *)buf, 3, 0);
1939 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
1940 send(fd, (char *)buf, 3, 0);
1941 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
1942 send(fd, (char *)buf, 3, 0);
1943 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
1944 send(fd, (char *)buf, 3, 0);
1947 static void socket_set_nodelay(int fd)
1949 int val = 1;
1950 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1953 static void tcp_chr_accept(void *opaque)
1955 CharDriverState *chr = opaque;
1956 TCPCharDriver *s = chr->opaque;
1957 struct sockaddr_in saddr;
1958 #ifndef _WIN32
1959 struct sockaddr_un uaddr;
1960 #endif
1961 struct sockaddr *addr;
1962 socklen_t len;
1963 int fd;
1965 for(;;) {
1966 #ifndef _WIN32
1967 if (s->is_unix) {
1968 len = sizeof(uaddr);
1969 addr = (struct sockaddr *)&uaddr;
1970 } else
1971 #endif
1973 len = sizeof(saddr);
1974 addr = (struct sockaddr *)&saddr;
1976 fd = accept(s->listen_fd, addr, &len);
1977 if (fd < 0 && errno != EINTR) {
1978 return;
1979 } else if (fd >= 0) {
1980 if (s->do_telnetopt)
1981 tcp_chr_telnet_init(fd);
1982 break;
1985 socket_set_nonblock(fd);
1986 if (s->do_nodelay)
1987 socket_set_nodelay(fd);
1988 s->fd = fd;
1989 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
1990 tcp_chr_connect(chr);
1993 static void tcp_chr_close(CharDriverState *chr)
1995 TCPCharDriver *s = chr->opaque;
1996 if (s->fd >= 0)
1997 closesocket(s->fd);
1998 if (s->listen_fd >= 0)
1999 closesocket(s->listen_fd);
2000 qemu_free(s);
2003 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2004 int is_telnet,
2005 int is_unix)
2007 CharDriverState *chr = NULL;
2008 TCPCharDriver *s = NULL;
2009 int fd = -1, offset = 0;
2010 int is_listen = 0;
2011 int is_waitconnect = 1;
2012 int do_nodelay = 0;
2013 const char *ptr;
2015 ptr = host_str;
2016 while((ptr = strchr(ptr,','))) {
2017 ptr++;
2018 if (!strncmp(ptr,"server",6)) {
2019 is_listen = 1;
2020 } else if (!strncmp(ptr,"nowait",6)) {
2021 is_waitconnect = 0;
2022 } else if (!strncmp(ptr,"nodelay",6)) {
2023 do_nodelay = 1;
2024 } else if (!strncmp(ptr,"to=",3)) {
2025 /* nothing, inet_listen() parses this one */;
2026 } else if (!strncmp(ptr,"ipv4",4)) {
2027 /* nothing, inet_connect() and inet_listen() parse this one */;
2028 } else if (!strncmp(ptr,"ipv6",4)) {
2029 /* nothing, inet_connect() and inet_listen() parse this one */;
2030 } else {
2031 printf("Unknown option: %s\n", ptr);
2032 goto fail;
2035 if (!is_listen)
2036 is_waitconnect = 0;
2038 chr = qemu_mallocz(sizeof(CharDriverState));
2039 s = qemu_mallocz(sizeof(TCPCharDriver));
2041 if (is_listen) {
2042 chr->filename = qemu_malloc(256);
2043 if (is_unix) {
2044 pstrcpy(chr->filename, 256, "unix:");
2045 } else if (is_telnet) {
2046 pstrcpy(chr->filename, 256, "telnet:");
2047 } else {
2048 pstrcpy(chr->filename, 256, "tcp:");
2050 offset = strlen(chr->filename);
2052 if (is_unix) {
2053 if (is_listen) {
2054 fd = unix_listen(host_str, chr->filename + offset, 256 - offset);
2055 } else {
2056 fd = unix_connect(host_str);
2058 } else {
2059 if (is_listen) {
2060 fd = inet_listen(host_str, chr->filename + offset, 256 - offset,
2061 SOCK_STREAM, 0);
2062 } else {
2063 fd = inet_connect(host_str, SOCK_STREAM);
2066 if (fd < 0)
2067 goto fail;
2069 if (!is_waitconnect)
2070 socket_set_nonblock(fd);
2072 s->connected = 0;
2073 s->fd = -1;
2074 s->listen_fd = -1;
2075 s->is_unix = is_unix;
2076 s->do_nodelay = do_nodelay && !is_unix;
2078 chr->opaque = s;
2079 chr->chr_write = tcp_chr_write;
2080 chr->chr_close = tcp_chr_close;
2082 if (is_listen) {
2083 s->listen_fd = fd;
2084 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2085 if (is_telnet)
2086 s->do_telnetopt = 1;
2087 } else {
2088 s->connected = 1;
2089 s->fd = fd;
2090 socket_set_nodelay(fd);
2091 tcp_chr_connect(chr);
2094 if (is_listen && is_waitconnect) {
2095 printf("QEMU waiting for connection on: %s\n",
2096 chr->filename ? chr->filename : host_str);
2097 tcp_chr_accept(chr);
2098 socket_set_nonblock(s->listen_fd);
2101 return chr;
2102 fail:
2103 if (fd >= 0)
2104 closesocket(fd);
2105 qemu_free(s);
2106 qemu_free(chr);
2107 return NULL;
2110 CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2112 const char *p;
2113 CharDriverState *chr;
2115 if (!strcmp(filename, "vc")) {
2116 chr = text_console_init(0);
2117 } else
2118 if (strstart(filename, "vc:", &p)) {
2119 chr = text_console_init(p);
2120 } else
2121 if (!strcmp(filename, "null")) {
2122 chr = qemu_chr_open_null();
2123 } else
2124 if (strstart(filename, "tcp:", &p)) {
2125 chr = qemu_chr_open_tcp(p, 0, 0);
2126 } else
2127 if (strstart(filename, "telnet:", &p)) {
2128 chr = qemu_chr_open_tcp(p, 1, 0);
2129 } else
2130 if (strstart(filename, "udp:", &p)) {
2131 chr = qemu_chr_open_udp(p);
2132 } else
2133 if (strstart(filename, "mon:", &p)) {
2134 chr = qemu_chr_open(label, p, NULL);
2135 if (chr) {
2136 chr = qemu_chr_open_mux(chr);
2137 monitor_init(chr, MONITOR_USE_READLINE);
2138 } else {
2139 printf("Unable to open driver: %s\n", p);
2141 } else if (!strcmp(filename, "msmouse")) {
2142 chr = qemu_chr_open_msmouse();
2143 } else
2144 #ifndef _WIN32
2145 if (strstart(filename, "unix:", &p)) {
2146 chr = qemu_chr_open_tcp(p, 0, 1);
2147 } else if (strstart(filename, "file:", &p)) {
2148 chr = qemu_chr_open_file_out(p);
2149 } else if (strstart(filename, "pipe:", &p)) {
2150 chr = qemu_chr_open_pipe(p);
2151 } else if (!strcmp(filename, "pty")) {
2152 chr = qemu_chr_open_pty();
2153 } else if (!strcmp(filename, "stdio")) {
2154 chr = qemu_chr_open_stdio();
2155 } else
2156 #if defined(__linux__)
2157 if (strstart(filename, "/dev/parport", NULL)) {
2158 chr = qemu_chr_open_pp(filename);
2159 } else
2160 #elif defined(__FreeBSD__) || defined(__DragonFly__)
2161 if (strstart(filename, "/dev/ppi", NULL)) {
2162 chr = qemu_chr_open_pp(filename);
2163 } else
2164 #endif
2165 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2166 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
2167 if (strstart(filename, "/dev/", NULL)) {
2168 chr = qemu_chr_open_tty(filename);
2169 } else
2170 #endif
2171 #else /* !_WIN32 */
2172 if (strstart(filename, "COM", NULL)) {
2173 chr = qemu_chr_open_win(filename);
2174 } else
2175 if (strstart(filename, "pipe:", &p)) {
2176 chr = qemu_chr_open_win_pipe(p);
2177 } else
2178 if (strstart(filename, "con:", NULL)) {
2179 chr = qemu_chr_open_win_con(filename);
2180 } else
2181 if (strstart(filename, "file:", &p)) {
2182 chr = qemu_chr_open_win_file_out(p);
2183 } else
2184 #endif
2185 #ifdef CONFIG_BRLAPI
2186 if (!strcmp(filename, "braille")) {
2187 chr = chr_baum_init();
2188 } else
2189 #endif
2191 chr = NULL;
2194 if (chr) {
2195 if (!chr->filename)
2196 chr->filename = qemu_strdup(filename);
2197 chr->init = init;
2198 chr->label = qemu_strdup(label);
2199 TAILQ_INSERT_TAIL(&chardevs, chr, next);
2201 return chr;
2204 void qemu_chr_close(CharDriverState *chr)
2206 TAILQ_REMOVE(&chardevs, chr, next);
2207 if (chr->chr_close)
2208 chr->chr_close(chr);
2209 qemu_free(chr->filename);
2210 qemu_free(chr->label);
2211 qemu_free(chr);
2214 void qemu_chr_info(Monitor *mon)
2216 CharDriverState *chr;
2218 TAILQ_FOREACH(chr, &chardevs, next) {
2219 monitor_printf(mon, "%s: filename=%s\n", chr->label, chr->filename);