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