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