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