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