raw-posix: fix hdev_create
[qemu-kvm/fedora.git] / qemu-char.c
blob1c0c9f5dffec287150dabab4400e73101d11d391
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 (display_type == DT_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 (display_type == DT_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 (display_type == DT_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 static 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 static 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_del_timer(s->timer);
933 qemu_free_timer(s->timer);
934 qemu_free(s);
937 static CharDriverState *qemu_chr_open_pty(void)
939 CharDriverState *chr;
940 PtyCharDriver *s;
941 struct termios tty;
942 int slave_fd, len;
943 #if defined(__OpenBSD__) || defined(__DragonFly__)
944 char pty_name[PATH_MAX];
945 #define q_ptsname(x) pty_name
946 #else
947 char *pty_name = NULL;
948 #define q_ptsname(x) ptsname(x)
949 #endif
951 chr = qemu_mallocz(sizeof(CharDriverState));
952 s = qemu_mallocz(sizeof(PtyCharDriver));
954 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
955 return NULL;
958 /* Set raw attributes on the pty. */
959 tcgetattr(slave_fd, &tty);
960 cfmakeraw(&tty);
961 tcsetattr(slave_fd, TCSAFLUSH, &tty);
962 close(slave_fd);
964 len = strlen(q_ptsname(s->fd)) + 5;
965 chr->filename = qemu_malloc(len);
966 snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
967 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
969 chr->opaque = s;
970 chr->chr_write = pty_chr_write;
971 chr->chr_update_read_handler = pty_chr_update_read_handler;
972 chr->chr_close = pty_chr_close;
974 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
976 return chr;
979 static void tty_serial_init(int fd, int speed,
980 int parity, int data_bits, int stop_bits)
982 struct termios tty;
983 speed_t spd;
985 #if 0
986 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
987 speed, parity, data_bits, stop_bits);
988 #endif
989 tcgetattr (fd, &tty);
991 #define MARGIN 1.1
992 if (speed <= 50 * MARGIN)
993 spd = B50;
994 else if (speed <= 75 * MARGIN)
995 spd = B75;
996 else if (speed <= 300 * MARGIN)
997 spd = B300;
998 else if (speed <= 600 * MARGIN)
999 spd = B600;
1000 else if (speed <= 1200 * MARGIN)
1001 spd = B1200;
1002 else if (speed <= 2400 * MARGIN)
1003 spd = B2400;
1004 else if (speed <= 4800 * MARGIN)
1005 spd = B4800;
1006 else if (speed <= 9600 * MARGIN)
1007 spd = B9600;
1008 else if (speed <= 19200 * MARGIN)
1009 spd = B19200;
1010 else if (speed <= 38400 * MARGIN)
1011 spd = B38400;
1012 else if (speed <= 57600 * MARGIN)
1013 spd = B57600;
1014 else if (speed <= 115200 * MARGIN)
1015 spd = B115200;
1016 else
1017 spd = B115200;
1019 cfsetispeed(&tty, spd);
1020 cfsetospeed(&tty, spd);
1022 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1023 |INLCR|IGNCR|ICRNL|IXON);
1024 tty.c_oflag |= OPOST;
1025 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1026 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1027 switch(data_bits) {
1028 default:
1029 case 8:
1030 tty.c_cflag |= CS8;
1031 break;
1032 case 7:
1033 tty.c_cflag |= CS7;
1034 break;
1035 case 6:
1036 tty.c_cflag |= CS6;
1037 break;
1038 case 5:
1039 tty.c_cflag |= CS5;
1040 break;
1042 switch(parity) {
1043 default:
1044 case 'N':
1045 break;
1046 case 'E':
1047 tty.c_cflag |= PARENB;
1048 break;
1049 case 'O':
1050 tty.c_cflag |= PARENB | PARODD;
1051 break;
1053 if (stop_bits == 2)
1054 tty.c_cflag |= CSTOPB;
1056 tcsetattr (fd, TCSANOW, &tty);
1059 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1061 FDCharDriver *s = chr->opaque;
1063 switch(cmd) {
1064 case CHR_IOCTL_SERIAL_SET_PARAMS:
1066 QEMUSerialSetParams *ssp = arg;
1067 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1068 ssp->data_bits, ssp->stop_bits);
1070 break;
1071 case CHR_IOCTL_SERIAL_SET_BREAK:
1073 int enable = *(int *)arg;
1074 if (enable)
1075 tcsendbreak(s->fd_in, 1);
1077 break;
1078 case CHR_IOCTL_SERIAL_GET_TIOCM:
1080 int sarg = 0;
1081 int *targ = (int *)arg;
1082 ioctl(s->fd_in, TIOCMGET, &sarg);
1083 *targ = 0;
1084 if (sarg & TIOCM_CTS)
1085 *targ |= CHR_TIOCM_CTS;
1086 if (sarg & TIOCM_CAR)
1087 *targ |= CHR_TIOCM_CAR;
1088 if (sarg & TIOCM_DSR)
1089 *targ |= CHR_TIOCM_DSR;
1090 if (sarg & TIOCM_RI)
1091 *targ |= CHR_TIOCM_RI;
1092 if (sarg & TIOCM_DTR)
1093 *targ |= CHR_TIOCM_DTR;
1094 if (sarg & TIOCM_RTS)
1095 *targ |= CHR_TIOCM_RTS;
1097 break;
1098 case CHR_IOCTL_SERIAL_SET_TIOCM:
1100 int sarg = *(int *)arg;
1101 int targ = 0;
1102 ioctl(s->fd_in, TIOCMGET, &targ);
1103 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1104 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1105 if (sarg & CHR_TIOCM_CTS)
1106 targ |= TIOCM_CTS;
1107 if (sarg & CHR_TIOCM_CAR)
1108 targ |= TIOCM_CAR;
1109 if (sarg & CHR_TIOCM_DSR)
1110 targ |= TIOCM_DSR;
1111 if (sarg & CHR_TIOCM_RI)
1112 targ |= TIOCM_RI;
1113 if (sarg & CHR_TIOCM_DTR)
1114 targ |= TIOCM_DTR;
1115 if (sarg & CHR_TIOCM_RTS)
1116 targ |= TIOCM_RTS;
1117 ioctl(s->fd_in, TIOCMSET, &targ);
1119 break;
1120 default:
1121 return -ENOTSUP;
1123 return 0;
1126 static CharDriverState *qemu_chr_open_tty(const char *filename)
1128 CharDriverState *chr;
1129 int fd;
1131 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
1132 tty_serial_init(fd, 115200, 'N', 8, 1);
1133 chr = qemu_chr_open_fd(fd, fd);
1134 if (!chr) {
1135 close(fd);
1136 return NULL;
1138 chr->chr_ioctl = tty_serial_ioctl;
1139 qemu_chr_reset(chr);
1140 return chr;
1142 #else /* ! __linux__ && ! __sun__ */
1143 static CharDriverState *qemu_chr_open_pty(void)
1145 return NULL;
1147 #endif /* __linux__ || __sun__ */
1149 #if defined(__linux__)
1150 typedef struct {
1151 int fd;
1152 int mode;
1153 } ParallelCharDriver;
1155 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1157 if (s->mode != mode) {
1158 int m = mode;
1159 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1160 return 0;
1161 s->mode = mode;
1163 return 1;
1166 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1168 ParallelCharDriver *drv = chr->opaque;
1169 int fd = drv->fd;
1170 uint8_t b;
1172 switch(cmd) {
1173 case CHR_IOCTL_PP_READ_DATA:
1174 if (ioctl(fd, PPRDATA, &b) < 0)
1175 return -ENOTSUP;
1176 *(uint8_t *)arg = b;
1177 break;
1178 case CHR_IOCTL_PP_WRITE_DATA:
1179 b = *(uint8_t *)arg;
1180 if (ioctl(fd, PPWDATA, &b) < 0)
1181 return -ENOTSUP;
1182 break;
1183 case CHR_IOCTL_PP_READ_CONTROL:
1184 if (ioctl(fd, PPRCONTROL, &b) < 0)
1185 return -ENOTSUP;
1186 /* Linux gives only the lowest bits, and no way to know data
1187 direction! For better compatibility set the fixed upper
1188 bits. */
1189 *(uint8_t *)arg = b | 0xc0;
1190 break;
1191 case CHR_IOCTL_PP_WRITE_CONTROL:
1192 b = *(uint8_t *)arg;
1193 if (ioctl(fd, PPWCONTROL, &b) < 0)
1194 return -ENOTSUP;
1195 break;
1196 case CHR_IOCTL_PP_READ_STATUS:
1197 if (ioctl(fd, PPRSTATUS, &b) < 0)
1198 return -ENOTSUP;
1199 *(uint8_t *)arg = b;
1200 break;
1201 case CHR_IOCTL_PP_DATA_DIR:
1202 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1203 return -ENOTSUP;
1204 break;
1205 case CHR_IOCTL_PP_EPP_READ_ADDR:
1206 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1207 struct ParallelIOArg *parg = arg;
1208 int n = read(fd, parg->buffer, parg->count);
1209 if (n != parg->count) {
1210 return -EIO;
1213 break;
1214 case CHR_IOCTL_PP_EPP_READ:
1215 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1216 struct ParallelIOArg *parg = arg;
1217 int n = read(fd, parg->buffer, parg->count);
1218 if (n != parg->count) {
1219 return -EIO;
1222 break;
1223 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1224 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1225 struct ParallelIOArg *parg = arg;
1226 int n = write(fd, parg->buffer, parg->count);
1227 if (n != parg->count) {
1228 return -EIO;
1231 break;
1232 case CHR_IOCTL_PP_EPP_WRITE:
1233 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1234 struct ParallelIOArg *parg = arg;
1235 int n = write(fd, parg->buffer, parg->count);
1236 if (n != parg->count) {
1237 return -EIO;
1240 break;
1241 default:
1242 return -ENOTSUP;
1244 return 0;
1247 static void pp_close(CharDriverState *chr)
1249 ParallelCharDriver *drv = chr->opaque;
1250 int fd = drv->fd;
1252 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1253 ioctl(fd, PPRELEASE);
1254 close(fd);
1255 qemu_free(drv);
1258 static CharDriverState *qemu_chr_open_pp(const char *filename)
1260 CharDriverState *chr;
1261 ParallelCharDriver *drv;
1262 int fd;
1264 TFR(fd = open(filename, O_RDWR));
1265 if (fd < 0)
1266 return NULL;
1268 if (ioctl(fd, PPCLAIM) < 0) {
1269 close(fd);
1270 return NULL;
1273 drv = qemu_mallocz(sizeof(ParallelCharDriver));
1274 drv->fd = fd;
1275 drv->mode = IEEE1284_MODE_COMPAT;
1277 chr = qemu_mallocz(sizeof(CharDriverState));
1278 chr->chr_write = null_chr_write;
1279 chr->chr_ioctl = pp_ioctl;
1280 chr->chr_close = pp_close;
1281 chr->opaque = drv;
1283 qemu_chr_reset(chr);
1285 return chr;
1287 #endif /* __linux__ */
1289 #if defined(__FreeBSD__) || defined(__DragonFly__)
1290 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1292 int fd = (int)chr->opaque;
1293 uint8_t b;
1295 switch(cmd) {
1296 case CHR_IOCTL_PP_READ_DATA:
1297 if (ioctl(fd, PPIGDATA, &b) < 0)
1298 return -ENOTSUP;
1299 *(uint8_t *)arg = b;
1300 break;
1301 case CHR_IOCTL_PP_WRITE_DATA:
1302 b = *(uint8_t *)arg;
1303 if (ioctl(fd, PPISDATA, &b) < 0)
1304 return -ENOTSUP;
1305 break;
1306 case CHR_IOCTL_PP_READ_CONTROL:
1307 if (ioctl(fd, PPIGCTRL, &b) < 0)
1308 return -ENOTSUP;
1309 *(uint8_t *)arg = b;
1310 break;
1311 case CHR_IOCTL_PP_WRITE_CONTROL:
1312 b = *(uint8_t *)arg;
1313 if (ioctl(fd, PPISCTRL, &b) < 0)
1314 return -ENOTSUP;
1315 break;
1316 case CHR_IOCTL_PP_READ_STATUS:
1317 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1318 return -ENOTSUP;
1319 *(uint8_t *)arg = b;
1320 break;
1321 default:
1322 return -ENOTSUP;
1324 return 0;
1327 static CharDriverState *qemu_chr_open_pp(const char *filename)
1329 CharDriverState *chr;
1330 int fd;
1332 fd = open(filename, O_RDWR);
1333 if (fd < 0)
1334 return NULL;
1336 chr = qemu_mallocz(sizeof(CharDriverState));
1337 chr->opaque = (void *)fd;
1338 chr->chr_write = null_chr_write;
1339 chr->chr_ioctl = pp_ioctl;
1340 return chr;
1342 #endif
1344 #else /* _WIN32 */
1346 typedef struct {
1347 int max_size;
1348 HANDLE hcom, hrecv, hsend;
1349 OVERLAPPED orecv, osend;
1350 BOOL fpipe;
1351 DWORD len;
1352 } WinCharState;
1354 #define NSENDBUF 2048
1355 #define NRECVBUF 2048
1356 #define MAXCONNECT 1
1357 #define NTIMEOUT 5000
1359 static int win_chr_poll(void *opaque);
1360 static int win_chr_pipe_poll(void *opaque);
1362 static void win_chr_close(CharDriverState *chr)
1364 WinCharState *s = chr->opaque;
1366 if (s->hsend) {
1367 CloseHandle(s->hsend);
1368 s->hsend = NULL;
1370 if (s->hrecv) {
1371 CloseHandle(s->hrecv);
1372 s->hrecv = NULL;
1374 if (s->hcom) {
1375 CloseHandle(s->hcom);
1376 s->hcom = NULL;
1378 if (s->fpipe)
1379 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1380 else
1381 qemu_del_polling_cb(win_chr_poll, chr);
1384 static int win_chr_init(CharDriverState *chr, const char *filename)
1386 WinCharState *s = chr->opaque;
1387 COMMCONFIG comcfg;
1388 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1389 COMSTAT comstat;
1390 DWORD size;
1391 DWORD err;
1393 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1394 if (!s->hsend) {
1395 fprintf(stderr, "Failed CreateEvent\n");
1396 goto fail;
1398 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1399 if (!s->hrecv) {
1400 fprintf(stderr, "Failed CreateEvent\n");
1401 goto fail;
1404 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1405 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1406 if (s->hcom == INVALID_HANDLE_VALUE) {
1407 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1408 s->hcom = NULL;
1409 goto fail;
1412 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1413 fprintf(stderr, "Failed SetupComm\n");
1414 goto fail;
1417 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1418 size = sizeof(COMMCONFIG);
1419 GetDefaultCommConfig(filename, &comcfg, &size);
1420 comcfg.dcb.DCBlength = sizeof(DCB);
1421 CommConfigDialog(filename, NULL, &comcfg);
1423 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1424 fprintf(stderr, "Failed SetCommState\n");
1425 goto fail;
1428 if (!SetCommMask(s->hcom, EV_ERR)) {
1429 fprintf(stderr, "Failed SetCommMask\n");
1430 goto fail;
1433 cto.ReadIntervalTimeout = MAXDWORD;
1434 if (!SetCommTimeouts(s->hcom, &cto)) {
1435 fprintf(stderr, "Failed SetCommTimeouts\n");
1436 goto fail;
1439 if (!ClearCommError(s->hcom, &err, &comstat)) {
1440 fprintf(stderr, "Failed ClearCommError\n");
1441 goto fail;
1443 qemu_add_polling_cb(win_chr_poll, chr);
1444 return 0;
1446 fail:
1447 win_chr_close(chr);
1448 return -1;
1451 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1453 WinCharState *s = chr->opaque;
1454 DWORD len, ret, size, err;
1456 len = len1;
1457 ZeroMemory(&s->osend, sizeof(s->osend));
1458 s->osend.hEvent = s->hsend;
1459 while (len > 0) {
1460 if (s->hsend)
1461 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1462 else
1463 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1464 if (!ret) {
1465 err = GetLastError();
1466 if (err == ERROR_IO_PENDING) {
1467 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1468 if (ret) {
1469 buf += size;
1470 len -= size;
1471 } else {
1472 break;
1474 } else {
1475 break;
1477 } else {
1478 buf += size;
1479 len -= size;
1482 return len1 - len;
1485 static int win_chr_read_poll(CharDriverState *chr)
1487 WinCharState *s = chr->opaque;
1489 s->max_size = qemu_chr_can_read(chr);
1490 return s->max_size;
1493 static void win_chr_readfile(CharDriverState *chr)
1495 WinCharState *s = chr->opaque;
1496 int ret, err;
1497 uint8_t buf[1024];
1498 DWORD size;
1500 ZeroMemory(&s->orecv, sizeof(s->orecv));
1501 s->orecv.hEvent = s->hrecv;
1502 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1503 if (!ret) {
1504 err = GetLastError();
1505 if (err == ERROR_IO_PENDING) {
1506 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1510 if (size > 0) {
1511 qemu_chr_read(chr, buf, size);
1515 static void win_chr_read(CharDriverState *chr)
1517 WinCharState *s = chr->opaque;
1519 if (s->len > s->max_size)
1520 s->len = s->max_size;
1521 if (s->len == 0)
1522 return;
1524 win_chr_readfile(chr);
1527 static int win_chr_poll(void *opaque)
1529 CharDriverState *chr = opaque;
1530 WinCharState *s = chr->opaque;
1531 COMSTAT status;
1532 DWORD comerr;
1534 ClearCommError(s->hcom, &comerr, &status);
1535 if (status.cbInQue > 0) {
1536 s->len = status.cbInQue;
1537 win_chr_read_poll(chr);
1538 win_chr_read(chr);
1539 return 1;
1541 return 0;
1544 static CharDriverState *qemu_chr_open_win(const char *filename)
1546 CharDriverState *chr;
1547 WinCharState *s;
1549 chr = qemu_mallocz(sizeof(CharDriverState));
1550 s = qemu_mallocz(sizeof(WinCharState));
1551 chr->opaque = s;
1552 chr->chr_write = win_chr_write;
1553 chr->chr_close = win_chr_close;
1555 if (win_chr_init(chr, filename) < 0) {
1556 free(s);
1557 free(chr);
1558 return NULL;
1560 qemu_chr_reset(chr);
1561 return chr;
1564 static int win_chr_pipe_poll(void *opaque)
1566 CharDriverState *chr = opaque;
1567 WinCharState *s = chr->opaque;
1568 DWORD size;
1570 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1571 if (size > 0) {
1572 s->len = size;
1573 win_chr_read_poll(chr);
1574 win_chr_read(chr);
1575 return 1;
1577 return 0;
1580 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1582 WinCharState *s = chr->opaque;
1583 OVERLAPPED ov;
1584 int ret;
1585 DWORD size;
1586 char openname[256];
1588 s->fpipe = TRUE;
1590 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1591 if (!s->hsend) {
1592 fprintf(stderr, "Failed CreateEvent\n");
1593 goto fail;
1595 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1596 if (!s->hrecv) {
1597 fprintf(stderr, "Failed CreateEvent\n");
1598 goto fail;
1601 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1602 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1603 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1604 PIPE_WAIT,
1605 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1606 if (s->hcom == INVALID_HANDLE_VALUE) {
1607 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1608 s->hcom = NULL;
1609 goto fail;
1612 ZeroMemory(&ov, sizeof(ov));
1613 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1614 ret = ConnectNamedPipe(s->hcom, &ov);
1615 if (ret) {
1616 fprintf(stderr, "Failed ConnectNamedPipe\n");
1617 goto fail;
1620 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1621 if (!ret) {
1622 fprintf(stderr, "Failed GetOverlappedResult\n");
1623 if (ov.hEvent) {
1624 CloseHandle(ov.hEvent);
1625 ov.hEvent = NULL;
1627 goto fail;
1630 if (ov.hEvent) {
1631 CloseHandle(ov.hEvent);
1632 ov.hEvent = NULL;
1634 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1635 return 0;
1637 fail:
1638 win_chr_close(chr);
1639 return -1;
1643 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
1645 CharDriverState *chr;
1646 WinCharState *s;
1648 chr = qemu_mallocz(sizeof(CharDriverState));
1649 s = qemu_mallocz(sizeof(WinCharState));
1650 chr->opaque = s;
1651 chr->chr_write = win_chr_write;
1652 chr->chr_close = win_chr_close;
1654 if (win_chr_pipe_init(chr, filename) < 0) {
1655 free(s);
1656 free(chr);
1657 return NULL;
1659 qemu_chr_reset(chr);
1660 return chr;
1663 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1665 CharDriverState *chr;
1666 WinCharState *s;
1668 chr = qemu_mallocz(sizeof(CharDriverState));
1669 s = qemu_mallocz(sizeof(WinCharState));
1670 s->hcom = fd_out;
1671 chr->opaque = s;
1672 chr->chr_write = win_chr_write;
1673 qemu_chr_reset(chr);
1674 return chr;
1677 static CharDriverState *qemu_chr_open_win_con(const char *filename)
1679 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1682 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
1684 HANDLE fd_out;
1686 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1687 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1688 if (fd_out == INVALID_HANDLE_VALUE)
1689 return NULL;
1691 return qemu_chr_open_win_file(fd_out);
1693 #endif /* !_WIN32 */
1695 /***********************************************************/
1696 /* UDP Net console */
1698 typedef struct {
1699 int fd;
1700 struct sockaddr_in daddr;
1701 uint8_t buf[1024];
1702 int bufcnt;
1703 int bufptr;
1704 int max_size;
1705 } NetCharDriver;
1707 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1709 NetCharDriver *s = chr->opaque;
1711 return sendto(s->fd, buf, len, 0,
1712 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
1715 static int udp_chr_read_poll(void *opaque)
1717 CharDriverState *chr = opaque;
1718 NetCharDriver *s = chr->opaque;
1720 s->max_size = qemu_chr_can_read(chr);
1722 /* If there were any stray characters in the queue process them
1723 * first
1725 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1726 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1727 s->bufptr++;
1728 s->max_size = qemu_chr_can_read(chr);
1730 return s->max_size;
1733 static void udp_chr_read(void *opaque)
1735 CharDriverState *chr = opaque;
1736 NetCharDriver *s = chr->opaque;
1738 if (s->max_size == 0)
1739 return;
1740 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
1741 s->bufptr = s->bufcnt;
1742 if (s->bufcnt <= 0)
1743 return;
1745 s->bufptr = 0;
1746 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1747 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1748 s->bufptr++;
1749 s->max_size = qemu_chr_can_read(chr);
1753 static void udp_chr_update_read_handler(CharDriverState *chr)
1755 NetCharDriver *s = chr->opaque;
1757 if (s->fd >= 0) {
1758 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
1759 udp_chr_read, NULL, chr);
1763 static void udp_chr_close(CharDriverState *chr)
1765 NetCharDriver *s = chr->opaque;
1766 if (s->fd >= 0) {
1767 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1768 closesocket(s->fd);
1770 qemu_free(s);
1773 static CharDriverState *qemu_chr_open_udp(const char *def)
1775 CharDriverState *chr = NULL;
1776 NetCharDriver *s = NULL;
1777 int fd = -1;
1778 struct sockaddr_in saddr;
1780 chr = qemu_mallocz(sizeof(CharDriverState));
1781 s = qemu_mallocz(sizeof(NetCharDriver));
1783 fd = socket(PF_INET, SOCK_DGRAM, 0);
1784 if (fd < 0) {
1785 perror("socket(PF_INET, SOCK_DGRAM)");
1786 goto return_err;
1789 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
1790 printf("Could not parse: %s\n", def);
1791 goto return_err;
1794 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
1796 perror("bind");
1797 goto return_err;
1800 s->fd = fd;
1801 s->bufcnt = 0;
1802 s->bufptr = 0;
1803 chr->opaque = s;
1804 chr->chr_write = udp_chr_write;
1805 chr->chr_update_read_handler = udp_chr_update_read_handler;
1806 chr->chr_close = udp_chr_close;
1807 return chr;
1809 return_err:
1810 if (chr)
1811 free(chr);
1812 if (s)
1813 free(s);
1814 if (fd >= 0)
1815 closesocket(fd);
1816 return NULL;
1819 /***********************************************************/
1820 /* TCP Net console */
1822 typedef struct {
1823 int fd, listen_fd;
1824 int connected;
1825 int max_size;
1826 int do_telnetopt;
1827 int do_nodelay;
1828 int is_unix;
1829 } TCPCharDriver;
1831 static void tcp_chr_accept(void *opaque);
1833 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1835 TCPCharDriver *s = chr->opaque;
1836 if (s->connected) {
1837 return send_all(s->fd, buf, len);
1838 } else {
1839 /* XXX: indicate an error ? */
1840 return len;
1844 static int tcp_chr_read_poll(void *opaque)
1846 CharDriverState *chr = opaque;
1847 TCPCharDriver *s = chr->opaque;
1848 if (!s->connected)
1849 return 0;
1850 s->max_size = qemu_chr_can_read(chr);
1851 return s->max_size;
1854 #define IAC 255
1855 #define IAC_BREAK 243
1856 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
1857 TCPCharDriver *s,
1858 uint8_t *buf, int *size)
1860 /* Handle any telnet client's basic IAC options to satisfy char by
1861 * char mode with no echo. All IAC options will be removed from
1862 * the buf and the do_telnetopt variable will be used to track the
1863 * state of the width of the IAC information.
1865 * IAC commands come in sets of 3 bytes with the exception of the
1866 * "IAC BREAK" command and the double IAC.
1869 int i;
1870 int j = 0;
1872 for (i = 0; i < *size; i++) {
1873 if (s->do_telnetopt > 1) {
1874 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
1875 /* Double IAC means send an IAC */
1876 if (j != i)
1877 buf[j] = buf[i];
1878 j++;
1879 s->do_telnetopt = 1;
1880 } else {
1881 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
1882 /* Handle IAC break commands by sending a serial break */
1883 qemu_chr_event(chr, CHR_EVENT_BREAK);
1884 s->do_telnetopt++;
1886 s->do_telnetopt++;
1888 if (s->do_telnetopt >= 4) {
1889 s->do_telnetopt = 1;
1891 } else {
1892 if ((unsigned char)buf[i] == IAC) {
1893 s->do_telnetopt = 2;
1894 } else {
1895 if (j != i)
1896 buf[j] = buf[i];
1897 j++;
1901 *size = j;
1904 static void tcp_chr_read(void *opaque)
1906 CharDriverState *chr = opaque;
1907 TCPCharDriver *s = chr->opaque;
1908 uint8_t buf[1024];
1909 int len, size;
1911 if (!s->connected || s->max_size <= 0)
1912 return;
1913 len = sizeof(buf);
1914 if (len > s->max_size)
1915 len = s->max_size;
1916 size = recv(s->fd, buf, len, 0);
1917 if (size == 0) {
1918 /* connection closed */
1919 s->connected = 0;
1920 if (s->listen_fd >= 0) {
1921 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
1923 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1924 closesocket(s->fd);
1925 s->fd = -1;
1926 } else if (size > 0) {
1927 if (s->do_telnetopt)
1928 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
1929 if (size > 0)
1930 qemu_chr_read(chr, buf, size);
1934 static void tcp_chr_connect(void *opaque)
1936 CharDriverState *chr = opaque;
1937 TCPCharDriver *s = chr->opaque;
1939 s->connected = 1;
1940 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
1941 tcp_chr_read, NULL, chr);
1942 qemu_chr_reset(chr);
1945 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
1946 static void tcp_chr_telnet_init(int fd)
1948 char buf[3];
1949 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
1950 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
1951 send(fd, (char *)buf, 3, 0);
1952 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
1953 send(fd, (char *)buf, 3, 0);
1954 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
1955 send(fd, (char *)buf, 3, 0);
1956 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
1957 send(fd, (char *)buf, 3, 0);
1960 static void socket_set_nodelay(int fd)
1962 int val = 1;
1963 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1966 static void tcp_chr_accept(void *opaque)
1968 CharDriverState *chr = opaque;
1969 TCPCharDriver *s = chr->opaque;
1970 struct sockaddr_in saddr;
1971 #ifndef _WIN32
1972 struct sockaddr_un uaddr;
1973 #endif
1974 struct sockaddr *addr;
1975 socklen_t len;
1976 int fd;
1978 for(;;) {
1979 #ifndef _WIN32
1980 if (s->is_unix) {
1981 len = sizeof(uaddr);
1982 addr = (struct sockaddr *)&uaddr;
1983 } else
1984 #endif
1986 len = sizeof(saddr);
1987 addr = (struct sockaddr *)&saddr;
1989 fd = accept(s->listen_fd, addr, &len);
1990 if (fd < 0 && errno != EINTR) {
1991 return;
1992 } else if (fd >= 0) {
1993 if (s->do_telnetopt)
1994 tcp_chr_telnet_init(fd);
1995 break;
1998 socket_set_nonblock(fd);
1999 if (s->do_nodelay)
2000 socket_set_nodelay(fd);
2001 s->fd = fd;
2002 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2003 tcp_chr_connect(chr);
2006 static void tcp_chr_close(CharDriverState *chr)
2008 TCPCharDriver *s = chr->opaque;
2009 if (s->fd >= 0) {
2010 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2011 closesocket(s->fd);
2013 if (s->listen_fd >= 0) {
2014 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2015 closesocket(s->listen_fd);
2017 qemu_free(s);
2020 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2021 int is_telnet,
2022 int is_unix)
2024 CharDriverState *chr = NULL;
2025 TCPCharDriver *s = NULL;
2026 int fd = -1, offset = 0;
2027 int is_listen = 0;
2028 int is_waitconnect = 1;
2029 int do_nodelay = 0;
2030 const char *ptr;
2032 ptr = host_str;
2033 while((ptr = strchr(ptr,','))) {
2034 ptr++;
2035 if (!strncmp(ptr,"server",6)) {
2036 is_listen = 1;
2037 } else if (!strncmp(ptr,"nowait",6)) {
2038 is_waitconnect = 0;
2039 } else if (!strncmp(ptr,"nodelay",6)) {
2040 do_nodelay = 1;
2041 } else if (!strncmp(ptr,"to=",3)) {
2042 /* nothing, inet_listen() parses this one */;
2043 } else if (!strncmp(ptr,"ipv4",4)) {
2044 /* nothing, inet_connect() and inet_listen() parse this one */;
2045 } else if (!strncmp(ptr,"ipv6",4)) {
2046 /* nothing, inet_connect() and inet_listen() parse this one */;
2047 } else {
2048 printf("Unknown option: %s\n", ptr);
2049 goto fail;
2052 if (!is_listen)
2053 is_waitconnect = 0;
2055 chr = qemu_mallocz(sizeof(CharDriverState));
2056 s = qemu_mallocz(sizeof(TCPCharDriver));
2058 if (is_listen) {
2059 chr->filename = qemu_malloc(256);
2060 if (is_unix) {
2061 pstrcpy(chr->filename, 256, "unix:");
2062 } else if (is_telnet) {
2063 pstrcpy(chr->filename, 256, "telnet:");
2064 } else {
2065 pstrcpy(chr->filename, 256, "tcp:");
2067 offset = strlen(chr->filename);
2069 if (is_unix) {
2070 if (is_listen) {
2071 fd = unix_listen(host_str, chr->filename + offset, 256 - offset);
2072 } else {
2073 fd = unix_connect(host_str);
2075 } else {
2076 if (is_listen) {
2077 fd = inet_listen(host_str, chr->filename + offset, 256 - offset,
2078 SOCK_STREAM, 0);
2079 } else {
2080 fd = inet_connect(host_str, SOCK_STREAM);
2083 if (fd < 0)
2084 goto fail;
2086 if (!is_waitconnect)
2087 socket_set_nonblock(fd);
2089 s->connected = 0;
2090 s->fd = -1;
2091 s->listen_fd = -1;
2092 s->is_unix = is_unix;
2093 s->do_nodelay = do_nodelay && !is_unix;
2095 chr->opaque = s;
2096 chr->chr_write = tcp_chr_write;
2097 chr->chr_close = tcp_chr_close;
2099 if (is_listen) {
2100 s->listen_fd = fd;
2101 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2102 if (is_telnet)
2103 s->do_telnetopt = 1;
2104 } else {
2105 s->connected = 1;
2106 s->fd = fd;
2107 socket_set_nodelay(fd);
2108 tcp_chr_connect(chr);
2111 if (is_listen && is_waitconnect) {
2112 printf("QEMU waiting for connection on: %s\n",
2113 chr->filename ? chr->filename : host_str);
2114 tcp_chr_accept(chr);
2115 socket_set_nonblock(s->listen_fd);
2118 return chr;
2119 fail:
2120 if (fd >= 0)
2121 closesocket(fd);
2122 qemu_free(s);
2123 qemu_free(chr);
2124 return NULL;
2127 CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2129 const char *p;
2130 CharDriverState *chr;
2132 if (!strcmp(filename, "vc")) {
2133 chr = text_console_init(0);
2134 } else
2135 if (strstart(filename, "vc:", &p)) {
2136 chr = text_console_init(p);
2137 } else
2138 if (!strcmp(filename, "null")) {
2139 chr = qemu_chr_open_null();
2140 } else
2141 if (strstart(filename, "tcp:", &p)) {
2142 chr = qemu_chr_open_tcp(p, 0, 0);
2143 } else
2144 if (strstart(filename, "telnet:", &p)) {
2145 chr = qemu_chr_open_tcp(p, 1, 0);
2146 } else
2147 if (strstart(filename, "udp:", &p)) {
2148 chr = qemu_chr_open_udp(p);
2149 } else
2150 if (strstart(filename, "mon:", &p)) {
2151 chr = qemu_chr_open(label, p, NULL);
2152 if (chr) {
2153 chr = qemu_chr_open_mux(chr);
2154 monitor_init(chr, MONITOR_USE_READLINE);
2155 } else {
2156 printf("Unable to open driver: %s\n", p);
2158 } else if (!strcmp(filename, "msmouse")) {
2159 chr = qemu_chr_open_msmouse();
2160 } else
2161 #ifndef _WIN32
2162 if (strstart(filename, "unix:", &p)) {
2163 chr = qemu_chr_open_tcp(p, 0, 1);
2164 } else if (strstart(filename, "file:", &p)) {
2165 chr = qemu_chr_open_file_out(p);
2166 } else if (strstart(filename, "pipe:", &p)) {
2167 chr = qemu_chr_open_pipe(p);
2168 } else if (!strcmp(filename, "pty")) {
2169 chr = qemu_chr_open_pty();
2170 } else if (!strcmp(filename, "stdio")) {
2171 chr = qemu_chr_open_stdio();
2172 } else
2173 #if defined(__linux__)
2174 if (strstart(filename, "/dev/parport", NULL)) {
2175 chr = qemu_chr_open_pp(filename);
2176 } else
2177 #elif defined(__FreeBSD__) || defined(__DragonFly__)
2178 if (strstart(filename, "/dev/ppi", NULL)) {
2179 chr = qemu_chr_open_pp(filename);
2180 } else
2181 #endif
2182 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2183 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
2184 if (strstart(filename, "/dev/", NULL)) {
2185 chr = qemu_chr_open_tty(filename);
2186 } else
2187 #endif
2188 #else /* !_WIN32 */
2189 if (strstart(filename, "COM", NULL)) {
2190 chr = qemu_chr_open_win(filename);
2191 } else
2192 if (strstart(filename, "pipe:", &p)) {
2193 chr = qemu_chr_open_win_pipe(p);
2194 } else
2195 if (strstart(filename, "con:", NULL)) {
2196 chr = qemu_chr_open_win_con(filename);
2197 } else
2198 if (strstart(filename, "file:", &p)) {
2199 chr = qemu_chr_open_win_file_out(p);
2200 } else
2201 #endif
2202 #ifdef CONFIG_BRLAPI
2203 if (!strcmp(filename, "braille")) {
2204 chr = chr_baum_init();
2205 } else
2206 #endif
2208 chr = NULL;
2211 if (chr) {
2212 if (!chr->filename)
2213 chr->filename = qemu_strdup(filename);
2214 chr->init = init;
2215 chr->label = qemu_strdup(label);
2216 TAILQ_INSERT_TAIL(&chardevs, chr, next);
2218 return chr;
2221 void qemu_chr_close(CharDriverState *chr)
2223 TAILQ_REMOVE(&chardevs, chr, next);
2224 if (chr->chr_close)
2225 chr->chr_close(chr);
2226 qemu_free(chr->filename);
2227 qemu_free(chr->label);
2228 qemu_free(chr);
2231 void qemu_chr_info(Monitor *mon)
2233 CharDriverState *chr;
2235 TAILQ_FOREACH(chr, &chardevs, next) {
2236 monitor_printf(mon, "%s: filename=%s\n", chr->label, chr->filename);