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