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