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