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