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