Home | History | Annotate | Download | only in qemu
      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 "sockets.h"
     26 #include "net.h"
     27 #include "monitor.h"
     28 #include "console.h"
     29 #include "sysemu.h"
     30 #include "qemu-timer.h"
     31 #include "qemu-char.h"
     32 #include "block.h"
     33 #include "hw/usb.h"
     34 #include "hw/baum.h"
     35 #include "hw/msmouse.h"
     36 
     37 #include <unistd.h>
     38 #include <fcntl.h>
     39 #include <signal.h>
     40 #include <time.h>
     41 #include <errno.h>
     42 #include <sys/time.h>
     43 #include <zlib.h>
     44 
     45 #ifndef _WIN32
     46 #include <sys/times.h>
     47 #include <sys/wait.h>
     48 #include <termios.h>
     49 #include <sys/mman.h>
     50 #include <sys/ioctl.h>
     51 #include <sys/resource.h>
     52 #include <sys/socket.h>
     53 #include <netinet/in.h>
     54 #include <net/if.h>
     55 #ifdef __NetBSD__
     56 #include <net/if_tap.h>
     57 #endif
     58 #ifdef __linux__
     59 #include <linux/if_tun.h>
     60 #endif
     61 #include <arpa/inet.h>
     62 #include <dirent.h>
     63 #include <netdb.h>
     64 #include <sys/select.h>
     65 #ifdef CONFIG_BSD
     66 #include <sys/stat.h>
     67 #ifdef __FreeBSD__
     68 #include <libutil.h>
     69 #include <dev/ppbus/ppi.h>
     70 #include <dev/ppbus/ppbconf.h>
     71 #elif defined(__DragonFly__)
     72 #include <libutil.h>
     73 #include <dev/misc/ppi/ppi.h>
     74 #include <bus/ppbus/ppbconf.h>
     75 #else
     76 #include <util.h>
     77 #endif
     78 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
     79 #include <freebsd/stdlib.h>
     80 #else
     81 #ifdef __linux__
     82 #include <pty.h>
     83 
     84 #include <linux/ppdev.h>
     85 #include <linux/parport.h>
     86 #endif
     87 #ifdef __sun__
     88 #include <sys/stat.h>
     89 #include <sys/ethernet.h>
     90 #include <sys/sockio.h>
     91 #include <netinet/arp.h>
     92 #include <netinet/in.h>
     93 #include <netinet/in_systm.h>
     94 #include <netinet/ip.h>
     95 #include <netinet/ip_icmp.h> // must come after ip.h
     96 #include <netinet/udp.h>
     97 #include <netinet/tcp.h>
     98 #include <net/if.h>
     99 #include <syslog.h>
    100 #include <stropts.h>
    101 #endif
    102 #endif
    103 #endif
    104 
    105 #include "qemu_socket.h"
    106 
    107 /* ANDROID */
    108 #include "charpipe.h"
    109 #include "modem_driver.h"
    110 #include "android/gps.h"
    111 #include "android/hw-kmsg.h"
    112 #include "android/hw-qemud.h"
    113 
    114 /***********************************************************/
    115 /* character device */
    116 
    117 static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
    118     QTAILQ_HEAD_INITIALIZER(chardevs);
    119 static int initial_reset_issued;
    120 
    121 static void qemu_chr_event(CharDriverState *s, int event)
    122 {
    123     if (!s->chr_event)
    124         return;
    125     s->chr_event(s->handler_opaque, event);
    126 }
    127 
    128 static void qemu_chr_reset_bh(void *opaque)
    129 {
    130     CharDriverState *s = opaque;
    131     qemu_chr_event(s, CHR_EVENT_OPENED);
    132     qemu_bh_delete(s->bh);
    133     s->bh = NULL;
    134 }
    135 
    136 void qemu_chr_reset(CharDriverState *s)
    137 {
    138     if (s->bh == NULL && initial_reset_issued) {
    139 	s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
    140 	qemu_bh_schedule(s->bh);
    141     }
    142 }
    143 
    144 void qemu_chr_initial_reset(void)
    145 {
    146     CharDriverState *chr;
    147 
    148     initial_reset_issued = 1;
    149 
    150     QTAILQ_FOREACH(chr, &chardevs, next) {
    151         qemu_chr_reset(chr);
    152     }
    153 }
    154 
    155 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
    156 {
    157     return s->chr_write(s, buf, len);
    158 }
    159 
    160 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
    161 {
    162     if (!s->chr_ioctl)
    163         return -ENOTSUP;
    164     return s->chr_ioctl(s, cmd, arg);
    165 }
    166 
    167 int qemu_chr_can_read(CharDriverState *s)
    168 {
    169     if (!s->chr_can_read)
    170         return 0;
    171     return s->chr_can_read(s->handler_opaque);
    172 }
    173 
    174 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
    175 {
    176     s->chr_read(s->handler_opaque, buf, len);
    177 }
    178 
    179 void qemu_chr_accept_input(CharDriverState *s)
    180 {
    181     if (s->chr_accept_input)
    182         s->chr_accept_input(s);
    183 }
    184 
    185 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
    186 {
    187     char buf[4096];
    188     va_list ap;
    189     va_start(ap, fmt);
    190     vsnprintf(buf, sizeof(buf), fmt, ap);
    191     qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
    192     va_end(ap);
    193 }
    194 
    195 void qemu_chr_send_event(CharDriverState *s, int event)
    196 {
    197     if (s->chr_send_event)
    198         s->chr_send_event(s, event);
    199 }
    200 
    201 void qemu_chr_add_handlers(CharDriverState *s,
    202                            IOCanRWHandler *fd_can_read,
    203                            IOReadHandler *fd_read,
    204                            IOEventHandler *fd_event,
    205                            void *opaque)
    206 {
    207     s->chr_can_read = fd_can_read;
    208     s->chr_read = fd_read;
    209     s->chr_event = fd_event;
    210     s->handler_opaque = opaque;
    211     if (s->chr_update_read_handler)
    212         s->chr_update_read_handler(s);
    213 }
    214 
    215 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
    216 {
    217     return len;
    218 }
    219 
    220 static CharDriverState *qemu_chr_open_null(void)
    221 {
    222     CharDriverState *chr;
    223 
    224     chr = qemu_mallocz(sizeof(CharDriverState));
    225     chr->chr_write = null_chr_write;
    226     return chr;
    227 }
    228 
    229 /* MUX driver for serial I/O splitting */
    230 #define MAX_MUX 4
    231 #define MUX_BUFFER_SIZE 32	/* Must be a power of 2.  */
    232 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
    233 typedef struct {
    234     IOCanRWHandler *chr_can_read[MAX_MUX];
    235     IOReadHandler *chr_read[MAX_MUX];
    236     IOEventHandler *chr_event[MAX_MUX];
    237     void *ext_opaque[MAX_MUX];
    238     CharDriverState *drv;
    239     int mux_cnt;
    240     int term_got_escape;
    241     int max_size;
    242     /* Intermediate input buffer allows to catch escape sequences even if the
    243        currently active device is not accepting any input - but only until it
    244        is full as well. */
    245     unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
    246     int prod[MAX_MUX];
    247     int cons[MAX_MUX];
    248     int timestamps;
    249     int linestart;
    250     int64_t timestamps_start;
    251 } MuxDriver;
    252 
    253 
    254 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
    255 {
    256     MuxDriver *d = chr->opaque;
    257     int ret;
    258     if (!d->timestamps) {
    259         ret = d->drv->chr_write(d->drv, buf, len);
    260     } else {
    261         int i;
    262 
    263         ret = 0;
    264         for (i = 0; i < len; i++) {
    265             if (d->linestart) {
    266                 char buf1[64];
    267                 int64_t ti;
    268                 int secs;
    269 
    270                 ti = qemu_get_clock(rt_clock);
    271                 if (d->timestamps_start == -1)
    272                     d->timestamps_start = ti;
    273                 ti -= d->timestamps_start;
    274                 secs = ti / 1000;
    275                 snprintf(buf1, sizeof(buf1),
    276                          "[%02d:%02d:%02d.%03d] ",
    277                          secs / 3600,
    278                          (secs / 60) % 60,
    279                          secs % 60,
    280                          (int)(ti % 1000));
    281                 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
    282                 d->linestart = 0;
    283             }
    284             ret += d->drv->chr_write(d->drv, buf+i, 1);
    285             if (buf[i] == '\n') {
    286                 d->linestart = 1;
    287             }
    288         }
    289     }
    290     return ret;
    291 }
    292 
    293 static const char * const mux_help[] = {
    294     "% h    print this help\n\r",
    295     "% x    exit emulator\n\r",
    296     "% s    save disk data back to file (if -snapshot)\n\r",
    297     "% t    toggle console timestamps\n\r"
    298     "% b    send break (magic sysrq)\n\r",
    299     "% c    switch between console and monitor\n\r",
    300     "% %  sends %\n\r",
    301     NULL
    302 };
    303 
    304 int term_escape_char = 0x01; /* ctrl-a is used for escape */
    305 static void mux_print_help(CharDriverState *chr)
    306 {
    307     int i, j;
    308     char ebuf[15] = "Escape-Char";
    309     char cbuf[50] = "\n\r";
    310 
    311     if (term_escape_char > 0 && term_escape_char < 26) {
    312         snprintf(cbuf, sizeof(cbuf), "\n\r");
    313         snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
    314     } else {
    315         snprintf(cbuf, sizeof(cbuf),
    316                  "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
    317                  term_escape_char);
    318     }
    319     chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
    320     for (i = 0; mux_help[i] != NULL; i++) {
    321         for (j=0; mux_help[i][j] != '\0'; j++) {
    322             if (mux_help[i][j] == '%')
    323                 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
    324             else
    325                 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
    326         }
    327     }
    328 }
    329 
    330 static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
    331 {
    332     if (d->chr_event[mux_nr])
    333         d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
    334 }
    335 
    336 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
    337 {
    338     if (d->term_got_escape) {
    339         d->term_got_escape = 0;
    340         if (ch == term_escape_char)
    341             goto send_char;
    342         switch(ch) {
    343         case '?':
    344         case 'h':
    345             mux_print_help(chr);
    346             break;
    347         case 'x':
    348             {
    349                  const char *term =  "QEMU: Terminated\n\r";
    350                  chr->chr_write(chr,(uint8_t *)term,strlen(term));
    351                  exit(0);
    352                  break;
    353             }
    354         case 's':
    355             {
    356                 int i;
    357                 for (i = 0; i < nb_drives; i++) {
    358                         bdrv_commit(drives_table[i].bdrv);
    359                 }
    360             }
    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, chr->focus, CHR_EVENT_MUX_OUT);
    368             chr->focus++;
    369             if (chr->focus >= d->mux_cnt)
    370                 chr->focus = 0;
    371             mux_chr_send_event(d, chr->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     int m = chr->focus;
    391     MuxDriver *d = chr->opaque;
    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 = chr->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 = chr->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     chr->focus = d->mux_cnt;
    463     d->mux_cnt++;
    464 }
    465 
    466 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
    467 {
    468     CharDriverState *chr;
    469     MuxDriver *d;
    470 
    471     chr = qemu_mallocz(sizeof(CharDriverState));
    472     d = qemu_mallocz(sizeof(MuxDriver));
    473 
    474     chr->opaque = d;
    475     d->drv = drv;
    476     chr->focus = -1;
    477     chr->chr_write = mux_chr_write;
    478     chr->chr_update_read_handler = mux_chr_update_read_handler;
    479     chr->chr_accept_input = mux_chr_accept_input;
    480     return chr;
    481 }
    482 
    483 
    484 #ifdef _WIN32
    485 int send_all(int fd, const void *buf, int len1)
    486 {
    487 #if 1
    488 	return socket_send(fd, buf, len1);
    489 #else
    490     int ret, len;
    491 
    492     len = len1;
    493     while (len > 0) {
    494         ret = send(fd, buf, len, 0);
    495         if (ret < 0) {
    496             errno = WSAGetLastError();
    497             if (errno != WSAEWOULDBLOCK && errno != WSAEAGAIN) {
    498                 return -1;
    499             }
    500         } else if (ret == 0) {
    501             break;
    502         } else {
    503             buf += ret;
    504             len -= ret;
    505         }
    506     }
    507     return len1 - len;
    508 #endif
    509 }
    510 
    511 #else
    512 
    513 static int unix_write(int fd, const uint8_t *buf, int len1)
    514 {
    515     int ret, len;
    516 
    517     len = len1;
    518     while (len > 0) {
    519         ret = write(fd, buf, len);
    520         if (ret < 0) {
    521             if (errno != EINTR && errno != EAGAIN)
    522                 return -1;
    523         } else if (ret == 0) {
    524             break;
    525         } else {
    526             buf += ret;
    527             len -= ret;
    528         }
    529     }
    530     return len1 - len;
    531 }
    532 
    533 int send_all(int fd, const void *buf, int len1)
    534 {
    535     return unix_write(fd, buf, len1);
    536 }
    537 #endif /* !_WIN32 */
    538 
    539 #ifndef _WIN32
    540 
    541 typedef struct {
    542     int fd_in, fd_out;
    543     int max_size;
    544 } FDCharDriver;
    545 
    546 #define STDIO_MAX_CLIENTS 1
    547 static int stdio_nb_clients = 0;
    548 
    549 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
    550 {
    551     FDCharDriver *s = chr->opaque;
    552     return send_all(s->fd_out, buf, len);
    553 }
    554 
    555 static int fd_chr_read_poll(void *opaque)
    556 {
    557     CharDriverState *chr = opaque;
    558     FDCharDriver *s = chr->opaque;
    559 
    560     s->max_size = qemu_chr_can_read(chr);
    561     return s->max_size;
    562 }
    563 
    564 static void fd_chr_read(void *opaque)
    565 {
    566     CharDriverState *chr = opaque;
    567     FDCharDriver *s = chr->opaque;
    568     int size, len;
    569     uint8_t buf[1024];
    570 
    571     len = sizeof(buf);
    572     if (len > s->max_size)
    573         len = s->max_size;
    574     if (len == 0)
    575         return;
    576     size = read(s->fd_in, buf, len);
    577     if (size == 0) {
    578         /* FD has been closed. Remove it from the active list.  */
    579         qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
    580         return;
    581     }
    582     if (size > 0) {
    583         qemu_chr_read(chr, buf, size);
    584     }
    585 }
    586 
    587 static void fd_chr_update_read_handler(CharDriverState *chr)
    588 {
    589     FDCharDriver *s = chr->opaque;
    590 
    591     if (s->fd_in >= 0) {
    592         if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
    593         } else {
    594             qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
    595                                  fd_chr_read, NULL, chr);
    596         }
    597     }
    598 }
    599 
    600 static void fd_chr_close(struct CharDriverState *chr)
    601 {
    602     FDCharDriver *s = chr->opaque;
    603 
    604     if (s->fd_in >= 0) {
    605         if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
    606         } else {
    607             qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
    608         }
    609     }
    610 
    611     qemu_free(s);
    612 }
    613 
    614 /* open a character device to a unix fd */
    615 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
    616 {
    617     CharDriverState *chr;
    618     FDCharDriver *s;
    619 
    620     chr = qemu_mallocz(sizeof(CharDriverState));
    621     s = qemu_mallocz(sizeof(FDCharDriver));
    622     s->fd_in = fd_in;
    623     s->fd_out = fd_out;
    624     chr->opaque = s;
    625     chr->chr_write = fd_chr_write;
    626     chr->chr_update_read_handler = fd_chr_update_read_handler;
    627     chr->chr_close = fd_chr_close;
    628 
    629     qemu_chr_reset(chr);
    630 
    631     return chr;
    632 }
    633 
    634 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
    635 {
    636     int fd_out;
    637 
    638     TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
    639     if (fd_out < 0)
    640         return NULL;
    641     return qemu_chr_open_fd(-1, fd_out);
    642 }
    643 
    644 static CharDriverState *qemu_chr_open_pipe(const char *filename)
    645 {
    646     int fd_in, fd_out;
    647     char filename_in[256], filename_out[256];
    648 
    649     snprintf(filename_in, 256, "%s.in", filename);
    650     snprintf(filename_out, 256, "%s.out", filename);
    651     TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
    652     TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
    653     if (fd_in < 0 || fd_out < 0) {
    654 	if (fd_in >= 0)
    655 	    close(fd_in);
    656 	if (fd_out >= 0)
    657 	    close(fd_out);
    658         TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
    659         if (fd_in < 0)
    660             return NULL;
    661     }
    662     return qemu_chr_open_fd(fd_in, fd_out);
    663 }
    664 
    665 static CharDriverState *qemu_chr_open_fdpair(const char *fd_pair)
    666 {
    667     int fd_in, fd_out;
    668     char *endptr;
    669 
    670     /* fd_pair should contain two decimal fd values, separated by
    671      * a colon. */
    672     endptr = NULL;
    673     fd_in = strtol(fd_pair, &endptr, 10);
    674     if (endptr == NULL || endptr == fd_pair || *endptr != ':')
    675         return NULL;
    676     endptr++;   // skip colon
    677     fd_pair = endptr;
    678     endptr = NULL;
    679     fd_out = strtol(fd_pair, &endptr, 10);
    680     if (endptr == NULL || endptr == fd_pair || *endptr != '\0')
    681         return NULL;
    682 
    683     return qemu_chr_open_fd(fd_in, fd_out);
    684 }
    685 
    686 /* for STDIO, we handle the case where several clients use it
    687    (nographic mode) */
    688 
    689 #define TERM_FIFO_MAX_SIZE 1
    690 
    691 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
    692 static int term_fifo_size;
    693 
    694 static int stdio_read_poll(void *opaque)
    695 {
    696     CharDriverState *chr = opaque;
    697 
    698     /* try to flush the queue if needed */
    699     if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
    700         qemu_chr_read(chr, term_fifo, 1);
    701         term_fifo_size = 0;
    702     }
    703     /* see if we can absorb more chars */
    704     if (term_fifo_size == 0)
    705         return 1;
    706     else
    707         return 0;
    708 }
    709 
    710 static void stdio_read(void *opaque)
    711 {
    712     int size;
    713     uint8_t buf[1];
    714     CharDriverState *chr = opaque;
    715 
    716     size = read(0, buf, 1);
    717     if (size == 0) {
    718         /* stdin has been closed. Remove it from the active list.  */
    719         qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
    720         return;
    721     }
    722     if (size > 0) {
    723         if (qemu_chr_can_read(chr) > 0) {
    724             qemu_chr_read(chr, buf, 1);
    725         } else if (term_fifo_size == 0) {
    726             term_fifo[term_fifo_size++] = buf[0];
    727         }
    728     }
    729 }
    730 
    731 /* init terminal so that we can grab keys */
    732 static struct termios oldtty;
    733 static int old_fd0_flags;
    734 static int term_atexit_done;
    735 
    736 static void term_exit(void)
    737 {
    738     tcsetattr (0, TCSANOW, &oldtty);
    739     fcntl(0, F_SETFL, old_fd0_flags);
    740 }
    741 
    742 static void term_init(void)
    743 {
    744     struct termios tty;
    745 
    746     tcgetattr (0, &tty);
    747     oldtty = tty;
    748     old_fd0_flags = fcntl(0, F_GETFL);
    749 
    750     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
    751                           |INLCR|IGNCR|ICRNL|IXON);
    752     tty.c_oflag |= OPOST;
    753     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
    754     /* if graphical mode, we allow Ctrl-C handling */
    755     if (display_type == DT_NOGRAPHIC)
    756         tty.c_lflag &= ~ISIG;
    757     tty.c_cflag &= ~(CSIZE|PARENB);
    758     tty.c_cflag |= CS8;
    759     tty.c_cc[VMIN] = 1;
    760     tty.c_cc[VTIME] = 0;
    761 
    762     tcsetattr (0, TCSANOW, &tty);
    763 
    764     if (!term_atexit_done++)
    765         atexit(term_exit);
    766 
    767     fcntl(0, F_SETFL, O_NONBLOCK);
    768 }
    769 
    770 static void qemu_chr_close_stdio(struct CharDriverState *chr)
    771 {
    772     term_exit();
    773     stdio_nb_clients--;
    774     qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
    775     fd_chr_close(chr);
    776 }
    777 
    778 static CharDriverState *qemu_chr_open_stdio(void)
    779 {
    780     CharDriverState *chr;
    781 
    782     if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
    783         return NULL;
    784     chr = qemu_chr_open_fd(0, 1);
    785     chr->chr_close = qemu_chr_close_stdio;
    786     qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
    787     stdio_nb_clients++;
    788     term_init();
    789 
    790     return chr;
    791 }
    792 
    793 #ifdef __sun__
    794 /* Once Solaris has openpty(), this is going to be removed. */
    795 static int openpty(int *amaster, int *aslave, char *name,
    796                    struct termios *termp, struct winsize *winp)
    797 {
    798         const char *slave;
    799         int mfd = -1, sfd = -1;
    800 
    801         *amaster = *aslave = -1;
    802 
    803         mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
    804         if (mfd < 0)
    805                 goto err;
    806 
    807         if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
    808                 goto err;
    809 
    810         if ((slave = ptsname(mfd)) == NULL)
    811                 goto err;
    812 
    813         if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
    814                 goto err;
    815 
    816         if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
    817             (termp != NULL && tcgetattr(sfd, termp) < 0))
    818                 goto err;
    819 
    820         if (amaster)
    821                 *amaster = mfd;
    822         if (aslave)
    823                 *aslave = sfd;
    824         if (winp)
    825                 ioctl(sfd, TIOCSWINSZ, winp);
    826 
    827         return 0;
    828 
    829 err:
    830         if (sfd != -1)
    831                 close(sfd);
    832         close(mfd);
    833         return -1;
    834 }
    835 
    836 static void cfmakeraw (struct termios *termios_p)
    837 {
    838         termios_p->c_iflag &=
    839                 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
    840         termios_p->c_oflag &= ~OPOST;
    841         termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
    842         termios_p->c_cflag &= ~(CSIZE|PARENB);
    843         termios_p->c_cflag |= CS8;
    844 
    845         termios_p->c_cc[VMIN] = 0;
    846         termios_p->c_cc[VTIME] = 0;
    847 }
    848 #endif
    849 
    850 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
    851     || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
    852 
    853 typedef struct {
    854     int fd;
    855     int connected;
    856     int polling;
    857     int read_bytes;
    858     QEMUTimer *timer;
    859 } PtyCharDriver;
    860 
    861 static void pty_chr_update_read_handler(CharDriverState *chr);
    862 static void pty_chr_state(CharDriverState *chr, int connected);
    863 
    864 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
    865 {
    866     PtyCharDriver *s = chr->opaque;
    867 
    868     if (!s->connected) {
    869         /* guest sends data, check for (re-)connect */
    870         pty_chr_update_read_handler(chr);
    871         return 0;
    872     }
    873     return send_all(s->fd, buf, len);
    874 }
    875 
    876 static int pty_chr_read_poll(void *opaque)
    877 {
    878     CharDriverState *chr = opaque;
    879     PtyCharDriver *s = chr->opaque;
    880 
    881     s->read_bytes = qemu_chr_can_read(chr);
    882     return s->read_bytes;
    883 }
    884 
    885 static void pty_chr_read(void *opaque)
    886 {
    887     CharDriverState *chr = opaque;
    888     PtyCharDriver *s = chr->opaque;
    889     int size, len;
    890     uint8_t buf[1024];
    891 
    892     len = sizeof(buf);
    893     if (len > s->read_bytes)
    894         len = s->read_bytes;
    895     if (len == 0)
    896         return;
    897     size = read(s->fd, buf, len);
    898     if ((size == -1 && errno == EIO) ||
    899         (size == 0)) {
    900         pty_chr_state(chr, 0);
    901         return;
    902     }
    903     if (size > 0) {
    904         pty_chr_state(chr, 1);
    905         qemu_chr_read(chr, buf, size);
    906     }
    907 }
    908 
    909 static void pty_chr_update_read_handler(CharDriverState *chr)
    910 {
    911     PtyCharDriver *s = chr->opaque;
    912 
    913     qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
    914                          pty_chr_read, NULL, chr);
    915     s->polling = 1;
    916     /*
    917      * Short timeout here: just need wait long enougth that qemu makes
    918      * it through the poll loop once.  When reconnected we want a
    919      * short timeout so we notice it almost instantly.  Otherwise
    920      * read() gives us -EIO instantly, making pty_chr_state() reset the
    921      * timeout to the normal (much longer) poll interval before the
    922      * timer triggers.
    923      */
    924     qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
    925 }
    926 
    927 static void pty_chr_state(CharDriverState *chr, int connected)
    928 {
    929     PtyCharDriver *s = chr->opaque;
    930 
    931     if (!connected) {
    932         qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
    933         s->connected = 0;
    934         s->polling = 0;
    935         /* (re-)connect poll interval for idle guests: once per second.
    936          * We check more frequently in case the guests sends data to
    937          * the virtual device linked to our pty. */
    938         qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
    939     } else {
    940         if (!s->connected)
    941             qemu_chr_reset(chr);
    942         s->connected = 1;
    943     }
    944 }
    945 
    946 static void pty_chr_timer(void *opaque)
    947 {
    948     struct CharDriverState *chr = opaque;
    949     PtyCharDriver *s = chr->opaque;
    950 
    951     if (s->connected)
    952         return;
    953     if (s->polling) {
    954         /* If we arrive here without polling being cleared due
    955          * read returning -EIO, then we are (re-)connected */
    956         pty_chr_state(chr, 1);
    957         return;
    958     }
    959 
    960     /* Next poll ... */
    961     pty_chr_update_read_handler(chr);
    962 }
    963 
    964 static void pty_chr_close(struct CharDriverState *chr)
    965 {
    966     PtyCharDriver *s = chr->opaque;
    967 
    968     qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
    969     close(s->fd);
    970     qemu_del_timer(s->timer);
    971     qemu_free_timer(s->timer);
    972     qemu_free(s);
    973 }
    974 
    975 static CharDriverState *qemu_chr_open_pty(void)
    976 {
    977     CharDriverState *chr;
    978     PtyCharDriver *s;
    979     struct termios tty;
    980     int slave_fd, len;
    981 #if defined(__OpenBSD__) || defined(__DragonFly__)
    982     char pty_name[PATH_MAX];
    983 #define q_ptsname(x) pty_name
    984 #else
    985     char *pty_name = NULL;
    986 #define q_ptsname(x) ptsname(x)
    987     extern char* ptsname(int);
    988 #endif
    989 
    990     chr = qemu_mallocz(sizeof(CharDriverState));
    991     s = qemu_mallocz(sizeof(PtyCharDriver));
    992 
    993     if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
    994         return NULL;
    995     }
    996 
    997     /* Set raw attributes on the pty. */
    998     tcgetattr(slave_fd, &tty);
    999     cfmakeraw(&tty);
   1000     tcsetattr(slave_fd, TCSAFLUSH, &tty);
   1001     close(slave_fd);
   1002 
   1003     len = strlen(q_ptsname(s->fd)) + 5;
   1004     chr->filename = qemu_malloc(len);
   1005     snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
   1006     fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
   1007 
   1008     chr->opaque = s;
   1009     chr->chr_write = pty_chr_write;
   1010     chr->chr_update_read_handler = pty_chr_update_read_handler;
   1011     chr->chr_close = pty_chr_close;
   1012 
   1013     s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
   1014 
   1015     return chr;
   1016 }
   1017 
   1018 static void tty_serial_init(int fd, int speed,
   1019                             int parity, int data_bits, int stop_bits)
   1020 {
   1021     struct termios tty;
   1022     speed_t spd;
   1023 
   1024 #if 0
   1025     printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
   1026            speed, parity, data_bits, stop_bits);
   1027 #endif
   1028     tcgetattr (fd, &tty);
   1029 
   1030 #define MARGIN 1.1
   1031     if (speed <= 50 * MARGIN)
   1032         spd = B50;
   1033     else if (speed <= 75 * MARGIN)
   1034         spd = B75;
   1035     else if (speed <= 300 * MARGIN)
   1036         spd = B300;
   1037     else if (speed <= 600 * MARGIN)
   1038         spd = B600;
   1039     else if (speed <= 1200 * MARGIN)
   1040         spd = B1200;
   1041     else if (speed <= 2400 * MARGIN)
   1042         spd = B2400;
   1043     else if (speed <= 4800 * MARGIN)
   1044         spd = B4800;
   1045     else if (speed <= 9600 * MARGIN)
   1046         spd = B9600;
   1047     else if (speed <= 19200 * MARGIN)
   1048         spd = B19200;
   1049     else if (speed <= 38400 * MARGIN)
   1050         spd = B38400;
   1051     else if (speed <= 57600 * MARGIN)
   1052         spd = B57600;
   1053     else if (speed <= 115200 * MARGIN)
   1054         spd = B115200;
   1055     else
   1056         spd = B115200;
   1057 
   1058     cfsetispeed(&tty, spd);
   1059     cfsetospeed(&tty, spd);
   1060 
   1061     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
   1062                           |INLCR|IGNCR|ICRNL|IXON);
   1063     tty.c_oflag |= OPOST;
   1064     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
   1065     tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
   1066     switch(data_bits) {
   1067     default:
   1068     case 8:
   1069         tty.c_cflag |= CS8;
   1070         break;
   1071     case 7:
   1072         tty.c_cflag |= CS7;
   1073         break;
   1074     case 6:
   1075         tty.c_cflag |= CS6;
   1076         break;
   1077     case 5:
   1078         tty.c_cflag |= CS5;
   1079         break;
   1080     }
   1081     switch(parity) {
   1082     default:
   1083     case 'N':
   1084         break;
   1085     case 'E':
   1086         tty.c_cflag |= PARENB;
   1087         break;
   1088     case 'O':
   1089         tty.c_cflag |= PARENB | PARODD;
   1090         break;
   1091     }
   1092     if (stop_bits == 2)
   1093         tty.c_cflag |= CSTOPB;
   1094 
   1095     tcsetattr (fd, TCSANOW, &tty);
   1096 }
   1097 
   1098 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
   1099 {
   1100     FDCharDriver *s = chr->opaque;
   1101 
   1102     switch(cmd) {
   1103     case CHR_IOCTL_SERIAL_SET_PARAMS:
   1104         {
   1105             QEMUSerialSetParams *ssp = arg;
   1106             tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
   1107                             ssp->data_bits, ssp->stop_bits);
   1108         }
   1109         break;
   1110     case CHR_IOCTL_SERIAL_SET_BREAK:
   1111         {
   1112             int enable = *(int *)arg;
   1113             if (enable)
   1114                 tcsendbreak(s->fd_in, 1);
   1115         }
   1116         break;
   1117     case CHR_IOCTL_SERIAL_GET_TIOCM:
   1118         {
   1119             int sarg = 0;
   1120             int *targ = (int *)arg;
   1121             ioctl(s->fd_in, TIOCMGET, &sarg);
   1122             *targ = 0;
   1123             if (sarg & TIOCM_CTS)
   1124                 *targ |= CHR_TIOCM_CTS;
   1125             if (sarg & TIOCM_CAR)
   1126                 *targ |= CHR_TIOCM_CAR;
   1127             if (sarg & TIOCM_DSR)
   1128                 *targ |= CHR_TIOCM_DSR;
   1129             if (sarg & TIOCM_RI)
   1130                 *targ |= CHR_TIOCM_RI;
   1131             if (sarg & TIOCM_DTR)
   1132                 *targ |= CHR_TIOCM_DTR;
   1133             if (sarg & TIOCM_RTS)
   1134                 *targ |= CHR_TIOCM_RTS;
   1135         }
   1136         break;
   1137     case CHR_IOCTL_SERIAL_SET_TIOCM:
   1138         {
   1139             int sarg = *(int *)arg;
   1140             int targ = 0;
   1141             ioctl(s->fd_in, TIOCMGET, &targ);
   1142             targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
   1143                      | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
   1144             if (sarg & CHR_TIOCM_CTS)
   1145                 targ |= TIOCM_CTS;
   1146             if (sarg & CHR_TIOCM_CAR)
   1147                 targ |= TIOCM_CAR;
   1148             if (sarg & CHR_TIOCM_DSR)
   1149                 targ |= TIOCM_DSR;
   1150             if (sarg & CHR_TIOCM_RI)
   1151                 targ |= TIOCM_RI;
   1152             if (sarg & CHR_TIOCM_DTR)
   1153                 targ |= TIOCM_DTR;
   1154             if (sarg & CHR_TIOCM_RTS)
   1155                 targ |= TIOCM_RTS;
   1156             ioctl(s->fd_in, TIOCMSET, &targ);
   1157         }
   1158         break;
   1159     default:
   1160         return -ENOTSUP;
   1161     }
   1162     return 0;
   1163 }
   1164 
   1165 static CharDriverState *qemu_chr_open_tty(const char *filename)
   1166 {
   1167     CharDriverState *chr;
   1168     int fd;
   1169 
   1170     TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
   1171     tty_serial_init(fd, 115200, 'N', 8, 1);
   1172     chr = qemu_chr_open_fd(fd, fd);
   1173     if (!chr) {
   1174         close(fd);
   1175         return NULL;
   1176     }
   1177     chr->chr_ioctl = tty_serial_ioctl;
   1178     qemu_chr_reset(chr);
   1179     return chr;
   1180 }
   1181 #else  /* ! __linux__ && ! __sun__ */
   1182 static CharDriverState *qemu_chr_open_pty(void)
   1183 {
   1184     return NULL;
   1185 }
   1186 #endif /* __linux__ || __sun__ */
   1187 
   1188 #if defined(__linux__)
   1189 typedef struct {
   1190     int fd;
   1191     int mode;
   1192 } ParallelCharDriver;
   1193 
   1194 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
   1195 {
   1196     if (s->mode != mode) {
   1197 	int m = mode;
   1198         if (ioctl(s->fd, PPSETMODE, &m) < 0)
   1199             return 0;
   1200 	s->mode = mode;
   1201     }
   1202     return 1;
   1203 }
   1204 
   1205 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
   1206 {
   1207     ParallelCharDriver *drv = chr->opaque;
   1208     int fd = drv->fd;
   1209     uint8_t b;
   1210 
   1211     switch(cmd) {
   1212     case CHR_IOCTL_PP_READ_DATA:
   1213         if (ioctl(fd, PPRDATA, &b) < 0)
   1214             return -ENOTSUP;
   1215         *(uint8_t *)arg = b;
   1216         break;
   1217     case CHR_IOCTL_PP_WRITE_DATA:
   1218         b = *(uint8_t *)arg;
   1219         if (ioctl(fd, PPWDATA, &b) < 0)
   1220             return -ENOTSUP;
   1221         break;
   1222     case CHR_IOCTL_PP_READ_CONTROL:
   1223         if (ioctl(fd, PPRCONTROL, &b) < 0)
   1224             return -ENOTSUP;
   1225 	/* Linux gives only the lowest bits, and no way to know data
   1226 	   direction! For better compatibility set the fixed upper
   1227 	   bits. */
   1228         *(uint8_t *)arg = b | 0xc0;
   1229         break;
   1230     case CHR_IOCTL_PP_WRITE_CONTROL:
   1231         b = *(uint8_t *)arg;
   1232         if (ioctl(fd, PPWCONTROL, &b) < 0)
   1233             return -ENOTSUP;
   1234         break;
   1235     case CHR_IOCTL_PP_READ_STATUS:
   1236         if (ioctl(fd, PPRSTATUS, &b) < 0)
   1237             return -ENOTSUP;
   1238         *(uint8_t *)arg = b;
   1239         break;
   1240     case CHR_IOCTL_PP_DATA_DIR:
   1241         if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
   1242             return -ENOTSUP;
   1243         break;
   1244     case CHR_IOCTL_PP_EPP_READ_ADDR:
   1245 	if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
   1246 	    struct ParallelIOArg *parg = arg;
   1247 	    int n = read(fd, parg->buffer, parg->count);
   1248 	    if (n != parg->count) {
   1249 		return -EIO;
   1250 	    }
   1251 	}
   1252         break;
   1253     case CHR_IOCTL_PP_EPP_READ:
   1254 	if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
   1255 	    struct ParallelIOArg *parg = arg;
   1256 	    int n = read(fd, parg->buffer, parg->count);
   1257 	    if (n != parg->count) {
   1258 		return -EIO;
   1259 	    }
   1260 	}
   1261         break;
   1262     case CHR_IOCTL_PP_EPP_WRITE_ADDR:
   1263 	if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
   1264 	    struct ParallelIOArg *parg = arg;
   1265 	    int n = write(fd, parg->buffer, parg->count);
   1266 	    if (n != parg->count) {
   1267 		return -EIO;
   1268 	    }
   1269 	}
   1270         break;
   1271     case CHR_IOCTL_PP_EPP_WRITE:
   1272 	if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
   1273 	    struct ParallelIOArg *parg = arg;
   1274 	    int n = write(fd, parg->buffer, parg->count);
   1275 	    if (n != parg->count) {
   1276 		return -EIO;
   1277 	    }
   1278 	}
   1279         break;
   1280     default:
   1281         return -ENOTSUP;
   1282     }
   1283     return 0;
   1284 }
   1285 
   1286 static void pp_close(CharDriverState *chr)
   1287 {
   1288     ParallelCharDriver *drv = chr->opaque;
   1289     int fd = drv->fd;
   1290 
   1291     pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
   1292     ioctl(fd, PPRELEASE);
   1293     close(fd);
   1294     qemu_free(drv);
   1295 }
   1296 
   1297 static CharDriverState *qemu_chr_open_pp(const char *filename)
   1298 {
   1299     CharDriverState *chr;
   1300     ParallelCharDriver *drv;
   1301     int fd;
   1302 
   1303     TFR(fd = open(filename, O_RDWR));
   1304     if (fd < 0)
   1305         return NULL;
   1306 
   1307     if (ioctl(fd, PPCLAIM) < 0) {
   1308         close(fd);
   1309         return NULL;
   1310     }
   1311 
   1312     drv = qemu_mallocz(sizeof(ParallelCharDriver));
   1313     drv->fd = fd;
   1314     drv->mode = IEEE1284_MODE_COMPAT;
   1315 
   1316     chr = qemu_mallocz(sizeof(CharDriverState));
   1317     chr->chr_write = null_chr_write;
   1318     chr->chr_ioctl = pp_ioctl;
   1319     chr->chr_close = pp_close;
   1320     chr->opaque = drv;
   1321 
   1322     qemu_chr_reset(chr);
   1323 
   1324     return chr;
   1325 }
   1326 #endif /* __linux__ */
   1327 
   1328 #if defined(__FreeBSD__) || defined(__DragonFly__)
   1329 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
   1330 {
   1331     int fd = (int)chr->opaque;
   1332     uint8_t b;
   1333 
   1334     switch(cmd) {
   1335     case CHR_IOCTL_PP_READ_DATA:
   1336         if (ioctl(fd, PPIGDATA, &b) < 0)
   1337             return -ENOTSUP;
   1338         *(uint8_t *)arg = b;
   1339         break;
   1340     case CHR_IOCTL_PP_WRITE_DATA:
   1341         b = *(uint8_t *)arg;
   1342         if (ioctl(fd, PPISDATA, &b) < 0)
   1343             return -ENOTSUP;
   1344         break;
   1345     case CHR_IOCTL_PP_READ_CONTROL:
   1346         if (ioctl(fd, PPIGCTRL, &b) < 0)
   1347             return -ENOTSUP;
   1348         *(uint8_t *)arg = b;
   1349         break;
   1350     case CHR_IOCTL_PP_WRITE_CONTROL:
   1351         b = *(uint8_t *)arg;
   1352         if (ioctl(fd, PPISCTRL, &b) < 0)
   1353             return -ENOTSUP;
   1354         break;
   1355     case CHR_IOCTL_PP_READ_STATUS:
   1356         if (ioctl(fd, PPIGSTATUS, &b) < 0)
   1357             return -ENOTSUP;
   1358         *(uint8_t *)arg = b;
   1359         break;
   1360     default:
   1361         return -ENOTSUP;
   1362     }
   1363     return 0;
   1364 }
   1365 
   1366 static CharDriverState *qemu_chr_open_pp(const char *filename)
   1367 {
   1368     CharDriverState *chr;
   1369     int fd;
   1370 
   1371     fd = open(filename, O_RDWR);
   1372     if (fd < 0)
   1373         return NULL;
   1374 
   1375     chr = qemu_mallocz(sizeof(CharDriverState));
   1376     chr->opaque = (void *)fd;
   1377     chr->chr_write = null_chr_write;
   1378     chr->chr_ioctl = pp_ioctl;
   1379     return chr;
   1380 }
   1381 #endif
   1382 
   1383 #else /* _WIN32 */
   1384 
   1385 typedef struct {
   1386     int max_size;
   1387     HANDLE hcom, hrecv, hsend;
   1388     OVERLAPPED orecv, osend;
   1389     BOOL fpipe;
   1390     DWORD len;
   1391 } WinCharState;
   1392 
   1393 #define NSENDBUF 2048
   1394 #define NRECVBUF 2048
   1395 #define MAXCONNECT 1
   1396 #define NTIMEOUT 5000
   1397 
   1398 static int win_chr_poll(void *opaque);
   1399 static int win_chr_pipe_poll(void *opaque);
   1400 
   1401 static void win_chr_close(CharDriverState *chr)
   1402 {
   1403     WinCharState *s = chr->opaque;
   1404 
   1405     if (s->hsend) {
   1406         CloseHandle(s->hsend);
   1407         s->hsend = NULL;
   1408     }
   1409     if (s->hrecv) {
   1410         CloseHandle(s->hrecv);
   1411         s->hrecv = NULL;
   1412     }
   1413     if (s->hcom) {
   1414         CloseHandle(s->hcom);
   1415         s->hcom = NULL;
   1416     }
   1417     if (s->fpipe)
   1418         qemu_del_polling_cb(win_chr_pipe_poll, chr);
   1419     else
   1420         qemu_del_polling_cb(win_chr_poll, chr);
   1421 }
   1422 
   1423 static int win_chr_init(CharDriverState *chr, const char *filename)
   1424 {
   1425     WinCharState *s = chr->opaque;
   1426     COMMCONFIG comcfg;
   1427     COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
   1428     COMSTAT comstat;
   1429     DWORD size;
   1430     DWORD err;
   1431 
   1432     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
   1433     if (!s->hsend) {
   1434         fprintf(stderr, "Failed CreateEvent\n");
   1435         goto fail;
   1436     }
   1437     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
   1438     if (!s->hrecv) {
   1439         fprintf(stderr, "Failed CreateEvent\n");
   1440         goto fail;
   1441     }
   1442 
   1443     s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
   1444                       OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
   1445     if (s->hcom == INVALID_HANDLE_VALUE) {
   1446         fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
   1447         s->hcom = NULL;
   1448         goto fail;
   1449     }
   1450 
   1451     if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
   1452         fprintf(stderr, "Failed SetupComm\n");
   1453         goto fail;
   1454     }
   1455 
   1456     ZeroMemory(&comcfg, sizeof(COMMCONFIG));
   1457     size = sizeof(COMMCONFIG);
   1458     GetDefaultCommConfig(filename, &comcfg, &size);
   1459     comcfg.dcb.DCBlength = sizeof(DCB);
   1460     CommConfigDialog(filename, NULL, &comcfg);
   1461 
   1462     if (!SetCommState(s->hcom, &comcfg.dcb)) {
   1463         fprintf(stderr, "Failed SetCommState\n");
   1464         goto fail;
   1465     }
   1466 
   1467     if (!SetCommMask(s->hcom, EV_ERR)) {
   1468         fprintf(stderr, "Failed SetCommMask\n");
   1469         goto fail;
   1470     }
   1471 
   1472     cto.ReadIntervalTimeout = MAXDWORD;
   1473     if (!SetCommTimeouts(s->hcom, &cto)) {
   1474         fprintf(stderr, "Failed SetCommTimeouts\n");
   1475         goto fail;
   1476     }
   1477 
   1478     if (!ClearCommError(s->hcom, &err, &comstat)) {
   1479         fprintf(stderr, "Failed ClearCommError\n");
   1480         goto fail;
   1481     }
   1482     qemu_add_polling_cb(win_chr_poll, chr);
   1483     return 0;
   1484 
   1485  fail:
   1486     win_chr_close(chr);
   1487     return -1;
   1488 }
   1489 
   1490 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
   1491 {
   1492     WinCharState *s = chr->opaque;
   1493     DWORD len, ret, size, err;
   1494 
   1495     len = len1;
   1496     ZeroMemory(&s->osend, sizeof(s->osend));
   1497     s->osend.hEvent = s->hsend;
   1498     while (len > 0) {
   1499         if (s->hsend)
   1500             ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
   1501         else
   1502             ret = WriteFile(s->hcom, buf, len, &size, NULL);
   1503         if (!ret) {
   1504             err = GetLastError();
   1505             if (err == ERROR_IO_PENDING) {
   1506                 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
   1507                 if (ret) {
   1508                     buf += size;
   1509                     len -= size;
   1510                 } else {
   1511                     break;
   1512                 }
   1513             } else {
   1514                 break;
   1515             }
   1516         } else {
   1517             buf += size;
   1518             len -= size;
   1519         }
   1520     }
   1521     return len1 - len;
   1522 }
   1523 
   1524 static int win_chr_read_poll(CharDriverState *chr)
   1525 {
   1526     WinCharState *s = chr->opaque;
   1527 
   1528     s->max_size = qemu_chr_can_read(chr);
   1529     return s->max_size;
   1530 }
   1531 
   1532 static void win_chr_readfile(CharDriverState *chr)
   1533 {
   1534     WinCharState *s = chr->opaque;
   1535     int ret, err;
   1536     uint8_t buf[1024];
   1537     DWORD size;
   1538 
   1539     ZeroMemory(&s->orecv, sizeof(s->orecv));
   1540     s->orecv.hEvent = s->hrecv;
   1541     ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
   1542     if (!ret) {
   1543         err = GetLastError();
   1544         if (err == ERROR_IO_PENDING) {
   1545             ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
   1546         }
   1547     }
   1548 
   1549     if (size > 0) {
   1550         qemu_chr_read(chr, buf, size);
   1551     }
   1552 }
   1553 
   1554 static void win_chr_read(CharDriverState *chr)
   1555 {
   1556     WinCharState *s = chr->opaque;
   1557 
   1558     if (s->len > s->max_size)
   1559         s->len = s->max_size;
   1560     if (s->len == 0)
   1561         return;
   1562 
   1563     win_chr_readfile(chr);
   1564 }
   1565 
   1566 static int win_chr_poll(void *opaque)
   1567 {
   1568     CharDriverState *chr = opaque;
   1569     WinCharState *s = chr->opaque;
   1570     COMSTAT status;
   1571     DWORD comerr;
   1572 
   1573     ClearCommError(s->hcom, &comerr, &status);
   1574     if (status.cbInQue > 0) {
   1575         s->len = status.cbInQue;
   1576         win_chr_read_poll(chr);
   1577         win_chr_read(chr);
   1578         return 1;
   1579     }
   1580     return 0;
   1581 }
   1582 
   1583 static CharDriverState *qemu_chr_open_win(const char *filename)
   1584 {
   1585     CharDriverState *chr;
   1586     WinCharState *s;
   1587 
   1588     chr = qemu_mallocz(sizeof(CharDriverState));
   1589     s = qemu_mallocz(sizeof(WinCharState));
   1590     chr->opaque = s;
   1591     chr->chr_write = win_chr_write;
   1592     chr->chr_close = win_chr_close;
   1593 
   1594     if (win_chr_init(chr, filename) < 0) {
   1595         free(s);
   1596         free(chr);
   1597         return NULL;
   1598     }
   1599     qemu_chr_reset(chr);
   1600     return chr;
   1601 }
   1602 
   1603 static int win_chr_pipe_poll(void *opaque)
   1604 {
   1605     CharDriverState *chr = opaque;
   1606     WinCharState *s = chr->opaque;
   1607     DWORD size;
   1608 
   1609     PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
   1610     if (size > 0) {
   1611         s->len = size;
   1612         win_chr_read_poll(chr);
   1613         win_chr_read(chr);
   1614         return 1;
   1615     }
   1616     return 0;
   1617 }
   1618 
   1619 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
   1620 {
   1621     WinCharState *s = chr->opaque;
   1622     OVERLAPPED ov;
   1623     int ret;
   1624     DWORD size;
   1625     char openname[256];
   1626 
   1627     s->fpipe = TRUE;
   1628 
   1629     s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
   1630     if (!s->hsend) {
   1631         fprintf(stderr, "Failed CreateEvent\n");
   1632         goto fail;
   1633     }
   1634     s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
   1635     if (!s->hrecv) {
   1636         fprintf(stderr, "Failed CreateEvent\n");
   1637         goto fail;
   1638     }
   1639 
   1640     snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
   1641     s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
   1642                               PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
   1643                               PIPE_WAIT,
   1644                               MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
   1645     if (s->hcom == INVALID_HANDLE_VALUE) {
   1646         fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
   1647         s->hcom = NULL;
   1648         goto fail;
   1649     }
   1650 
   1651     ZeroMemory(&ov, sizeof(ov));
   1652     ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
   1653     ret = ConnectNamedPipe(s->hcom, &ov);
   1654     if (ret) {
   1655         fprintf(stderr, "Failed ConnectNamedPipe\n");
   1656         goto fail;
   1657     }
   1658 
   1659     ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
   1660     if (!ret) {
   1661         fprintf(stderr, "Failed GetOverlappedResult\n");
   1662         if (ov.hEvent) {
   1663             CloseHandle(ov.hEvent);
   1664             ov.hEvent = NULL;
   1665         }
   1666         goto fail;
   1667     }
   1668 
   1669     if (ov.hEvent) {
   1670         CloseHandle(ov.hEvent);
   1671         ov.hEvent = NULL;
   1672     }
   1673     qemu_add_polling_cb(win_chr_pipe_poll, chr);
   1674     return 0;
   1675 
   1676  fail:
   1677     win_chr_close(chr);
   1678     return -1;
   1679 }
   1680 
   1681 
   1682 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
   1683 {
   1684     CharDriverState *chr;
   1685     WinCharState *s;
   1686 
   1687     chr = qemu_mallocz(sizeof(CharDriverState));
   1688     s = qemu_mallocz(sizeof(WinCharState));
   1689     chr->opaque = s;
   1690     chr->chr_write = win_chr_write;
   1691     chr->chr_close = win_chr_close;
   1692 
   1693     if (win_chr_pipe_init(chr, filename) < 0) {
   1694         free(s);
   1695         free(chr);
   1696         return NULL;
   1697     }
   1698     qemu_chr_reset(chr);
   1699     return chr;
   1700 }
   1701 
   1702 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
   1703 {
   1704     CharDriverState *chr;
   1705     WinCharState *s;
   1706 
   1707     chr = qemu_mallocz(sizeof(CharDriverState));
   1708     s = qemu_mallocz(sizeof(WinCharState));
   1709     s->hcom = fd_out;
   1710     chr->opaque = s;
   1711     chr->chr_write = win_chr_write;
   1712     qemu_chr_reset(chr);
   1713     return chr;
   1714 }
   1715 
   1716 static CharDriverState *qemu_chr_open_win_con(const char *filename)
   1717 {
   1718     return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
   1719 }
   1720 
   1721 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
   1722 {
   1723     HANDLE fd_out;
   1724 
   1725     fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
   1726                         OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
   1727     if (fd_out == INVALID_HANDLE_VALUE)
   1728         return NULL;
   1729 
   1730     return qemu_chr_open_win_file(fd_out);
   1731 }
   1732 #endif /* !_WIN32 */
   1733 
   1734 /***********************************************************/
   1735 /* UDP Net console */
   1736 
   1737 typedef struct {
   1738     int fd;
   1739     SockAddress  daddr;
   1740     uint8_t buf[1024];
   1741     int bufcnt;
   1742     int bufptr;
   1743     int max_size;
   1744 } NetCharDriver;
   1745 
   1746 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
   1747 {
   1748     NetCharDriver *s = chr->opaque;
   1749 
   1750     return socket_sendto(s->fd, (const void *)buf, len, &s->daddr);
   1751 }
   1752 
   1753 static int udp_chr_read_poll(void *opaque)
   1754 {
   1755     CharDriverState *chr = opaque;
   1756     NetCharDriver *s = chr->opaque;
   1757 
   1758     s->max_size = qemu_chr_can_read(chr);
   1759 
   1760     /* If there were any stray characters in the queue process them
   1761      * first
   1762      */
   1763     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
   1764         qemu_chr_read(chr, &s->buf[s->bufptr], 1);
   1765         s->bufptr++;
   1766         s->max_size = qemu_chr_can_read(chr);
   1767     }
   1768     return s->max_size;
   1769 }
   1770 
   1771 static void udp_chr_read(void *opaque)
   1772 {
   1773     CharDriverState *chr = opaque;
   1774     NetCharDriver *s = chr->opaque;
   1775 
   1776     if (s->max_size == 0)
   1777         return;
   1778     s->bufcnt = socket_recv(s->fd, (void *)s->buf, sizeof(s->buf));
   1779     s->bufptr = s->bufcnt;
   1780     if (s->bufcnt <= 0)
   1781         return;
   1782 
   1783     s->bufptr = 0;
   1784     while (s->max_size > 0 && s->bufptr < s->bufcnt) {
   1785         qemu_chr_read(chr, &s->buf[s->bufptr], 1);
   1786         s->bufptr++;
   1787         s->max_size = qemu_chr_can_read(chr);
   1788     }
   1789 }
   1790 
   1791 static void udp_chr_update_read_handler(CharDriverState *chr)
   1792 {
   1793     NetCharDriver *s = chr->opaque;
   1794 
   1795     if (s->fd >= 0) {
   1796         qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
   1797                              udp_chr_read, NULL, chr);
   1798     }
   1799 }
   1800 
   1801 static void udp_chr_close(CharDriverState *chr)
   1802 {
   1803     NetCharDriver *s = chr->opaque;
   1804     if (s->fd >= 0) {
   1805         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
   1806         socket_close(s->fd);
   1807     }
   1808     qemu_free(s);
   1809 }
   1810 
   1811 static CharDriverState *qemu_chr_open_udp(const char *def)
   1812 {
   1813     CharDriverState *chr = NULL;
   1814     NetCharDriver *s = NULL;
   1815     int fd = -1;
   1816     SockAddress  saddr;
   1817 
   1818     chr = qemu_mallocz(sizeof(CharDriverState));
   1819     s   = qemu_mallocz(sizeof(NetCharDriver));
   1820 
   1821     fd = socket_create_inet(SOCKET_DGRAM);
   1822     if (fd < 0) {
   1823         perror("socket(PF_INET, SOCK_DGRAM)");
   1824         goto return_err;
   1825     }
   1826 
   1827     if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
   1828         printf("Could not parse: %s\n", def);
   1829         goto return_err;
   1830     }
   1831 
   1832     if (socket_bind(fd, &saddr) < 0) {
   1833         perror("bind");
   1834         goto return_err;
   1835     }
   1836 
   1837     s->fd = fd;
   1838     s->bufcnt = 0;
   1839     s->bufptr = 0;
   1840     chr->opaque = s;
   1841     chr->chr_write = udp_chr_write;
   1842     chr->chr_update_read_handler = udp_chr_update_read_handler;
   1843     chr->chr_close = udp_chr_close;
   1844     return chr;
   1845 
   1846 return_err:
   1847     if (chr)
   1848         free(chr);
   1849     if (s)
   1850         free(s);
   1851     if (fd >= 0)
   1852         closesocket(fd);
   1853     return NULL;
   1854 }
   1855 
   1856 /***********************************************************/
   1857 /* TCP Net console */
   1858 
   1859 typedef struct {
   1860     int fd, listen_fd;
   1861     int connected;
   1862     int max_size;
   1863     int do_telnetopt;
   1864     int do_nodelay;
   1865     int is_unix;
   1866 } TCPCharDriver;
   1867 
   1868 static void tcp_chr_accept(void *opaque);
   1869 
   1870 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
   1871 {
   1872     TCPCharDriver *s = chr->opaque;
   1873     if (s->connected) {
   1874         return send_all(s->fd, buf, len);
   1875     } else {
   1876         /* XXX: indicate an error ? */
   1877         return len;
   1878     }
   1879 }
   1880 
   1881 static int tcp_chr_read_poll(void *opaque)
   1882 {
   1883     CharDriverState *chr = opaque;
   1884     TCPCharDriver *s = chr->opaque;
   1885     if (!s->connected)
   1886         return 0;
   1887     s->max_size = qemu_chr_can_read(chr);
   1888     return s->max_size;
   1889 }
   1890 
   1891 #define IAC 255
   1892 #define IAC_BREAK 243
   1893 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
   1894                                       TCPCharDriver *s,
   1895                                       uint8_t *buf, int *size)
   1896 {
   1897     /* Handle any telnet client's basic IAC options to satisfy char by
   1898      * char mode with no echo.  All IAC options will be removed from
   1899      * the buf and the do_telnetopt variable will be used to track the
   1900      * state of the width of the IAC information.
   1901      *
   1902      * IAC commands come in sets of 3 bytes with the exception of the
   1903      * "IAC BREAK" command and the double IAC.
   1904      */
   1905 
   1906     int i;
   1907     int j = 0;
   1908 
   1909     for (i = 0; i < *size; i++) {
   1910         if (s->do_telnetopt > 1) {
   1911             if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
   1912                 /* Double IAC means send an IAC */
   1913                 if (j != i)
   1914                     buf[j] = buf[i];
   1915                 j++;
   1916                 s->do_telnetopt = 1;
   1917             } else {
   1918                 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
   1919                     /* Handle IAC break commands by sending a serial break */
   1920                     qemu_chr_event(chr, CHR_EVENT_BREAK);
   1921                     s->do_telnetopt++;
   1922                 }
   1923                 s->do_telnetopt++;
   1924             }
   1925             if (s->do_telnetopt >= 4) {
   1926                 s->do_telnetopt = 1;
   1927             }
   1928         } else {
   1929             if ((unsigned char)buf[i] == IAC) {
   1930                 s->do_telnetopt = 2;
   1931             } else {
   1932                 if (j != i)
   1933                     buf[j] = buf[i];
   1934                 j++;
   1935             }
   1936         }
   1937     }
   1938     *size = j;
   1939 }
   1940 
   1941 static void tcp_chr_read(void *opaque)
   1942 {
   1943     CharDriverState *chr = opaque;
   1944     TCPCharDriver *s = chr->opaque;
   1945     uint8_t buf[1024];
   1946     int len, size;
   1947 
   1948     if (!s->connected || s->max_size <= 0)
   1949         return;
   1950     len = sizeof(buf);
   1951     if (len > s->max_size)
   1952         len = s->max_size;
   1953     size = socket_recv(s->fd, (void *)buf, len);
   1954     if (size == 0) {
   1955         /* connection closed */
   1956         s->connected = 0;
   1957         if (s->listen_fd >= 0) {
   1958             qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
   1959         }
   1960         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
   1961         socket_close(s->fd);
   1962         s->fd = -1;
   1963     } else if (size > 0) {
   1964         if (s->do_telnetopt)
   1965             tcp_chr_process_IAC_bytes(chr, s, buf, &size);
   1966         if (size > 0)
   1967             qemu_chr_read(chr, buf, size);
   1968     }
   1969 }
   1970 
   1971 static void tcp_chr_connect(void *opaque)
   1972 {
   1973     CharDriverState *chr = opaque;
   1974     TCPCharDriver *s = chr->opaque;
   1975 
   1976     s->connected = 1;
   1977     qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
   1978                          tcp_chr_read, NULL, chr);
   1979     qemu_chr_reset(chr);
   1980 }
   1981 
   1982 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
   1983 static void tcp_chr_telnet_init(int fd)
   1984 {
   1985     char buf[3];
   1986     /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
   1987     IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
   1988     socket_send(fd, (char *)buf, 3);
   1989     IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
   1990     socket_send(fd, (char *)buf, 3);
   1991     IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
   1992     socket_send(fd, (char *)buf, 3);
   1993     IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
   1994     socket_send(fd, (char *)buf, 3);
   1995 }
   1996 
   1997 static void tcp_chr_accept(void *opaque)
   1998 {
   1999     CharDriverState *chr = opaque;
   2000     TCPCharDriver *s = chr->opaque;
   2001     int fd;
   2002 
   2003     for(;;) {
   2004         fd = socket_accept(s->listen_fd, NULL);
   2005         if (fd < 0) {
   2006             return;
   2007         } else if (fd >= 0) {
   2008             if (s->do_telnetopt)
   2009                 tcp_chr_telnet_init(fd);
   2010             break;
   2011         }
   2012     }
   2013     socket_set_nonblock(fd);
   2014     if (s->do_nodelay)
   2015         socket_set_nodelay(fd);
   2016     s->fd = fd;
   2017     qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
   2018     tcp_chr_connect(chr);
   2019 }
   2020 
   2021 static void tcp_chr_close(CharDriverState *chr)
   2022 {
   2023     TCPCharDriver *s = chr->opaque;
   2024     if (s->fd >= 0) {
   2025         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
   2026         closesocket(s->fd);
   2027     }
   2028     if (s->listen_fd >= 0) {
   2029         qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
   2030         closesocket(s->listen_fd);
   2031     }
   2032     qemu_free(s);
   2033 }
   2034 
   2035 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
   2036                                           int is_telnet,
   2037 					  int is_unix)
   2038 {
   2039     CharDriverState *chr = NULL;
   2040     TCPCharDriver *s = NULL;
   2041     int fd = -1, offset = 0;
   2042     int is_listen = 0;
   2043     int is_waitconnect = 1;
   2044     int do_nodelay = 0;
   2045     const char *ptr;
   2046 
   2047     ptr = host_str;
   2048     while((ptr = strchr(ptr,','))) {
   2049         ptr++;
   2050         if (!strncmp(ptr,"server",6)) {
   2051             is_listen = 1;
   2052         } else if (!strncmp(ptr,"nowait",6)) {
   2053             is_waitconnect = 0;
   2054         } else if (!strncmp(ptr,"nodelay",6)) {
   2055             do_nodelay = 1;
   2056         } else if (!strncmp(ptr,"to=",3)) {
   2057             /* nothing, inet_listen() parses this one */;
   2058         } else if (!strncmp(ptr,"ipv4",4)) {
   2059             /* nothing, inet_connect() and inet_listen() parse this one */;
   2060         } else if (!strncmp(ptr,"ipv6",4)) {
   2061             /* nothing, inet_connect() and inet_listen() parse this one */;
   2062         } else {
   2063             printf("Unknown option: %s\n", ptr);
   2064             goto fail;
   2065         }
   2066     }
   2067     if (!is_listen)
   2068         is_waitconnect = 0;
   2069 
   2070     chr = qemu_mallocz(sizeof(CharDriverState));
   2071     s = qemu_mallocz(sizeof(TCPCharDriver));
   2072 
   2073     if (is_listen) {
   2074         chr->filename = qemu_malloc(256);
   2075         if (is_unix) {
   2076             pstrcpy(chr->filename, 256, "unix:");
   2077         } else if (is_telnet) {
   2078             pstrcpy(chr->filename, 256, "telnet:");
   2079         } else {
   2080             pstrcpy(chr->filename, 256, "tcp:");
   2081         }
   2082         offset = strlen(chr->filename);
   2083     }
   2084     if (is_unix) {
   2085         if (is_listen) {
   2086             fd = unix_listen(host_str, chr->filename + offset, 256 - offset);
   2087         } else {
   2088             fd = unix_connect(host_str);
   2089         }
   2090     } else {
   2091         if (is_listen) {
   2092             fd = inet_listen(host_str, chr->filename + offset, 256 - offset,
   2093                              SOCKET_STREAM, 0);
   2094         } else {
   2095             fd = inet_connect(host_str, SOCKET_STREAM);
   2096         }
   2097     }
   2098     if (fd < 0)
   2099         goto fail;
   2100 
   2101     if (!is_waitconnect)
   2102         socket_set_nonblock(fd);
   2103 
   2104     s->connected = 0;
   2105     s->fd = -1;
   2106     s->listen_fd = -1;
   2107     s->is_unix = is_unix;
   2108     s->do_nodelay = do_nodelay && !is_unix;
   2109 
   2110     chr->opaque = s;
   2111     chr->chr_write = tcp_chr_write;
   2112     chr->chr_close = tcp_chr_close;
   2113 
   2114     if (is_listen) {
   2115         s->listen_fd = fd;
   2116         qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
   2117         if (is_telnet)
   2118             s->do_telnetopt = 1;
   2119     } else {
   2120         s->connected = 1;
   2121         s->fd = fd;
   2122         socket_set_nodelay(fd);
   2123         tcp_chr_connect(chr);
   2124     }
   2125 
   2126     if (is_listen && is_waitconnect) {
   2127         printf("QEMU waiting for connection on: %s\n",
   2128                chr->filename ? chr->filename : host_str);
   2129         tcp_chr_accept(chr);
   2130         socket_set_nonblock(s->listen_fd);
   2131     }
   2132 
   2133     return chr;
   2134  fail:
   2135     if (fd >= 0)
   2136         closesocket(fd);
   2137     qemu_free(s);
   2138     qemu_free(chr);
   2139     return NULL;
   2140 }
   2141 
   2142 CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
   2143 {
   2144     const char *p;
   2145     CharDriverState *chr;
   2146 
   2147     if (!strcmp(filename, "vc")) {
   2148         chr = text_console_init(0);
   2149     } else
   2150     if (strstart(filename, "vc:", &p)) {
   2151         chr = text_console_init(p);
   2152     } else
   2153     if (!strcmp(filename, "null")) {
   2154         chr = qemu_chr_open_null();
   2155     } else
   2156     if (strstart(filename, "tcp:", &p)) {
   2157         chr = qemu_chr_open_tcp(p, 0, 0);
   2158     } else
   2159     if (strstart(filename, "telnet:", &p)) {
   2160         chr = qemu_chr_open_tcp(p, 1, 0);
   2161     } else
   2162     if (strstart(filename, "udp:", &p)) {
   2163         chr = qemu_chr_open_udp(p);
   2164     } else
   2165     if (strstart(filename, "mon:", &p)) {
   2166         chr = qemu_chr_open(label, p, NULL);
   2167         if (chr) {
   2168             chr = qemu_chr_open_mux(chr);
   2169             monitor_init(chr, MONITOR_USE_READLINE);
   2170         } else {
   2171             printf("Unable to open driver: %s\n", p);
   2172         }
   2173     } else if (!strcmp(filename, "msmouse")) {
   2174         chr = qemu_chr_open_msmouse();
   2175     } else
   2176 #ifndef _WIN32
   2177     if (strstart(filename, "unix:", &p)) {
   2178 	chr = qemu_chr_open_tcp(p, 0, 1);
   2179     } else if (strstart(filename, "file:", &p)) {
   2180         chr = qemu_chr_open_file_out(p);
   2181     } else if (strstart(filename, "pipe:", &p)) {
   2182         chr = qemu_chr_open_pipe(p);
   2183     } else if (strstart(filename, "fdpair:", &p)) {
   2184         chr = qemu_chr_open_fdpair(p);
   2185     } else if (!strcmp(filename, "pty")) {
   2186         chr = qemu_chr_open_pty();
   2187     } else if (!strcmp(filename, "stdio")) {
   2188         chr = qemu_chr_open_stdio();
   2189     } else
   2190 #if defined(__linux__)
   2191     if (strstart(filename, "/dev/parport", NULL)) {
   2192         chr = qemu_chr_open_pp(filename);
   2193     } else
   2194 #elif defined(__FreeBSD__) || defined(__DragonFly__)
   2195     if (strstart(filename, "/dev/ppi", NULL)) {
   2196         chr = qemu_chr_open_pp(filename);
   2197     } else
   2198 #endif
   2199 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
   2200     || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
   2201     if (strstart(filename, "/dev/", NULL)) {
   2202         chr = qemu_chr_open_tty(filename);
   2203     } else
   2204 #endif
   2205 #else /* !_WIN32 */
   2206     if (strstart(filename, "COM", NULL)) {
   2207         chr = qemu_chr_open_win(filename);
   2208     } else
   2209     if (strstart(filename, "pipe:", &p)) {
   2210         chr = qemu_chr_open_win_pipe(p);
   2211     } else
   2212     if (strstart(filename, "con:", NULL)) {
   2213         chr = qemu_chr_open_win_con(filename);
   2214     } else
   2215     if (strstart(filename, "file:", &p)) {
   2216         chr = qemu_chr_open_win_file_out(p);
   2217     } else
   2218 #endif
   2219     if (!strcmp(filename, "android-modem")) {
   2220         CharDriverState*  cs;
   2221         qemu_chr_open_charpipe( &cs, &android_modem_cs );
   2222         return cs;
   2223     } else if (!strcmp(filename, "android-gps")) {
   2224         CharDriverState*  cs;
   2225         qemu_chr_open_charpipe( &cs, &android_gps_cs );
   2226         return cs;
   2227     } else if (!strcmp(filename, "android-kmsg")) {
   2228         return android_kmsg_get_cs();
   2229     } else if (!strcmp(filename, "android-qemud")) {
   2230         return android_qemud_get_cs();
   2231     } else
   2232 #ifdef CONFIG_BRLAPI
   2233     if (!strcmp(filename, "braille")) {
   2234         chr = chr_baum_init();
   2235     } else
   2236 #endif
   2237     {
   2238         chr = NULL;
   2239     }
   2240 
   2241     if (chr) {
   2242         if (!chr->filename)
   2243             chr->filename = qemu_strdup(filename);
   2244         chr->init = init;
   2245         chr->label = qemu_strdup(label);
   2246         QTAILQ_INSERT_TAIL(&chardevs, chr, next);
   2247     }
   2248     return chr;
   2249 }
   2250 
   2251 void qemu_chr_close(CharDriverState *chr)
   2252 {
   2253     QTAILQ_REMOVE(&chardevs, chr, next);
   2254     if (chr->chr_close)
   2255         chr->chr_close(chr);
   2256     qemu_free(chr->filename);
   2257     qemu_free(chr->label);
   2258     qemu_free(chr);
   2259 }
   2260 
   2261 void qemu_chr_info(Monitor *mon)
   2262 {
   2263     CharDriverState *chr;
   2264 
   2265     QTAILQ_FOREACH(chr, &chardevs, next) {
   2266         monitor_printf(mon, "%s: filename=%s\n", chr->label, chr->filename);
   2267     }
   2268 }
   2269