Fix command len detection (esp_3_cmdlen.diff)
[qemu/mini2440.git] / qemu-char.c
blobd2335dd6097469d7ded78f7e15fe5be17d23f61f
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu-common.h"
25 #include "net.h"
26 #include "console.h"
27 #include "sysemu.h"
28 #include "qemu-timer.h"
29 #include "qemu-char.h"
30 #include "block.h"
31 #include "hw/usb.h"
32 #include "hw/baum.h"
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <signal.h>
37 #include <time.h>
38 #include <errno.h>
39 #include <sys/time.h>
40 #include <zlib.h>
42 #ifndef _WIN32
43 #include <sys/times.h>
44 #include <sys/wait.h>
45 #include <termios.h>
46 #include <sys/mman.h>
47 #include <sys/ioctl.h>
48 #include <sys/resource.h>
49 #include <sys/socket.h>
50 #include <netinet/in.h>
51 #include <net/if.h>
52 #ifdef __NetBSD__
53 #include <net/if_tap.h>
54 #endif
55 #ifdef __linux__
56 #include <linux/if_tun.h>
57 #endif
58 #include <arpa/inet.h>
59 #include <dirent.h>
60 #include <netdb.h>
61 #include <sys/select.h>
62 #ifdef _BSD
63 #include <sys/stat.h>
64 #ifdef __FreeBSD__
65 #include <libutil.h>
66 #include <dev/ppbus/ppi.h>
67 #include <dev/ppbus/ppbconf.h>
68 #else
69 #include <util.h>
70 #endif
71 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
72 #include <freebsd/stdlib.h>
73 #else
74 #ifdef __linux__
75 #include <pty.h>
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
79 #endif
80 #ifdef __sun__
81 #include <sys/stat.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
91 #include <net/if.h>
92 #include <syslog.h>
93 #include <stropts.h>
94 #endif
95 #endif
96 #endif
98 #include "qemu_socket.h"
100 /***********************************************************/
101 /* character device */
103 static void qemu_chr_event(CharDriverState *s, int event)
105 if (!s->chr_event)
106 return;
107 s->chr_event(s->handler_opaque, event);
110 static void qemu_chr_reset_bh(void *opaque)
112 CharDriverState *s = opaque;
113 qemu_chr_event(s, CHR_EVENT_RESET);
114 qemu_bh_delete(s->bh);
115 s->bh = NULL;
118 void qemu_chr_reset(CharDriverState *s)
120 if (s->bh == NULL) {
121 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
122 qemu_bh_schedule(s->bh);
126 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
128 return s->chr_write(s, buf, len);
131 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
133 if (!s->chr_ioctl)
134 return -ENOTSUP;
135 return s->chr_ioctl(s, cmd, arg);
138 int qemu_chr_can_read(CharDriverState *s)
140 if (!s->chr_can_read)
141 return 0;
142 return s->chr_can_read(s->handler_opaque);
145 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
147 s->chr_read(s->handler_opaque, buf, len);
150 void qemu_chr_accept_input(CharDriverState *s)
152 if (s->chr_accept_input)
153 s->chr_accept_input(s);
156 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
158 char buf[4096];
159 va_list ap;
160 va_start(ap, fmt);
161 vsnprintf(buf, sizeof(buf), fmt, ap);
162 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
163 va_end(ap);
166 void qemu_chr_send_event(CharDriverState *s, int event)
168 if (s->chr_send_event)
169 s->chr_send_event(s, event);
172 void qemu_chr_add_handlers(CharDriverState *s,
173 IOCanRWHandler *fd_can_read,
174 IOReadHandler *fd_read,
175 IOEventHandler *fd_event,
176 void *opaque)
178 s->chr_can_read = fd_can_read;
179 s->chr_read = fd_read;
180 s->chr_event = fd_event;
181 s->handler_opaque = opaque;
182 if (s->chr_update_read_handler)
183 s->chr_update_read_handler(s);
186 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
188 return len;
191 static CharDriverState *qemu_chr_open_null(void)
193 CharDriverState *chr;
195 chr = qemu_mallocz(sizeof(CharDriverState));
196 if (!chr)
197 return NULL;
198 chr->chr_write = null_chr_write;
199 return chr;
202 /* MUX driver for serial I/O splitting */
203 static int term_timestamps;
204 static int64_t term_timestamps_start;
205 #define MAX_MUX 4
206 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
207 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
208 typedef struct {
209 IOCanRWHandler *chr_can_read[MAX_MUX];
210 IOReadHandler *chr_read[MAX_MUX];
211 IOEventHandler *chr_event[MAX_MUX];
212 void *ext_opaque[MAX_MUX];
213 CharDriverState *drv;
214 unsigned char buffer[MUX_BUFFER_SIZE];
215 int prod;
216 int cons;
217 int mux_cnt;
218 int term_got_escape;
219 int max_size;
220 } MuxDriver;
223 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
225 MuxDriver *d = chr->opaque;
226 int ret;
227 if (!term_timestamps) {
228 ret = d->drv->chr_write(d->drv, buf, len);
229 } else {
230 int i;
232 ret = 0;
233 for(i = 0; i < len; i++) {
234 ret += d->drv->chr_write(d->drv, buf+i, 1);
235 if (buf[i] == '\n') {
236 char buf1[64];
237 int64_t ti;
238 int secs;
240 ti = qemu_get_clock(rt_clock);
241 if (term_timestamps_start == -1)
242 term_timestamps_start = ti;
243 ti -= term_timestamps_start;
244 secs = ti / 1000000000;
245 snprintf(buf1, sizeof(buf1),
246 "[%02d:%02d:%02d.%03d] ",
247 secs / 3600,
248 (secs / 60) % 60,
249 secs % 60,
250 (int)((ti / 1000000) % 1000));
251 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
255 return ret;
258 static const char * const mux_help[] = {
259 "% h print this help\n\r",
260 "% x exit emulator\n\r",
261 "% s save disk data back to file (if -snapshot)\n\r",
262 "% t toggle console timestamps\n\r"
263 "% b send break (magic sysrq)\n\r",
264 "% c switch between console and monitor\n\r",
265 "% % sends %\n\r",
266 NULL
269 int term_escape_char = 0x01; /* ctrl-a is used for escape */
270 static void mux_print_help(CharDriverState *chr)
272 int i, j;
273 char ebuf[15] = "Escape-Char";
274 char cbuf[50] = "\n\r";
276 if (term_escape_char > 0 && term_escape_char < 26) {
277 snprintf(cbuf, sizeof(cbuf), "\n\r");
278 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
279 } else {
280 snprintf(cbuf, sizeof(cbuf),
281 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
282 term_escape_char);
284 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
285 for (i = 0; mux_help[i] != NULL; i++) {
286 for (j=0; mux_help[i][j] != '\0'; j++) {
287 if (mux_help[i][j] == '%')
288 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
289 else
290 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
295 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
297 if (d->term_got_escape) {
298 d->term_got_escape = 0;
299 if (ch == term_escape_char)
300 goto send_char;
301 switch(ch) {
302 case '?':
303 case 'h':
304 mux_print_help(chr);
305 break;
306 case 'x':
308 const char *term = "QEMU: Terminated\n\r";
309 chr->chr_write(chr,(uint8_t *)term,strlen(term));
310 exit(0);
311 break;
313 case 's':
315 int i;
316 for (i = 0; i < nb_drives; i++) {
317 bdrv_commit(drives_table[i].bdrv);
320 break;
321 case 'b':
322 qemu_chr_event(chr, CHR_EVENT_BREAK);
323 break;
324 case 'c':
325 /* Switch to the next registered device */
326 chr->focus++;
327 if (chr->focus >= d->mux_cnt)
328 chr->focus = 0;
329 break;
330 case 't':
331 term_timestamps = !term_timestamps;
332 term_timestamps_start = -1;
333 break;
335 } else if (ch == term_escape_char) {
336 d->term_got_escape = 1;
337 } else {
338 send_char:
339 return 1;
341 return 0;
344 static void mux_chr_accept_input(CharDriverState *chr)
346 int m = chr->focus;
347 MuxDriver *d = chr->opaque;
349 while (d->prod != d->cons &&
350 d->chr_can_read[m] &&
351 d->chr_can_read[m](d->ext_opaque[m])) {
352 d->chr_read[m](d->ext_opaque[m],
353 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
357 static int mux_chr_can_read(void *opaque)
359 CharDriverState *chr = opaque;
360 MuxDriver *d = chr->opaque;
362 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
363 return 1;
364 if (d->chr_can_read[chr->focus])
365 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
366 return 0;
369 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
371 CharDriverState *chr = opaque;
372 MuxDriver *d = chr->opaque;
373 int m = chr->focus;
374 int i;
376 mux_chr_accept_input (opaque);
378 for(i = 0; i < size; i++)
379 if (mux_proc_byte(chr, d, buf[i])) {
380 if (d->prod == d->cons &&
381 d->chr_can_read[m] &&
382 d->chr_can_read[m](d->ext_opaque[m]))
383 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
384 else
385 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
389 static void mux_chr_event(void *opaque, int event)
391 CharDriverState *chr = opaque;
392 MuxDriver *d = chr->opaque;
393 int i;
395 /* Send the event to all registered listeners */
396 for (i = 0; i < d->mux_cnt; i++)
397 if (d->chr_event[i])
398 d->chr_event[i](d->ext_opaque[i], event);
401 static void mux_chr_update_read_handler(CharDriverState *chr)
403 MuxDriver *d = chr->opaque;
405 if (d->mux_cnt >= MAX_MUX) {
406 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
407 return;
409 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
410 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
411 d->chr_read[d->mux_cnt] = chr->chr_read;
412 d->chr_event[d->mux_cnt] = chr->chr_event;
413 /* Fix up the real driver with mux routines */
414 if (d->mux_cnt == 0) {
415 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
416 mux_chr_event, chr);
418 chr->focus = d->mux_cnt;
419 d->mux_cnt++;
422 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
424 CharDriverState *chr;
425 MuxDriver *d;
427 chr = qemu_mallocz(sizeof(CharDriverState));
428 if (!chr)
429 return NULL;
430 d = qemu_mallocz(sizeof(MuxDriver));
431 if (!d) {
432 free(chr);
433 return NULL;
436 chr->opaque = d;
437 d->drv = drv;
438 chr->focus = -1;
439 chr->chr_write = mux_chr_write;
440 chr->chr_update_read_handler = mux_chr_update_read_handler;
441 chr->chr_accept_input = mux_chr_accept_input;
442 return chr;
446 #ifdef _WIN32
447 int send_all(int fd, const void *buf, int len1)
449 int ret, len;
451 len = len1;
452 while (len > 0) {
453 ret = send(fd, buf, len, 0);
454 if (ret < 0) {
455 int errno;
456 errno = WSAGetLastError();
457 if (errno != WSAEWOULDBLOCK) {
458 return -1;
460 } else if (ret == 0) {
461 break;
462 } else {
463 buf += ret;
464 len -= ret;
467 return len1 - len;
470 #else
472 static int unix_write(int fd, const uint8_t *buf, int len1)
474 int ret, len;
476 len = len1;
477 while (len > 0) {
478 ret = write(fd, buf, len);
479 if (ret < 0) {
480 if (errno != EINTR && errno != EAGAIN)
481 return -1;
482 } else if (ret == 0) {
483 break;
484 } else {
485 buf += ret;
486 len -= ret;
489 return len1 - len;
492 int send_all(int fd, const void *buf, int len1)
494 return unix_write(fd, buf, len1);
496 #endif /* !_WIN32 */
498 #ifndef _WIN32
500 typedef struct {
501 int fd_in, fd_out;
502 int max_size;
503 } FDCharDriver;
505 #define STDIO_MAX_CLIENTS 1
506 static int stdio_nb_clients = 0;
508 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
510 FDCharDriver *s = chr->opaque;
511 return send_all(s->fd_out, buf, len);
514 static int fd_chr_read_poll(void *opaque)
516 CharDriverState *chr = opaque;
517 FDCharDriver *s = chr->opaque;
519 s->max_size = qemu_chr_can_read(chr);
520 return s->max_size;
523 static void fd_chr_read(void *opaque)
525 CharDriverState *chr = opaque;
526 FDCharDriver *s = chr->opaque;
527 int size, len;
528 uint8_t buf[1024];
530 len = sizeof(buf);
531 if (len > s->max_size)
532 len = s->max_size;
533 if (len == 0)
534 return;
535 size = read(s->fd_in, buf, len);
536 if (size == 0) {
537 /* FD has been closed. Remove it from the active list. */
538 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
539 return;
541 if (size > 0) {
542 qemu_chr_read(chr, buf, size);
546 static void fd_chr_update_read_handler(CharDriverState *chr)
548 FDCharDriver *s = chr->opaque;
550 if (s->fd_in >= 0) {
551 if (nographic && s->fd_in == 0) {
552 } else {
553 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
554 fd_chr_read, NULL, chr);
559 static void fd_chr_close(struct CharDriverState *chr)
561 FDCharDriver *s = chr->opaque;
563 if (s->fd_in >= 0) {
564 if (nographic && s->fd_in == 0) {
565 } else {
566 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
570 qemu_free(s);
573 /* open a character device to a unix fd */
574 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
576 CharDriverState *chr;
577 FDCharDriver *s;
579 chr = qemu_mallocz(sizeof(CharDriverState));
580 if (!chr)
581 return NULL;
582 s = qemu_mallocz(sizeof(FDCharDriver));
583 if (!s) {
584 free(chr);
585 return NULL;
587 s->fd_in = fd_in;
588 s->fd_out = fd_out;
589 chr->opaque = s;
590 chr->chr_write = fd_chr_write;
591 chr->chr_update_read_handler = fd_chr_update_read_handler;
592 chr->chr_close = fd_chr_close;
594 qemu_chr_reset(chr);
596 return chr;
599 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
601 int fd_out;
603 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
604 if (fd_out < 0)
605 return NULL;
606 return qemu_chr_open_fd(-1, fd_out);
609 static CharDriverState *qemu_chr_open_pipe(const char *filename)
611 int fd_in, fd_out;
612 char filename_in[256], filename_out[256];
614 snprintf(filename_in, 256, "%s.in", filename);
615 snprintf(filename_out, 256, "%s.out", filename);
616 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
617 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
618 if (fd_in < 0 || fd_out < 0) {
619 if (fd_in >= 0)
620 close(fd_in);
621 if (fd_out >= 0)
622 close(fd_out);
623 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
624 if (fd_in < 0)
625 return NULL;
627 return qemu_chr_open_fd(fd_in, fd_out);
631 /* for STDIO, we handle the case where several clients use it
632 (nographic mode) */
634 #define TERM_FIFO_MAX_SIZE 1
636 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
637 static int term_fifo_size;
639 static int stdio_read_poll(void *opaque)
641 CharDriverState *chr = opaque;
643 /* try to flush the queue if needed */
644 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
645 qemu_chr_read(chr, term_fifo, 1);
646 term_fifo_size = 0;
648 /* see if we can absorb more chars */
649 if (term_fifo_size == 0)
650 return 1;
651 else
652 return 0;
655 static void stdio_read(void *opaque)
657 int size;
658 uint8_t buf[1];
659 CharDriverState *chr = opaque;
661 size = read(0, buf, 1);
662 if (size == 0) {
663 /* stdin has been closed. Remove it from the active list. */
664 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
665 return;
667 if (size > 0) {
668 if (qemu_chr_can_read(chr) > 0) {
669 qemu_chr_read(chr, buf, 1);
670 } else if (term_fifo_size == 0) {
671 term_fifo[term_fifo_size++] = buf[0];
676 /* init terminal so that we can grab keys */
677 static struct termios oldtty;
678 static int old_fd0_flags;
679 static int term_atexit_done;
681 static void term_exit(void)
683 tcsetattr (0, TCSANOW, &oldtty);
684 fcntl(0, F_SETFL, old_fd0_flags);
687 static void term_init(void)
689 struct termios tty;
691 tcgetattr (0, &tty);
692 oldtty = tty;
693 old_fd0_flags = fcntl(0, F_GETFL);
695 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
696 |INLCR|IGNCR|ICRNL|IXON);
697 tty.c_oflag |= OPOST;
698 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
699 /* if graphical mode, we allow Ctrl-C handling */
700 if (nographic)
701 tty.c_lflag &= ~ISIG;
702 tty.c_cflag &= ~(CSIZE|PARENB);
703 tty.c_cflag |= CS8;
704 tty.c_cc[VMIN] = 1;
705 tty.c_cc[VTIME] = 0;
707 tcsetattr (0, TCSANOW, &tty);
709 if (!term_atexit_done++)
710 atexit(term_exit);
712 fcntl(0, F_SETFL, O_NONBLOCK);
715 static void qemu_chr_close_stdio(struct CharDriverState *chr)
717 term_exit();
718 stdio_nb_clients--;
719 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
720 fd_chr_close(chr);
723 static CharDriverState *qemu_chr_open_stdio(void)
725 CharDriverState *chr;
727 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
728 return NULL;
729 chr = qemu_chr_open_fd(0, 1);
730 chr->chr_close = qemu_chr_close_stdio;
731 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
732 stdio_nb_clients++;
733 term_init();
735 return chr;
738 #ifdef __sun__
739 /* Once Solaris has openpty(), this is going to be removed. */
740 int openpty(int *amaster, int *aslave, char *name,
741 struct termios *termp, struct winsize *winp)
743 const char *slave;
744 int mfd = -1, sfd = -1;
746 *amaster = *aslave = -1;
748 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
749 if (mfd < 0)
750 goto err;
752 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
753 goto err;
755 if ((slave = ptsname(mfd)) == NULL)
756 goto err;
758 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
759 goto err;
761 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
762 (termp != NULL && tcgetattr(sfd, termp) < 0))
763 goto err;
765 if (amaster)
766 *amaster = mfd;
767 if (aslave)
768 *aslave = sfd;
769 if (winp)
770 ioctl(sfd, TIOCSWINSZ, winp);
772 return 0;
774 err:
775 if (sfd != -1)
776 close(sfd);
777 close(mfd);
778 return -1;
781 void cfmakeraw (struct termios *termios_p)
783 termios_p->c_iflag &=
784 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
785 termios_p->c_oflag &= ~OPOST;
786 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
787 termios_p->c_cflag &= ~(CSIZE|PARENB);
788 termios_p->c_cflag |= CS8;
790 termios_p->c_cc[VMIN] = 0;
791 termios_p->c_cc[VTIME] = 0;
793 #endif
795 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
796 || defined(__NetBSD__) || defined(__OpenBSD__)
798 typedef struct {
799 int fd;
800 int connected;
801 int polling;
802 int read_bytes;
803 QEMUTimer *timer;
804 } PtyCharDriver;
806 static void pty_chr_update_read_handler(CharDriverState *chr);
807 static void pty_chr_state(CharDriverState *chr, int connected);
809 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
811 PtyCharDriver *s = chr->opaque;
813 if (!s->connected) {
814 /* guest sends data, check for (re-)connect */
815 pty_chr_update_read_handler(chr);
816 return 0;
818 return send_all(s->fd, buf, len);
821 static int pty_chr_read_poll(void *opaque)
823 CharDriverState *chr = opaque;
824 PtyCharDriver *s = chr->opaque;
826 s->read_bytes = qemu_chr_can_read(chr);
827 return s->read_bytes;
830 static void pty_chr_read(void *opaque)
832 CharDriverState *chr = opaque;
833 PtyCharDriver *s = chr->opaque;
834 int size, len;
835 uint8_t buf[1024];
837 len = sizeof(buf);
838 if (len > s->read_bytes)
839 len = s->read_bytes;
840 if (len == 0)
841 return;
842 size = read(s->fd, buf, len);
843 if ((size == -1 && errno == EIO) ||
844 (size == 0)) {
845 pty_chr_state(chr, 0);
846 return;
848 if (size > 0) {
849 pty_chr_state(chr, 1);
850 qemu_chr_read(chr, buf, size);
854 static void pty_chr_update_read_handler(CharDriverState *chr)
856 PtyCharDriver *s = chr->opaque;
858 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
859 pty_chr_read, NULL, chr);
860 s->polling = 1;
862 * Short timeout here: just need wait long enougth that qemu makes
863 * it through the poll loop once. When reconnected we want a
864 * short timeout so we notice it almost instantly. Otherwise
865 * read() gives us -EIO instantly, making pty_chr_state() reset the
866 * timeout to the normal (much longer) poll interval before the
867 * timer triggers.
869 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
872 static void pty_chr_state(CharDriverState *chr, int connected)
874 PtyCharDriver *s = chr->opaque;
876 if (!connected) {
877 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
878 s->connected = 0;
879 s->polling = 0;
880 /* (re-)connect poll interval for idle guests: once per second.
881 * We check more frequently in case the guests sends data to
882 * the virtual device linked to our pty. */
883 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
884 } else {
885 if (!s->connected)
886 qemu_chr_reset(chr);
887 s->connected = 1;
891 static void pty_chr_timer(void *opaque)
893 struct CharDriverState *chr = opaque;
894 PtyCharDriver *s = chr->opaque;
896 if (s->connected)
897 return;
898 if (s->polling) {
899 /* If we arrive here without polling being cleared due
900 * read returning -EIO, then we are (re-)connected */
901 pty_chr_state(chr, 1);
902 return;
905 /* Next poll ... */
906 pty_chr_update_read_handler(chr);
909 static void pty_chr_close(struct CharDriverState *chr)
911 PtyCharDriver *s = chr->opaque;
913 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
914 close(s->fd);
915 qemu_free(s);
918 static CharDriverState *qemu_chr_open_pty(void)
920 CharDriverState *chr;
921 PtyCharDriver *s;
922 struct termios tty;
923 int slave_fd, len;
924 #if defined(__OpenBSD__)
925 char pty_name[PATH_MAX];
926 #define q_ptsname(x) pty_name
927 #else
928 char *pty_name = NULL;
929 #define q_ptsname(x) ptsname(x)
930 #endif
932 chr = qemu_mallocz(sizeof(CharDriverState));
933 if (!chr)
934 return NULL;
935 s = qemu_mallocz(sizeof(PtyCharDriver));
936 if (!s) {
937 qemu_free(chr);
938 return NULL;
941 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
942 return NULL;
945 /* Set raw attributes on the pty. */
946 tcgetattr(slave_fd, &tty);
947 cfmakeraw(&tty);
948 tcsetattr(slave_fd, TCSAFLUSH, &tty);
949 close(slave_fd);
951 len = strlen(q_ptsname(s->fd)) + 5;
952 chr->filename = qemu_malloc(len);
953 snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
954 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
956 chr->opaque = s;
957 chr->chr_write = pty_chr_write;
958 chr->chr_update_read_handler = pty_chr_update_read_handler;
959 chr->chr_close = pty_chr_close;
961 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
963 return chr;
966 static void tty_serial_init(int fd, int speed,
967 int parity, int data_bits, int stop_bits)
969 struct termios tty;
970 speed_t spd;
972 #if 0
973 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
974 speed, parity, data_bits, stop_bits);
975 #endif
976 tcgetattr (fd, &tty);
978 #define MARGIN 1.1
979 if (speed <= 50 * MARGIN)
980 spd = B50;
981 else if (speed <= 75 * MARGIN)
982 spd = B75;
983 else if (speed <= 300 * MARGIN)
984 spd = B300;
985 else if (speed <= 600 * MARGIN)
986 spd = B600;
987 else if (speed <= 1200 * MARGIN)
988 spd = B1200;
989 else if (speed <= 2400 * MARGIN)
990 spd = B2400;
991 else if (speed <= 4800 * MARGIN)
992 spd = B4800;
993 else if (speed <= 9600 * MARGIN)
994 spd = B9600;
995 else if (speed <= 19200 * MARGIN)
996 spd = B19200;
997 else if (speed <= 38400 * MARGIN)
998 spd = B38400;
999 else if (speed <= 57600 * MARGIN)
1000 spd = B57600;
1001 else if (speed <= 115200 * MARGIN)
1002 spd = B115200;
1003 else
1004 spd = B115200;
1006 cfsetispeed(&tty, spd);
1007 cfsetospeed(&tty, spd);
1009 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1010 |INLCR|IGNCR|ICRNL|IXON);
1011 tty.c_oflag |= OPOST;
1012 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1013 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1014 switch(data_bits) {
1015 default:
1016 case 8:
1017 tty.c_cflag |= CS8;
1018 break;
1019 case 7:
1020 tty.c_cflag |= CS7;
1021 break;
1022 case 6:
1023 tty.c_cflag |= CS6;
1024 break;
1025 case 5:
1026 tty.c_cflag |= CS5;
1027 break;
1029 switch(parity) {
1030 default:
1031 case 'N':
1032 break;
1033 case 'E':
1034 tty.c_cflag |= PARENB;
1035 break;
1036 case 'O':
1037 tty.c_cflag |= PARENB | PARODD;
1038 break;
1040 if (stop_bits == 2)
1041 tty.c_cflag |= CSTOPB;
1043 tcsetattr (fd, TCSANOW, &tty);
1046 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1048 FDCharDriver *s = chr->opaque;
1050 switch(cmd) {
1051 case CHR_IOCTL_SERIAL_SET_PARAMS:
1053 QEMUSerialSetParams *ssp = arg;
1054 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1055 ssp->data_bits, ssp->stop_bits);
1057 break;
1058 case CHR_IOCTL_SERIAL_SET_BREAK:
1060 int enable = *(int *)arg;
1061 if (enable)
1062 tcsendbreak(s->fd_in, 1);
1064 break;
1065 case CHR_IOCTL_SERIAL_GET_TIOCM:
1067 int sarg = 0;
1068 int *targ = (int *)arg;
1069 ioctl(s->fd_in, TIOCMGET, &sarg);
1070 *targ = 0;
1071 if (sarg | TIOCM_CTS)
1072 *targ |= CHR_TIOCM_CTS;
1073 if (sarg | TIOCM_CAR)
1074 *targ |= CHR_TIOCM_CAR;
1075 if (sarg | TIOCM_DSR)
1076 *targ |= CHR_TIOCM_DSR;
1077 if (sarg | TIOCM_RI)
1078 *targ |= CHR_TIOCM_RI;
1079 if (sarg | TIOCM_DTR)
1080 *targ |= CHR_TIOCM_DTR;
1081 if (sarg | TIOCM_RTS)
1082 *targ |= CHR_TIOCM_RTS;
1084 break;
1085 case CHR_IOCTL_SERIAL_SET_TIOCM:
1087 int sarg = *(int *)arg;
1088 int targ = 0;
1089 if (sarg | CHR_TIOCM_DTR)
1090 targ |= TIOCM_DTR;
1091 if (sarg | CHR_TIOCM_RTS)
1092 targ |= TIOCM_RTS;
1093 ioctl(s->fd_in, TIOCMSET, &targ);
1095 break;
1096 default:
1097 return -ENOTSUP;
1099 return 0;
1102 static CharDriverState *qemu_chr_open_tty(const char *filename)
1104 CharDriverState *chr;
1105 int fd;
1107 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
1108 tty_serial_init(fd, 115200, 'N', 8, 1);
1109 chr = qemu_chr_open_fd(fd, fd);
1110 if (!chr) {
1111 close(fd);
1112 return NULL;
1114 chr->chr_ioctl = tty_serial_ioctl;
1115 qemu_chr_reset(chr);
1116 return chr;
1118 #else /* ! __linux__ && ! __sun__ */
1119 static CharDriverState *qemu_chr_open_pty(void)
1121 return NULL;
1123 #endif /* __linux__ || __sun__ */
1125 #if defined(__linux__)
1126 typedef struct {
1127 int fd;
1128 int mode;
1129 } ParallelCharDriver;
1131 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1133 if (s->mode != mode) {
1134 int m = mode;
1135 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1136 return 0;
1137 s->mode = mode;
1139 return 1;
1142 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1144 ParallelCharDriver *drv = chr->opaque;
1145 int fd = drv->fd;
1146 uint8_t b;
1148 switch(cmd) {
1149 case CHR_IOCTL_PP_READ_DATA:
1150 if (ioctl(fd, PPRDATA, &b) < 0)
1151 return -ENOTSUP;
1152 *(uint8_t *)arg = b;
1153 break;
1154 case CHR_IOCTL_PP_WRITE_DATA:
1155 b = *(uint8_t *)arg;
1156 if (ioctl(fd, PPWDATA, &b) < 0)
1157 return -ENOTSUP;
1158 break;
1159 case CHR_IOCTL_PP_READ_CONTROL:
1160 if (ioctl(fd, PPRCONTROL, &b) < 0)
1161 return -ENOTSUP;
1162 /* Linux gives only the lowest bits, and no way to know data
1163 direction! For better compatibility set the fixed upper
1164 bits. */
1165 *(uint8_t *)arg = b | 0xc0;
1166 break;
1167 case CHR_IOCTL_PP_WRITE_CONTROL:
1168 b = *(uint8_t *)arg;
1169 if (ioctl(fd, PPWCONTROL, &b) < 0)
1170 return -ENOTSUP;
1171 break;
1172 case CHR_IOCTL_PP_READ_STATUS:
1173 if (ioctl(fd, PPRSTATUS, &b) < 0)
1174 return -ENOTSUP;
1175 *(uint8_t *)arg = b;
1176 break;
1177 case CHR_IOCTL_PP_DATA_DIR:
1178 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1179 return -ENOTSUP;
1180 break;
1181 case CHR_IOCTL_PP_EPP_READ_ADDR:
1182 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1183 struct ParallelIOArg *parg = arg;
1184 int n = read(fd, parg->buffer, parg->count);
1185 if (n != parg->count) {
1186 return -EIO;
1189 break;
1190 case CHR_IOCTL_PP_EPP_READ:
1191 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1192 struct ParallelIOArg *parg = arg;
1193 int n = read(fd, parg->buffer, parg->count);
1194 if (n != parg->count) {
1195 return -EIO;
1198 break;
1199 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1200 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1201 struct ParallelIOArg *parg = arg;
1202 int n = write(fd, parg->buffer, parg->count);
1203 if (n != parg->count) {
1204 return -EIO;
1207 break;
1208 case CHR_IOCTL_PP_EPP_WRITE:
1209 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1210 struct ParallelIOArg *parg = arg;
1211 int n = write(fd, parg->buffer, parg->count);
1212 if (n != parg->count) {
1213 return -EIO;
1216 break;
1217 default:
1218 return -ENOTSUP;
1220 return 0;
1223 static void pp_close(CharDriverState *chr)
1225 ParallelCharDriver *drv = chr->opaque;
1226 int fd = drv->fd;
1228 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1229 ioctl(fd, PPRELEASE);
1230 close(fd);
1231 qemu_free(drv);
1234 static CharDriverState *qemu_chr_open_pp(const char *filename)
1236 CharDriverState *chr;
1237 ParallelCharDriver *drv;
1238 int fd;
1240 TFR(fd = open(filename, O_RDWR));
1241 if (fd < 0)
1242 return NULL;
1244 if (ioctl(fd, PPCLAIM) < 0) {
1245 close(fd);
1246 return NULL;
1249 drv = qemu_mallocz(sizeof(ParallelCharDriver));
1250 if (!drv) {
1251 close(fd);
1252 return NULL;
1254 drv->fd = fd;
1255 drv->mode = IEEE1284_MODE_COMPAT;
1257 chr = qemu_mallocz(sizeof(CharDriverState));
1258 if (!chr) {
1259 qemu_free(drv);
1260 close(fd);
1261 return NULL;
1263 chr->chr_write = null_chr_write;
1264 chr->chr_ioctl = pp_ioctl;
1265 chr->chr_close = pp_close;
1266 chr->opaque = drv;
1268 qemu_chr_reset(chr);
1270 return chr;
1272 #endif /* __linux__ */
1274 #if defined(__FreeBSD__)
1275 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1277 int fd = (int)chr->opaque;
1278 uint8_t b;
1280 switch(cmd) {
1281 case CHR_IOCTL_PP_READ_DATA:
1282 if (ioctl(fd, PPIGDATA, &b) < 0)
1283 return -ENOTSUP;
1284 *(uint8_t *)arg = b;
1285 break;
1286 case CHR_IOCTL_PP_WRITE_DATA:
1287 b = *(uint8_t *)arg;
1288 if (ioctl(fd, PPISDATA, &b) < 0)
1289 return -ENOTSUP;
1290 break;
1291 case CHR_IOCTL_PP_READ_CONTROL:
1292 if (ioctl(fd, PPIGCTRL, &b) < 0)
1293 return -ENOTSUP;
1294 *(uint8_t *)arg = b;
1295 break;
1296 case CHR_IOCTL_PP_WRITE_CONTROL:
1297 b = *(uint8_t *)arg;
1298 if (ioctl(fd, PPISCTRL, &b) < 0)
1299 return -ENOTSUP;
1300 break;
1301 case CHR_IOCTL_PP_READ_STATUS:
1302 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1303 return -ENOTSUP;
1304 *(uint8_t *)arg = b;
1305 break;
1306 default:
1307 return -ENOTSUP;
1309 return 0;
1312 static CharDriverState *qemu_chr_open_pp(const char *filename)
1314 CharDriverState *chr;
1315 int fd;
1317 fd = open(filename, O_RDWR);
1318 if (fd < 0)
1319 return NULL;
1321 chr = qemu_mallocz(sizeof(CharDriverState));
1322 if (!chr) {
1323 close(fd);
1324 return NULL;
1326 chr->opaque = (void *)fd;
1327 chr->chr_write = null_chr_write;
1328 chr->chr_ioctl = pp_ioctl;
1329 return chr;
1331 #endif
1333 #else /* _WIN32 */
1335 typedef struct {
1336 int max_size;
1337 HANDLE hcom, hrecv, hsend;
1338 OVERLAPPED orecv, osend;
1339 BOOL fpipe;
1340 DWORD len;
1341 } WinCharState;
1343 #define NSENDBUF 2048
1344 #define NRECVBUF 2048
1345 #define MAXCONNECT 1
1346 #define NTIMEOUT 5000
1348 static int win_chr_poll(void *opaque);
1349 static int win_chr_pipe_poll(void *opaque);
1351 static void win_chr_close(CharDriverState *chr)
1353 WinCharState *s = chr->opaque;
1355 if (s->hsend) {
1356 CloseHandle(s->hsend);
1357 s->hsend = NULL;
1359 if (s->hrecv) {
1360 CloseHandle(s->hrecv);
1361 s->hrecv = NULL;
1363 if (s->hcom) {
1364 CloseHandle(s->hcom);
1365 s->hcom = NULL;
1367 if (s->fpipe)
1368 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1369 else
1370 qemu_del_polling_cb(win_chr_poll, chr);
1373 static int win_chr_init(CharDriverState *chr, const char *filename)
1375 WinCharState *s = chr->opaque;
1376 COMMCONFIG comcfg;
1377 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1378 COMSTAT comstat;
1379 DWORD size;
1380 DWORD err;
1382 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1383 if (!s->hsend) {
1384 fprintf(stderr, "Failed CreateEvent\n");
1385 goto fail;
1387 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1388 if (!s->hrecv) {
1389 fprintf(stderr, "Failed CreateEvent\n");
1390 goto fail;
1393 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1394 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1395 if (s->hcom == INVALID_HANDLE_VALUE) {
1396 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1397 s->hcom = NULL;
1398 goto fail;
1401 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1402 fprintf(stderr, "Failed SetupComm\n");
1403 goto fail;
1406 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1407 size = sizeof(COMMCONFIG);
1408 GetDefaultCommConfig(filename, &comcfg, &size);
1409 comcfg.dcb.DCBlength = sizeof(DCB);
1410 CommConfigDialog(filename, NULL, &comcfg);
1412 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1413 fprintf(stderr, "Failed SetCommState\n");
1414 goto fail;
1417 if (!SetCommMask(s->hcom, EV_ERR)) {
1418 fprintf(stderr, "Failed SetCommMask\n");
1419 goto fail;
1422 cto.ReadIntervalTimeout = MAXDWORD;
1423 if (!SetCommTimeouts(s->hcom, &cto)) {
1424 fprintf(stderr, "Failed SetCommTimeouts\n");
1425 goto fail;
1428 if (!ClearCommError(s->hcom, &err, &comstat)) {
1429 fprintf(stderr, "Failed ClearCommError\n");
1430 goto fail;
1432 qemu_add_polling_cb(win_chr_poll, chr);
1433 return 0;
1435 fail:
1436 win_chr_close(chr);
1437 return -1;
1440 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1442 WinCharState *s = chr->opaque;
1443 DWORD len, ret, size, err;
1445 len = len1;
1446 ZeroMemory(&s->osend, sizeof(s->osend));
1447 s->osend.hEvent = s->hsend;
1448 while (len > 0) {
1449 if (s->hsend)
1450 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1451 else
1452 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1453 if (!ret) {
1454 err = GetLastError();
1455 if (err == ERROR_IO_PENDING) {
1456 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1457 if (ret) {
1458 buf += size;
1459 len -= size;
1460 } else {
1461 break;
1463 } else {
1464 break;
1466 } else {
1467 buf += size;
1468 len -= size;
1471 return len1 - len;
1474 static int win_chr_read_poll(CharDriverState *chr)
1476 WinCharState *s = chr->opaque;
1478 s->max_size = qemu_chr_can_read(chr);
1479 return s->max_size;
1482 static void win_chr_readfile(CharDriverState *chr)
1484 WinCharState *s = chr->opaque;
1485 int ret, err;
1486 uint8_t buf[1024];
1487 DWORD size;
1489 ZeroMemory(&s->orecv, sizeof(s->orecv));
1490 s->orecv.hEvent = s->hrecv;
1491 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1492 if (!ret) {
1493 err = GetLastError();
1494 if (err == ERROR_IO_PENDING) {
1495 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1499 if (size > 0) {
1500 qemu_chr_read(chr, buf, size);
1504 static void win_chr_read(CharDriverState *chr)
1506 WinCharState *s = chr->opaque;
1508 if (s->len > s->max_size)
1509 s->len = s->max_size;
1510 if (s->len == 0)
1511 return;
1513 win_chr_readfile(chr);
1516 static int win_chr_poll(void *opaque)
1518 CharDriverState *chr = opaque;
1519 WinCharState *s = chr->opaque;
1520 COMSTAT status;
1521 DWORD comerr;
1523 ClearCommError(s->hcom, &comerr, &status);
1524 if (status.cbInQue > 0) {
1525 s->len = status.cbInQue;
1526 win_chr_read_poll(chr);
1527 win_chr_read(chr);
1528 return 1;
1530 return 0;
1533 static CharDriverState *qemu_chr_open_win(const char *filename)
1535 CharDriverState *chr;
1536 WinCharState *s;
1538 chr = qemu_mallocz(sizeof(CharDriverState));
1539 if (!chr)
1540 return NULL;
1541 s = qemu_mallocz(sizeof(WinCharState));
1542 if (!s) {
1543 free(chr);
1544 return NULL;
1546 chr->opaque = s;
1547 chr->chr_write = win_chr_write;
1548 chr->chr_close = win_chr_close;
1550 if (win_chr_init(chr, filename) < 0) {
1551 free(s);
1552 free(chr);
1553 return NULL;
1555 qemu_chr_reset(chr);
1556 return chr;
1559 static int win_chr_pipe_poll(void *opaque)
1561 CharDriverState *chr = opaque;
1562 WinCharState *s = chr->opaque;
1563 DWORD size;
1565 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1566 if (size > 0) {
1567 s->len = size;
1568 win_chr_read_poll(chr);
1569 win_chr_read(chr);
1570 return 1;
1572 return 0;
1575 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1577 WinCharState *s = chr->opaque;
1578 OVERLAPPED ov;
1579 int ret;
1580 DWORD size;
1581 char openname[256];
1583 s->fpipe = TRUE;
1585 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1586 if (!s->hsend) {
1587 fprintf(stderr, "Failed CreateEvent\n");
1588 goto fail;
1590 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1591 if (!s->hrecv) {
1592 fprintf(stderr, "Failed CreateEvent\n");
1593 goto fail;
1596 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1597 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1598 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1599 PIPE_WAIT,
1600 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1601 if (s->hcom == INVALID_HANDLE_VALUE) {
1602 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1603 s->hcom = NULL;
1604 goto fail;
1607 ZeroMemory(&ov, sizeof(ov));
1608 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1609 ret = ConnectNamedPipe(s->hcom, &ov);
1610 if (ret) {
1611 fprintf(stderr, "Failed ConnectNamedPipe\n");
1612 goto fail;
1615 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1616 if (!ret) {
1617 fprintf(stderr, "Failed GetOverlappedResult\n");
1618 if (ov.hEvent) {
1619 CloseHandle(ov.hEvent);
1620 ov.hEvent = NULL;
1622 goto fail;
1625 if (ov.hEvent) {
1626 CloseHandle(ov.hEvent);
1627 ov.hEvent = NULL;
1629 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1630 return 0;
1632 fail:
1633 win_chr_close(chr);
1634 return -1;
1638 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
1640 CharDriverState *chr;
1641 WinCharState *s;
1643 chr = qemu_mallocz(sizeof(CharDriverState));
1644 if (!chr)
1645 return NULL;
1646 s = qemu_mallocz(sizeof(WinCharState));
1647 if (!s) {
1648 free(chr);
1649 return NULL;
1651 chr->opaque = s;
1652 chr->chr_write = win_chr_write;
1653 chr->chr_close = win_chr_close;
1655 if (win_chr_pipe_init(chr, filename) < 0) {
1656 free(s);
1657 free(chr);
1658 return NULL;
1660 qemu_chr_reset(chr);
1661 return chr;
1664 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1666 CharDriverState *chr;
1667 WinCharState *s;
1669 chr = qemu_mallocz(sizeof(CharDriverState));
1670 if (!chr)
1671 return NULL;
1672 s = qemu_mallocz(sizeof(WinCharState));
1673 if (!s) {
1674 free(chr);
1675 return NULL;
1677 s->hcom = fd_out;
1678 chr->opaque = s;
1679 chr->chr_write = win_chr_write;
1680 qemu_chr_reset(chr);
1681 return chr;
1684 static CharDriverState *qemu_chr_open_win_con(const char *filename)
1686 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1689 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
1691 HANDLE fd_out;
1693 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1694 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1695 if (fd_out == INVALID_HANDLE_VALUE)
1696 return NULL;
1698 return qemu_chr_open_win_file(fd_out);
1700 #endif /* !_WIN32 */
1702 /***********************************************************/
1703 /* UDP Net console */
1705 typedef struct {
1706 int fd;
1707 struct sockaddr_in daddr;
1708 uint8_t buf[1024];
1709 int bufcnt;
1710 int bufptr;
1711 int max_size;
1712 } NetCharDriver;
1714 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1716 NetCharDriver *s = chr->opaque;
1718 return sendto(s->fd, buf, len, 0,
1719 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
1722 static int udp_chr_read_poll(void *opaque)
1724 CharDriverState *chr = opaque;
1725 NetCharDriver *s = chr->opaque;
1727 s->max_size = qemu_chr_can_read(chr);
1729 /* If there were any stray characters in the queue process them
1730 * first
1732 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1733 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1734 s->bufptr++;
1735 s->max_size = qemu_chr_can_read(chr);
1737 return s->max_size;
1740 static void udp_chr_read(void *opaque)
1742 CharDriverState *chr = opaque;
1743 NetCharDriver *s = chr->opaque;
1745 if (s->max_size == 0)
1746 return;
1747 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
1748 s->bufptr = s->bufcnt;
1749 if (s->bufcnt <= 0)
1750 return;
1752 s->bufptr = 0;
1753 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1754 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1755 s->bufptr++;
1756 s->max_size = qemu_chr_can_read(chr);
1760 static void udp_chr_update_read_handler(CharDriverState *chr)
1762 NetCharDriver *s = chr->opaque;
1764 if (s->fd >= 0) {
1765 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
1766 udp_chr_read, NULL, chr);
1770 static CharDriverState *qemu_chr_open_udp(const char *def)
1772 CharDriverState *chr = NULL;
1773 NetCharDriver *s = NULL;
1774 int fd = -1;
1775 struct sockaddr_in saddr;
1777 chr = qemu_mallocz(sizeof(CharDriverState));
1778 if (!chr)
1779 goto return_err;
1780 s = qemu_mallocz(sizeof(NetCharDriver));
1781 if (!s)
1782 goto return_err;
1784 fd = socket(PF_INET, SOCK_DGRAM, 0);
1785 if (fd < 0) {
1786 perror("socket(PF_INET, SOCK_DGRAM)");
1787 goto return_err;
1790 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
1791 printf("Could not parse: %s\n", def);
1792 goto return_err;
1795 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
1797 perror("bind");
1798 goto return_err;
1801 s->fd = fd;
1802 s->bufcnt = 0;
1803 s->bufptr = 0;
1804 chr->opaque = s;
1805 chr->chr_write = udp_chr_write;
1806 chr->chr_update_read_handler = udp_chr_update_read_handler;
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 closesocket(s->fd);
2011 if (s->listen_fd >= 0)
2012 closesocket(s->listen_fd);
2013 qemu_free(s);
2016 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2017 int is_telnet,
2018 int is_unix)
2020 CharDriverState *chr = NULL;
2021 TCPCharDriver *s = NULL;
2022 int fd = -1, offset = 0;
2023 int is_listen = 0;
2024 int is_waitconnect = 1;
2025 int do_nodelay = 0;
2026 const char *ptr;
2028 ptr = host_str;
2029 while((ptr = strchr(ptr,','))) {
2030 ptr++;
2031 if (!strncmp(ptr,"server",6)) {
2032 is_listen = 1;
2033 } else if (!strncmp(ptr,"nowait",6)) {
2034 is_waitconnect = 0;
2035 } else if (!strncmp(ptr,"nodelay",6)) {
2036 do_nodelay = 1;
2037 } else if (!strncmp(ptr,"to=",3)) {
2038 /* nothing, inet_listen() parses this one */;
2039 } else {
2040 printf("Unknown option: %s\n", ptr);
2041 goto fail;
2044 if (!is_listen)
2045 is_waitconnect = 0;
2047 chr = qemu_mallocz(sizeof(CharDriverState));
2048 if (!chr)
2049 goto fail;
2050 s = qemu_mallocz(sizeof(TCPCharDriver));
2051 if (!s)
2052 goto fail;
2054 if (is_listen) {
2055 chr->filename = qemu_malloc(256);
2056 if (is_unix) {
2057 strcpy(chr->filename, "unix:");
2058 } else if (is_telnet) {
2059 strcpy(chr->filename, "telnet:");
2060 } else {
2061 strcpy(chr->filename, "tcp:");
2063 offset = strlen(chr->filename);
2065 if (is_unix) {
2066 if (is_listen) {
2067 fd = unix_listen(host_str, chr->filename + offset, 256 - offset);
2068 } else {
2069 fd = unix_connect(host_str);
2071 } else {
2072 if (is_listen) {
2073 fd = inet_listen(host_str, chr->filename + offset, 256 - offset,
2074 SOCK_STREAM, 0);
2075 } else {
2076 fd = inet_connect(host_str, SOCK_STREAM);
2079 if (fd < 0)
2080 goto fail;
2082 if (!is_waitconnect)
2083 socket_set_nonblock(fd);
2085 s->connected = 0;
2086 s->fd = -1;
2087 s->listen_fd = -1;
2088 s->is_unix = is_unix;
2089 s->do_nodelay = do_nodelay && !is_unix;
2091 chr->opaque = s;
2092 chr->chr_write = tcp_chr_write;
2093 chr->chr_close = tcp_chr_close;
2095 if (is_listen) {
2096 s->listen_fd = fd;
2097 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2098 if (is_telnet)
2099 s->do_telnetopt = 1;
2100 } else {
2101 s->connected = 1;
2102 s->fd = fd;
2103 socket_set_nodelay(fd);
2104 tcp_chr_connect(chr);
2107 if (is_listen && is_waitconnect) {
2108 printf("QEMU waiting for connection on: %s\n",
2109 chr->filename ? chr->filename : host_str);
2110 tcp_chr_accept(chr);
2111 socket_set_nonblock(s->listen_fd);
2114 return chr;
2115 fail:
2116 if (fd >= 0)
2117 closesocket(fd);
2118 qemu_free(s);
2119 qemu_free(chr);
2120 return NULL;
2123 static TAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs
2124 = TAILQ_HEAD_INITIALIZER(chardevs);
2126 CharDriverState *qemu_chr_open(const char *label, const char *filename)
2128 const char *p;
2129 CharDriverState *chr;
2131 if (!strcmp(filename, "vc")) {
2132 chr = text_console_init(&display_state, 0);
2133 } else
2134 if (strstart(filename, "vc:", &p)) {
2135 chr = text_console_init(&display_state, p);
2136 } else
2137 if (!strcmp(filename, "null")) {
2138 chr = qemu_chr_open_null();
2139 } else
2140 if (strstart(filename, "tcp:", &p)) {
2141 chr = qemu_chr_open_tcp(p, 0, 0);
2142 } else
2143 if (strstart(filename, "telnet:", &p)) {
2144 chr = qemu_chr_open_tcp(p, 1, 0);
2145 } else
2146 if (strstart(filename, "udp:", &p)) {
2147 chr = qemu_chr_open_udp(p);
2148 } else
2149 if (strstart(filename, "mon:", &p)) {
2150 chr = qemu_chr_open(label, p);
2151 if (chr) {
2152 chr = qemu_chr_open_mux(chr);
2153 monitor_init(chr, !nographic);
2154 } else {
2155 printf("Unable to open driver: %s\n", p);
2157 } else
2158 #ifndef _WIN32
2159 if (strstart(filename, "unix:", &p)) {
2160 chr = qemu_chr_open_tcp(p, 0, 1);
2161 } else if (strstart(filename, "file:", &p)) {
2162 chr = qemu_chr_open_file_out(p);
2163 } else if (strstart(filename, "pipe:", &p)) {
2164 chr = qemu_chr_open_pipe(p);
2165 } else if (!strcmp(filename, "pty")) {
2166 chr = qemu_chr_open_pty();
2167 } else if (!strcmp(filename, "stdio")) {
2168 chr = qemu_chr_open_stdio();
2169 } else
2170 #if defined(__linux__)
2171 if (strstart(filename, "/dev/parport", NULL)) {
2172 chr = qemu_chr_open_pp(filename);
2173 } else
2174 #elif defined(__FreeBSD__)
2175 if (strstart(filename, "/dev/ppi", NULL)) {
2176 chr = qemu_chr_open_pp(filename);
2177 } else
2178 #endif
2179 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2180 || defined(__NetBSD__) || defined(__OpenBSD__)
2181 if (strstart(filename, "/dev/", NULL)) {
2182 chr = qemu_chr_open_tty(filename);
2183 } else
2184 #endif
2185 #else /* !_WIN32 */
2186 if (strstart(filename, "COM", NULL)) {
2187 chr = qemu_chr_open_win(filename);
2188 } else
2189 if (strstart(filename, "pipe:", &p)) {
2190 chr = qemu_chr_open_win_pipe(p);
2191 } else
2192 if (strstart(filename, "con:", NULL)) {
2193 chr = qemu_chr_open_win_con(filename);
2194 } else
2195 if (strstart(filename, "file:", &p)) {
2196 chr = qemu_chr_open_win_file_out(p);
2197 } else
2198 #endif
2199 #ifdef CONFIG_BRLAPI
2200 if (!strcmp(filename, "braille")) {
2201 chr = chr_baum_init();
2202 } else
2203 #endif
2205 chr = NULL;
2208 if (chr) {
2209 if (!chr->filename)
2210 chr->filename = qemu_strdup(filename);
2211 chr->label = qemu_strdup(label);
2212 TAILQ_INSERT_TAIL(&chardevs, chr, next);
2214 return chr;
2217 void qemu_chr_close(CharDriverState *chr)
2219 TAILQ_REMOVE(&chardevs, chr, next);
2220 if (chr->chr_close)
2221 chr->chr_close(chr);
2222 qemu_free(chr->filename);
2223 qemu_free(chr->label);
2224 qemu_free(chr);
2227 void qemu_chr_info(void)
2229 CharDriverState *chr;
2231 TAILQ_FOREACH(chr, &chardevs, next) {
2232 term_printf("%s: filename=%s\n", chr->label, chr->filename);