]> git.proxmox.com Git - mirror_qemu.git/blob - qemu-char.c
0a74c10df78a4faabf0068660672507d2bab79c1
[mirror_qemu.git] / qemu-char.c
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 #include "qemu-common.h"
25 #include "monitor/monitor.h"
26 #include "ui/console.h"
27 #include "sysemu/sysemu.h"
28 #include "qemu/timer.h"
29 #include "char/char.h"
30 #include "hw/usb.h"
31 #include "hw/baum.h"
32 #include "hw/msmouse.h"
33 #include "qmp-commands.h"
34
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <time.h>
38 #include <errno.h>
39 #include <sys/time.h>
40 #include <zlib.h>
41
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 #include <arpa/inet.h>
53 #include <dirent.h>
54 #include <netdb.h>
55 #include <sys/select.h>
56 #ifdef CONFIG_BSD
57 #include <sys/stat.h>
58 #if defined(__GLIBC__)
59 #include <pty.h>
60 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
61 #include <libutil.h>
62 #else
63 #include <util.h>
64 #endif
65 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
66 #include <dev/ppbus/ppi.h>
67 #include <dev/ppbus/ppbconf.h>
68 #elif defined(__DragonFly__)
69 #include <dev/misc/ppi/ppi.h>
70 #include <bus/ppbus/ppbconf.h>
71 #endif
72 #else
73 #ifdef __linux__
74 #include <pty.h>
75
76 #include <linux/ppdev.h>
77 #include <linux/parport.h>
78 #endif
79 #ifdef __sun__
80 #include <sys/stat.h>
81 #include <sys/ethernet.h>
82 #include <sys/sockio.h>
83 #include <netinet/arp.h>
84 #include <netinet/in.h>
85 #include <netinet/in_systm.h>
86 #include <netinet/ip.h>
87 #include <netinet/ip_icmp.h> // must come after ip.h
88 #include <netinet/udp.h>
89 #include <netinet/tcp.h>
90 #include <net/if.h>
91 #include <syslog.h>
92 #include <stropts.h>
93 #endif
94 #endif
95 #endif
96
97 #include "qemu/sockets.h"
98 #include "ui/qemu-spice.h"
99
100 #define READ_BUF_LEN 4096
101
102 /***********************************************************/
103 /* character device */
104
105 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
106 QTAILQ_HEAD_INITIALIZER(chardevs);
107
108 void qemu_chr_be_event(CharDriverState *s, int event)
109 {
110 /* Keep track if the char device is open */
111 switch (event) {
112 case CHR_EVENT_OPENED:
113 s->opened = 1;
114 break;
115 case CHR_EVENT_CLOSED:
116 s->opened = 0;
117 break;
118 }
119
120 if (!s->chr_event)
121 return;
122 s->chr_event(s->handler_opaque, event);
123 }
124
125 static void qemu_chr_fire_open_event(void *opaque)
126 {
127 CharDriverState *s = opaque;
128 qemu_chr_be_event(s, CHR_EVENT_OPENED);
129 qemu_free_timer(s->open_timer);
130 s->open_timer = NULL;
131 }
132
133 void qemu_chr_generic_open(CharDriverState *s)
134 {
135 if (s->open_timer == NULL) {
136 s->open_timer = qemu_new_timer_ms(rt_clock,
137 qemu_chr_fire_open_event, s);
138 qemu_mod_timer(s->open_timer, qemu_get_clock_ms(rt_clock) - 1);
139 }
140 }
141
142 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
143 {
144 return s->chr_write(s, buf, len);
145 }
146
147 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
148 {
149 if (!s->chr_ioctl)
150 return -ENOTSUP;
151 return s->chr_ioctl(s, cmd, arg);
152 }
153
154 int qemu_chr_be_can_write(CharDriverState *s)
155 {
156 if (!s->chr_can_read)
157 return 0;
158 return s->chr_can_read(s->handler_opaque);
159 }
160
161 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
162 {
163 if (s->chr_read) {
164 s->chr_read(s->handler_opaque, buf, len);
165 }
166 }
167
168 int qemu_chr_fe_get_msgfd(CharDriverState *s)
169 {
170 return s->get_msgfd ? s->get_msgfd(s) : -1;
171 }
172
173 int qemu_chr_add_client(CharDriverState *s, int fd)
174 {
175 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
176 }
177
178 void qemu_chr_accept_input(CharDriverState *s)
179 {
180 if (s->chr_accept_input)
181 s->chr_accept_input(s);
182 qemu_notify_event();
183 }
184
185 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
186 {
187 char buf[READ_BUF_LEN];
188 va_list ap;
189 va_start(ap, fmt);
190 vsnprintf(buf, sizeof(buf), fmt, ap);
191 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
192 va_end(ap);
193 }
194
195 void qemu_chr_add_handlers(CharDriverState *s,
196 IOCanReadHandler *fd_can_read,
197 IOReadHandler *fd_read,
198 IOEventHandler *fd_event,
199 void *opaque)
200 {
201 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
202 /* chr driver being released. */
203 ++s->avail_connections;
204 }
205 s->chr_can_read = fd_can_read;
206 s->chr_read = fd_read;
207 s->chr_event = fd_event;
208 s->handler_opaque = opaque;
209 if (s->chr_update_read_handler)
210 s->chr_update_read_handler(s);
211
212 /* We're connecting to an already opened device, so let's make sure we
213 also get the open event */
214 if (s->opened) {
215 qemu_chr_generic_open(s);
216 }
217 }
218
219 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
220 {
221 return len;
222 }
223
224 static CharDriverState *qemu_chr_open_null(QemuOpts *opts)
225 {
226 CharDriverState *chr;
227
228 chr = g_malloc0(sizeof(CharDriverState));
229 chr->chr_write = null_chr_write;
230 return chr;
231 }
232
233 /* MUX driver for serial I/O splitting */
234 #define MAX_MUX 4
235 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
236 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
237 typedef struct {
238 IOCanReadHandler *chr_can_read[MAX_MUX];
239 IOReadHandler *chr_read[MAX_MUX];
240 IOEventHandler *chr_event[MAX_MUX];
241 void *ext_opaque[MAX_MUX];
242 CharDriverState *drv;
243 int focus;
244 int mux_cnt;
245 int term_got_escape;
246 int max_size;
247 /* Intermediate input buffer allows to catch escape sequences even if the
248 currently active device is not accepting any input - but only until it
249 is full as well. */
250 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
251 int prod[MAX_MUX];
252 int cons[MAX_MUX];
253 int timestamps;
254 int linestart;
255 int64_t timestamps_start;
256 } MuxDriver;
257
258
259 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
260 {
261 MuxDriver *d = chr->opaque;
262 int ret;
263 if (!d->timestamps) {
264 ret = d->drv->chr_write(d->drv, buf, len);
265 } else {
266 int i;
267
268 ret = 0;
269 for (i = 0; i < len; i++) {
270 if (d->linestart) {
271 char buf1[64];
272 int64_t ti;
273 int secs;
274
275 ti = qemu_get_clock_ms(rt_clock);
276 if (d->timestamps_start == -1)
277 d->timestamps_start = ti;
278 ti -= d->timestamps_start;
279 secs = ti / 1000;
280 snprintf(buf1, sizeof(buf1),
281 "[%02d:%02d:%02d.%03d] ",
282 secs / 3600,
283 (secs / 60) % 60,
284 secs % 60,
285 (int)(ti % 1000));
286 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
287 d->linestart = 0;
288 }
289 ret += d->drv->chr_write(d->drv, buf+i, 1);
290 if (buf[i] == '\n') {
291 d->linestart = 1;
292 }
293 }
294 }
295 return ret;
296 }
297
298 static const char * const mux_help[] = {
299 "% h print this help\n\r",
300 "% x exit emulator\n\r",
301 "% s save disk data back to file (if -snapshot)\n\r",
302 "% t toggle console timestamps\n\r"
303 "% b send break (magic sysrq)\n\r",
304 "% c switch between console and monitor\n\r",
305 "% % sends %\n\r",
306 NULL
307 };
308
309 int term_escape_char = 0x01; /* ctrl-a is used for escape */
310 static void mux_print_help(CharDriverState *chr)
311 {
312 int i, j;
313 char ebuf[15] = "Escape-Char";
314 char cbuf[50] = "\n\r";
315
316 if (term_escape_char > 0 && term_escape_char < 26) {
317 snprintf(cbuf, sizeof(cbuf), "\n\r");
318 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
319 } else {
320 snprintf(cbuf, sizeof(cbuf),
321 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
322 term_escape_char);
323 }
324 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
325 for (i = 0; mux_help[i] != NULL; i++) {
326 for (j=0; mux_help[i][j] != '\0'; j++) {
327 if (mux_help[i][j] == '%')
328 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
329 else
330 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
331 }
332 }
333 }
334
335 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
336 {
337 if (d->chr_event[mux_nr])
338 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
339 }
340
341 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
342 {
343 if (d->term_got_escape) {
344 d->term_got_escape = 0;
345 if (ch == term_escape_char)
346 goto send_char;
347 switch(ch) {
348 case '?':
349 case 'h':
350 mux_print_help(chr);
351 break;
352 case 'x':
353 {
354 const char *term = "QEMU: Terminated\n\r";
355 chr->chr_write(chr,(uint8_t *)term,strlen(term));
356 exit(0);
357 break;
358 }
359 case 's':
360 bdrv_commit_all();
361 break;
362 case 'b':
363 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
364 break;
365 case 'c':
366 /* Switch to the next registered device */
367 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
368 d->focus++;
369 if (d->focus >= d->mux_cnt)
370 d->focus = 0;
371 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
372 break;
373 case 't':
374 d->timestamps = !d->timestamps;
375 d->timestamps_start = -1;
376 d->linestart = 0;
377 break;
378 }
379 } else if (ch == term_escape_char) {
380 d->term_got_escape = 1;
381 } else {
382 send_char:
383 return 1;
384 }
385 return 0;
386 }
387
388 static void mux_chr_accept_input(CharDriverState *chr)
389 {
390 MuxDriver *d = chr->opaque;
391 int m = d->focus;
392
393 while (d->prod[m] != d->cons[m] &&
394 d->chr_can_read[m] &&
395 d->chr_can_read[m](d->ext_opaque[m])) {
396 d->chr_read[m](d->ext_opaque[m],
397 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
398 }
399 }
400
401 static int mux_chr_can_read(void *opaque)
402 {
403 CharDriverState *chr = opaque;
404 MuxDriver *d = chr->opaque;
405 int m = d->focus;
406
407 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
408 return 1;
409 if (d->chr_can_read[m])
410 return d->chr_can_read[m](d->ext_opaque[m]);
411 return 0;
412 }
413
414 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
415 {
416 CharDriverState *chr = opaque;
417 MuxDriver *d = chr->opaque;
418 int m = d->focus;
419 int i;
420
421 mux_chr_accept_input (opaque);
422
423 for(i = 0; i < size; i++)
424 if (mux_proc_byte(chr, d, buf[i])) {
425 if (d->prod[m] == d->cons[m] &&
426 d->chr_can_read[m] &&
427 d->chr_can_read[m](d->ext_opaque[m]))
428 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
429 else
430 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
431 }
432 }
433
434 static void mux_chr_event(void *opaque, int event)
435 {
436 CharDriverState *chr = opaque;
437 MuxDriver *d = chr->opaque;
438 int i;
439
440 /* Send the event to all registered listeners */
441 for (i = 0; i < d->mux_cnt; i++)
442 mux_chr_send_event(d, i, event);
443 }
444
445 static void mux_chr_update_read_handler(CharDriverState *chr)
446 {
447 MuxDriver *d = chr->opaque;
448
449 if (d->mux_cnt >= MAX_MUX) {
450 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
451 return;
452 }
453 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
454 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
455 d->chr_read[d->mux_cnt] = chr->chr_read;
456 d->chr_event[d->mux_cnt] = chr->chr_event;
457 /* Fix up the real driver with mux routines */
458 if (d->mux_cnt == 0) {
459 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
460 mux_chr_event, chr);
461 }
462 if (d->focus != -1) {
463 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
464 }
465 d->focus = d->mux_cnt;
466 d->mux_cnt++;
467 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
468 }
469
470 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
471 {
472 CharDriverState *chr;
473 MuxDriver *d;
474
475 chr = g_malloc0(sizeof(CharDriverState));
476 d = g_malloc0(sizeof(MuxDriver));
477
478 chr->opaque = d;
479 d->drv = drv;
480 d->focus = -1;
481 chr->chr_write = mux_chr_write;
482 chr->chr_update_read_handler = mux_chr_update_read_handler;
483 chr->chr_accept_input = mux_chr_accept_input;
484 /* Frontend guest-open / -close notification is not support with muxes */
485 chr->chr_guest_open = NULL;
486 chr->chr_guest_close = NULL;
487
488 /* Muxes are always open on creation */
489 qemu_chr_generic_open(chr);
490
491 return chr;
492 }
493
494
495 #ifdef _WIN32
496 int send_all(int fd, const void *buf, int len1)
497 {
498 int ret, len;
499
500 len = len1;
501 while (len > 0) {
502 ret = send(fd, buf, len, 0);
503 if (ret < 0) {
504 errno = WSAGetLastError();
505 if (errno != WSAEWOULDBLOCK) {
506 return -1;
507 }
508 } else if (ret == 0) {
509 break;
510 } else {
511 buf += ret;
512 len -= ret;
513 }
514 }
515 return len1 - len;
516 }
517
518 #else
519
520 int send_all(int fd, const void *_buf, int len1)
521 {
522 int ret, len;
523 const uint8_t *buf = _buf;
524
525 len = len1;
526 while (len > 0) {
527 ret = write(fd, buf, len);
528 if (ret < 0) {
529 if (errno != EINTR && errno != EAGAIN)
530 return -1;
531 } else if (ret == 0) {
532 break;
533 } else {
534 buf += ret;
535 len -= ret;
536 }
537 }
538 return len1 - len;
539 }
540 #endif /* !_WIN32 */
541
542 #ifndef _WIN32
543
544 typedef struct {
545 int fd_in, fd_out;
546 int max_size;
547 } FDCharDriver;
548
549
550 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
551 {
552 FDCharDriver *s = chr->opaque;
553 return send_all(s->fd_out, buf, len);
554 }
555
556 static int fd_chr_read_poll(void *opaque)
557 {
558 CharDriverState *chr = opaque;
559 FDCharDriver *s = chr->opaque;
560
561 s->max_size = qemu_chr_be_can_write(chr);
562 return s->max_size;
563 }
564
565 static void fd_chr_read(void *opaque)
566 {
567 CharDriverState *chr = opaque;
568 FDCharDriver *s = chr->opaque;
569 int size, len;
570 uint8_t buf[READ_BUF_LEN];
571
572 len = sizeof(buf);
573 if (len > s->max_size)
574 len = s->max_size;
575 if (len == 0)
576 return;
577 size = read(s->fd_in, buf, len);
578 if (size == 0) {
579 /* FD has been closed. Remove it from the active list. */
580 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
581 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
582 return;
583 }
584 if (size > 0) {
585 qemu_chr_be_write(chr, buf, size);
586 }
587 }
588
589 static void fd_chr_update_read_handler(CharDriverState *chr)
590 {
591 FDCharDriver *s = chr->opaque;
592
593 if (s->fd_in >= 0) {
594 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
595 fd_chr_read, NULL, chr);
596 }
597 }
598
599 static void fd_chr_close(struct CharDriverState *chr)
600 {
601 FDCharDriver *s = chr->opaque;
602
603 if (s->fd_in >= 0) {
604 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
605 }
606
607 g_free(s);
608 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
609 }
610
611 /* open a character device to a unix fd */
612 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
613 {
614 CharDriverState *chr;
615 FDCharDriver *s;
616
617 chr = g_malloc0(sizeof(CharDriverState));
618 s = g_malloc0(sizeof(FDCharDriver));
619 s->fd_in = fd_in;
620 s->fd_out = fd_out;
621 chr->opaque = s;
622 chr->chr_write = fd_chr_write;
623 chr->chr_update_read_handler = fd_chr_update_read_handler;
624 chr->chr_close = fd_chr_close;
625
626 qemu_chr_generic_open(chr);
627
628 return chr;
629 }
630
631 static CharDriverState *qemu_chr_open_file_out(QemuOpts *opts)
632 {
633 int fd_out;
634
635 TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
636 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
637 if (fd_out < 0) {
638 return NULL;
639 }
640 return qemu_chr_open_fd(-1, fd_out);
641 }
642
643 static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)
644 {
645 int fd_in, fd_out;
646 char filename_in[256], filename_out[256];
647 const char *filename = qemu_opt_get(opts, "path");
648
649 if (filename == NULL) {
650 fprintf(stderr, "chardev: pipe: no filename given\n");
651 return NULL;
652 }
653
654 snprintf(filename_in, 256, "%s.in", filename);
655 snprintf(filename_out, 256, "%s.out", filename);
656 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
657 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
658 if (fd_in < 0 || fd_out < 0) {
659 if (fd_in >= 0)
660 close(fd_in);
661 if (fd_out >= 0)
662 close(fd_out);
663 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
664 if (fd_in < 0) {
665 return NULL;
666 }
667 }
668 return qemu_chr_open_fd(fd_in, fd_out);
669 }
670
671 /* init terminal so that we can grab keys */
672 static struct termios oldtty;
673 static int old_fd0_flags;
674 static bool stdio_allow_signal;
675
676 static void term_exit(void)
677 {
678 tcsetattr (0, TCSANOW, &oldtty);
679 fcntl(0, F_SETFL, old_fd0_flags);
680 }
681
682 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
683 {
684 struct termios tty;
685
686 tty = oldtty;
687 if (!echo) {
688 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
689 |INLCR|IGNCR|ICRNL|IXON);
690 tty.c_oflag |= OPOST;
691 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
692 tty.c_cflag &= ~(CSIZE|PARENB);
693 tty.c_cflag |= CS8;
694 tty.c_cc[VMIN] = 1;
695 tty.c_cc[VTIME] = 0;
696 }
697 /* if graphical mode, we allow Ctrl-C handling */
698 if (!stdio_allow_signal)
699 tty.c_lflag &= ~ISIG;
700
701 tcsetattr (0, TCSANOW, &tty);
702 }
703
704 static void qemu_chr_close_stdio(struct CharDriverState *chr)
705 {
706 term_exit();
707 fd_chr_close(chr);
708 }
709
710 static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)
711 {
712 CharDriverState *chr;
713
714 if (is_daemonized()) {
715 error_report("cannot use stdio with -daemonize");
716 return NULL;
717 }
718 old_fd0_flags = fcntl(0, F_GETFL);
719 tcgetattr (0, &oldtty);
720 fcntl(0, F_SETFL, O_NONBLOCK);
721 atexit(term_exit);
722
723 chr = qemu_chr_open_fd(0, 1);
724 chr->chr_close = qemu_chr_close_stdio;
725 chr->chr_set_echo = qemu_chr_set_echo_stdio;
726 stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
727 display_type != DT_NOGRAPHIC);
728 qemu_chr_fe_set_echo(chr, false);
729
730 return chr;
731 }
732
733 #ifdef __sun__
734 /* Once Solaris has openpty(), this is going to be removed. */
735 static int openpty(int *amaster, int *aslave, char *name,
736 struct termios *termp, struct winsize *winp)
737 {
738 const char *slave;
739 int mfd = -1, sfd = -1;
740
741 *amaster = *aslave = -1;
742
743 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
744 if (mfd < 0)
745 goto err;
746
747 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
748 goto err;
749
750 if ((slave = ptsname(mfd)) == NULL)
751 goto err;
752
753 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
754 goto err;
755
756 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
757 (termp != NULL && tcgetattr(sfd, termp) < 0))
758 goto err;
759
760 if (amaster)
761 *amaster = mfd;
762 if (aslave)
763 *aslave = sfd;
764 if (winp)
765 ioctl(sfd, TIOCSWINSZ, winp);
766
767 return 0;
768
769 err:
770 if (sfd != -1)
771 close(sfd);
772 close(mfd);
773 return -1;
774 }
775
776 static void cfmakeraw (struct termios *termios_p)
777 {
778 termios_p->c_iflag &=
779 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
780 termios_p->c_oflag &= ~OPOST;
781 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
782 termios_p->c_cflag &= ~(CSIZE|PARENB);
783 termios_p->c_cflag |= CS8;
784
785 termios_p->c_cc[VMIN] = 0;
786 termios_p->c_cc[VTIME] = 0;
787 }
788 #endif
789
790 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
791 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
792 || defined(__GLIBC__)
793
794 #define HAVE_CHARDEV_TTY 1
795
796 typedef struct {
797 int fd;
798 int connected;
799 int polling;
800 int read_bytes;
801 QEMUTimer *timer;
802 } PtyCharDriver;
803
804 static void pty_chr_update_read_handler(CharDriverState *chr);
805 static void pty_chr_state(CharDriverState *chr, int connected);
806
807 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
808 {
809 PtyCharDriver *s = chr->opaque;
810
811 if (!s->connected) {
812 /* guest sends data, check for (re-)connect */
813 pty_chr_update_read_handler(chr);
814 return 0;
815 }
816 return send_all(s->fd, buf, len);
817 }
818
819 static int pty_chr_read_poll(void *opaque)
820 {
821 CharDriverState *chr = opaque;
822 PtyCharDriver *s = chr->opaque;
823
824 s->read_bytes = qemu_chr_be_can_write(chr);
825 return s->read_bytes;
826 }
827
828 static void pty_chr_read(void *opaque)
829 {
830 CharDriverState *chr = opaque;
831 PtyCharDriver *s = chr->opaque;
832 int size, len;
833 uint8_t buf[READ_BUF_LEN];
834
835 len = sizeof(buf);
836 if (len > s->read_bytes)
837 len = s->read_bytes;
838 if (len == 0)
839 return;
840 size = read(s->fd, buf, len);
841 if ((size == -1 && errno == EIO) ||
842 (size == 0)) {
843 pty_chr_state(chr, 0);
844 return;
845 }
846 if (size > 0) {
847 pty_chr_state(chr, 1);
848 qemu_chr_be_write(chr, buf, size);
849 }
850 }
851
852 static void pty_chr_update_read_handler(CharDriverState *chr)
853 {
854 PtyCharDriver *s = chr->opaque;
855
856 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
857 pty_chr_read, NULL, chr);
858 s->polling = 1;
859 /*
860 * Short timeout here: just need wait long enougth that qemu makes
861 * it through the poll loop once. When reconnected we want a
862 * short timeout so we notice it almost instantly. Otherwise
863 * read() gives us -EIO instantly, making pty_chr_state() reset the
864 * timeout to the normal (much longer) poll interval before the
865 * timer triggers.
866 */
867 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 10);
868 }
869
870 static void pty_chr_state(CharDriverState *chr, int connected)
871 {
872 PtyCharDriver *s = chr->opaque;
873
874 if (!connected) {
875 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
876 s->connected = 0;
877 s->polling = 0;
878 /* (re-)connect poll interval for idle guests: once per second.
879 * We check more frequently in case the guests sends data to
880 * the virtual device linked to our pty. */
881 qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 1000);
882 } else {
883 if (!s->connected)
884 qemu_chr_generic_open(chr);
885 s->connected = 1;
886 }
887 }
888
889 static void pty_chr_timer(void *opaque)
890 {
891 struct CharDriverState *chr = opaque;
892 PtyCharDriver *s = chr->opaque;
893
894 if (s->connected)
895 return;
896 if (s->polling) {
897 /* If we arrive here without polling being cleared due
898 * read returning -EIO, then we are (re-)connected */
899 pty_chr_state(chr, 1);
900 return;
901 }
902
903 /* Next poll ... */
904 pty_chr_update_read_handler(chr);
905 }
906
907 static void pty_chr_close(struct CharDriverState *chr)
908 {
909 PtyCharDriver *s = chr->opaque;
910
911 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
912 close(s->fd);
913 qemu_del_timer(s->timer);
914 qemu_free_timer(s->timer);
915 g_free(s);
916 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
917 }
918
919 static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
920 {
921 CharDriverState *chr;
922 PtyCharDriver *s;
923 struct termios tty;
924 const char *label;
925 int master_fd, slave_fd, len;
926 #if defined(__OpenBSD__) || defined(__DragonFly__)
927 char pty_name[PATH_MAX];
928 #define q_ptsname(x) pty_name
929 #else
930 char *pty_name = NULL;
931 #define q_ptsname(x) ptsname(x)
932 #endif
933
934 if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
935 return NULL;
936 }
937
938 /* Set raw attributes on the pty. */
939 tcgetattr(slave_fd, &tty);
940 cfmakeraw(&tty);
941 tcsetattr(slave_fd, TCSAFLUSH, &tty);
942 close(slave_fd);
943
944 chr = g_malloc0(sizeof(CharDriverState));
945
946 len = strlen(q_ptsname(master_fd)) + 5;
947 chr->filename = g_malloc(len);
948 snprintf(chr->filename, len, "pty:%s", q_ptsname(master_fd));
949 qemu_opt_set(opts, "path", q_ptsname(master_fd));
950
951 label = qemu_opts_id(opts);
952 fprintf(stderr, "char device redirected to %s%s%s%s\n",
953 q_ptsname(master_fd),
954 label ? " (label " : "",
955 label ? label : "",
956 label ? ")" : "");
957
958 s = g_malloc0(sizeof(PtyCharDriver));
959 chr->opaque = s;
960 chr->chr_write = pty_chr_write;
961 chr->chr_update_read_handler = pty_chr_update_read_handler;
962 chr->chr_close = pty_chr_close;
963
964 s->fd = master_fd;
965 s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr);
966
967 return chr;
968 }
969
970 static void tty_serial_init(int fd, int speed,
971 int parity, int data_bits, int stop_bits)
972 {
973 struct termios tty;
974 speed_t spd;
975
976 #if 0
977 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
978 speed, parity, data_bits, stop_bits);
979 #endif
980 tcgetattr (fd, &tty);
981
982 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
983 speed = speed * 10 / 11;
984 do {
985 check_speed(50);
986 check_speed(75);
987 check_speed(110);
988 check_speed(134);
989 check_speed(150);
990 check_speed(200);
991 check_speed(300);
992 check_speed(600);
993 check_speed(1200);
994 check_speed(1800);
995 check_speed(2400);
996 check_speed(4800);
997 check_speed(9600);
998 check_speed(19200);
999 check_speed(38400);
1000 /* Non-Posix values follow. They may be unsupported on some systems. */
1001 check_speed(57600);
1002 check_speed(115200);
1003 #ifdef B230400
1004 check_speed(230400);
1005 #endif
1006 #ifdef B460800
1007 check_speed(460800);
1008 #endif
1009 #ifdef B500000
1010 check_speed(500000);
1011 #endif
1012 #ifdef B576000
1013 check_speed(576000);
1014 #endif
1015 #ifdef B921600
1016 check_speed(921600);
1017 #endif
1018 #ifdef B1000000
1019 check_speed(1000000);
1020 #endif
1021 #ifdef B1152000
1022 check_speed(1152000);
1023 #endif
1024 #ifdef B1500000
1025 check_speed(1500000);
1026 #endif
1027 #ifdef B2000000
1028 check_speed(2000000);
1029 #endif
1030 #ifdef B2500000
1031 check_speed(2500000);
1032 #endif
1033 #ifdef B3000000
1034 check_speed(3000000);
1035 #endif
1036 #ifdef B3500000
1037 check_speed(3500000);
1038 #endif
1039 #ifdef B4000000
1040 check_speed(4000000);
1041 #endif
1042 spd = B115200;
1043 } while (0);
1044
1045 cfsetispeed(&tty, spd);
1046 cfsetospeed(&tty, spd);
1047
1048 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1049 |INLCR|IGNCR|ICRNL|IXON);
1050 tty.c_oflag |= OPOST;
1051 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1052 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1053 switch(data_bits) {
1054 default:
1055 case 8:
1056 tty.c_cflag |= CS8;
1057 break;
1058 case 7:
1059 tty.c_cflag |= CS7;
1060 break;
1061 case 6:
1062 tty.c_cflag |= CS6;
1063 break;
1064 case 5:
1065 tty.c_cflag |= CS5;
1066 break;
1067 }
1068 switch(parity) {
1069 default:
1070 case 'N':
1071 break;
1072 case 'E':
1073 tty.c_cflag |= PARENB;
1074 break;
1075 case 'O':
1076 tty.c_cflag |= PARENB | PARODD;
1077 break;
1078 }
1079 if (stop_bits == 2)
1080 tty.c_cflag |= CSTOPB;
1081
1082 tcsetattr (fd, TCSANOW, &tty);
1083 }
1084
1085 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1086 {
1087 FDCharDriver *s = chr->opaque;
1088
1089 switch(cmd) {
1090 case CHR_IOCTL_SERIAL_SET_PARAMS:
1091 {
1092 QEMUSerialSetParams *ssp = arg;
1093 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1094 ssp->data_bits, ssp->stop_bits);
1095 }
1096 break;
1097 case CHR_IOCTL_SERIAL_SET_BREAK:
1098 {
1099 int enable = *(int *)arg;
1100 if (enable)
1101 tcsendbreak(s->fd_in, 1);
1102 }
1103 break;
1104 case CHR_IOCTL_SERIAL_GET_TIOCM:
1105 {
1106 int sarg = 0;
1107 int *targ = (int *)arg;
1108 ioctl(s->fd_in, TIOCMGET, &sarg);
1109 *targ = 0;
1110 if (sarg & TIOCM_CTS)
1111 *targ |= CHR_TIOCM_CTS;
1112 if (sarg & TIOCM_CAR)
1113 *targ |= CHR_TIOCM_CAR;
1114 if (sarg & TIOCM_DSR)
1115 *targ |= CHR_TIOCM_DSR;
1116 if (sarg & TIOCM_RI)
1117 *targ |= CHR_TIOCM_RI;
1118 if (sarg & TIOCM_DTR)
1119 *targ |= CHR_TIOCM_DTR;
1120 if (sarg & TIOCM_RTS)
1121 *targ |= CHR_TIOCM_RTS;
1122 }
1123 break;
1124 case CHR_IOCTL_SERIAL_SET_TIOCM:
1125 {
1126 int sarg = *(int *)arg;
1127 int targ = 0;
1128 ioctl(s->fd_in, TIOCMGET, &targ);
1129 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1130 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1131 if (sarg & CHR_TIOCM_CTS)
1132 targ |= TIOCM_CTS;
1133 if (sarg & CHR_TIOCM_CAR)
1134 targ |= TIOCM_CAR;
1135 if (sarg & CHR_TIOCM_DSR)
1136 targ |= TIOCM_DSR;
1137 if (sarg & CHR_TIOCM_RI)
1138 targ |= TIOCM_RI;
1139 if (sarg & CHR_TIOCM_DTR)
1140 targ |= TIOCM_DTR;
1141 if (sarg & CHR_TIOCM_RTS)
1142 targ |= TIOCM_RTS;
1143 ioctl(s->fd_in, TIOCMSET, &targ);
1144 }
1145 break;
1146 default:
1147 return -ENOTSUP;
1148 }
1149 return 0;
1150 }
1151
1152 static void qemu_chr_close_tty(CharDriverState *chr)
1153 {
1154 FDCharDriver *s = chr->opaque;
1155 int fd = -1;
1156
1157 if (s) {
1158 fd = s->fd_in;
1159 }
1160
1161 fd_chr_close(chr);
1162
1163 if (fd >= 0) {
1164 close(fd);
1165 }
1166 }
1167
1168 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1169 {
1170 CharDriverState *chr;
1171
1172 tty_serial_init(fd, 115200, 'N', 8, 1);
1173 chr = qemu_chr_open_fd(fd, fd);
1174 chr->chr_ioctl = tty_serial_ioctl;
1175 chr->chr_close = qemu_chr_close_tty;
1176 return chr;
1177 }
1178
1179 static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
1180 {
1181 const char *filename = qemu_opt_get(opts, "path");
1182 int fd;
1183
1184 TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
1185 if (fd < 0) {
1186 return NULL;
1187 }
1188 return qemu_chr_open_tty_fd(fd);
1189 }
1190 #endif /* __linux__ || __sun__ */
1191
1192 #if defined(__linux__)
1193
1194 #define HAVE_CHARDEV_PARPORT 1
1195
1196 typedef struct {
1197 int fd;
1198 int mode;
1199 } ParallelCharDriver;
1200
1201 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1202 {
1203 if (s->mode != mode) {
1204 int m = mode;
1205 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1206 return 0;
1207 s->mode = mode;
1208 }
1209 return 1;
1210 }
1211
1212 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1213 {
1214 ParallelCharDriver *drv = chr->opaque;
1215 int fd = drv->fd;
1216 uint8_t b;
1217
1218 switch(cmd) {
1219 case CHR_IOCTL_PP_READ_DATA:
1220 if (ioctl(fd, PPRDATA, &b) < 0)
1221 return -ENOTSUP;
1222 *(uint8_t *)arg = b;
1223 break;
1224 case CHR_IOCTL_PP_WRITE_DATA:
1225 b = *(uint8_t *)arg;
1226 if (ioctl(fd, PPWDATA, &b) < 0)
1227 return -ENOTSUP;
1228 break;
1229 case CHR_IOCTL_PP_READ_CONTROL:
1230 if (ioctl(fd, PPRCONTROL, &b) < 0)
1231 return -ENOTSUP;
1232 /* Linux gives only the lowest bits, and no way to know data
1233 direction! For better compatibility set the fixed upper
1234 bits. */
1235 *(uint8_t *)arg = b | 0xc0;
1236 break;
1237 case CHR_IOCTL_PP_WRITE_CONTROL:
1238 b = *(uint8_t *)arg;
1239 if (ioctl(fd, PPWCONTROL, &b) < 0)
1240 return -ENOTSUP;
1241 break;
1242 case CHR_IOCTL_PP_READ_STATUS:
1243 if (ioctl(fd, PPRSTATUS, &b) < 0)
1244 return -ENOTSUP;
1245 *(uint8_t *)arg = b;
1246 break;
1247 case CHR_IOCTL_PP_DATA_DIR:
1248 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1249 return -ENOTSUP;
1250 break;
1251 case CHR_IOCTL_PP_EPP_READ_ADDR:
1252 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1253 struct ParallelIOArg *parg = arg;
1254 int n = read(fd, parg->buffer, parg->count);
1255 if (n != parg->count) {
1256 return -EIO;
1257 }
1258 }
1259 break;
1260 case CHR_IOCTL_PP_EPP_READ:
1261 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1262 struct ParallelIOArg *parg = arg;
1263 int n = read(fd, parg->buffer, parg->count);
1264 if (n != parg->count) {
1265 return -EIO;
1266 }
1267 }
1268 break;
1269 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1270 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1271 struct ParallelIOArg *parg = arg;
1272 int n = write(fd, parg->buffer, parg->count);
1273 if (n != parg->count) {
1274 return -EIO;
1275 }
1276 }
1277 break;
1278 case CHR_IOCTL_PP_EPP_WRITE:
1279 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1280 struct ParallelIOArg *parg = arg;
1281 int n = write(fd, parg->buffer, parg->count);
1282 if (n != parg->count) {
1283 return -EIO;
1284 }
1285 }
1286 break;
1287 default:
1288 return -ENOTSUP;
1289 }
1290 return 0;
1291 }
1292
1293 static void pp_close(CharDriverState *chr)
1294 {
1295 ParallelCharDriver *drv = chr->opaque;
1296 int fd = drv->fd;
1297
1298 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1299 ioctl(fd, PPRELEASE);
1300 close(fd);
1301 g_free(drv);
1302 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1303 }
1304
1305 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1306 {
1307 CharDriverState *chr;
1308 ParallelCharDriver *drv;
1309
1310 if (ioctl(fd, PPCLAIM) < 0) {
1311 close(fd);
1312 return NULL;
1313 }
1314
1315 drv = g_malloc0(sizeof(ParallelCharDriver));
1316 drv->fd = fd;
1317 drv->mode = IEEE1284_MODE_COMPAT;
1318
1319 chr = g_malloc0(sizeof(CharDriverState));
1320 chr->chr_write = null_chr_write;
1321 chr->chr_ioctl = pp_ioctl;
1322 chr->chr_close = pp_close;
1323 chr->opaque = drv;
1324
1325 qemu_chr_generic_open(chr);
1326
1327 return chr;
1328 }
1329 #endif /* __linux__ */
1330
1331 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1332
1333 #define HAVE_CHARDEV_PARPORT 1
1334
1335 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1336 {
1337 int fd = (int)(intptr_t)chr->opaque;
1338 uint8_t b;
1339
1340 switch(cmd) {
1341 case CHR_IOCTL_PP_READ_DATA:
1342 if (ioctl(fd, PPIGDATA, &b) < 0)
1343 return -ENOTSUP;
1344 *(uint8_t *)arg = b;
1345 break;
1346 case CHR_IOCTL_PP_WRITE_DATA:
1347 b = *(uint8_t *)arg;
1348 if (ioctl(fd, PPISDATA, &b) < 0)
1349 return -ENOTSUP;
1350 break;
1351 case CHR_IOCTL_PP_READ_CONTROL:
1352 if (ioctl(fd, PPIGCTRL, &b) < 0)
1353 return -ENOTSUP;
1354 *(uint8_t *)arg = b;
1355 break;
1356 case CHR_IOCTL_PP_WRITE_CONTROL:
1357 b = *(uint8_t *)arg;
1358 if (ioctl(fd, PPISCTRL, &b) < 0)
1359 return -ENOTSUP;
1360 break;
1361 case CHR_IOCTL_PP_READ_STATUS:
1362 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1363 return -ENOTSUP;
1364 *(uint8_t *)arg = b;
1365 break;
1366 default:
1367 return -ENOTSUP;
1368 }
1369 return 0;
1370 }
1371
1372 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1373 {
1374 CharDriverState *chr;
1375
1376 chr = g_malloc0(sizeof(CharDriverState));
1377 chr->opaque = (void *)(intptr_t)fd;
1378 chr->chr_write = null_chr_write;
1379 chr->chr_ioctl = pp_ioctl;
1380 return chr;
1381 }
1382 #endif
1383
1384 #else /* _WIN32 */
1385
1386 typedef struct {
1387 int max_size;
1388 HANDLE hcom, hrecv, hsend;
1389 OVERLAPPED orecv, osend;
1390 BOOL fpipe;
1391 DWORD len;
1392 } WinCharState;
1393
1394 typedef struct {
1395 HANDLE hStdIn;
1396 HANDLE hInputReadyEvent;
1397 HANDLE hInputDoneEvent;
1398 HANDLE hInputThread;
1399 uint8_t win_stdio_buf;
1400 } WinStdioCharState;
1401
1402 #define NSENDBUF 2048
1403 #define NRECVBUF 2048
1404 #define MAXCONNECT 1
1405 #define NTIMEOUT 5000
1406
1407 static int win_chr_poll(void *opaque);
1408 static int win_chr_pipe_poll(void *opaque);
1409
1410 static void win_chr_close(CharDriverState *chr)
1411 {
1412 WinCharState *s = chr->opaque;
1413
1414 if (s->hsend) {
1415 CloseHandle(s->hsend);
1416 s->hsend = NULL;
1417 }
1418 if (s->hrecv) {
1419 CloseHandle(s->hrecv);
1420 s->hrecv = NULL;
1421 }
1422 if (s->hcom) {
1423 CloseHandle(s->hcom);
1424 s->hcom = NULL;
1425 }
1426 if (s->fpipe)
1427 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1428 else
1429 qemu_del_polling_cb(win_chr_poll, chr);
1430
1431 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1432 }
1433
1434 static int win_chr_init(CharDriverState *chr, const char *filename)
1435 {
1436 WinCharState *s = chr->opaque;
1437 COMMCONFIG comcfg;
1438 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1439 COMSTAT comstat;
1440 DWORD size;
1441 DWORD err;
1442
1443 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1444 if (!s->hsend) {
1445 fprintf(stderr, "Failed CreateEvent\n");
1446 goto fail;
1447 }
1448 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1449 if (!s->hrecv) {
1450 fprintf(stderr, "Failed CreateEvent\n");
1451 goto fail;
1452 }
1453
1454 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1455 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1456 if (s->hcom == INVALID_HANDLE_VALUE) {
1457 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1458 s->hcom = NULL;
1459 goto fail;
1460 }
1461
1462 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1463 fprintf(stderr, "Failed SetupComm\n");
1464 goto fail;
1465 }
1466
1467 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1468 size = sizeof(COMMCONFIG);
1469 GetDefaultCommConfig(filename, &comcfg, &size);
1470 comcfg.dcb.DCBlength = sizeof(DCB);
1471 CommConfigDialog(filename, NULL, &comcfg);
1472
1473 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1474 fprintf(stderr, "Failed SetCommState\n");
1475 goto fail;
1476 }
1477
1478 if (!SetCommMask(s->hcom, EV_ERR)) {
1479 fprintf(stderr, "Failed SetCommMask\n");
1480 goto fail;
1481 }
1482
1483 cto.ReadIntervalTimeout = MAXDWORD;
1484 if (!SetCommTimeouts(s->hcom, &cto)) {
1485 fprintf(stderr, "Failed SetCommTimeouts\n");
1486 goto fail;
1487 }
1488
1489 if (!ClearCommError(s->hcom, &err, &comstat)) {
1490 fprintf(stderr, "Failed ClearCommError\n");
1491 goto fail;
1492 }
1493 qemu_add_polling_cb(win_chr_poll, chr);
1494 return 0;
1495
1496 fail:
1497 win_chr_close(chr);
1498 return -1;
1499 }
1500
1501 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1502 {
1503 WinCharState *s = chr->opaque;
1504 DWORD len, ret, size, err;
1505
1506 len = len1;
1507 ZeroMemory(&s->osend, sizeof(s->osend));
1508 s->osend.hEvent = s->hsend;
1509 while (len > 0) {
1510 if (s->hsend)
1511 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1512 else
1513 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1514 if (!ret) {
1515 err = GetLastError();
1516 if (err == ERROR_IO_PENDING) {
1517 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1518 if (ret) {
1519 buf += size;
1520 len -= size;
1521 } else {
1522 break;
1523 }
1524 } else {
1525 break;
1526 }
1527 } else {
1528 buf += size;
1529 len -= size;
1530 }
1531 }
1532 return len1 - len;
1533 }
1534
1535 static int win_chr_read_poll(CharDriverState *chr)
1536 {
1537 WinCharState *s = chr->opaque;
1538
1539 s->max_size = qemu_chr_be_can_write(chr);
1540 return s->max_size;
1541 }
1542
1543 static void win_chr_readfile(CharDriverState *chr)
1544 {
1545 WinCharState *s = chr->opaque;
1546 int ret, err;
1547 uint8_t buf[READ_BUF_LEN];
1548 DWORD size;
1549
1550 ZeroMemory(&s->orecv, sizeof(s->orecv));
1551 s->orecv.hEvent = s->hrecv;
1552 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1553 if (!ret) {
1554 err = GetLastError();
1555 if (err == ERROR_IO_PENDING) {
1556 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1557 }
1558 }
1559
1560 if (size > 0) {
1561 qemu_chr_be_write(chr, buf, size);
1562 }
1563 }
1564
1565 static void win_chr_read(CharDriverState *chr)
1566 {
1567 WinCharState *s = chr->opaque;
1568
1569 if (s->len > s->max_size)
1570 s->len = s->max_size;
1571 if (s->len == 0)
1572 return;
1573
1574 win_chr_readfile(chr);
1575 }
1576
1577 static int win_chr_poll(void *opaque)
1578 {
1579 CharDriverState *chr = opaque;
1580 WinCharState *s = chr->opaque;
1581 COMSTAT status;
1582 DWORD comerr;
1583
1584 ClearCommError(s->hcom, &comerr, &status);
1585 if (status.cbInQue > 0) {
1586 s->len = status.cbInQue;
1587 win_chr_read_poll(chr);
1588 win_chr_read(chr);
1589 return 1;
1590 }
1591 return 0;
1592 }
1593
1594 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1595 {
1596 CharDriverState *chr;
1597 WinCharState *s;
1598
1599 chr = g_malloc0(sizeof(CharDriverState));
1600 s = g_malloc0(sizeof(WinCharState));
1601 chr->opaque = s;
1602 chr->chr_write = win_chr_write;
1603 chr->chr_close = win_chr_close;
1604
1605 if (win_chr_init(chr, filename) < 0) {
1606 g_free(s);
1607 g_free(chr);
1608 return NULL;
1609 }
1610 qemu_chr_generic_open(chr);
1611 return chr;
1612 }
1613
1614 static CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1615 {
1616 return qemu_chr_open_win_path(qemu_opt_get(opts, "path"));
1617 }
1618
1619 static int win_chr_pipe_poll(void *opaque)
1620 {
1621 CharDriverState *chr = opaque;
1622 WinCharState *s = chr->opaque;
1623 DWORD size;
1624
1625 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1626 if (size > 0) {
1627 s->len = size;
1628 win_chr_read_poll(chr);
1629 win_chr_read(chr);
1630 return 1;
1631 }
1632 return 0;
1633 }
1634
1635 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1636 {
1637 WinCharState *s = chr->opaque;
1638 OVERLAPPED ov;
1639 int ret;
1640 DWORD size;
1641 char openname[256];
1642
1643 s->fpipe = TRUE;
1644
1645 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1646 if (!s->hsend) {
1647 fprintf(stderr, "Failed CreateEvent\n");
1648 goto fail;
1649 }
1650 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1651 if (!s->hrecv) {
1652 fprintf(stderr, "Failed CreateEvent\n");
1653 goto fail;
1654 }
1655
1656 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1657 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1658 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1659 PIPE_WAIT,
1660 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1661 if (s->hcom == INVALID_HANDLE_VALUE) {
1662 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1663 s->hcom = NULL;
1664 goto fail;
1665 }
1666
1667 ZeroMemory(&ov, sizeof(ov));
1668 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1669 ret = ConnectNamedPipe(s->hcom, &ov);
1670 if (ret) {
1671 fprintf(stderr, "Failed ConnectNamedPipe\n");
1672 goto fail;
1673 }
1674
1675 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1676 if (!ret) {
1677 fprintf(stderr, "Failed GetOverlappedResult\n");
1678 if (ov.hEvent) {
1679 CloseHandle(ov.hEvent);
1680 ov.hEvent = NULL;
1681 }
1682 goto fail;
1683 }
1684
1685 if (ov.hEvent) {
1686 CloseHandle(ov.hEvent);
1687 ov.hEvent = NULL;
1688 }
1689 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1690 return 0;
1691
1692 fail:
1693 win_chr_close(chr);
1694 return -1;
1695 }
1696
1697
1698 static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
1699 {
1700 const char *filename = qemu_opt_get(opts, "path");
1701 CharDriverState *chr;
1702 WinCharState *s;
1703
1704 chr = g_malloc0(sizeof(CharDriverState));
1705 s = g_malloc0(sizeof(WinCharState));
1706 chr->opaque = s;
1707 chr->chr_write = win_chr_write;
1708 chr->chr_close = win_chr_close;
1709
1710 if (win_chr_pipe_init(chr, filename) < 0) {
1711 g_free(s);
1712 g_free(chr);
1713 return NULL;
1714 }
1715 qemu_chr_generic_open(chr);
1716 return chr;
1717 }
1718
1719 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1720 {
1721 CharDriverState *chr;
1722 WinCharState *s;
1723
1724 chr = g_malloc0(sizeof(CharDriverState));
1725 s = g_malloc0(sizeof(WinCharState));
1726 s->hcom = fd_out;
1727 chr->opaque = s;
1728 chr->chr_write = win_chr_write;
1729 qemu_chr_generic_open(chr);
1730 return chr;
1731 }
1732
1733 static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
1734 {
1735 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1736 }
1737
1738 static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
1739 {
1740 const char *file_out = qemu_opt_get(opts, "path");
1741 HANDLE fd_out;
1742
1743 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1744 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1745 if (fd_out == INVALID_HANDLE_VALUE) {
1746 return NULL;
1747 }
1748
1749 return qemu_chr_open_win_file(fd_out);
1750 }
1751
1752 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1753 {
1754 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1755 DWORD dwSize;
1756 int len1;
1757
1758 len1 = len;
1759
1760 while (len1 > 0) {
1761 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
1762 break;
1763 }
1764 buf += dwSize;
1765 len1 -= dwSize;
1766 }
1767
1768 return len - len1;
1769 }
1770
1771 static void win_stdio_wait_func(void *opaque)
1772 {
1773 CharDriverState *chr = opaque;
1774 WinStdioCharState *stdio = chr->opaque;
1775 INPUT_RECORD buf[4];
1776 int ret;
1777 DWORD dwSize;
1778 int i;
1779
1780 ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
1781 &dwSize);
1782
1783 if (!ret) {
1784 /* Avoid error storm */
1785 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
1786 return;
1787 }
1788
1789 for (i = 0; i < dwSize; i++) {
1790 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
1791
1792 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
1793 int j;
1794 if (kev->uChar.AsciiChar != 0) {
1795 for (j = 0; j < kev->wRepeatCount; j++) {
1796 if (qemu_chr_be_can_write(chr)) {
1797 uint8_t c = kev->uChar.AsciiChar;
1798 qemu_chr_be_write(chr, &c, 1);
1799 }
1800 }
1801 }
1802 }
1803 }
1804 }
1805
1806 static DWORD WINAPI win_stdio_thread(LPVOID param)
1807 {
1808 CharDriverState *chr = param;
1809 WinStdioCharState *stdio = chr->opaque;
1810 int ret;
1811 DWORD dwSize;
1812
1813 while (1) {
1814
1815 /* Wait for one byte */
1816 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
1817
1818 /* Exit in case of error, continue if nothing read */
1819 if (!ret) {
1820 break;
1821 }
1822 if (!dwSize) {
1823 continue;
1824 }
1825
1826 /* Some terminal emulator returns \r\n for Enter, just pass \n */
1827 if (stdio->win_stdio_buf == '\r') {
1828 continue;
1829 }
1830
1831 /* Signal the main thread and wait until the byte was eaten */
1832 if (!SetEvent(stdio->hInputReadyEvent)) {
1833 break;
1834 }
1835 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
1836 != WAIT_OBJECT_0) {
1837 break;
1838 }
1839 }
1840
1841 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
1842 return 0;
1843 }
1844
1845 static void win_stdio_thread_wait_func(void *opaque)
1846 {
1847 CharDriverState *chr = opaque;
1848 WinStdioCharState *stdio = chr->opaque;
1849
1850 if (qemu_chr_be_can_write(chr)) {
1851 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
1852 }
1853
1854 SetEvent(stdio->hInputDoneEvent);
1855 }
1856
1857 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
1858 {
1859 WinStdioCharState *stdio = chr->opaque;
1860 DWORD dwMode = 0;
1861
1862 GetConsoleMode(stdio->hStdIn, &dwMode);
1863
1864 if (echo) {
1865 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
1866 } else {
1867 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
1868 }
1869 }
1870
1871 static void win_stdio_close(CharDriverState *chr)
1872 {
1873 WinStdioCharState *stdio = chr->opaque;
1874
1875 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
1876 CloseHandle(stdio->hInputReadyEvent);
1877 }
1878 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
1879 CloseHandle(stdio->hInputDoneEvent);
1880 }
1881 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
1882 TerminateThread(stdio->hInputThread, 0);
1883 }
1884
1885 g_free(chr->opaque);
1886 g_free(chr);
1887 }
1888
1889 static CharDriverState *qemu_chr_open_win_stdio(QemuOpts *opts)
1890 {
1891 CharDriverState *chr;
1892 WinStdioCharState *stdio;
1893 DWORD dwMode;
1894 int is_console = 0;
1895
1896 chr = g_malloc0(sizeof(CharDriverState));
1897 stdio = g_malloc0(sizeof(WinStdioCharState));
1898
1899 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
1900 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
1901 fprintf(stderr, "cannot open stdio: invalid handle\n");
1902 exit(1);
1903 }
1904
1905 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
1906
1907 chr->opaque = stdio;
1908 chr->chr_write = win_stdio_write;
1909 chr->chr_close = win_stdio_close;
1910
1911 if (is_console) {
1912 if (qemu_add_wait_object(stdio->hStdIn,
1913 win_stdio_wait_func, chr)) {
1914 fprintf(stderr, "qemu_add_wait_object: failed\n");
1915 }
1916 } else {
1917 DWORD dwId;
1918
1919 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
1920 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
1921 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
1922 chr, 0, &dwId);
1923
1924 if (stdio->hInputThread == INVALID_HANDLE_VALUE
1925 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
1926 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
1927 fprintf(stderr, "cannot create stdio thread or event\n");
1928 exit(1);
1929 }
1930 if (qemu_add_wait_object(stdio->hInputReadyEvent,
1931 win_stdio_thread_wait_func, chr)) {
1932 fprintf(stderr, "qemu_add_wait_object: failed\n");
1933 }
1934 }
1935
1936 dwMode |= ENABLE_LINE_INPUT;
1937
1938 if (is_console) {
1939 /* set the terminal in raw mode */
1940 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
1941 dwMode |= ENABLE_PROCESSED_INPUT;
1942 }
1943
1944 SetConsoleMode(stdio->hStdIn, dwMode);
1945
1946 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
1947 qemu_chr_fe_set_echo(chr, false);
1948
1949 return chr;
1950 }
1951 #endif /* !_WIN32 */
1952
1953 /***********************************************************/
1954 /* UDP Net console */
1955
1956 typedef struct {
1957 int fd;
1958 uint8_t buf[READ_BUF_LEN];
1959 int bufcnt;
1960 int bufptr;
1961 int max_size;
1962 } NetCharDriver;
1963
1964 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1965 {
1966 NetCharDriver *s = chr->opaque;
1967
1968 return send(s->fd, (const void *)buf, len, 0);
1969 }
1970
1971 static int udp_chr_read_poll(void *opaque)
1972 {
1973 CharDriverState *chr = opaque;
1974 NetCharDriver *s = chr->opaque;
1975
1976 s->max_size = qemu_chr_be_can_write(chr);
1977
1978 /* If there were any stray characters in the queue process them
1979 * first
1980 */
1981 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1982 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
1983 s->bufptr++;
1984 s->max_size = qemu_chr_be_can_write(chr);
1985 }
1986 return s->max_size;
1987 }
1988
1989 static void udp_chr_read(void *opaque)
1990 {
1991 CharDriverState *chr = opaque;
1992 NetCharDriver *s = chr->opaque;
1993
1994 if (s->max_size == 0)
1995 return;
1996 s->bufcnt = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
1997 s->bufptr = s->bufcnt;
1998 if (s->bufcnt <= 0)
1999 return;
2000
2001 s->bufptr = 0;
2002 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2003 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2004 s->bufptr++;
2005 s->max_size = qemu_chr_be_can_write(chr);
2006 }
2007 }
2008
2009 static void udp_chr_update_read_handler(CharDriverState *chr)
2010 {
2011 NetCharDriver *s = chr->opaque;
2012
2013 if (s->fd >= 0) {
2014 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2015 udp_chr_read, NULL, chr);
2016 }
2017 }
2018
2019 static void udp_chr_close(CharDriverState *chr)
2020 {
2021 NetCharDriver *s = chr->opaque;
2022 if (s->fd >= 0) {
2023 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2024 closesocket(s->fd);
2025 }
2026 g_free(s);
2027 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2028 }
2029
2030 static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2031 {
2032 CharDriverState *chr = NULL;
2033 NetCharDriver *s = NULL;
2034 Error *local_err = NULL;
2035 int fd = -1;
2036
2037 chr = g_malloc0(sizeof(CharDriverState));
2038 s = g_malloc0(sizeof(NetCharDriver));
2039
2040 fd = inet_dgram_opts(opts, &local_err);
2041 if (fd < 0) {
2042 goto return_err;
2043 }
2044
2045 s->fd = fd;
2046 s->bufcnt = 0;
2047 s->bufptr = 0;
2048 chr->opaque = s;
2049 chr->chr_write = udp_chr_write;
2050 chr->chr_update_read_handler = udp_chr_update_read_handler;
2051 chr->chr_close = udp_chr_close;
2052 return chr;
2053
2054 return_err:
2055 if (local_err) {
2056 qerror_report_err(local_err);
2057 error_free(local_err);
2058 }
2059 g_free(chr);
2060 g_free(s);
2061 if (fd >= 0) {
2062 closesocket(fd);
2063 }
2064 return NULL;
2065 }
2066
2067 /***********************************************************/
2068 /* TCP Net console */
2069
2070 typedef struct {
2071 int fd, listen_fd;
2072 int connected;
2073 int max_size;
2074 int do_telnetopt;
2075 int do_nodelay;
2076 int is_unix;
2077 int msgfd;
2078 } TCPCharDriver;
2079
2080 static void tcp_chr_accept(void *opaque);
2081
2082 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2083 {
2084 TCPCharDriver *s = chr->opaque;
2085 if (s->connected) {
2086 return send_all(s->fd, buf, len);
2087 } else {
2088 /* XXX: indicate an error ? */
2089 return len;
2090 }
2091 }
2092
2093 static int tcp_chr_read_poll(void *opaque)
2094 {
2095 CharDriverState *chr = opaque;
2096 TCPCharDriver *s = chr->opaque;
2097 if (!s->connected)
2098 return 0;
2099 s->max_size = qemu_chr_be_can_write(chr);
2100 return s->max_size;
2101 }
2102
2103 #define IAC 255
2104 #define IAC_BREAK 243
2105 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2106 TCPCharDriver *s,
2107 uint8_t *buf, int *size)
2108 {
2109 /* Handle any telnet client's basic IAC options to satisfy char by
2110 * char mode with no echo. All IAC options will be removed from
2111 * the buf and the do_telnetopt variable will be used to track the
2112 * state of the width of the IAC information.
2113 *
2114 * IAC commands come in sets of 3 bytes with the exception of the
2115 * "IAC BREAK" command and the double IAC.
2116 */
2117
2118 int i;
2119 int j = 0;
2120
2121 for (i = 0; i < *size; i++) {
2122 if (s->do_telnetopt > 1) {
2123 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2124 /* Double IAC means send an IAC */
2125 if (j != i)
2126 buf[j] = buf[i];
2127 j++;
2128 s->do_telnetopt = 1;
2129 } else {
2130 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2131 /* Handle IAC break commands by sending a serial break */
2132 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2133 s->do_telnetopt++;
2134 }
2135 s->do_telnetopt++;
2136 }
2137 if (s->do_telnetopt >= 4) {
2138 s->do_telnetopt = 1;
2139 }
2140 } else {
2141 if ((unsigned char)buf[i] == IAC) {
2142 s->do_telnetopt = 2;
2143 } else {
2144 if (j != i)
2145 buf[j] = buf[i];
2146 j++;
2147 }
2148 }
2149 }
2150 *size = j;
2151 }
2152
2153 static int tcp_get_msgfd(CharDriverState *chr)
2154 {
2155 TCPCharDriver *s = chr->opaque;
2156 int fd = s->msgfd;
2157 s->msgfd = -1;
2158 return fd;
2159 }
2160
2161 #ifndef _WIN32
2162 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2163 {
2164 TCPCharDriver *s = chr->opaque;
2165 struct cmsghdr *cmsg;
2166
2167 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2168 int fd;
2169
2170 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2171 cmsg->cmsg_level != SOL_SOCKET ||
2172 cmsg->cmsg_type != SCM_RIGHTS)
2173 continue;
2174
2175 fd = *((int *)CMSG_DATA(cmsg));
2176 if (fd < 0)
2177 continue;
2178
2179 #ifndef MSG_CMSG_CLOEXEC
2180 qemu_set_cloexec(fd);
2181 #endif
2182 if (s->msgfd != -1)
2183 close(s->msgfd);
2184 s->msgfd = fd;
2185 }
2186 }
2187
2188 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2189 {
2190 TCPCharDriver *s = chr->opaque;
2191 struct msghdr msg = { NULL, };
2192 struct iovec iov[1];
2193 union {
2194 struct cmsghdr cmsg;
2195 char control[CMSG_SPACE(sizeof(int))];
2196 } msg_control;
2197 int flags = 0;
2198 ssize_t ret;
2199
2200 iov[0].iov_base = buf;
2201 iov[0].iov_len = len;
2202
2203 msg.msg_iov = iov;
2204 msg.msg_iovlen = 1;
2205 msg.msg_control = &msg_control;
2206 msg.msg_controllen = sizeof(msg_control);
2207
2208 #ifdef MSG_CMSG_CLOEXEC
2209 flags |= MSG_CMSG_CLOEXEC;
2210 #endif
2211 ret = recvmsg(s->fd, &msg, flags);
2212 if (ret > 0 && s->is_unix) {
2213 unix_process_msgfd(chr, &msg);
2214 }
2215
2216 return ret;
2217 }
2218 #else
2219 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2220 {
2221 TCPCharDriver *s = chr->opaque;
2222 return qemu_recv(s->fd, buf, len, 0);
2223 }
2224 #endif
2225
2226 static void tcp_chr_read(void *opaque)
2227 {
2228 CharDriverState *chr = opaque;
2229 TCPCharDriver *s = chr->opaque;
2230 uint8_t buf[READ_BUF_LEN];
2231 int len, size;
2232
2233 if (!s->connected || s->max_size <= 0)
2234 return;
2235 len = sizeof(buf);
2236 if (len > s->max_size)
2237 len = s->max_size;
2238 size = tcp_chr_recv(chr, (void *)buf, len);
2239 if (size == 0) {
2240 /* connection closed */
2241 s->connected = 0;
2242 if (s->listen_fd >= 0) {
2243 qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2244 }
2245 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2246 closesocket(s->fd);
2247 s->fd = -1;
2248 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2249 } else if (size > 0) {
2250 if (s->do_telnetopt)
2251 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2252 if (size > 0)
2253 qemu_chr_be_write(chr, buf, size);
2254 }
2255 }
2256
2257 #ifndef _WIN32
2258 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2259 {
2260 return qemu_chr_open_fd(eventfd, eventfd);
2261 }
2262 #endif
2263
2264 static void tcp_chr_connect(void *opaque)
2265 {
2266 CharDriverState *chr = opaque;
2267 TCPCharDriver *s = chr->opaque;
2268
2269 s->connected = 1;
2270 if (s->fd >= 0) {
2271 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2272 tcp_chr_read, NULL, chr);
2273 }
2274 qemu_chr_generic_open(chr);
2275 }
2276
2277 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2278 static void tcp_chr_telnet_init(int fd)
2279 {
2280 char buf[3];
2281 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2282 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2283 send(fd, (char *)buf, 3, 0);
2284 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2285 send(fd, (char *)buf, 3, 0);
2286 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2287 send(fd, (char *)buf, 3, 0);
2288 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2289 send(fd, (char *)buf, 3, 0);
2290 }
2291
2292 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2293 {
2294 TCPCharDriver *s = chr->opaque;
2295 if (s->fd != -1)
2296 return -1;
2297
2298 socket_set_nonblock(fd);
2299 if (s->do_nodelay)
2300 socket_set_nodelay(fd);
2301 s->fd = fd;
2302 qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2303 tcp_chr_connect(chr);
2304
2305 return 0;
2306 }
2307
2308 static void tcp_chr_accept(void *opaque)
2309 {
2310 CharDriverState *chr = opaque;
2311 TCPCharDriver *s = chr->opaque;
2312 struct sockaddr_in saddr;
2313 #ifndef _WIN32
2314 struct sockaddr_un uaddr;
2315 #endif
2316 struct sockaddr *addr;
2317 socklen_t len;
2318 int fd;
2319
2320 for(;;) {
2321 #ifndef _WIN32
2322 if (s->is_unix) {
2323 len = sizeof(uaddr);
2324 addr = (struct sockaddr *)&uaddr;
2325 } else
2326 #endif
2327 {
2328 len = sizeof(saddr);
2329 addr = (struct sockaddr *)&saddr;
2330 }
2331 fd = qemu_accept(s->listen_fd, addr, &len);
2332 if (fd < 0 && errno != EINTR) {
2333 return;
2334 } else if (fd >= 0) {
2335 if (s->do_telnetopt)
2336 tcp_chr_telnet_init(fd);
2337 break;
2338 }
2339 }
2340 if (tcp_chr_add_client(chr, fd) < 0)
2341 close(fd);
2342 }
2343
2344 static void tcp_chr_close(CharDriverState *chr)
2345 {
2346 TCPCharDriver *s = chr->opaque;
2347 if (s->fd >= 0) {
2348 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2349 closesocket(s->fd);
2350 }
2351 if (s->listen_fd >= 0) {
2352 qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2353 closesocket(s->listen_fd);
2354 }
2355 g_free(s);
2356 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2357 }
2358
2359 static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2360 bool is_listen, bool is_telnet,
2361 bool is_waitconnect,
2362 Error **errp)
2363 {
2364 CharDriverState *chr = NULL;
2365 TCPCharDriver *s = NULL;
2366 char host[NI_MAXHOST], serv[NI_MAXSERV];
2367 const char *left = "", *right = "";
2368 struct sockaddr_storage ss;
2369 socklen_t ss_len = sizeof(ss);
2370
2371 memset(&ss, 0, ss_len);
2372 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2373 error_setg(errp, "getsockname: %s", strerror(errno));
2374 return NULL;
2375 }
2376
2377 chr = g_malloc0(sizeof(CharDriverState));
2378 s = g_malloc0(sizeof(TCPCharDriver));
2379
2380 s->connected = 0;
2381 s->fd = -1;
2382 s->listen_fd = -1;
2383 s->msgfd = -1;
2384
2385 chr->filename = g_malloc(256);
2386 switch (ss.ss_family) {
2387 #ifndef _WIN32
2388 case AF_UNIX:
2389 s->is_unix = 1;
2390 snprintf(chr->filename, 256, "unix:%s%s",
2391 ((struct sockaddr_un *)(&ss))->sun_path,
2392 is_listen ? ",server" : "");
2393 break;
2394 #endif
2395 case AF_INET6:
2396 left = "[";
2397 right = "]";
2398 /* fall through */
2399 case AF_INET:
2400 s->do_nodelay = do_nodelay;
2401 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2402 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2403 snprintf(chr->filename, 256, "%s:%s:%s%s%s%s",
2404 is_telnet ? "telnet" : "tcp",
2405 left, host, right, serv,
2406 is_listen ? ",server" : "");
2407 break;
2408 }
2409
2410 chr->opaque = s;
2411 chr->chr_write = tcp_chr_write;
2412 chr->chr_close = tcp_chr_close;
2413 chr->get_msgfd = tcp_get_msgfd;
2414 chr->chr_add_client = tcp_chr_add_client;
2415
2416 if (is_listen) {
2417 s->listen_fd = fd;
2418 qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2419 if (is_telnet) {
2420 s->do_telnetopt = 1;
2421 }
2422 } else {
2423 s->connected = 1;
2424 s->fd = fd;
2425 socket_set_nodelay(fd);
2426 tcp_chr_connect(chr);
2427 }
2428
2429 if (is_listen && is_waitconnect) {
2430 printf("QEMU waiting for connection on: %s\n",
2431 chr->filename);
2432 tcp_chr_accept(chr);
2433 socket_set_nonblock(s->listen_fd);
2434 }
2435 return chr;
2436 }
2437
2438 static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2439 {
2440 CharDriverState *chr = NULL;
2441 Error *local_err = NULL;
2442 int fd = -1;
2443 int is_listen;
2444 int is_waitconnect;
2445 int do_nodelay;
2446 int is_unix;
2447 int is_telnet;
2448
2449 is_listen = qemu_opt_get_bool(opts, "server", 0);
2450 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2451 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2452 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2453 is_unix = qemu_opt_get(opts, "path") != NULL;
2454 if (!is_listen)
2455 is_waitconnect = 0;
2456
2457 if (is_unix) {
2458 if (is_listen) {
2459 fd = unix_listen_opts(opts, &local_err);
2460 } else {
2461 fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2462 }
2463 } else {
2464 if (is_listen) {
2465 fd = inet_listen_opts(opts, 0, &local_err);
2466 } else {
2467 fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2468 }
2469 }
2470 if (fd < 0) {
2471 goto fail;
2472 }
2473
2474 if (!is_waitconnect)
2475 socket_set_nonblock(fd);
2476
2477 chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2478 is_waitconnect, &local_err);
2479 if (error_is_set(&local_err)) {
2480 goto fail;
2481 }
2482 return chr;
2483
2484
2485 fail:
2486 if (local_err) {
2487 qerror_report_err(local_err);
2488 error_free(local_err);
2489 }
2490 if (fd >= 0) {
2491 closesocket(fd);
2492 }
2493 if (chr) {
2494 g_free(chr->opaque);
2495 g_free(chr);
2496 }
2497 return NULL;
2498 }
2499
2500 /***********************************************************/
2501 /* Memory chardev */
2502 typedef struct {
2503 size_t outbuf_size;
2504 size_t outbuf_capacity;
2505 uint8_t *outbuf;
2506 } MemoryDriver;
2507
2508 static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2509 {
2510 MemoryDriver *d = chr->opaque;
2511
2512 /* TODO: the QString implementation has the same code, we should
2513 * introduce a generic way to do this in cutils.c */
2514 if (d->outbuf_capacity < d->outbuf_size + len) {
2515 /* grow outbuf */
2516 d->outbuf_capacity += len;
2517 d->outbuf_capacity *= 2;
2518 d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
2519 }
2520
2521 memcpy(d->outbuf + d->outbuf_size, buf, len);
2522 d->outbuf_size += len;
2523
2524 return len;
2525 }
2526
2527 void qemu_chr_init_mem(CharDriverState *chr)
2528 {
2529 MemoryDriver *d;
2530
2531 d = g_malloc(sizeof(*d));
2532 d->outbuf_size = 0;
2533 d->outbuf_capacity = 4096;
2534 d->outbuf = g_malloc0(d->outbuf_capacity);
2535
2536 memset(chr, 0, sizeof(*chr));
2537 chr->opaque = d;
2538 chr->chr_write = mem_chr_write;
2539 }
2540
2541 QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2542 {
2543 MemoryDriver *d = chr->opaque;
2544 return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2545 }
2546
2547 /* NOTE: this driver can not be closed with qemu_chr_delete()! */
2548 void qemu_chr_close_mem(CharDriverState *chr)
2549 {
2550 MemoryDriver *d = chr->opaque;
2551
2552 g_free(d->outbuf);
2553 g_free(chr->opaque);
2554 chr->opaque = NULL;
2555 chr->chr_write = NULL;
2556 }
2557
2558 size_t qemu_chr_mem_osize(const CharDriverState *chr)
2559 {
2560 const MemoryDriver *d = chr->opaque;
2561 return d->outbuf_size;
2562 }
2563
2564 /*********************************************************/
2565 /* Ring buffer chardev */
2566
2567 typedef struct {
2568 size_t size;
2569 size_t prod;
2570 size_t cons;
2571 uint8_t *cbuf;
2572 } RingBufCharDriver;
2573
2574 static size_t ringbuf_count(const CharDriverState *chr)
2575 {
2576 const RingBufCharDriver *d = chr->opaque;
2577
2578 return d->prod - d->cons;
2579 }
2580
2581 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2582 {
2583 RingBufCharDriver *d = chr->opaque;
2584 int i;
2585
2586 if (!buf || (len < 0)) {
2587 return -1;
2588 }
2589
2590 for (i = 0; i < len; i++ ) {
2591 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2592 if (d->prod - d->cons > d->size) {
2593 d->cons = d->prod - d->size;
2594 }
2595 }
2596
2597 return 0;
2598 }
2599
2600 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2601 {
2602 RingBufCharDriver *d = chr->opaque;
2603 int i;
2604
2605 for (i = 0; i < len && d->cons != d->prod; i++) {
2606 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2607 }
2608
2609 return i;
2610 }
2611
2612 static void ringbuf_chr_close(struct CharDriverState *chr)
2613 {
2614 RingBufCharDriver *d = chr->opaque;
2615
2616 g_free(d->cbuf);
2617 g_free(d);
2618 chr->opaque = NULL;
2619 }
2620
2621 static CharDriverState *qemu_chr_open_ringbuf(QemuOpts *opts)
2622 {
2623 CharDriverState *chr;
2624 RingBufCharDriver *d;
2625
2626 chr = g_malloc0(sizeof(CharDriverState));
2627 d = g_malloc(sizeof(*d));
2628
2629 d->size = qemu_opt_get_size(opts, "size", 0);
2630 if (d->size == 0) {
2631 d->size = 65536;
2632 }
2633
2634 /* The size must be power of 2 */
2635 if (d->size & (d->size - 1)) {
2636 error_report("size of ringbuf device must be power of two");
2637 goto fail;
2638 }
2639
2640 d->prod = 0;
2641 d->cons = 0;
2642 d->cbuf = g_malloc0(d->size);
2643
2644 chr->opaque = d;
2645 chr->chr_write = ringbuf_chr_write;
2646 chr->chr_close = ringbuf_chr_close;
2647
2648 return chr;
2649
2650 fail:
2651 g_free(d);
2652 g_free(chr);
2653 return NULL;
2654 }
2655
2656 static bool chr_is_ringbuf(const CharDriverState *chr)
2657 {
2658 return chr->chr_write == ringbuf_chr_write;
2659 }
2660
2661 void qmp_ringbuf_write(const char *device, const char *data,
2662 bool has_format, enum DataFormat format,
2663 Error **errp)
2664 {
2665 CharDriverState *chr;
2666 const uint8_t *write_data;
2667 int ret;
2668 size_t write_count;
2669
2670 chr = qemu_chr_find(device);
2671 if (!chr) {
2672 error_setg(errp, "Device '%s' not found", device);
2673 return;
2674 }
2675
2676 if (!chr_is_ringbuf(chr)) {
2677 error_setg(errp,"%s is not a ringbuf device", device);
2678 return;
2679 }
2680
2681 if (has_format && (format == DATA_FORMAT_BASE64)) {
2682 write_data = g_base64_decode(data, &write_count);
2683 } else {
2684 write_data = (uint8_t *)data;
2685 write_count = strlen(data);
2686 }
2687
2688 ret = ringbuf_chr_write(chr, write_data, write_count);
2689
2690 if (write_data != (uint8_t *)data) {
2691 g_free((void *)write_data);
2692 }
2693
2694 if (ret < 0) {
2695 error_setg(errp, "Failed to write to device %s", device);
2696 return;
2697 }
2698 }
2699
2700 char *qmp_ringbuf_read(const char *device, int64_t size,
2701 bool has_format, enum DataFormat format,
2702 Error **errp)
2703 {
2704 CharDriverState *chr;
2705 uint8_t *read_data;
2706 size_t count;
2707 char *data;
2708
2709 chr = qemu_chr_find(device);
2710 if (!chr) {
2711 error_setg(errp, "Device '%s' not found", device);
2712 return NULL;
2713 }
2714
2715 if (!chr_is_ringbuf(chr)) {
2716 error_setg(errp,"%s is not a ringbuf device", device);
2717 return NULL;
2718 }
2719
2720 if (size <= 0) {
2721 error_setg(errp, "size must be greater than zero");
2722 return NULL;
2723 }
2724
2725 count = ringbuf_count(chr);
2726 size = size > count ? count : size;
2727 read_data = g_malloc(size + 1);
2728
2729 ringbuf_chr_read(chr, read_data, size);
2730
2731 if (has_format && (format == DATA_FORMAT_BASE64)) {
2732 data = g_base64_encode(read_data, size);
2733 g_free(read_data);
2734 } else {
2735 /*
2736 * FIXME should read only complete, valid UTF-8 characters up
2737 * to @size bytes. Invalid sequences should be replaced by a
2738 * suitable replacement character. Except when (and only
2739 * when) ring buffer lost characters since last read, initial
2740 * continuation characters should be dropped.
2741 */
2742 read_data[size] = 0;
2743 data = (char *)read_data;
2744 }
2745
2746 return data;
2747 }
2748
2749 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2750 {
2751 char host[65], port[33], width[8], height[8];
2752 int pos;
2753 const char *p;
2754 QemuOpts *opts;
2755 Error *local_err = NULL;
2756
2757 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
2758 if (error_is_set(&local_err)) {
2759 qerror_report_err(local_err);
2760 error_free(local_err);
2761 return NULL;
2762 }
2763
2764 if (strstart(filename, "mon:", &p)) {
2765 filename = p;
2766 qemu_opt_set(opts, "mux", "on");
2767 }
2768
2769 if (strcmp(filename, "null") == 0 ||
2770 strcmp(filename, "pty") == 0 ||
2771 strcmp(filename, "msmouse") == 0 ||
2772 strcmp(filename, "braille") == 0 ||
2773 strcmp(filename, "stdio") == 0) {
2774 qemu_opt_set(opts, "backend", filename);
2775 return opts;
2776 }
2777 if (strstart(filename, "vc", &p)) {
2778 qemu_opt_set(opts, "backend", "vc");
2779 if (*p == ':') {
2780 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2781 /* pixels */
2782 qemu_opt_set(opts, "width", width);
2783 qemu_opt_set(opts, "height", height);
2784 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2785 /* chars */
2786 qemu_opt_set(opts, "cols", width);
2787 qemu_opt_set(opts, "rows", height);
2788 } else {
2789 goto fail;
2790 }
2791 }
2792 return opts;
2793 }
2794 if (strcmp(filename, "con:") == 0) {
2795 qemu_opt_set(opts, "backend", "console");
2796 return opts;
2797 }
2798 if (strstart(filename, "COM", NULL)) {
2799 qemu_opt_set(opts, "backend", "serial");
2800 qemu_opt_set(opts, "path", filename);
2801 return opts;
2802 }
2803 if (strstart(filename, "file:", &p)) {
2804 qemu_opt_set(opts, "backend", "file");
2805 qemu_opt_set(opts, "path", p);
2806 return opts;
2807 }
2808 if (strstart(filename, "pipe:", &p)) {
2809 qemu_opt_set(opts, "backend", "pipe");
2810 qemu_opt_set(opts, "path", p);
2811 return opts;
2812 }
2813 if (strstart(filename, "tcp:", &p) ||
2814 strstart(filename, "telnet:", &p)) {
2815 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2816 host[0] = 0;
2817 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2818 goto fail;
2819 }
2820 qemu_opt_set(opts, "backend", "socket");
2821 qemu_opt_set(opts, "host", host);
2822 qemu_opt_set(opts, "port", port);
2823 if (p[pos] == ',') {
2824 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2825 goto fail;
2826 }
2827 if (strstart(filename, "telnet:", &p))
2828 qemu_opt_set(opts, "telnet", "on");
2829 return opts;
2830 }
2831 if (strstart(filename, "udp:", &p)) {
2832 qemu_opt_set(opts, "backend", "udp");
2833 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2834 host[0] = 0;
2835 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
2836 goto fail;
2837 }
2838 }
2839 qemu_opt_set(opts, "host", host);
2840 qemu_opt_set(opts, "port", port);
2841 if (p[pos] == '@') {
2842 p += pos + 1;
2843 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2844 host[0] = 0;
2845 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2846 goto fail;
2847 }
2848 }
2849 qemu_opt_set(opts, "localaddr", host);
2850 qemu_opt_set(opts, "localport", port);
2851 }
2852 return opts;
2853 }
2854 if (strstart(filename, "unix:", &p)) {
2855 qemu_opt_set(opts, "backend", "socket");
2856 if (qemu_opts_do_parse(opts, p, "path") != 0)
2857 goto fail;
2858 return opts;
2859 }
2860 if (strstart(filename, "/dev/parport", NULL) ||
2861 strstart(filename, "/dev/ppi", NULL)) {
2862 qemu_opt_set(opts, "backend", "parport");
2863 qemu_opt_set(opts, "path", filename);
2864 return opts;
2865 }
2866 if (strstart(filename, "/dev/", NULL)) {
2867 qemu_opt_set(opts, "backend", "tty");
2868 qemu_opt_set(opts, "path", filename);
2869 return opts;
2870 }
2871
2872 fail:
2873 qemu_opts_del(opts);
2874 return NULL;
2875 }
2876
2877 #ifdef HAVE_CHARDEV_PARPORT
2878
2879 static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
2880 {
2881 const char *filename = qemu_opt_get(opts, "path");
2882 int fd;
2883
2884 fd = qemu_open(filename, O_RDWR);
2885 if (fd < 0) {
2886 return NULL;
2887 }
2888 return qemu_chr_open_pp_fd(fd);
2889 }
2890
2891 #endif
2892
2893 static const struct {
2894 const char *name;
2895 CharDriverState *(*open)(QemuOpts *opts);
2896 } backend_table[] = {
2897 { .name = "null", .open = qemu_chr_open_null },
2898 { .name = "socket", .open = qemu_chr_open_socket },
2899 { .name = "udp", .open = qemu_chr_open_udp },
2900 { .name = "msmouse", .open = qemu_chr_open_msmouse },
2901 { .name = "vc", .open = vc_init },
2902 { .name = "memory", .open = qemu_chr_open_ringbuf },
2903 #ifdef _WIN32
2904 { .name = "file", .open = qemu_chr_open_win_file_out },
2905 { .name = "pipe", .open = qemu_chr_open_win_pipe },
2906 { .name = "console", .open = qemu_chr_open_win_con },
2907 { .name = "serial", .open = qemu_chr_open_win },
2908 { .name = "stdio", .open = qemu_chr_open_win_stdio },
2909 #else
2910 { .name = "file", .open = qemu_chr_open_file_out },
2911 { .name = "pipe", .open = qemu_chr_open_pipe },
2912 { .name = "stdio", .open = qemu_chr_open_stdio },
2913 #endif
2914 #ifdef CONFIG_BRLAPI
2915 { .name = "braille", .open = chr_baum_init },
2916 #endif
2917 #ifdef HAVE_CHARDEV_TTY
2918 { .name = "tty", .open = qemu_chr_open_tty },
2919 { .name = "serial", .open = qemu_chr_open_tty },
2920 { .name = "pty", .open = qemu_chr_open_pty },
2921 #endif
2922 #ifdef HAVE_CHARDEV_PARPORT
2923 { .name = "parallel", .open = qemu_chr_open_pp },
2924 { .name = "parport", .open = qemu_chr_open_pp },
2925 #endif
2926 #ifdef CONFIG_SPICE
2927 { .name = "spicevmc", .open = qemu_chr_open_spice },
2928 #if SPICE_SERVER_VERSION >= 0x000c02
2929 { .name = "spiceport", .open = qemu_chr_open_spice_port },
2930 #endif
2931 #endif
2932 };
2933
2934 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
2935 void (*init)(struct CharDriverState *s),
2936 Error **errp)
2937 {
2938 CharDriverState *chr;
2939 int i;
2940
2941 if (qemu_opts_id(opts) == NULL) {
2942 error_setg(errp, "chardev: no id specified");
2943 goto err;
2944 }
2945
2946 if (qemu_opt_get(opts, "backend") == NULL) {
2947 error_setg(errp, "chardev: \"%s\" missing backend",
2948 qemu_opts_id(opts));
2949 goto err;
2950 }
2951 for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
2952 if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
2953 break;
2954 }
2955 if (i == ARRAY_SIZE(backend_table)) {
2956 error_setg(errp, "chardev: backend \"%s\" not found",
2957 qemu_opt_get(opts, "backend"));
2958 goto err;
2959 }
2960
2961 chr = backend_table[i].open(opts);
2962 if (!chr) {
2963 error_setg(errp, "chardev: opening backend \"%s\" failed",
2964 qemu_opt_get(opts, "backend"));
2965 goto err;
2966 }
2967
2968 if (!chr->filename)
2969 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
2970 chr->init = init;
2971 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2972
2973 if (qemu_opt_get_bool(opts, "mux", 0)) {
2974 CharDriverState *base = chr;
2975 int len = strlen(qemu_opts_id(opts)) + 6;
2976 base->label = g_malloc(len);
2977 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
2978 chr = qemu_chr_open_mux(base);
2979 chr->filename = base->filename;
2980 chr->avail_connections = MAX_MUX;
2981 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2982 } else {
2983 chr->avail_connections = 1;
2984 }
2985 chr->label = g_strdup(qemu_opts_id(opts));
2986 chr->opts = opts;
2987 return chr;
2988
2989 err:
2990 qemu_opts_del(opts);
2991 return NULL;
2992 }
2993
2994 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2995 {
2996 const char *p;
2997 CharDriverState *chr;
2998 QemuOpts *opts;
2999 Error *err = NULL;
3000
3001 if (strstart(filename, "chardev:", &p)) {
3002 return qemu_chr_find(p);
3003 }
3004
3005 opts = qemu_chr_parse_compat(label, filename);
3006 if (!opts)
3007 return NULL;
3008
3009 chr = qemu_chr_new_from_opts(opts, init, &err);
3010 if (error_is_set(&err)) {
3011 fprintf(stderr, "%s\n", error_get_pretty(err));
3012 error_free(err);
3013 }
3014 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3015 monitor_init(chr, MONITOR_USE_READLINE);
3016 }
3017 return chr;
3018 }
3019
3020 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3021 {
3022 if (chr->chr_set_echo) {
3023 chr->chr_set_echo(chr, echo);
3024 }
3025 }
3026
3027 void qemu_chr_fe_open(struct CharDriverState *chr)
3028 {
3029 if (chr->chr_guest_open) {
3030 chr->chr_guest_open(chr);
3031 }
3032 }
3033
3034 void qemu_chr_fe_close(struct CharDriverState *chr)
3035 {
3036 if (chr->chr_guest_close) {
3037 chr->chr_guest_close(chr);
3038 }
3039 }
3040
3041 void qemu_chr_delete(CharDriverState *chr)
3042 {
3043 QTAILQ_REMOVE(&chardevs, chr, next);
3044 if (chr->chr_close) {
3045 chr->chr_close(chr);
3046 }
3047 g_free(chr->filename);
3048 g_free(chr->label);
3049 if (chr->opts) {
3050 qemu_opts_del(chr->opts);
3051 }
3052 g_free(chr);
3053 }
3054
3055 ChardevInfoList *qmp_query_chardev(Error **errp)
3056 {
3057 ChardevInfoList *chr_list = NULL;
3058 CharDriverState *chr;
3059
3060 QTAILQ_FOREACH(chr, &chardevs, next) {
3061 ChardevInfoList *info = g_malloc0(sizeof(*info));
3062 info->value = g_malloc0(sizeof(*info->value));
3063 info->value->label = g_strdup(chr->label);
3064 info->value->filename = g_strdup(chr->filename);
3065
3066 info->next = chr_list;
3067 chr_list = info;
3068 }
3069
3070 return chr_list;
3071 }
3072
3073 CharDriverState *qemu_chr_find(const char *name)
3074 {
3075 CharDriverState *chr;
3076
3077 QTAILQ_FOREACH(chr, &chardevs, next) {
3078 if (strcmp(chr->label, name) != 0)
3079 continue;
3080 return chr;
3081 }
3082 return NULL;
3083 }
3084
3085 /* Get a character (serial) device interface. */
3086 CharDriverState *qemu_char_get_next_serial(void)
3087 {
3088 static int next_serial;
3089
3090 /* FIXME: This function needs to go away: use chardev properties! */
3091 return serial_hds[next_serial++];
3092 }
3093
3094 QemuOptsList qemu_chardev_opts = {
3095 .name = "chardev",
3096 .implied_opt_name = "backend",
3097 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3098 .desc = {
3099 {
3100 .name = "backend",
3101 .type = QEMU_OPT_STRING,
3102 },{
3103 .name = "path",
3104 .type = QEMU_OPT_STRING,
3105 },{
3106 .name = "host",
3107 .type = QEMU_OPT_STRING,
3108 },{
3109 .name = "port",
3110 .type = QEMU_OPT_STRING,
3111 },{
3112 .name = "localaddr",
3113 .type = QEMU_OPT_STRING,
3114 },{
3115 .name = "localport",
3116 .type = QEMU_OPT_STRING,
3117 },{
3118 .name = "to",
3119 .type = QEMU_OPT_NUMBER,
3120 },{
3121 .name = "ipv4",
3122 .type = QEMU_OPT_BOOL,
3123 },{
3124 .name = "ipv6",
3125 .type = QEMU_OPT_BOOL,
3126 },{
3127 .name = "wait",
3128 .type = QEMU_OPT_BOOL,
3129 },{
3130 .name = "server",
3131 .type = QEMU_OPT_BOOL,
3132 },{
3133 .name = "delay",
3134 .type = QEMU_OPT_BOOL,
3135 },{
3136 .name = "telnet",
3137 .type = QEMU_OPT_BOOL,
3138 },{
3139 .name = "width",
3140 .type = QEMU_OPT_NUMBER,
3141 },{
3142 .name = "height",
3143 .type = QEMU_OPT_NUMBER,
3144 },{
3145 .name = "cols",
3146 .type = QEMU_OPT_NUMBER,
3147 },{
3148 .name = "rows",
3149 .type = QEMU_OPT_NUMBER,
3150 },{
3151 .name = "mux",
3152 .type = QEMU_OPT_BOOL,
3153 },{
3154 .name = "signal",
3155 .type = QEMU_OPT_BOOL,
3156 },{
3157 .name = "name",
3158 .type = QEMU_OPT_STRING,
3159 },{
3160 .name = "debug",
3161 .type = QEMU_OPT_NUMBER,
3162 },{
3163 .name = "size",
3164 .type = QEMU_OPT_SIZE,
3165 },
3166 { /* end of list */ }
3167 },
3168 };
3169
3170 #ifdef _WIN32
3171
3172 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3173 {
3174 HANDLE out;
3175
3176 if (file->in) {
3177 error_setg(errp, "input file not supported");
3178 return NULL;
3179 }
3180
3181 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3182 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3183 if (out == INVALID_HANDLE_VALUE) {
3184 error_setg(errp, "open %s failed", file->out);
3185 return NULL;
3186 }
3187 return qemu_chr_open_win_file(out);
3188 }
3189
3190 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3191 Error **errp)
3192 {
3193 return qemu_chr_open_win_path(serial->device);
3194 }
3195
3196 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3197 Error **errp)
3198 {
3199 error_setg(errp, "character device backend type 'parallel' not supported");
3200 return NULL;
3201 }
3202
3203 #else /* WIN32 */
3204
3205 static int qmp_chardev_open_file_source(char *src, int flags,
3206 Error **errp)
3207 {
3208 int fd = -1;
3209
3210 TFR(fd = qemu_open(src, flags, 0666));
3211 if (fd == -1) {
3212 error_setg(errp, "open %s: %s", src, strerror(errno));
3213 }
3214 return fd;
3215 }
3216
3217 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3218 {
3219 int flags, in = -1, out = -1;
3220
3221 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3222 out = qmp_chardev_open_file_source(file->out, flags, errp);
3223 if (error_is_set(errp)) {
3224 return NULL;
3225 }
3226
3227 if (file->in) {
3228 flags = O_RDONLY;
3229 in = qmp_chardev_open_file_source(file->in, flags, errp);
3230 if (error_is_set(errp)) {
3231 qemu_close(out);
3232 return NULL;
3233 }
3234 }
3235
3236 return qemu_chr_open_fd(in, out);
3237 }
3238
3239 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3240 Error **errp)
3241 {
3242 #ifdef HAVE_CHARDEV_TTY
3243 int fd;
3244
3245 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3246 if (error_is_set(errp)) {
3247 return NULL;
3248 }
3249 socket_set_nonblock(fd);
3250 return qemu_chr_open_tty_fd(fd);
3251 #else
3252 error_setg(errp, "character device backend type 'serial' not supported");
3253 return NULL;
3254 #endif
3255 }
3256
3257 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3258 Error **errp)
3259 {
3260 #ifdef HAVE_CHARDEV_PARPORT
3261 int fd;
3262
3263 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3264 if (error_is_set(errp)) {
3265 return NULL;
3266 }
3267 return qemu_chr_open_pp_fd(fd);
3268 #else
3269 error_setg(errp, "character device backend type 'parallel' not supported");
3270 return NULL;
3271 #endif
3272 }
3273
3274 #endif /* WIN32 */
3275
3276 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3277 Error **errp)
3278 {
3279 SocketAddress *addr = sock->addr;
3280 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3281 bool is_listen = sock->has_server ? sock->server : true;
3282 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3283 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3284 int fd;
3285
3286 if (is_listen) {
3287 fd = socket_listen(addr, errp);
3288 } else {
3289 fd = socket_connect(addr, errp, NULL, NULL);
3290 }
3291 if (error_is_set(errp)) {
3292 return NULL;
3293 }
3294 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3295 is_telnet, is_waitconnect, errp);
3296 }
3297
3298 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3299 Error **errp)
3300 {
3301 ChardevReturn *ret = g_new0(ChardevReturn, 1);
3302 CharDriverState *chr = NULL;
3303
3304 chr = qemu_chr_find(id);
3305 if (chr) {
3306 error_setg(errp, "Chardev '%s' already exists", id);
3307 g_free(ret);
3308 return NULL;
3309 }
3310
3311 switch (backend->kind) {
3312 case CHARDEV_BACKEND_KIND_FILE:
3313 chr = qmp_chardev_open_file(backend->file, errp);
3314 break;
3315 case CHARDEV_BACKEND_KIND_SERIAL:
3316 chr = qmp_chardev_open_serial(backend->serial, errp);
3317 break;
3318 case CHARDEV_BACKEND_KIND_PARALLEL:
3319 chr = qmp_chardev_open_parallel(backend->parallel, errp);
3320 break;
3321 case CHARDEV_BACKEND_KIND_SOCKET:
3322 chr = qmp_chardev_open_socket(backend->socket, errp);
3323 break;
3324 #ifdef HAVE_CHARDEV_TTY
3325 case CHARDEV_BACKEND_KIND_PTY:
3326 {
3327 /* qemu_chr_open_pty sets "path" in opts */
3328 QemuOpts *opts;
3329 opts = qemu_opts_create_nofail(qemu_find_opts("chardev"));
3330 chr = qemu_chr_open_pty(opts);
3331 ret->pty = g_strdup(qemu_opt_get(opts, "path"));
3332 ret->has_pty = true;
3333 qemu_opts_del(opts);
3334 break;
3335 }
3336 #endif
3337 case CHARDEV_BACKEND_KIND_NULL:
3338 chr = qemu_chr_open_null(NULL);
3339 break;
3340 default:
3341 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3342 break;
3343 }
3344
3345 if (chr == NULL && !error_is_set(errp)) {
3346 error_setg(errp, "Failed to create chardev");
3347 }
3348 if (chr) {
3349 chr->label = g_strdup(id);
3350 chr->avail_connections = 1;
3351 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3352 return ret;
3353 } else {
3354 g_free(ret);
3355 return NULL;
3356 }
3357 }
3358
3359 void qmp_chardev_remove(const char *id, Error **errp)
3360 {
3361 CharDriverState *chr;
3362
3363 chr = qemu_chr_find(id);
3364 if (NULL == chr) {
3365 error_setg(errp, "Chardev '%s' not found", id);
3366 return;
3367 }
3368 if (chr->chr_can_read || chr->chr_read ||
3369 chr->chr_event || chr->handler_opaque) {
3370 error_setg(errp, "Chardev '%s' is busy", id);
3371 return;
3372 }
3373 qemu_chr_delete(chr);
3374 }