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