qemu-char.c 113 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 * QEMU System Emulator
 *
 * Copyright (c) 2003-2008 Fabrice Bellard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include "qemu-common.h"
25
#include "monitor/monitor.h"
26
#include "sysemu/sysemu.h"
27
#include "qemu/timer.h"
28
#include "sysemu/char.h"
aurel32's avatar
aurel32 committed
29
#include "hw/usb.h"
30
#include "qmp-commands.h"
31 32 33
#include "qapi/qmp-input-visitor.h"
#include "qapi/qmp-output-visitor.h"
#include "qapi-visit.h"
34 35 36 37 38 39 40 41 42 43 44 45 46 47

#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <sys/time.h>
#include <zlib.h>

#ifndef _WIN32
#include <sys/times.h>
#include <sys/wait.h>
#include <termios.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
48
#include <sys/resource.h>
49 50
#include <sys/socket.h>
#include <netinet/in.h>
51 52
#include <net/if.h>
#include <arpa/inet.h>
53 54 55
#include <dirent.h>
#include <netdb.h>
#include <sys/select.h>
56
#ifdef CONFIG_BSD
57
#include <sys/stat.h>
58 59 60
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
#include <dev/ppbus/ppi.h>
#include <dev/ppbus/ppbconf.h>
61 62 63
#elif defined(__DragonFly__)
#include <dev/misc/ppi/ppi.h>
#include <bus/ppbus/ppbconf.h>
64
#endif
Aurelien Jarno's avatar
Aurelien Jarno committed
65
#else
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
#ifdef __linux__
#include <linux/ppdev.h>
#include <linux/parport.h>
#endif
#ifdef __sun__
#include <sys/stat.h>
#include <sys/ethernet.h>
#include <sys/sockio.h>
#include <netinet/arp.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h> // must come after ip.h
#include <netinet/udp.h>
#include <netinet/tcp.h>
#endif
#endif
#endif

85
#include "qemu/sockets.h"
Alon Levy's avatar
Alon Levy committed
86
#include "ui/qemu-spice.h"
87

88
#define READ_BUF_LEN 4096
89
#define READ_RETRIES 10
90
#define CHR_MAX_FILENAME_SIZE 256
91
#define TCP_MAX_FDS 16
92

93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
/***********************************************************/
/* Socket address helpers */
static void qapi_copy_SocketAddress(SocketAddress **p_dest,
                                    SocketAddress *src)
{
    QmpOutputVisitor *qov;
    QmpInputVisitor *qiv;
    Visitor *ov, *iv;
    QObject *obj;

    *p_dest = NULL;

    qov = qmp_output_visitor_new();
    ov = qmp_output_get_visitor(qov);
    visit_type_SocketAddress(ov, &src, NULL, &error_abort);
    obj = qmp_output_get_qobject(qov);
    qmp_output_visitor_cleanup(qov);
    if (!obj) {
        return;
    }

    qiv = qmp_input_visitor_new(obj);
    iv = qmp_input_get_visitor(qiv);
    visit_type_SocketAddress(iv, p_dest, NULL, &error_abort);
    qmp_input_visitor_cleanup(qiv);
    qobject_decref(obj);
}

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
static int SocketAddress_to_str(char *dest, int max_len,
                                const char *prefix, SocketAddress *addr,
                                bool is_listen, bool is_telnet)
{
    switch (addr->kind) {
    case SOCKET_ADDRESS_KIND_INET:
        return snprintf(dest, max_len, "%s%s:%s:%s%s", prefix,
                        is_telnet ? "telnet" : "tcp", addr->inet->host,
                        addr->inet->port, is_listen ? ",server" : "");
        break;
    case SOCKET_ADDRESS_KIND_UNIX:
        return snprintf(dest, max_len, "%sunix:%s%s", prefix,
                        addr->q_unix->path, is_listen ? ",server" : "");
        break;
    case SOCKET_ADDRESS_KIND_FD:
        return snprintf(dest, max_len, "%sfd:%s%s", prefix, addr->fd->str,
                        is_listen ? ",server" : "");
        break;
    default:
        abort();
    }
}

static int sockaddr_to_str(char *dest, int max_len,
                           struct sockaddr_storage *ss, socklen_t ss_len,
146
                           struct sockaddr_storage *ps, socklen_t ps_len,
147 148
                           bool is_listen, bool is_telnet)
{
149 150
    char shost[NI_MAXHOST], sserv[NI_MAXSERV];
    char phost[NI_MAXHOST], pserv[NI_MAXSERV];
151 152 153 154 155 156 157 158 159 160 161 162 163 164
    const char *left = "", *right = "";

    switch (ss->ss_family) {
#ifndef _WIN32
    case AF_UNIX:
        return snprintf(dest, max_len, "unix:%s%s",
                        ((struct sockaddr_un *)(ss))->sun_path,
                        is_listen ? ",server" : "");
#endif
    case AF_INET6:
        left  = "[";
        right = "]";
        /* fall through */
    case AF_INET:
165 166 167 168 169
        getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),
                    sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);
        getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),
                    pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);
        return snprintf(dest, max_len, "%s:%s%s%s:%s%s <-> %s%s%s:%s",
170
                        is_telnet ? "telnet" : "tcp",
171 172 173
                        left, shost, right, sserv,
                        is_listen ? ",server" : "",
                        left, phost, right, pserv);
174 175 176 177 178 179

    default:
        return snprintf(dest, max_len, "unknown");
    }
}

180 181 182
/***********************************************************/
/* character device */

183 184
static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
    QTAILQ_HEAD_INITIALIZER(chardevs);
185

186 187 188
CharDriverState *qemu_chr_alloc(void)
{
    CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
189
    qemu_mutex_init(&chr->chr_write_lock);
190 191 192
    return chr;
}

193
void qemu_chr_be_event(CharDriverState *s, int event)
194
{
195 196 197
    /* Keep track if the char device is open */
    switch (event) {
        case CHR_EVENT_OPENED:
198
            s->be_open = 1;
199 200
            break;
        case CHR_EVENT_CLOSED:
201
            s->be_open = 0;
202 203 204
            break;
    }

205 206 207 208 209
    if (!s->chr_event)
        return;
    s->chr_event(s->handler_opaque, event);
}

210
void qemu_chr_be_generic_open(CharDriverState *s)
211
{
212
    qemu_chr_be_event(s, CHR_EVENT_OPENED);
213 214
}

215
int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
216
{
217 218 219 220 221 222
    int ret;

    qemu_mutex_lock(&s->chr_write_lock);
    ret = s->chr_write(s, buf, len);
    qemu_mutex_unlock(&s->chr_write_lock);
    return ret;
223 224
}

225 226 227
int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
{
    int offset = 0;
228
    int res = 0;
229

230
    qemu_mutex_lock(&s->chr_write_lock);
231 232 233 234 235 236 237 238
    while (offset < len) {
        do {
            res = s->chr_write(s, buf + offset, len - offset);
            if (res == -1 && errno == EAGAIN) {
                g_usleep(100);
            }
        } while (res == -1 && errno == EAGAIN);

239
        if (res <= 0) {
240 241 242 243 244
            break;
        }

        offset += res;
    }
245
    qemu_mutex_unlock(&s->chr_write_lock);
246

247 248 249
    if (res < 0) {
        return res;
    }
250 251 252
    return offset;
}

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)
{
    int offset = 0, counter = 10;
    int res;

    if (!s->chr_sync_read) {
        return 0;
    }

    while (offset < len) {
        do {
            res = s->chr_sync_read(s, buf + offset, len - offset);
            if (res == -1 && errno == EAGAIN) {
                g_usleep(100);
            }
        } while (res == -1 && errno == EAGAIN);

        if (res == 0) {
            break;
        }

        if (res < 0) {
            return res;
        }

        offset += res;

        if (!counter--) {
            break;
        }
    }

    return offset;
}

288
int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
289 290 291 292 293 294
{
    if (!s->chr_ioctl)
        return -ENOTSUP;
    return s->chr_ioctl(s, cmd, arg);
}

295
int qemu_chr_be_can_write(CharDriverState *s)
296 297 298 299 300 301
{
    if (!s->chr_can_read)
        return 0;
    return s->chr_can_read(s->handler_opaque);
}

302
void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
303
{
304 305 306
    if (s->chr_read) {
        s->chr_read(s->handler_opaque, buf, len);
    }
307 308
}

309
int qemu_chr_fe_get_msgfd(CharDriverState *s)
310
{
311
    int fd;
312
    return (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
313 314 315 316 317
}

int qemu_chr_fe_get_msgfds(CharDriverState *s, int *fds, int len)
{
    return s->get_msgfds ? s->get_msgfds(s, fds, len) : -1;
318 319
}

320 321 322 323 324
int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
{
    return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
}

325 326 327 328 329
int qemu_chr_add_client(CharDriverState *s, int fd)
{
    return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
}

330 331 332 333
void qemu_chr_accept_input(CharDriverState *s)
{
    if (s->chr_accept_input)
        s->chr_accept_input(s);
334
    qemu_notify_event();
335 336
}

337
void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
338
{
339
    char buf[READ_BUF_LEN];
340 341 342
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(buf, sizeof(buf), fmt, ap);
343
    qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
344 345 346
    va_end(ap);
}

347 348
static void remove_fd_in_watch(CharDriverState *chr);

349
void qemu_chr_add_handlers(CharDriverState *s,
350
                           IOCanReadHandler *fd_can_read,
351 352 353 354
                           IOReadHandler *fd_read,
                           IOEventHandler *fd_event,
                           void *opaque)
{
355 356
    int fe_open;

357
    if (!opaque && !fd_can_read && !fd_read && !fd_event) {
358
        fe_open = 0;
359
        remove_fd_in_watch(s);
360 361
    } else {
        fe_open = 1;
362
    }
363 364 365 366
    s->chr_can_read = fd_can_read;
    s->chr_read = fd_read;
    s->chr_event = fd_event;
    s->handler_opaque = opaque;
367
    if (fe_open && s->chr_update_read_handler)
368
        s->chr_update_read_handler(s);
369

370
    if (!s->explicit_fe_open) {
371
        qemu_chr_fe_set_open(s, fe_open);
372 373
    }

374 375
    /* We're connecting to an already opened device, so let's make sure we
       also get the open event */
376
    if (fe_open && s->be_open) {
377
        qemu_chr_be_generic_open(s);
378
    }
379 380 381 382 383 384 385
}

static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    return len;
}

386
static CharDriverState *qemu_chr_open_null(void)
387 388 389
{
    CharDriverState *chr;

390
    chr = qemu_chr_alloc();
391
    chr->chr_write = null_chr_write;
392
    chr->explicit_be_open = true;
393
    return chr;
394 395 396 397 398 399 400
}

/* MUX driver for serial I/O splitting */
#define MAX_MUX 4
#define MUX_BUFFER_SIZE 32	/* Must be a power of 2.  */
#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
typedef struct {
401
    IOCanReadHandler *chr_can_read[MAX_MUX];
402 403 404 405
    IOReadHandler *chr_read[MAX_MUX];
    IOEventHandler *chr_event[MAX_MUX];
    void *ext_opaque[MAX_MUX];
    CharDriverState *drv;
406
    int focus;
407 408 409
    int mux_cnt;
    int term_got_escape;
    int max_size;
410 411 412 413 414 415
    /* Intermediate input buffer allows to catch escape sequences even if the
       currently active device is not accepting any input - but only until it
       is full as well. */
    unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
    int prod[MAX_MUX];
    int cons[MAX_MUX];
416
    int timestamps;
417 418

    /* Protected by the CharDriverState chr_write_lock.  */
419
    int linestart;
420
    int64_t timestamps_start;
421 422 423
} MuxDriver;


424
/* Called with chr_write_lock held.  */
425 426 427 428
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    MuxDriver *d = chr->opaque;
    int ret;
429
    if (!d->timestamps) {
430
        ret = qemu_chr_fe_write(d->drv, buf, len);
431 432 433 434
    } else {
        int i;

        ret = 0;
435 436
        for (i = 0; i < len; i++) {
            if (d->linestart) {
437 438 439 440
                char buf1[64];
                int64_t ti;
                int secs;

441
                ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
442 443 444
                if (d->timestamps_start == -1)
                    d->timestamps_start = ti;
                ti -= d->timestamps_start;
445
                secs = ti / 1000;
446 447 448 449 450
                snprintf(buf1, sizeof(buf1),
                         "[%02d:%02d:%02d.%03d] ",
                         secs / 3600,
                         (secs / 60) % 60,
                         secs % 60,
451
                         (int)(ti % 1000));
452
                qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
453 454
                d->linestart = 0;
            }
455
            ret += qemu_chr_fe_write(d->drv, buf+i, 1);
456 457
            if (buf[i] == '\n') {
                d->linestart = 1;
458 459 460 461 462 463 464 465 466 467
            }
        }
    }
    return ret;
}

static const char * const mux_help[] = {
    "% h    print this help\n\r",
    "% x    exit emulator\n\r",
    "% s    save disk data back to file (if -snapshot)\n\r",
Gonglei's avatar
Gonglei committed
468
    "% t    toggle console timestamps\n\r",
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    "% b    send break (magic sysrq)\n\r",
    "% c    switch between console and monitor\n\r",
    "% %  sends %\n\r",
    NULL
};

int term_escape_char = 0x01; /* ctrl-a is used for escape */
static void mux_print_help(CharDriverState *chr)
{
    int i, j;
    char ebuf[15] = "Escape-Char";
    char cbuf[50] = "\n\r";

    if (term_escape_char > 0 && term_escape_char < 26) {
        snprintf(cbuf, sizeof(cbuf), "\n\r");
        snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
    } else {
        snprintf(cbuf, sizeof(cbuf),
                 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
                 term_escape_char);
    }
490
    qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
491 492 493
    for (i = 0; mux_help[i] != NULL; i++) {
        for (j=0; mux_help[i][j] != '\0'; j++) {
            if (mux_help[i][j] == '%')
494
                qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
495
            else
496
                qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
497 498 499 500
        }
    }
}

501 502 503 504 505 506
static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
{
    if (d->chr_event[mux_nr])
        d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
}

507 508 509 510 511 512 513 514 515 516 517 518 519 520
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
{
    if (d->term_got_escape) {
        d->term_got_escape = 0;
        if (ch == term_escape_char)
            goto send_char;
        switch(ch) {
        case '?':
        case 'h':
            mux_print_help(chr);
            break;
        case 'x':
            {
                 const char *term =  "QEMU: Terminated\n\r";
521
                 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
522 523 524 525
                 exit(0);
                 break;
            }
        case 's':
526
            bdrv_commit_all();
527 528
            break;
        case 'b':
529
            qemu_chr_be_event(chr, CHR_EVENT_BREAK);
530 531 532
            break;
        case 'c':
            /* Switch to the next registered device */
533 534 535 536 537
            mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
            d->focus++;
            if (d->focus >= d->mux_cnt)
                d->focus = 0;
            mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
538
            break;
539 540 541
        case 't':
            d->timestamps = !d->timestamps;
            d->timestamps_start = -1;
542
            d->linestart = 0;
543
            break;
544 545 546 547 548 549 550 551 552 553 554 555 556
        }
    } else if (ch == term_escape_char) {
        d->term_got_escape = 1;
    } else {
    send_char:
        return 1;
    }
    return 0;
}

static void mux_chr_accept_input(CharDriverState *chr)
{
    MuxDriver *d = chr->opaque;
557
    int m = d->focus;
558

559
    while (d->prod[m] != d->cons[m] &&
560 561 562
           d->chr_can_read[m] &&
           d->chr_can_read[m](d->ext_opaque[m])) {
        d->chr_read[m](d->ext_opaque[m],
563
                       &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
564 565 566 567 568 569 570
    }
}

static int mux_chr_can_read(void *opaque)
{
    CharDriverState *chr = opaque;
    MuxDriver *d = chr->opaque;
571
    int m = d->focus;
572

573
    if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
574
        return 1;
575 576
    if (d->chr_can_read[m])
        return d->chr_can_read[m](d->ext_opaque[m]);
577 578 579 580 581 582 583
    return 0;
}

static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
{
    CharDriverState *chr = opaque;
    MuxDriver *d = chr->opaque;
584
    int m = d->focus;
585 586 587 588 589 590
    int i;

    mux_chr_accept_input (opaque);

    for(i = 0; i < size; i++)
        if (mux_proc_byte(chr, d, buf[i])) {
591
            if (d->prod[m] == d->cons[m] &&
592 593 594 595
                d->chr_can_read[m] &&
                d->chr_can_read[m](d->ext_opaque[m]))
                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
            else
596
                d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
597 598 599 600 601 602 603 604 605 606 607
        }
}

static void mux_chr_event(void *opaque, int event)
{
    CharDriverState *chr = opaque;
    MuxDriver *d = chr->opaque;
    int i;

    /* Send the event to all registered listeners */
    for (i = 0; i < d->mux_cnt; i++)
608
        mux_chr_send_event(d, i, event);
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
}

static void mux_chr_update_read_handler(CharDriverState *chr)
{
    MuxDriver *d = chr->opaque;

    if (d->mux_cnt >= MAX_MUX) {
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
        return;
    }
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
    d->chr_read[d->mux_cnt] = chr->chr_read;
    d->chr_event[d->mux_cnt] = chr->chr_event;
    /* Fix up the real driver with mux routines */
    if (d->mux_cnt == 0) {
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
                              mux_chr_event, chr);
    }
628 629
    if (d->focus != -1) {
        mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
Gerd Hoffmann's avatar
Gerd Hoffmann committed
630
    }
631
    d->focus = d->mux_cnt;
632
    d->mux_cnt++;
633
    mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
634 635
}

636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
static bool muxes_realized;

/**
 * Called after processing of default and command-line-specified
 * chardevs to deliver CHR_EVENT_OPENED events to any FEs attached
 * to a mux chardev. This is done here to ensure that
 * output/prompts/banners are only displayed for the FE that has
 * focus when initial command-line processing/machine init is
 * completed.
 *
 * After this point, any new FE attached to any new or existing
 * mux will receive CHR_EVENT_OPENED notifications for the BE
 * immediately.
 */
static void muxes_realize_done(Notifier *notifier, void *unused)
{
    CharDriverState *chr;

    QTAILQ_FOREACH(chr, &chardevs, next) {
        if (chr->is_mux) {
            MuxDriver *d = chr->opaque;
            int i;

            /* send OPENED to all already-attached FEs */
            for (i = 0; i < d->mux_cnt; i++) {
                mux_chr_send_event(d, i, CHR_EVENT_OPENED);
            }
            /* mark mux as OPENED so any new FEs will immediately receive
             * OPENED event
             */
            qemu_chr_be_generic_open(chr);
        }
    }
    muxes_realized = true;
}

static Notifier muxes_realize_notify = {
    .notify = muxes_realize_done,
};

676 677 678 679 680 681
static GSource *mux_chr_add_watch(CharDriverState *s, GIOCondition cond)
{
    MuxDriver *d = s->opaque;
    return d->drv->chr_add_watch(d->drv, cond);
}

682 683 684 685 686
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
{
    CharDriverState *chr;
    MuxDriver *d;

687
    chr = qemu_chr_alloc();
688
    d = g_malloc0(sizeof(MuxDriver));
689 690 691

    chr->opaque = d;
    d->drv = drv;
692
    d->focus = -1;
693 694 695
    chr->chr_write = mux_chr_write;
    chr->chr_update_read_handler = mux_chr_update_read_handler;
    chr->chr_accept_input = mux_chr_accept_input;
696
    /* Frontend guest-open / -close notification is not support with muxes */
697
    chr->chr_set_fe_open = NULL;
698 699 700
    if (drv->chr_add_watch) {
        chr->chr_add_watch = mux_chr_add_watch;
    }
701 702 703 704 705
    /* only default to opened state if we've realized the initial
     * set of muxes
     */
    chr->explicit_be_open = muxes_realized ? 0 : 1;
    chr->is_mux = 1;
706

707 708 709 710 711
    return chr;
}


#ifdef _WIN32
712
int send_all(int fd, const void *buf, int len1)
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
{
    int ret, len;

    len = len1;
    while (len > 0) {
        ret = send(fd, buf, len, 0);
        if (ret < 0) {
            errno = WSAGetLastError();
            if (errno != WSAEWOULDBLOCK) {
                return -1;
            }
        } else if (ret == 0) {
            break;
        } else {
            buf += ret;
            len -= ret;
        }
    }
    return len1 - len;
}

#else

736
int send_all(int fd, const void *_buf, int len1)
737 738
{
    int ret, len;
739
    const uint8_t *buf = _buf;
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755

    len = len1;
    while (len > 0) {
        ret = write(fd, buf, len);
        if (ret < 0) {
            if (errno != EINTR && errno != EAGAIN)
                return -1;
        } else if (ret == 0) {
            break;
        } else {
            buf += ret;
            len -= ret;
        }
    }
    return len1 - len;
}
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779

int recv_all(int fd, void *_buf, int len1, bool single_read)
{
    int ret, len;
    uint8_t *buf = _buf;

    len = len1;
    while ((len > 0) && (ret = read(fd, buf, len)) != 0) {
        if (ret < 0) {
            if (errno != EINTR && errno != EAGAIN) {
                return -1;
            }
            continue;
        } else {
            if (single_read) {
                return ret;
            }
            buf += ret;
            len -= ret;
        }
    }
    return len1 - len;
}

780 781
#endif /* !_WIN32 */

782 783
typedef struct IOWatchPoll
{
784 785
    GSource parent;

786
    GIOChannel *channel;
787 788 789
    GSource *src;

    IOCanReadHandler *fd_can_read;
790
    GSourceFunc fd_read;
791 792 793 794 795
    void *opaque;
} IOWatchPoll;

static IOWatchPoll *io_watch_poll_from_source(GSource *source)
{
796
    return container_of(source, IOWatchPoll, parent);
797 798 799 800 801
}

static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
{
    IOWatchPoll *iwp = io_watch_poll_from_source(source);
802
    bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
803
    bool was_active = iwp->src != NULL;
804
    if (was_active == now_active) {
805 806 807
        return FALSE;
    }

808
    if (now_active) {
809 810
        iwp->src = g_io_create_watch(iwp->channel, G_IO_IN | G_IO_ERR | G_IO_HUP);
        g_source_set_callback(iwp->src, iwp->fd_read, iwp->opaque, NULL);
811 812
        g_source_attach(iwp->src, NULL);
    } else {
813 814 815
        g_source_destroy(iwp->src);
        g_source_unref(iwp->src);
        iwp->src = NULL;
816 817
    }
    return FALSE;
818 819 820 821
}

static gboolean io_watch_poll_check(GSource *source)
{
822
    return FALSE;
823 824 825 826 827
}

static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
                                       gpointer user_data)
{
828
    abort();
829 830 831 832
}

static void io_watch_poll_finalize(GSource *source)
{
833 834 835 836 837 838 839 840 841 842
    /* Due to a glib bug, removing the last reference to a source
     * inside a finalize callback causes recursive locking (and a
     * deadlock).  This is not a problem inside other callbacks,
     * including dispatch callbacks, so we call io_remove_watch_poll
     * to remove this source.  At this point, iwp->src must
     * be NULL, or we would leak it.
     *
     * This would be solved much more elegantly by child sources,
     * but we support older glib versions that do not have them.
     */
843
    IOWatchPoll *iwp = io_watch_poll_from_source(source);
844
    assert(iwp->src == NULL);
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
}

static GSourceFuncs io_watch_poll_funcs = {
    .prepare = io_watch_poll_prepare,
    .check = io_watch_poll_check,
    .dispatch = io_watch_poll_dispatch,
    .finalize = io_watch_poll_finalize,
};

/* Can only be used for read */
static guint io_add_watch_poll(GIOChannel *channel,
                               IOCanReadHandler *fd_can_read,
                               GIOFunc fd_read,
                               gpointer user_data)
{
    IOWatchPoll *iwp;
861
    int tag;
862

863
    iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
864 865
    iwp->fd_can_read = fd_can_read;
    iwp->opaque = user_data;
866 867 868
    iwp->channel = channel;
    iwp->fd_read = (GSourceFunc) fd_read;
    iwp->src = NULL;
869

870 871 872
    tag = g_source_attach(&iwp->parent, NULL);
    g_source_unref(&iwp->parent);
    return tag;
873 874
}

875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
static void io_remove_watch_poll(guint tag)
{
    GSource *source;
    IOWatchPoll *iwp;

    g_return_if_fail (tag > 0);

    source = g_main_context_find_source_by_id(NULL, tag);
    g_return_if_fail (source != NULL);

    iwp = io_watch_poll_from_source(source);
    if (iwp->src) {
        g_source_destroy(iwp->src);
        g_source_unref(iwp->src);
        iwp->src = NULL;
    }
    g_source_destroy(&iwp->parent);
}

894 895 896 897 898 899 900 901
static void remove_fd_in_watch(CharDriverState *chr)
{
    if (chr->fd_in_tag) {
        io_remove_watch_poll(chr->fd_in_tag);
        chr->fd_in_tag = 0;
    }
}

Blue Swirl's avatar
Blue Swirl committed
902
#ifndef _WIN32
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
static GIOChannel *io_channel_from_fd(int fd)
{
    GIOChannel *chan;

    if (fd == -1) {
        return NULL;
    }

    chan = g_io_channel_unix_new(fd);

    g_io_channel_set_encoding(chan, NULL, NULL);
    g_io_channel_set_buffered(chan, FALSE);

    return chan;
}
Blue Swirl's avatar
Blue Swirl committed
918
#endif
919

920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
static GIOChannel *io_channel_from_socket(int fd)
{
    GIOChannel *chan;

    if (fd == -1) {
        return NULL;
    }

#ifdef _WIN32
    chan = g_io_channel_win32_new_socket(fd);
#else
    chan = g_io_channel_unix_new(fd);
#endif

    g_io_channel_set_encoding(chan, NULL, NULL);
    g_io_channel_set_buffered(chan, FALSE);

    return chan;
}

940
static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
941
{
942 943
    size_t offset = 0;
    GIOStatus status = G_IO_STATUS_NORMAL;
944

945 946
    while (offset < len && status == G_IO_STATUS_NORMAL) {
        gsize bytes_written = 0;
947 948

        status = g_io_channel_write_chars(fd, buf + offset, len - offset,
949
                                          &bytes_written, NULL);
950
        offset += bytes_written;
951
    }
952

953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
    if (offset > 0) {
        return offset;
    }
    switch (status) {
    case G_IO_STATUS_NORMAL:
        g_assert(len == 0);
        return 0;
    case G_IO_STATUS_AGAIN:
        errno = EAGAIN;
        return -1;
    default:
        break;
    }
    errno = EINVAL;
    return -1;
968 969
}

Blue Swirl's avatar
Blue Swirl committed
970 971
#ifndef _WIN32

972 973 974
typedef struct FDCharDriver {
    CharDriverState *chr;
    GIOChannel *fd_in, *fd_out;
975
    int max_size;
976
    QTAILQ_ENTRY(FDCharDriver) node;
977 978
} FDCharDriver;

979
/* Called with chr_write_lock held.  */
980 981 982
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    FDCharDriver *s = chr->opaque;
983
    
984
    return io_channel_send(s->fd_out, buf, len);
985 986
}

987
static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
988 989 990
{
    CharDriverState *chr = opaque;
    FDCharDriver *s = chr->opaque;
991
    int len;
992
    uint8_t buf[READ_BUF_LEN];
993 994
    GIOStatus status;
    gsize bytes_read;
995 996

    len = sizeof(buf);
997
    if (len > s->max_size) {
998
        len = s->max_size;
999 1000
    }
    if (len == 0) {
1001
        return TRUE;
1002 1003 1004 1005 1006
    }

    status = g_io_channel_read_chars(chan, (gchar *)buf,
                                     len, &bytes_read, NULL);
    if (status == G_IO_STATUS_EOF) {
1007
        remove_fd_in_watch(chr);
1008
        qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1009
        return FALSE;
1010
    }
1011 1012
    if (status == G_IO_STATUS_NORMAL) {
        qemu_chr_be_write(chr, buf, bytes_read);
1013
    }
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024

    return TRUE;
}

static int fd_chr_read_poll(void *opaque)
{
    CharDriverState *chr = opaque;
    FDCharDriver *s = chr->opaque;

    s->max_size = qemu_chr_be_can_write(chr);
    return s->max_size;
1025 1026
}

1027 1028 1029 1030 1031 1032
static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
{
    FDCharDriver *s = chr->opaque;
    return g_io_create_watch(s->fd_out, cond);
}

1033 1034 1035 1036
static void fd_chr_update_read_handler(CharDriverState *chr)
{
    FDCharDriver *s = chr->opaque;

1037
    remove_fd_in_watch(chr);
1038
    if (s->fd_in) {
1039 1040
        chr->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll,
                                           fd_chr_read, chr);
1041 1042 1043 1044 1045 1046 1047
    }
}

static void fd_chr_close(struct CharDriverState *chr)
{
    FDCharDriver *s = chr->opaque;

1048
    remove_fd_in_watch(chr);
1049 1050 1051 1052 1053
    if (s->fd_in) {
        g_io_channel_unref(s->fd_in);
    }
    if (s->fd_out) {
        g_io_channel_unref(s->fd_out);
1054 1055
    }

1056
    g_free(s);
1057
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1058 1059 1060 1061 1062 1063 1064 1065
}

/* open a character device to a unix fd */
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
{
    CharDriverState *chr;
    FDCharDriver *s;

1066
    chr = qemu_chr_alloc();
1067
    s = g_malloc0(sizeof(FDCharDriver));
1068 1069
    s->fd_in = io_channel_from_fd(fd_in);
    s->fd_out = io_channel_from_fd(fd_out);
1070
    qemu_set_nonblock(fd_out);
1071
    s->chr = chr;
1072
    chr->opaque = s;
1073
    chr->chr_add_watch = fd_chr_add_watch;
1074 1075 1076 1077 1078 1079 1080
    chr->chr_write = fd_chr_write;
    chr->chr_update_read_handler = fd_chr_update_read_handler;
    chr->chr_close = fd_chr_close;

    return chr;
}

1081
static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
1082 1083
{
    int fd_in, fd_out;
1084 1085
    char filename_in[CHR_MAX_FILENAME_SIZE];
    char filename_out[CHR_MAX_FILENAME_SIZE];
1086
    const char *filename = opts->device;
1087 1088 1089

    if (filename == NULL) {
        fprintf(stderr, "chardev: pipe: no filename given\n");
1090
        return NULL;
1091
    }
1092

1093 1094
    snprintf(filename_in, CHR_MAX_FILENAME_SIZE, "%s.in", filename);
    snprintf(filename_out, CHR_MAX_FILENAME_SIZE, "%s.out", filename);
Kevin Wolf's avatar
Kevin Wolf committed
1095 1096
    TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
    TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1097 1098 1099 1100 1101
    if (fd_in < 0 || fd_out < 0) {
	if (fd_in >= 0)
	    close(fd_in);
	if (fd_out >= 0)
	    close(fd_out);
1102
        TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1103
        if (fd_in < 0) {
1104
            return NULL;
1105
        }
1106
    }
1107
    return qemu_chr_open_fd(fd_in, fd_out);
1108 1109 1110 1111 1112
}

/* init terminal so that we can grab keys */
static struct termios oldtty;
static int old_fd0_flags;
1113
static bool stdio_in_use;
1114
static bool stdio_allow_signal;
1115 1116 1117 1118 1119 1120 1121

static void term_exit(void)
{
    tcsetattr (0, TCSANOW, &oldtty);
    fcntl(0, F_SETFL, old_fd0_flags);
}

1122
static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
1123 1124 1125
{
    struct termios tty;

1126
    tty = oldtty;
1127 1128
    if (!echo) {
        tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1129
                          |INLCR|IGNCR|ICRNL|IXON);
1130 1131 1132 1133 1134 1135 1136 1137
        tty.c_oflag |= OPOST;
        tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
        tty.c_cflag &= ~(CSIZE|PARENB);
        tty.c_cflag |= CS8;
        tty.c_cc[VMIN] = 1;
        tty.c_cc[VTIME] = 0;
    }
    if (!stdio_allow_signal)
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
        tty.c_lflag &= ~ISIG;

    tcsetattr (0, TCSANOW, &tty);
}

static void qemu_chr_close_stdio(struct CharDriverState *chr)
{
    term_exit();
    fd_chr_close(chr);
}

1149
static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
1150 1151 1152
{
    CharDriverState *chr;

1153 1154 1155 1156
    if (is_daemonized()) {
        error_report("cannot use stdio with -daemonize");
        return NULL;
    }
1157 1158 1159 1160 1161 1162 1163

    if (stdio_in_use) {
        error_report("cannot use stdio by multiple character devices");
        exit(1);
    }

    stdio_in_use = true;
1164
    old_fd0_flags = fcntl(0, F_GETFL);
1165
    tcgetattr(0, &oldtty);
1166
    qemu_set_nonblock(0);
1167
    atexit(term_exit);
1168

1169 1170
    chr = qemu_chr_open_fd(0, 1);
    chr->chr_close = qemu_chr_close_stdio;
1171
    chr->chr_set_echo = qemu_chr_set_echo_stdio;
1172 1173 1174
    if (opts->has_signal) {
        stdio_allow_signal = opts->signal;
    }
1175
    qemu_chr_fe_set_echo(chr, false);
1176

1177
    return chr;
1178 1179 1180
}

#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
1181 1182
    || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
    || defined(__GLIBC__)
1183

1184 1185
#define HAVE_CHARDEV_TTY 1

1186
typedef struct {
1187
    GIOChannel *fd;
1188
    int read_bytes;
1189 1190 1191

    /* Protected by the CharDriverState chr_write_lock.  */
    int connected;
1192
    guint timer_tag;
1193
    guint open_tag;
1194 1195
} PtyCharDriver;

1196
static void pty_chr_update_read_handler_locked(CharDriverState *chr);
1197 1198
static void pty_chr_state(CharDriverState *chr, int connected);

1199 1200 1201 1202 1203
static gboolean pty_chr_timer(gpointer opaque)
{
    struct CharDriverState *chr = opaque;
    PtyCharDriver *s = chr->opaque;

1204
    qemu_mutex_lock(&chr->chr_write_lock);
1205
    s->timer_tag = 0;
1206
    s->open_tag = 0;
1207 1208
    if (!s->connected) {
        /* Next poll ... */
1209
        pty_chr_update_read_handler_locked(chr);
1210
    }
1211
    qemu_mutex_unlock(&chr->chr_write_lock);
1212 1213 1214
    return FALSE;
}

1215
/* Called with chr_write_lock held.  */
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
static void pty_chr_rearm_timer(CharDriverState *chr, int ms)
{
    PtyCharDriver *s = chr->opaque;

    if (s->timer_tag) {
        g_source_remove(s->timer_tag);
        s->timer_tag = 0;
    }

    if (ms == 1000) {
        s->timer_tag = g_timeout_add_seconds(1, pty_chr_timer, chr);
    } else {
        s->timer_tag = g_timeout_add(ms, pty_chr_timer, chr);
    }
}

1232 1233
/* Called with chr_write_lock held.  */
static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
{
    PtyCharDriver *s = chr->opaque;
    GPollFD pfd;

    pfd.fd = g_io_channel_unix_get_fd(s->fd);
    pfd.events = G_IO_OUT;
    pfd.revents = 0;
    g_poll(&pfd, 1, 0);
    if (pfd.revents & G_IO_HUP) {
        pty_chr_state(chr, 0);
    } else {
        pty_chr_state(chr, 1);
    }
}

1249 1250 1251 1252 1253 1254 1255 1256
static void pty_chr_update_read_handler(CharDriverState *chr)
{
    qemu_mutex_lock(&chr->chr_write_lock);
    pty_chr_update_read_handler_locked(chr);
    qemu_mutex_unlock(&chr->chr_write_lock);
}

/* Called with chr_write_lock held.  */
1257 1258 1259 1260 1261 1262
static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    PtyCharDriver *s = chr->opaque;

    if (!s->connected) {
        /* guest sends data, check for (re-)connect */
1263
        pty_chr_update_read_handler_locked(chr);
1264 1265 1266
        if (!s->connected) {
            return 0;
        }
1267
    }
1268
    return io_channel_send(s->fd, buf, len);
1269 1270
}

1271 1272 1273
static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
{
    PtyCharDriver *s = chr->opaque;
1274 1275 1276
    if (!s->connected) {
        return NULL;
    }
1277 1278 1279
    return g_io_create_watch(s->fd, cond);
}

1280 1281 1282 1283 1284
static int pty_chr_read_poll(void *opaque)
{
    CharDriverState *chr = opaque;
    PtyCharDriver *s = chr->opaque;

1285
    s->read_bytes = qemu_chr_be_can_write(chr);
1286 1287 1288
    return s->read_bytes;
}

1289
static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
1290 1291 1292
{
    CharDriverState *chr = opaque;
    PtyCharDriver *s = chr->opaque;
1293
    gsize size, len;
1294
    uint8_t buf[READ_BUF_LEN];
1295
    GIOStatus status;
1296 1297 1298 1299

    len = sizeof(buf);
    if (len > s->read_bytes)
        len = s->read_bytes;
1300 1301 1302
    if (len == 0) {
        return TRUE;
    }
1303 1304
    status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
    if (status != G_IO_STATUS_NORMAL) {
1305
        pty_chr_state(chr, 0);
1306 1307
        return FALSE;
    } else {
1308
        pty_chr_state(chr, 1);
1309
        qemu_chr_be_write(chr, buf, size);
1310
    }
1311
    return TRUE;
1312 1313
}

1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
static gboolean qemu_chr_be_generic_open_func(gpointer opaque)
{
    CharDriverState *chr = opaque;
    PtyCharDriver *s = chr->opaque;

    s->open_tag = 0;
    qemu_chr_be_generic_open(chr);
    return FALSE;
}

1324
/* Called with chr_write_lock held.  */
1325 1326 1327 1328 1329
static void pty_chr_state(CharDriverState *chr, int connected)
{
    PtyCharDriver *s = chr->opaque;

    if (!connected) {
1330 1331 1332 1333
        if (s->open_tag) {
            g_source_remove(s->open_tag);
            s->open_tag = 0;
        }
1334
        remove_fd_in_watch(chr);
1335 1336 1337 1338
        s->connected = 0;
        /* (re-)connect poll interval for idle guests: once per second.
         * We check more frequently in case the guests sends data to
         * the virtual device linked to our pty. */
1339
        pty_chr_rearm_timer(chr, 1000);
1340
    } else {
1341 1342 1343 1344 1345
        if (s->timer_tag) {
            g_source_remove(s->timer_tag);
            s->timer_tag = 0;
        }
        if (!s->connected) {
1346
            g_assert(s->open_tag == 0);
1347
            s->connected = 1;
1348
            s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1349 1350
        }
        if (!chr->fd_in_tag) {
1351 1352
            chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
                                               pty_chr_read, chr);
1353
        }
1354 1355 1356 1357 1358 1359
    }
}

static void pty_chr_close(struct CharDriverState *chr)
{
    PtyCharDriver *s = chr->opaque;
1360
    int fd;
1361

1362 1363
    qemu_mutex_lock(&chr->chr_write_lock);
    pty_chr_state(chr, 0);
1364 1365 1366
    fd = g_io_channel_unix_get_fd(s->fd);
    g_io_channel_unref(s->fd);
    close(fd);
1367 1368
    if (s->timer_tag) {
        g_source_remove(s->timer_tag);
1369
        s->timer_tag = 0;
1370
    }
1371
    qemu_mutex_unlock(&chr->chr_write_lock);
1372
    g_free(s);
1373
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1374 1375
}

1376 1377
static CharDriverState *qemu_chr_open_pty(const char *id,
                                          ChardevReturn *ret)
1378 1379 1380
{
    CharDriverState *chr;
    PtyCharDriver *s;
1381
    int master_fd, slave_fd;
1382 1383
    char pty_name[PATH_MAX];

1384 1385
    master_fd = qemu_openpty_raw(&slave_fd, pty_name);
    if (master_fd < 0) {
1386
        return NULL;
1387 1388 1389 1390
    }

    close(slave_fd);

1391
    chr = qemu_chr_alloc();
1392

1393 1394
    chr->filename = g_strdup_printf("pty:%s", pty_name);
    ret->pty = g_strdup(pty_name);
1395
    ret->has_pty = true;
1396

1397
    fprintf(stderr, "char device redirected to %s (label %s)\n",
1398
            pty_name, id);
1399

1400
    s = g_malloc0(sizeof(PtyCharDriver));
1401 1402 1403 1404
    chr->opaque = s;
    chr->chr_write = pty_chr_write;
    chr->chr_update_read_handler = pty_chr_update_read_handler;
    chr->chr_close = pty_chr_close;
1405
    chr->chr_add_watch = pty_chr_add_watch;
1406
    chr->explicit_be_open = true;
1407

1408
    s->fd = io_channel_from_fd(master_fd);
1409
    s->timer_tag = 0;
1410

1411
    return chr;
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
}

static void tty_serial_init(int fd, int speed,
                            int parity, int data_bits, int stop_bits)
{
    struct termios tty;
    speed_t spd;

#if 0
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
           speed, parity, data_bits, stop_bits);
#endif
    tcgetattr (fd, &tty);

1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
#define check_speed(val) if (speed <= val) { spd = B##val; break; }
    speed = speed * 10 / 11;
    do {
        check_speed(50);
        check_speed(75);
        check_speed(110);
        check_speed(134);
        check_speed(150);
        check_speed(200);
        check_speed(300);
        check_speed(600);
        check_speed(1200);
        check_speed(1800);
        check_speed(2400);
        check_speed(4800);
        check_speed(9600);
        check_speed(19200);
        check_speed(38400);
        /* Non-Posix values follow. They may be unsupported on some systems. */
        check_speed(57600);
        check_speed(115200);
#ifdef B230400
        check_speed(230400);
#endif
#ifdef B460800
        check_speed(460800);
#endif
#ifdef