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