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

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
/***********************************************************/
/* 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);
}

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
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,
145
                           struct sockaddr_storage *ps, socklen_t ps_len,
146 147
                           bool is_listen, bool is_telnet)
{
148 149
    char shost[NI_MAXHOST], sserv[NI_MAXSERV];
    char phost[NI_MAXHOST], pserv[NI_MAXSERV];
150 151 152 153 154 155 156 157 158 159 160 161 162 163
    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:
164 165 166 167 168
        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",
169
                        is_telnet ? "telnet" : "tcp",
170 171 172
                        left, shost, right, sserv,
                        is_listen ? ",server" : "",
                        left, phost, right, pserv);
173 174 175 176 177 178

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

179 180 181
/***********************************************************/
/* character device */

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

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

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

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

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

214
int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
215
{
216 217 218 219 220 221
    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;
222 223
}

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

229
    qemu_mutex_lock(&s->chr_write_lock);
230 231 232 233 234 235 236 237
    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);

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

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

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

252 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
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;
}

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

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

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

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

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

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

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

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

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

346 347
static void remove_fd_in_watch(CharDriverState *chr);

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

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

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

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

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

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

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

/* 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 {
400
    IOCanReadHandler *chr_can_read[MAX_MUX];
401 402 403 404
    IOReadHandler *chr_read[MAX_MUX];
    IOEventHandler *chr_event[MAX_MUX];
    void *ext_opaque[MAX_MUX];
    CharDriverState *drv;
405
    int focus;
406 407 408
    int mux_cnt;
    int term_got_escape;
    int max_size;
409 410 411 412 413 414
    /* 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];
415
    int timestamps;
416 417

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


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

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

440
                ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
441 442 443
                if (d->timestamps_start == -1)
                    d->timestamps_start = ti;
                ti -= d->timestamps_start;
444
                secs = ti / 1000;
445 446 447 448 449
                snprintf(buf1, sizeof(buf1),
                         "[%02d:%02d:%02d.%03d] ",
                         secs / 3600,
                         (secs / 60) % 60,
                         secs % 60,
450
                         (int)(ti % 1000));
451
                qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
452 453
                d->linestart = 0;
            }
454
            ret += qemu_chr_fe_write(d->drv, buf+i, 1);
455 456
            if (buf[i] == '\n') {
                d->linestart = 1;
457 458 459 460 461 462 463 464 465 466
            }
        }
    }
    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
467
    "% t    toggle console timestamps\n\r",
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    "% 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);
    }
489
    qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
490 491 492
    for (i = 0; mux_help[i] != NULL; i++) {
        for (j=0; mux_help[i][j] != '\0'; j++) {
            if (mux_help[i][j] == '%')
493
                qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
494
            else
495
                qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
496 497 498 499
        }
    }
}

500 501 502 503 504 505
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);
}

506 507 508 509 510 511 512 513 514 515 516 517 518 519
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";
520
                 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
521 522 523 524
                 exit(0);
                 break;
            }
        case 's':
525
            bdrv_commit_all();
526 527
            break;
        case 'b':
528
            qemu_chr_be_event(chr, CHR_EVENT_BREAK);
529 530 531
            break;
        case 'c':
            /* Switch to the next registered device */
532 533 534 535 536
            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);
537
            break;
538 539 540
        case 't':
            d->timestamps = !d->timestamps;
            d->timestamps_start = -1;
541
            d->linestart = 0;
542
            break;
543 544 545 546 547 548 549 550 551 552 553 554 555
        }
    } 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;
556
    int m = d->focus;
557

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

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

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

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

    mux_chr_accept_input (opaque);

    for(i = 0; i < size; i++)
        if (mux_proc_byte(chr, d, buf[i])) {
590
            if (d->prod[m] == d->cons[m] &&
591 592 593 594
                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
595
                d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
596 597 598 599 600 601 602 603 604 605 606
        }
}

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++)
607
        mux_chr_send_event(d, i, event);
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
}

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);
    }
627 628
    if (d->focus != -1) {
        mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
Gerd Hoffmann's avatar
Gerd Hoffmann committed
629
    }
630
    d->focus = d->mux_cnt;
631
    d->mux_cnt++;
632
    mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
633 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
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,
};

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

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

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

    chr->opaque = d;
    d->drv = drv;
691
    d->focus = -1;
692 693 694
    chr->chr_write = mux_chr_write;
    chr->chr_update_read_handler = mux_chr_update_read_handler;
    chr->chr_accept_input = mux_chr_accept_input;
695
    /* Frontend guest-open / -close notification is not support with muxes */
696
    chr->chr_set_fe_open = NULL;
697 698 699
    if (drv->chr_add_watch) {
        chr->chr_add_watch = mux_chr_add_watch;
    }
700 701 702 703 704
    /* 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;
705

706 707 708 709 710
    return chr;
}


#ifdef _WIN32
711
int send_all(int fd, const void *buf, int len1)
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
{
    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

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

    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;
}
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778

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;
}

779 780
#endif /* !_WIN32 */

781 782
typedef struct IOWatchPoll
{
783 784
    GSource parent;

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

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

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

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

807
    if (now_active) {
808 809
        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);
810 811
        g_source_attach(iwp->src, NULL);
    } else {
812 813 814
        g_source_destroy(iwp->src);
        g_source_unref(iwp->src);
        iwp->src = NULL;
815 816
    }
    return FALSE;
817 818 819 820
}

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

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

static void io_watch_poll_finalize(GSource *source)
{
832 833 834 835 836 837 838 839 840 841
    /* 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.
     */
842
    IOWatchPoll *iwp = io_watch_poll_from_source(source);
843
    assert(iwp->src == NULL);
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
}

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;
860
    int tag;
861

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

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

874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
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);
}

893 894 895 896 897 898 899 900
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
901
#ifndef _WIN32
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
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
917
#endif
918

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
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;
}

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

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

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

952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
    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;
967 968
}

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

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

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

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

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

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

    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;
1024 1025
}

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

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

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

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

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

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

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

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

    return chr;
}

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

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

1092 1093
    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
1094 1095
    TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
    TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
1096 1097 1098 1099 1100
    if (fd_in < 0 || fd_out < 0) {
	if (fd_in >= 0)
	    close(fd_in);
	if (fd_out >= 0)
	    close(fd_out);
1101
        TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1102
        if (fd_in < 0) {
1103
            return NULL;
1104
        }
1105
    }
1106
    return qemu_chr_open_fd(fd_in, fd_out);
1107 1108 1109 1110 1111
}

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

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

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

1125
    tty = oldtty;
1126 1127
    if (!echo) {
        tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1128
                          |INLCR|IGNCR|ICRNL|IXON);
1129 1130 1131 1132 1133 1134 1135 1136
        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)
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
        tty.c_lflag &= ~ISIG;

    tcsetattr (0, TCSANOW, &tty);
}

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

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

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

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

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

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

1176
    return chr;
1177 1178 1179
}

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

1183 1184
#define HAVE_CHARDEV_TTY 1

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

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

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

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

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

1214
/* Called with chr_write_lock held.  */
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
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);
    }
}

1231 1232
/* Called with chr_write_lock held.  */
static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
{
    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);
    }
}

1248 1249 1250 1251 1252 1253 1254 1255
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.  */
1256 1257 1258 1259 1260 1261
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 */
1262
        pty_chr_update_read_handler_locked(chr);
1263 1264 1265
        if (!s->connected) {
            return 0;
        }
1266
    }
1267
    return io_channel_send(s->fd, buf, len);
1268 1269
}

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

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

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

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

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

1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
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;
}

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

    if (!connected) {
1329 1330 1331 1332
        if (s->open_tag) {
            g_source_remove(s->open_tag);
            s->open_tag = 0;
        }
1333
        remove_fd_in_watch(chr);
1334 1335 1336 1337
        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. */
1338
        pty_chr_rearm_timer(chr, 1000);
1339
    } else {
1340 1341 1342 1343 1344
        if (s->timer_tag) {
            g_source_remove(s->timer_tag);
            s->timer_tag = 0;
        }
        if (!s->connected) {
1345
            g_assert(s->open_tag == 0);
1346
            s->connected = 1;
1347
            s->open_tag = g_idle_add(qemu_chr_be_generic_open_func, chr);
1348 1349
        }
        if (!chr->fd_in_tag) {
1350 1351
            chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
                                               pty_chr_read, chr);
1352
        }
1353 1354 1355 1356 1357 1358
    }
}

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

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

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

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

    close(slave_fd);

1390
    chr = qemu_chr_alloc();
1391

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

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

1399
    s = g_malloc0(sizeof(PtyCharDriver));
1400 1401 1402 1403
    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;
1404
    chr->chr_add_watch = pty_chr_add_watch;
1405
    chr->explicit_be_open = true;
1406

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

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

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);

1425 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
#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 B500000
        check_speed(500000);
#endif
#ifdef B576000
        check_speed(576000);
#endif
#ifdef B921600
        check_speed(921600);
#endif
#ifdef B1000000
        check_speed(1000000);
#endif
#ifdef B1152000