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