]> git.proxmox.com Git - mirror_qemu.git/blob - qemu-char.c
qemu-char: Rework qemu_chr_open_socket() for reconnect
[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 "sysemu/sysemu.h"
27 #include "qemu/timer.h"
28 #include "sysemu/char.h"
29 #include "hw/usb.h"
30 #include "qmp-commands.h"
31
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <time.h>
35 #include <errno.h>
36 #include <sys/time.h>
37 #include <zlib.h>
38
39 #ifndef _WIN32
40 #include <sys/times.h>
41 #include <sys/wait.h>
42 #include <termios.h>
43 #include <sys/mman.h>
44 #include <sys/ioctl.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <net/if.h>
49 #include <arpa/inet.h>
50 #include <dirent.h>
51 #include <netdb.h>
52 #include <sys/select.h>
53 #ifdef CONFIG_BSD
54 #include <sys/stat.h>
55 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
56 #include <dev/ppbus/ppi.h>
57 #include <dev/ppbus/ppbconf.h>
58 #elif defined(__DragonFly__)
59 #include <dev/misc/ppi/ppi.h>
60 #include <bus/ppbus/ppbconf.h>
61 #endif
62 #else
63 #ifdef __linux__
64 #include <linux/ppdev.h>
65 #include <linux/parport.h>
66 #endif
67 #ifdef __sun__
68 #include <sys/stat.h>
69 #include <sys/ethernet.h>
70 #include <sys/sockio.h>
71 #include <netinet/arp.h>
72 #include <netinet/in.h>
73 #include <netinet/in_systm.h>
74 #include <netinet/ip.h>
75 #include <netinet/ip_icmp.h> // must come after ip.h
76 #include <netinet/udp.h>
77 #include <netinet/tcp.h>
78 #endif
79 #endif
80 #endif
81
82 #include "qemu/sockets.h"
83 #include "ui/qemu-spice.h"
84
85 #define READ_BUF_LEN 4096
86 #define READ_RETRIES 10
87 #define CHR_MAX_FILENAME_SIZE 256
88
89 /***********************************************************/
90 /* character device */
91
92 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
93 QTAILQ_HEAD_INITIALIZER(chardevs);
94
95 CharDriverState *qemu_chr_alloc(void)
96 {
97 CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
98 qemu_mutex_init(&chr->chr_write_lock);
99 return chr;
100 }
101
102 void qemu_chr_be_event(CharDriverState *s, int event)
103 {
104 /* Keep track if the char device is open */
105 switch (event) {
106 case CHR_EVENT_OPENED:
107 s->be_open = 1;
108 break;
109 case CHR_EVENT_CLOSED:
110 s->be_open = 0;
111 break;
112 }
113
114 if (!s->chr_event)
115 return;
116 s->chr_event(s->handler_opaque, event);
117 }
118
119 void qemu_chr_be_generic_open(CharDriverState *s)
120 {
121 qemu_chr_be_event(s, CHR_EVENT_OPENED);
122 }
123
124 int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
125 {
126 int ret;
127
128 qemu_mutex_lock(&s->chr_write_lock);
129 ret = s->chr_write(s, buf, len);
130 qemu_mutex_unlock(&s->chr_write_lock);
131 return ret;
132 }
133
134 int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
135 {
136 int offset = 0;
137 int res = 0;
138
139 qemu_mutex_lock(&s->chr_write_lock);
140 while (offset < len) {
141 do {
142 res = s->chr_write(s, buf + offset, len - offset);
143 if (res == -1 && errno == EAGAIN) {
144 g_usleep(100);
145 }
146 } while (res == -1 && errno == EAGAIN);
147
148 if (res <= 0) {
149 break;
150 }
151
152 offset += res;
153 }
154 qemu_mutex_unlock(&s->chr_write_lock);
155
156 if (res < 0) {
157 return res;
158 }
159 return offset;
160 }
161
162 int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
163 {
164 int offset = 0, counter = 10;
165 int res;
166
167 if (!s->chr_sync_read) {
168 return 0;
169 }
170
171 while (offset < len) {
172 do {
173 res = s->chr_sync_read(s, buf + offset, len - offset);
174 if (res == -1 && errno == EAGAIN) {
175 g_usleep(100);
176 }
177 } while (res == -1 && errno == EAGAIN);
178
179 if (res == 0) {
180 break;
181 }
182
183 if (res < 0) {
184 return res;
185 }
186
187 offset += res;
188
189 if (!counter--) {
190 break;
191 }
192 }
193
194 return offset;
195 }
196
197 int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
198 {
199 if (!s->chr_ioctl)
200 return -ENOTSUP;
201 return s->chr_ioctl(s, cmd, arg);
202 }
203
204 int qemu_chr_be_can_write(CharDriverState *s)
205 {
206 if (!s->chr_can_read)
207 return 0;
208 return s->chr_can_read(s->handler_opaque);
209 }
210
211 void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
212 {
213 if (s->chr_read) {
214 s->chr_read(s->handler_opaque, buf, len);
215 }
216 }
217
218 int qemu_chr_fe_get_msgfd(CharDriverState *s)
219 {
220 int fd;
221 return (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
222 }
223
224 int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
225 {
226 return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
227 }
228
229 int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
230 {
231 return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
232 }
233
234 int qemu_chr_add_client(CharDriverState *s, int fd)
235 {
236 return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
237 }
238
239 void qemu_chr_accept_input(CharDriverState *s)
240 {
241 if (s->chr_accept_input)
242 s->chr_accept_input(s);
243 qemu_notify_event();
244 }
245
246 void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
247 {
248 char buf[READ_BUF_LEN];
249 va_list ap;
250 va_start(ap, fmt);
251 vsnprintf(buf, sizeof(buf), fmt, ap);
252 qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
253 va_end(ap);
254 }
255
256 static void remove_fd_in_watch(CharDriverState *chr);
257
258 void qemu_chr_add_handlers(CharDriverState *s,
259 IOCanReadHandler *fd_can_read,
260 IOReadHandler *fd_read,
261 IOEventHandler *fd_event,
262 void *opaque)
263 {
264 int fe_open;
265
266 if (!opaque && !fd_can_read && !fd_read && !fd_event) {
267 fe_open = 0;
268 remove_fd_in_watch(s);
269 } else {
270 fe_open = 1;
271 }
272 s->chr_can_read = fd_can_read;
273 s->chr_read = fd_read;
274 s->chr_event = fd_event;
275 s->handler_opaque = opaque;
276 if (fe_open && s->chr_update_read_handler)
277 s->chr_update_read_handler(s);
278
279 if (!s->explicit_fe_open) {
280 qemu_chr_fe_set_open(s, fe_open);
281 }
282
283 /* We're connecting to an already opened device, so let's make sure we
284 also get the open event */
285 if (fe_open && s->be_open) {
286 qemu_chr_be_generic_open(s);
287 }
288 }
289
290 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
291 {
292 return len;
293 }
294
295 static CharDriverState *qemu_chr_open_null(void)
296 {
297 CharDriverState *chr;
298
299 chr = qemu_chr_alloc();
300 chr->chr_write = null_chr_write;
301 chr->explicit_be_open = true;
302 return chr;
303 }
304
305 /* MUX driver for serial I/O splitting */
306 #define MAX_MUX 4
307 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
308 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
309 typedef struct {
310 IOCanReadHandler *chr_can_read[MAX_MUX];
311 IOReadHandler *chr_read[MAX_MUX];
312 IOEventHandler *chr_event[MAX_MUX];
313 void *ext_opaque[MAX_MUX];
314 CharDriverState *drv;
315 int focus;
316 int mux_cnt;
317 int term_got_escape;
318 int max_size;
319 /* Intermediate input buffer allows to catch escape sequences even if the
320 currently active device is not accepting any input - but only until it
321 is full as well. */
322 unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
323 int prod[MAX_MUX];
324 int cons[MAX_MUX];
325 int timestamps;
326
327 /* Protected by the CharDriverState chr_write_lock. */
328 int linestart;
329 int64_t timestamps_start;
330 } MuxDriver;
331
332
333 /* Called with chr_write_lock held. */
334 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
335 {
336 MuxDriver *d = chr->opaque;
337 int ret;
338 if (!d->timestamps) {
339 ret = qemu_chr_fe_write(d->drv, buf, len);
340 } else {
341 int i;
342
343 ret = 0;
344 for (i = 0; i < len; i++) {
345 if (d->linestart) {
346 char buf1[64];
347 int64_t ti;
348 int secs;
349
350 ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
351 if (d->timestamps_start == -1)
352 d->timestamps_start = ti;
353 ti -= d->timestamps_start;
354 secs = ti / 1000;
355 snprintf(buf1, sizeof(buf1),
356 "[%02d:%02d:%02d.%03d] ",
357 secs / 3600,
358 (secs / 60) % 60,
359 secs % 60,
360 (int)(ti % 1000));
361 qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
362 d->linestart = 0;
363 }
364 ret += qemu_chr_fe_write(d->drv, buf+i, 1);
365 if (buf[i] == '\n') {
366 d->linestart = 1;
367 }
368 }
369 }
370 return ret;
371 }
372
373 static const char * const mux_help[] = {
374 "% h print this help\n\r",
375 "% x exit emulator\n\r",
376 "% s save disk data back to file (if -snapshot)\n\r",
377 "% t toggle console timestamps\n\r"
378 "% b send break (magic sysrq)\n\r",
379 "% c switch between console and monitor\n\r",
380 "% % sends %\n\r",
381 NULL
382 };
383
384 int term_escape_char = 0x01; /* ctrl-a is used for escape */
385 static void mux_print_help(CharDriverState *chr)
386 {
387 int i, j;
388 char ebuf[15] = "Escape-Char";
389 char cbuf[50] = "\n\r";
390
391 if (term_escape_char > 0 && term_escape_char < 26) {
392 snprintf(cbuf, sizeof(cbuf), "\n\r");
393 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
394 } else {
395 snprintf(cbuf, sizeof(cbuf),
396 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
397 term_escape_char);
398 }
399 qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
400 for (i = 0; mux_help[i] != NULL; i++) {
401 for (j=0; mux_help[i][j] != '\0'; j++) {
402 if (mux_help[i][j] == '%')
403 qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
404 else
405 qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
406 }
407 }
408 }
409
410 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
411 {
412 if (d->chr_event[mux_nr])
413 d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
414 }
415
416 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
417 {
418 if (d->term_got_escape) {
419 d->term_got_escape = 0;
420 if (ch == term_escape_char)
421 goto send_char;
422 switch(ch) {
423 case '?':
424 case 'h':
425 mux_print_help(chr);
426 break;
427 case 'x':
428 {
429 const char *term = "QEMU: Terminated\n\r";
430 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
431 exit(0);
432 break;
433 }
434 case 's':
435 bdrv_commit_all();
436 break;
437 case 'b':
438 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
439 break;
440 case 'c':
441 /* Switch to the next registered device */
442 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
443 d->focus++;
444 if (d->focus >= d->mux_cnt)
445 d->focus = 0;
446 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
447 break;
448 case 't':
449 d->timestamps = !d->timestamps;
450 d->timestamps_start = -1;
451 d->linestart = 0;
452 break;
453 }
454 } else if (ch == term_escape_char) {
455 d->term_got_escape = 1;
456 } else {
457 send_char:
458 return 1;
459 }
460 return 0;
461 }
462
463 static void mux_chr_accept_input(CharDriverState *chr)
464 {
465 MuxDriver *d = chr->opaque;
466 int m = d->focus;
467
468 while (d->prod[m] != d->cons[m] &&
469 d->chr_can_read[m] &&
470 d->chr_can_read[m](d->ext_opaque[m])) {
471 d->chr_read[m](d->ext_opaque[m],
472 &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
473 }
474 }
475
476 static int mux_chr_can_read(void *opaque)
477 {
478 CharDriverState *chr = opaque;
479 MuxDriver *d = chr->opaque;
480 int m = d->focus;
481
482 if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
483 return 1;
484 if (d->chr_can_read[m])
485 return d->chr_can_read[m](d->ext_opaque[m]);
486 return 0;
487 }
488
489 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
490 {
491 CharDriverState *chr = opaque;
492 MuxDriver *d = chr->opaque;
493 int m = d->focus;
494 int i;
495
496 mux_chr_accept_input (opaque);
497
498 for(i = 0; i < size; i++)
499 if (mux_proc_byte(chr, d, buf[i])) {
500 if (d->prod[m] == d->cons[m] &&
501 d->chr_can_read[m] &&
502 d->chr_can_read[m](d->ext_opaque[m]))
503 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
504 else
505 d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
506 }
507 }
508
509 static void mux_chr_event(void *opaque, int event)
510 {
511 CharDriverState *chr = opaque;
512 MuxDriver *d = chr->opaque;
513 int i;
514
515 /* Send the event to all registered listeners */
516 for (i = 0; i < d->mux_cnt; i++)
517 mux_chr_send_event(d, i, event);
518 }
519
520 static void mux_chr_update_read_handler(CharDriverState *chr)
521 {
522 MuxDriver *d = chr->opaque;
523
524 if (d->mux_cnt >= MAX_MUX) {
525 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
526 return;
527 }
528 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
529 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
530 d->chr_read[d->mux_cnt] = chr->chr_read;
531 d->chr_event[d->mux_cnt] = chr->chr_event;
532 /* Fix up the real driver with mux routines */
533 if (d->mux_cnt == 0) {
534 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
535 mux_chr_event, chr);
536 }
537 if (d->focus != -1) {
538 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
539 }
540 d->focus = d->mux_cnt;
541 d->mux_cnt++;
542 mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
543 }
544
545 static bool muxes_realized;
546
547 /**
548 * Called after processing of default and command-line-specified
549 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
550 * to a mux chardev. This is done here to ensure that
551 * output/prompts/banners are only displayed for the FE that has
552 * focus when initial command-line processing/machine init is
553 * completed.
554 *
555 * After this point, any new FE attached to any new or existing
556 * mux will receive CHR_EVENT_OPENED notifications for the BE
557 * immediately.
558 */
559 static void muxes_realize_done(Notifier *notifier, void *unused)
560 {
561 CharDriverState *chr;
562
563 QTAILQ_FOREACH(chr, &chardevs, next) {
564 if (chr->is_mux) {
565 MuxDriver *d = chr->opaque;
566 int i;
567
568 /* send OPENED to all already-attached FEs */
569 for (i = 0; i < d->mux_cnt; i++) {
570 mux_chr_send_event(d, i, CHR_EVENT_OPENED);
571 }
572 /* mark mux as OPENED so any new FEs will immediately receive
573 * OPENED event
574 */
575 qemu_chr_be_generic_open(chr);
576 }
577 }
578 muxes_realized = true;
579 }
580
581 static Notifier muxes_realize_notify = {
582 .notify = muxes_realize_done,
583 };
584
585 static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
586 {
587 MuxDriver *d = s->opaque;
588 return d->drv->chr_add_watch(d->drv, cond);
589 }
590
591 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
592 {
593 CharDriverState *chr;
594 MuxDriver *d;
595
596 chr = qemu_chr_alloc();
597 d = g_malloc0(sizeof(MuxDriver));
598
599 chr->opaque = d;
600 d->drv = drv;
601 d->focus = -1;
602 chr->chr_write = mux_chr_write;
603 chr->chr_update_read_handler = mux_chr_update_read_handler;
604 chr->chr_accept_input = mux_chr_accept_input;
605 /* Frontend guest-open / -close notification is not support with muxes */
606 chr->chr_set_fe_open = NULL;
607 if (drv->chr_add_watch) {
608 chr->chr_add_watch = mux_chr_add_watch;
609 }
610 /* only default to opened state if we've realized the initial
611 * set of muxes
612 */
613 chr->explicit_be_open = muxes_realized ? 0 : 1;
614 chr->is_mux = 1;
615
616 return chr;
617 }
618
619
620 #ifdef _WIN32
621 int send_all(int fd, const void *buf, int len1)
622 {
623 int ret, len;
624
625 len = len1;
626 while (len > 0) {
627 ret = send(fd, buf, len, 0);
628 if (ret < 0) {
629 errno = WSAGetLastError();
630 if (errno != WSAEWOULDBLOCK) {
631 return -1;
632 }
633 } else if (ret == 0) {
634 break;
635 } else {
636 buf += ret;
637 len -= ret;
638 }
639 }
640 return len1 - len;
641 }
642
643 #else
644
645 int send_all(int fd, const void *_buf, int len1)
646 {
647 int ret, len;
648 const uint8_t *buf = _buf;
649
650 len = len1;
651 while (len > 0) {
652 ret = write(fd, buf, len);
653 if (ret < 0) {
654 if (errno != EINTR && errno != EAGAIN)
655 return -1;
656 } else if (ret == 0) {
657 break;
658 } else {
659 buf += ret;
660 len -= ret;
661 }
662 }
663 return len1 - len;
664 }
665
666 int recv_all(int fd, void *_buf, int len1, bool single_read)
667 {
668 int ret, len;
669 uint8_t *buf = _buf;
670
671 len = len1;
672 while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
673 if (ret < 0) {
674 if (errno != EINTR && errno != EAGAIN) {
675 return -1;
676 }
677 continue;
678 } else {
679 if (single_read) {
680 return ret;
681 }
682 buf += ret;
683 len -= ret;
684 }
685 }
686 return len1 - len;
687 }
688
689 #endif /* !_WIN32 */
690
691 typedef struct IOWatchPoll
692 {
693 GSource parent;
694
695 GIOChannel *channel;
696 GSource *src;
697
698 IOCanReadHandler *fd_can_read;
699 GSourceFunc fd_read;
700 void *opaque;
701 } IOWatchPoll;
702
703 static IOWatchPoll *io_watch_poll_from_source(GSource *source)
704 {
705 return container_of(source, IOWatchPoll, parent);
706 }
707
708 static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
709 {
710 IOWatchPoll *iwp = io_watch_poll_from_source(source);
711 bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
712 bool was_active = iwp->src != NULL;
713 if (was_active == now_active) {
714 return FALSE;
715 }
716
717 if (now_active) {
718 iwp->src = g_io_create_watch(iwp->channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
719 g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
720 g_source_attach(iwp->src, NULL);
721 } else {
722 g_source_destroy(iwp->src);
723 g_source_unref(iwp->src);
724 iwp->src = NULL;
725 }
726 return FALSE;
727 }
728
729 static gboolean io_watch_poll_check(GSource *source)
730 {
731 return FALSE;
732 }
733
734 static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
735 gpointer user_data)
736 {
737 abort();
738 }
739
740 static void io_watch_poll_finalize(GSource *source)
741 {
742 /* Due to a glib bug, removing the last reference to a source
743 * inside a finalize callback causes recursive locking (and a
744 * deadlock). This is not a problem inside other callbacks,
745 * including dispatch callbacks, so we call io_remove_watch_poll
746 * to remove this source. At this point, iwp->src must
747 * be NULL, or we would leak it.
748 *
749 * This would be solved much more elegantly by child sources,
750 * but we support older glib versions that do not have them.
751 */
752 IOWatchPoll *iwp = io_watch_poll_from_source(source);
753 assert(iwp->src == NULL);
754 }
755
756 static GSourceFuncs io_watch_poll_funcs = {
757 .prepare = io_watch_poll_prepare,
758 .check = io_watch_poll_check,
759 .dispatch = io_watch_poll_dispatch,
760 .finalize = io_watch_poll_finalize,
761 };
762
763 /* Can only be used for read */
764 static guint io_add_watch_poll(GIOChannel *channel,
765 IOCanReadHandler *fd_can_read,
766 GIOFunc fd_read,
767 gpointer user_data)
768 {
769 IOWatchPoll *iwp;
770 int tag;
771
772 iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
773 iwp->fd_can_read = fd_can_read;
774 iwp->opaque = user_data;
775 iwp->channel = channel;
776 iwp->fd_read = (GSourceFunc) fd_read;
777 iwp->src = NULL;
778
779 tag = g_source_attach(&iwp->parent, NULL);
780 g_source_unref(&iwp->parent);
781 return tag;
782 }
783
784 static void io_remove_watch_poll(guint tag)
785 {
786 GSource *source;
787 IOWatchPoll *iwp;
788
789 g_return_if_fail (tag > 0);
790
791 source = g_main_context_find_source_by_id(NULL, tag);
792 g_return_if_fail (source != NULL);
793
794 iwp = io_watch_poll_from_source(source);
795 if (iwp->src) {
796 g_source_destroy(iwp->src);
797 g_source_unref(iwp->src);
798 iwp->src = NULL;
799 }
800 g_source_destroy(&iwp->parent);
801 }
802
803 static void remove_fd_in_watch(CharDriverState *chr)
804 {
805 if (chr->fd_in_tag) {
806 io_remove_watch_poll(chr->fd_in_tag);
807 chr->fd_in_tag = 0;
808 }
809 }
810
811 #ifndef _WIN32
812 static GIOChannel *io_channel_from_fd(int fd)
813 {
814 GIOChannel *chan;
815
816 if (fd == -1) {
817 return NULL;
818 }
819
820 chan = g_io_channel_unix_new(fd);
821
822 g_io_channel_set_encoding(chan, NULL, NULL);
823 g_io_channel_set_buffered(chan, FALSE);
824
825 return chan;
826 }
827 #endif
828
829 static GIOChannel *io_channel_from_socket(int fd)
830 {
831 GIOChannel *chan;
832
833 if (fd == -1) {
834 return NULL;
835 }
836
837 #ifdef _WIN32
838 chan = g_io_channel_win32_new_socket(fd);
839 #else
840 chan = g_io_channel_unix_new(fd);
841 #endif
842
843 g_io_channel_set_encoding(chan, NULL, NULL);
844 g_io_channel_set_buffered(chan, FALSE);
845
846 return chan;
847 }
848
849 static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
850 {
851 size_t offset = 0;
852 GIOStatus status = G_IO_STATUS_NORMAL;
853
854 while (offset < len && status == G_IO_STATUS_NORMAL) {
855 gsize bytes_written = 0;
856
857 status = g_io_channel_write_chars(fd, buf + offset, len - offset,
858 &bytes_written, NULL);
859 offset += bytes_written;
860 }
861
862 if (offset > 0) {
863 return offset;
864 }
865 switch (status) {
866 case G_IO_STATUS_NORMAL:
867 g_assert(len == 0);
868 return 0;
869 case G_IO_STATUS_AGAIN:
870 errno = EAGAIN;
871 return -1;
872 default:
873 break;
874 }
875 errno = EINVAL;
876 return -1;
877 }
878
879 #ifndef _WIN32
880
881 typedef struct FDCharDriver {
882 CharDriverState *chr;
883 GIOChannel *fd_in, *fd_out;
884 int max_size;
885 QTAILQ_ENTRY(FDCharDriver) node;
886 } FDCharDriver;
887
888 /* Called with chr_write_lock held. */
889 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
890 {
891 FDCharDriver *s = chr->opaque;
892
893 return io_channel_send(s->fd_out, buf, len);
894 }
895
896 static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
897 {
898 CharDriverState *chr = opaque;
899 FDCharDriver *s = chr->opaque;
900 int len;
901 uint8_t buf[READ_BUF_LEN];
902 GIOStatus status;
903 gsize bytes_read;
904
905 len = sizeof(buf);
906 if (len > s->max_size) {
907 len = s->max_size;
908 }
909 if (len == 0) {
910 return TRUE;
911 }
912
913 status = g_io_channel_read_chars(chan, (gchar *)buf,
914 len, &bytes_read, NULL);
915 if (status == G_IO_STATUS_EOF) {
916 remove_fd_in_watch(chr);
917 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
918 return FALSE;
919 }
920 if (status == G_IO_STATUS_NORMAL) {
921 qemu_chr_be_write(chr, buf, bytes_read);
922 }
923
924 return TRUE;
925 }
926
927 static int fd_chr_read_poll(void *opaque)
928 {
929 CharDriverState *chr = opaque;
930 FDCharDriver *s = chr->opaque;
931
932 s->max_size = qemu_chr_be_can_write(chr);
933 return s->max_size;
934 }
935
936 static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
937 {
938 FDCharDriver *s = chr->opaque;
939 return g_io_create_watch(s->fd_out, cond);
940 }
941
942 static void fd_chr_update_read_handler(CharDriverState *chr)
943 {
944 FDCharDriver *s = chr->opaque;
945
946 remove_fd_in_watch(chr);
947 if (s->fd_in) {
948 chr->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll,
949 fd_chr_read, chr);
950 }
951 }
952
953 static void fd_chr_close(struct CharDriverState *chr)
954 {
955 FDCharDriver *s = chr->opaque;
956
957 remove_fd_in_watch(chr);
958 if (s->fd_in) {
959 g_io_channel_unref(s->fd_in);
960 }
961 if (s->fd_out) {
962 g_io_channel_unref(s->fd_out);
963 }
964
965 g_free(s);
966 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
967 }
968
969 /* open a character device to a unix fd */
970 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
971 {
972 CharDriverState *chr;
973 FDCharDriver *s;
974
975 chr = qemu_chr_alloc();
976 s = g_malloc0(sizeof(FDCharDriver));
977 s->fd_in = io_channel_from_fd(fd_in);
978 s->fd_out = io_channel_from_fd(fd_out);
979 qemu_set_nonblock(fd_out);
980 s->chr = chr;
981 chr->opaque = s;
982 chr->chr_add_watch = fd_chr_add_watch;
983 chr->chr_write = fd_chr_write;
984 chr->chr_update_read_handler = fd_chr_update_read_handler;
985 chr->chr_close = fd_chr_close;
986
987 return chr;
988 }
989
990 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
991 {
992 int fd_in, fd_out;
993 char filename_in[CHR_MAX_FILENAME_SIZE];
994 char filename_out[CHR_MAX_FILENAME_SIZE];
995 const char *filename = opts->device;
996
997 if (filename == NULL) {
998 fprintf(stderr, "chardev: pipe: no filename given\n");
999 return NULL;
1000 }
1001
1002 snprintf(filename_in, CHR_MAX_FILENAME_SIZE, "%s.in", filename);
1003 snprintf(filename_out, CHR_MAX_FILENAME_SIZE, "%s.out", filename);
1004 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
1005 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1006 if (fd_in < 0 || fd_out < 0) {
1007 if (fd_in >= 0)
1008 close(fd_in);
1009 if (fd_out >= 0)
1010 close(fd_out);
1011 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1012 if (fd_in < 0) {
1013 return NULL;
1014 }
1015 }
1016 return qemu_chr_open_fd(fd_in, fd_out);
1017 }
1018
1019 /* init terminal so that we can grab keys */
1020 static struct termios oldtty;
1021 static int old_fd0_flags;
1022 static bool stdio_in_use;
1023 static bool stdio_allow_signal;
1024
1025 static void term_exit(void)
1026 {
1027 tcsetattr (0, TCSANOW, &oldtty);
1028 fcntl(0, F_SETFL, old_fd0_flags);
1029 }
1030
1031 static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1032 {
1033 struct termios tty;
1034
1035 tty = oldtty;
1036 if (!echo) {
1037 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1038 |INLCR|IGNCR|ICRNL|IXON);
1039 tty.c_oflag |= OPOST;
1040 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1041 tty.c_cflag &= ~(CSIZE|PARENB);
1042 tty.c_cflag |= CS8;
1043 tty.c_cc[VMIN] = 1;
1044 tty.c_cc[VTIME] = 0;
1045 }
1046 if (!stdio_allow_signal)
1047 tty.c_lflag &= ~ISIG;
1048
1049 tcsetattr (0, TCSANOW, &tty);
1050 }
1051
1052 static void qemu_chr_close_stdio(struct CharDriverState *chr)
1053 {
1054 term_exit();
1055 fd_chr_close(chr);
1056 }
1057
1058 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
1059 {
1060 CharDriverState *chr;
1061
1062 if (is_daemonized()) {
1063 error_report("cannot use stdio with -daemonize");
1064 return NULL;
1065 }
1066
1067 if (stdio_in_use) {
1068 error_report("cannot use stdio by multiple character devices");
1069 exit(1);
1070 }
1071
1072 stdio_in_use = true;
1073 old_fd0_flags = fcntl(0, F_GETFL);
1074 tcgetattr(0, &oldtty);
1075 qemu_set_nonblock(0);
1076 atexit(term_exit);
1077
1078 chr = qemu_chr_open_fd(0, 1);
1079 chr->chr_close = qemu_chr_close_stdio;
1080 chr->chr_set_echo = qemu_chr_set_echo_stdio;
1081 if (opts->has_signal) {
1082 stdio_allow_signal = opts->signal;
1083 }
1084 qemu_chr_fe_set_echo(chr, false);
1085
1086 return chr;
1087 }
1088
1089 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1090 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1091 || defined(__GLIBC__)
1092
1093 #define HAVE_CHARDEV_TTY 1
1094
1095 typedef struct {
1096 GIOChannel *fd;
1097 int read_bytes;
1098
1099 /* Protected by the CharDriverState chr_write_lock. */
1100 int connected;
1101 guint timer_tag;
1102 guint open_tag;
1103 } PtyCharDriver;
1104
1105 static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1106 static void pty_chr_state(CharDriverState *chr, int connected);
1107
1108 static gboolean pty_chr_timer(gpointer opaque)
1109 {
1110 struct CharDriverState *chr = opaque;
1111 PtyCharDriver *s = chr->opaque;
1112
1113 qemu_mutex_lock(&chr->chr_write_lock);
1114 s->timer_tag = 0;
1115 s->open_tag = 0;
1116 if (!s->connected) {
1117 /* Next poll ... */
1118 pty_chr_update_read_handler_locked(chr);
1119 }
1120 qemu_mutex_unlock(&chr->chr_write_lock);
1121 return FALSE;
1122 }
1123
1124 /* Called with chr_write_lock held. */
1125 static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1126 {
1127 PtyCharDriver *s = chr->opaque;
1128
1129 if (s->timer_tag) {
1130 g_source_remove(s->timer_tag);
1131 s->timer_tag = 0;
1132 }
1133
1134 if (ms == 1000) {
1135 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1136 } else {
1137 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1138 }
1139 }
1140
1141 /* Called with chr_write_lock held. */
1142 static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1143 {
1144 PtyCharDriver *s = chr->opaque;
1145 GPollFD pfd;
1146
1147 pfd.fd = g_io_channel_unix_get_fd(s->fd);
1148 pfd.events = G_IO_OUT;
1149 pfd.revents = 0;
1150 g_poll(&pfd, 1, 0);
1151 if (pfd.revents & G_IO_HUP) {
1152 pty_chr_state(chr, 0);
1153 } else {
1154 pty_chr_state(chr, 1);
1155 }
1156 }
1157
1158 static void pty_chr_update_read_handler(CharDriverState *chr)
1159 {
1160 qemu_mutex_lock(&chr->chr_write_lock);
1161 pty_chr_update_read_handler_locked(chr);
1162 qemu_mutex_unlock(&chr->chr_write_lock);
1163 }
1164
1165 /* Called with chr_write_lock held. */
1166 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1167 {
1168 PtyCharDriver *s = chr->opaque;
1169
1170 if (!s->connected) {
1171 /* guest sends data, check for (re-)connect */
1172 pty_chr_update_read_handler_locked(chr);
1173 if (!s->connected) {
1174 return 0;
1175 }
1176 }
1177 return io_channel_send(s->fd, buf, len);
1178 }
1179
1180 static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1181 {
1182 PtyCharDriver *s = chr->opaque;
1183 if (!s->connected) {
1184 return NULL;
1185 }
1186 return g_io_create_watch(s->fd, cond);
1187 }
1188
1189 static int pty_chr_read_poll(void *opaque)
1190 {
1191 CharDriverState *chr = opaque;
1192 PtyCharDriver *s = chr->opaque;
1193
1194 s->read_bytes = qemu_chr_be_can_write(chr);
1195 return s->read_bytes;
1196 }
1197
1198 static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1199 {
1200 CharDriverState *chr = opaque;
1201 PtyCharDriver *s = chr->opaque;
1202 gsize size, len;
1203 uint8_t buf[READ_BUF_LEN];
1204 GIOStatus status;
1205
1206 len = sizeof(buf);
1207 if (len > s->read_bytes)
1208 len = s->read_bytes;
1209 if (len == 0) {
1210 return TRUE;
1211 }
1212 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1213 if (status != G_IO_STATUS_NORMAL) {
1214 pty_chr_state(chr, 0);
1215 return FALSE;
1216 } else {
1217 pty_chr_state(chr, 1);
1218 qemu_chr_be_write(chr, buf, size);
1219 }
1220 return TRUE;
1221 }
1222
1223 static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
1224 {
1225 CharDriverState *chr = opaque;
1226 PtyCharDriver *s = chr->opaque;
1227
1228 s->open_tag = 0;
1229 qemu_chr_be_generic_open(chr);
1230 return FALSE;
1231 }
1232
1233 /* Called with chr_write_lock held. */
1234 static void pty_chr_state(CharDriverState *chr, int connected)
1235 {
1236 PtyCharDriver *s = chr->opaque;
1237
1238 if (!connected) {
1239 if (s->open_tag) {
1240 g_source_remove(s->open_tag);
1241 s->open_tag = 0;
1242 }
1243 remove_fd_in_watch(chr);
1244 s->connected = 0;
1245 /* (re-)connect poll interval for idle guests: once per second.
1246 * We check more frequently in case the guests sends data to
1247 * the virtual device linked to our pty. */
1248 pty_chr_rearm_timer(chr, 1000);
1249 } else {
1250 if (s->timer_tag) {
1251 g_source_remove(s->timer_tag);
1252 s->timer_tag = 0;
1253 }
1254 if (!s->connected) {
1255 g_assert(s->open_tag == 0);
1256 s->connected = 1;
1257 s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1258 }
1259 if (!chr->fd_in_tag) {
1260 chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
1261 pty_chr_read, chr);
1262 }
1263 }
1264 }
1265
1266 static void pty_chr_close(struct CharDriverState *chr)
1267 {
1268 PtyCharDriver *s = chr->opaque;
1269 int fd;
1270
1271 qemu_mutex_lock(&chr->chr_write_lock);
1272 pty_chr_state(chr, 0);
1273 fd = g_io_channel_unix_get_fd(s->fd);
1274 g_io_channel_unref(s->fd);
1275 close(fd);
1276 if (s->timer_tag) {
1277 g_source_remove(s->timer_tag);
1278 s->timer_tag = 0;
1279 }
1280 qemu_mutex_unlock(&chr->chr_write_lock);
1281 g_free(s);
1282 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1283 }
1284
1285 static CharDriverState *qemu_chr_open_pty(const char *id,
1286 ChardevReturn *ret)
1287 {
1288 CharDriverState *chr;
1289 PtyCharDriver *s;
1290 int master_fd, slave_fd;
1291 char pty_name[PATH_MAX];
1292
1293 master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1294 if (master_fd < 0) {
1295 return NULL;
1296 }
1297
1298 close(slave_fd);
1299
1300 chr = qemu_chr_alloc();
1301
1302 chr->filename = g_strdup_printf("pty:%s", pty_name);
1303 ret->pty = g_strdup(pty_name);
1304 ret->has_pty = true;
1305
1306 fprintf(stderr, "char device redirected to %s (label %s)\n",
1307 pty_name, id);
1308
1309 s = g_malloc0(sizeof(PtyCharDriver));
1310 chr->opaque = s;
1311 chr->chr_write = pty_chr_write;
1312 chr->chr_update_read_handler = pty_chr_update_read_handler;
1313 chr->chr_close = pty_chr_close;
1314 chr->chr_add_watch = pty_chr_add_watch;
1315 chr->explicit_be_open = true;
1316
1317 s->fd = io_channel_from_fd(master_fd);
1318 s->timer_tag = 0;
1319
1320 return chr;
1321 }
1322
1323 static void tty_serial_init(int fd, int speed,
1324 int parity, int data_bits, int stop_bits)
1325 {
1326 struct termios tty;
1327 speed_t spd;
1328
1329 #if 0
1330 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1331 speed, parity, data_bits, stop_bits);
1332 #endif
1333 tcgetattr (fd, &tty);
1334
1335 #define check_speed(val) if (speed <= val) { spd = B##val; break; }
1336 speed = speed * 10 / 11;
1337 do {
1338 check_speed(50);
1339 check_speed(75);
1340 check_speed(110);
1341 check_speed(134);
1342 check_speed(150);
1343 check_speed(200);
1344 check_speed(300);
1345 check_speed(600);
1346 check_speed(1200);
1347 check_speed(1800);
1348 check_speed(2400);
1349 check_speed(4800);
1350 check_speed(9600);
1351 check_speed(19200);
1352 check_speed(38400);
1353 /* Non-Posix values follow. They may be unsupported on some systems. */
1354 check_speed(57600);
1355 check_speed(115200);
1356 #ifdef B230400
1357 check_speed(230400);
1358 #endif
1359 #ifdef B460800
1360 check_speed(460800);
1361 #endif
1362 #ifdef B500000
1363 check_speed(500000);
1364 #endif
1365 #ifdef B576000
1366 check_speed(576000);
1367 #endif
1368 #ifdef B921600
1369 check_speed(921600);
1370 #endif
1371 #ifdef B1000000
1372 check_speed(1000000);
1373 #endif
1374 #ifdef B1152000
1375 check_speed(1152000);
1376 #endif
1377 #ifdef B1500000
1378 check_speed(1500000);
1379 #endif
1380 #ifdef B2000000
1381 check_speed(2000000);
1382 #endif
1383 #ifdef B2500000
1384 check_speed(2500000);
1385 #endif
1386 #ifdef B3000000
1387 check_speed(3000000);
1388 #endif
1389 #ifdef B3500000
1390 check_speed(3500000);
1391 #endif
1392 #ifdef B4000000
1393 check_speed(4000000);
1394 #endif
1395 spd = B115200;
1396 } while (0);
1397
1398 cfsetispeed(&tty, spd);
1399 cfsetospeed(&tty, spd);
1400
1401 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1402 |INLCR|IGNCR|ICRNL|IXON);
1403 tty.c_oflag |= OPOST;
1404 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1405 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1406 switch(data_bits) {
1407 default:
1408 case 8:
1409 tty.c_cflag |= CS8;
1410 break;
1411 case 7:
1412 tty.c_cflag |= CS7;
1413 break;
1414 case 6:
1415 tty.c_cflag |= CS6;
1416 break;
1417 case 5:
1418 tty.c_cflag |= CS5;
1419 break;
1420 }
1421 switch(parity) {
1422 default:
1423 case 'N':
1424 break;
1425 case 'E':
1426 tty.c_cflag |= PARENB;
1427 break;
1428 case 'O':
1429 tty.c_cflag |= PARENB | PARODD;
1430 break;
1431 }
1432 if (stop_bits == 2)
1433 tty.c_cflag |= CSTOPB;
1434
1435 tcsetattr (fd, TCSANOW, &tty);
1436 }
1437
1438 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1439 {
1440 FDCharDriver *s = chr->opaque;
1441
1442 switch(cmd) {
1443 case CHR_IOCTL_SERIAL_SET_PARAMS:
1444 {
1445 QEMUSerialSetParams *ssp = arg;
1446 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1447 ssp->speed, ssp->parity,
1448 ssp->data_bits, ssp->stop_bits);
1449 }
1450 break;
1451 case CHR_IOCTL_SERIAL_SET_BREAK:
1452 {
1453 int enable = *(int *)arg;
1454 if (enable) {
1455 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1456 }
1457 }
1458 break;
1459 case CHR_IOCTL_SERIAL_GET_TIOCM:
1460 {
1461 int sarg = 0;
1462 int *targ = (int *)arg;
1463 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1464 *targ = 0;
1465 if (sarg & TIOCM_CTS)
1466 *targ |= CHR_TIOCM_CTS;
1467 if (sarg & TIOCM_CAR)
1468 *targ |= CHR_TIOCM_CAR;
1469 if (sarg & TIOCM_DSR)
1470 *targ |= CHR_TIOCM_DSR;
1471 if (sarg & TIOCM_RI)
1472 *targ |= CHR_TIOCM_RI;
1473 if (sarg & TIOCM_DTR)
1474 *targ |= CHR_TIOCM_DTR;
1475 if (sarg & TIOCM_RTS)
1476 *targ |= CHR_TIOCM_RTS;
1477 }
1478 break;
1479 case CHR_IOCTL_SERIAL_SET_TIOCM:
1480 {
1481 int sarg = *(int *)arg;
1482 int targ = 0;
1483 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1484 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1485 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1486 if (sarg & CHR_TIOCM_CTS)
1487 targ |= TIOCM_CTS;
1488 if (sarg & CHR_TIOCM_CAR)
1489 targ |= TIOCM_CAR;
1490 if (sarg & CHR_TIOCM_DSR)
1491 targ |= TIOCM_DSR;
1492 if (sarg & CHR_TIOCM_RI)
1493 targ |= TIOCM_RI;
1494 if (sarg & CHR_TIOCM_DTR)
1495 targ |= TIOCM_DTR;
1496 if (sarg & CHR_TIOCM_RTS)
1497 targ |= TIOCM_RTS;
1498 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1499 }
1500 break;
1501 default:
1502 return -ENOTSUP;
1503 }
1504 return 0;
1505 }
1506
1507 static void qemu_chr_close_tty(CharDriverState *chr)
1508 {
1509 FDCharDriver *s = chr->opaque;
1510 int fd = -1;
1511
1512 if (s) {
1513 fd = g_io_channel_unix_get_fd(s->fd_in);
1514 }
1515
1516 fd_chr_close(chr);
1517
1518 if (fd >= 0) {
1519 close(fd);
1520 }
1521 }
1522
1523 static CharDriverState *qemu_chr_open_tty_fd(int fd)
1524 {
1525 CharDriverState *chr;
1526
1527 tty_serial_init(fd, 115200, 'N', 8, 1);
1528 chr = qemu_chr_open_fd(fd, fd);
1529 chr->chr_ioctl = tty_serial_ioctl;
1530 chr->chr_close = qemu_chr_close_tty;
1531 return chr;
1532 }
1533 #endif /* __linux__ || __sun__ */
1534
1535 #if defined(__linux__)
1536
1537 #define HAVE_CHARDEV_PARPORT 1
1538
1539 typedef struct {
1540 int fd;
1541 int mode;
1542 } ParallelCharDriver;
1543
1544 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1545 {
1546 if (s->mode != mode) {
1547 int m = mode;
1548 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1549 return 0;
1550 s->mode = mode;
1551 }
1552 return 1;
1553 }
1554
1555 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1556 {
1557 ParallelCharDriver *drv = chr->opaque;
1558 int fd = drv->fd;
1559 uint8_t b;
1560
1561 switch(cmd) {
1562 case CHR_IOCTL_PP_READ_DATA:
1563 if (ioctl(fd, PPRDATA, &b) < 0)
1564 return -ENOTSUP;
1565 *(uint8_t *)arg = b;
1566 break;
1567 case CHR_IOCTL_PP_WRITE_DATA:
1568 b = *(uint8_t *)arg;
1569 if (ioctl(fd, PPWDATA, &b) < 0)
1570 return -ENOTSUP;
1571 break;
1572 case CHR_IOCTL_PP_READ_CONTROL:
1573 if (ioctl(fd, PPRCONTROL, &b) < 0)
1574 return -ENOTSUP;
1575 /* Linux gives only the lowest bits, and no way to know data
1576 direction! For better compatibility set the fixed upper
1577 bits. */
1578 *(uint8_t *)arg = b | 0xc0;
1579 break;
1580 case CHR_IOCTL_PP_WRITE_CONTROL:
1581 b = *(uint8_t *)arg;
1582 if (ioctl(fd, PPWCONTROL, &b) < 0)
1583 return -ENOTSUP;
1584 break;
1585 case CHR_IOCTL_PP_READ_STATUS:
1586 if (ioctl(fd, PPRSTATUS, &b) < 0)
1587 return -ENOTSUP;
1588 *(uint8_t *)arg = b;
1589 break;
1590 case CHR_IOCTL_PP_DATA_DIR:
1591 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1592 return -ENOTSUP;
1593 break;
1594 case CHR_IOCTL_PP_EPP_READ_ADDR:
1595 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1596 struct ParallelIOArg *parg = arg;
1597 int n = read(fd, parg->buffer, parg->count);
1598 if (n != parg->count) {
1599 return -EIO;
1600 }
1601 }
1602 break;
1603 case CHR_IOCTL_PP_EPP_READ:
1604 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1605 struct ParallelIOArg *parg = arg;
1606 int n = read(fd, parg->buffer, parg->count);
1607 if (n != parg->count) {
1608 return -EIO;
1609 }
1610 }
1611 break;
1612 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1613 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1614 struct ParallelIOArg *parg = arg;
1615 int n = write(fd, parg->buffer, parg->count);
1616 if (n != parg->count) {
1617 return -EIO;
1618 }
1619 }
1620 break;
1621 case CHR_IOCTL_PP_EPP_WRITE:
1622 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1623 struct ParallelIOArg *parg = arg;
1624 int n = write(fd, parg->buffer, parg->count);
1625 if (n != parg->count) {
1626 return -EIO;
1627 }
1628 }
1629 break;
1630 default:
1631 return -ENOTSUP;
1632 }
1633 return 0;
1634 }
1635
1636 static void pp_close(CharDriverState *chr)
1637 {
1638 ParallelCharDriver *drv = chr->opaque;
1639 int fd = drv->fd;
1640
1641 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1642 ioctl(fd, PPRELEASE);
1643 close(fd);
1644 g_free(drv);
1645 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1646 }
1647
1648 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1649 {
1650 CharDriverState *chr;
1651 ParallelCharDriver *drv;
1652
1653 if (ioctl(fd, PPCLAIM) < 0) {
1654 close(fd);
1655 return NULL;
1656 }
1657
1658 drv = g_malloc0(sizeof(ParallelCharDriver));
1659 drv->fd = fd;
1660 drv->mode = IEEE1284_MODE_COMPAT;
1661
1662 chr = qemu_chr_alloc();
1663 chr->chr_write = null_chr_write;
1664 chr->chr_ioctl = pp_ioctl;
1665 chr->chr_close = pp_close;
1666 chr->opaque = drv;
1667
1668 return chr;
1669 }
1670 #endif /* __linux__ */
1671
1672 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1673
1674 #define HAVE_CHARDEV_PARPORT 1
1675
1676 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1677 {
1678 int fd = (int)(intptr_t)chr->opaque;
1679 uint8_t b;
1680
1681 switch(cmd) {
1682 case CHR_IOCTL_PP_READ_DATA:
1683 if (ioctl(fd, PPIGDATA, &b) < 0)
1684 return -ENOTSUP;
1685 *(uint8_t *)arg = b;
1686 break;
1687 case CHR_IOCTL_PP_WRITE_DATA:
1688 b = *(uint8_t *)arg;
1689 if (ioctl(fd, PPISDATA, &b) < 0)
1690 return -ENOTSUP;
1691 break;
1692 case CHR_IOCTL_PP_READ_CONTROL:
1693 if (ioctl(fd, PPIGCTRL, &b) < 0)
1694 return -ENOTSUP;
1695 *(uint8_t *)arg = b;
1696 break;
1697 case CHR_IOCTL_PP_WRITE_CONTROL:
1698 b = *(uint8_t *)arg;
1699 if (ioctl(fd, PPISCTRL, &b) < 0)
1700 return -ENOTSUP;
1701 break;
1702 case CHR_IOCTL_PP_READ_STATUS:
1703 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1704 return -ENOTSUP;
1705 *(uint8_t *)arg = b;
1706 break;
1707 default:
1708 return -ENOTSUP;
1709 }
1710 return 0;
1711 }
1712
1713 static CharDriverState *qemu_chr_open_pp_fd(int fd)
1714 {
1715 CharDriverState *chr;
1716
1717 chr = qemu_chr_alloc();
1718 chr->opaque = (void *)(intptr_t)fd;
1719 chr->chr_write = null_chr_write;
1720 chr->chr_ioctl = pp_ioctl;
1721 chr->explicit_be_open = true;
1722 return chr;
1723 }
1724 #endif
1725
1726 #else /* _WIN32 */
1727
1728 typedef struct {
1729 int max_size;
1730 HANDLE hcom, hrecv, hsend;
1731 OVERLAPPED orecv;
1732 BOOL fpipe;
1733 DWORD len;
1734
1735 /* Protected by the CharDriverState chr_write_lock. */
1736 OVERLAPPED osend;
1737 } WinCharState;
1738
1739 typedef struct {
1740 HANDLE hStdIn;
1741 HANDLE hInputReadyEvent;
1742 HANDLE hInputDoneEvent;
1743 HANDLE hInputThread;
1744 uint8_t win_stdio_buf;
1745 } WinStdioCharState;
1746
1747 #define NSENDBUF 2048
1748 #define NRECVBUF 2048
1749 #define MAXCONNECT 1
1750 #define NTIMEOUT 5000
1751
1752 static int win_chr_poll(void *opaque);
1753 static int win_chr_pipe_poll(void *opaque);
1754
1755 static void win_chr_close(CharDriverState *chr)
1756 {
1757 WinCharState *s = chr->opaque;
1758
1759 if (s->hsend) {
1760 CloseHandle(s->hsend);
1761 s->hsend = NULL;
1762 }
1763 if (s->hrecv) {
1764 CloseHandle(s->hrecv);
1765 s->hrecv = NULL;
1766 }
1767 if (s->hcom) {
1768 CloseHandle(s->hcom);
1769 s->hcom = NULL;
1770 }
1771 if (s->fpipe)
1772 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1773 else
1774 qemu_del_polling_cb(win_chr_poll, chr);
1775
1776 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1777 }
1778
1779 static int win_chr_init(CharDriverState *chr, const char *filename)
1780 {
1781 WinCharState *s = chr->opaque;
1782 COMMCONFIG comcfg;
1783 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1784 COMSTAT comstat;
1785 DWORD size;
1786 DWORD err;
1787
1788 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1789 if (!s->hsend) {
1790 fprintf(stderr, "Failed CreateEvent\n");
1791 goto fail;
1792 }
1793 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1794 if (!s->hrecv) {
1795 fprintf(stderr, "Failed CreateEvent\n");
1796 goto fail;
1797 }
1798
1799 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1800 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1801 if (s->hcom == INVALID_HANDLE_VALUE) {
1802 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1803 s->hcom = NULL;
1804 goto fail;
1805 }
1806
1807 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1808 fprintf(stderr, "Failed SetupComm\n");
1809 goto fail;
1810 }
1811
1812 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1813 size = sizeof(COMMCONFIG);
1814 GetDefaultCommConfig(filename, &comcfg, &size);
1815 comcfg.dcb.DCBlength = sizeof(DCB);
1816 CommConfigDialog(filename, NULL, &comcfg);
1817
1818 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1819 fprintf(stderr, "Failed SetCommState\n");
1820 goto fail;
1821 }
1822
1823 if (!SetCommMask(s->hcom, EV_ERR)) {
1824 fprintf(stderr, "Failed SetCommMask\n");
1825 goto fail;
1826 }
1827
1828 cto.ReadIntervalTimeout = MAXDWORD;
1829 if (!SetCommTimeouts(s->hcom, &cto)) {
1830 fprintf(stderr, "Failed SetCommTimeouts\n");
1831 goto fail;
1832 }
1833
1834 if (!ClearCommError(s->hcom, &err, &comstat)) {
1835 fprintf(stderr, "Failed ClearCommError\n");
1836 goto fail;
1837 }
1838 qemu_add_polling_cb(win_chr_poll, chr);
1839 return 0;
1840
1841 fail:
1842 win_chr_close(chr);
1843 return -1;
1844 }
1845
1846 /* Called with chr_write_lock held. */
1847 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1848 {
1849 WinCharState *s = chr->opaque;
1850 DWORD len, ret, size, err;
1851
1852 len = len1;
1853 ZeroMemory(&s->osend, sizeof(s->osend));
1854 s->osend.hEvent = s->hsend;
1855 while (len > 0) {
1856 if (s->hsend)
1857 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1858 else
1859 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1860 if (!ret) {
1861 err = GetLastError();
1862 if (err == ERROR_IO_PENDING) {
1863 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1864 if (ret) {
1865 buf += size;
1866 len -= size;
1867 } else {
1868 break;
1869 }
1870 } else {
1871 break;
1872 }
1873 } else {
1874 buf += size;
1875 len -= size;
1876 }
1877 }
1878 return len1 - len;
1879 }
1880
1881 static int win_chr_read_poll(CharDriverState *chr)
1882 {
1883 WinCharState *s = chr->opaque;
1884
1885 s->max_size = qemu_chr_be_can_write(chr);
1886 return s->max_size;
1887 }
1888
1889 static void win_chr_readfile(CharDriverState *chr)
1890 {
1891 WinCharState *s = chr->opaque;
1892 int ret, err;
1893 uint8_t buf[READ_BUF_LEN];
1894 DWORD size;
1895
1896 ZeroMemory(&s->orecv, sizeof(s->orecv));
1897 s->orecv.hEvent = s->hrecv;
1898 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1899 if (!ret) {
1900 err = GetLastError();
1901 if (err == ERROR_IO_PENDING) {
1902 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1903 }
1904 }
1905
1906 if (size > 0) {
1907 qemu_chr_be_write(chr, buf, size);
1908 }
1909 }
1910
1911 static void win_chr_read(CharDriverState *chr)
1912 {
1913 WinCharState *s = chr->opaque;
1914
1915 if (s->len > s->max_size)
1916 s->len = s->max_size;
1917 if (s->len == 0)
1918 return;
1919
1920 win_chr_readfile(chr);
1921 }
1922
1923 static int win_chr_poll(void *opaque)
1924 {
1925 CharDriverState *chr = opaque;
1926 WinCharState *s = chr->opaque;
1927 COMSTAT status;
1928 DWORD comerr;
1929
1930 ClearCommError(s->hcom, &comerr, &status);
1931 if (status.cbInQue > 0) {
1932 s->len = status.cbInQue;
1933 win_chr_read_poll(chr);
1934 win_chr_read(chr);
1935 return 1;
1936 }
1937 return 0;
1938 }
1939
1940 static CharDriverState *qemu_chr_open_win_path(const char *filename)
1941 {
1942 CharDriverState *chr;
1943 WinCharState *s;
1944
1945 chr = qemu_chr_alloc();
1946 s = g_malloc0(sizeof(WinCharState));
1947 chr->opaque = s;
1948 chr->chr_write = win_chr_write;
1949 chr->chr_close = win_chr_close;
1950
1951 if (win_chr_init(chr, filename) < 0) {
1952 g_free(s);
1953 g_free(chr);
1954 return NULL;
1955 }
1956 return chr;
1957 }
1958
1959 static int win_chr_pipe_poll(void *opaque)
1960 {
1961 CharDriverState *chr = opaque;
1962 WinCharState *s = chr->opaque;
1963 DWORD size;
1964
1965 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1966 if (size > 0) {
1967 s->len = size;
1968 win_chr_read_poll(chr);
1969 win_chr_read(chr);
1970 return 1;
1971 }
1972 return 0;
1973 }
1974
1975 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1976 {
1977 WinCharState *s = chr->opaque;
1978 OVERLAPPED ov;
1979 int ret;
1980 DWORD size;
1981 char openname[CHR_MAX_FILENAME_SIZE];
1982
1983 s->fpipe = TRUE;
1984
1985 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1986 if (!s->hsend) {
1987 fprintf(stderr, "Failed CreateEvent\n");
1988 goto fail;
1989 }
1990 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1991 if (!s->hrecv) {
1992 fprintf(stderr, "Failed CreateEvent\n");
1993 goto fail;
1994 }
1995
1996 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1997 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1998 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1999 PIPE_WAIT,
2000 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2001 if (s->hcom == INVALID_HANDLE_VALUE) {
2002 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2003 s->hcom = NULL;
2004 goto fail;
2005 }
2006
2007 ZeroMemory(&ov, sizeof(ov));
2008 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2009 ret = ConnectNamedPipe(s->hcom, &ov);
2010 if (ret) {
2011 fprintf(stderr, "Failed ConnectNamedPipe\n");
2012 goto fail;
2013 }
2014
2015 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2016 if (!ret) {
2017 fprintf(stderr, "Failed GetOverlappedResult\n");
2018 if (ov.hEvent) {
2019 CloseHandle(ov.hEvent);
2020 ov.hEvent = NULL;
2021 }
2022 goto fail;
2023 }
2024
2025 if (ov.hEvent) {
2026 CloseHandle(ov.hEvent);
2027 ov.hEvent = NULL;
2028 }
2029 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2030 return 0;
2031
2032 fail:
2033 win_chr_close(chr);
2034 return -1;
2035 }
2036
2037
2038 static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
2039 {
2040 const char *filename = opts->device;
2041 CharDriverState *chr;
2042 WinCharState *s;
2043
2044 chr = qemu_chr_alloc();
2045 s = g_malloc0(sizeof(WinCharState));
2046 chr->opaque = s;
2047 chr->chr_write = win_chr_write;
2048 chr->chr_close = win_chr_close;
2049
2050 if (win_chr_pipe_init(chr, filename) < 0) {
2051 g_free(s);
2052 g_free(chr);
2053 return NULL;
2054 }
2055 return chr;
2056 }
2057
2058 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2059 {
2060 CharDriverState *chr;
2061 WinCharState *s;
2062
2063 chr = qemu_chr_alloc();
2064 s = g_malloc0(sizeof(WinCharState));
2065 s->hcom = fd_out;
2066 chr->opaque = s;
2067 chr->chr_write = win_chr_write;
2068 return chr;
2069 }
2070
2071 static CharDriverState *qemu_chr_open_win_con(void)
2072 {
2073 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2074 }
2075
2076 static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
2077 {
2078 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
2079 DWORD dwSize;
2080 int len1;
2081
2082 len1 = len;
2083
2084 while (len1 > 0) {
2085 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
2086 break;
2087 }
2088 buf += dwSize;
2089 len1 -= dwSize;
2090 }
2091
2092 return len - len1;
2093 }
2094
2095 static void win_stdio_wait_func(void *opaque)
2096 {
2097 CharDriverState *chr = opaque;
2098 WinStdioCharState *stdio = chr->opaque;
2099 INPUT_RECORD buf[4];
2100 int ret;
2101 DWORD dwSize;
2102 int i;
2103
2104 ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
2105
2106 if (!ret) {
2107 /* Avoid error storm */
2108 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2109 return;
2110 }
2111
2112 for (i = 0; i < dwSize; i++) {
2113 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2114
2115 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2116 int j;
2117 if (kev->uChar.AsciiChar != 0) {
2118 for (j = 0; j < kev->wRepeatCount; j++) {
2119 if (qemu_chr_be_can_write(chr)) {
2120 uint8_t c = kev->uChar.AsciiChar;
2121 qemu_chr_be_write(chr, &c, 1);
2122 }
2123 }
2124 }
2125 }
2126 }
2127 }
2128
2129 static DWORD WINAPI win_stdio_thread(LPVOID param)
2130 {
2131 CharDriverState *chr = param;
2132 WinStdioCharState *stdio = chr->opaque;
2133 int ret;
2134 DWORD dwSize;
2135
2136 while (1) {
2137
2138 /* Wait for one byte */
2139 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2140
2141 /* Exit in case of error, continue if nothing read */
2142 if (!ret) {
2143 break;
2144 }
2145 if (!dwSize) {
2146 continue;
2147 }
2148
2149 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2150 if (stdio->win_stdio_buf == '\r') {
2151 continue;
2152 }
2153
2154 /* Signal the main thread and wait until the byte was eaten */
2155 if (!SetEvent(stdio->hInputReadyEvent)) {
2156 break;
2157 }
2158 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2159 != WAIT_OBJECT_0) {
2160 break;
2161 }
2162 }
2163
2164 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2165 return 0;
2166 }
2167
2168 static void win_stdio_thread_wait_func(void *opaque)
2169 {
2170 CharDriverState *chr = opaque;
2171 WinStdioCharState *stdio = chr->opaque;
2172
2173 if (qemu_chr_be_can_write(chr)) {
2174 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2175 }
2176
2177 SetEvent(stdio->hInputDoneEvent);
2178 }
2179
2180 static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2181 {
2182 WinStdioCharState *stdio = chr->opaque;
2183 DWORD dwMode = 0;
2184
2185 GetConsoleMode(stdio->hStdIn, &dwMode);
2186
2187 if (echo) {
2188 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2189 } else {
2190 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2191 }
2192 }
2193
2194 static void win_stdio_close(CharDriverState *chr)
2195 {
2196 WinStdioCharState *stdio = chr->opaque;
2197
2198 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2199 CloseHandle(stdio->hInputReadyEvent);
2200 }
2201 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2202 CloseHandle(stdio->hInputDoneEvent);
2203 }
2204 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2205 TerminateThread(stdio->hInputThread, 0);
2206 }
2207
2208 g_free(chr->opaque);
2209 g_free(chr);
2210 }
2211
2212 static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2213 {
2214 CharDriverState *chr;
2215 WinStdioCharState *stdio;
2216 DWORD dwMode;
2217 int is_console = 0;
2218
2219 chr = qemu_chr_alloc();
2220 stdio = g_malloc0(sizeof(WinStdioCharState));
2221
2222 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2223 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2224 fprintf(stderr, "cannot open stdio: invalid handle\n");
2225 exit(1);
2226 }
2227
2228 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2229
2230 chr->opaque = stdio;
2231 chr->chr_write = win_stdio_write;
2232 chr->chr_close = win_stdio_close;
2233
2234 if (is_console) {
2235 if (qemu_add_wait_object(stdio->hStdIn,
2236 win_stdio_wait_func, chr)) {
2237 fprintf(stderr, "qemu_add_wait_object: failed\n");
2238 }
2239 } else {
2240 DWORD dwId;
2241
2242 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2243 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2244 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2245 chr, 0, &dwId);
2246
2247 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2248 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2249 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2250 fprintf(stderr, "cannot create stdio thread or event\n");
2251 exit(1);
2252 }
2253 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2254 win_stdio_thread_wait_func, chr)) {
2255 fprintf(stderr, "qemu_add_wait_object: failed\n");
2256 }
2257 }
2258
2259 dwMode |= ENABLE_LINE_INPUT;
2260
2261 if (is_console) {
2262 /* set the terminal in raw mode */
2263 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2264 dwMode |= ENABLE_PROCESSED_INPUT;
2265 }
2266
2267 SetConsoleMode(stdio->hStdIn, dwMode);
2268
2269 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2270 qemu_chr_fe_set_echo(chr, false);
2271
2272 return chr;
2273 }
2274 #endif /* !_WIN32 */
2275
2276
2277 /***********************************************************/
2278 /* UDP Net console */
2279
2280 typedef struct {
2281 int fd;
2282 GIOChannel *chan;
2283 uint8_t buf[READ_BUF_LEN];
2284 int bufcnt;
2285 int bufptr;
2286 int max_size;
2287 } NetCharDriver;
2288
2289 /* Called with chr_write_lock held. */
2290 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2291 {
2292 NetCharDriver *s = chr->opaque;
2293 gsize bytes_written;
2294 GIOStatus status;
2295
2296 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2297 if (status == G_IO_STATUS_EOF) {
2298 return 0;
2299 } else if (status != G_IO_STATUS_NORMAL) {
2300 return -1;
2301 }
2302
2303 return bytes_written;
2304 }
2305
2306 static int udp_chr_read_poll(void *opaque)
2307 {
2308 CharDriverState *chr = opaque;
2309 NetCharDriver *s = chr->opaque;
2310
2311 s->max_size = qemu_chr_be_can_write(chr);
2312
2313 /* If there were any stray characters in the queue process them
2314 * first
2315 */
2316 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2317 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2318 s->bufptr++;
2319 s->max_size = qemu_chr_be_can_write(chr);
2320 }
2321 return s->max_size;
2322 }
2323
2324 static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2325 {
2326 CharDriverState *chr = opaque;
2327 NetCharDriver *s = chr->opaque;
2328 gsize bytes_read = 0;
2329 GIOStatus status;
2330
2331 if (s->max_size == 0) {
2332 return TRUE;
2333 }
2334 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2335 &bytes_read, NULL);
2336 s->bufcnt = bytes_read;
2337 s->bufptr = s->bufcnt;
2338 if (status != G_IO_STATUS_NORMAL) {
2339 remove_fd_in_watch(chr);
2340 return FALSE;
2341 }
2342
2343 s->bufptr = 0;
2344 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2345 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2346 s->bufptr++;
2347 s->max_size = qemu_chr_be_can_write(chr);
2348 }
2349
2350 return TRUE;
2351 }
2352
2353 static void udp_chr_update_read_handler(CharDriverState *chr)
2354 {
2355 NetCharDriver *s = chr->opaque;
2356
2357 remove_fd_in_watch(chr);
2358 if (s->chan) {
2359 chr->fd_in_tag = io_add_watch_poll(s->chan, udp_chr_read_poll,
2360 udp_chr_read, chr);
2361 }
2362 }
2363
2364 static void udp_chr_close(CharDriverState *chr)
2365 {
2366 NetCharDriver *s = chr->opaque;
2367
2368 remove_fd_in_watch(chr);
2369 if (s->chan) {
2370 g_io_channel_unref(s->chan);
2371 closesocket(s->fd);
2372 }
2373 g_free(s);
2374 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2375 }
2376
2377 static CharDriverState *qemu_chr_open_udp_fd(int fd)
2378 {
2379 CharDriverState *chr = NULL;
2380 NetCharDriver *s = NULL;
2381
2382 chr = qemu_chr_alloc();
2383 s = g_malloc0(sizeof(NetCharDriver));
2384
2385 s->fd = fd;
2386 s->chan = io_channel_from_socket(s->fd);
2387 s->bufcnt = 0;
2388 s->bufptr = 0;
2389 chr->opaque = s;
2390 chr->chr_write = udp_chr_write;
2391 chr->chr_update_read_handler = udp_chr_update_read_handler;
2392 chr->chr_close = udp_chr_close;
2393 /* be isn't opened until we get a connection */
2394 chr->explicit_be_open = true;
2395 return chr;
2396 }
2397
2398 /***********************************************************/
2399 /* TCP Net console */
2400
2401 typedef struct {
2402
2403 GIOChannel *chan, *listen_chan;
2404 guint listen_tag;
2405 int fd, listen_fd;
2406 int connected;
2407 int max_size;
2408 int do_telnetopt;
2409 int do_nodelay;
2410 int is_unix;
2411 int *read_msgfds;
2412 int read_msgfds_num;
2413 int *write_msgfds;
2414 int write_msgfds_num;
2415 } TCPCharDriver;
2416
2417 static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2418
2419 #ifndef _WIN32
2420 static int unix_send_msgfds(CharDriverState *chr, const uint8_t *buf, int len)
2421 {
2422 TCPCharDriver *s = chr->opaque;
2423 struct msghdr msgh;
2424 struct iovec iov;
2425 int r;
2426
2427 size_t fd_size = s->write_msgfds_num * sizeof(int);
2428 char control[CMSG_SPACE(fd_size)];
2429 struct cmsghdr *cmsg;
2430
2431 memset(&msgh, 0, sizeof(msgh));
2432 memset(control, 0, sizeof(control));
2433
2434 /* set the payload */
2435 iov.iov_base = (uint8_t *) buf;
2436 iov.iov_len = len;
2437
2438 msgh.msg_iov = &iov;
2439 msgh.msg_iovlen = 1;
2440
2441 msgh.msg_control = control;
2442 msgh.msg_controllen = sizeof(control);
2443
2444 cmsg = CMSG_FIRSTHDR(&msgh);
2445
2446 cmsg->cmsg_len = CMSG_LEN(fd_size);
2447 cmsg->cmsg_level = SOL_SOCKET;
2448 cmsg->cmsg_type = SCM_RIGHTS;
2449 memcpy(CMSG_DATA(cmsg), s->write_msgfds, fd_size);
2450
2451 do {
2452 r = sendmsg(s->fd, &msgh, 0);
2453 } while (r < 0 && errno == EINTR);
2454
2455 /* free the written msgfds, no matter what */
2456 if (s->write_msgfds_num) {
2457 g_free(s->write_msgfds);
2458 s->write_msgfds = 0;
2459 s->write_msgfds_num = 0;
2460 }
2461
2462 return r;
2463 }
2464 #endif
2465
2466 /* Called with chr_write_lock held. */
2467 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2468 {
2469 TCPCharDriver *s = chr->opaque;
2470 if (s->connected) {
2471 #ifndef _WIN32
2472 if (s->is_unix && s->write_msgfds_num) {
2473 return unix_send_msgfds(chr, buf, len);
2474 } else
2475 #endif
2476 {
2477 return io_channel_send(s->chan, buf, len);
2478 }
2479 } else {
2480 /* XXX: indicate an error ? */
2481 return len;
2482 }
2483 }
2484
2485 static int tcp_chr_read_poll(void *opaque)
2486 {
2487 CharDriverState *chr = opaque;
2488 TCPCharDriver *s = chr->opaque;
2489 if (!s->connected)
2490 return 0;
2491 s->max_size = qemu_chr_be_can_write(chr);
2492 return s->max_size;
2493 }
2494
2495 #define IAC 255
2496 #define IAC_BREAK 243
2497 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2498 TCPCharDriver *s,
2499 uint8_t *buf, int *size)
2500 {
2501 /* Handle any telnet client's basic IAC options to satisfy char by
2502 * char mode with no echo. All IAC options will be removed from
2503 * the buf and the do_telnetopt variable will be used to track the
2504 * state of the width of the IAC information.
2505 *
2506 * IAC commands come in sets of 3 bytes with the exception of the
2507 * "IAC BREAK" command and the double IAC.
2508 */
2509
2510 int i;
2511 int j = 0;
2512
2513 for (i = 0; i < *size; i++) {
2514 if (s->do_telnetopt > 1) {
2515 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2516 /* Double IAC means send an IAC */
2517 if (j != i)
2518 buf[j] = buf[i];
2519 j++;
2520 s->do_telnetopt = 1;
2521 } else {
2522 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2523 /* Handle IAC break commands by sending a serial break */
2524 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2525 s->do_telnetopt++;
2526 }
2527 s->do_telnetopt++;
2528 }
2529 if (s->do_telnetopt >= 4) {
2530 s->do_telnetopt = 1;
2531 }
2532 } else {
2533 if ((unsigned char)buf[i] == IAC) {
2534 s->do_telnetopt = 2;
2535 } else {
2536 if (j != i)
2537 buf[j] = buf[i];
2538 j++;
2539 }
2540 }
2541 }
2542 *size = j;
2543 }
2544
2545 static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2546 {
2547 TCPCharDriver *s = chr->opaque;
2548 int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
2549
2550 if (to_copy) {
2551 int i;
2552
2553 memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
2554
2555 /* Close unused fds */
2556 for (i = to_copy; i < s->read_msgfds_num; i++) {
2557 close(s->read_msgfds[i]);
2558 }
2559
2560 g_free(s->read_msgfds);
2561 s->read_msgfds = 0;
2562 s->read_msgfds_num = 0;
2563 }
2564
2565 return to_copy;
2566 }
2567
2568 static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
2569 {
2570 TCPCharDriver *s = chr->opaque;
2571
2572 /* clear old pending fd array */
2573 if (s->write_msgfds) {
2574 g_free(s->write_msgfds);
2575 }
2576
2577 if (num) {
2578 s->write_msgfds = g_malloc(num * sizeof(int));
2579 memcpy(s->write_msgfds, fds, num * sizeof(int));
2580 }
2581
2582 s->write_msgfds_num = num;
2583
2584 return 0;
2585 }
2586
2587 #ifndef _WIN32
2588 static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2589 {
2590 TCPCharDriver *s = chr->opaque;
2591 struct cmsghdr *cmsg;
2592
2593 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2594 int fd_size, i;
2595
2596 if (cmsg->cmsg_len < CMSG_LEN(sizeof(int)) ||
2597 cmsg->cmsg_level != SOL_SOCKET ||
2598 cmsg->cmsg_type != SCM_RIGHTS) {
2599 continue;
2600 }
2601
2602 fd_size = cmsg->cmsg_len - CMSG_LEN(0);
2603
2604 if (!fd_size) {
2605 continue;
2606 }
2607
2608 /* close and clean read_msgfds */
2609 for (i = 0; i < s->read_msgfds_num; i++) {
2610 close(s->read_msgfds[i]);
2611 }
2612
2613 if (s->read_msgfds_num) {
2614 g_free(s->read_msgfds);
2615 }
2616
2617 s->read_msgfds_num = fd_size / sizeof(int);
2618 s->read_msgfds = g_malloc(fd_size);
2619 memcpy(s->read_msgfds, CMSG_DATA(cmsg), fd_size);
2620
2621 for (i = 0; i < s->read_msgfds_num; i++) {
2622 int fd = s->read_msgfds[i];
2623 if (fd < 0) {
2624 continue;
2625 }
2626
2627 /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2628 qemu_set_block(fd);
2629
2630 #ifndef MSG_CMSG_CLOEXEC
2631 qemu_set_cloexec(fd);
2632 #endif
2633 }
2634 }
2635 }
2636
2637 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2638 {
2639 TCPCharDriver *s = chr->opaque;
2640 struct msghdr msg = { NULL, };
2641 struct iovec iov[1];
2642 union {
2643 struct cmsghdr cmsg;
2644 char control[CMSG_SPACE(sizeof(int))];
2645 } msg_control;
2646 int flags = 0;
2647 ssize_t ret;
2648
2649 iov[0].iov_base = buf;
2650 iov[0].iov_len = len;
2651
2652 msg.msg_iov = iov;
2653 msg.msg_iovlen = 1;
2654 msg.msg_control = &msg_control;
2655 msg.msg_controllen = sizeof(msg_control);
2656
2657 #ifdef MSG_CMSG_CLOEXEC
2658 flags |= MSG_CMSG_CLOEXEC;
2659 #endif
2660 ret = recvmsg(s->fd, &msg, flags);
2661 if (ret > 0 && s->is_unix) {
2662 unix_process_msgfd(chr, &msg);
2663 }
2664
2665 return ret;
2666 }
2667 #else
2668 static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2669 {
2670 TCPCharDriver *s = chr->opaque;
2671 return qemu_recv(s->fd, buf, len, 0);
2672 }
2673 #endif
2674
2675 static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2676 {
2677 TCPCharDriver *s = chr->opaque;
2678 return g_io_create_watch(s->chan, cond);
2679 }
2680
2681 static void tcp_chr_disconnect(CharDriverState *chr)
2682 {
2683 TCPCharDriver *s = chr->opaque;
2684
2685 s->connected = 0;
2686 if (s->listen_chan) {
2687 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
2688 tcp_chr_accept, chr);
2689 }
2690 remove_fd_in_watch(chr);
2691 g_io_channel_unref(s->chan);
2692 s->chan = NULL;
2693 closesocket(s->fd);
2694 s->fd = -1;
2695 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2696 }
2697
2698 static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2699 {
2700 CharDriverState *chr = opaque;
2701 TCPCharDriver *s = chr->opaque;
2702 uint8_t buf[READ_BUF_LEN];
2703 int len, size;
2704
2705 if (cond & G_IO_HUP) {
2706 /* connection closed */
2707 tcp_chr_disconnect(chr);
2708 return TRUE;
2709 }
2710
2711 if (!s->connected || s->max_size <= 0) {
2712 return TRUE;
2713 }
2714 len = sizeof(buf);
2715 if (len > s->max_size)
2716 len = s->max_size;
2717 size = tcp_chr_recv(chr, (void *)buf, len);
2718 if (size == 0) {
2719 /* connection closed */
2720 tcp_chr_disconnect(chr);
2721 } else if (size > 0) {
2722 if (s->do_telnetopt)
2723 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2724 if (size > 0)
2725 qemu_chr_be_write(chr, buf, size);
2726 }
2727
2728 return TRUE;
2729 }
2730
2731 static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
2732 {
2733 TCPCharDriver *s = chr->opaque;
2734 int size;
2735
2736 if (!s->connected) {
2737 return 0;
2738 }
2739
2740 size = tcp_chr_recv(chr, (void *) buf, len);
2741 if (size == 0) {
2742 /* connection closed */
2743 tcp_chr_disconnect(chr);
2744 }
2745
2746 return size;
2747 }
2748
2749 #ifndef _WIN32
2750 CharDriverState *qemu_chr_open_eventfd(int eventfd)
2751 {
2752 CharDriverState *chr = qemu_chr_open_fd(eventfd, eventfd);
2753
2754 if (chr) {
2755 chr->avail_connections = 1;
2756 }
2757
2758 return chr;
2759 }
2760 #endif
2761
2762 static void tcp_chr_connect(void *opaque)
2763 {
2764 CharDriverState *chr = opaque;
2765 TCPCharDriver *s = chr->opaque;
2766
2767 s->connected = 1;
2768 if (s->chan) {
2769 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2770 tcp_chr_read, chr);
2771 }
2772 qemu_chr_be_generic_open(chr);
2773 }
2774
2775 static void tcp_chr_update_read_handler(CharDriverState *chr)
2776 {
2777 TCPCharDriver *s = chr->opaque;
2778
2779 remove_fd_in_watch(chr);
2780 if (s->chan) {
2781 chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2782 tcp_chr_read, chr);
2783 }
2784 }
2785
2786 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2787 static void tcp_chr_telnet_init(int fd)
2788 {
2789 char buf[3];
2790 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2791 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2792 send(fd, (char *)buf, 3, 0);
2793 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2794 send(fd, (char *)buf, 3, 0);
2795 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2796 send(fd, (char *)buf, 3, 0);
2797 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2798 send(fd, (char *)buf, 3, 0);
2799 }
2800
2801 static int tcp_chr_add_client(CharDriverState *chr, int fd)
2802 {
2803 TCPCharDriver *s = chr->opaque;
2804 if (s->fd != -1)
2805 return -1;
2806
2807 qemu_set_nonblock(fd);
2808 if (s->do_nodelay)
2809 socket_set_nodelay(fd);
2810 s->fd = fd;
2811 s->chan = io_channel_from_socket(fd);
2812 if (s->listen_tag) {
2813 g_source_remove(s->listen_tag);
2814 s->listen_tag = 0;
2815 }
2816 tcp_chr_connect(chr);
2817
2818 return 0;
2819 }
2820
2821 static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2822 {
2823 CharDriverState *chr = opaque;
2824 TCPCharDriver *s = chr->opaque;
2825 struct sockaddr_in saddr;
2826 #ifndef _WIN32
2827 struct sockaddr_un uaddr;
2828 #endif
2829 struct sockaddr *addr;
2830 socklen_t len;
2831 int fd;
2832
2833 for(;;) {
2834 #ifndef _WIN32
2835 if (s->is_unix) {
2836 len = sizeof(uaddr);
2837 addr = (struct sockaddr *)&uaddr;
2838 } else
2839 #endif
2840 {
2841 len = sizeof(saddr);
2842 addr = (struct sockaddr *)&saddr;
2843 }
2844 fd = qemu_accept(s->listen_fd, addr, &len);
2845 if (fd < 0 && errno != EINTR) {
2846 s->listen_tag = 0;
2847 return FALSE;
2848 } else if (fd >= 0) {
2849 if (s->do_telnetopt)
2850 tcp_chr_telnet_init(fd);
2851 break;
2852 }
2853 }
2854 if (tcp_chr_add_client(chr, fd) < 0)
2855 close(fd);
2856
2857 return TRUE;
2858 }
2859
2860 static void tcp_chr_close(CharDriverState *chr)
2861 {
2862 TCPCharDriver *s = chr->opaque;
2863 int i;
2864 if (s->fd >= 0) {
2865 remove_fd_in_watch(chr);
2866 if (s->chan) {
2867 g_io_channel_unref(s->chan);
2868 }
2869 closesocket(s->fd);
2870 }
2871 if (s->listen_fd >= 0) {
2872 if (s->listen_tag) {
2873 g_source_remove(s->listen_tag);
2874 s->listen_tag = 0;
2875 }
2876 if (s->listen_chan) {
2877 g_io_channel_unref(s->listen_chan);
2878 }
2879 closesocket(s->listen_fd);
2880 }
2881 if (s->read_msgfds_num) {
2882 for (i = 0; i < s->read_msgfds_num; i++) {
2883 close(s->read_msgfds[i]);
2884 }
2885 g_free(s->read_msgfds);
2886 }
2887 if (s->write_msgfds_num) {
2888 g_free(s->write_msgfds);
2889 }
2890 g_free(s);
2891 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2892 }
2893
2894 static bool qemu_chr_finish_socket_connection(CharDriverState *chr, int fd,
2895 bool is_listen, bool is_telnet,
2896 Error **errp)
2897 {
2898 TCPCharDriver *s = chr->opaque;
2899 char host[NI_MAXHOST], serv[NI_MAXSERV];
2900 const char *left = "", *right = "";
2901 struct sockaddr_storage ss;
2902 socklen_t ss_len = sizeof(ss);
2903
2904 memset(&ss, 0, ss_len);
2905 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2906 closesocket(fd);
2907 error_setg_errno(errp, errno, "getsockname");
2908 return false;
2909 }
2910
2911 switch (ss.ss_family) {
2912 #ifndef _WIN32
2913 case AF_UNIX:
2914 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "unix:%s%s",
2915 ((struct sockaddr_un *)(&ss))->sun_path,
2916 is_listen ? ",server" : "");
2917 break;
2918 #endif
2919 case AF_INET6:
2920 left = "[";
2921 right = "]";
2922 /* fall through */
2923 case AF_INET:
2924 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2925 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2926 snprintf(chr->filename, CHR_MAX_FILENAME_SIZE, "%s:%s%s%s:%s%s",
2927 is_telnet ? "telnet" : "tcp",
2928 left, host, right, serv,
2929 is_listen ? ",server" : "");
2930 break;
2931 }
2932
2933 if (is_listen) {
2934 s->listen_fd = fd;
2935 s->listen_chan = io_channel_from_socket(s->listen_fd);
2936 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
2937 tcp_chr_accept, chr);
2938 } else {
2939 s->connected = 1;
2940 s->fd = fd;
2941 socket_set_nodelay(fd);
2942 s->chan = io_channel_from_socket(s->fd);
2943 tcp_chr_connect(chr);
2944 }
2945
2946 return true;
2947 }
2948
2949 static bool qemu_chr_open_socket_fd(CharDriverState *chr, SocketAddress *addr,
2950 bool is_listen, bool is_telnet,
2951 Error **errp)
2952 {
2953 int fd;
2954
2955 if (is_listen) {
2956 fd = socket_listen(addr, errp);
2957 } else {
2958 fd = socket_connect(addr, errp, NULL, NULL);
2959 }
2960 if (fd < 0) {
2961 return false;
2962 }
2963
2964 return qemu_chr_finish_socket_connection(chr, fd, is_listen, is_telnet,
2965 errp);
2966 }
2967
2968 /*********************************************************/
2969 /* Ring buffer chardev */
2970
2971 typedef struct {
2972 size_t size;
2973 size_t prod;
2974 size_t cons;
2975 uint8_t *cbuf;
2976 } RingBufCharDriver;
2977
2978 static size_t ringbuf_count(const CharDriverState *chr)
2979 {
2980 const RingBufCharDriver *d = chr->opaque;
2981
2982 return d->prod - d->cons;
2983 }
2984
2985 /* Called with chr_write_lock held. */
2986 static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2987 {
2988 RingBufCharDriver *d = chr->opaque;
2989 int i;
2990
2991 if (!buf || (len < 0)) {
2992 return -1;
2993 }
2994
2995 for (i = 0; i < len; i++ ) {
2996 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2997 if (d->prod - d->cons > d->size) {
2998 d->cons = d->prod - d->size;
2999 }
3000 }
3001
3002 return 0;
3003 }
3004
3005 static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3006 {
3007 RingBufCharDriver *d = chr->opaque;
3008 int i;
3009
3010 qemu_mutex_lock(&chr->chr_write_lock);
3011 for (i = 0; i < len && d->cons != d->prod; i++) {
3012 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3013 }
3014 qemu_mutex_unlock(&chr->chr_write_lock);
3015
3016 return i;
3017 }
3018
3019 static void ringbuf_chr_close(struct CharDriverState *chr)
3020 {
3021 RingBufCharDriver *d = chr->opaque;
3022
3023 g_free(d->cbuf);
3024 g_free(d);
3025 chr->opaque = NULL;
3026 }
3027
3028 static CharDriverState *qemu_chr_open_ringbuf(ChardevRingbuf *opts,
3029 Error **errp)
3030 {
3031 CharDriverState *chr;
3032 RingBufCharDriver *d;
3033
3034 chr = qemu_chr_alloc();
3035 d = g_malloc(sizeof(*d));
3036
3037 d->size = opts->has_size ? opts->size : 65536;
3038
3039 /* The size must be power of 2 */
3040 if (d->size & (d->size - 1)) {
3041 error_setg(errp, "size of ringbuf chardev must be power of two");
3042 goto fail;
3043 }
3044
3045 d->prod = 0;
3046 d->cons = 0;
3047 d->cbuf = g_malloc0(d->size);
3048
3049 chr->opaque = d;
3050 chr->chr_write = ringbuf_chr_write;
3051 chr->chr_close = ringbuf_chr_close;
3052
3053 return chr;
3054
3055 fail:
3056 g_free(d);
3057 g_free(chr);
3058 return NULL;
3059 }
3060
3061 bool chr_is_ringbuf(const CharDriverState *chr)
3062 {
3063 return chr->chr_write == ringbuf_chr_write;
3064 }
3065
3066 void qmp_ringbuf_write(const char *device, const char *data,
3067 bool has_format, enum DataFormat format,
3068 Error **errp)
3069 {
3070 CharDriverState *chr;
3071 const uint8_t *write_data;
3072 int ret;
3073 gsize write_count;
3074
3075 chr = qemu_chr_find(device);
3076 if (!chr) {
3077 error_setg(errp, "Device '%s' not found", device);
3078 return;
3079 }
3080
3081 if (!chr_is_ringbuf(chr)) {
3082 error_setg(errp,"%s is not a ringbuf device", device);
3083 return;
3084 }
3085
3086 if (has_format && (format == DATA_FORMAT_BASE64)) {
3087 write_data = g_base64_decode(data, &write_count);
3088 } else {
3089 write_data = (uint8_t *)data;
3090 write_count = strlen(data);
3091 }
3092
3093 ret = ringbuf_chr_write(chr, write_data, write_count);
3094
3095 if (write_data != (uint8_t *)data) {
3096 g_free((void *)write_data);
3097 }
3098
3099 if (ret < 0) {
3100 error_setg(errp, "Failed to write to device %s", device);
3101 return;
3102 }
3103 }
3104
3105 char *qmp_ringbuf_read(const char *device, int64_t size,
3106 bool has_format, enum DataFormat format,
3107 Error **errp)
3108 {
3109 CharDriverState *chr;
3110 uint8_t *read_data;
3111 size_t count;
3112 char *data;
3113
3114 chr = qemu_chr_find(device);
3115 if (!chr) {
3116 error_setg(errp, "Device '%s' not found", device);
3117 return NULL;
3118 }
3119
3120 if (!chr_is_ringbuf(chr)) {
3121 error_setg(errp,"%s is not a ringbuf device", device);
3122 return NULL;
3123 }
3124
3125 if (size <= 0) {
3126 error_setg(errp, "size must be greater than zero");
3127 return NULL;
3128 }
3129
3130 count = ringbuf_count(chr);
3131 size = size > count ? count : size;
3132 read_data = g_malloc(size + 1);
3133
3134 ringbuf_chr_read(chr, read_data, size);
3135
3136 if (has_format && (format == DATA_FORMAT_BASE64)) {
3137 data = g_base64_encode(read_data, size);
3138 g_free(read_data);
3139 } else {
3140 /*
3141 * FIXME should read only complete, valid UTF-8 characters up
3142 * to @size bytes. Invalid sequences should be replaced by a
3143 * suitable replacement character. Except when (and only
3144 * when) ring buffer lost characters since last read, initial
3145 * continuation characters should be dropped.
3146 */
3147 read_data[size] = 0;
3148 data = (char *)read_data;
3149 }
3150
3151 return data;
3152 }
3153
3154 QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3155 {
3156 char host[65], port[33], width[8], height[8];
3157 int pos;
3158 const char *p;
3159 QemuOpts *opts;
3160 Error *local_err = NULL;
3161
3162 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3163 if (local_err) {
3164 qerror_report_err(local_err);
3165 error_free(local_err);
3166 return NULL;
3167 }
3168
3169 if (strstart(filename, "mon:", &p)) {
3170 filename = p;
3171 qemu_opt_set(opts, "mux", "on");
3172 if (strcmp(filename, "stdio") == 0) {
3173 /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
3174 * but pass it to the guest. Handle this only for compat syntax,
3175 * for -chardev syntax we have special option for this.
3176 * This is what -nographic did, redirecting+muxing serial+monitor
3177 * to stdio causing Ctrl+C to be passed to guest. */
3178 qemu_opt_set(opts, "signal", "off");
3179 }
3180 }
3181
3182 if (strcmp(filename, "null") == 0 ||
3183 strcmp(filename, "pty") == 0 ||
3184 strcmp(filename, "msmouse") == 0 ||
3185 strcmp(filename, "braille") == 0 ||
3186 strcmp(filename, "testdev") == 0 ||
3187 strcmp(filename, "stdio") == 0) {
3188 qemu_opt_set(opts, "backend", filename);
3189 return opts;
3190 }
3191 if (strstart(filename, "vc", &p)) {
3192 qemu_opt_set(opts, "backend", "vc");
3193 if (*p == ':') {
3194 if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
3195 /* pixels */
3196 qemu_opt_set(opts, "width", width);
3197 qemu_opt_set(opts, "height", height);
3198 } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
3199 /* chars */
3200 qemu_opt_set(opts, "cols", width);
3201 qemu_opt_set(opts, "rows", height);
3202 } else {
3203 goto fail;
3204 }
3205 }
3206 return opts;
3207 }
3208 if (strcmp(filename, "con:") == 0) {
3209 qemu_opt_set(opts, "backend", "console");
3210 return opts;
3211 }
3212 if (strstart(filename, "COM", NULL)) {
3213 qemu_opt_set(opts, "backend", "serial");
3214 qemu_opt_set(opts, "path", filename);
3215 return opts;
3216 }
3217 if (strstart(filename, "file:", &p)) {
3218 qemu_opt_set(opts, "backend", "file");
3219 qemu_opt_set(opts, "path", p);
3220 return opts;
3221 }
3222 if (strstart(filename, "pipe:", &p)) {
3223 qemu_opt_set(opts, "backend", "pipe");
3224 qemu_opt_set(opts, "path", p);
3225 return opts;
3226 }
3227 if (strstart(filename, "tcp:", &p) ||
3228 strstart(filename, "telnet:", &p)) {
3229 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3230 host[0] = 0;
3231 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3232 goto fail;
3233 }
3234 qemu_opt_set(opts, "backend", "socket");
3235 qemu_opt_set(opts, "host", host);
3236 qemu_opt_set(opts, "port", port);
3237 if (p[pos] == ',') {
3238 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3239 goto fail;
3240 }
3241 if (strstart(filename, "telnet:", &p))
3242 qemu_opt_set(opts, "telnet", "on");
3243 return opts;
3244 }
3245 if (strstart(filename, "udp:", &p)) {
3246 qemu_opt_set(opts, "backend", "udp");
3247 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3248 host[0] = 0;
3249 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3250 goto fail;
3251 }
3252 }
3253 qemu_opt_set(opts, "host", host);
3254 qemu_opt_set(opts, "port", port);
3255 if (p[pos] == '@') {
3256 p += pos + 1;
3257 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3258 host[0] = 0;
3259 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3260 goto fail;
3261 }
3262 }
3263 qemu_opt_set(opts, "localaddr", host);
3264 qemu_opt_set(opts, "localport", port);
3265 }
3266 return opts;
3267 }
3268 if (strstart(filename, "unix:", &p)) {
3269 qemu_opt_set(opts, "backend", "socket");
3270 if (qemu_opts_do_parse(opts, p, "path") != 0)
3271 goto fail;
3272 return opts;
3273 }
3274 if (strstart(filename, "/dev/parport", NULL) ||
3275 strstart(filename, "/dev/ppi", NULL)) {
3276 qemu_opt_set(opts, "backend", "parport");
3277 qemu_opt_set(opts, "path", filename);
3278 return opts;
3279 }
3280 if (strstart(filename, "/dev/", NULL)) {
3281 qemu_opt_set(opts, "backend", "tty");
3282 qemu_opt_set(opts, "path", filename);
3283 return opts;
3284 }
3285
3286 fail:
3287 qemu_opts_del(opts);
3288 return NULL;
3289 }
3290
3291 static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3292 Error **errp)
3293 {
3294 const char *path = qemu_opt_get(opts, "path");
3295
3296 if (path == NULL) {
3297 error_setg(errp, "chardev: file: no filename given");
3298 return;
3299 }
3300 backend->file = g_new0(ChardevFile, 1);
3301 backend->file->out = g_strdup(path);
3302 }
3303
3304 static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3305 Error **errp)
3306 {
3307 backend->stdio = g_new0(ChardevStdio, 1);
3308 backend->stdio->has_signal = true;
3309 backend->stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3310 }
3311
3312 static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3313 Error **errp)
3314 {
3315 const char *device = qemu_opt_get(opts, "path");
3316
3317 if (device == NULL) {
3318 error_setg(errp, "chardev: serial/tty: no device path given");
3319 return;
3320 }
3321 backend->serial = g_new0(ChardevHostdev, 1);
3322 backend->serial->device = g_strdup(device);
3323 }
3324
3325 static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3326 Error **errp)
3327 {
3328 const char *device = qemu_opt_get(opts, "path");
3329
3330 if (device == NULL) {
3331 error_setg(errp, "chardev: parallel: no device path given");
3332 return;
3333 }
3334 backend->parallel = g_new0(ChardevHostdev, 1);
3335 backend->parallel->device = g_strdup(device);
3336 }
3337
3338 static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3339 Error **errp)
3340 {
3341 const char *device = qemu_opt_get(opts, "path");
3342
3343 if (device == NULL) {
3344 error_setg(errp, "chardev: pipe: no device path given");
3345 return;
3346 }
3347 backend->pipe = g_new0(ChardevHostdev, 1);
3348 backend->pipe->device = g_strdup(device);
3349 }
3350
3351 static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3352 Error **errp)
3353 {
3354 int val;
3355
3356 backend->ringbuf = g_new0(ChardevRingbuf, 1);
3357
3358 val = qemu_opt_get_size(opts, "size", 0);
3359 if (val != 0) {
3360 backend->ringbuf->has_size = true;
3361 backend->ringbuf->size = val;
3362 }
3363 }
3364
3365 static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3366 Error **errp)
3367 {
3368 const char *chardev = qemu_opt_get(opts, "chardev");
3369
3370 if (chardev == NULL) {
3371 error_setg(errp, "chardev: mux: no chardev given");
3372 return;
3373 }
3374 backend->mux = g_new0(ChardevMux, 1);
3375 backend->mux->chardev = g_strdup(chardev);
3376 }
3377
3378 static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,
3379 Error **errp)
3380 {
3381 bool is_listen = qemu_opt_get_bool(opts, "server", false);
3382 bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
3383 bool is_telnet = qemu_opt_get_bool(opts, "telnet", false);
3384 bool do_nodelay = !qemu_opt_get_bool(opts, "delay", true);
3385 const char *path = qemu_opt_get(opts, "path");
3386 const char *host = qemu_opt_get(opts, "host");
3387 const char *port = qemu_opt_get(opts, "port");
3388 SocketAddress *addr;
3389
3390 if (!path) {
3391 if (!host) {
3392 error_setg(errp, "chardev: socket: no host given");
3393 return;
3394 }
3395 if (!port) {
3396 error_setg(errp, "chardev: socket: no port given");
3397 return;
3398 }
3399 }
3400
3401 backend->socket = g_new0(ChardevSocket, 1);
3402
3403 backend->socket->has_nodelay = true;
3404 backend->socket->nodelay = do_nodelay;
3405 backend->socket->has_server = true;
3406 backend->socket->server = is_listen;
3407 backend->socket->has_telnet = true;
3408 backend->socket->telnet = is_telnet;
3409 backend->socket->has_wait = true;
3410 backend->socket->wait = is_waitconnect;
3411
3412 addr = g_new0(SocketAddress, 1);
3413 if (path) {
3414 addr->kind = SOCKET_ADDRESS_KIND_UNIX;
3415 addr->q_unix = g_new0(UnixSocketAddress, 1);
3416 addr->q_unix->path = g_strdup(path);
3417 } else {
3418 addr->kind = SOCKET_ADDRESS_KIND_INET;
3419 addr->inet = g_new0(InetSocketAddress, 1);
3420 addr->inet->host = g_strdup(host);
3421 addr->inet->port = g_strdup(port);
3422 addr->inet->has_to = qemu_opt_get(opts, "to");
3423 addr->inet->to = qemu_opt_get_number(opts, "to", 0);
3424 addr->inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3425 addr->inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3426 addr->inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3427 addr->inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3428 }
3429 backend->socket->addr = addr;
3430 }
3431
3432 static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,
3433 Error **errp)
3434 {
3435 const char *host = qemu_opt_get(opts, "host");
3436 const char *port = qemu_opt_get(opts, "port");
3437 const char *localaddr = qemu_opt_get(opts, "localaddr");
3438 const char *localport = qemu_opt_get(opts, "localport");
3439 bool has_local = false;
3440 SocketAddress *addr;
3441
3442 if (host == NULL || strlen(host) == 0) {
3443 host = "localhost";
3444 }
3445 if (port == NULL || strlen(port) == 0) {
3446 error_setg(errp, "chardev: udp: remote port not specified");
3447 return;
3448 }
3449 if (localport == NULL || strlen(localport) == 0) {
3450 localport = "0";
3451 } else {
3452 has_local = true;
3453 }
3454 if (localaddr == NULL || strlen(localaddr) == 0) {
3455 localaddr = "";
3456 } else {
3457 has_local = true;
3458 }
3459
3460 backend->udp = g_new0(ChardevUdp, 1);
3461
3462 addr = g_new0(SocketAddress, 1);
3463 addr->kind = SOCKET_ADDRESS_KIND_INET;
3464 addr->inet = g_new0(InetSocketAddress, 1);
3465 addr->inet->host = g_strdup(host);
3466 addr->inet->port = g_strdup(port);
3467 addr->inet->has_ipv4 = qemu_opt_get(opts, "ipv4");
3468 addr->inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);
3469 addr->inet->has_ipv6 = qemu_opt_get(opts, "ipv6");
3470 addr->inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);
3471 backend->udp->remote = addr;
3472
3473 if (has_local) {
3474 backend->udp->has_local = true;
3475 addr = g_new0(SocketAddress, 1);
3476 addr->kind = SOCKET_ADDRESS_KIND_INET;
3477 addr->inet = g_new0(InetSocketAddress, 1);
3478 addr->inet->host = g_strdup(localaddr);
3479 addr->inet->port = g_strdup(localport);
3480 backend->udp->local = addr;
3481 }
3482 }
3483
3484 typedef struct CharDriver {
3485 const char *name;
3486 ChardevBackendKind kind;
3487 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3488 } CharDriver;
3489
3490 static GSList *backends;
3491
3492 void register_char_driver(const char *name, ChardevBackendKind kind,
3493 void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3494 {
3495 CharDriver *s;
3496
3497 s = g_malloc0(sizeof(*s));
3498 s->name = g_strdup(name);
3499 s->kind = kind;
3500 s->parse = parse;
3501
3502 backends = g_slist_append(backends, s);
3503 }
3504
3505 CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3506 void (*init)(struct CharDriverState *s),
3507 Error **errp)
3508 {
3509 Error *local_err = NULL;
3510 CharDriver *cd;
3511 CharDriverState *chr;
3512 GSList *i;
3513 ChardevReturn *ret = NULL;
3514 ChardevBackend *backend;
3515 const char *id = qemu_opts_id(opts);
3516 char *bid = NULL;
3517
3518 if (id == NULL) {
3519 error_setg(errp, "chardev: no id specified");
3520 goto err;
3521 }
3522
3523 if (qemu_opt_get(opts, "backend") == NULL) {
3524 error_setg(errp, "chardev: \"%s\" missing backend",
3525 qemu_opts_id(opts));
3526 goto err;
3527 }
3528 for (i = backends; i; i = i->next) {
3529 cd = i->data;
3530
3531 if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3532 break;
3533 }
3534 }
3535 if (i == NULL) {
3536 error_setg(errp, "chardev: backend \"%s\" not found",
3537 qemu_opt_get(opts, "backend"));
3538 goto err;
3539 }
3540
3541 backend = g_new0(ChardevBackend, 1);
3542
3543 if (qemu_opt_get_bool(opts, "mux", 0)) {
3544 bid = g_strdup_printf("%s-base", id);
3545 }
3546
3547 chr = NULL;
3548 backend->kind = cd->kind;
3549 if (cd->parse) {
3550 cd->parse(opts, backend, &local_err);
3551 if (local_err) {
3552 error_propagate(errp, local_err);
3553 goto qapi_out;
3554 }
3555 }
3556 ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3557 if (!ret) {
3558 goto qapi_out;
3559 }
3560
3561 if (bid) {
3562 qapi_free_ChardevBackend(backend);
3563 qapi_free_ChardevReturn(ret);
3564 backend = g_new0(ChardevBackend, 1);
3565 backend->mux = g_new0(ChardevMux, 1);
3566 backend->kind = CHARDEV_BACKEND_KIND_MUX;
3567 backend->mux->chardev = g_strdup(bid);
3568 ret = qmp_chardev_add(id, backend, errp);
3569 if (!ret) {
3570 chr = qemu_chr_find(bid);
3571 qemu_chr_delete(chr);
3572 chr = NULL;
3573 goto qapi_out;
3574 }
3575 }
3576
3577 chr = qemu_chr_find(id);
3578 chr->opts = opts;
3579
3580 qapi_out:
3581 qapi_free_ChardevBackend(backend);
3582 qapi_free_ChardevReturn(ret);
3583 g_free(bid);
3584 return chr;
3585
3586 err:
3587 qemu_opts_del(opts);
3588 return NULL;
3589 }
3590
3591 CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3592 {
3593 const char *p;
3594 CharDriverState *chr;
3595 QemuOpts *opts;
3596 Error *err = NULL;
3597
3598 if (strstart(filename, "chardev:", &p)) {
3599 return qemu_chr_find(p);
3600 }
3601
3602 opts = qemu_chr_parse_compat(label, filename);
3603 if (!opts)
3604 return NULL;
3605
3606 chr = qemu_chr_new_from_opts(opts, init, &err);
3607 if (err) {
3608 error_report("%s", error_get_pretty(err));
3609 error_free(err);
3610 }
3611 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3612 qemu_chr_fe_claim_no_fail(chr);
3613 monitor_init(chr, MONITOR_USE_READLINE);
3614 }
3615 return chr;
3616 }
3617
3618 void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3619 {
3620 if (chr->chr_set_echo) {
3621 chr->chr_set_echo(chr, echo);
3622 }
3623 }
3624
3625 void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3626 {
3627 if (chr->fe_open == fe_open) {
3628 return;
3629 }
3630 chr->fe_open = fe_open;
3631 if (chr->chr_set_fe_open) {
3632 chr->chr_set_fe_open(chr, fe_open);
3633 }
3634 }
3635
3636 void qemu_chr_fe_event(struct CharDriverState *chr, int event)
3637 {
3638 if (chr->chr_fe_event) {
3639 chr->chr_fe_event(chr, event);
3640 }
3641 }
3642
3643 int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3644 GIOFunc func, void *user_data)
3645 {
3646 GSource *src;
3647 guint tag;
3648
3649 if (s->chr_add_watch == NULL) {
3650 return -ENOSYS;
3651 }
3652
3653 src = s->chr_add_watch(s, cond);
3654 if (!src) {
3655 return -EINVAL;
3656 }
3657
3658 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3659 tag = g_source_attach(src, NULL);
3660 g_source_unref(src);
3661
3662 return tag;
3663 }
3664
3665 int qemu_chr_fe_claim(CharDriverState *s)
3666 {
3667 if (s->avail_connections < 1) {
3668 return -1;
3669 }
3670 s->avail_connections--;
3671 return 0;
3672 }
3673
3674 void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3675 {
3676 if (qemu_chr_fe_claim(s) != 0) {
3677 fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3678 __func__, s->label);
3679 exit(1);
3680 }
3681 }
3682
3683 void qemu_chr_fe_release(CharDriverState *s)
3684 {
3685 s->avail_connections++;
3686 }
3687
3688 void qemu_chr_delete(CharDriverState *chr)
3689 {
3690 QTAILQ_REMOVE(&chardevs, chr, next);
3691 if (chr->chr_close) {
3692 chr->chr_close(chr);
3693 }
3694 g_free(chr->filename);
3695 g_free(chr->label);
3696 if (chr->opts) {
3697 qemu_opts_del(chr->opts);
3698 }
3699 g_free(chr);
3700 }
3701
3702 ChardevInfoList *qmp_query_chardev(Error **errp)
3703 {
3704 ChardevInfoList *chr_list = NULL;
3705 CharDriverState *chr;
3706
3707 QTAILQ_FOREACH(chr, &chardevs, next) {
3708 ChardevInfoList *info = g_malloc0(sizeof(*info));
3709 info->value = g_malloc0(sizeof(*info->value));
3710 info->value->label = g_strdup(chr->label);
3711 info->value->filename = g_strdup(chr->filename);
3712 info->value->frontend_open = chr->fe_open;
3713
3714 info->next = chr_list;
3715 chr_list = info;
3716 }
3717
3718 return chr_list;
3719 }
3720
3721 ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
3722 {
3723 ChardevBackendInfoList *backend_list = NULL;
3724 CharDriver *c = NULL;
3725 GSList *i = NULL;
3726
3727 for (i = backends; i; i = i->next) {
3728 ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
3729 c = i->data;
3730 info->value = g_malloc0(sizeof(*info->value));
3731 info->value->name = g_strdup(c->name);
3732
3733 info->next = backend_list;
3734 backend_list = info;
3735 }
3736
3737 return backend_list;
3738 }
3739
3740 CharDriverState *qemu_chr_find(const char *name)
3741 {
3742 CharDriverState *chr;
3743
3744 QTAILQ_FOREACH(chr, &chardevs, next) {
3745 if (strcmp(chr->label, name) != 0)
3746 continue;
3747 return chr;
3748 }
3749 return NULL;
3750 }
3751
3752 /* Get a character (serial) device interface. */
3753 CharDriverState *qemu_char_get_next_serial(void)
3754 {
3755 static int next_serial;
3756 CharDriverState *chr;
3757
3758 /* FIXME: This function needs to go away: use chardev properties! */
3759
3760 while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3761 chr = serial_hds[next_serial++];
3762 qemu_chr_fe_claim_no_fail(chr);
3763 return chr;
3764 }
3765 return NULL;
3766 }
3767
3768 QemuOptsList qemu_chardev_opts = {
3769 .name = "chardev",
3770 .implied_opt_name = "backend",
3771 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3772 .desc = {
3773 {
3774 .name = "backend",
3775 .type = QEMU_OPT_STRING,
3776 },{
3777 .name = "path",
3778 .type = QEMU_OPT_STRING,
3779 },{
3780 .name = "host",
3781 .type = QEMU_OPT_STRING,
3782 },{
3783 .name = "port",
3784 .type = QEMU_OPT_STRING,
3785 },{
3786 .name = "localaddr",
3787 .type = QEMU_OPT_STRING,
3788 },{
3789 .name = "localport",
3790 .type = QEMU_OPT_STRING,
3791 },{
3792 .name = "to",
3793 .type = QEMU_OPT_NUMBER,
3794 },{
3795 .name = "ipv4",
3796 .type = QEMU_OPT_BOOL,
3797 },{
3798 .name = "ipv6",
3799 .type = QEMU_OPT_BOOL,
3800 },{
3801 .name = "wait",
3802 .type = QEMU_OPT_BOOL,
3803 },{
3804 .name = "server",
3805 .type = QEMU_OPT_BOOL,
3806 },{
3807 .name = "delay",
3808 .type = QEMU_OPT_BOOL,
3809 },{
3810 .name = "telnet",
3811 .type = QEMU_OPT_BOOL,
3812 },{
3813 .name = "width",
3814 .type = QEMU_OPT_NUMBER,
3815 },{
3816 .name = "height",
3817 .type = QEMU_OPT_NUMBER,
3818 },{
3819 .name = "cols",
3820 .type = QEMU_OPT_NUMBER,
3821 },{
3822 .name = "rows",
3823 .type = QEMU_OPT_NUMBER,
3824 },{
3825 .name = "mux",
3826 .type = QEMU_OPT_BOOL,
3827 },{
3828 .name = "signal",
3829 .type = QEMU_OPT_BOOL,
3830 },{
3831 .name = "name",
3832 .type = QEMU_OPT_STRING,
3833 },{
3834 .name = "debug",
3835 .type = QEMU_OPT_NUMBER,
3836 },{
3837 .name = "size",
3838 .type = QEMU_OPT_SIZE,
3839 },{
3840 .name = "chardev",
3841 .type = QEMU_OPT_STRING,
3842 },
3843 { /* end of list */ }
3844 },
3845 };
3846
3847 #ifdef _WIN32
3848
3849 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3850 {
3851 HANDLE out;
3852
3853 if (file->has_in) {
3854 error_setg(errp, "input file not supported");
3855 return NULL;
3856 }
3857
3858 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3859 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3860 if (out == INVALID_HANDLE_VALUE) {
3861 error_setg(errp, "open %s failed", file->out);
3862 return NULL;
3863 }
3864 return qemu_chr_open_win_file(out);
3865 }
3866
3867 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3868 Error **errp)
3869 {
3870 return qemu_chr_open_win_path(serial->device);
3871 }
3872
3873 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3874 Error **errp)
3875 {
3876 error_setg(errp, "character device backend type 'parallel' not supported");
3877 return NULL;
3878 }
3879
3880 #else /* WIN32 */
3881
3882 static int qmp_chardev_open_file_source(char *src, int flags,
3883 Error **errp)
3884 {
3885 int fd = -1;
3886
3887 TFR(fd = qemu_open(src, flags, 0666));
3888 if (fd == -1) {
3889 error_setg_file_open(errp, errno, src);
3890 }
3891 return fd;
3892 }
3893
3894 static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3895 {
3896 int flags, in = -1, out;
3897
3898 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3899 out = qmp_chardev_open_file_source(file->out, flags, errp);
3900 if (out < 0) {
3901 return NULL;
3902 }
3903
3904 if (file->has_in) {
3905 flags = O_RDONLY;
3906 in = qmp_chardev_open_file_source(file->in, flags, errp);
3907 if (in < 0) {
3908 qemu_close(out);
3909 return NULL;
3910 }
3911 }
3912
3913 return qemu_chr_open_fd(in, out);
3914 }
3915
3916 static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3917 Error **errp)
3918 {
3919 #ifdef HAVE_CHARDEV_TTY
3920 int fd;
3921
3922 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3923 if (fd < 0) {
3924 return NULL;
3925 }
3926 qemu_set_nonblock(fd);
3927 return qemu_chr_open_tty_fd(fd);
3928 #else
3929 error_setg(errp, "character device backend type 'serial' not supported");
3930 return NULL;
3931 #endif
3932 }
3933
3934 static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3935 Error **errp)
3936 {
3937 #ifdef HAVE_CHARDEV_PARPORT
3938 int fd;
3939
3940 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3941 if (fd < 0) {
3942 return NULL;
3943 }
3944 return qemu_chr_open_pp_fd(fd);
3945 #else
3946 error_setg(errp, "character device backend type 'parallel' not supported");
3947 return NULL;
3948 #endif
3949 }
3950
3951 #endif /* WIN32 */
3952
3953 static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3954 Error **errp)
3955 {
3956 CharDriverState *chr;
3957 TCPCharDriver *s;
3958 SocketAddress *addr = sock->addr;
3959 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3960 bool is_listen = sock->has_server ? sock->server : true;
3961 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3962 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3963
3964 chr = qemu_chr_alloc();
3965 s = g_malloc0(sizeof(TCPCharDriver));
3966
3967 s->fd = -1;
3968 s->listen_fd = -1;
3969 s->is_unix = addr->kind == SOCKET_ADDRESS_KIND_UNIX;
3970 s->do_nodelay = do_nodelay;
3971
3972 chr->opaque = s;
3973 chr->chr_write = tcp_chr_write;
3974 chr->chr_sync_read = tcp_chr_sync_read;
3975 chr->chr_close = tcp_chr_close;
3976 chr->get_msgfds = tcp_get_msgfds;
3977 chr->set_msgfds = tcp_set_msgfds;
3978 chr->chr_add_client = tcp_chr_add_client;
3979 chr->chr_add_watch = tcp_chr_add_watch;
3980 chr->chr_update_read_handler = tcp_chr_update_read_handler;
3981 /* be isn't opened until we get a connection */
3982 chr->explicit_be_open = true;
3983
3984 chr->filename = g_malloc(CHR_MAX_FILENAME_SIZE);
3985
3986 if (is_listen) {
3987 if (is_telnet) {
3988 s->do_telnetopt = 1;
3989 }
3990 }
3991
3992 if (!qemu_chr_open_socket_fd(chr, addr, is_listen, is_telnet, errp)) {
3993 g_free(s);
3994 g_free(chr->filename);
3995 g_free(chr);
3996 return NULL;
3997 }
3998
3999 if (is_listen && is_waitconnect) {
4000 fprintf(stderr, "QEMU waiting for connection on: %s\n",
4001 chr->filename);
4002 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
4003 qemu_set_nonblock(s->listen_fd);
4004 }
4005
4006 return chr;
4007 }
4008
4009 static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
4010 Error **errp)
4011 {
4012 int fd;
4013
4014 fd = socket_dgram(udp->remote, udp->local, errp);
4015 if (fd < 0) {
4016 return NULL;
4017 }
4018 return qemu_chr_open_udp_fd(fd);
4019 }
4020
4021 ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
4022 Error **errp)
4023 {
4024 ChardevReturn *ret = g_new0(ChardevReturn, 1);
4025 CharDriverState *base, *chr = NULL;
4026
4027 chr = qemu_chr_find(id);
4028 if (chr) {
4029 error_setg(errp, "Chardev '%s' already exists", id);
4030 g_free(ret);
4031 return NULL;
4032 }
4033
4034 switch (backend->kind) {
4035 case CHARDEV_BACKEND_KIND_FILE:
4036 chr = qmp_chardev_open_file(backend->file, errp);
4037 break;
4038 case CHARDEV_BACKEND_KIND_SERIAL:
4039 chr = qmp_chardev_open_serial(backend->serial, errp);
4040 break;
4041 case CHARDEV_BACKEND_KIND_PARALLEL:
4042 chr = qmp_chardev_open_parallel(backend->parallel, errp);
4043 break;
4044 case CHARDEV_BACKEND_KIND_PIPE:
4045 chr = qemu_chr_open_pipe(backend->pipe);
4046 break;
4047 case CHARDEV_BACKEND_KIND_SOCKET:
4048 chr = qmp_chardev_open_socket(backend->socket, errp);
4049 break;
4050 case CHARDEV_BACKEND_KIND_UDP:
4051 chr = qmp_chardev_open_udp(backend->udp, errp);
4052 break;
4053 #ifdef HAVE_CHARDEV_TTY
4054 case CHARDEV_BACKEND_KIND_PTY:
4055 chr = qemu_chr_open_pty(id, ret);
4056 break;
4057 #endif
4058 case CHARDEV_BACKEND_KIND_NULL:
4059 chr = qemu_chr_open_null();
4060 break;
4061 case CHARDEV_BACKEND_KIND_MUX:
4062 base = qemu_chr_find(backend->mux->chardev);
4063 if (base == NULL) {
4064 error_setg(errp, "mux: base chardev %s not found",
4065 backend->mux->chardev);
4066 break;
4067 }
4068 chr = qemu_chr_open_mux(base);
4069 break;
4070 case CHARDEV_BACKEND_KIND_MSMOUSE:
4071 chr = qemu_chr_open_msmouse();
4072 break;
4073 #ifdef CONFIG_BRLAPI
4074 case CHARDEV_BACKEND_KIND_BRAILLE:
4075 chr = chr_baum_init();
4076 break;
4077 #endif
4078 case CHARDEV_BACKEND_KIND_TESTDEV:
4079 chr = chr_testdev_init();
4080 break;
4081 case CHARDEV_BACKEND_KIND_STDIO:
4082 chr = qemu_chr_open_stdio(backend->stdio);
4083 break;
4084 #ifdef _WIN32
4085 case CHARDEV_BACKEND_KIND_CONSOLE:
4086 chr = qemu_chr_open_win_con();
4087 break;
4088 #endif
4089 #ifdef CONFIG_SPICE
4090 case CHARDEV_BACKEND_KIND_SPICEVMC:
4091 chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
4092 break;
4093 case CHARDEV_BACKEND_KIND_SPICEPORT:
4094 chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
4095 break;
4096 #endif
4097 case CHARDEV_BACKEND_KIND_VC:
4098 chr = vc_init(backend->vc);
4099 break;
4100 case CHARDEV_BACKEND_KIND_RINGBUF:
4101 case CHARDEV_BACKEND_KIND_MEMORY:
4102 chr = qemu_chr_open_ringbuf(backend->ringbuf, errp);
4103 break;
4104 default:
4105 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
4106 break;
4107 }
4108
4109 /*
4110 * Character backend open hasn't been fully converted to the Error
4111 * API. Some opens fail without setting an error. Set a generic
4112 * error then.
4113 * TODO full conversion to Error API
4114 */
4115 if (chr == NULL && errp && !*errp) {
4116 error_setg(errp, "Failed to create chardev");
4117 }
4118 if (chr) {
4119 chr->label = g_strdup(id);
4120 chr->avail_connections =
4121 (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4122 if (!chr->filename) {
4123 chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
4124 }
4125 if (!chr->explicit_be_open) {
4126 qemu_chr_be_event(chr, CHR_EVENT_OPENED);
4127 }
4128 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
4129 return ret;
4130 } else {
4131 g_free(ret);
4132 return NULL;
4133 }
4134 }
4135
4136 void qmp_chardev_remove(const char *id, Error **errp)
4137 {
4138 CharDriverState *chr;
4139
4140 chr = qemu_chr_find(id);
4141 if (chr == NULL) {
4142 error_setg(errp, "Chardev '%s' not found", id);
4143 return;
4144 }
4145 if (chr->chr_can_read || chr->chr_read ||
4146 chr->chr_event || chr->handler_opaque) {
4147 error_setg(errp, "Chardev '%s' is busy", id);
4148 return;
4149 }
4150 qemu_chr_delete(chr);
4151 }
4152
4153 static void register_types(void)
4154 {
4155 register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL);
4156 register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,
4157 qemu_chr_parse_socket);
4158 register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp);
4159 register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4160 qemu_chr_parse_ringbuf);
4161 register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,
4162 qemu_chr_parse_file_out);
4163 register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,
4164 qemu_chr_parse_stdio);
4165 register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,
4166 qemu_chr_parse_serial);
4167 register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,
4168 qemu_chr_parse_serial);
4169 register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
4170 qemu_chr_parse_parallel);
4171 register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,
4172 qemu_chr_parse_parallel);
4173 register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
4174 register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
4175 register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,
4176 qemu_chr_parse_pipe);
4177 register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux);
4178 /* Bug-compatibility: */
4179 register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,
4180 qemu_chr_parse_ringbuf);
4181 /* this must be done after machine init, since we register FEs with muxes
4182 * as part of realize functions like serial_isa_realizefn when -nographic
4183 * is specified
4184 */
4185 qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4186 }
4187
4188 type_init(register_types);