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