]> git.proxmox.com Git - qemu.git/blame - qemu-char.c
qemu-char: use a glib timeout instead of qemu-timer
[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
76a9644b
AL
657static GIOChannel *io_channel_from_socket(int fd)
658{
659 GIOChannel *chan;
660
661 if (fd == -1) {
662 return NULL;
663 }
664
665#ifdef _WIN32
666 chan = g_io_channel_win32_new_socket(fd);
667#else
668 chan = g_io_channel_unix_new(fd);
669#endif
670
671 g_io_channel_set_encoding(chan, NULL, NULL);
672 g_io_channel_set_buffered(chan, FALSE);
673
674 return chan;
675}
676
96c63847
AL
677static int io_channel_send_all(GIOChannel *fd, const void *_buf, int len1)
678{
679 GIOStatus status;
680 gsize bytes_written;
681 int len;
682 const uint8_t *buf = _buf;
683
684 len = len1;
685 while (len > 0) {
686 status = g_io_channel_write_chars(fd, (const gchar *)buf, len,
687 &bytes_written, NULL);
688 if (status != G_IO_STATUS_NORMAL) {
23673ca7
AL
689 if (status == G_IO_STATUS_AGAIN) {
690 errno = EAGAIN;
691 return -1;
692 } else {
693 errno = EINVAL;
96c63847
AL
694 return -1;
695 }
696 } else if (status == G_IO_STATUS_EOF) {
697 break;
698 } else {
699 buf += bytes_written;
700 len -= bytes_written;
701 }
702 }
703 return len1 - len;
704}
96c63847 705
a29753f8
AL
706typedef struct FDCharDriver {
707 CharDriverState *chr;
708 GIOChannel *fd_in, *fd_out;
709 guint fd_in_tag;
6f97dba0 710 int max_size;
a29753f8 711 QTAILQ_ENTRY(FDCharDriver) node;
6f97dba0
AL
712} FDCharDriver;
713
6f97dba0
AL
714static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
715{
716 FDCharDriver *s = chr->opaque;
a29753f8
AL
717
718 return io_channel_send_all(s->fd_out, buf, len);
6f97dba0
AL
719}
720
a29753f8 721static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
6f97dba0
AL
722{
723 CharDriverState *chr = opaque;
724 FDCharDriver *s = chr->opaque;
a29753f8 725 int len;
9bd7854e 726 uint8_t buf[READ_BUF_LEN];
a29753f8
AL
727 GIOStatus status;
728 gsize bytes_read;
6f97dba0
AL
729
730 len = sizeof(buf);
a29753f8 731 if (len > s->max_size) {
6f97dba0 732 len = s->max_size;
a29753f8
AL
733 }
734 if (len == 0) {
735 return FALSE;
736 }
737
738 status = g_io_channel_read_chars(chan, (gchar *)buf,
739 len, &bytes_read, NULL);
740 if (status == G_IO_STATUS_EOF) {
a425d23f 741 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
a29753f8 742 return FALSE;
6f97dba0 743 }
a29753f8
AL
744 if (status == G_IO_STATUS_NORMAL) {
745 qemu_chr_be_write(chr, buf, bytes_read);
6f97dba0 746 }
a29753f8
AL
747
748 return TRUE;
749}
750
751static int fd_chr_read_poll(void *opaque)
752{
753 CharDriverState *chr = opaque;
754 FDCharDriver *s = chr->opaque;
755
756 s->max_size = qemu_chr_be_can_write(chr);
757 return s->max_size;
6f97dba0
AL
758}
759
23673ca7
AL
760static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
761{
762 FDCharDriver *s = chr->opaque;
763 return g_io_create_watch(s->fd_out, cond);
764}
765
6f97dba0
AL
766static void fd_chr_update_read_handler(CharDriverState *chr)
767{
768 FDCharDriver *s = chr->opaque;
769
a29753f8
AL
770 if (s->fd_in_tag) {
771 g_source_remove(s->fd_in_tag);
772 }
773
774 if (s->fd_in) {
775 s->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll, fd_chr_read, chr);
6f97dba0
AL
776 }
777}
778
779static void fd_chr_close(struct CharDriverState *chr)
780{
781 FDCharDriver *s = chr->opaque;
782
a29753f8
AL
783 if (s->fd_in_tag) {
784 g_source_remove(s->fd_in_tag);
785 s->fd_in_tag = 0;
786 }
787
788 if (s->fd_in) {
789 g_io_channel_unref(s->fd_in);
790 }
791 if (s->fd_out) {
792 g_io_channel_unref(s->fd_out);
6f97dba0
AL
793 }
794
7267c094 795 g_free(s);
a425d23f 796 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
6f97dba0
AL
797}
798
799/* open a character device to a unix fd */
800static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
801{
802 CharDriverState *chr;
803 FDCharDriver *s;
804
7267c094
AL
805 chr = g_malloc0(sizeof(CharDriverState));
806 s = g_malloc0(sizeof(FDCharDriver));
a29753f8
AL
807 s->fd_in = io_channel_from_fd(fd_in);
808 s->fd_out = io_channel_from_fd(fd_out);
23673ca7 809 fcntl(fd_out, F_SETFL, O_NONBLOCK);
a29753f8 810 s->chr = chr;
6f97dba0 811 chr->opaque = s;
23673ca7 812 chr->chr_add_watch = fd_chr_add_watch;
6f97dba0
AL
813 chr->chr_write = fd_chr_write;
814 chr->chr_update_read_handler = fd_chr_update_read_handler;
815 chr->chr_close = fd_chr_close;
816
127338e6 817 qemu_chr_generic_open(chr);
6f97dba0
AL
818
819 return chr;
820}
821
1f51470d 822static CharDriverState *qemu_chr_open_file_out(QemuOpts *opts)
6f97dba0
AL
823{
824 int fd_out;
825
40ff6d7e 826 TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
7d31544f 827 O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
a89dd6c3 828 if (fd_out < 0) {
1f51470d 829 return NULL;
a89dd6c3 830 }
1f51470d 831 return qemu_chr_open_fd(-1, fd_out);
6f97dba0
AL
832}
833
1f51470d 834static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)
6f97dba0
AL
835{
836 int fd_in, fd_out;
837 char filename_in[256], filename_out[256];
7d31544f
GH
838 const char *filename = qemu_opt_get(opts, "path");
839
840 if (filename == NULL) {
841 fprintf(stderr, "chardev: pipe: no filename given\n");
1f51470d 842 return NULL;
7d31544f 843 }
6f97dba0
AL
844
845 snprintf(filename_in, 256, "%s.in", filename);
846 snprintf(filename_out, 256, "%s.out", filename);
40ff6d7e
KW
847 TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
848 TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
6f97dba0
AL
849 if (fd_in < 0 || fd_out < 0) {
850 if (fd_in >= 0)
851 close(fd_in);
852 if (fd_out >= 0)
853 close(fd_out);
b181e047 854 TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
a89dd6c3 855 if (fd_in < 0) {
1f51470d 856 return NULL;
a89dd6c3 857 }
6f97dba0 858 }
1f51470d 859 return qemu_chr_open_fd(fd_in, fd_out);
6f97dba0
AL
860}
861
6f97dba0
AL
862/* init terminal so that we can grab keys */
863static struct termios oldtty;
864static int old_fd0_flags;
bb002513 865static bool stdio_allow_signal;
6f97dba0
AL
866
867static void term_exit(void)
868{
869 tcsetattr (0, TCSANOW, &oldtty);
870 fcntl(0, F_SETFL, old_fd0_flags);
871}
872
bb002513 873static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
6f97dba0
AL
874{
875 struct termios tty;
876
0369364b 877 tty = oldtty;
bb002513
PB
878 if (!echo) {
879 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
6f97dba0 880 |INLCR|IGNCR|ICRNL|IXON);
bb002513
PB
881 tty.c_oflag |= OPOST;
882 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
883 tty.c_cflag &= ~(CSIZE|PARENB);
884 tty.c_cflag |= CS8;
885 tty.c_cc[VMIN] = 1;
886 tty.c_cc[VTIME] = 0;
887 }
6f97dba0 888 /* if graphical mode, we allow Ctrl-C handling */
bb002513 889 if (!stdio_allow_signal)
6f97dba0 890 tty.c_lflag &= ~ISIG;
6f97dba0
AL
891
892 tcsetattr (0, TCSANOW, &tty);
6f97dba0
AL
893}
894
895static void qemu_chr_close_stdio(struct CharDriverState *chr)
896{
897 term_exit();
6f97dba0
AL
898 fd_chr_close(chr);
899}
900
1f51470d 901static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)
6f97dba0
AL
902{
903 CharDriverState *chr;
904
ab51b1d5
MT
905 if (is_daemonized()) {
906 error_report("cannot use stdio with -daemonize");
907 return NULL;
908 }
ed7a1540
AL
909 old_fd0_flags = fcntl(0, F_GETFL);
910 tcgetattr (0, &oldtty);
911 fcntl(0, F_SETFL, O_NONBLOCK);
912 atexit(term_exit);
0369364b 913
6f97dba0
AL
914 chr = qemu_chr_open_fd(0, 1);
915 chr->chr_close = qemu_chr_close_stdio;
bb002513 916 chr->chr_set_echo = qemu_chr_set_echo_stdio;
bb002513
PB
917 stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
918 display_type != DT_NOGRAPHIC);
15f31519 919 qemu_chr_fe_set_echo(chr, false);
6f97dba0 920
1f51470d 921 return chr;
6f97dba0
AL
922}
923
924#ifdef __sun__
925/* Once Solaris has openpty(), this is going to be removed. */
3f4cb3d3
BS
926static int openpty(int *amaster, int *aslave, char *name,
927 struct termios *termp, struct winsize *winp)
6f97dba0
AL
928{
929 const char *slave;
930 int mfd = -1, sfd = -1;
931
932 *amaster = *aslave = -1;
933
934 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
935 if (mfd < 0)
936 goto err;
937
938 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
939 goto err;
940
941 if ((slave = ptsname(mfd)) == NULL)
942 goto err;
943
944 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
945 goto err;
946
947 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
948 (termp != NULL && tcgetattr(sfd, termp) < 0))
949 goto err;
950
951 if (amaster)
952 *amaster = mfd;
953 if (aslave)
954 *aslave = sfd;
955 if (winp)
956 ioctl(sfd, TIOCSWINSZ, winp);
957
958 return 0;
959
960err:
961 if (sfd != -1)
962 close(sfd);
963 close(mfd);
964 return -1;
965}
966
3f4cb3d3 967static void cfmakeraw (struct termios *termios_p)
6f97dba0
AL
968{
969 termios_p->c_iflag &=
970 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
971 termios_p->c_oflag &= ~OPOST;
972 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
973 termios_p->c_cflag &= ~(CSIZE|PARENB);
974 termios_p->c_cflag |= CS8;
975
976 termios_p->c_cc[VMIN] = 0;
977 termios_p->c_cc[VTIME] = 0;
978}
979#endif
980
981#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
a167ba50
AJ
982 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
983 || defined(__GLIBC__)
6f97dba0 984
e551498e
GH
985#define HAVE_CHARDEV_TTY 1
986
6f97dba0 987typedef struct {
093d3a20
AL
988 GIOChannel *fd;
989 guint fd_tag;
6f97dba0
AL
990 int connected;
991 int polling;
992 int read_bytes;
8aa33caf 993 guint timer_tag;
6f97dba0
AL
994} PtyCharDriver;
995
996static void pty_chr_update_read_handler(CharDriverState *chr);
997static void pty_chr_state(CharDriverState *chr, int connected);
998
8aa33caf
AL
999static gboolean pty_chr_timer(gpointer opaque)
1000{
1001 struct CharDriverState *chr = opaque;
1002 PtyCharDriver *s = chr->opaque;
1003
1004 if (s->connected) {
1005 goto out;
1006 }
1007 if (s->polling) {
1008 /* If we arrive here without polling being cleared due
1009 * read returning -EIO, then we are (re-)connected */
1010 pty_chr_state(chr, 1);
1011 goto out;
1012 }
1013
1014 /* Next poll ... */
1015 pty_chr_update_read_handler(chr);
1016
1017out:
1018 return FALSE;
1019}
1020
1021static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1022{
1023 PtyCharDriver *s = chr->opaque;
1024
1025 if (s->timer_tag) {
1026 g_source_remove(s->timer_tag);
1027 s->timer_tag = 0;
1028 }
1029
1030 if (ms == 1000) {
1031 s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1032 } else {
1033 s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1034 }
1035}
1036
6f97dba0
AL
1037static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1038{
1039 PtyCharDriver *s = chr->opaque;
1040
1041 if (!s->connected) {
1042 /* guest sends data, check for (re-)connect */
1043 pty_chr_update_read_handler(chr);
1044 return 0;
1045 }
093d3a20 1046 return io_channel_send_all(s->fd, buf, len);
6f97dba0
AL
1047}
1048
e6a87ed8
AL
1049static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1050{
1051 PtyCharDriver *s = chr->opaque;
1052 return g_io_create_watch(s->fd, cond);
1053}
1054
6f97dba0
AL
1055static int pty_chr_read_poll(void *opaque)
1056{
1057 CharDriverState *chr = opaque;
1058 PtyCharDriver *s = chr->opaque;
1059
909cda12 1060 s->read_bytes = qemu_chr_be_can_write(chr);
6f97dba0
AL
1061 return s->read_bytes;
1062}
1063
093d3a20 1064static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
6f97dba0
AL
1065{
1066 CharDriverState *chr = opaque;
1067 PtyCharDriver *s = chr->opaque;
093d3a20 1068 gsize size, len;
9bd7854e 1069 uint8_t buf[READ_BUF_LEN];
093d3a20 1070 GIOStatus status;
6f97dba0
AL
1071
1072 len = sizeof(buf);
1073 if (len > s->read_bytes)
1074 len = s->read_bytes;
1075 if (len == 0)
093d3a20
AL
1076 return FALSE;
1077 status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1078 if (status != G_IO_STATUS_NORMAL) {
6f97dba0 1079 pty_chr_state(chr, 0);
093d3a20
AL
1080 return FALSE;
1081 } else {
6f97dba0 1082 pty_chr_state(chr, 1);
fa5efccb 1083 qemu_chr_be_write(chr, buf, size);
6f97dba0 1084 }
093d3a20 1085 return TRUE;
6f97dba0
AL
1086}
1087
1088static void pty_chr_update_read_handler(CharDriverState *chr)
1089{
1090 PtyCharDriver *s = chr->opaque;
1091
093d3a20
AL
1092 if (s->fd_tag) {
1093 g_source_remove(s->fd_tag);
1094 }
1095
1096 s->fd_tag = io_add_watch_poll(s->fd, pty_chr_read_poll, pty_chr_read, chr);
6f97dba0
AL
1097 s->polling = 1;
1098 /*
1099 * Short timeout here: just need wait long enougth that qemu makes
1100 * it through the poll loop once. When reconnected we want a
1101 * short timeout so we notice it almost instantly. Otherwise
1102 * read() gives us -EIO instantly, making pty_chr_state() reset the
1103 * timeout to the normal (much longer) poll interval before the
1104 * timer triggers.
1105 */
8aa33caf 1106 pty_chr_rearm_timer(chr, 10);
6f97dba0
AL
1107}
1108
1109static void pty_chr_state(CharDriverState *chr, int connected)
1110{
1111 PtyCharDriver *s = chr->opaque;
1112
1113 if (!connected) {
093d3a20
AL
1114 g_source_remove(s->fd_tag);
1115 s->fd_tag = 0;
6f97dba0
AL
1116 s->connected = 0;
1117 s->polling = 0;
1118 /* (re-)connect poll interval for idle guests: once per second.
1119 * We check more frequently in case the guests sends data to
1120 * the virtual device linked to our pty. */
8aa33caf 1121 pty_chr_rearm_timer(chr, 1000);
6f97dba0
AL
1122 } else {
1123 if (!s->connected)
127338e6 1124 qemu_chr_generic_open(chr);
6f97dba0
AL
1125 s->connected = 1;
1126 }
1127}
1128
6f97dba0
AL
1129
1130static void pty_chr_close(struct CharDriverState *chr)
1131{
1132 PtyCharDriver *s = chr->opaque;
093d3a20 1133 int fd;
6f97dba0 1134
093d3a20
AL
1135 if (s->fd_tag) {
1136 g_source_remove(s->fd_tag);
1137 }
1138 fd = g_io_channel_unix_get_fd(s->fd);
1139 g_io_channel_unref(s->fd);
1140 close(fd);
8aa33caf
AL
1141 if (s->timer_tag) {
1142 g_source_remove(s->timer_tag);
1143 }
7267c094 1144 g_free(s);
a425d23f 1145 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
6f97dba0
AL
1146}
1147
1f51470d 1148static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
6f97dba0
AL
1149{
1150 CharDriverState *chr;
1151 PtyCharDriver *s;
1152 struct termios tty;
58650218 1153 const char *label;
a4e26048 1154 int master_fd, slave_fd, len;
c5e97233 1155#if defined(__OpenBSD__) || defined(__DragonFly__)
6f97dba0
AL
1156 char pty_name[PATH_MAX];
1157#define q_ptsname(x) pty_name
1158#else
1159 char *pty_name = NULL;
1160#define q_ptsname(x) ptsname(x)
1161#endif
1162
a4e26048 1163 if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
1f51470d 1164 return NULL;
6f97dba0
AL
1165 }
1166
1167 /* Set raw attributes on the pty. */
c3b972c3 1168 tcgetattr(slave_fd, &tty);
6f97dba0
AL
1169 cfmakeraw(&tty);
1170 tcsetattr(slave_fd, TCSAFLUSH, &tty);
1171 close(slave_fd);
1172
a4e26048
MA
1173 chr = g_malloc0(sizeof(CharDriverState));
1174
1175 len = strlen(q_ptsname(master_fd)) + 5;
7267c094 1176 chr->filename = g_malloc(len);
a4e26048
MA
1177 snprintf(chr->filename, len, "pty:%s", q_ptsname(master_fd));
1178 qemu_opt_set(opts, "path", q_ptsname(master_fd));
58650218
LL
1179
1180 label = qemu_opts_id(opts);
25bbf61e
GH
1181 fprintf(stderr, "char device redirected to %s%s%s%s\n",
1182 q_ptsname(master_fd),
1183 label ? " (label " : "",
1184 label ? label : "",
1185 label ? ")" : "");
6f97dba0 1186
a4e26048 1187 s = g_malloc0(sizeof(PtyCharDriver));
6f97dba0
AL
1188 chr->opaque = s;
1189 chr->chr_write = pty_chr_write;
1190 chr->chr_update_read_handler = pty_chr_update_read_handler;
1191 chr->chr_close = pty_chr_close;
e6a87ed8 1192 chr->chr_add_watch = pty_chr_add_watch;
6f97dba0 1193
093d3a20 1194 s->fd = io_channel_from_fd(master_fd);
8aa33caf 1195 s->timer_tag = 0;
6f97dba0 1196
1f51470d 1197 return chr;
6f97dba0
AL
1198}
1199
1200static void tty_serial_init(int fd, int speed,
1201 int parity, int data_bits, int stop_bits)
1202{
1203 struct termios tty;
1204 speed_t spd;
1205
1206#if 0
1207 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1208 speed, parity, data_bits, stop_bits);
1209#endif
1210 tcgetattr (fd, &tty);
1211
45eea13b
SW
1212#define check_speed(val) if (speed <= val) { spd = B##val; break; }
1213 speed = speed * 10 / 11;
1214 do {
1215 check_speed(50);
1216 check_speed(75);
1217 check_speed(110);
1218 check_speed(134);
1219 check_speed(150);
1220 check_speed(200);
1221 check_speed(300);
1222 check_speed(600);
1223 check_speed(1200);
1224 check_speed(1800);
1225 check_speed(2400);
1226 check_speed(4800);
1227 check_speed(9600);
1228 check_speed(19200);
1229 check_speed(38400);
1230 /* Non-Posix values follow. They may be unsupported on some systems. */
1231 check_speed(57600);
1232 check_speed(115200);
1233#ifdef B230400
1234 check_speed(230400);
1235#endif
1236#ifdef B460800
1237 check_speed(460800);
1238#endif
1239#ifdef B500000
1240 check_speed(500000);
1241#endif
1242#ifdef B576000
1243 check_speed(576000);
1244#endif
1245#ifdef B921600
1246 check_speed(921600);
1247#endif
1248#ifdef B1000000
1249 check_speed(1000000);
1250#endif
1251#ifdef B1152000
1252 check_speed(1152000);
1253#endif
1254#ifdef B1500000
1255 check_speed(1500000);
1256#endif
1257#ifdef B2000000
1258 check_speed(2000000);
1259#endif
1260#ifdef B2500000
1261 check_speed(2500000);
1262#endif
1263#ifdef B3000000
1264 check_speed(3000000);
1265#endif
1266#ifdef B3500000
1267 check_speed(3500000);
1268#endif
1269#ifdef B4000000
1270 check_speed(4000000);
1271#endif
6f97dba0 1272 spd = B115200;
45eea13b 1273 } while (0);
6f97dba0
AL
1274
1275 cfsetispeed(&tty, spd);
1276 cfsetospeed(&tty, spd);
1277
1278 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1279 |INLCR|IGNCR|ICRNL|IXON);
1280 tty.c_oflag |= OPOST;
1281 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1282 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1283 switch(data_bits) {
1284 default:
1285 case 8:
1286 tty.c_cflag |= CS8;
1287 break;
1288 case 7:
1289 tty.c_cflag |= CS7;
1290 break;
1291 case 6:
1292 tty.c_cflag |= CS6;
1293 break;
1294 case 5:
1295 tty.c_cflag |= CS5;
1296 break;
1297 }
1298 switch(parity) {
1299 default:
1300 case 'N':
1301 break;
1302 case 'E':
1303 tty.c_cflag |= PARENB;
1304 break;
1305 case 'O':
1306 tty.c_cflag |= PARENB | PARODD;
1307 break;
1308 }
1309 if (stop_bits == 2)
1310 tty.c_cflag |= CSTOPB;
1311
1312 tcsetattr (fd, TCSANOW, &tty);
1313}
1314
1315static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1316{
1317 FDCharDriver *s = chr->opaque;
1318
1319 switch(cmd) {
1320 case CHR_IOCTL_SERIAL_SET_PARAMS:
1321 {
1322 QEMUSerialSetParams *ssp = arg;
a29753f8
AL
1323 tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1324 ssp->speed, ssp->parity,
6f97dba0
AL
1325 ssp->data_bits, ssp->stop_bits);
1326 }
1327 break;
1328 case CHR_IOCTL_SERIAL_SET_BREAK:
1329 {
1330 int enable = *(int *)arg;
a29753f8
AL
1331 if (enable) {
1332 tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1333 }
6f97dba0
AL
1334 }
1335 break;
1336 case CHR_IOCTL_SERIAL_GET_TIOCM:
1337 {
1338 int sarg = 0;
1339 int *targ = (int *)arg;
a29753f8 1340 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
6f97dba0 1341 *targ = 0;
b4abdfa4 1342 if (sarg & TIOCM_CTS)
6f97dba0 1343 *targ |= CHR_TIOCM_CTS;
b4abdfa4 1344 if (sarg & TIOCM_CAR)
6f97dba0 1345 *targ |= CHR_TIOCM_CAR;
b4abdfa4 1346 if (sarg & TIOCM_DSR)
6f97dba0 1347 *targ |= CHR_TIOCM_DSR;
b4abdfa4 1348 if (sarg & TIOCM_RI)
6f97dba0 1349 *targ |= CHR_TIOCM_RI;
b4abdfa4 1350 if (sarg & TIOCM_DTR)
6f97dba0 1351 *targ |= CHR_TIOCM_DTR;
b4abdfa4 1352 if (sarg & TIOCM_RTS)
6f97dba0
AL
1353 *targ |= CHR_TIOCM_RTS;
1354 }
1355 break;
1356 case CHR_IOCTL_SERIAL_SET_TIOCM:
1357 {
1358 int sarg = *(int *)arg;
1359 int targ = 0;
a29753f8 1360 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
b4abdfa4
AJ
1361 targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1362 | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1363 if (sarg & CHR_TIOCM_CTS)
1364 targ |= TIOCM_CTS;
1365 if (sarg & CHR_TIOCM_CAR)
1366 targ |= TIOCM_CAR;
1367 if (sarg & CHR_TIOCM_DSR)
1368 targ |= TIOCM_DSR;
1369 if (sarg & CHR_TIOCM_RI)
1370 targ |= TIOCM_RI;
1371 if (sarg & CHR_TIOCM_DTR)
6f97dba0 1372 targ |= TIOCM_DTR;
b4abdfa4 1373 if (sarg & CHR_TIOCM_RTS)
6f97dba0 1374 targ |= TIOCM_RTS;
a29753f8 1375 ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
6f97dba0
AL
1376 }
1377 break;
1378 default:
1379 return -ENOTSUP;
1380 }
1381 return 0;
1382}
1383
4266a134
DA
1384static void qemu_chr_close_tty(CharDriverState *chr)
1385{
1386 FDCharDriver *s = chr->opaque;
1387 int fd = -1;
1388
1389 if (s) {
a29753f8 1390 fd = g_io_channel_unix_get_fd(s->fd_in);
4266a134
DA
1391 }
1392
1393 fd_chr_close(chr);
1394
1395 if (fd >= 0) {
1396 close(fd);
1397 }
1398}
1399
d59044ef
GH
1400static CharDriverState *qemu_chr_open_tty_fd(int fd)
1401{
1402 CharDriverState *chr;
1403
1404 tty_serial_init(fd, 115200, 'N', 8, 1);
1405 chr = qemu_chr_open_fd(fd, fd);
1406 chr->chr_ioctl = tty_serial_ioctl;
1407 chr->chr_close = qemu_chr_close_tty;
1408 return chr;
1409}
1410
1f51470d 1411static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
6f97dba0 1412{
48b76496 1413 const char *filename = qemu_opt_get(opts, "path");
6f97dba0
AL
1414 int fd;
1415
b181e047 1416 TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
afc535ac 1417 if (fd < 0) {
1f51470d 1418 return NULL;
afc535ac 1419 }
d59044ef 1420 return qemu_chr_open_tty_fd(fd);
6f97dba0 1421}
6f97dba0
AL
1422#endif /* __linux__ || __sun__ */
1423
1424#if defined(__linux__)
e551498e
GH
1425
1426#define HAVE_CHARDEV_PARPORT 1
1427
6f97dba0
AL
1428typedef struct {
1429 int fd;
1430 int mode;
1431} ParallelCharDriver;
1432
1433static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1434{
1435 if (s->mode != mode) {
1436 int m = mode;
1437 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1438 return 0;
1439 s->mode = mode;
1440 }
1441 return 1;
1442}
1443
1444static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1445{
1446 ParallelCharDriver *drv = chr->opaque;
1447 int fd = drv->fd;
1448 uint8_t b;
1449
1450 switch(cmd) {
1451 case CHR_IOCTL_PP_READ_DATA:
1452 if (ioctl(fd, PPRDATA, &b) < 0)
1453 return -ENOTSUP;
1454 *(uint8_t *)arg = b;
1455 break;
1456 case CHR_IOCTL_PP_WRITE_DATA:
1457 b = *(uint8_t *)arg;
1458 if (ioctl(fd, PPWDATA, &b) < 0)
1459 return -ENOTSUP;
1460 break;
1461 case CHR_IOCTL_PP_READ_CONTROL:
1462 if (ioctl(fd, PPRCONTROL, &b) < 0)
1463 return -ENOTSUP;
1464 /* Linux gives only the lowest bits, and no way to know data
1465 direction! For better compatibility set the fixed upper
1466 bits. */
1467 *(uint8_t *)arg = b | 0xc0;
1468 break;
1469 case CHR_IOCTL_PP_WRITE_CONTROL:
1470 b = *(uint8_t *)arg;
1471 if (ioctl(fd, PPWCONTROL, &b) < 0)
1472 return -ENOTSUP;
1473 break;
1474 case CHR_IOCTL_PP_READ_STATUS:
1475 if (ioctl(fd, PPRSTATUS, &b) < 0)
1476 return -ENOTSUP;
1477 *(uint8_t *)arg = b;
1478 break;
1479 case CHR_IOCTL_PP_DATA_DIR:
1480 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1481 return -ENOTSUP;
1482 break;
1483 case CHR_IOCTL_PP_EPP_READ_ADDR:
1484 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1485 struct ParallelIOArg *parg = arg;
1486 int n = read(fd, parg->buffer, parg->count);
1487 if (n != parg->count) {
1488 return -EIO;
1489 }
1490 }
1491 break;
1492 case CHR_IOCTL_PP_EPP_READ:
1493 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1494 struct ParallelIOArg *parg = arg;
1495 int n = read(fd, parg->buffer, parg->count);
1496 if (n != parg->count) {
1497 return -EIO;
1498 }
1499 }
1500 break;
1501 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1502 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1503 struct ParallelIOArg *parg = arg;
1504 int n = write(fd, parg->buffer, parg->count);
1505 if (n != parg->count) {
1506 return -EIO;
1507 }
1508 }
1509 break;
1510 case CHR_IOCTL_PP_EPP_WRITE:
1511 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1512 struct ParallelIOArg *parg = arg;
1513 int n = write(fd, parg->buffer, parg->count);
1514 if (n != parg->count) {
1515 return -EIO;
1516 }
1517 }
1518 break;
1519 default:
1520 return -ENOTSUP;
1521 }
1522 return 0;
1523}
1524
1525static void pp_close(CharDriverState *chr)
1526{
1527 ParallelCharDriver *drv = chr->opaque;
1528 int fd = drv->fd;
1529
1530 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1531 ioctl(fd, PPRELEASE);
1532 close(fd);
7267c094 1533 g_free(drv);
a425d23f 1534 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
6f97dba0
AL
1535}
1536
88a946d3 1537static CharDriverState *qemu_chr_open_pp_fd(int fd)
6f97dba0
AL
1538{
1539 CharDriverState *chr;
1540 ParallelCharDriver *drv;
6f97dba0
AL
1541
1542 if (ioctl(fd, PPCLAIM) < 0) {
1543 close(fd);
1f51470d 1544 return NULL;
6f97dba0
AL
1545 }
1546
7267c094 1547 drv = g_malloc0(sizeof(ParallelCharDriver));
6f97dba0
AL
1548 drv->fd = fd;
1549 drv->mode = IEEE1284_MODE_COMPAT;
1550
7267c094 1551 chr = g_malloc0(sizeof(CharDriverState));
6f97dba0
AL
1552 chr->chr_write = null_chr_write;
1553 chr->chr_ioctl = pp_ioctl;
1554 chr->chr_close = pp_close;
1555 chr->opaque = drv;
1556
127338e6 1557 qemu_chr_generic_open(chr);
6f97dba0 1558
1f51470d 1559 return chr;
6f97dba0
AL
1560}
1561#endif /* __linux__ */
1562
a167ba50 1563#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
e551498e
GH
1564
1565#define HAVE_CHARDEV_PARPORT 1
1566
6972f935
BS
1567static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1568{
e0efb993 1569 int fd = (int)(intptr_t)chr->opaque;
6972f935
BS
1570 uint8_t b;
1571
1572 switch(cmd) {
1573 case CHR_IOCTL_PP_READ_DATA:
1574 if (ioctl(fd, PPIGDATA, &b) < 0)
1575 return -ENOTSUP;
1576 *(uint8_t *)arg = b;
1577 break;
1578 case CHR_IOCTL_PP_WRITE_DATA:
1579 b = *(uint8_t *)arg;
1580 if (ioctl(fd, PPISDATA, &b) < 0)
1581 return -ENOTSUP;
1582 break;
1583 case CHR_IOCTL_PP_READ_CONTROL:
1584 if (ioctl(fd, PPIGCTRL, &b) < 0)
1585 return -ENOTSUP;
1586 *(uint8_t *)arg = b;
1587 break;
1588 case CHR_IOCTL_PP_WRITE_CONTROL:
1589 b = *(uint8_t *)arg;
1590 if (ioctl(fd, PPISCTRL, &b) < 0)
1591 return -ENOTSUP;
1592 break;
1593 case CHR_IOCTL_PP_READ_STATUS:
1594 if (ioctl(fd, PPIGSTATUS, &b) < 0)
1595 return -ENOTSUP;
1596 *(uint8_t *)arg = b;
1597 break;
1598 default:
1599 return -ENOTSUP;
1600 }
1601 return 0;
1602}
1603
88a946d3 1604static CharDriverState *qemu_chr_open_pp_fd(int fd)
6972f935
BS
1605{
1606 CharDriverState *chr;
6972f935 1607
7267c094 1608 chr = g_malloc0(sizeof(CharDriverState));
e0efb993 1609 chr->opaque = (void *)(intptr_t)fd;
6972f935
BS
1610 chr->chr_write = null_chr_write;
1611 chr->chr_ioctl = pp_ioctl;
1f51470d 1612 return chr;
6972f935
BS
1613}
1614#endif
1615
6f97dba0
AL
1616#else /* _WIN32 */
1617
1618typedef struct {
1619 int max_size;
1620 HANDLE hcom, hrecv, hsend;
1621 OVERLAPPED orecv, osend;
1622 BOOL fpipe;
1623 DWORD len;
1624} WinCharState;
1625
db418a0a
FC
1626typedef struct {
1627 HANDLE hStdIn;
1628 HANDLE hInputReadyEvent;
1629 HANDLE hInputDoneEvent;
1630 HANDLE hInputThread;
1631 uint8_t win_stdio_buf;
1632} WinStdioCharState;
1633
6f97dba0
AL
1634#define NSENDBUF 2048
1635#define NRECVBUF 2048
1636#define MAXCONNECT 1
1637#define NTIMEOUT 5000
1638
1639static int win_chr_poll(void *opaque);
1640static int win_chr_pipe_poll(void *opaque);
1641
1642static void win_chr_close(CharDriverState *chr)
1643{
1644 WinCharState *s = chr->opaque;
1645
1646 if (s->hsend) {
1647 CloseHandle(s->hsend);
1648 s->hsend = NULL;
1649 }
1650 if (s->hrecv) {
1651 CloseHandle(s->hrecv);
1652 s->hrecv = NULL;
1653 }
1654 if (s->hcom) {
1655 CloseHandle(s->hcom);
1656 s->hcom = NULL;
1657 }
1658 if (s->fpipe)
1659 qemu_del_polling_cb(win_chr_pipe_poll, chr);
1660 else
1661 qemu_del_polling_cb(win_chr_poll, chr);
793cbfb5 1662
a425d23f 1663 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
6f97dba0
AL
1664}
1665
1666static int win_chr_init(CharDriverState *chr, const char *filename)
1667{
1668 WinCharState *s = chr->opaque;
1669 COMMCONFIG comcfg;
1670 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1671 COMSTAT comstat;
1672 DWORD size;
1673 DWORD err;
1674
1675 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1676 if (!s->hsend) {
1677 fprintf(stderr, "Failed CreateEvent\n");
1678 goto fail;
1679 }
1680 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1681 if (!s->hrecv) {
1682 fprintf(stderr, "Failed CreateEvent\n");
1683 goto fail;
1684 }
1685
1686 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1687 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1688 if (s->hcom == INVALID_HANDLE_VALUE) {
1689 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1690 s->hcom = NULL;
1691 goto fail;
1692 }
1693
1694 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1695 fprintf(stderr, "Failed SetupComm\n");
1696 goto fail;
1697 }
1698
1699 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1700 size = sizeof(COMMCONFIG);
1701 GetDefaultCommConfig(filename, &comcfg, &size);
1702 comcfg.dcb.DCBlength = sizeof(DCB);
1703 CommConfigDialog(filename, NULL, &comcfg);
1704
1705 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1706 fprintf(stderr, "Failed SetCommState\n");
1707 goto fail;
1708 }
1709
1710 if (!SetCommMask(s->hcom, EV_ERR)) {
1711 fprintf(stderr, "Failed SetCommMask\n");
1712 goto fail;
1713 }
1714
1715 cto.ReadIntervalTimeout = MAXDWORD;
1716 if (!SetCommTimeouts(s->hcom, &cto)) {
1717 fprintf(stderr, "Failed SetCommTimeouts\n");
1718 goto fail;
1719 }
1720
1721 if (!ClearCommError(s->hcom, &err, &comstat)) {
1722 fprintf(stderr, "Failed ClearCommError\n");
1723 goto fail;
1724 }
1725 qemu_add_polling_cb(win_chr_poll, chr);
1726 return 0;
1727
1728 fail:
1729 win_chr_close(chr);
1730 return -1;
1731}
1732
1733static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1734{
1735 WinCharState *s = chr->opaque;
1736 DWORD len, ret, size, err;
1737
1738 len = len1;
1739 ZeroMemory(&s->osend, sizeof(s->osend));
1740 s->osend.hEvent = s->hsend;
1741 while (len > 0) {
1742 if (s->hsend)
1743 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1744 else
1745 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1746 if (!ret) {
1747 err = GetLastError();
1748 if (err == ERROR_IO_PENDING) {
1749 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1750 if (ret) {
1751 buf += size;
1752 len -= size;
1753 } else {
1754 break;
1755 }
1756 } else {
1757 break;
1758 }
1759 } else {
1760 buf += size;
1761 len -= size;
1762 }
1763 }
1764 return len1 - len;
1765}
1766
1767static int win_chr_read_poll(CharDriverState *chr)
1768{
1769 WinCharState *s = chr->opaque;
1770
909cda12 1771 s->max_size = qemu_chr_be_can_write(chr);
6f97dba0
AL
1772 return s->max_size;
1773}
1774
1775static void win_chr_readfile(CharDriverState *chr)
1776{
1777 WinCharState *s = chr->opaque;
1778 int ret, err;
9bd7854e 1779 uint8_t buf[READ_BUF_LEN];
6f97dba0
AL
1780 DWORD size;
1781
1782 ZeroMemory(&s->orecv, sizeof(s->orecv));
1783 s->orecv.hEvent = s->hrecv;
1784 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1785 if (!ret) {
1786 err = GetLastError();
1787 if (err == ERROR_IO_PENDING) {
1788 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1789 }
1790 }
1791
1792 if (size > 0) {
fa5efccb 1793 qemu_chr_be_write(chr, buf, size);
6f97dba0
AL
1794 }
1795}
1796
1797static void win_chr_read(CharDriverState *chr)
1798{
1799 WinCharState *s = chr->opaque;
1800
1801 if (s->len > s->max_size)
1802 s->len = s->max_size;
1803 if (s->len == 0)
1804 return;
1805
1806 win_chr_readfile(chr);
1807}
1808
1809static int win_chr_poll(void *opaque)
1810{
1811 CharDriverState *chr = opaque;
1812 WinCharState *s = chr->opaque;
1813 COMSTAT status;
1814 DWORD comerr;
1815
1816 ClearCommError(s->hcom, &comerr, &status);
1817 if (status.cbInQue > 0) {
1818 s->len = status.cbInQue;
1819 win_chr_read_poll(chr);
1820 win_chr_read(chr);
1821 return 1;
1822 }
1823 return 0;
1824}
1825
d59044ef 1826static CharDriverState *qemu_chr_open_win_path(const char *filename)
6f97dba0
AL
1827{
1828 CharDriverState *chr;
1829 WinCharState *s;
1830
7267c094
AL
1831 chr = g_malloc0(sizeof(CharDriverState));
1832 s = g_malloc0(sizeof(WinCharState));
6f97dba0
AL
1833 chr->opaque = s;
1834 chr->chr_write = win_chr_write;
1835 chr->chr_close = win_chr_close;
1836
1837 if (win_chr_init(chr, filename) < 0) {
2e02e18b
SW
1838 g_free(s);
1839 g_free(chr);
1f51470d 1840 return NULL;
6f97dba0 1841 }
127338e6 1842 qemu_chr_generic_open(chr);
1f51470d 1843 return chr;
6f97dba0
AL
1844}
1845
d59044ef
GH
1846static CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1847{
1848 return qemu_chr_open_win_path(qemu_opt_get(opts, "path"));
1849}
1850
6f97dba0
AL
1851static int win_chr_pipe_poll(void *opaque)
1852{
1853 CharDriverState *chr = opaque;
1854 WinCharState *s = chr->opaque;
1855 DWORD size;
1856
1857 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1858 if (size > 0) {
1859 s->len = size;
1860 win_chr_read_poll(chr);
1861 win_chr_read(chr);
1862 return 1;
1863 }
1864 return 0;
1865}
1866
1867static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1868{
1869 WinCharState *s = chr->opaque;
1870 OVERLAPPED ov;
1871 int ret;
1872 DWORD size;
1873 char openname[256];
1874
1875 s->fpipe = TRUE;
1876
1877 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1878 if (!s->hsend) {
1879 fprintf(stderr, "Failed CreateEvent\n");
1880 goto fail;
1881 }
1882 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1883 if (!s->hrecv) {
1884 fprintf(stderr, "Failed CreateEvent\n");
1885 goto fail;
1886 }
1887
1888 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1889 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1890 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1891 PIPE_WAIT,
1892 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1893 if (s->hcom == INVALID_HANDLE_VALUE) {
1894 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1895 s->hcom = NULL;
1896 goto fail;
1897 }
1898
1899 ZeroMemory(&ov, sizeof(ov));
1900 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1901 ret = ConnectNamedPipe(s->hcom, &ov);
1902 if (ret) {
1903 fprintf(stderr, "Failed ConnectNamedPipe\n");
1904 goto fail;
1905 }
1906
1907 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1908 if (!ret) {
1909 fprintf(stderr, "Failed GetOverlappedResult\n");
1910 if (ov.hEvent) {
1911 CloseHandle(ov.hEvent);
1912 ov.hEvent = NULL;
1913 }
1914 goto fail;
1915 }
1916
1917 if (ov.hEvent) {
1918 CloseHandle(ov.hEvent);
1919 ov.hEvent = NULL;
1920 }
1921 qemu_add_polling_cb(win_chr_pipe_poll, chr);
1922 return 0;
1923
1924 fail:
1925 win_chr_close(chr);
1926 return -1;
1927}
1928
1929
1f51470d 1930static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
6f97dba0 1931{
7d31544f 1932 const char *filename = qemu_opt_get(opts, "path");
6f97dba0
AL
1933 CharDriverState *chr;
1934 WinCharState *s;
1935
7267c094
AL
1936 chr = g_malloc0(sizeof(CharDriverState));
1937 s = g_malloc0(sizeof(WinCharState));
6f97dba0
AL
1938 chr->opaque = s;
1939 chr->chr_write = win_chr_write;
1940 chr->chr_close = win_chr_close;
1941
1942 if (win_chr_pipe_init(chr, filename) < 0) {
2e02e18b
SW
1943 g_free(s);
1944 g_free(chr);
1f51470d 1945 return NULL;
6f97dba0 1946 }
127338e6 1947 qemu_chr_generic_open(chr);
1f51470d 1948 return chr;
6f97dba0
AL
1949}
1950
1f51470d 1951static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
6f97dba0
AL
1952{
1953 CharDriverState *chr;
1954 WinCharState *s;
1955
7267c094
AL
1956 chr = g_malloc0(sizeof(CharDriverState));
1957 s = g_malloc0(sizeof(WinCharState));
6f97dba0
AL
1958 s->hcom = fd_out;
1959 chr->opaque = s;
1960 chr->chr_write = win_chr_write;
127338e6 1961 qemu_chr_generic_open(chr);
1f51470d 1962 return chr;
6f97dba0
AL
1963}
1964
1f51470d 1965static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
6f97dba0 1966{
1f51470d 1967 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
6f97dba0
AL
1968}
1969
1f51470d 1970static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
6f97dba0 1971{
7d31544f 1972 const char *file_out = qemu_opt_get(opts, "path");
6f97dba0
AL
1973 HANDLE fd_out;
1974
1975 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1976 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
a89dd6c3 1977 if (fd_out == INVALID_HANDLE_VALUE) {
1f51470d 1978 return NULL;
a89dd6c3 1979 }
6f97dba0 1980
1f51470d 1981 return qemu_chr_open_win_file(fd_out);
6f97dba0 1982}
db418a0a
FC
1983
1984static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1985{
1986 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1987 DWORD dwSize;
1988 int len1;
1989
1990 len1 = len;
1991
1992 while (len1 > 0) {
1993 if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
1994 break;
1995 }
1996 buf += dwSize;
1997 len1 -= dwSize;
1998 }
1999
2000 return len - len1;
2001}
2002
2003static void win_stdio_wait_func(void *opaque)
2004{
2005 CharDriverState *chr = opaque;
2006 WinStdioCharState *stdio = chr->opaque;
2007 INPUT_RECORD buf[4];
2008 int ret;
2009 DWORD dwSize;
2010 int i;
2011
2012 ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
2013 &dwSize);
2014
2015 if (!ret) {
2016 /* Avoid error storm */
2017 qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
2018 return;
2019 }
2020
2021 for (i = 0; i < dwSize; i++) {
2022 KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
2023
2024 if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
2025 int j;
2026 if (kev->uChar.AsciiChar != 0) {
2027 for (j = 0; j < kev->wRepeatCount; j++) {
2028 if (qemu_chr_be_can_write(chr)) {
2029 uint8_t c = kev->uChar.AsciiChar;
2030 qemu_chr_be_write(chr, &c, 1);
2031 }
2032 }
2033 }
2034 }
2035 }
2036}
2037
2038static DWORD WINAPI win_stdio_thread(LPVOID param)
2039{
2040 CharDriverState *chr = param;
2041 WinStdioCharState *stdio = chr->opaque;
2042 int ret;
2043 DWORD dwSize;
2044
2045 while (1) {
2046
2047 /* Wait for one byte */
2048 ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2049
2050 /* Exit in case of error, continue if nothing read */
2051 if (!ret) {
2052 break;
2053 }
2054 if (!dwSize) {
2055 continue;
2056 }
2057
2058 /* Some terminal emulator returns \r\n for Enter, just pass \n */
2059 if (stdio->win_stdio_buf == '\r') {
2060 continue;
2061 }
2062
2063 /* Signal the main thread and wait until the byte was eaten */
2064 if (!SetEvent(stdio->hInputReadyEvent)) {
2065 break;
2066 }
2067 if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2068 != WAIT_OBJECT_0) {
2069 break;
2070 }
2071 }
2072
2073 qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2074 return 0;
2075}
2076
2077static void win_stdio_thread_wait_func(void *opaque)
2078{
2079 CharDriverState *chr = opaque;
2080 WinStdioCharState *stdio = chr->opaque;
2081
2082 if (qemu_chr_be_can_write(chr)) {
2083 qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2084 }
2085
2086 SetEvent(stdio->hInputDoneEvent);
2087}
2088
2089static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2090{
2091 WinStdioCharState *stdio = chr->opaque;
2092 DWORD dwMode = 0;
2093
2094 GetConsoleMode(stdio->hStdIn, &dwMode);
2095
2096 if (echo) {
2097 SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2098 } else {
2099 SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2100 }
2101}
2102
2103static void win_stdio_close(CharDriverState *chr)
2104{
2105 WinStdioCharState *stdio = chr->opaque;
2106
2107 if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2108 CloseHandle(stdio->hInputReadyEvent);
2109 }
2110 if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2111 CloseHandle(stdio->hInputDoneEvent);
2112 }
2113 if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2114 TerminateThread(stdio->hInputThread, 0);
2115 }
2116
2117 g_free(chr->opaque);
2118 g_free(chr);
db418a0a
FC
2119}
2120
1f51470d 2121static CharDriverState *qemu_chr_open_win_stdio(QemuOpts *opts)
db418a0a
FC
2122{
2123 CharDriverState *chr;
2124 WinStdioCharState *stdio;
2125 DWORD dwMode;
2126 int is_console = 0;
2127
db418a0a
FC
2128 chr = g_malloc0(sizeof(CharDriverState));
2129 stdio = g_malloc0(sizeof(WinStdioCharState));
2130
2131 stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2132 if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2133 fprintf(stderr, "cannot open stdio: invalid handle\n");
2134 exit(1);
2135 }
2136
2137 is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2138
2139 chr->opaque = stdio;
2140 chr->chr_write = win_stdio_write;
2141 chr->chr_close = win_stdio_close;
2142
ed7a1540
AL
2143 if (is_console) {
2144 if (qemu_add_wait_object(stdio->hStdIn,
2145 win_stdio_wait_func, chr)) {
2146 fprintf(stderr, "qemu_add_wait_object: failed\n");
2147 }
2148 } else {
2149 DWORD dwId;
2150
2151 stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2152 stdio->hInputDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2153 stdio->hInputThread = CreateThread(NULL, 0, win_stdio_thread,
2154 chr, 0, &dwId);
2155
2156 if (stdio->hInputThread == INVALID_HANDLE_VALUE
2157 || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2158 || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2159 fprintf(stderr, "cannot create stdio thread or event\n");
2160 exit(1);
2161 }
2162 if (qemu_add_wait_object(stdio->hInputReadyEvent,
2163 win_stdio_thread_wait_func, chr)) {
2164 fprintf(stderr, "qemu_add_wait_object: failed\n");
db418a0a
FC
2165 }
2166 }
2167
2168 dwMode |= ENABLE_LINE_INPUT;
2169
ed7a1540 2170 if (is_console) {
db418a0a
FC
2171 /* set the terminal in raw mode */
2172 /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2173 dwMode |= ENABLE_PROCESSED_INPUT;
2174 }
2175
2176 SetConsoleMode(stdio->hStdIn, dwMode);
2177
2178 chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2179 qemu_chr_fe_set_echo(chr, false);
2180
1f51470d 2181 return chr;
db418a0a 2182}
6f97dba0
AL
2183#endif /* !_WIN32 */
2184
2185/***********************************************************/
2186/* UDP Net console */
2187
2188typedef struct {
2189 int fd;
76a9644b
AL
2190 GIOChannel *chan;
2191 guint tag;
9bd7854e 2192 uint8_t buf[READ_BUF_LEN];
6f97dba0
AL
2193 int bufcnt;
2194 int bufptr;
2195 int max_size;
2196} NetCharDriver;
2197
2198static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2199{
2200 NetCharDriver *s = chr->opaque;
76a9644b
AL
2201 gsize bytes_written;
2202 GIOStatus status;
2203
2204 status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2205 if (status == G_IO_STATUS_EOF) {
2206 return 0;
2207 } else if (status != G_IO_STATUS_NORMAL) {
2208 return -1;
2209 }
6f97dba0 2210
76a9644b 2211 return bytes_written;
6f97dba0
AL
2212}
2213
2214static int udp_chr_read_poll(void *opaque)
2215{
2216 CharDriverState *chr = opaque;
2217 NetCharDriver *s = chr->opaque;
2218
909cda12 2219 s->max_size = qemu_chr_be_can_write(chr);
6f97dba0
AL
2220
2221 /* If there were any stray characters in the queue process them
2222 * first
2223 */
2224 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
fa5efccb 2225 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
6f97dba0 2226 s->bufptr++;
909cda12 2227 s->max_size = qemu_chr_be_can_write(chr);
6f97dba0
AL
2228 }
2229 return s->max_size;
2230}
2231
76a9644b 2232static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
6f97dba0
AL
2233{
2234 CharDriverState *chr = opaque;
2235 NetCharDriver *s = chr->opaque;
76a9644b
AL
2236 gsize bytes_read = 0;
2237 GIOStatus status;
6f97dba0
AL
2238
2239 if (s->max_size == 0)
76a9644b
AL
2240 return FALSE;
2241 status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2242 &bytes_read, NULL);
2243 s->bufcnt = bytes_read;
6f97dba0 2244 s->bufptr = s->bufcnt;
76a9644b
AL
2245 if (status != G_IO_STATUS_NORMAL) {
2246 return FALSE;
2247 }
6f97dba0
AL
2248
2249 s->bufptr = 0;
2250 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
fa5efccb 2251 qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
6f97dba0 2252 s->bufptr++;
909cda12 2253 s->max_size = qemu_chr_be_can_write(chr);
6f97dba0 2254 }
76a9644b
AL
2255
2256 return TRUE;
6f97dba0
AL
2257}
2258
2259static void udp_chr_update_read_handler(CharDriverState *chr)
2260{
2261 NetCharDriver *s = chr->opaque;
2262
76a9644b
AL
2263 if (s->tag) {
2264 g_source_remove(s->tag);
2265 s->tag = 0;
2266 }
2267
2268 if (s->chan) {
2269 s->tag = io_add_watch_poll(s->chan, udp_chr_read_poll, udp_chr_read, chr);
6f97dba0
AL
2270 }
2271}
2272
819f56b7
AL
2273static void udp_chr_close(CharDriverState *chr)
2274{
2275 NetCharDriver *s = chr->opaque;
76a9644b
AL
2276 if (s->tag) {
2277 g_source_remove(s->tag);
2278 }
2279 if (s->chan) {
2280 g_io_channel_unref(s->chan);
819f56b7
AL
2281 closesocket(s->fd);
2282 }
7267c094 2283 g_free(s);
a425d23f 2284 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
819f56b7
AL
2285}
2286
1f51470d 2287static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
6f97dba0
AL
2288{
2289 CharDriverState *chr = NULL;
2290 NetCharDriver *s = NULL;
87d5f24f 2291 Error *local_err = NULL;
6f97dba0 2292 int fd = -1;
6f97dba0 2293
7267c094
AL
2294 chr = g_malloc0(sizeof(CharDriverState));
2295 s = g_malloc0(sizeof(NetCharDriver));
6f97dba0 2296
87d5f24f 2297 fd = inet_dgram_opts(opts, &local_err);
6f97dba0 2298 if (fd < 0) {
6f97dba0
AL
2299 goto return_err;
2300 }
2301
2302 s->fd = fd;
76a9644b 2303 s->chan = io_channel_from_socket(s->fd);
6f97dba0
AL
2304 s->bufcnt = 0;
2305 s->bufptr = 0;
2306 chr->opaque = s;
2307 chr->chr_write = udp_chr_write;
2308 chr->chr_update_read_handler = udp_chr_update_read_handler;
819f56b7 2309 chr->chr_close = udp_chr_close;
1f51470d 2310 return chr;
6f97dba0
AL
2311
2312return_err:
87d5f24f
PB
2313 if (local_err) {
2314 qerror_report_err(local_err);
2315 error_free(local_err);
2316 }
7267c094
AL
2317 g_free(chr);
2318 g_free(s);
6e1db57b 2319 if (fd >= 0) {
6f97dba0 2320 closesocket(fd);
6e1db57b 2321 }
1f51470d 2322 return NULL;
6f97dba0
AL
2323}
2324
2325/***********************************************************/
2326/* TCP Net console */
2327
2328typedef struct {
2ea5a7af
AL
2329
2330 GIOChannel *chan, *listen_chan;
2331 guint tag, listen_tag;
6f97dba0
AL
2332 int fd, listen_fd;
2333 int connected;
2334 int max_size;
2335 int do_telnetopt;
2336 int do_nodelay;
2337 int is_unix;
7d174059 2338 int msgfd;
6f97dba0
AL
2339} TCPCharDriver;
2340
2ea5a7af 2341static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
6f97dba0
AL
2342
2343static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2344{
2345 TCPCharDriver *s = chr->opaque;
2346 if (s->connected) {
2ea5a7af 2347 return io_channel_send_all(s->chan, buf, len);
455aa1e0 2348 } else {
6db0fdce 2349 /* XXX: indicate an error ? */
455aa1e0 2350 return len;
6f97dba0
AL
2351 }
2352}
2353
2354static int tcp_chr_read_poll(void *opaque)
2355{
2356 CharDriverState *chr = opaque;
2357 TCPCharDriver *s = chr->opaque;
2358 if (!s->connected)
2359 return 0;
909cda12 2360 s->max_size = qemu_chr_be_can_write(chr);
6f97dba0
AL
2361 return s->max_size;
2362}
2363
2364#define IAC 255
2365#define IAC_BREAK 243
2366static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2367 TCPCharDriver *s,
2368 uint8_t *buf, int *size)
2369{
2370 /* Handle any telnet client's basic IAC options to satisfy char by
2371 * char mode with no echo. All IAC options will be removed from
2372 * the buf and the do_telnetopt variable will be used to track the
2373 * state of the width of the IAC information.
2374 *
2375 * IAC commands come in sets of 3 bytes with the exception of the
2376 * "IAC BREAK" command and the double IAC.
2377 */
2378
2379 int i;
2380 int j = 0;
2381
2382 for (i = 0; i < *size; i++) {
2383 if (s->do_telnetopt > 1) {
2384 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2385 /* Double IAC means send an IAC */
2386 if (j != i)
2387 buf[j] = buf[i];
2388 j++;
2389 s->do_telnetopt = 1;
2390 } else {
2391 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2392 /* Handle IAC break commands by sending a serial break */
a425d23f 2393 qemu_chr_be_event(chr, CHR_EVENT_BREAK);
6f97dba0
AL
2394 s->do_telnetopt++;
2395 }
2396 s->do_telnetopt++;
2397 }
2398 if (s->do_telnetopt >= 4) {
2399 s->do_telnetopt = 1;
2400 }
2401 } else {
2402 if ((unsigned char)buf[i] == IAC) {
2403 s->do_telnetopt = 2;
2404 } else {
2405 if (j != i)
2406 buf[j] = buf[i];
2407 j++;
2408 }
2409 }
2410 }
2411 *size = j;
2412}
2413
7d174059
MM
2414static int tcp_get_msgfd(CharDriverState *chr)
2415{
2416 TCPCharDriver *s = chr->opaque;
e53f27b9
PB
2417 int fd = s->msgfd;
2418 s->msgfd = -1;
2419 return fd;
7d174059
MM
2420}
2421
73bcc2ac 2422#ifndef _WIN32
7d174059
MM
2423static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2424{
2425 TCPCharDriver *s = chr->opaque;
2426 struct cmsghdr *cmsg;
2427
2428 for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2429 int fd;
2430
2431 if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2432 cmsg->cmsg_level != SOL_SOCKET ||
2433 cmsg->cmsg_type != SCM_RIGHTS)
2434 continue;
2435
2436 fd = *((int *)CMSG_DATA(cmsg));
2437 if (fd < 0)
2438 continue;
2439
06138651
CB
2440#ifndef MSG_CMSG_CLOEXEC
2441 qemu_set_cloexec(fd);
2442#endif
7d174059
MM
2443 if (s->msgfd != -1)
2444 close(s->msgfd);
2445 s->msgfd = fd;
2446 }
2447}
2448
9977c894
MM
2449static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2450{
2451 TCPCharDriver *s = chr->opaque;
7cba04f6 2452 struct msghdr msg = { NULL, };
9977c894 2453 struct iovec iov[1];
7d174059
MM
2454 union {
2455 struct cmsghdr cmsg;
2456 char control[CMSG_SPACE(sizeof(int))];
2457 } msg_control;
06138651 2458 int flags = 0;
7d174059 2459 ssize_t ret;
9977c894
MM
2460
2461 iov[0].iov_base = buf;
2462 iov[0].iov_len = len;
2463
2464 msg.msg_iov = iov;
2465 msg.msg_iovlen = 1;
7d174059
MM
2466 msg.msg_control = &msg_control;
2467 msg.msg_controllen = sizeof(msg_control);
2468
06138651
CB
2469#ifdef MSG_CMSG_CLOEXEC
2470 flags |= MSG_CMSG_CLOEXEC;
2471#endif
2472 ret = recvmsg(s->fd, &msg, flags);
2473 if (ret > 0 && s->is_unix) {
7d174059 2474 unix_process_msgfd(chr, &msg);
06138651 2475 }
9977c894 2476
7d174059 2477 return ret;
9977c894
MM
2478}
2479#else
2480static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2481{
2482 TCPCharDriver *s = chr->opaque;
00aa0040 2483 return qemu_recv(s->fd, buf, len, 0);
9977c894
MM
2484}
2485#endif
2486
d3cc5bc4
AS
2487static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2488{
2489 TCPCharDriver *s = chr->opaque;
2490 return g_io_create_watch(s->chan, cond);
2491}
2492
2ea5a7af 2493static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
6f97dba0
AL
2494{
2495 CharDriverState *chr = opaque;
2496 TCPCharDriver *s = chr->opaque;
9bd7854e 2497 uint8_t buf[READ_BUF_LEN];
6f97dba0
AL
2498 int len, size;
2499
2ea5a7af
AL
2500 if (!s->connected || s->max_size <= 0) {
2501 return FALSE;
2502 }
6f97dba0
AL
2503 len = sizeof(buf);
2504 if (len > s->max_size)
2505 len = s->max_size;
9977c894 2506 size = tcp_chr_recv(chr, (void *)buf, len);
6f97dba0
AL
2507 if (size == 0) {
2508 /* connection closed */
2509 s->connected = 0;
2ea5a7af
AL
2510 if (s->listen_chan) {
2511 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
6f97dba0 2512 }
2ea5a7af
AL
2513 g_source_remove(s->tag);
2514 s->tag = 0;
2515 g_io_channel_unref(s->chan);
2516 s->chan = NULL;
6f97dba0
AL
2517 closesocket(s->fd);
2518 s->fd = -1;
a425d23f 2519 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
6f97dba0
AL
2520 } else if (size > 0) {
2521 if (s->do_telnetopt)
2522 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2523 if (size > 0)
fa5efccb 2524 qemu_chr_be_write(chr, buf, size);
6f97dba0 2525 }
2ea5a7af
AL
2526
2527 return TRUE;
6f97dba0
AL
2528}
2529
68c18d1c
BS
2530#ifndef _WIN32
2531CharDriverState *qemu_chr_open_eventfd(int eventfd)
2532{
6cbf4c8c 2533 return qemu_chr_open_fd(eventfd, eventfd);
6cbf4c8c 2534}
68c18d1c 2535#endif
6cbf4c8c 2536
6f97dba0
AL
2537static void tcp_chr_connect(void *opaque)
2538{
2539 CharDriverState *chr = opaque;
2540 TCPCharDriver *s = chr->opaque;
2541
2542 s->connected = 1;
2ea5a7af
AL
2543 if (s->chan) {
2544 s->tag = io_add_watch_poll(s->chan, tcp_chr_read_poll, tcp_chr_read, chr);
bbdd2ad0 2545 }
127338e6 2546 qemu_chr_generic_open(chr);
6f97dba0
AL
2547}
2548
2549#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2550static void tcp_chr_telnet_init(int fd)
2551{
2552 char buf[3];
2553 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2554 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2555 send(fd, (char *)buf, 3, 0);
2556 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2557 send(fd, (char *)buf, 3, 0);
2558 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2559 send(fd, (char *)buf, 3, 0);
2560 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2561 send(fd, (char *)buf, 3, 0);
2562}
2563
13661089
DB
2564static int tcp_chr_add_client(CharDriverState *chr, int fd)
2565{
2566 TCPCharDriver *s = chr->opaque;
2567 if (s->fd != -1)
2568 return -1;
2569
2570 socket_set_nonblock(fd);
2571 if (s->do_nodelay)
2572 socket_set_nodelay(fd);
2573 s->fd = fd;
2ea5a7af
AL
2574 s->chan = io_channel_from_socket(fd);
2575 g_source_remove(s->listen_tag);
2576 s->listen_tag = 0;
13661089
DB
2577 tcp_chr_connect(chr);
2578
2579 return 0;
2580}
2581
2ea5a7af 2582static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
6f97dba0
AL
2583{
2584 CharDriverState *chr = opaque;
2585 TCPCharDriver *s = chr->opaque;
2586 struct sockaddr_in saddr;
2587#ifndef _WIN32
2588 struct sockaddr_un uaddr;
2589#endif
2590 struct sockaddr *addr;
2591 socklen_t len;
2592 int fd;
2593
2594 for(;;) {
2595#ifndef _WIN32
2596 if (s->is_unix) {
2597 len = sizeof(uaddr);
2598 addr = (struct sockaddr *)&uaddr;
2599 } else
2600#endif
2601 {
2602 len = sizeof(saddr);
2603 addr = (struct sockaddr *)&saddr;
2604 }
40ff6d7e 2605 fd = qemu_accept(s->listen_fd, addr, &len);
6f97dba0 2606 if (fd < 0 && errno != EINTR) {
2ea5a7af 2607 return FALSE;
6f97dba0
AL
2608 } else if (fd >= 0) {
2609 if (s->do_telnetopt)
2610 tcp_chr_telnet_init(fd);
2611 break;
2612 }
2613 }
13661089
DB
2614 if (tcp_chr_add_client(chr, fd) < 0)
2615 close(fd);
2ea5a7af
AL
2616
2617 return TRUE;
6f97dba0
AL
2618}
2619
2620static void tcp_chr_close(CharDriverState *chr)
2621{
2622 TCPCharDriver *s = chr->opaque;
819f56b7 2623 if (s->fd >= 0) {
2ea5a7af
AL
2624 if (s->tag) {
2625 g_source_remove(s->tag);
2626 }
2627 if (s->chan) {
2628 g_io_channel_unref(s->chan);
2629 }
6f97dba0 2630 closesocket(s->fd);
819f56b7
AL
2631 }
2632 if (s->listen_fd >= 0) {
2ea5a7af
AL
2633 if (s->listen_tag) {
2634 g_source_remove(s->listen_tag);
2635 }
2636 if (s->listen_chan) {
2637 g_io_channel_unref(s->listen_chan);
2638 }
6f97dba0 2639 closesocket(s->listen_fd);
819f56b7 2640 }
7267c094 2641 g_free(s);
a425d23f 2642 qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
6f97dba0
AL
2643}
2644
f6bd5d6e
GH
2645static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2646 bool is_listen, bool is_telnet,
2647 bool is_waitconnect,
2648 Error **errp)
6f97dba0
AL
2649{
2650 CharDriverState *chr = NULL;
2651 TCPCharDriver *s = NULL;
f6bd5d6e
GH
2652 char host[NI_MAXHOST], serv[NI_MAXSERV];
2653 const char *left = "", *right = "";
2654 struct sockaddr_storage ss;
2655 socklen_t ss_len = sizeof(ss);
2656
2657 memset(&ss, 0, ss_len);
2658 if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2659 error_setg(errp, "getsockname: %s", strerror(errno));
2660 return NULL;
2661 }
2662
2663 chr = g_malloc0(sizeof(CharDriverState));
2664 s = g_malloc0(sizeof(TCPCharDriver));
2665
2666 s->connected = 0;
2667 s->fd = -1;
2668 s->listen_fd = -1;
2669 s->msgfd = -1;
2670
2671 chr->filename = g_malloc(256);
2672 switch (ss.ss_family) {
2673#ifndef _WIN32
2674 case AF_UNIX:
2675 s->is_unix = 1;
2676 snprintf(chr->filename, 256, "unix:%s%s",
2677 ((struct sockaddr_un *)(&ss))->sun_path,
2678 is_listen ? ",server" : "");
2679 break;
2680#endif
2681 case AF_INET6:
2682 left = "[";
2683 right = "]";
2684 /* fall through */
2685 case AF_INET:
2686 s->do_nodelay = do_nodelay;
2687 getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2688 serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2689 snprintf(chr->filename, 256, "%s:%s:%s%s%s%s",
2690 is_telnet ? "telnet" : "tcp",
2691 left, host, right, serv,
2692 is_listen ? ",server" : "");
2693 break;
2694 }
2695
2696 chr->opaque = s;
2697 chr->chr_write = tcp_chr_write;
2698 chr->chr_close = tcp_chr_close;
2699 chr->get_msgfd = tcp_get_msgfd;
2700 chr->chr_add_client = tcp_chr_add_client;
d3cc5bc4 2701 chr->chr_add_watch = tcp_chr_add_watch;
f6bd5d6e
GH
2702
2703 if (is_listen) {
2704 s->listen_fd = fd;
2ea5a7af
AL
2705 s->listen_chan = io_channel_from_socket(s->listen_fd);
2706 s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
f6bd5d6e
GH
2707 if (is_telnet) {
2708 s->do_telnetopt = 1;
2709 }
2710 } else {
2711 s->connected = 1;
2712 s->fd = fd;
2713 socket_set_nodelay(fd);
2ea5a7af 2714 s->chan = io_channel_from_socket(s->fd);
f6bd5d6e
GH
2715 tcp_chr_connect(chr);
2716 }
2717
2718 if (is_listen && is_waitconnect) {
2719 printf("QEMU waiting for connection on: %s\n",
2720 chr->filename);
2ea5a7af 2721 tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
f6bd5d6e
GH
2722 socket_set_nonblock(s->listen_fd);
2723 }
2724 return chr;
2725}
2726
2727static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2728{
2729 CharDriverState *chr = NULL;
87d5f24f 2730 Error *local_err = NULL;
aeb2c47a
GH
2731 int fd = -1;
2732 int is_listen;
2733 int is_waitconnect;
2734 int do_nodelay;
2735 int is_unix;
2736 int is_telnet;
2737
2738 is_listen = qemu_opt_get_bool(opts, "server", 0);
2739 is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2740 is_telnet = qemu_opt_get_bool(opts, "telnet", 0);
2741 do_nodelay = !qemu_opt_get_bool(opts, "delay", 1);
2742 is_unix = qemu_opt_get(opts, "path") != NULL;
6f97dba0
AL
2743 if (!is_listen)
2744 is_waitconnect = 0;
2745
f07b6003
AL
2746 if (is_unix) {
2747 if (is_listen) {
87d5f24f 2748 fd = unix_listen_opts(opts, &local_err);
f07b6003 2749 } else {
87d5f24f 2750 fd = unix_connect_opts(opts, &local_err, NULL, NULL);
f07b6003
AL
2751 }
2752 } else {
2753 if (is_listen) {
87d5f24f 2754 fd = inet_listen_opts(opts, 0, &local_err);
f07b6003 2755 } else {
87d5f24f 2756 fd = inet_connect_opts(opts, &local_err, NULL, NULL);
f07b6003
AL
2757 }
2758 }
a89dd6c3 2759 if (fd < 0) {
6f97dba0 2760 goto fail;
a89dd6c3 2761 }
6f97dba0
AL
2762
2763 if (!is_waitconnect)
2764 socket_set_nonblock(fd);
2765
f6bd5d6e
GH
2766 chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2767 is_waitconnect, &local_err);
2768 if (error_is_set(&local_err)) {
2769 goto fail;
6f97dba0 2770 }
1f51470d 2771 return chr;
aeb2c47a 2772
f6bd5d6e 2773
6f97dba0 2774 fail:
87d5f24f
PB
2775 if (local_err) {
2776 qerror_report_err(local_err);
2777 error_free(local_err);
2778 }
2779 if (fd >= 0) {
6f97dba0 2780 closesocket(fd);
87d5f24f 2781 }
f6bd5d6e
GH
2782 if (chr) {
2783 g_free(chr->opaque);
2784 g_free(chr);
2785 }
1f51470d 2786 return NULL;
6f97dba0
AL
2787}
2788
999bd67c
LC
2789/***********************************************************/
2790/* Memory chardev */
2791typedef struct {
2792 size_t outbuf_size;
2793 size_t outbuf_capacity;
2794 uint8_t *outbuf;
2795} MemoryDriver;
2796
2797static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2798{
2799 MemoryDriver *d = chr->opaque;
2800
2801 /* TODO: the QString implementation has the same code, we should
2802 * introduce a generic way to do this in cutils.c */
2803 if (d->outbuf_capacity < d->outbuf_size + len) {
2804 /* grow outbuf */
2805 d->outbuf_capacity += len;
2806 d->outbuf_capacity *= 2;
7267c094 2807 d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
999bd67c
LC
2808 }
2809
2810 memcpy(d->outbuf + d->outbuf_size, buf, len);
2811 d->outbuf_size += len;
2812
2813 return len;
2814}
2815
2816void qemu_chr_init_mem(CharDriverState *chr)
2817{
2818 MemoryDriver *d;
2819
7267c094 2820 d = g_malloc(sizeof(*d));
999bd67c
LC
2821 d->outbuf_size = 0;
2822 d->outbuf_capacity = 4096;
7267c094 2823 d->outbuf = g_malloc0(d->outbuf_capacity);
999bd67c
LC
2824
2825 memset(chr, 0, sizeof(*chr));
2826 chr->opaque = d;
2827 chr->chr_write = mem_chr_write;
2828}
2829
2830QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2831{
2832 MemoryDriver *d = chr->opaque;
2833 return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2834}
2835
70f24fb6 2836/* NOTE: this driver can not be closed with qemu_chr_delete()! */
999bd67c
LC
2837void qemu_chr_close_mem(CharDriverState *chr)
2838{
2839 MemoryDriver *d = chr->opaque;
2840
7267c094
AL
2841 g_free(d->outbuf);
2842 g_free(chr->opaque);
999bd67c
LC
2843 chr->opaque = NULL;
2844 chr->chr_write = NULL;
2845}
2846
2847size_t qemu_chr_mem_osize(const CharDriverState *chr)
2848{
2849 const MemoryDriver *d = chr->opaque;
2850 return d->outbuf_size;
2851}
2852
51767e7c 2853/*********************************************************/
3949e594 2854/* Ring buffer chardev */
51767e7c
LL
2855
2856typedef struct {
2857 size_t size;
2858 size_t prod;
2859 size_t cons;
2860 uint8_t *cbuf;
3949e594 2861} RingBufCharDriver;
51767e7c 2862
3949e594 2863static size_t ringbuf_count(const CharDriverState *chr)
51767e7c 2864{
3949e594 2865 const RingBufCharDriver *d = chr->opaque;
51767e7c 2866
5c230105 2867 return d->prod - d->cons;
51767e7c
LL
2868}
2869
3949e594 2870static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
51767e7c 2871{
3949e594 2872 RingBufCharDriver *d = chr->opaque;
51767e7c
LL
2873 int i;
2874
2875 if (!buf || (len < 0)) {
2876 return -1;
2877 }
2878
2879 for (i = 0; i < len; i++ ) {
5c230105
MA
2880 d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2881 if (d->prod - d->cons > d->size) {
51767e7c
LL
2882 d->cons = d->prod - d->size;
2883 }
2884 }
2885
2886 return 0;
2887}
2888
3949e594 2889static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
51767e7c 2890{
3949e594 2891 RingBufCharDriver *d = chr->opaque;
51767e7c
LL
2892 int i;
2893
5c230105
MA
2894 for (i = 0; i < len && d->cons != d->prod; i++) {
2895 buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
51767e7c
LL
2896 }
2897
2898 return i;
2899}
2900
3949e594 2901static void ringbuf_chr_close(struct CharDriverState *chr)
51767e7c 2902{
3949e594 2903 RingBufCharDriver *d = chr->opaque;
51767e7c
LL
2904
2905 g_free(d->cbuf);
2906 g_free(d);
2907 chr->opaque = NULL;
2908}
2909
3949e594 2910static CharDriverState *qemu_chr_open_ringbuf(QemuOpts *opts)
51767e7c
LL
2911{
2912 CharDriverState *chr;
3949e594 2913 RingBufCharDriver *d;
51767e7c
LL
2914
2915 chr = g_malloc0(sizeof(CharDriverState));
2916 d = g_malloc(sizeof(*d));
2917
de1cc36e 2918 d->size = qemu_opt_get_size(opts, "size", 0);
51767e7c 2919 if (d->size == 0) {
de1cc36e 2920 d->size = 65536;
51767e7c
LL
2921 }
2922
2923 /* The size must be power of 2 */
2924 if (d->size & (d->size - 1)) {
3949e594 2925 error_report("size of ringbuf device must be power of two");
51767e7c
LL
2926 goto fail;
2927 }
2928
2929 d->prod = 0;
2930 d->cons = 0;
2931 d->cbuf = g_malloc0(d->size);
2932
2933 chr->opaque = d;
3949e594
MA
2934 chr->chr_write = ringbuf_chr_write;
2935 chr->chr_close = ringbuf_chr_close;
51767e7c
LL
2936
2937 return chr;
2938
2939fail:
2940 g_free(d);
2941 g_free(chr);
2942 return NULL;
2943}
2944
3949e594 2945static bool chr_is_ringbuf(const CharDriverState *chr)
1f590cf9 2946{
3949e594 2947 return chr->chr_write == ringbuf_chr_write;
1f590cf9
LL
2948}
2949
3949e594 2950void qmp_ringbuf_write(const char *device, const char *data,
82e59a67 2951 bool has_format, enum DataFormat format,
1f590cf9
LL
2952 Error **errp)
2953{
2954 CharDriverState *chr;
c4f331b6 2955 const uint8_t *write_data;
1f590cf9 2956 int ret;
c4f331b6 2957 size_t write_count;
1f590cf9
LL
2958
2959 chr = qemu_chr_find(device);
2960 if (!chr) {
1a69278e 2961 error_setg(errp, "Device '%s' not found", device);
1f590cf9
LL
2962 return;
2963 }
2964
3949e594
MA
2965 if (!chr_is_ringbuf(chr)) {
2966 error_setg(errp,"%s is not a ringbuf device", device);
1f590cf9
LL
2967 return;
2968 }
2969
1f590cf9
LL
2970 if (has_format && (format == DATA_FORMAT_BASE64)) {
2971 write_data = g_base64_decode(data, &write_count);
2972 } else {
2973 write_data = (uint8_t *)data;
82e59a67 2974 write_count = strlen(data);
1f590cf9
LL
2975 }
2976
3949e594 2977 ret = ringbuf_chr_write(chr, write_data, write_count);
1f590cf9 2978
13289fb5
MA
2979 if (write_data != (uint8_t *)data) {
2980 g_free((void *)write_data);
2981 }
2982
1f590cf9
LL
2983 if (ret < 0) {
2984 error_setg(errp, "Failed to write to device %s", device);
2985 return;
2986 }
2987}
2988
3949e594 2989char *qmp_ringbuf_read(const char *device, int64_t size,
3ab651fc
MA
2990 bool has_format, enum DataFormat format,
2991 Error **errp)
49b6d722
LL
2992{
2993 CharDriverState *chr;
c4f331b6 2994 uint8_t *read_data;
49b6d722 2995 size_t count;
3ab651fc 2996 char *data;
49b6d722
LL
2997
2998 chr = qemu_chr_find(device);
2999 if (!chr) {
1a69278e 3000 error_setg(errp, "Device '%s' not found", device);
49b6d722
LL
3001 return NULL;
3002 }
3003
3949e594
MA
3004 if (!chr_is_ringbuf(chr)) {
3005 error_setg(errp,"%s is not a ringbuf device", device);
49b6d722
LL
3006 return NULL;
3007 }
3008
3009 if (size <= 0) {
3010 error_setg(errp, "size must be greater than zero");
3011 return NULL;
3012 }
3013
3949e594 3014 count = ringbuf_count(chr);
49b6d722 3015 size = size > count ? count : size;
44f3bcd2 3016 read_data = g_malloc(size + 1);
49b6d722 3017
3949e594 3018 ringbuf_chr_read(chr, read_data, size);
49b6d722
LL
3019
3020 if (has_format && (format == DATA_FORMAT_BASE64)) {
3ab651fc 3021 data = g_base64_encode(read_data, size);
13289fb5 3022 g_free(read_data);
49b6d722 3023 } else {
3949e594
MA
3024 /*
3025 * FIXME should read only complete, valid UTF-8 characters up
3026 * to @size bytes. Invalid sequences should be replaced by a
3027 * suitable replacement character. Except when (and only
3028 * when) ring buffer lost characters since last read, initial
3029 * continuation characters should be dropped.
3030 */
44f3bcd2 3031 read_data[size] = 0;
3ab651fc 3032 data = (char *)read_data;
49b6d722
LL
3033 }
3034
3ab651fc 3035 return data;
49b6d722
LL
3036}
3037
33521634 3038QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
191bc01b 3039{
6ea314d9 3040 char host[65], port[33], width[8], height[8];
aeb2c47a 3041 int pos;
7d31544f 3042 const char *p;
191bc01b 3043 QemuOpts *opts;
8be7e7e4 3044 Error *local_err = NULL;
191bc01b 3045
8be7e7e4
LC
3046 opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3047 if (error_is_set(&local_err)) {
3048 qerror_report_err(local_err);
3049 error_free(local_err);
191bc01b 3050 return NULL;
8be7e7e4 3051 }
191bc01b 3052
7591c5c1
GH
3053 if (strstart(filename, "mon:", &p)) {
3054 filename = p;
3055 qemu_opt_set(opts, "mux", "on");
3056 }
3057
f0457e8d
GH
3058 if (strcmp(filename, "null") == 0 ||
3059 strcmp(filename, "pty") == 0 ||
3060 strcmp(filename, "msmouse") == 0 ||
dc1c21e6 3061 strcmp(filename, "braille") == 0 ||
f0457e8d 3062 strcmp(filename, "stdio") == 0) {
4490dadf 3063 qemu_opt_set(opts, "backend", filename);
191bc01b
GH
3064 return opts;
3065 }
6ea314d9
GH
3066 if (strstart(filename, "vc", &p)) {
3067 qemu_opt_set(opts, "backend", "vc");
3068 if (*p == ':') {
3069 if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
3070 /* pixels */
3071 qemu_opt_set(opts, "width", width);
3072 qemu_opt_set(opts, "height", height);
3073 } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
3074 /* chars */
3075 qemu_opt_set(opts, "cols", width);
3076 qemu_opt_set(opts, "rows", height);
3077 } else {
3078 goto fail;
3079 }
3080 }
3081 return opts;
3082 }
d6c983cd
GH
3083 if (strcmp(filename, "con:") == 0) {
3084 qemu_opt_set(opts, "backend", "console");
3085 return opts;
3086 }
48b76496
GH
3087 if (strstart(filename, "COM", NULL)) {
3088 qemu_opt_set(opts, "backend", "serial");
3089 qemu_opt_set(opts, "path", filename);
3090 return opts;
3091 }
7d31544f
GH
3092 if (strstart(filename, "file:", &p)) {
3093 qemu_opt_set(opts, "backend", "file");
3094 qemu_opt_set(opts, "path", p);
3095 return opts;
3096 }
3097 if (strstart(filename, "pipe:", &p)) {
3098 qemu_opt_set(opts, "backend", "pipe");
3099 qemu_opt_set(opts, "path", p);
3100 return opts;
3101 }
aeb2c47a
GH
3102 if (strstart(filename, "tcp:", &p) ||
3103 strstart(filename, "telnet:", &p)) {
3104 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3105 host[0] = 0;
3106 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3107 goto fail;
3108 }
3109 qemu_opt_set(opts, "backend", "socket");
3110 qemu_opt_set(opts, "host", host);
3111 qemu_opt_set(opts, "port", port);
3112 if (p[pos] == ',') {
3113 if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3114 goto fail;
3115 }
3116 if (strstart(filename, "telnet:", &p))
3117 qemu_opt_set(opts, "telnet", "on");
3118 return opts;
3119 }
7e1b35b4
GH
3120 if (strstart(filename, "udp:", &p)) {
3121 qemu_opt_set(opts, "backend", "udp");
3122 if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3123 host[0] = 0;
39324ca4 3124 if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
7e1b35b4
GH
3125 goto fail;
3126 }
3127 }
3128 qemu_opt_set(opts, "host", host);
3129 qemu_opt_set(opts, "port", port);
3130 if (p[pos] == '@') {
3131 p += pos + 1;
3132 if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3133 host[0] = 0;
3134 if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
7e1b35b4
GH
3135 goto fail;
3136 }
3137 }
3138 qemu_opt_set(opts, "localaddr", host);
3139 qemu_opt_set(opts, "localport", port);
3140 }
3141 return opts;
3142 }
aeb2c47a
GH
3143 if (strstart(filename, "unix:", &p)) {
3144 qemu_opt_set(opts, "backend", "socket");
3145 if (qemu_opts_do_parse(opts, p, "path") != 0)
3146 goto fail;
3147 return opts;
3148 }
48b76496
GH
3149 if (strstart(filename, "/dev/parport", NULL) ||
3150 strstart(filename, "/dev/ppi", NULL)) {
3151 qemu_opt_set(opts, "backend", "parport");
3152 qemu_opt_set(opts, "path", filename);
3153 return opts;
3154 }
3155 if (strstart(filename, "/dev/", NULL)) {
3156 qemu_opt_set(opts, "backend", "tty");
3157 qemu_opt_set(opts, "path", filename);
3158 return opts;
3159 }
191bc01b 3160
aeb2c47a 3161fail:
191bc01b
GH
3162 qemu_opts_del(opts);
3163 return NULL;
3164}
3165
88a946d3
GH
3166#ifdef HAVE_CHARDEV_PARPORT
3167
3168static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
3169{
3170 const char *filename = qemu_opt_get(opts, "path");
3171 int fd;
3172
3173 fd = qemu_open(filename, O_RDWR);
3174 if (fd < 0) {
3175 return NULL;
3176 }
3177 return qemu_chr_open_pp_fd(fd);
3178}
3179
3180#endif
3181
191bc01b
GH
3182static const struct {
3183 const char *name;
1f51470d 3184 CharDriverState *(*open)(QemuOpts *opts);
191bc01b
GH
3185} backend_table[] = {
3186 { .name = "null", .open = qemu_chr_open_null },
aeb2c47a 3187 { .name = "socket", .open = qemu_chr_open_socket },
7e1b35b4 3188 { .name = "udp", .open = qemu_chr_open_udp },
f0457e8d 3189 { .name = "msmouse", .open = qemu_chr_open_msmouse },
d82831db 3190 { .name = "vc", .open = vc_init },
3949e594 3191 { .name = "memory", .open = qemu_chr_open_ringbuf },
7d31544f
GH
3192#ifdef _WIN32
3193 { .name = "file", .open = qemu_chr_open_win_file_out },
3194 { .name = "pipe", .open = qemu_chr_open_win_pipe },
d6c983cd 3195 { .name = "console", .open = qemu_chr_open_win_con },
48b76496 3196 { .name = "serial", .open = qemu_chr_open_win },
db418a0a 3197 { .name = "stdio", .open = qemu_chr_open_win_stdio },
7d31544f
GH
3198#else
3199 { .name = "file", .open = qemu_chr_open_file_out },
3200 { .name = "pipe", .open = qemu_chr_open_pipe },
3c17affb 3201 { .name = "stdio", .open = qemu_chr_open_stdio },
7d31544f 3202#endif
dc1c21e6
GH
3203#ifdef CONFIG_BRLAPI
3204 { .name = "braille", .open = chr_baum_init },
3205#endif
e551498e 3206#ifdef HAVE_CHARDEV_TTY
48b76496 3207 { .name = "tty", .open = qemu_chr_open_tty },
d59044ef 3208 { .name = "serial", .open = qemu_chr_open_tty },
e551498e 3209 { .name = "pty", .open = qemu_chr_open_pty },
48b76496 3210#endif
e551498e 3211#ifdef HAVE_CHARDEV_PARPORT
88a946d3 3212 { .name = "parallel", .open = qemu_chr_open_pp },
48b76496
GH
3213 { .name = "parport", .open = qemu_chr_open_pp },
3214#endif
cbcc6336
AL
3215#ifdef CONFIG_SPICE
3216 { .name = "spicevmc", .open = qemu_chr_open_spice },
5a49d3e9
MAL
3217#if SPICE_SERVER_VERSION >= 0x000c02
3218 { .name = "spiceport", .open = qemu_chr_open_spice_port },
3219#endif
cbcc6336 3220#endif
191bc01b
GH
3221};
3222
f69554b9 3223CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
bd2d80b2
GH
3224 void (*init)(struct CharDriverState *s),
3225 Error **errp)
191bc01b
GH
3226{
3227 CharDriverState *chr;
3228 int i;
3229
3230 if (qemu_opts_id(opts) == NULL) {
312fd5f2 3231 error_setg(errp, "chardev: no id specified");
2274ae9d 3232 goto err;
191bc01b
GH
3233 }
3234
1bbd185f 3235 if (qemu_opt_get(opts, "backend") == NULL) {
312fd5f2 3236 error_setg(errp, "chardev: \"%s\" missing backend",
bd2d80b2 3237 qemu_opts_id(opts));
2274ae9d 3238 goto err;
1bbd185f 3239 }
191bc01b
GH
3240 for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
3241 if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
3242 break;
3243 }
3244 if (i == ARRAY_SIZE(backend_table)) {
312fd5f2 3245 error_setg(errp, "chardev: backend \"%s\" not found",
bd2d80b2 3246 qemu_opt_get(opts, "backend"));
2274ae9d 3247 goto err;
191bc01b
GH
3248 }
3249
1f51470d
MA
3250 chr = backend_table[i].open(opts);
3251 if (!chr) {
312fd5f2 3252 error_setg(errp, "chardev: opening backend \"%s\" failed",
bd2d80b2 3253 qemu_opt_get(opts, "backend"));
2274ae9d 3254 goto err;
191bc01b
GH
3255 }
3256
3257 if (!chr->filename)
7267c094 3258 chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
191bc01b 3259 chr->init = init;
72cf2d4f 3260 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
7591c5c1
GH
3261
3262 if (qemu_opt_get_bool(opts, "mux", 0)) {
3263 CharDriverState *base = chr;
3264 int len = strlen(qemu_opts_id(opts)) + 6;
7267c094 3265 base->label = g_malloc(len);
7591c5c1
GH
3266 snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3267 chr = qemu_chr_open_mux(base);
3268 chr->filename = base->filename;
d5b27167 3269 chr->avail_connections = MAX_MUX;
72cf2d4f 3270 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
d5b27167
KK
3271 } else {
3272 chr->avail_connections = 1;
7591c5c1 3273 }
7267c094 3274 chr->label = g_strdup(qemu_opts_id(opts));
2274ae9d 3275 chr->opts = opts;
191bc01b 3276 return chr;
2274ae9d
GH
3277
3278err:
3279 qemu_opts_del(opts);
3280 return NULL;
191bc01b
GH
3281}
3282
27143a44 3283CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
6f97dba0
AL
3284{
3285 const char *p;
3286 CharDriverState *chr;
191bc01b 3287 QemuOpts *opts;
bd2d80b2 3288 Error *err = NULL;
191bc01b 3289
c845f401
GH
3290 if (strstart(filename, "chardev:", &p)) {
3291 return qemu_chr_find(p);
3292 }
3293
191bc01b 3294 opts = qemu_chr_parse_compat(label, filename);
7e1b35b4
GH
3295 if (!opts)
3296 return NULL;
6f97dba0 3297
bd2d80b2
GH
3298 chr = qemu_chr_new_from_opts(opts, init, &err);
3299 if (error_is_set(&err)) {
3300 fprintf(stderr, "%s\n", error_get_pretty(err));
3301 error_free(err);
3302 }
7e1b35b4
GH
3303 if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3304 monitor_init(chr, MONITOR_USE_READLINE);
6f97dba0
AL
3305 }
3306 return chr;
3307}
3308
15f31519 3309void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
c48855e1
PB
3310{
3311 if (chr->chr_set_echo) {
3312 chr->chr_set_echo(chr, echo);
3313 }
3314}
3315
c9d830ed 3316void qemu_chr_fe_open(struct CharDriverState *chr)
7c32c4fe
HG
3317{
3318 if (chr->chr_guest_open) {
3319 chr->chr_guest_open(chr);
3320 }
3321}
3322
2817822d 3323void qemu_chr_fe_close(struct CharDriverState *chr)
7c32c4fe
HG
3324{
3325 if (chr->chr_guest_close) {
3326 chr->chr_guest_close(chr);
3327 }
3328}
3329
23673ca7
AL
3330guint qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3331 GIOFunc func, void *user_data)
3332{
3333 GSource *src;
3334 guint tag;
3335
3336 if (s->chr_add_watch == NULL) {
3337 return -ENOSYS;
3338 }
3339
3340 src = s->chr_add_watch(s, cond);
3341 g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3342 tag = g_source_attach(src, NULL);
3343 g_source_unref(src);
3344
3345 return tag;
3346}
3347
70f24fb6 3348void qemu_chr_delete(CharDriverState *chr)
6f97dba0 3349{
72cf2d4f 3350 QTAILQ_REMOVE(&chardevs, chr, next);
2274ae9d 3351 if (chr->chr_close) {
6f97dba0 3352 chr->chr_close(chr);
2274ae9d 3353 }
7267c094
AL
3354 g_free(chr->filename);
3355 g_free(chr->label);
2274ae9d
GH
3356 if (chr->opts) {
3357 qemu_opts_del(chr->opts);
3358 }
7267c094 3359 g_free(chr);
6f97dba0
AL
3360}
3361
c5a415a0 3362ChardevInfoList *qmp_query_chardev(Error **errp)
6f97dba0 3363{
c5a415a0 3364 ChardevInfoList *chr_list = NULL;
6f97dba0
AL
3365 CharDriverState *chr;
3366
72cf2d4f 3367 QTAILQ_FOREACH(chr, &chardevs, next) {
c5a415a0
LC
3368 ChardevInfoList *info = g_malloc0(sizeof(*info));
3369 info->value = g_malloc0(sizeof(*info->value));
3370 info->value->label = g_strdup(chr->label);
3371 info->value->filename = g_strdup(chr->filename);
3372
3373 info->next = chr_list;
3374 chr_list = info;
6f97dba0 3375 }
588b3832 3376
c5a415a0 3377 return chr_list;
6f97dba0 3378}
c845f401
GH
3379
3380CharDriverState *qemu_chr_find(const char *name)
3381{
3382 CharDriverState *chr;
3383
72cf2d4f 3384 QTAILQ_FOREACH(chr, &chardevs, next) {
c845f401
GH
3385 if (strcmp(chr->label, name) != 0)
3386 continue;
3387 return chr;
3388 }
3389 return NULL;
3390}
0beb4942
AL
3391
3392/* Get a character (serial) device interface. */
3393CharDriverState *qemu_char_get_next_serial(void)
3394{
3395 static int next_serial;
3396
3397 /* FIXME: This function needs to go away: use chardev properties! */
3398 return serial_hds[next_serial++];
3399}
3400
4d454574
PB
3401QemuOptsList qemu_chardev_opts = {
3402 .name = "chardev",
3403 .implied_opt_name = "backend",
3404 .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3405 .desc = {
3406 {
3407 .name = "backend",
3408 .type = QEMU_OPT_STRING,
3409 },{
3410 .name = "path",
3411 .type = QEMU_OPT_STRING,
3412 },{
3413 .name = "host",
3414 .type = QEMU_OPT_STRING,
3415 },{
3416 .name = "port",
3417 .type = QEMU_OPT_STRING,
3418 },{
3419 .name = "localaddr",
3420 .type = QEMU_OPT_STRING,
3421 },{
3422 .name = "localport",
3423 .type = QEMU_OPT_STRING,
3424 },{
3425 .name = "to",
3426 .type = QEMU_OPT_NUMBER,
3427 },{
3428 .name = "ipv4",
3429 .type = QEMU_OPT_BOOL,
3430 },{
3431 .name = "ipv6",
3432 .type = QEMU_OPT_BOOL,
3433 },{
3434 .name = "wait",
3435 .type = QEMU_OPT_BOOL,
3436 },{
3437 .name = "server",
3438 .type = QEMU_OPT_BOOL,
3439 },{
3440 .name = "delay",
3441 .type = QEMU_OPT_BOOL,
3442 },{
3443 .name = "telnet",
3444 .type = QEMU_OPT_BOOL,
3445 },{
3446 .name = "width",
3447 .type = QEMU_OPT_NUMBER,
3448 },{
3449 .name = "height",
3450 .type = QEMU_OPT_NUMBER,
3451 },{
3452 .name = "cols",
3453 .type = QEMU_OPT_NUMBER,
3454 },{
3455 .name = "rows",
3456 .type = QEMU_OPT_NUMBER,
3457 },{
3458 .name = "mux",
3459 .type = QEMU_OPT_BOOL,
3460 },{
3461 .name = "signal",
3462 .type = QEMU_OPT_BOOL,
3463 },{
3464 .name = "name",
3465 .type = QEMU_OPT_STRING,
3466 },{
3467 .name = "debug",
3468 .type = QEMU_OPT_NUMBER,
51767e7c 3469 },{
3949e594 3470 .name = "size",
de1cc36e 3471 .type = QEMU_OPT_SIZE,
4d454574
PB
3472 },
3473 { /* end of list */ }
3474 },
3475};
f1a1a356 3476
ffbdbe59
GH
3477#ifdef _WIN32
3478
3479static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3480{
3481 HANDLE out;
3482
3483 if (file->in) {
3484 error_setg(errp, "input file not supported");
3485 return NULL;
3486 }
3487
3488 out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3489 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3490 if (out == INVALID_HANDLE_VALUE) {
3491 error_setg(errp, "open %s failed", file->out);
3492 return NULL;
3493 }
3494 return qemu_chr_open_win_file(out);
3495}
3496
d36b2b90
MA
3497static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3498 Error **errp)
d59044ef 3499{
d36b2b90
MA
3500 return qemu_chr_open_win_path(serial->device);
3501}
3502
3503static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3504 Error **errp)
3505{
3506 error_setg(errp, "character device backend type 'parallel' not supported");
3507 return NULL;
d59044ef
GH
3508}
3509
ffbdbe59
GH
3510#else /* WIN32 */
3511
3512static int qmp_chardev_open_file_source(char *src, int flags,
3513 Error **errp)
3514{
3515 int fd = -1;
3516
3517 TFR(fd = qemu_open(src, flags, 0666));
3518 if (fd == -1) {
3519 error_setg(errp, "open %s: %s", src, strerror(errno));
3520 }
3521 return fd;
3522}
3523
3524static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3525{
3526 int flags, in = -1, out = -1;
3527
3528 flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3529 out = qmp_chardev_open_file_source(file->out, flags, errp);
3530 if (error_is_set(errp)) {
3531 return NULL;
3532 }
3533
3534 if (file->in) {
3535 flags = O_RDONLY;
3536 in = qmp_chardev_open_file_source(file->in, flags, errp);
3537 if (error_is_set(errp)) {
3538 qemu_close(out);
3539 return NULL;
3540 }
3541 }
3542
3543 return qemu_chr_open_fd(in, out);
3544}
3545
d36b2b90
MA
3546static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3547 Error **errp)
d59044ef 3548{
d59044ef 3549#ifdef HAVE_CHARDEV_TTY
d36b2b90
MA
3550 int fd;
3551
3552 fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3553 if (error_is_set(errp)) {
3554 return NULL;
39099991 3555 }
d36b2b90
MA
3556 socket_set_nonblock(fd);
3557 return qemu_chr_open_tty_fd(fd);
3558#else
3559 error_setg(errp, "character device backend type 'serial' not supported");
3560 return NULL;
88a946d3 3561#endif
d36b2b90
MA
3562}
3563
3564static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3565 Error **errp)
3566{
88a946d3 3567#ifdef HAVE_CHARDEV_PARPORT
d36b2b90
MA
3568 int fd;
3569
3570 fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3571 if (error_is_set(errp)) {
d59044ef
GH
3572 return NULL;
3573 }
d36b2b90
MA
3574 return qemu_chr_open_pp_fd(fd);
3575#else
3576 error_setg(errp, "character device backend type 'parallel' not supported");
3577 return NULL;
3578#endif
d59044ef
GH
3579}
3580
ffbdbe59
GH
3581#endif /* WIN32 */
3582
f6bd5d6e
GH
3583static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3584 Error **errp)
3585{
3586 SocketAddress *addr = sock->addr;
3587 bool do_nodelay = sock->has_nodelay ? sock->nodelay : false;
3588 bool is_listen = sock->has_server ? sock->server : true;
3589 bool is_telnet = sock->has_telnet ? sock->telnet : false;
3590 bool is_waitconnect = sock->has_wait ? sock->wait : false;
3591 int fd;
3592
3593 if (is_listen) {
3594 fd = socket_listen(addr, errp);
3595 } else {
3596 fd = socket_connect(addr, errp, NULL, NULL);
3597 }
3598 if (error_is_set(errp)) {
3599 return NULL;
3600 }
3601 return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3602 is_telnet, is_waitconnect, errp);
3603}
3604
f1a1a356
GH
3605ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3606 Error **errp)
3607{
3608 ChardevReturn *ret = g_new0(ChardevReturn, 1);
3609 CharDriverState *chr = NULL;
3610
3611 chr = qemu_chr_find(id);
3612 if (chr) {
3613 error_setg(errp, "Chardev '%s' already exists", id);
3614 g_free(ret);
3615 return NULL;
3616 }
3617
3618 switch (backend->kind) {
ffbdbe59
GH
3619 case CHARDEV_BACKEND_KIND_FILE:
3620 chr = qmp_chardev_open_file(backend->file, errp);
3621 break;
d36b2b90
MA
3622 case CHARDEV_BACKEND_KIND_SERIAL:
3623 chr = qmp_chardev_open_serial(backend->serial, errp);
3624 break;
3625 case CHARDEV_BACKEND_KIND_PARALLEL:
3626 chr = qmp_chardev_open_parallel(backend->parallel, errp);
d59044ef 3627 break;
f6bd5d6e
GH
3628 case CHARDEV_BACKEND_KIND_SOCKET:
3629 chr = qmp_chardev_open_socket(backend->socket, errp);
3630 break;
0a1a7fab
GH
3631#ifdef HAVE_CHARDEV_TTY
3632 case CHARDEV_BACKEND_KIND_PTY:
3633 {
3634 /* qemu_chr_open_pty sets "path" in opts */
3635 QemuOpts *opts;
3636 opts = qemu_opts_create_nofail(qemu_find_opts("chardev"));
3637 chr = qemu_chr_open_pty(opts);
3638 ret->pty = g_strdup(qemu_opt_get(opts, "path"));
3639 ret->has_pty = true;
3640 qemu_opts_del(opts);
3641 break;
3642 }
3643#endif
f1a1a356
GH
3644 case CHARDEV_BACKEND_KIND_NULL:
3645 chr = qemu_chr_open_null(NULL);
3646 break;
3647 default:
3648 error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3649 break;
3650 }
3651
3652 if (chr == NULL && !error_is_set(errp)) {
3653 error_setg(errp, "Failed to create chardev");
3654 }
3655 if (chr) {
3656 chr->label = g_strdup(id);
3657 chr->avail_connections = 1;
3658 QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3659 return ret;
3660 } else {
3661 g_free(ret);
3662 return NULL;
3663 }
3664}
3665
3666void qmp_chardev_remove(const char *id, Error **errp)
3667{
3668 CharDriverState *chr;
3669
3670 chr = qemu_chr_find(id);
3671 if (NULL == chr) {
3672 error_setg(errp, "Chardev '%s' not found", id);
3673 return;
3674 }
3675 if (chr->chr_can_read || chr->chr_read ||
3676 chr->chr_event || chr->handler_opaque) {
3677 error_setg(errp, "Chardev '%s' is busy", id);
3678 return;
3679 }
3680 qemu_chr_delete(chr);
3681}