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