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