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