qemu/qemu-char.c
<<
>>
Prefs
   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 "monitor/monitor.h"
  26#include "ui/console.h"
  27#include "sysemu/sysemu.h"
  28#include "qemu/timer.h"
  29#include "sysemu/char.h"
  30#include "hw/usb.h"
  31#include "qmp-commands.h"
  32
  33#include <unistd.h>
  34#include <fcntl.h>
  35#include <time.h>
  36#include <errno.h>
  37#include <sys/time.h>
  38#include <zlib.h>
  39
  40#ifndef _WIN32
  41#include <sys/times.h>
  42#include <sys/wait.h>
  43#include <termios.h>
  44#include <sys/mman.h>
  45#include <sys/ioctl.h>
  46#include <sys/resource.h>
  47#include <sys/socket.h>
  48#include <netinet/in.h>
  49#include <net/if.h>
  50#include <arpa/inet.h>
  51#include <dirent.h>
  52#include <netdb.h>
  53#include <sys/select.h>
  54#ifdef CONFIG_BSD
  55#include <sys/stat.h>
  56#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
  57#include <dev/ppbus/ppi.h>
  58#include <dev/ppbus/ppbconf.h>
  59#elif defined(__DragonFly__)
  60#include <dev/misc/ppi/ppi.h>
  61#include <bus/ppbus/ppbconf.h>
  62#endif
  63#else
  64#ifdef __linux__
  65#include <linux/ppdev.h>
  66#include <linux/parport.h>
  67#endif
  68#ifdef __sun__
  69#include <sys/stat.h>
  70#include <sys/ethernet.h>
  71#include <sys/sockio.h>
  72#include <netinet/arp.h>
  73#include <netinet/in.h>
  74#include <netinet/in_systm.h>
  75#include <netinet/ip.h>
  76#include <netinet/ip_icmp.h> // must come after ip.h
  77#include <netinet/udp.h>
  78#include <netinet/tcp.h>
  79#endif
  80#endif
  81#endif
  82
  83#include "qemu/sockets.h"
  84#include "ui/qemu-spice.h"
  85
  86#define READ_BUF_LEN 4096
  87
  88/***********************************************************/
  89/* character device */
  90
  91static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
  92    QTAILQ_HEAD_INITIALIZER(chardevs);
  93
  94void qemu_chr_be_event(CharDriverState *s, int event)
  95{
  96    /* Keep track if the char device is open */
  97    switch (event) {
  98        case CHR_EVENT_OPENED:
  99            s->be_open = 1;
 100            break;
 101        case CHR_EVENT_CLOSED:
 102            s->be_open = 0;
 103            break;
 104    }
 105
 106    if (!s->chr_event)
 107        return;
 108    s->chr_event(s->handler_opaque, event);
 109}
 110
 111void qemu_chr_be_generic_open(CharDriverState *s)
 112{
 113    qemu_chr_be_event(s, CHR_EVENT_OPENED);
 114}
 115
 116int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
 117{
 118    return s->chr_write(s, buf, len);
 119}
 120
 121int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
 122{
 123    int offset = 0;
 124    int res;
 125
 126    while (offset < len) {
 127        do {
 128            res = s->chr_write(s, buf + offset, len - offset);
 129            if (res == -1 && errno == EAGAIN) {
 130                g_usleep(100);
 131            }
 132        } while (res == -1 && errno == EAGAIN);
 133
 134        if (res == 0) {
 135            break;
 136        }
 137
 138        if (res < 0) {
 139            return res;
 140        }
 141
 142        offset += res;
 143    }
 144
 145    return offset;
 146}
 147
 148int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
 149{
 150    if (!s->chr_ioctl)
 151        return -ENOTSUP;
 152    return s->chr_ioctl(s, cmd, arg);
 153}
 154
 155int qemu_chr_be_can_write(CharDriverState *s)
 156{
 157    if (!s->chr_can_read)
 158        return 0;
 159    return s->chr_can_read(s->handler_opaque);
 160}
 161
 162void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
 163{
 164    if (s->chr_read) {
 165        s->chr_read(s->handler_opaque, buf, len);
 166    }
 167}
 168
 169int qemu_chr_fe_get_msgfd(CharDriverState *s)
 170{
 171    return s->get_msgfd ? s->get_msgfd(s) : -1;
 172}
 173
 174int qemu_chr_add_client(CharDriverState *s, int fd)
 175{
 176    return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
 177}
 178
 179void qemu_chr_accept_input(CharDriverState *s)
 180{
 181    if (s->chr_accept_input)
 182        s->chr_accept_input(s);
 183    qemu_notify_event();
 184}
 185
 186void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
 187{
 188    char buf[READ_BUF_LEN];
 189    va_list ap;
 190    va_start(ap, fmt);
 191    vsnprintf(buf, sizeof(buf), fmt, ap);
 192    qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
 193    va_end(ap);
 194}
 195
 196static void remove_fd_in_watch(CharDriverState *chr);
 197
 198void qemu_chr_add_handlers(CharDriverState *s,
 199                           IOCanReadHandler *fd_can_read,
 200                           IOReadHandler *fd_read,
 201                           IOEventHandler *fd_event,
 202                           void *opaque)
 203{
 204    int fe_open;
 205
 206    if (!opaque && !fd_can_read && !fd_read && !fd_event) {
 207        fe_open = 0;
 208        remove_fd_in_watch(s);
 209    } else {
 210        fe_open = 1;
 211    }
 212    s->chr_can_read = fd_can_read;
 213    s->chr_read = fd_read;
 214    s->chr_event = fd_event;
 215    s->handler_opaque = opaque;
 216    if (fe_open && s->chr_update_read_handler)
 217        s->chr_update_read_handler(s);
 218
 219    if (!s->explicit_fe_open) {
 220        qemu_chr_fe_set_open(s, fe_open);
 221    }
 222
 223    /* We're connecting to an already opened device, so let's make sure we
 224       also get the open event */
 225    if (fe_open && s->be_open) {
 226        qemu_chr_be_generic_open(s);
 227    }
 228}
 229
 230static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
 231{
 232    return len;
 233}
 234
 235static CharDriverState *qemu_chr_open_null(void)
 236{
 237    CharDriverState *chr;
 238
 239    chr = g_malloc0(sizeof(CharDriverState));
 240    chr->chr_write = null_chr_write;
 241    chr->explicit_be_open = true;
 242    return chr;
 243}
 244
 245/* MUX driver for serial I/O splitting */
 246#define MAX_MUX 4
 247#define MUX_BUFFER_SIZE 32      /* Must be a power of 2.  */
 248#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
 249typedef struct {
 250    IOCanReadHandler *chr_can_read[MAX_MUX];
 251    IOReadHandler *chr_read[MAX_MUX];
 252    IOEventHandler *chr_event[MAX_MUX];
 253    void *ext_opaque[MAX_MUX];
 254    CharDriverState *drv;
 255    int focus;
 256    int mux_cnt;
 257    int term_got_escape;
 258    int max_size;
 259    /* Intermediate input buffer allows to catch escape sequences even if the
 260       currently active device is not accepting any input - but only until it
 261       is full as well. */
 262    unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
 263    int prod[MAX_MUX];
 264    int cons[MAX_MUX];
 265    int timestamps;
 266    int linestart;
 267    int64_t timestamps_start;
 268} MuxDriver;
 269
 270
 271static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
 272{
 273    MuxDriver *d = chr->opaque;
 274    int ret;
 275    if (!d->timestamps) {
 276        ret = d->drv->chr_write(d->drv, buf, len);
 277    } else {
 278        int i;
 279
 280        ret = 0;
 281        for (i = 0; i < len; i++) {
 282            if (d->linestart) {
 283                char buf1[64];
 284                int64_t ti;
 285                int secs;
 286
 287                ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
 288                if (d->timestamps_start == -1)
 289                    d->timestamps_start = ti;
 290                ti -= d->timestamps_start;
 291                secs = ti / 1000;
 292                snprintf(buf1, sizeof(buf1),
 293                         "[%02d:%02d:%02d.%03d] ",
 294                         secs / 3600,
 295                         (secs / 60) % 60,
 296                         secs % 60,
 297                         (int)(ti % 1000));
 298                d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
 299                d->linestart = 0;
 300            }
 301            ret += d->drv->chr_write(d->drv, buf+i, 1);
 302            if (buf[i] == '\n') {
 303                d->linestart = 1;
 304            }
 305        }
 306    }
 307    return ret;
 308}
 309
 310static const char * const mux_help[] = {
 311    "% h    print this help\n\r",
 312    "% x    exit emulator\n\r",
 313    "% s    save disk data back to file (if -snapshot)\n\r",
 314    "% t    toggle console timestamps\n\r"
 315    "% b    send break (magic sysrq)\n\r",
 316    "% c    switch between console and monitor\n\r",
 317    "% %  sends %\n\r",
 318    NULL
 319};
 320
 321int term_escape_char = 0x01; /* ctrl-a is used for escape */
 322static void mux_print_help(CharDriverState *chr)
 323{
 324    int i, j;
 325    char ebuf[15] = "Escape-Char";
 326    char cbuf[50] = "\n\r";
 327
 328    if (term_escape_char > 0 && term_escape_char < 26) {
 329        snprintf(cbuf, sizeof(cbuf), "\n\r");
 330        snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
 331    } else {
 332        snprintf(cbuf, sizeof(cbuf),
 333                 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
 334                 term_escape_char);
 335    }
 336    chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
 337    for (i = 0; mux_help[i] != NULL; i++) {
 338        for (j=0; mux_help[i][j] != '\0'; j++) {
 339            if (mux_help[i][j] == '%')
 340                chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
 341            else
 342                chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
 343        }
 344    }
 345}
 346
 347static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
 348{
 349    if (d->chr_event[mux_nr])
 350        d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
 351}
 352
 353static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
 354{
 355    if (d->term_got_escape) {
 356        d->term_got_escape = 0;
 357        if (ch == term_escape_char)
 358            goto send_char;
 359        switch(ch) {
 360        case '?':
 361        case 'h':
 362            mux_print_help(chr);
 363            break;
 364        case 'x':
 365            {
 366                 const char *term =  "QEMU: Terminated\n\r";
 367                 chr->chr_write(chr,(uint8_t *)term,strlen(term));
 368                 exit(0);
 369                 break;
 370            }
 371        case 's':
 372            bdrv_commit_all();
 373            break;
 374        case 'b':
 375            qemu_chr_be_event(chr, CHR_EVENT_BREAK);
 376            break;
 377        case 'c':
 378            /* Switch to the next registered device */
 379            mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
 380            d->focus++;
 381            if (d->focus >= d->mux_cnt)
 382                d->focus = 0;
 383            mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
 384            break;
 385        case 't':
 386            d->timestamps = !d->timestamps;
 387            d->timestamps_start = -1;
 388            d->linestart = 0;
 389            break;
 390        }
 391    } else if (ch == term_escape_char) {
 392        d->term_got_escape = 1;
 393    } else {
 394    send_char:
 395        return 1;
 396    }
 397    return 0;
 398}
 399
 400static void mux_chr_accept_input(CharDriverState *chr)
 401{
 402    MuxDriver *d = chr->opaque;
 403    int m = d->focus;
 404
 405    while (d->prod[m] != d->cons[m] &&
 406           d->chr_can_read[m] &&
 407           d->chr_can_read[m](d->ext_opaque[m])) {
 408        d->chr_read[m](d->ext_opaque[m],
 409                       &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
 410    }
 411}
 412
 413static int mux_chr_can_read(void *opaque)
 414{
 415    CharDriverState *chr = opaque;
 416    MuxDriver *d = chr->opaque;
 417    int m = d->focus;
 418
 419    if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
 420        return 1;
 421    if (d->chr_can_read[m])
 422        return d->chr_can_read[m](d->ext_opaque[m]);
 423    return 0;
 424}
 425
 426static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
 427{
 428    CharDriverState *chr = opaque;
 429    MuxDriver *d = chr->opaque;
 430    int m = d->focus;
 431    int i;
 432
 433    mux_chr_accept_input (opaque);
 434
 435    for(i = 0; i < size; i++)
 436        if (mux_proc_byte(chr, d, buf[i])) {
 437            if (d->prod[m] == d->cons[m] &&
 438                d->chr_can_read[m] &&
 439                d->chr_can_read[m](d->ext_opaque[m]))
 440                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
 441            else
 442                d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
 443        }
 444}
 445
 446static void mux_chr_event(void *opaque, int event)
 447{
 448    CharDriverState *chr = opaque;
 449    MuxDriver *d = chr->opaque;
 450    int i;
 451
 452    /* Send the event to all registered listeners */
 453    for (i = 0; i < d->mux_cnt; i++)
 454        mux_chr_send_event(d, i, event);
 455}
 456
 457static void mux_chr_update_read_handler(CharDriverState *chr)
 458{
 459    MuxDriver *d = chr->opaque;
 460
 461    if (d->mux_cnt >= MAX_MUX) {
 462        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
 463        return;
 464    }
 465    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
 466    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
 467    d->chr_read[d->mux_cnt] = chr->chr_read;
 468    d->chr_event[d->mux_cnt] = chr->chr_event;
 469    /* Fix up the real driver with mux routines */
 470    if (d->mux_cnt == 0) {
 471        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
 472                              mux_chr_event, chr);
 473    }
 474    if (d->focus != -1) {
 475        mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
 476    }
 477    d->focus = d->mux_cnt;
 478    d->mux_cnt++;
 479    mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
 480}
 481
 482static bool muxes_realized;
 483
 484/**
 485 * Called after processing of default and command-line-specified
 486 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
 487 * to a mux chardev. This is done here to ensure that
 488 * output/prompts/banners are only displayed for the FE that has
 489 * focus when initial command-line processing/machine init is
 490 * completed.
 491 *
 492 * After this point, any new FE attached to any new or existing
 493 * mux will receive CHR_EVENT_OPENED notifications for the BE
 494 * immediately.
 495 */
 496static void muxes_realize_done(Notifier *notifier, void *unused)
 497{
 498    CharDriverState *chr;
 499
 500    QTAILQ_FOREACH(chr, &chardevs, next) {
 501        if (chr->is_mux) {
 502            MuxDriver *d = chr->opaque;
 503            int i;
 504
 505            /* send OPENED to all already-attached FEs */
 506            for (i = 0; i < d->mux_cnt; i++) {
 507                mux_chr_send_event(d, i, CHR_EVENT_OPENED);
 508            }
 509            /* mark mux as OPENED so any new FEs will immediately receive
 510             * OPENED event
 511             */
 512            qemu_chr_be_generic_open(chr);
 513        }
 514    }
 515    muxes_realized = true;
 516}
 517
 518static Notifier muxes_realize_notify = {
 519    .notify = muxes_realize_done,
 520};
 521
 522static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
 523{
 524    CharDriverState *chr;
 525    MuxDriver *d;
 526
 527    chr = g_malloc0(sizeof(CharDriverState));
 528    d = g_malloc0(sizeof(MuxDriver));
 529
 530    chr->opaque = d;
 531    d->drv = drv;
 532    d->focus = -1;
 533    chr->chr_write = mux_chr_write;
 534    chr->chr_update_read_handler = mux_chr_update_read_handler;
 535    chr->chr_accept_input = mux_chr_accept_input;
 536    /* Frontend guest-open / -close notification is not support with muxes */
 537    chr->chr_set_fe_open = NULL;
 538    /* only default to opened state if we've realized the initial
 539     * set of muxes
 540     */
 541    chr->explicit_be_open = muxes_realized ? 0 : 1;
 542    chr->is_mux = 1;
 543
 544    return chr;
 545}
 546
 547
 548#ifdef _WIN32
 549int send_all(int fd, const void *buf, int len1)
 550{
 551    int ret, len;
 552
 553    len = len1;
 554    while (len > 0) {
 555        ret = send(fd, buf, len, 0);
 556        if (ret < 0) {
 557            errno = WSAGetLastError();
 558            if (errno != WSAEWOULDBLOCK) {
 559                return -1;
 560            }
 561        } else if (ret == 0) {
 562            break;
 563        } else {
 564            buf += ret;
 565            len -= ret;
 566        }
 567    }
 568    return len1 - len;
 569}
 570
 571#else
 572
 573int send_all(int fd, const void *_buf, int len1)
 574{
 575    int ret, len;
 576    const uint8_t *buf = _buf;
 577
 578    len = len1;
 579    while (len > 0) {
 580        ret = write(fd, buf, len);
 581        if (ret < 0) {
 582            if (errno != EINTR && errno != EAGAIN)
 583                return -1;
 584        } else if (ret == 0) {
 585            break;
 586        } else {
 587            buf += ret;
 588            len -= ret;
 589        }
 590    }
 591    return len1 - len;
 592}
 593
 594int recv_all(int fd, void *_buf, int len1, bool single_read)
 595{
 596    int ret, len;
 597    uint8_t *buf = _buf;
 598
 599    len = len1;
 600    while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
 601        if (ret < 0) {
 602            if (errno != EINTR && errno != EAGAIN) {
 603                return -1;
 604            }
 605            continue;
 606        } else {
 607            if (single_read) {
 608                return ret;
 609            }
 610            buf += ret;
 611            len -= ret;
 612        }
 613    }
 614    return len1 - len;
 615}
 616
 617#endif /* !_WIN32 */
 618
 619typedef struct IOWatchPoll
 620{
 621    GSource parent;
 622
 623    GIOChannel *channel;
 624    GSource *src;
 625
 626    IOCanReadHandler *fd_can_read;
 627    GSourceFunc fd_read;
 628    void *opaque;
 629} IOWatchPoll;
 630
 631static IOWatchPoll *io_watch_poll_from_source(GSource *source)
 632{
 633    return container_of(source, IOWatchPoll, parent);
 634}
 635
 636static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
 637{
 638    IOWatchPoll *iwp = io_watch_poll_from_source(source);
 639    bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
 640    bool was_active = iwp->src != NULL;
 641    if (was_active == now_active) {
 642        return FALSE;
 643    }
 644
 645    if (now_active) {
 646        iwp->src = g_io_create_watch(iwp->channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
 647        g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
 648        g_source_attach(iwp->src, NULL);
 649    } else {
 650        g_source_destroy(iwp->src);
 651        g_source_unref(iwp->src);
 652        iwp->src = NULL;
 653    }
 654    return FALSE;
 655}
 656
 657static gboolean io_watch_poll_check(GSource *source)
 658{
 659    return FALSE;
 660}
 661
 662static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
 663                                       gpointer user_data)
 664{
 665    abort();
 666}
 667
 668static void io_watch_poll_finalize(GSource *source)
 669{
 670    /* Due to a glib bug, removing the last reference to a source
 671     * inside a finalize callback causes recursive locking (and a
 672     * deadlock).  This is not a problem inside other callbacks,
 673     * including dispatch callbacks, so we call io_remove_watch_poll
 674     * to remove this source.  At this point, iwp->src must
 675     * be NULL, or we would leak it.
 676     *
 677     * This would be solved much more elegantly by child sources,
 678     * but we support older glib versions that do not have them.
 679     */
 680    IOWatchPoll *iwp = io_watch_poll_from_source(source);
 681    assert(iwp->src == NULL);
 682}
 683
 684static GSourceFuncs io_watch_poll_funcs = {
 685    .prepare = io_watch_poll_prepare,
 686    .check = io_watch_poll_check,
 687    .dispatch = io_watch_poll_dispatch,
 688    .finalize = io_watch_poll_finalize,
 689};
 690
 691/* Can only be used for read */
 692static guint io_add_watch_poll(GIOChannel *channel,
 693                               IOCanReadHandler *fd_can_read,
 694                               GIOFunc fd_read,
 695                               gpointer user_data)
 696{
 697    IOWatchPoll *iwp;
 698    int tag;
 699
 700    iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
 701    iwp->fd_can_read = fd_can_read;
 702    iwp->opaque = user_data;
 703    iwp->channel = channel;
 704    iwp->fd_read = (GSourceFunc) fd_read;
 705    iwp->src = NULL;
 706
 707    tag = g_source_attach(&iwp->parent, NULL);
 708    g_source_unref(&iwp->parent);
 709    return tag;
 710}
 711
 712static void io_remove_watch_poll(guint tag)
 713{
 714    GSource *source;
 715    IOWatchPoll *iwp;
 716
 717    g_return_if_fail (tag > 0);
 718
 719    source = g_main_context_find_source_by_id(NULL, tag);
 720    g_return_if_fail (source != NULL);
 721
 722    iwp = io_watch_poll_from_source(source);
 723    if (iwp->src) {
 724        g_source_destroy(iwp->src);
 725        g_source_unref(iwp->src);
 726        iwp->src = NULL;
 727    }
 728    g_source_destroy(&iwp->parent);
 729}
 730
 731static void remove_fd_in_watch(CharDriverState *chr)
 732{
 733    if (chr->fd_in_tag) {
 734        io_remove_watch_poll(chr->fd_in_tag);
 735        chr->fd_in_tag = 0;
 736    }
 737}
 738
 739#ifndef _WIN32
 740static GIOChannel *io_channel_from_fd(int fd)
 741{
 742    GIOChannel *chan;
 743
 744    if (fd == -1) {
 745        return NULL;
 746    }
 747
 748    chan = g_io_channel_unix_new(fd);
 749
 750    g_io_channel_set_encoding(chan, NULL, NULL);
 751    g_io_channel_set_buffered(chan, FALSE);
 752
 753    return chan;
 754}
 755#endif
 756
 757static GIOChannel *io_channel_from_socket(int fd)
 758{
 759    GIOChannel *chan;
 760
 761    if (fd == -1) {
 762        return NULL;
 763    }
 764
 765#ifdef _WIN32
 766    chan = g_io_channel_win32_new_socket(fd);
 767#else
 768    chan = g_io_channel_unix_new(fd);
 769#endif
 770
 771    g_io_channel_set_encoding(chan, NULL, NULL);
 772    g_io_channel_set_buffered(chan, FALSE);
 773
 774    return chan;
 775}
 776
 777static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
 778{
 779    size_t offset = 0;
 780    GIOStatus status = G_IO_STATUS_NORMAL;
 781
 782    while (offset < len && status == G_IO_STATUS_NORMAL) {
 783        gsize bytes_written = 0;
 784
 785        status = g_io_channel_write_chars(fd, buf + offset, len - offset,
 786                                          &bytes_written, NULL);
 787        offset += bytes_written;
 788    }
 789
 790    if (offset > 0) {
 791        return offset;
 792    }
 793    switch (status) {
 794    case G_IO_STATUS_NORMAL:
 795        g_assert(len == 0);
 796        return 0;
 797    case G_IO_STATUS_AGAIN:
 798        errno = EAGAIN;
 799        return -1;
 800    default:
 801        break;
 802    }
 803    errno = EINVAL;
 804    return -1;
 805}
 806
 807#ifndef _WIN32
 808
 809typedef struct FDCharDriver {
 810    CharDriverState *chr;
 811    GIOChannel *fd_in, *fd_out;
 812    int max_size;
 813    QTAILQ_ENTRY(FDCharDriver) node;
 814} FDCharDriver;
 815
 816static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
 817{
 818    FDCharDriver *s = chr->opaque;
 819    
 820    return io_channel_send(s->fd_out, buf, len);
 821}
 822
 823static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
 824{
 825    CharDriverState *chr = opaque;
 826    FDCharDriver *s = chr->opaque;
 827    int len;
 828    uint8_t buf[READ_BUF_LEN];
 829    GIOStatus status;
 830    gsize bytes_read;
 831
 832    len = sizeof(buf);
 833    if (len > s->max_size) {
 834        len = s->max_size;
 835    }
 836    if (len == 0) {
 837        return TRUE;
 838    }
 839
 840    status = g_io_channel_read_chars(chan, (gchar *)buf,
 841                                     len, &bytes_read, NULL);
 842    if (status == G_IO_STATUS_EOF) {
 843        remove_fd_in_watch(chr);
 844        qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
 845        return FALSE;
 846    }
 847    if (status == G_IO_STATUS_NORMAL) {
 848        qemu_chr_be_write(chr, buf, bytes_read);
 849    }
 850
 851    return TRUE;
 852}
 853
 854static int fd_chr_read_poll(void *opaque)
 855{
 856    CharDriverState *chr = opaque;
 857    FDCharDriver *s = chr->opaque;
 858
 859    s->max_size = qemu_chr_be_can_write(chr);
 860    return s->max_size;
 861}
 862
 863static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
 864{
 865    FDCharDriver *s = chr->opaque;
 866    return g_io_create_watch(s->fd_out, cond);
 867}
 868
 869static void fd_chr_update_read_handler(CharDriverState *chr)
 870{
 871    FDCharDriver *s = chr->opaque;
 872
 873    remove_fd_in_watch(chr);
 874    if (s->fd_in) {
 875        chr->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll,
 876                                           fd_chr_read, chr);
 877    }
 878}
 879
 880static void fd_chr_close(struct CharDriverState *chr)
 881{
 882    FDCharDriver *s = chr->opaque;
 883
 884    remove_fd_in_watch(chr);
 885    if (s->fd_in) {
 886        g_io_channel_unref(s->fd_in);
 887    }
 888    if (s->fd_out) {
 889        g_io_channel_unref(s->fd_out);
 890    }
 891
 892    g_free(s);
 893    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
 894}
 895
 896/* open a character device to a unix fd */
 897static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
 898{
 899    CharDriverState *chr;
 900    FDCharDriver *s;
 901
 902    chr = g_malloc0(sizeof(CharDriverState));
 903    s = g_malloc0(sizeof(FDCharDriver));
 904    s->fd_in = io_channel_from_fd(fd_in);
 905    s->fd_out = io_channel_from_fd(fd_out);
 906    fcntl(fd_out, F_SETFL, O_NONBLOCK);
 907    s->chr = chr;
 908    chr->opaque = s;
 909    chr->chr_add_watch = fd_chr_add_watch;
 910    chr->chr_write = fd_chr_write;
 911    chr->chr_update_read_handler = fd_chr_update_read_handler;
 912    chr->chr_close = fd_chr_close;
 913
 914    return chr;
 915}
 916
 917static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
 918{
 919    int fd_in, fd_out;
 920    char filename_in[256], filename_out[256];
 921    const char *filename = opts->device;
 922
 923    if (filename == NULL) {
 924        fprintf(stderr, "chardev: pipe: no filename given\n");
 925        return NULL;
 926    }
 927
 928    snprintf(filename_in, 256, "%s.in", filename);
 929    snprintf(filename_out, 256, "%s.out", filename);
 930    TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
 931    TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
 932    if (fd_in < 0 || fd_out < 0) {
 933        if (fd_in >= 0)
 934            close(fd_in);
 935        if (fd_out >= 0)
 936            close(fd_out);
 937        TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
 938        if (fd_in < 0) {
 939            return NULL;
 940        }
 941    }
 942    return qemu_chr_open_fd(fd_in, fd_out);
 943}
 944
 945/* init terminal so that we can grab keys */
 946static struct termios oldtty;
 947static int old_fd0_flags;
 948static bool stdio_allow_signal;
 949
 950static void term_exit(void)
 951{
 952    tcsetattr (0, TCSANOW, &oldtty);
 953    fcntl(0, F_SETFL, old_fd0_flags);
 954}
 955
 956static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
 957{
 958    struct termios tty;
 959
 960    tty = oldtty;
 961    if (!echo) {
 962        tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
 963                          |INLCR|IGNCR|ICRNL|IXON);
 964        tty.c_oflag |= OPOST;
 965        tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
 966        tty.c_cflag &= ~(CSIZE|PARENB);
 967        tty.c_cflag |= CS8;
 968        tty.c_cc[VMIN] = 1;
 969        tty.c_cc[VTIME] = 0;
 970    }
 971    if (!stdio_allow_signal)
 972        tty.c_lflag &= ~ISIG;
 973
 974    tcsetattr (0, TCSANOW, &tty);
 975}
 976
 977static void qemu_chr_close_stdio(struct CharDriverState *chr)
 978{
 979    term_exit();
 980    fd_chr_close(chr);
 981}
 982
 983static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
 984{
 985    CharDriverState *chr;
 986
 987    if (is_daemonized()) {
 988        error_report("cannot use stdio with -daemonize");
 989        return NULL;
 990    }
 991    old_fd0_flags = fcntl(0, F_GETFL);
 992    tcgetattr (0, &oldtty);
 993    fcntl(0, F_SETFL, O_NONBLOCK);
 994    atexit(term_exit);
 995
 996    chr = qemu_chr_open_fd(0, 1);
 997    chr->chr_close = qemu_chr_close_stdio;
 998    chr->chr_set_echo = qemu_chr_set_echo_stdio;
 999    if (opts->has_signal) {
1000        stdio_allow_signal = opts->signal;
1001    }
1002    qemu_chr_fe_set_echo(chr, false);
1003
1004    return chr;
1005}
1006
1007#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1008    || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
1009    || defined(__GLIBC__)
1010
1011#define HAVE_CHARDEV_TTY 1
1012
1013typedef struct {
1014    GIOChannel *fd;
1015    int connected;
1016    int read_bytes;
1017    guint timer_tag;
1018} PtyCharDriver;
1019
1020static void pty_chr_update_read_handler(CharDriverState *chr);
1021static void pty_chr_state(CharDriverState *chr, int connected);
1022
1023static gboolean pty_chr_timer(gpointer opaque)
1024{
1025    struct CharDriverState *chr = opaque;
1026    PtyCharDriver *s = chr->opaque;
1027
1028    s->timer_tag = 0;
1029    if (!s->connected) {
1030        /* Next poll ... */
1031        pty_chr_update_read_handler(chr);
1032    }
1033    return FALSE;
1034}
1035
1036static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
1037{
1038    PtyCharDriver *s = chr->opaque;
1039
1040    if (s->timer_tag) {
1041        g_source_remove(s->timer_tag);
1042        s->timer_tag = 0;
1043    }
1044
1045    if (ms == 1000) {
1046        s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
1047    } else {
1048        s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
1049    }
1050}
1051
1052static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1053{
1054    PtyCharDriver *s = chr->opaque;
1055
1056    if (!s->connected) {
1057        /* guest sends data, check for (re-)connect */
1058        pty_chr_update_read_handler(chr);
1059        return 0;
1060    }
1061    return io_channel_send(s->fd, buf, len);
1062}
1063
1064static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
1065{
1066    PtyCharDriver *s = chr->opaque;
1067    return g_io_create_watch(s->fd, cond);
1068}
1069
1070static int pty_chr_read_poll(void *opaque)
1071{
1072    CharDriverState *chr = opaque;
1073    PtyCharDriver *s = chr->opaque;
1074
1075    s->read_bytes = qemu_chr_be_can_write(chr);
1076    return s->read_bytes;
1077}
1078
1079static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1080{
1081    CharDriverState *chr = opaque;
1082    PtyCharDriver *s = chr->opaque;
1083    gsize size, len;
1084    uint8_t buf[READ_BUF_LEN];
1085    GIOStatus status;
1086
1087    len = sizeof(buf);
1088    if (len > s->read_bytes)
1089        len = s->read_bytes;
1090    if (len == 0) {
1091        return TRUE;
1092    }
1093    status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
1094    if (status != G_IO_STATUS_NORMAL) {
1095        pty_chr_state(chr, 0);
1096        return FALSE;
1097    } else {
1098        pty_chr_state(chr, 1);
1099        qemu_chr_be_write(chr, buf, size);
1100    }
1101    return TRUE;
1102}
1103
1104static void pty_chr_update_read_handler(CharDriverState *chr)
1105{
1106    PtyCharDriver *s = chr->opaque;
1107    GPollFD pfd;
1108
1109    pfd.fd = g_io_channel_unix_get_fd(s->fd);
1110    pfd.events = G_IO_OUT;
1111    pfd.revents = 0;
1112    g_poll(&pfd, 1, 0);
1113    if (pfd.revents & G_IO_HUP) {
1114        pty_chr_state(chr, 0);
1115    } else {
1116        pty_chr_state(chr, 1);
1117    }
1118}
1119
1120static void pty_chr_state(CharDriverState *chr, int connected)
1121{
1122    PtyCharDriver *s = chr->opaque;
1123
1124    if (!connected) {
1125        remove_fd_in_watch(chr);
1126        s->connected = 0;
1127        /* (re-)connect poll interval for idle guests: once per second.
1128         * We check more frequently in case the guests sends data to
1129         * the virtual device linked to our pty. */
1130        pty_chr_rearm_timer(chr, 1000);
1131    } else {
1132        if (s->timer_tag) {
1133            g_source_remove(s->timer_tag);
1134            s->timer_tag = 0;
1135        }
1136        if (!s->connected) {
1137            s->connected = 1;
1138            qemu_chr_be_generic_open(chr);
1139        }
1140        if (!chr->fd_in_tag) {
1141            chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
1142                                               pty_chr_read, chr);
1143        }
1144    }
1145}
1146
1147static void pty_chr_close(struct CharDriverState *chr)
1148{
1149    PtyCharDriver *s = chr->opaque;
1150    int fd;
1151
1152    remove_fd_in_watch(chr);
1153    fd = g_io_channel_unix_get_fd(s->fd);
1154    g_io_channel_unref(s->fd);
1155    close(fd);
1156    if (s->timer_tag) {
1157        g_source_remove(s->timer_tag);
1158        s->timer_tag = 0;
1159    }
1160    g_free(s);
1161    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1162}
1163
1164static CharDriverState *qemu_chr_open_pty(const char *id,
1165                                          ChardevReturn *ret)
1166{
1167    CharDriverState *chr;
1168    PtyCharDriver *s;
1169    int master_fd, slave_fd;
1170    char pty_name[PATH_MAX];
1171
1172    master_fd = qemu_openpty_raw(&slave_fd, pty_name);
1173    if (master_fd < 0) {
1174        return NULL;
1175    }
1176
1177    close(slave_fd);
1178
1179    chr = g_malloc0(sizeof(CharDriverState));
1180
1181    chr->filename = g_strdup_printf("pty:%s", pty_name);
1182    ret->pty = g_strdup(pty_name);
1183    ret->has_pty = true;
1184
1185    fprintf(stderr, "char device redirected to %s (label %s)\n",
1186            pty_name, id);
1187
1188    s = g_malloc0(sizeof(PtyCharDriver));
1189    chr->opaque = s;
1190    chr->chr_write = pty_chr_write;
1191    chr->chr_update_read_handler = pty_chr_update_read_handler;
1192    chr->chr_close = pty_chr_close;
1193    chr->chr_add_watch = pty_chr_add_watch;
1194    chr->explicit_be_open = true;
1195
1196    s->fd = io_channel_from_fd(master_fd);
1197    s->timer_tag = 0;
1198
1199    return chr;
1200}
1201
1202static void tty_serial_init(int fd, int speed,
1203                            int parity, int data_bits, int stop_bits)
1204{
1205    struct termios tty;
1206    speed_t spd;
1207
1208#if 0
1209    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1210           speed, parity, data_bits, stop_bits);
1211#endif
1212    tcgetattr (fd, &tty);
1213
1214#define check_speed(val) if (speed <= val) { spd = B##val; break; }
1215    speed = speed * 10 / 11;
1216    do {
1217        check_speed(50);
1218        check_speed(75);
1219        check_speed(110);
1220        check_speed(134);
1221        check_speed(150);
1222        check_speed(200);
1223        check_speed(300);
1224        check_speed(600);
1225        check_speed(1200);
1226        check_speed(1800);
1227        check_speed(2400);
1228        check_speed(4800);
1229        check_speed(9600);
1230        check_speed(19200);
1231        check_speed(38400);
1232        /* Non-Posix values follow. They may be unsupported on some systems. */
1233        check_speed(57600);
1234        check_speed(115200);
1235#ifdef B230400
1236        check_speed(230400);
1237#endif
1238#ifdef B460800
1239        check_speed(460800);
1240#endif
1241#ifdef B500000
1242        check_speed(500000);
1243#endif
1244#ifdef B576000
1245        check_speed(576000);
1246#endif
1247#ifdef B921600
1248        check_speed(921600);
1249#endif
1250#ifdef B1000000
1251        check_speed(1000000);
1252#endif
1253#ifdef B1152000
1254        check_speed(1152000);
1255#endif
1256#ifdef B1500000
1257        check_speed(1500000);
1258#endif
1259#ifdef B2000000
1260        check_speed(2000000);
1261#endif
1262#ifdef B2500000
1263        check_speed(2500000);
1264#endif
1265#ifdef B3000000
1266        check_speed(3000000);
1267#endif
1268#ifdef B3500000
1269        check_speed(3500000);
1270#endif
1271#ifdef B4000000
1272        check_speed(4000000);
1273#endif
1274        spd = B115200;
1275    } while (0);
1276
1277    cfsetispeed(&tty, spd);
1278    cfsetospeed(&tty, spd);
1279
1280    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1281                          |INLCR|IGNCR|ICRNL|IXON);
1282    tty.c_oflag |= OPOST;
1283    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1284    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1285    switch(data_bits) {
1286    default:
1287    case 8:
1288        tty.c_cflag |= CS8;
1289        break;
1290    case 7:
1291        tty.c_cflag |= CS7;
1292        break;
1293    case 6:
1294        tty.c_cflag |= CS6;
1295        break;
1296    case 5:
1297        tty.c_cflag |= CS5;
1298        break;
1299    }
1300    switch(parity) {
1301    default:
1302    case 'N':
1303        break;
1304    case 'E':
1305        tty.c_cflag |= PARENB;
1306        break;
1307    case 'O':
1308        tty.c_cflag |= PARENB | PARODD;
1309        break;
1310    }
1311    if (stop_bits == 2)
1312        tty.c_cflag |= CSTOPB;
1313
1314    tcsetattr (fd, TCSANOW, &tty);
1315}
1316
1317static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1318{
1319    FDCharDriver *s = chr->opaque;
1320
1321    switch(cmd) {
1322    case CHR_IOCTL_SERIAL_SET_PARAMS:
1323        {
1324            QEMUSerialSetParams *ssp = arg;
1325            tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
1326                            ssp->speed, ssp->parity,
1327                            ssp->data_bits, ssp->stop_bits);
1328        }
1329        break;
1330    case CHR_IOCTL_SERIAL_SET_BREAK:
1331        {
1332            int enable = *(int *)arg;
1333            if (enable) {
1334                tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
1335            }
1336        }
1337        break;
1338    case CHR_IOCTL_SERIAL_GET_TIOCM:
1339        {
1340            int sarg = 0;
1341            int *targ = (int *)arg;
1342            ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
1343            *targ = 0;
1344            if (sarg & TIOCM_CTS)
1345                *targ |= CHR_TIOCM_CTS;
1346            if (sarg & TIOCM_CAR)
1347                *targ |= CHR_TIOCM_CAR;
1348            if (sarg & TIOCM_DSR)
1349                *targ |= CHR_TIOCM_DSR;
1350            if (sarg & TIOCM_RI)
1351                *targ |= CHR_TIOCM_RI;
1352            if (sarg & TIOCM_DTR)
1353                *targ |= CHR_TIOCM_DTR;
1354            if (sarg & TIOCM_RTS)
1355                *targ |= CHR_TIOCM_RTS;
1356        }
1357        break;
1358    case CHR_IOCTL_SERIAL_SET_TIOCM:
1359        {
1360            int sarg = *(int *)arg;
1361            int targ = 0;
1362            ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
1363            targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1364                     | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1365            if (sarg & CHR_TIOCM_CTS)
1366                targ |= TIOCM_CTS;
1367            if (sarg & CHR_TIOCM_CAR)
1368                targ |= TIOCM_CAR;
1369            if (sarg & CHR_TIOCM_DSR)
1370                targ |= TIOCM_DSR;
1371            if (sarg & CHR_TIOCM_RI)
1372                targ |= TIOCM_RI;
1373            if (sarg & CHR_TIOCM_DTR)
1374                targ |= TIOCM_DTR;
1375            if (sarg & CHR_TIOCM_RTS)
1376                targ |= TIOCM_RTS;
1377            ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
1378        }
1379        break;
1380    default:
1381        return -ENOTSUP;
1382    }
1383    return 0;
1384}
1385
1386static void qemu_chr_close_tty(CharDriverState *chr)
1387{
1388    FDCharDriver *s = chr->opaque;
1389    int fd = -1;
1390
1391    if (s) {
1392        fd = g_io_channel_unix_get_fd(s->fd_in);
1393    }
1394
1395    fd_chr_close(chr);
1396
1397    if (fd >= 0) {
1398        close(fd);
1399    }
1400}
1401
1402static CharDriverState *qemu_chr_open_tty_fd(int fd)
1403{
1404    CharDriverState *chr;
1405
1406    tty_serial_init(fd, 115200, 'N', 8, 1);
1407    chr = qemu_chr_open_fd(fd, fd);
1408    chr->chr_ioctl = tty_serial_ioctl;
1409    chr->chr_close = qemu_chr_close_tty;
1410    return chr;
1411}
1412#endif /* __linux__ || __sun__ */
1413
1414#if defined(__linux__)
1415
1416#define HAVE_CHARDEV_PARPORT 1
1417
1418typedef struct {
1419    int fd;
1420    int mode;
1421} ParallelCharDriver;
1422
1423static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1424{
1425    if (s->mode != mode) {
1426        int m = mode;
1427        if (ioctl(s->fd, PPSETMODE, &m) < 0)
1428            return 0;
1429        s->mode = mode;
1430    }
1431    return 1;
1432}
1433
1434static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1435{
1436    ParallelCharDriver *drv = chr->opaque;
1437    int fd = drv->fd;
1438    uint8_t b;
1439
1440    switch(cmd) {
1441    case CHR_IOCTL_PP_READ_DATA:
1442        if (ioctl(fd, PPRDATA, &b) < 0)
1443            return -ENOTSUP;
1444        *(uint8_t *)arg = b;
1445        break;
1446    case CHR_IOCTL_PP_WRITE_DATA:
1447        b = *(uint8_t *)arg;
1448        if (ioctl(fd, PPWDATA, &b) < 0)
1449            return -ENOTSUP;
1450        break;
1451    case CHR_IOCTL_PP_READ_CONTROL:
1452        if (ioctl(fd, PPRCONTROL, &b) < 0)
1453            return -ENOTSUP;
1454        /* Linux gives only the lowest bits, and no way to know data
1455           direction! For better compatibility set the fixed upper
1456           bits. */
1457        *(uint8_t *)arg = b | 0xc0;
1458        break;
1459    case CHR_IOCTL_PP_WRITE_CONTROL:
1460        b = *(uint8_t *)arg;
1461        if (ioctl(fd, PPWCONTROL, &b) < 0)
1462            return -ENOTSUP;
1463        break;
1464    case CHR_IOCTL_PP_READ_STATUS:
1465        if (ioctl(fd, PPRSTATUS, &b) < 0)
1466            return -ENOTSUP;
1467        *(uint8_t *)arg = b;
1468        break;
1469    case CHR_IOCTL_PP_DATA_DIR:
1470        if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1471            return -ENOTSUP;
1472        break;
1473    case CHR_IOCTL_PP_EPP_READ_ADDR:
1474        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1475            struct ParallelIOArg *parg = arg;
1476            int n = read(fd, parg->buffer, parg->count);
1477            if (n != parg->count) {
1478                return -EIO;
1479            }
1480        }
1481        break;
1482    case CHR_IOCTL_PP_EPP_READ:
1483        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1484            struct ParallelIOArg *parg = arg;
1485            int n = read(fd, parg->buffer, parg->count);
1486            if (n != parg->count) {
1487                return -EIO;
1488            }
1489        }
1490        break;
1491    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1492        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1493            struct ParallelIOArg *parg = arg;
1494            int n = write(fd, parg->buffer, parg->count);
1495            if (n != parg->count) {
1496                return -EIO;
1497            }
1498        }
1499        break;
1500    case CHR_IOCTL_PP_EPP_WRITE:
1501        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1502            struct ParallelIOArg *parg = arg;
1503            int n = write(fd, parg->buffer, parg->count);
1504            if (n != parg->count) {
1505                return -EIO;
1506            }
1507        }
1508        break;
1509    default:
1510        return -ENOTSUP;
1511    }
1512    return 0;
1513}
1514
1515static void pp_close(CharDriverState *chr)
1516{
1517    ParallelCharDriver *drv = chr->opaque;
1518    int fd = drv->fd;
1519
1520    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1521    ioctl(fd, PPRELEASE);
1522    close(fd);
1523    g_free(drv);
1524    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1525}
1526
1527static CharDriverState *qemu_chr_open_pp_fd(int fd)
1528{
1529    CharDriverState *chr;
1530    ParallelCharDriver *drv;
1531
1532    if (ioctl(fd, PPCLAIM) < 0) {
1533        close(fd);
1534        return NULL;
1535    }
1536
1537    drv = g_malloc0(sizeof(ParallelCharDriver));
1538    drv->fd = fd;
1539    drv->mode = IEEE1284_MODE_COMPAT;
1540
1541    chr = g_malloc0(sizeof(CharDriverState));
1542    chr->chr_write = null_chr_write;
1543    chr->chr_ioctl = pp_ioctl;
1544    chr->chr_close = pp_close;
1545    chr->opaque = drv;
1546
1547    return chr;
1548}
1549#endif /* __linux__ */
1550
1551#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1552
1553#define HAVE_CHARDEV_PARPORT 1
1554
1555static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1556{
1557    int fd = (int)(intptr_t)chr->opaque;
1558    uint8_t b;
1559
1560    switch(cmd) {
1561    case CHR_IOCTL_PP_READ_DATA:
1562        if (ioctl(fd, PPIGDATA, &b) < 0)
1563            return -ENOTSUP;
1564        *(uint8_t *)arg = b;
1565        break;
1566    case CHR_IOCTL_PP_WRITE_DATA:
1567        b = *(uint8_t *)arg;
1568        if (ioctl(fd, PPISDATA, &b) < 0)
1569            return -ENOTSUP;
1570        break;
1571    case CHR_IOCTL_PP_READ_CONTROL:
1572        if (ioctl(fd, PPIGCTRL, &b) < 0)
1573            return -ENOTSUP;
1574        *(uint8_t *)arg = b;
1575        break;
1576    case CHR_IOCTL_PP_WRITE_CONTROL:
1577        b = *(uint8_t *)arg;
1578        if (ioctl(fd, PPISCTRL, &b) < 0)
1579            return -ENOTSUP;
1580        break;
1581    case CHR_IOCTL_PP_READ_STATUS:
1582        if (ioctl(fd, PPIGSTATUS, &b) < 0)
1583            return -ENOTSUP;
1584        *(uint8_t *)arg = b;
1585        break;
1586    default:
1587        return -ENOTSUP;
1588    }
1589    return 0;
1590}
1591
1592static CharDriverState *qemu_chr_open_pp_fd(int fd)
1593{
1594    CharDriverState *chr;
1595
1596    chr = g_malloc0(sizeof(CharDriverState));
1597    chr->opaque = (void *)(intptr_t)fd;
1598    chr->chr_write = null_chr_write;
1599    chr->chr_ioctl = pp_ioctl;
1600    chr->explicit_be_open = true;
1601    return chr;
1602}
1603#endif
1604
1605#else /* _WIN32 */
1606
1607typedef struct {
1608    int max_size;
1609    HANDLE hcom, hrecv, hsend;
1610    OVERLAPPED orecv, osend;
1611    BOOL fpipe;
1612    DWORD len;
1613} WinCharState;
1614
1615typedef struct {
1616    HANDLE  hStdIn;
1617    HANDLE  hInputReadyEvent;
1618    HANDLE  hInputDoneEvent;
1619    HANDLE  hInputThread;
1620    uint8_t win_stdio_buf;
1621} WinStdioCharState;
1622
1623#define NSENDBUF 2048
1624#define NRECVBUF 2048
1625#define MAXCONNECT 1
1626#define NTIMEOUT 5000
1627
1628static int win_chr_poll(void *opaque);
1629static int win_chr_pipe_poll(void *opaque);
1630
1631static void win_chr_close(CharDriverState *chr)
1632{
1633    WinCharState *s = chr->opaque;
1634
1635    if (s->hsend) {
1636        CloseHandle(s->hsend);
1637        s->hsend = NULL;
1638    }
1639    if (s->hrecv) {
1640        CloseHandle(s->hrecv);
1641        s->hrecv = NULL;
1642    }
1643    if (s->hcom) {
1644        CloseHandle(s->hcom);
1645        s->hcom = NULL;
1646    }
1647    if (s->fpipe)
1648        qemu_del_polling_cb(win_chr_pipe_poll, chr);
1649    else
1650        qemu_del_polling_cb(win_chr_poll, chr);
1651
1652    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1653}
1654
1655static int win_chr_init(CharDriverState *chr, const char *filename)
1656{
1657    WinCharState *s = chr->opaque;
1658    COMMCONFIG comcfg;
1659    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1660    COMSTAT comstat;
1661    DWORD size;
1662    DWORD err;
1663
1664    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1665    if (!s->hsend) {
1666        fprintf(stderr, "Failed CreateEvent\n");
1667        goto fail;
1668    }
1669    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1670    if (!s->hrecv) {
1671        fprintf(stderr, "Failed CreateEvent\n");
1672        goto fail;
1673    }
1674
1675    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1676                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1677    if (s->hcom == INVALID_HANDLE_VALUE) {
1678        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1679        s->hcom = NULL;
1680        goto fail;
1681    }
1682
1683    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1684        fprintf(stderr, "Failed SetupComm\n");
1685        goto fail;
1686    }
1687
1688    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1689    size = sizeof(COMMCONFIG);
1690    GetDefaultCommConfig(filename, &comcfg, &size);
1691    comcfg.dcb.DCBlength = sizeof(DCB);
1692    CommConfigDialog(filename, NULL, &comcfg);
1693
1694    if (!SetCommState(s->hcom, &comcfg.dcb)) {
1695        fprintf(stderr, "Failed SetCommState\n");
1696        goto fail;
1697    }
1698
1699    if (!SetCommMask(s->hcom, EV_ERR)) {
1700        fprintf(stderr, "Failed SetCommMask\n");
1701        goto fail;
1702    }
1703
1704    cto.ReadIntervalTimeout = MAXDWORD;
1705    if (!SetCommTimeouts(s->hcom, &cto)) {
1706        fprintf(stderr, "Failed SetCommTimeouts\n");
1707        goto fail;
1708    }
1709
1710    if (!ClearCommError(s->hcom, &err, &comstat)) {
1711        fprintf(stderr, "Failed ClearCommError\n");
1712        goto fail;
1713    }
1714    qemu_add_polling_cb(win_chr_poll, chr);
1715    return 0;
1716
1717 fail:
1718    win_chr_close(chr);
1719    return -1;
1720}
1721
1722static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1723{
1724    WinCharState *s = chr->opaque;
1725    DWORD len, ret, size, err;
1726
1727    len = len1;
1728    ZeroMemory(&s->osend, sizeof(s->osend));
1729    s->osend.hEvent = s->hsend;
1730    while (len > 0) {
1731        if (s->hsend)
1732            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1733        else
1734            ret = WriteFile(s->hcom, buf, len, &size, NULL);
1735        if (!ret) {
1736            err = GetLastError();
1737            if (err == ERROR_IO_PENDING) {
1738                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1739                if (ret) {
1740                    buf += size;
1741                    len -= size;
1742                } else {
1743                    break;
1744                }
1745            } else {
1746                break;
1747            }
1748        } else {
1749            buf += size;
1750            len -= size;
1751        }
1752    }
1753    return len1 - len;
1754}
1755
1756static int win_chr_read_poll(CharDriverState *chr)
1757{
1758    WinCharState *s = chr->opaque;
1759
1760    s->max_size = qemu_chr_be_can_write(chr);
1761    return s->max_size;
1762}
1763
1764static void win_chr_readfile(CharDriverState *chr)
1765{
1766    WinCharState *s = chr->opaque;
1767    int ret, err;
1768    uint8_t buf[READ_BUF_LEN];
1769    DWORD size;
1770
1771    ZeroMemory(&s->orecv, sizeof(s->orecv));
1772    s->orecv.hEvent = s->hrecv;
1773    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1774    if (!ret) {
1775        err = GetLastError();
1776        if (err == ERROR_IO_PENDING) {
1777            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1778        }
1779    }
1780
1781    if (size > 0) {
1782        qemu_chr_be_write(chr, buf, size);
1783    }
1784}
1785
1786static void win_chr_read(CharDriverState *chr)
1787{
1788    WinCharState *s = chr->opaque;
1789
1790    if (s->len > s->max_size)
1791        s->len = s->max_size;
1792    if (s->len == 0)
1793        return;
1794
1795    win_chr_readfile(chr);
1796}
1797
1798static int win_chr_poll(void *opaque)
1799{
1800    CharDriverState *chr = opaque;
1801    WinCharState *s = chr->opaque;
1802    COMSTAT status;
1803    DWORD comerr;
1804
1805    ClearCommError(s->hcom, &comerr, &status);
1806    if (status.cbInQue > 0) {
1807        s->len = status.cbInQue;
1808        win_chr_read_poll(chr);
1809        win_chr_read(chr);
1810        return 1;
1811    }
1812    return 0;
1813}
1814
1815static CharDriverState *qemu_chr_open_win_path(const char *filename)
1816{
1817    CharDriverState *chr;
1818    WinCharState *s;
1819
1820    chr = g_malloc0(sizeof(CharDriverState));
1821    s = g_malloc0(sizeof(WinCharState));
1822    chr->opaque = s;
1823    chr->chr_write = win_chr_write;
1824    chr->chr_close = win_chr_close;
1825
1826    if (win_chr_init(chr, filename) < 0) {
1827        g_free(s);
1828        g_free(chr);
1829        return NULL;
1830    }
1831    return chr;
1832}
1833
1834static int win_chr_pipe_poll(void *opaque)
1835{
1836    CharDriverState *chr = opaque;
1837    WinCharState *s = chr->opaque;
1838    DWORD size;
1839
1840    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1841    if (size > 0) {
1842        s->len = size;
1843        win_chr_read_poll(chr);
1844        win_chr_read(chr);
1845        return 1;
1846    }
1847    return 0;
1848}
1849
1850static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1851{
1852    WinCharState *s = chr->opaque;
1853    OVERLAPPED ov;
1854    int ret;
1855    DWORD size;
1856    char openname[256];
1857
1858    s->fpipe = TRUE;
1859
1860    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1861    if (!s->hsend) {
1862        fprintf(stderr, "Failed CreateEvent\n");
1863        goto fail;
1864    }
1865    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1866    if (!s->hrecv) {
1867        fprintf(stderr, "Failed CreateEvent\n");
1868        goto fail;
1869    }
1870
1871    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1872    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1873                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1874                              PIPE_WAIT,
1875                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1876    if (s->hcom == INVALID_HANDLE_VALUE) {
1877        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1878        s->hcom = NULL;
1879        goto fail;
1880    }
1881
1882    ZeroMemory(&ov, sizeof(ov));
1883    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1884    ret = ConnectNamedPipe(s->hcom, &ov);
1885    if (ret) {
1886        fprintf(stderr, "Failed ConnectNamedPipe\n");
1887        goto fail;
1888    }
1889
1890    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1891    if (!ret) {
1892        fprintf(stderr, "Failed GetOverlappedResult\n");
1893        if (ov.hEvent) {
1894            CloseHandle(ov.hEvent);
1895            ov.hEvent = NULL;
1896        }
1897        goto fail;
1898    }
1899
1900    if (ov.hEvent) {
1901        CloseHandle(ov.hEvent);
1902        ov.hEvent = NULL;
1903    }
1904    qemu_add_polling_cb(win_chr_pipe_poll, chr);
1905    return 0;
1906
1907 fail:
1908    win_chr_close(chr);
1909    return -1;
1910}
1911
1912
1913static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
1914{
1915    const char *filename = opts->device;
1916    CharDriverState *chr;
1917    WinCharState *s;
1918
1919    chr = g_malloc0(sizeof(CharDriverState));
1920    s = g_malloc0(sizeof(WinCharState));
1921    chr->opaque = s;
1922    chr->chr_write = win_chr_write;
1923    chr->chr_close = win_chr_close;
1924
1925    if (win_chr_pipe_init(chr, filename) < 0) {
1926        g_free(s);
1927        g_free(chr);
1928        return NULL;
1929    }
1930    return chr;
1931}
1932
1933static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1934{
1935    CharDriverState *chr;
1936    WinCharState *s;
1937
1938    chr = g_malloc0(sizeof(CharDriverState));
1939    s = g_malloc0(sizeof(WinCharState));
1940    s->hcom = fd_out;
1941    chr->opaque = s;
1942    chr->chr_write = win_chr_write;
1943    return chr;
1944}
1945
1946static CharDriverState *qemu_chr_open_win_con(void)
1947{
1948    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1949}
1950
1951static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1952{
1953    HANDLE  hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1954    DWORD   dwSize;
1955    int     len1;
1956
1957    len1 = len;
1958
1959    while (len1 > 0) {
1960        if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
1961            break;
1962        }
1963        buf  += dwSize;
1964        len1 -= dwSize;
1965    }
1966
1967    return len - len1;
1968}
1969
1970static void win_stdio_wait_func(void *opaque)
1971{
1972    CharDriverState   *chr   = opaque;
1973    WinStdioCharState *stdio = chr->opaque;
1974    INPUT_RECORD       buf[4];
1975    int                ret;
1976    DWORD              dwSize;
1977    int                i;
1978
1979    ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
1980                           &dwSize);
1981
1982    if (!ret) {
1983        /* Avoid error storm */
1984        qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
1985        return;
1986    }
1987
1988    for (i = 0; i < dwSize; i++) {
1989        KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;
1990
1991        if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
1992            int j;
1993            if (kev->uChar.AsciiChar != 0) {
1994                for (j = 0; j < kev->wRepeatCount; j++) {
1995                    if (qemu_chr_be_can_write(chr)) {
1996                        uint8_t c = kev->uChar.AsciiChar;
1997                        qemu_chr_be_write(chr, &c, 1);
1998                    }
1999                }
2000            }
2001        }
2002    }
2003}
2004
2005static DWORD WINAPI win_stdio_thread(LPVOID param)
2006{
2007    CharDriverState   *chr   = param;
2008    WinStdioCharState *stdio = chr->opaque;
2009    int                ret;
2010    DWORD              dwSize;
2011
2012    while (1) {
2013
2014        /* Wait for one byte */
2015        ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);
2016
2017        /* Exit in case of error, continue if nothing read */
2018        if (!ret) {
2019            break;
2020        }
2021        if (!dwSize) {
2022            continue;
2023        }
2024
2025        /* Some terminal emulator returns \r\n for Enter, just pass \n */
2026        if (stdio->win_stdio_buf == '\r') {
2027            continue;
2028        }
2029
2030        /* Signal the main thread and wait until the byte was eaten */
2031        if (!SetEvent(stdio->hInputReadyEvent)) {
2032            break;
2033        }
2034        if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
2035            != WAIT_OBJECT_0) {
2036            break;
2037        }
2038    }
2039
2040    qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
2041    return 0;
2042}
2043
2044static void win_stdio_thread_wait_func(void *opaque)
2045{
2046    CharDriverState   *chr   = opaque;
2047    WinStdioCharState *stdio = chr->opaque;
2048
2049    if (qemu_chr_be_can_write(chr)) {
2050        qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
2051    }
2052
2053    SetEvent(stdio->hInputDoneEvent);
2054}
2055
2056static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
2057{
2058    WinStdioCharState *stdio  = chr->opaque;
2059    DWORD              dwMode = 0;
2060
2061    GetConsoleMode(stdio->hStdIn, &dwMode);
2062
2063    if (echo) {
2064        SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
2065    } else {
2066        SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
2067    }
2068}
2069
2070static void win_stdio_close(CharDriverState *chr)
2071{
2072    WinStdioCharState *stdio = chr->opaque;
2073
2074    if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
2075        CloseHandle(stdio->hInputReadyEvent);
2076    }
2077    if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
2078        CloseHandle(stdio->hInputDoneEvent);
2079    }
2080    if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
2081        TerminateThread(stdio->hInputThread, 0);
2082    }
2083
2084    g_free(chr->opaque);
2085    g_free(chr);
2086}
2087
2088static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
2089{
2090    CharDriverState   *chr;
2091    WinStdioCharState *stdio;
2092    DWORD              dwMode;
2093    int                is_console = 0;
2094
2095    chr   = g_malloc0(sizeof(CharDriverState));
2096    stdio = g_malloc0(sizeof(WinStdioCharState));
2097
2098    stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
2099    if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
2100        fprintf(stderr, "cannot open stdio: invalid handle\n");
2101        exit(1);
2102    }
2103
2104    is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;
2105
2106    chr->opaque    = stdio;
2107    chr->chr_write = win_stdio_write;
2108    chr->chr_close = win_stdio_close;
2109
2110    if (is_console) {
2111        if (qemu_add_wait_object(stdio->hStdIn,
2112                                 win_stdio_wait_func, chr)) {
2113            fprintf(stderr, "qemu_add_wait_object: failed\n");
2114        }
2115    } else {
2116        DWORD   dwId;
2117            
2118        stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2119        stdio->hInputDoneEvent  = CreateEvent(NULL, FALSE, FALSE, NULL);
2120        stdio->hInputThread     = CreateThread(NULL, 0, win_stdio_thread,
2121                                               chr, 0, &dwId);
2122
2123        if (stdio->hInputThread == INVALID_HANDLE_VALUE
2124            || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
2125            || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
2126            fprintf(stderr, "cannot create stdio thread or event\n");
2127            exit(1);
2128        }
2129        if (qemu_add_wait_object(stdio->hInputReadyEvent,
2130                                 win_stdio_thread_wait_func, chr)) {
2131            fprintf(stderr, "qemu_add_wait_object: failed\n");
2132        }
2133    }
2134
2135    dwMode |= ENABLE_LINE_INPUT;
2136
2137    if (is_console) {
2138        /* set the terminal in raw mode */
2139        /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2140        dwMode |= ENABLE_PROCESSED_INPUT;
2141    }
2142
2143    SetConsoleMode(stdio->hStdIn, dwMode);
2144
2145    chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
2146    qemu_chr_fe_set_echo(chr, false);
2147
2148    return chr;
2149}
2150#endif /* !_WIN32 */
2151
2152
2153/***********************************************************/
2154/* UDP Net console */
2155
2156typedef struct {
2157    int fd;
2158    GIOChannel *chan;
2159    uint8_t buf[READ_BUF_LEN];
2160    int bufcnt;
2161    int bufptr;
2162    int max_size;
2163} NetCharDriver;
2164
2165static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2166{
2167    NetCharDriver *s = chr->opaque;
2168    gsize bytes_written;
2169    GIOStatus status;
2170
2171    status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
2172    if (status == G_IO_STATUS_EOF) {
2173        return 0;
2174    } else if (status != G_IO_STATUS_NORMAL) {
2175        return -1;
2176    }
2177
2178    return bytes_written;
2179}
2180
2181static int udp_chr_read_poll(void *opaque)
2182{
2183    CharDriverState *chr = opaque;
2184    NetCharDriver *s = chr->opaque;
2185
2186    s->max_size = qemu_chr_be_can_write(chr);
2187
2188    /* If there were any stray characters in the queue process them
2189     * first
2190     */
2191    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2192        qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2193        s->bufptr++;
2194        s->max_size = qemu_chr_be_can_write(chr);
2195    }
2196    return s->max_size;
2197}
2198
2199static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2200{
2201    CharDriverState *chr = opaque;
2202    NetCharDriver *s = chr->opaque;
2203    gsize bytes_read = 0;
2204    GIOStatus status;
2205
2206    if (s->max_size == 0) {
2207        return TRUE;
2208    }
2209    status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
2210                                     &bytes_read, NULL);
2211    s->bufcnt = bytes_read;
2212    s->bufptr = s->bufcnt;
2213    if (status != G_IO_STATUS_NORMAL) {
2214        remove_fd_in_watch(chr);
2215        return FALSE;
2216    }
2217
2218    s->bufptr = 0;
2219    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2220        qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2221        s->bufptr++;
2222        s->max_size = qemu_chr_be_can_write(chr);
2223    }
2224
2225    return TRUE;
2226}
2227
2228static void udp_chr_update_read_handler(CharDriverState *chr)
2229{
2230    NetCharDriver *s = chr->opaque;
2231
2232    remove_fd_in_watch(chr);
2233    if (s->chan) {
2234        chr->fd_in_tag = io_add_watch_poll(s->chan, udp_chr_read_poll,
2235                                           udp_chr_read, chr);
2236    }
2237}
2238
2239static void udp_chr_close(CharDriverState *chr)
2240{
2241    NetCharDriver *s = chr->opaque;
2242
2243    remove_fd_in_watch(chr);
2244    if (s->chan) {
2245        g_io_channel_unref(s->chan);
2246        closesocket(s->fd);
2247    }
2248    g_free(s);
2249    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2250}
2251
2252static CharDriverState *qemu_chr_open_udp_fd(int fd)
2253{
2254    CharDriverState *chr = NULL;
2255    NetCharDriver *s = NULL;
2256
2257    chr = g_malloc0(sizeof(CharDriverState));
2258    s = g_malloc0(sizeof(NetCharDriver));
2259
2260    s->fd = fd;
2261    s->chan = io_channel_from_socket(s->fd);
2262    s->bufcnt = 0;
2263    s->bufptr = 0;
2264    chr->opaque = s;
2265    chr->chr_write = udp_chr_write;
2266    chr->chr_update_read_handler = udp_chr_update_read_handler;
2267    chr->chr_close = udp_chr_close;
2268    /* be isn't opened until we get a connection */
2269    chr->explicit_be_open = true;
2270    return chr;
2271}
2272
2273static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2274{
2275    Error *local_err = NULL;
2276    int fd = -1;
2277
2278    fd = inet_dgram_opts(opts, &local_err);
2279    if (fd < 0) {
2280        qerror_report_err(local_err);
2281        error_free(local_err);
2282        return NULL;
2283    }
2284    return qemu_chr_open_udp_fd(fd);
2285}
2286
2287/***********************************************************/
2288/* TCP Net console */
2289
2290typedef struct {
2291
2292    GIOChannel *chan, *listen_chan;
2293    guint listen_tag;
2294    int fd, listen_fd;
2295    int connected;
2296    int max_size;
2297    int do_telnetopt;
2298    int do_nodelay;
2299    int is_unix;
2300    int msgfd;
2301} TCPCharDriver;
2302
2303static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
2304
2305static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2306{
2307    TCPCharDriver *s = chr->opaque;
2308    if (s->connected) {
2309        return io_channel_send(s->chan, buf, len);
2310    } else {
2311        /* XXX: indicate an error ? */
2312        return len;
2313    }
2314}
2315
2316static int tcp_chr_read_poll(void *opaque)
2317{
2318    CharDriverState *chr = opaque;
2319    TCPCharDriver *s = chr->opaque;
2320    if (!s->connected)
2321        return 0;
2322    s->max_size = qemu_chr_be_can_write(chr);
2323    return s->max_size;
2324}
2325
2326#define IAC 255
2327#define IAC_BREAK 243
2328static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2329                                      TCPCharDriver *s,
2330                                      uint8_t *buf, int *size)
2331{
2332    /* Handle any telnet client's basic IAC options to satisfy char by
2333     * char mode with no echo.  All IAC options will be removed from
2334     * the buf and the do_telnetopt variable will be used to track the
2335     * state of the width of the IAC information.
2336     *
2337     * IAC commands come in sets of 3 bytes with the exception of the
2338     * "IAC BREAK" command and the double IAC.
2339     */
2340
2341    int i;
2342    int j = 0;
2343
2344    for (i = 0; i < *size; i++) {
2345        if (s->do_telnetopt > 1) {
2346            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2347                /* Double IAC means send an IAC */
2348                if (j != i)
2349                    buf[j] = buf[i];
2350                j++;
2351                s->do_telnetopt = 1;
2352            } else {
2353                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2354                    /* Handle IAC break commands by sending a serial break */
2355                    qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2356                    s->do_telnetopt++;
2357                }
2358                s->do_telnetopt++;
2359            }
2360            if (s->do_telnetopt >= 4) {
2361                s->do_telnetopt = 1;
2362            }
2363        } else {
2364            if ((unsigned char)buf[i] == IAC) {
2365                s->do_telnetopt = 2;
2366            } else {
2367                if (j != i)
2368                    buf[j] = buf[i];
2369                j++;
2370            }
2371        }
2372    }
2373    *size = j;
2374}
2375
2376static int tcp_get_msgfd(CharDriverState *chr)
2377{
2378    TCPCharDriver *s = chr->opaque;
2379    int fd = s->msgfd;
2380    s->msgfd = -1;
2381    return fd;
2382}
2383
2384#ifndef _WIN32
2385static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2386{
2387    TCPCharDriver *s = chr->opaque;
2388    struct cmsghdr *cmsg;
2389
2390    for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2391        int fd;
2392
2393        if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2394            cmsg->cmsg_level != SOL_SOCKET ||
2395            cmsg->cmsg_type != SCM_RIGHTS)
2396            continue;
2397
2398        fd = *((int *)CMSG_DATA(cmsg));
2399        if (fd < 0)
2400            continue;
2401
2402        /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
2403        qemu_set_block(fd);
2404
2405#ifndef MSG_CMSG_CLOEXEC
2406        qemu_set_cloexec(fd);
2407#endif
2408        if (s->msgfd != -1)
2409            close(s->msgfd);
2410        s->msgfd = fd;
2411    }
2412}
2413
2414static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2415{
2416    TCPCharDriver *s = chr->opaque;
2417    struct msghdr msg = { NULL, };
2418    struct iovec iov[1];
2419    union {
2420        struct cmsghdr cmsg;
2421        char control[CMSG_SPACE(sizeof(int))];
2422    } msg_control;
2423    int flags = 0;
2424    ssize_t ret;
2425
2426    iov[0].iov_base = buf;
2427    iov[0].iov_len = len;
2428
2429    msg.msg_iov = iov;
2430    msg.msg_iovlen = 1;
2431    msg.msg_control = &msg_control;
2432    msg.msg_controllen = sizeof(msg_control);
2433
2434#ifdef MSG_CMSG_CLOEXEC
2435    flags |= MSG_CMSG_CLOEXEC;
2436#endif
2437    ret = recvmsg(s->fd, &msg, flags);
2438    if (ret > 0 && s->is_unix) {
2439        unix_process_msgfd(chr, &msg);
2440    }
2441
2442    return ret;
2443}
2444#else
2445static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2446{
2447    TCPCharDriver *s = chr->opaque;
2448    return qemu_recv(s->fd, buf, len, 0);
2449}
2450#endif
2451
2452static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
2453{
2454    TCPCharDriver *s = chr->opaque;
2455    return g_io_create_watch(s->chan, cond);
2456}
2457
2458static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
2459{
2460    CharDriverState *chr = opaque;
2461    TCPCharDriver *s = chr->opaque;
2462    uint8_t buf[READ_BUF_LEN];
2463    int len, size;
2464
2465    if (!s->connected || s->max_size <= 0) {
2466        return TRUE;
2467    }
2468    len = sizeof(buf);
2469    if (len > s->max_size)
2470        len = s->max_size;
2471    size = tcp_chr_recv(chr, (void *)buf, len);
2472    if (size == 0) {
2473        /* connection closed */
2474        s->connected = 0;
2475        if (s->listen_chan) {
2476            s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2477        }
2478        remove_fd_in_watch(chr);
2479        g_io_channel_unref(s->chan);
2480        s->chan = NULL;
2481        closesocket(s->fd);
2482        s->fd = -1;
2483        qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2484    } else if (size > 0) {
2485        if (s->do_telnetopt)
2486            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2487        if (size > 0)
2488            qemu_chr_be_write(chr, buf, size);
2489    }
2490
2491    return TRUE;
2492}
2493
2494#ifndef _WIN32
2495CharDriverState *qemu_chr_open_eventfd(int eventfd)
2496{
2497    return qemu_chr_open_fd(eventfd, eventfd);
2498}
2499#endif
2500
2501static void tcp_chr_connect(void *opaque)
2502{
2503    CharDriverState *chr = opaque;
2504    TCPCharDriver *s = chr->opaque;
2505
2506    s->connected = 1;
2507    if (s->chan) {
2508        chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2509                                           tcp_chr_read, chr);
2510    }
2511    qemu_chr_be_generic_open(chr);
2512}
2513
2514static void tcp_chr_update_read_handler(CharDriverState *chr)
2515{
2516    TCPCharDriver *s = chr->opaque;
2517
2518    remove_fd_in_watch(chr);
2519    if (s->chan) {
2520        chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
2521                                           tcp_chr_read, chr);
2522    }
2523}
2524
2525#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2526static void tcp_chr_telnet_init(int fd)
2527{
2528    char buf[3];
2529    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2530    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2531    send(fd, (char *)buf, 3, 0);
2532    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2533    send(fd, (char *)buf, 3, 0);
2534    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2535    send(fd, (char *)buf, 3, 0);
2536    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2537    send(fd, (char *)buf, 3, 0);
2538}
2539
2540static int tcp_chr_add_client(CharDriverState *chr, int fd)
2541{
2542    TCPCharDriver *s = chr->opaque;
2543    if (s->fd != -1)
2544        return -1;
2545
2546    qemu_set_nonblock(fd);
2547    if (s->do_nodelay)
2548        socket_set_nodelay(fd);
2549    s->fd = fd;
2550    s->chan = io_channel_from_socket(fd);
2551    if (s->listen_tag) {
2552        g_source_remove(s->listen_tag);
2553        s->listen_tag = 0;
2554    }
2555    tcp_chr_connect(chr);
2556
2557    return 0;
2558}
2559
2560static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
2561{
2562    CharDriverState *chr = opaque;
2563    TCPCharDriver *s = chr->opaque;
2564    struct sockaddr_in saddr;
2565#ifndef _WIN32
2566    struct sockaddr_un uaddr;
2567#endif
2568    struct sockaddr *addr;
2569    socklen_t len;
2570    int fd;
2571
2572    for(;;) {
2573#ifndef _WIN32
2574        if (s->is_unix) {
2575            len = sizeof(uaddr);
2576            addr = (struct sockaddr *)&uaddr;
2577        } else
2578#endif
2579        {
2580            len = sizeof(saddr);
2581            addr = (struct sockaddr *)&saddr;
2582        }
2583        fd = qemu_accept(s->listen_fd, addr, &len);
2584        if (fd < 0 && errno != EINTR) {
2585            s->listen_tag = 0;
2586            return FALSE;
2587        } else if (fd >= 0) {
2588            if (s->do_telnetopt)
2589                tcp_chr_telnet_init(fd);
2590            break;
2591        }
2592    }
2593    if (tcp_chr_add_client(chr, fd) < 0)
2594        close(fd);
2595
2596    return TRUE;
2597}
2598
2599static void tcp_chr_close(CharDriverState *chr)
2600{
2601    TCPCharDriver *s = chr->opaque;
2602    if (s->fd >= 0) {
2603        remove_fd_in_watch(chr);
2604        if (s->chan) {
2605            g_io_channel_unref(s->chan);
2606        }
2607        closesocket(s->fd);
2608    }
2609    if (s->listen_fd >= 0) {
2610        if (s->listen_tag) {
2611            g_source_remove(s->listen_tag);
2612            s->listen_tag = 0;
2613        }
2614        if (s->listen_chan) {
2615            g_io_channel_unref(s->listen_chan);
2616        }
2617        closesocket(s->listen_fd);
2618    }
2619    g_free(s);
2620    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2621}
2622
2623static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
2624                                                bool is_listen, bool is_telnet,
2625                                                bool is_waitconnect,
2626                                                Error **errp)
2627{
2628    CharDriverState *chr = NULL;
2629    TCPCharDriver *s = NULL;
2630    char host[NI_MAXHOST], serv[NI_MAXSERV];
2631    const char *left = "", *right = "";
2632    struct sockaddr_storage ss;
2633    socklen_t ss_len = sizeof(ss);
2634
2635    memset(&ss, 0, ss_len);
2636    if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2637        error_setg_errno(errp, errno, "getsockname");
2638        return NULL;
2639    }
2640
2641    chr = g_malloc0(sizeof(CharDriverState));
2642    s = g_malloc0(sizeof(TCPCharDriver));
2643
2644    s->connected = 0;
2645    s->fd = -1;
2646    s->listen_fd = -1;
2647    s->msgfd = -1;
2648
2649    chr->filename = g_malloc(256);
2650    switch (ss.ss_family) {
2651#ifndef _WIN32
2652    case AF_UNIX:
2653        s->is_unix = 1;
2654        snprintf(chr->filename, 256, "unix:%s%s",
2655                 ((struct sockaddr_un *)(&ss))->sun_path,
2656                 is_listen ? ",server" : "");
2657        break;
2658#endif
2659    case AF_INET6:
2660        left  = "[";
2661        right = "]";
2662        /* fall through */
2663    case AF_INET:
2664        s->do_nodelay = do_nodelay;
2665        getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
2666                    serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2667        snprintf(chr->filename, 256, "%s:%s%s%s:%s%s",
2668                 is_telnet ? "telnet" : "tcp",
2669                 left, host, right, serv,
2670                 is_listen ? ",server" : "");
2671        break;
2672    }
2673
2674    chr->opaque = s;
2675    chr->chr_write = tcp_chr_write;
2676    chr->chr_close = tcp_chr_close;
2677    chr->get_msgfd = tcp_get_msgfd;
2678    chr->chr_add_client = tcp_chr_add_client;
2679    chr->chr_add_watch = tcp_chr_add_watch;
2680    chr->chr_update_read_handler = tcp_chr_update_read_handler;
2681    /* be isn't opened until we get a connection */
2682    chr->explicit_be_open = true;
2683
2684    if (is_listen) {
2685        s->listen_fd = fd;
2686        s->listen_chan = io_channel_from_socket(s->listen_fd);
2687        s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2688        if (is_telnet) {
2689            s->do_telnetopt = 1;
2690        }
2691    } else {
2692        s->connected = 1;
2693        s->fd = fd;
2694        socket_set_nodelay(fd);
2695        s->chan = io_channel_from_socket(s->fd);
2696        tcp_chr_connect(chr);
2697    }
2698
2699    if (is_listen && is_waitconnect) {
2700        fprintf(stderr, "QEMU waiting for connection on: %s\n",
2701                chr->filename);
2702        tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2703        qemu_set_nonblock(s->listen_fd);
2704    }
2705    return chr;
2706}
2707
2708static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2709{
2710    CharDriverState *chr = NULL;
2711    Error *local_err = NULL;
2712    int fd = -1;
2713
2714    bool is_listen      = qemu_opt_get_bool(opts, "server", false);
2715    bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
2716    bool is_telnet      = qemu_opt_get_bool(opts, "telnet", false);
2717    bool do_nodelay     = !qemu_opt_get_bool(opts, "delay", true);
2718    bool is_unix        = qemu_opt_get(opts, "path") != NULL;
2719
2720    if (is_unix) {
2721        if (is_listen) {
2722            fd = unix_listen_opts(opts, &local_err);
2723        } else {
2724            fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2725        }
2726    } else {
2727        if (is_listen) {
2728            fd = inet_listen_opts(opts, 0, &local_err);
2729        } else {
2730            fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2731        }
2732    }
2733    if (fd < 0) {
2734        goto fail;
2735    }
2736
2737    if (!is_waitconnect)
2738        qemu_set_nonblock(fd);
2739
2740    chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
2741                                  is_waitconnect, &local_err);
2742    if (error_is_set(&local_err)) {
2743        goto fail;
2744    }
2745    return chr;
2746
2747
2748 fail:
2749    if (local_err) {
2750        qerror_report_err(local_err);
2751        error_free(local_err);
2752    }
2753    if (fd >= 0) {
2754        closesocket(fd);
2755    }
2756    if (chr) {
2757        g_free(chr->opaque);
2758        g_free(chr);
2759    }
2760    return NULL;
2761}
2762
2763/*********************************************************/
2764/* Ring buffer chardev */
2765
2766typedef struct {
2767    size_t size;
2768    size_t prod;
2769    size_t cons;
2770    uint8_t *cbuf;
2771} RingBufCharDriver;
2772
2773static size_t ringbuf_count(const CharDriverState *chr)
2774{
2775    const RingBufCharDriver *d = chr->opaque;
2776
2777    return d->prod - d->cons;
2778}
2779
2780static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2781{
2782    RingBufCharDriver *d = chr->opaque;
2783    int i;
2784
2785    if (!buf || (len < 0)) {
2786        return -1;
2787    }
2788
2789    for (i = 0; i < len; i++ ) {
2790        d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
2791        if (d->prod - d->cons > d->size) {
2792            d->cons = d->prod - d->size;
2793        }
2794    }
2795
2796    return 0;
2797}
2798
2799static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
2800{
2801    RingBufCharDriver *d = chr->opaque;
2802    int i;
2803
2804    for (i = 0; i < len && d->cons != d->prod; i++) {
2805        buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
2806    }
2807
2808    return i;
2809}
2810
2811static void ringbuf_chr_close(struct CharDriverState *chr)
2812{
2813    RingBufCharDriver *d = chr->opaque;
2814
2815    g_free(d->cbuf);
2816    g_free(d);
2817    chr->opaque = NULL;
2818}
2819
2820static CharDriverState *qemu_chr_open_ringbuf(ChardevRingbuf *opts,
2821                                              Error **errp)
2822{
2823    CharDriverState *chr;
2824    RingBufCharDriver *d;
2825
2826    chr = g_malloc0(sizeof(CharDriverState));
2827    d = g_malloc(sizeof(*d));
2828
2829    d->size = opts->has_size ? opts->size : 65536;
2830
2831    /* The size must be power of 2 */
2832    if (d->size & (d->size - 1)) {
2833        error_setg(errp, "size of ringbuf chardev must be power of two");
2834        goto fail;
2835    }
2836
2837    d->prod = 0;
2838    d->cons = 0;
2839    d->cbuf = g_malloc0(d->size);
2840
2841    chr->opaque = d;
2842    chr->chr_write = ringbuf_chr_write;
2843    chr->chr_close = ringbuf_chr_close;
2844
2845    return chr;
2846
2847fail:
2848    g_free(d);
2849    g_free(chr);
2850    return NULL;
2851}
2852
2853static bool chr_is_ringbuf(const CharDriverState *chr)
2854{
2855    return chr->chr_write == ringbuf_chr_write;
2856}
2857
2858void qmp_ringbuf_write(const char *device, const char *data,
2859                       bool has_format, enum DataFormat format,
2860                       Error **errp)
2861{
2862    CharDriverState *chr;
2863    const uint8_t *write_data;
2864    int ret;
2865    gsize write_count;
2866
2867    chr = qemu_chr_find(device);
2868    if (!chr) {
2869        error_setg(errp, "Device '%s' not found", device);
2870        return;
2871    }
2872
2873    if (!chr_is_ringbuf(chr)) {
2874        error_setg(errp,"%s is not a ringbuf device", device);
2875        return;
2876    }
2877
2878    if (has_format && (format == DATA_FORMAT_BASE64)) {
2879        write_data = g_base64_decode(data, &write_count);
2880    } else {
2881        write_data = (uint8_t *)data;
2882        write_count = strlen(data);
2883    }
2884
2885    ret = ringbuf_chr_write(chr, write_data, write_count);
2886
2887    if (write_data != (uint8_t *)data) {
2888        g_free((void *)write_data);
2889    }
2890
2891    if (ret < 0) {
2892        error_setg(errp, "Failed to write to device %s", device);
2893        return;
2894    }
2895}
2896
2897char *qmp_ringbuf_read(const char *device, int64_t size,
2898                       bool has_format, enum DataFormat format,
2899                       Error **errp)
2900{
2901    CharDriverState *chr;
2902    uint8_t *read_data;
2903    size_t count;
2904    char *data;
2905
2906    chr = qemu_chr_find(device);
2907    if (!chr) {
2908        error_setg(errp, "Device '%s' not found", device);
2909        return NULL;
2910    }
2911
2912    if (!chr_is_ringbuf(chr)) {
2913        error_setg(errp,"%s is not a ringbuf device", device);
2914        return NULL;
2915    }
2916
2917    if (size <= 0) {
2918        error_setg(errp, "size must be greater than zero");
2919        return NULL;
2920    }
2921
2922    count = ringbuf_count(chr);
2923    size = size > count ? count : size;
2924    read_data = g_malloc(size + 1);
2925
2926    ringbuf_chr_read(chr, read_data, size);
2927
2928    if (has_format && (format == DATA_FORMAT_BASE64)) {
2929        data = g_base64_encode(read_data, size);
2930        g_free(read_data);
2931    } else {
2932        /*
2933         * FIXME should read only complete, valid UTF-8 characters up
2934         * to @size bytes.  Invalid sequences should be replaced by a
2935         * suitable replacement character.  Except when (and only
2936         * when) ring buffer lost characters since last read, initial
2937         * continuation characters should be dropped.
2938         */
2939        read_data[size] = 0;
2940        data = (char *)read_data;
2941    }
2942
2943    return data;
2944}
2945
2946QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2947{
2948    char host[65], port[33], width[8], height[8];
2949    int pos;
2950    const char *p;
2951    QemuOpts *opts;
2952    Error *local_err = NULL;
2953
2954    opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
2955    if (error_is_set(&local_err)) {
2956        qerror_report_err(local_err);
2957        error_free(local_err);
2958        return NULL;
2959    }
2960
2961    if (strstart(filename, "mon:", &p)) {
2962        filename = p;
2963        qemu_opt_set(opts, "mux", "on");
2964        if (strcmp(filename, "stdio") == 0) {
2965            /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
2966             * but pass it to the guest.  Handle this only for compat syntax,
2967             * for -chardev syntax we have special option for this.
2968             * This is what -nographic did, redirecting+muxing serial+monitor
2969             * to stdio causing Ctrl+C to be passed to guest. */
2970            qemu_opt_set(opts, "signal", "off");
2971        }
2972    }
2973
2974    if (strcmp(filename, "null")    == 0 ||
2975        strcmp(filename, "pty")     == 0 ||
2976        strcmp(filename, "msmouse") == 0 ||
2977        strcmp(filename, "braille") == 0 ||
2978        strcmp(filename, "stdio")   == 0) {
2979        qemu_opt_set(opts, "backend", filename);
2980        return opts;
2981    }
2982    if (strstart(filename, "vc", &p)) {
2983        qemu_opt_set(opts, "backend", "vc");
2984        if (*p == ':') {
2985            if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
2986                /* pixels */
2987                qemu_opt_set(opts, "width", width);
2988                qemu_opt_set(opts, "height", height);
2989            } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
2990                /* chars */
2991                qemu_opt_set(opts, "cols", width);
2992                qemu_opt_set(opts, "rows", height);
2993            } else {
2994                goto fail;
2995            }
2996        }
2997        return opts;
2998    }
2999    if (strcmp(filename, "con:") == 0) {
3000        qemu_opt_set(opts, "backend", "console");
3001        return opts;
3002    }
3003    if (strstart(filename, "COM", NULL)) {
3004        qemu_opt_set(opts, "backend", "serial");
3005        qemu_opt_set(opts, "path", filename);
3006        return opts;
3007    }
3008    if (strstart(filename, "file:", &p)) {
3009        qemu_opt_set(opts, "backend", "file");
3010        qemu_opt_set(opts, "path", p);
3011        return opts;
3012    }
3013    if (strstart(filename, "pipe:", &p)) {
3014        qemu_opt_set(opts, "backend", "pipe");
3015        qemu_opt_set(opts, "path", p);
3016        return opts;
3017    }
3018    if (strstart(filename, "tcp:", &p) ||
3019        strstart(filename, "telnet:", &p)) {
3020        if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3021            host[0] = 0;
3022            if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
3023                goto fail;
3024        }
3025        qemu_opt_set(opts, "backend", "socket");
3026        qemu_opt_set(opts, "host", host);
3027        qemu_opt_set(opts, "port", port);
3028        if (p[pos] == ',') {
3029            if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
3030                goto fail;
3031        }
3032        if (strstart(filename, "telnet:", &p))
3033            qemu_opt_set(opts, "telnet", "on");
3034        return opts;
3035    }
3036    if (strstart(filename, "udp:", &p)) {
3037        qemu_opt_set(opts, "backend", "udp");
3038        if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
3039            host[0] = 0;
3040            if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
3041                goto fail;
3042            }
3043        }
3044        qemu_opt_set(opts, "host", host);
3045        qemu_opt_set(opts, "port", port);
3046        if (p[pos] == '@') {
3047            p += pos + 1;
3048            if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
3049                host[0] = 0;
3050                if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
3051                    goto fail;
3052                }
3053            }
3054            qemu_opt_set(opts, "localaddr", host);
3055            qemu_opt_set(opts, "localport", port);
3056        }
3057        return opts;
3058    }
3059    if (strstart(filename, "unix:", &p)) {
3060        qemu_opt_set(opts, "backend", "socket");
3061        if (qemu_opts_do_parse(opts, p, "path") != 0)
3062            goto fail;
3063        return opts;
3064    }
3065    if (strstart(filename, "/dev/parport", NULL) ||
3066        strstart(filename, "/dev/ppi", NULL)) {
3067        qemu_opt_set(opts, "backend", "parport");
3068        qemu_opt_set(opts, "path", filename);
3069        return opts;
3070    }
3071    if (strstart(filename, "/dev/", NULL)) {
3072        qemu_opt_set(opts, "backend", "tty");
3073        qemu_opt_set(opts, "path", filename);
3074        return opts;
3075    }
3076
3077fail:
3078    qemu_opts_del(opts);
3079    return NULL;
3080}
3081
3082static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
3083                                    Error **errp)
3084{
3085    const char *path = qemu_opt_get(opts, "path");
3086
3087    if (path == NULL) {
3088        error_setg(errp, "chardev: file: no filename given");
3089        return;
3090    }
3091    backend->file = g_new0(ChardevFile, 1);
3092    backend->file->out = g_strdup(path);
3093}
3094
3095static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
3096                                 Error **errp)
3097{
3098    backend->stdio = g_new0(ChardevStdio, 1);
3099    backend->stdio->has_signal = true;
3100    backend->stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3101}
3102
3103static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
3104                                  Error **errp)
3105{
3106    const char *device = qemu_opt_get(opts, "path");
3107
3108    if (device == NULL) {
3109        error_setg(errp, "chardev: serial/tty: no device path given");
3110        return;
3111    }
3112    backend->serial = g_new0(ChardevHostdev, 1);
3113    backend->serial->device = g_strdup(device);
3114}
3115
3116static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
3117                                    Error **errp)
3118{
3119    const char *device = qemu_opt_get(opts, "path");
3120
3121    if (device == NULL) {
3122        error_setg(errp, "chardev: parallel: no device path given");
3123        return;
3124    }
3125    backend->parallel = g_new0(ChardevHostdev, 1);
3126    backend->parallel->device = g_strdup(device);
3127}
3128
3129static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
3130                                Error **errp)
3131{
3132    const char *device = qemu_opt_get(opts, "path");
3133
3134    if (device == NULL) {
3135        error_setg(errp, "chardev: pipe: no device path given");
3136        return;
3137    }
3138    backend->pipe = g_new0(ChardevHostdev, 1);
3139    backend->pipe->device = g_strdup(device);
3140}
3141
3142static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
3143                                   Error **errp)
3144{
3145    int val;
3146
3147    backend->ringbuf = g_new0(ChardevRingbuf, 1);
3148
3149    val = qemu_opt_get_size(opts, "size", 0);
3150    if (val != 0) {
3151        backend->ringbuf->has_size = true;
3152        backend->ringbuf->size = val;
3153    }
3154}
3155
3156static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
3157                               Error **errp)
3158{
3159    const char *chardev = qemu_opt_get(opts, "chardev");
3160
3161    if (chardev == NULL) {
3162        error_setg(errp, "chardev: mux: no chardev given");
3163        return;
3164    }
3165    backend->mux = g_new0(ChardevMux, 1);
3166    backend->mux->chardev = g_strdup(chardev);
3167}
3168
3169typedef struct CharDriver {
3170    const char *name;
3171    /* old, pre qapi */
3172    CharDriverState *(*open)(QemuOpts *opts);
3173    /* new, qapi-based */
3174    ChardevBackendKind kind;
3175    void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3176} CharDriver;
3177
3178static GSList *backends;
3179
3180void register_char_driver(const char *name, CharDriverState *(*open)(QemuOpts *))
3181{
3182    CharDriver *s;
3183
3184    s = g_malloc0(sizeof(*s));
3185    s->name = g_strdup(name);
3186    s->open = open;
3187
3188    backends = g_slist_append(backends, s);
3189}
3190
3191void register_char_driver_qapi(const char *name, ChardevBackendKind kind,
3192        void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
3193{
3194    CharDriver *s;
3195
3196    s = g_malloc0(sizeof(*s));
3197    s->name = g_strdup(name);
3198    s->kind = kind;
3199    s->parse = parse;
3200
3201    backends = g_slist_append(backends, s);
3202}
3203
3204CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3205                                    void (*init)(struct CharDriverState *s),
3206                                    Error **errp)
3207{
3208    CharDriver *cd;
3209    CharDriverState *chr;
3210    GSList *i;
3211
3212    if (qemu_opts_id(opts) == NULL) {
3213        error_setg(errp, "chardev: no id specified");
3214        goto err;
3215    }
3216
3217    if (qemu_opt_get(opts, "backend") == NULL) {
3218        error_setg(errp, "chardev: \"%s\" missing backend",
3219                   qemu_opts_id(opts));
3220        goto err;
3221    }
3222    for (i = backends; i; i = i->next) {
3223        cd = i->data;
3224
3225        if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3226            break;
3227        }
3228    }
3229    if (i == NULL) {
3230        error_setg(errp, "chardev: backend \"%s\" not found",
3231                   qemu_opt_get(opts, "backend"));
3232        goto err;
3233    }
3234
3235    if (!cd->open) {
3236        /* using new, qapi init */
3237        ChardevBackend *backend = g_new0(ChardevBackend, 1);
3238        ChardevReturn *ret = NULL;
3239        const char *id = qemu_opts_id(opts);
3240        char *bid = NULL;
3241
3242        if (qemu_opt_get_bool(opts, "mux", 0)) {
3243            bid = g_strdup_printf("%s-base", id);
3244        }
3245
3246        chr = NULL;
3247        backend->kind = cd->kind;
3248        if (cd->parse) {
3249            cd->parse(opts, backend, errp);
3250            if (error_is_set(errp)) {
3251                goto qapi_out;
3252            }
3253        }
3254        ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3255        if (error_is_set(errp)) {
3256            goto qapi_out;
3257        }
3258
3259        if (bid) {
3260            qapi_free_ChardevBackend(backend);
3261            qapi_free_ChardevReturn(ret);
3262            backend = g_new0(ChardevBackend, 1);
3263            backend->mux = g_new0(ChardevMux, 1);
3264            backend->kind = CHARDEV_BACKEND_KIND_MUX;
3265            backend->mux->chardev = g_strdup(bid);
3266            ret = qmp_chardev_add(id, backend, errp);
3267            if (error_is_set(errp)) {
3268                chr = qemu_chr_find(bid);
3269                qemu_chr_delete(chr);
3270                chr = NULL;
3271                goto qapi_out;
3272            }
3273        }
3274
3275        chr = qemu_chr_find(id);
3276        chr->opts = opts;
3277
3278    qapi_out:
3279        qapi_free_ChardevBackend(backend);
3280        qapi_free_ChardevReturn(ret);
3281        g_free(bid);
3282        return chr;
3283    }
3284
3285    chr = cd->open(opts);
3286    if (!chr) {
3287        error_setg(errp, "chardev: opening backend \"%s\" failed",
3288                   qemu_opt_get(opts, "backend"));
3289        goto err;
3290    }
3291
3292    if (!chr->filename)
3293        chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3294    chr->init = init;
3295    /* if we didn't create the chardev via qmp_chardev_add, we
3296     * need to send the OPENED event here
3297     */
3298    if (!chr->explicit_be_open) {
3299        qemu_chr_be_event(chr, CHR_EVENT_OPENED);
3300    }
3301    QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3302
3303    if (qemu_opt_get_bool(opts, "mux", 0)) {
3304        CharDriverState *base = chr;
3305        int len = strlen(qemu_opts_id(opts)) + 6;
3306        base->label = g_malloc(len);
3307        snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
3308        chr = qemu_chr_open_mux(base);
3309        chr->filename = base->filename;
3310        chr->avail_connections = MAX_MUX;
3311        QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3312    } else {
3313        chr->avail_connections = 1;
3314    }
3315    chr->label = g_strdup(qemu_opts_id(opts));
3316    chr->opts = opts;
3317    return chr;
3318
3319err:
3320    qemu_opts_del(opts);
3321    return NULL;
3322}
3323
3324CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
3325{
3326    const char *p;
3327    CharDriverState *chr;
3328    QemuOpts *opts;
3329    Error *err = NULL;
3330
3331    if (strstart(filename, "chardev:", &p)) {
3332        return qemu_chr_find(p);
3333    }
3334
3335    opts = qemu_chr_parse_compat(label, filename);
3336    if (!opts)
3337        return NULL;
3338
3339    chr = qemu_chr_new_from_opts(opts, init, &err);
3340    if (error_is_set(&err)) {
3341        error_report("%s", error_get_pretty(err));
3342        error_free(err);
3343    }
3344    if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3345        qemu_chr_fe_claim_no_fail(chr);
3346        monitor_init(chr, MONITOR_USE_READLINE);
3347    }
3348    return chr;
3349}
3350
3351void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
3352{
3353    if (chr->chr_set_echo) {
3354        chr->chr_set_echo(chr, echo);
3355    }
3356}
3357
3358void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3359{
3360    if (chr->fe_open == fe_open) {
3361        return;
3362    }
3363    chr->fe_open = fe_open;
3364    if (chr->chr_set_fe_open) {
3365        chr->chr_set_fe_open(chr, fe_open);
3366    }
3367}
3368
3369int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
3370                          GIOFunc func, void *user_data)
3371{
3372    GSource *src;
3373    guint tag;
3374
3375    if (s->chr_add_watch == NULL) {
3376        return -ENOSYS;
3377    }
3378
3379    src = s->chr_add_watch(s, cond);
3380    g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
3381    tag = g_source_attach(src, NULL);
3382    g_source_unref(src);
3383
3384    return tag;
3385}
3386
3387int qemu_chr_fe_claim(CharDriverState *s)
3388{
3389    if (s->avail_connections < 1) {
3390        return -1;
3391    }
3392    s->avail_connections--;
3393    return 0;
3394}
3395
3396void qemu_chr_fe_claim_no_fail(CharDriverState *s)
3397{
3398    if (qemu_chr_fe_claim(s) != 0) {
3399        fprintf(stderr, "%s: error chardev \"%s\" already used\n",
3400                __func__, s->label);
3401        exit(1);
3402    }
3403}
3404
3405void qemu_chr_fe_release(CharDriverState *s)
3406{
3407    s->avail_connections++;
3408}
3409
3410void qemu_chr_delete(CharDriverState *chr)
3411{
3412    QTAILQ_REMOVE(&chardevs, chr, next);
3413    if (chr->chr_close) {
3414        chr->chr_close(chr);
3415    }
3416    g_free(chr->filename);
3417    g_free(chr->label);
3418    if (chr->opts) {
3419        qemu_opts_del(chr->opts);
3420    }
3421    g_free(chr);
3422}
3423
3424ChardevInfoList *qmp_query_chardev(Error **errp)
3425{
3426    ChardevInfoList *chr_list = NULL;
3427    CharDriverState *chr;
3428
3429    QTAILQ_FOREACH(chr, &chardevs, next) {
3430        ChardevInfoList *info = g_malloc0(sizeof(*info));
3431        info->value = g_malloc0(sizeof(*info->value));
3432        info->value->label = g_strdup(chr->label);
3433        info->value->filename = g_strdup(chr->filename);
3434
3435        info->next = chr_list;
3436        chr_list = info;
3437    }
3438
3439    return chr_list;
3440}
3441
3442CharDriverState *qemu_chr_find(const char *name)
3443{
3444    CharDriverState *chr;
3445
3446    QTAILQ_FOREACH(chr, &chardevs, next) {
3447        if (strcmp(chr->label, name) != 0)
3448            continue;
3449        return chr;
3450    }
3451    return NULL;
3452}
3453
3454/* Get a character (serial) device interface.  */
3455CharDriverState *qemu_char_get_next_serial(void)
3456{
3457    static int next_serial;
3458    CharDriverState *chr;
3459
3460    /* FIXME: This function needs to go away: use chardev properties!  */
3461
3462    while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
3463        chr = serial_hds[next_serial++];
3464        qemu_chr_fe_claim_no_fail(chr);
3465        return chr;
3466    }
3467    return NULL;
3468}
3469
3470QemuOptsList qemu_chardev_opts = {
3471    .name = "chardev",
3472    .implied_opt_name = "backend",
3473    .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
3474    .desc = {
3475        {
3476            .name = "backend",
3477            .type = QEMU_OPT_STRING,
3478        },{
3479            .name = "path",
3480            .type = QEMU_OPT_STRING,
3481        },{
3482            .name = "host",
3483            .type = QEMU_OPT_STRING,
3484        },{
3485            .name = "port",
3486            .type = QEMU_OPT_STRING,
3487        },{
3488            .name = "localaddr",
3489            .type = QEMU_OPT_STRING,
3490        },{
3491            .name = "localport",
3492            .type = QEMU_OPT_STRING,
3493        },{
3494            .name = "to",
3495            .type = QEMU_OPT_NUMBER,
3496        },{
3497            .name = "ipv4",
3498            .type = QEMU_OPT_BOOL,
3499        },{
3500            .name = "ipv6",
3501            .type = QEMU_OPT_BOOL,
3502        },{
3503            .name = "wait",
3504            .type = QEMU_OPT_BOOL,
3505        },{
3506            .name = "server",
3507            .type = QEMU_OPT_BOOL,
3508        },{
3509            .name = "delay",
3510            .type = QEMU_OPT_BOOL,
3511        },{
3512            .name = "telnet",
3513            .type = QEMU_OPT_BOOL,
3514        },{
3515            .name = "width",
3516            .type = QEMU_OPT_NUMBER,
3517        },{
3518            .name = "height",
3519            .type = QEMU_OPT_NUMBER,
3520        },{
3521            .name = "cols",
3522            .type = QEMU_OPT_NUMBER,
3523        },{
3524            .name = "rows",
3525            .type = QEMU_OPT_NUMBER,
3526        },{
3527            .name = "mux",
3528            .type = QEMU_OPT_BOOL,
3529        },{
3530            .name = "signal",
3531            .type = QEMU_OPT_BOOL,
3532        },{
3533            .name = "name",
3534            .type = QEMU_OPT_STRING,
3535        },{
3536            .name = "debug",
3537            .type = QEMU_OPT_NUMBER,
3538        },{
3539            .name = "size",
3540            .type = QEMU_OPT_SIZE,
3541        },{
3542            .name = "chardev",
3543            .type = QEMU_OPT_STRING,
3544        },
3545        { /* end of list */ }
3546    },
3547};
3548
3549#ifdef _WIN32
3550
3551static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3552{
3553    HANDLE out;
3554
3555    if (file->has_in) {
3556        error_setg(errp, "input file not supported");
3557        return NULL;
3558    }
3559
3560    out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3561                     OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3562    if (out == INVALID_HANDLE_VALUE) {
3563        error_setg(errp, "open %s failed", file->out);
3564        return NULL;
3565    }
3566    return qemu_chr_open_win_file(out);
3567}
3568
3569static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3570                                                Error **errp)
3571{
3572    return qemu_chr_open_win_path(serial->device);
3573}
3574
3575static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3576                                                  Error **errp)
3577{
3578    error_setg(errp, "character device backend type 'parallel' not supported");
3579    return NULL;
3580}
3581
3582#else /* WIN32 */
3583
3584static int qmp_chardev_open_file_source(char *src, int flags,
3585                                        Error **errp)
3586{
3587    int fd = -1;
3588
3589    TFR(fd = qemu_open(src, flags, 0666));
3590    if (fd == -1) {
3591        error_setg_file_open(errp, errno, src);
3592    }
3593    return fd;
3594}
3595
3596static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
3597{
3598    int flags, in = -1, out = -1;
3599
3600    flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
3601    out = qmp_chardev_open_file_source(file->out, flags, errp);
3602    if (error_is_set(errp)) {
3603        return NULL;
3604    }
3605
3606    if (file->has_in) {
3607        flags = O_RDONLY;
3608        in = qmp_chardev_open_file_source(file->in, flags, errp);
3609        if (error_is_set(errp)) {
3610            qemu_close(out);
3611            return NULL;
3612        }
3613    }
3614
3615    return qemu_chr_open_fd(in, out);
3616}
3617
3618static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
3619                                                Error **errp)
3620{
3621#ifdef HAVE_CHARDEV_TTY
3622    int fd;
3623
3624    fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3625    if (error_is_set(errp)) {
3626        return NULL;
3627    }
3628    qemu_set_nonblock(fd);
3629    return qemu_chr_open_tty_fd(fd);
3630#else
3631    error_setg(errp, "character device backend type 'serial' not supported");
3632    return NULL;
3633#endif
3634}
3635
3636static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
3637                                                  Error **errp)
3638{
3639#ifdef HAVE_CHARDEV_PARPORT
3640    int fd;
3641
3642    fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3643    if (error_is_set(errp)) {
3644        return NULL;
3645    }
3646    return qemu_chr_open_pp_fd(fd);
3647#else
3648    error_setg(errp, "character device backend type 'parallel' not supported");
3649    return NULL;
3650#endif
3651}
3652
3653#endif /* WIN32 */
3654
3655static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
3656                                                Error **errp)
3657{
3658    SocketAddress *addr = sock->addr;
3659    bool do_nodelay     = sock->has_nodelay ? sock->nodelay : false;
3660    bool is_listen      = sock->has_server  ? sock->server  : true;
3661    bool is_telnet      = sock->has_telnet  ? sock->telnet  : false;
3662    bool is_waitconnect = sock->has_wait    ? sock->wait    : false;
3663    int fd;
3664
3665    if (is_listen) {
3666        fd = socket_listen(addr, errp);
3667    } else {
3668        fd = socket_connect(addr, errp, NULL, NULL);
3669    }
3670    if (error_is_set(errp)) {
3671        return NULL;
3672    }
3673    return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
3674                                   is_telnet, is_waitconnect, errp);
3675}
3676
3677static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
3678                                             Error **errp)
3679{
3680    int fd;
3681
3682    fd = socket_dgram(udp->remote, udp->local, errp);
3683    if (error_is_set(errp)) {
3684        return NULL;
3685    }
3686    return qemu_chr_open_udp_fd(fd);
3687}
3688
3689ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
3690                               Error **errp)
3691{
3692    ChardevReturn *ret = g_new0(ChardevReturn, 1);
3693    CharDriverState *base, *chr = NULL;
3694
3695    chr = qemu_chr_find(id);
3696    if (chr) {
3697        error_setg(errp, "Chardev '%s' already exists", id);
3698        g_free(ret);
3699        return NULL;
3700    }
3701
3702    switch (backend->kind) {
3703    case CHARDEV_BACKEND_KIND_FILE:
3704        chr = qmp_chardev_open_file(backend->file, errp);
3705        break;
3706    case CHARDEV_BACKEND_KIND_SERIAL:
3707        chr = qmp_chardev_open_serial(backend->serial, errp);
3708        break;
3709    case CHARDEV_BACKEND_KIND_PARALLEL:
3710        chr = qmp_chardev_open_parallel(backend->parallel, errp);
3711        break;
3712    case CHARDEV_BACKEND_KIND_PIPE:
3713        chr = qemu_chr_open_pipe(backend->pipe);
3714        break;
3715    case CHARDEV_BACKEND_KIND_SOCKET:
3716        chr = qmp_chardev_open_socket(backend->socket, errp);
3717        break;
3718    case CHARDEV_BACKEND_KIND_UDP:
3719        chr = qmp_chardev_open_udp(backend->udp, errp);
3720        break;
3721#ifdef HAVE_CHARDEV_TTY
3722    case CHARDEV_BACKEND_KIND_PTY:
3723        chr = qemu_chr_open_pty(id, ret);
3724        break;
3725#endif
3726    case CHARDEV_BACKEND_KIND_NULL:
3727        chr = qemu_chr_open_null();
3728        break;
3729    case CHARDEV_BACKEND_KIND_MUX:
3730        base = qemu_chr_find(backend->mux->chardev);
3731        if (base == NULL) {
3732            error_setg(errp, "mux: base chardev %s not found",
3733                       backend->mux->chardev);
3734            break;
3735        }
3736        chr = qemu_chr_open_mux(base);
3737        break;
3738    case CHARDEV_BACKEND_KIND_MSMOUSE:
3739        chr = qemu_chr_open_msmouse();
3740        break;
3741#ifdef CONFIG_BRLAPI
3742    case CHARDEV_BACKEND_KIND_BRAILLE:
3743        chr = chr_baum_init();
3744        break;
3745#endif
3746    case CHARDEV_BACKEND_KIND_STDIO:
3747        chr = qemu_chr_open_stdio(backend->stdio);
3748        break;
3749#ifdef _WIN32
3750    case CHARDEV_BACKEND_KIND_CONSOLE:
3751        chr = qemu_chr_open_win_con();
3752        break;
3753#endif
3754#ifdef CONFIG_SPICE
3755    case CHARDEV_BACKEND_KIND_SPICEVMC:
3756        chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
3757        break;
3758    case CHARDEV_BACKEND_KIND_SPICEPORT:
3759        chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
3760        break;
3761#endif
3762    case CHARDEV_BACKEND_KIND_VC:
3763        chr = vc_init(backend->vc);
3764        break;
3765    case CHARDEV_BACKEND_KIND_RINGBUF:
3766    case CHARDEV_BACKEND_KIND_MEMORY:
3767        chr = qemu_chr_open_ringbuf(backend->ringbuf, errp);
3768        break;
3769    default:
3770        error_setg(errp, "unknown chardev backend (%d)", backend->kind);
3771        break;
3772    }
3773
3774    if (chr == NULL && !error_is_set(errp)) {
3775        error_setg(errp, "Failed to create chardev");
3776    }
3777    if (chr) {
3778        chr->label = g_strdup(id);
3779        chr->avail_connections =
3780            (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
3781        if (!chr->filename) {
3782            chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
3783        }
3784        if (!chr->explicit_be_open) {
3785            qemu_chr_be_event(chr, CHR_EVENT_OPENED);
3786        }
3787        QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3788        return ret;
3789    } else {
3790        g_free(ret);
3791        return NULL;
3792    }
3793}
3794
3795void qmp_chardev_remove(const char *id, Error **errp)
3796{
3797    CharDriverState *chr;
3798
3799    chr = qemu_chr_find(id);
3800    if (NULL == chr) {
3801        error_setg(errp, "Chardev '%s' not found", id);
3802        return;
3803    }
3804    if (chr->chr_can_read || chr->chr_read ||
3805        chr->chr_event || chr->handler_opaque) {
3806        error_setg(errp, "Chardev '%s' is busy", id);
3807        return;
3808    }
3809    qemu_chr_delete(chr);
3810}
3811
3812static void register_types(void)
3813{
3814    register_char_driver_qapi("null", CHARDEV_BACKEND_KIND_NULL, NULL);
3815    register_char_driver("socket", qemu_chr_open_socket);
3816    register_char_driver("udp", qemu_chr_open_udp);
3817    register_char_driver_qapi("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
3818                              qemu_chr_parse_ringbuf);
3819    register_char_driver_qapi("file", CHARDEV_BACKEND_KIND_FILE,
3820                              qemu_chr_parse_file_out);
3821    register_char_driver_qapi("stdio", CHARDEV_BACKEND_KIND_STDIO,
3822                              qemu_chr_parse_stdio);
3823    register_char_driver_qapi("serial", CHARDEV_BACKEND_KIND_SERIAL,
3824                              qemu_chr_parse_serial);
3825    register_char_driver_qapi("tty", CHARDEV_BACKEND_KIND_SERIAL,
3826                              qemu_chr_parse_serial);
3827    register_char_driver_qapi("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
3828                              qemu_chr_parse_parallel);
3829    register_char_driver_qapi("parport", CHARDEV_BACKEND_KIND_PARALLEL,
3830                              qemu_chr_parse_parallel);
3831    register_char_driver_qapi("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
3832    register_char_driver_qapi("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
3833    register_char_driver_qapi("pipe", CHARDEV_BACKEND_KIND_PIPE,
3834                              qemu_chr_parse_pipe);
3835    register_char_driver_qapi("mux", CHARDEV_BACKEND_KIND_MUX,
3836                              qemu_chr_parse_mux);
3837    /* Bug-compatibility: */
3838    register_char_driver_qapi("memory", CHARDEV_BACKEND_KIND_MEMORY,
3839                              qemu_chr_parse_ringbuf);
3840    /* this must be done after machine init, since we register FEs with muxes
3841     * as part of realize functions like serial_isa_realizefn when -nographic
3842     * is specified
3843     */
3844    qemu_add_machine_init_done_notifier(&muxes_realize_notify);
3845}
3846
3847type_init(register_types);
3848