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