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