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