qemu-char.c 105.9 KB
Newer Older
A
aliguori 已提交
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"
A
aurel32 已提交
29
#include "hw/usb.h"
L
Luiz Capitulino 已提交
30
#include "qmp-commands.h"
A
aliguori 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44

#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>
B
blueswir1 已提交
45
#include <sys/resource.h>
A
aliguori 已提交
46 47
#include <sys/socket.h>
#include <netinet/in.h>
B
blueswir1 已提交
48 49
#include <net/if.h>
#include <arpa/inet.h>
A
aliguori 已提交
50 51 52
#include <dirent.h>
#include <netdb.h>
#include <sys/select.h>
J
Juan Quintela 已提交
53
#ifdef CONFIG_BSD
A
aliguori 已提交
54
#include <sys/stat.h>
55 56 57
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
#include <dev/ppbus/ppi.h>
#include <dev/ppbus/ppbconf.h>
58 59 60
#elif defined(__DragonFly__)
#include <dev/misc/ppi/ppi.h>
#include <bus/ppbus/ppbconf.h>
A
aliguori 已提交
61
#endif
62
#else
A
aliguori 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
#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

82
#include "qemu/sockets.h"
A
Alon Levy 已提交
83
#include "ui/qemu-spice.h"
A
aliguori 已提交
84

85
#define READ_BUF_LEN 4096
86
#define READ_RETRIES 10
87

A
aliguori 已提交
88 89 90
/***********************************************************/
/* character device */

B
Blue Swirl 已提交
91 92
static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
    QTAILQ_HEAD_INITIALIZER(chardevs);
A
aliguori 已提交
93

94 95 96 97 98 99
CharDriverState *qemu_chr_alloc(void)
{
    CharDriverState *chr = g_malloc0(sizeof(CharDriverState));
    return chr;
}

100
void qemu_chr_be_event(CharDriverState *s, int event)
A
aliguori 已提交
101
{
102 103 104
    /* Keep track if the char device is open */
    switch (event) {
        case CHR_EVENT_OPENED:
105
            s->be_open = 1;
106 107
            break;
        case CHR_EVENT_CLOSED:
108
            s->be_open = 0;
109 110 111
            break;
    }

A
aliguori 已提交
112 113 114 115 116
    if (!s->chr_event)
        return;
    s->chr_event(s->handler_opaque, event);
}

117
void qemu_chr_be_generic_open(CharDriverState *s)
A
aliguori 已提交
118
{
119
    qemu_chr_be_event(s, CHR_EVENT_OPENED);
A
aliguori 已提交
120 121
}

122
int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
A
aliguori 已提交
123
{
124 125 126 127 128 129
    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;
A
aliguori 已提交
130 131
}

132 133 134 135 136
int qemu_chr_fe_write_all(CharDriverState *s, const uint8_t *buf, int len)
{
    int offset = 0;
    int res;

137
    qemu_mutex_lock(&s->chr_write_lock);
138 139 140 141 142 143 144 145
    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);

146
        if (res <= 0) {
147 148 149 150 151
            break;
        }

        offset += res;
    }
152
    qemu_mutex_unlock(&s->chr_write_lock);
153

154 155 156
    if (res < 0) {
        return res;
    }
157 158 159
    return offset;
}

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
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;
}

195
int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
A
aliguori 已提交
196 197 198 199 200 201
{
    if (!s->chr_ioctl)
        return -ENOTSUP;
    return s->chr_ioctl(s, cmd, arg);
}

202
int qemu_chr_be_can_write(CharDriverState *s)
A
aliguori 已提交
203 204 205 206 207 208
{
    if (!s->chr_can_read)
        return 0;
    return s->chr_can_read(s->handler_opaque);
}

209
void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
A
aliguori 已提交
210
{
211 212 213
    if (s->chr_read) {
        s->chr_read(s->handler_opaque, buf, len);
    }
A
aliguori 已提交
214 215
}

216
int qemu_chr_fe_get_msgfd(CharDriverState *s)
217
{
218
    int fd;
219
    return (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;
220 221 222 223 224
}

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

227 228 229 230 231
int qemu_chr_fe_set_msgfds(CharDriverState *s, int *fds, int num)
{
    return s->set_msgfds ? s->set_msgfds(s, fds, num) : -1;
}

232 233 234 235 236
int qemu_chr_add_client(CharDriverState *s, int fd)
{
    return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
}

A
aliguori 已提交
237 238 239 240
void qemu_chr_accept_input(CharDriverState *s)
{
    if (s->chr_accept_input)
        s->chr_accept_input(s);
241
    qemu_notify_event();
A
aliguori 已提交
242 243
}

244
void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
A
aliguori 已提交
245
{
246
    char buf[READ_BUF_LEN];
A
aliguori 已提交
247 248 249
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(buf, sizeof(buf), fmt, ap);
250
    qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
A
aliguori 已提交
251 252 253
    va_end(ap);
}

254 255
static void remove_fd_in_watch(CharDriverState *chr);

A
aliguori 已提交
256
void qemu_chr_add_handlers(CharDriverState *s,
257
                           IOCanReadHandler *fd_can_read,
A
aliguori 已提交
258 259 260 261
                           IOReadHandler *fd_read,
                           IOEventHandler *fd_event,
                           void *opaque)
{
262 263
    int fe_open;

264
    if (!opaque && !fd_can_read && !fd_read && !fd_event) {
265
        fe_open = 0;
266
        remove_fd_in_watch(s);
267 268
    } else {
        fe_open = 1;
269
    }
A
aliguori 已提交
270 271 272 273
    s->chr_can_read = fd_can_read;
    s->chr_read = fd_read;
    s->chr_event = fd_event;
    s->handler_opaque = opaque;
274
    if (fe_open && s->chr_update_read_handler)
A
aliguori 已提交
275
        s->chr_update_read_handler(s);
276

277
    if (!s->explicit_fe_open) {
278
        qemu_chr_fe_set_open(s, fe_open);
279 280
    }

281 282
    /* We're connecting to an already opened device, so let's make sure we
       also get the open event */
283
    if (fe_open && s->be_open) {
284
        qemu_chr_be_generic_open(s);
285
    }
A
aliguori 已提交
286 287 288 289 290 291 292
}

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

293
static CharDriverState *qemu_chr_open_null(void)
A
aliguori 已提交
294 295 296
{
    CharDriverState *chr;

297
    chr = qemu_chr_alloc();
A
aliguori 已提交
298
    chr->chr_write = null_chr_write;
299
    chr->explicit_be_open = true;
300
    return chr;
A
aliguori 已提交
301 302 303 304 305 306 307
}

/* 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 {
308
    IOCanReadHandler *chr_can_read[MAX_MUX];
A
aliguori 已提交
309 310 311 312
    IOReadHandler *chr_read[MAX_MUX];
    IOEventHandler *chr_event[MAX_MUX];
    void *ext_opaque[MAX_MUX];
    CharDriverState *drv;
313
    int focus;
A
aliguori 已提交
314 315 316
    int mux_cnt;
    int term_got_escape;
    int max_size;
317 318 319 320 321 322
    /* 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];
J
Jan Kiszka 已提交
323
    int timestamps;
324 325

    /* Protected by the CharDriverState chr_write_lock.  */
J
Jan Kiszka 已提交
326
    int linestart;
J
Jan Kiszka 已提交
327
    int64_t timestamps_start;
A
aliguori 已提交
328 329 330
} MuxDriver;


331
/* Called with chr_write_lock held.  */
A
aliguori 已提交
332 333 334 335
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    MuxDriver *d = chr->opaque;
    int ret;
J
Jan Kiszka 已提交
336
    if (!d->timestamps) {
337
        ret = qemu_chr_fe_write(d->drv, buf, len);
A
aliguori 已提交
338 339 340 341
    } else {
        int i;

        ret = 0;
J
Jan Kiszka 已提交
342 343
        for (i = 0; i < len; i++) {
            if (d->linestart) {
A
aliguori 已提交
344 345 346 347
                char buf1[64];
                int64_t ti;
                int secs;

348
                ti = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
J
Jan Kiszka 已提交
349 350 351
                if (d->timestamps_start == -1)
                    d->timestamps_start = ti;
                ti -= d->timestamps_start;
352
                secs = ti / 1000;
A
aliguori 已提交
353 354 355 356 357
                snprintf(buf1, sizeof(buf1),
                         "[%02d:%02d:%02d.%03d] ",
                         secs / 3600,
                         (secs / 60) % 60,
                         secs % 60,
358
                         (int)(ti % 1000));
359
                qemu_chr_fe_write(d->drv, (uint8_t *)buf1, strlen(buf1));
J
Jan Kiszka 已提交
360 361
                d->linestart = 0;
            }
362
            ret += qemu_chr_fe_write(d->drv, buf+i, 1);
J
Jan Kiszka 已提交
363 364
            if (buf[i] == '\n') {
                d->linestart = 1;
A
aliguori 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
            }
        }
    }
    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",
    "% t    toggle console timestamps\n\r"
    "% 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);
    }
397
    qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));
A
aliguori 已提交
398 399 400
    for (i = 0; mux_help[i] != NULL; i++) {
        for (j=0; mux_help[i][j] != '\0'; j++) {
            if (mux_help[i][j] == '%')
401
                qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));
A
aliguori 已提交
402
            else
403
                qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);
A
aliguori 已提交
404 405 406 407
        }
    }
}

408 409 410 411 412 413
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);
}

A
aliguori 已提交
414 415 416 417 418 419 420 421 422 423 424 425 426 427
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";
428
                 qemu_chr_fe_write(chr, (uint8_t *)term, strlen(term));
A
aliguori 已提交
429 430 431 432
                 exit(0);
                 break;
            }
        case 's':
433
            bdrv_commit_all();
A
aliguori 已提交
434 435
            break;
        case 'b':
436
            qemu_chr_be_event(chr, CHR_EVENT_BREAK);
A
aliguori 已提交
437 438 439
            break;
        case 'c':
            /* Switch to the next registered device */
440 441 442 443 444
            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);
A
aliguori 已提交
445
            break;
J
Jan Kiszka 已提交
446 447 448
        case 't':
            d->timestamps = !d->timestamps;
            d->timestamps_start = -1;
J
Jan Kiszka 已提交
449
            d->linestart = 0;
J
Jan Kiszka 已提交
450
            break;
A
aliguori 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463
        }
    } 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;
464
    int m = d->focus;
A
aliguori 已提交
465

466
    while (d->prod[m] != d->cons[m] &&
A
aliguori 已提交
467 468 469
           d->chr_can_read[m] &&
           d->chr_can_read[m](d->ext_opaque[m])) {
        d->chr_read[m](d->ext_opaque[m],
470
                       &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
A
aliguori 已提交
471 472 473 474 475 476 477
    }
}

static int mux_chr_can_read(void *opaque)
{
    CharDriverState *chr = opaque;
    MuxDriver *d = chr->opaque;
478
    int m = d->focus;
A
aliguori 已提交
479

480
    if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
A
aliguori 已提交
481
        return 1;
482 483
    if (d->chr_can_read[m])
        return d->chr_can_read[m](d->ext_opaque[m]);
A
aliguori 已提交
484 485 486 487 488 489 490
    return 0;
}

static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
{
    CharDriverState *chr = opaque;
    MuxDriver *d = chr->opaque;
491
    int m = d->focus;
A
aliguori 已提交
492 493 494 495 496 497
    int i;

    mux_chr_accept_input (opaque);

    for(i = 0; i < size; i++)
        if (mux_proc_byte(chr, d, buf[i])) {
498
            if (d->prod[m] == d->cons[m] &&
A
aliguori 已提交
499 500 501 502
                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
503
                d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
A
aliguori 已提交
504 505 506 507 508 509 510 511 512 513 514
        }
}

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++)
515
        mux_chr_send_event(d, i, event);
A
aliguori 已提交
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
}

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);
    }
535 536
    if (d->focus != -1) {
        mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
G
Gerd Hoffmann 已提交
537
    }
538
    d->focus = d->mux_cnt;
A
aliguori 已提交
539
    d->mux_cnt++;
540
    mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
A
aliguori 已提交
541 542
}

543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
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,
};

A
aliguori 已提交
583 584 585 586 587
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
{
    CharDriverState *chr;
    MuxDriver *d;

588
    chr = qemu_chr_alloc();
589
    d = g_malloc0(sizeof(MuxDriver));
A
aliguori 已提交
590 591 592

    chr->opaque = d;
    d->drv = drv;
593
    d->focus = -1;
A
aliguori 已提交
594 595 596
    chr->chr_write = mux_chr_write;
    chr->chr_update_read_handler = mux_chr_update_read_handler;
    chr->chr_accept_input = mux_chr_accept_input;
597
    /* Frontend guest-open / -close notification is not support with muxes */
598
    chr->chr_set_fe_open = NULL;
599 600 601 602 603
    /* 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;
604

A
aliguori 已提交
605 606 607 608 609
    return chr;
}


#ifdef _WIN32
610
int send_all(int fd, const void *buf, int len1)
A
aliguori 已提交
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
{
    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

634
int send_all(int fd, const void *_buf, int len1)
A
aliguori 已提交
635 636
{
    int ret, len;
637
    const uint8_t *buf = _buf;
A
aliguori 已提交
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653

    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;
}
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677

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

A
aliguori 已提交
678 679
#endif /* !_WIN32 */

A
Anthony Liguori 已提交
680 681
typedef struct IOWatchPoll
{
682 683
    GSource parent;

684
    GIOChannel *channel;
A
Anthony Liguori 已提交
685 686 687
    GSource *src;

    IOCanReadHandler *fd_can_read;
688
    GSourceFunc fd_read;
A
Anthony Liguori 已提交
689 690 691 692 693
    void *opaque;
} IOWatchPoll;

static IOWatchPoll *io_watch_poll_from_source(GSource *source)
{
694
    return container_of(source, IOWatchPoll, parent);
A
Anthony Liguori 已提交
695 696 697 698 699
}

static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)
{
    IOWatchPoll *iwp = io_watch_poll_from_source(source);
700
    bool now_active = iwp->fd_can_read(iwp->opaque) > 0;
701
    bool was_active = iwp->src != NULL;
702
    if (was_active == now_active) {
A
Anthony Liguori 已提交
703 704 705
        return FALSE;
    }

706
    if (now_active) {
707 708
        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);
709 710
        g_source_attach(iwp->src, NULL);
    } else {
711 712 713
        g_source_destroy(iwp->src);
        g_source_unref(iwp->src);
        iwp->src = NULL;
714 715
    }
    return FALSE;
A
Anthony Liguori 已提交
716 717 718 719
}

static gboolean io_watch_poll_check(GSource *source)
{
720
    return FALSE;
A
Anthony Liguori 已提交
721 722 723 724 725
}

static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,
                                       gpointer user_data)
{
726
    abort();
A
Anthony Liguori 已提交
727 728 729 730
}

static void io_watch_poll_finalize(GSource *source)
{
731 732 733 734 735 736 737 738 739 740
    /* 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.
     */
A
Anthony Liguori 已提交
741
    IOWatchPoll *iwp = io_watch_poll_from_source(source);
742
    assert(iwp->src == NULL);
A
Anthony Liguori 已提交
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
}

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;
759
    int tag;
A
Anthony Liguori 已提交
760

761
    iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));
A
Anthony Liguori 已提交
762 763
    iwp->fd_can_read = fd_can_read;
    iwp->opaque = user_data;
764 765 766
    iwp->channel = channel;
    iwp->fd_read = (GSourceFunc) fd_read;
    iwp->src = NULL;
A
Anthony Liguori 已提交
767

768 769 770
    tag = g_source_attach(&iwp->parent, NULL);
    g_source_unref(&iwp->parent);
    return tag;
A
Anthony Liguori 已提交
771 772
}

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
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);
}

792 793 794 795 796 797 798 799
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;
    }
}

B
Blue Swirl 已提交
800
#ifndef _WIN32
A
Anthony Liguori 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
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;
}
B
Blue Swirl 已提交
816
#endif
A
Anthony Liguori 已提交
817

818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
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;
}

838
static int io_channel_send(GIOChannel *fd, const void *buf, size_t len)
A
Anthony Liguori 已提交
839
{
840 841
    size_t offset = 0;
    GIOStatus status = G_IO_STATUS_NORMAL;
A
Anthony Liguori 已提交
842

843 844
    while (offset < len && status == G_IO_STATUS_NORMAL) {
        gsize bytes_written = 0;
845 846

        status = g_io_channel_write_chars(fd, buf + offset, len - offset,
A
Anthony Liguori 已提交
847
                                          &bytes_written, NULL);
848
        offset += bytes_written;
A
Anthony Liguori 已提交
849
    }
850

851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
    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;
A
Anthony Liguori 已提交
866 867
}

B
Blue Swirl 已提交
868 869
#ifndef _WIN32

870 871 872
typedef struct FDCharDriver {
    CharDriverState *chr;
    GIOChannel *fd_in, *fd_out;
A
aliguori 已提交
873
    int max_size;
874
    QTAILQ_ENTRY(FDCharDriver) node;
A
aliguori 已提交
875 876
} FDCharDriver;

877
/* Called with chr_write_lock held.  */
A
aliguori 已提交
878 879 880
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    FDCharDriver *s = chr->opaque;
881
    
882
    return io_channel_send(s->fd_out, buf, len);
A
aliguori 已提交
883 884
}

885
static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
A
aliguori 已提交
886 887 888
{
    CharDriverState *chr = opaque;
    FDCharDriver *s = chr->opaque;
889
    int len;
890
    uint8_t buf[READ_BUF_LEN];
891 892
    GIOStatus status;
    gsize bytes_read;
A
aliguori 已提交
893 894

    len = sizeof(buf);
895
    if (len > s->max_size) {
A
aliguori 已提交
896
        len = s->max_size;
897 898
    }
    if (len == 0) {
899
        return TRUE;
900 901 902 903 904
    }

    status = g_io_channel_read_chars(chan, (gchar *)buf,
                                     len, &bytes_read, NULL);
    if (status == G_IO_STATUS_EOF) {
905
        remove_fd_in_watch(chr);
906
        qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
907
        return FALSE;
A
aliguori 已提交
908
    }
909 910
    if (status == G_IO_STATUS_NORMAL) {
        qemu_chr_be_write(chr, buf, bytes_read);
A
aliguori 已提交
911
    }
912 913 914 915 916 917 918 919 920 921 922

    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;
A
aliguori 已提交
923 924
}

A
Anthony Liguori 已提交
925 926 927 928 929 930
static GSource *fd_chr_add_watch(CharDriverState *chr, GIOCondition cond)
{
    FDCharDriver *s = chr->opaque;
    return g_io_create_watch(s->fd_out, cond);
}

A
aliguori 已提交
931 932 933 934
static void fd_chr_update_read_handler(CharDriverState *chr)
{
    FDCharDriver *s = chr->opaque;

935
    remove_fd_in_watch(chr);
936
    if (s->fd_in) {
937 938
        chr->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll,
                                           fd_chr_read, chr);
A
aliguori 已提交
939 940 941 942 943 944 945
    }
}

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

946
    remove_fd_in_watch(chr);
947 948 949 950 951
    if (s->fd_in) {
        g_io_channel_unref(s->fd_in);
    }
    if (s->fd_out) {
        g_io_channel_unref(s->fd_out);
A
aliguori 已提交
952 953
    }

954
    g_free(s);
955
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
A
aliguori 已提交
956 957 958 959 960 961 962 963
}

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

964
    chr = qemu_chr_alloc();
965
    s = g_malloc0(sizeof(FDCharDriver));
966 967
    s->fd_in = io_channel_from_fd(fd_in);
    s->fd_out = io_channel_from_fd(fd_out);
A
Anthony Liguori 已提交
968
    fcntl(fd_out, F_SETFL, O_NONBLOCK);
969
    s->chr = chr;
A
aliguori 已提交
970
    chr->opaque = s;
A
Anthony Liguori 已提交
971
    chr->chr_add_watch = fd_chr_add_watch;
A
aliguori 已提交
972 973 974 975 976 977 978
    chr->chr_write = fd_chr_write;
    chr->chr_update_read_handler = fd_chr_update_read_handler;
    chr->chr_close = fd_chr_close;

    return chr;
}

979
static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
A
aliguori 已提交
980 981 982
{
    int fd_in, fd_out;
    char filename_in[256], filename_out[256];
983
    const char *filename = opts->device;
984 985 986

    if (filename == NULL) {
        fprintf(stderr, "chardev: pipe: no filename given\n");
987
        return NULL;
988
    }
A
aliguori 已提交
989 990 991

    snprintf(filename_in, 256, "%s.in", filename);
    snprintf(filename_out, 256, "%s.out", filename);
K
Kevin Wolf 已提交
992 993
    TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
    TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
A
aliguori 已提交
994 995 996 997 998
    if (fd_in < 0 || fd_out < 0) {
	if (fd_in >= 0)
	    close(fd_in);
	if (fd_out >= 0)
	    close(fd_out);
999
        TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
1000
        if (fd_in < 0) {
1001
            return NULL;
1002
        }
A
aliguori 已提交
1003
    }
1004
    return qemu_chr_open_fd(fd_in, fd_out);
A
aliguori 已提交
1005 1006 1007 1008 1009
}

/* init terminal so that we can grab keys */
static struct termios oldtty;
static int old_fd0_flags;
1010
static bool stdio_allow_signal;
A
aliguori 已提交
1011 1012 1013 1014 1015 1016 1017

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

1018
static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
A
aliguori 已提交
1019 1020 1021
{
    struct termios tty;

1022
    tty = oldtty;
1023 1024
    if (!echo) {
        tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
A
aliguori 已提交
1025
                          |INLCR|IGNCR|ICRNL|IXON);
1026 1027 1028 1029 1030 1031 1032 1033
        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)
A
aliguori 已提交
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
        tty.c_lflag &= ~ISIG;

    tcsetattr (0, TCSANOW, &tty);
}

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

1045
static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
A
aliguori 已提交
1046 1047 1048
{
    CharDriverState *chr;

1049 1050 1051 1052
    if (is_daemonized()) {
        error_report("cannot use stdio with -daemonize");
        return NULL;
    }
1053 1054 1055 1056
    old_fd0_flags = fcntl(0, F_GETFL);
    tcgetattr (0, &oldtty);
    fcntl(0, F_SETFL, O_NONBLOCK);
    atexit(term_exit);
1057

A
aliguori 已提交
1058 1059
    chr = qemu_chr_open_fd(0, 1);
    chr->chr_close = qemu_chr_close_stdio;
1060
    chr->chr_set_echo = qemu_chr_set_echo_stdio;
1061 1062 1063
    if (opts->has_signal) {
        stdio_allow_signal = opts->signal;
    }
1064
    qemu_chr_fe_set_echo(chr, false);
A
aliguori 已提交
1065

1066
    return chr;
A
aliguori 已提交
1067 1068 1069
}

#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
A
Aurelien Jarno 已提交
1070 1071
    || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
    || defined(__GLIBC__)
A
aliguori 已提交
1072

1073 1074
#define HAVE_CHARDEV_TTY 1

A
aliguori 已提交
1075
typedef struct {
1076
    GIOChannel *fd;
A
aliguori 已提交
1077
    int read_bytes;
1078 1079 1080

    /* Protected by the CharDriverState chr_write_lock.  */
    int connected;
1081
    guint timer_tag;
A
aliguori 已提交
1082 1083
} PtyCharDriver;

1084
static void pty_chr_update_read_handler_locked(CharDriverState *chr);
A
aliguori 已提交
1085 1086
static void pty_chr_state(CharDriverState *chr, int connected);

1087 1088 1089 1090 1091
static gboolean pty_chr_timer(gpointer opaque)
{
    struct CharDriverState *chr = opaque;
    PtyCharDriver *s = chr->opaque;

1092
    qemu_mutex_lock(&chr->chr_write_lock);
1093
    s->timer_tag = 0;
G
Gerd Hoffmann 已提交
1094 1095
    if (!s->connected) {
        /* Next poll ... */
1096
        pty_chr_update_read_handler_locked(chr);
G
Gerd Hoffmann 已提交
1097
    }
1098
    qemu_mutex_unlock(&chr->chr_write_lock);
1099 1100 1101
    return FALSE;
}

1102
/* Called with chr_write_lock held.  */
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
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);
    }
}

1119 1120
/* Called with chr_write_lock held.  */
static void pty_chr_update_read_handler_locked(CharDriverState *chr)
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
{
    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);
    }
}

1136 1137 1138 1139 1140 1141 1142 1143
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.  */
A
aliguori 已提交
1144 1145 1146 1147 1148 1149
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 */
1150
        pty_chr_update_read_handler_locked(chr);
A
aliguori 已提交
1151 1152
        return 0;
    }
1153
    return io_channel_send(s->fd, buf, len);
A
aliguori 已提交
1154 1155
}

A
Anthony Liguori 已提交
1156 1157 1158 1159 1160 1161
static GSource *pty_chr_add_watch(CharDriverState *chr, GIOCondition cond)
{
    PtyCharDriver *s = chr->opaque;
    return g_io_create_watch(s->fd, cond);
}

A
aliguori 已提交
1162 1163 1164 1165 1166
static int pty_chr_read_poll(void *opaque)
{
    CharDriverState *chr = opaque;
    PtyCharDriver *s = chr->opaque;

1167
    s->read_bytes = qemu_chr_be_can_write(chr);
A
aliguori 已提交
1168 1169 1170
    return s->read_bytes;
}

1171
static gboolean pty_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
A
aliguori 已提交
1172 1173 1174
{
    CharDriverState *chr = opaque;
    PtyCharDriver *s = chr->opaque;
1175
    gsize size, len;
1176
    uint8_t buf[READ_BUF_LEN];
1177
    GIOStatus status;
A
aliguori 已提交
1178 1179 1180 1181

    len = sizeof(buf);
    if (len > s->read_bytes)
        len = s->read_bytes;
1182 1183 1184
    if (len == 0) {
        return TRUE;
    }
1185 1186
    status = g_io_channel_read_chars(s->fd, (gchar *)buf, len, &size, NULL);
    if (status != G_IO_STATUS_NORMAL) {
A
aliguori 已提交
1187
        pty_chr_state(chr, 0);
1188 1189
        return FALSE;
    } else {
A
aliguori 已提交
1190
        pty_chr_state(chr, 1);
1191
        qemu_chr_be_write(chr, buf, size);
A
aliguori 已提交
1192
    }
1193
    return TRUE;
A
aliguori 已提交
1194 1195
}

1196
/* Called with chr_write_lock held.  */
A
aliguori 已提交
1197 1198 1199 1200 1201
static void pty_chr_state(CharDriverState *chr, int connected)
{
    PtyCharDriver *s = chr->opaque;

    if (!connected) {
1202
        remove_fd_in_watch(chr);
A
aliguori 已提交
1203 1204 1205 1206
        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. */
1207
        pty_chr_rearm_timer(chr, 1000);
A
aliguori 已提交
1208
    } else {
P
Paolo Bonzini 已提交
1209 1210 1211 1212 1213 1214
        if (s->timer_tag) {
            g_source_remove(s->timer_tag);
            s->timer_tag = 0;
        }
        if (!s->connected) {
            s->connected = 1;
1215
            qemu_chr_be_generic_open(chr);
1216 1217
        }
        if (!chr->fd_in_tag) {
1218 1219
            chr->fd_in_tag = io_add_watch_poll(s->fd, pty_chr_read_poll,
                                               pty_chr_read, chr);
P
Paolo Bonzini 已提交
1220
        }
A
aliguori 已提交
1221 1222 1223 1224 1225 1226
    }
}

static void pty_chr_close(struct CharDriverState *chr)
{
    PtyCharDriver *s = chr->opaque;
1227
    int fd;
A
aliguori 已提交
1228

1229
    remove_fd_in_watch(chr);
1230 1231 1232
    fd = g_io_channel_unix_get_fd(s->fd);
    g_io_channel_unref(s->fd);
    close(fd);
1233 1234
    if (s->timer_tag) {
        g_source_remove(s->timer_tag);
1235
        s->timer_tag = 0;
1236
    }
1237
    g_free(s);
1238
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
A
aliguori 已提交
1239 1240
}

G
Gerd Hoffmann 已提交
1241 1242
static CharDriverState *qemu_chr_open_pty(const char *id,
                                          ChardevReturn *ret)
A
aliguori 已提交
1243 1244 1245
{
    CharDriverState *chr;
    PtyCharDriver *s;
G
Gerd Hoffmann 已提交
1246
    int master_fd, slave_fd;
A
aliguori 已提交
1247 1248
    char pty_name[PATH_MAX];

1249 1250
    master_fd = qemu_openpty_raw(&slave_fd, pty_name);
    if (master_fd < 0) {
1251
        return NULL;
A
aliguori 已提交
1252 1253 1254 1255
    }

    close(slave_fd);

1256
    chr = qemu_chr_alloc();
1257

1258 1259
    chr->filename = g_strdup_printf("pty:%s", pty_name);
    ret->pty = g_strdup(pty_name);
G
Gerd Hoffmann 已提交
1260
    ret->has_pty = true;
1261

G
Gerd Hoffmann 已提交
1262
    fprintf(stderr, "char device redirected to %s (label %s)\n",
1263
            pty_name, id);
A
aliguori 已提交
1264

1265
    s = g_malloc0(sizeof(PtyCharDriver));
A
aliguori 已提交
1266 1267 1268 1269
    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;
A
Anthony Liguori 已提交
1270
    chr->chr_add_watch = pty_chr_add_watch;
1271
    chr->explicit_be_open = true;
A
aliguori 已提交
1272

1273
    s->fd = io_channel_from_fd(master_fd);
1274
    s->timer_tag = 0;
A
aliguori 已提交
1275

1276
    return chr;
A
aliguori 已提交
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
}

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

1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
#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
        check_speed(1152000);
#endif
#ifdef B1500000
        check_speed(1500000);
#endif
#ifdef B2000000
        check_speed(2000000);
#endif
#ifdef B2500000
        check_speed(2500000);
#endif
#ifdef B3000000
        check_speed(3000000);
#endif
#ifdef B3500000
        check_speed(3500000);
#endif
#ifdef B4000000
        check_speed(4000000);
#endif
A
aliguori 已提交
1351
        spd = B115200;
1352
    } while (0);
A
aliguori 已提交
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401

    cfsetispeed(&tty, spd);
    cfsetospeed(&tty, spd);

    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
                          |INLCR|IGNCR|ICRNL|IXON);
    tty.c_oflag |= OPOST;
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
    switch(data_bits) {
    default:
    case 8:
        tty.c_cflag |= CS8;
        break;
    case 7:
        tty.c_cflag |= CS7;
        break;
    case 6:
        tty.c_cflag |= CS6;
        break;
    case 5:
        tty.c_cflag |= CS5;
        break;
    }
    switch(parity) {
    default:
    case 'N':
        break;
    case 'E':
        tty.c_cflag |= PARENB;
        break;
    case 'O':
        tty.c_cflag |= PARENB | PARODD;
        break;
    }
    if (stop_bits == 2)
        tty.c_cflag |= CSTOPB;

    tcsetattr (fd, TCSANOW, &tty);
}

static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
{
    FDCharDriver *s = chr->opaque;

    switch(cmd) {
    case CHR_IOCTL_SERIAL_SET_PARAMS:
        {
            QEMUSerialSetParams *ssp = arg;
1402 1403
            tty_serial_init(g_io_channel_unix_get_fd(s->fd_in),
                            ssp->speed, ssp->parity,
A
aliguori 已提交
1404 1405 1406 1407 1408 1409
                            ssp->data_bits, ssp->stop_bits);
        }
        break;
    case CHR_IOCTL_SERIAL_SET_BREAK:
        {
            int enable = *(int *)arg;
1410 1411 1412
            if (enable) {
                tcsendbreak(g_io_channel_unix_get_fd(s->fd_in), 1);
            }
A
aliguori 已提交
1413 1414 1415 1416 1417 1418
        }
        break;
    case CHR_IOCTL_SERIAL_GET_TIOCM:
        {
            int sarg = 0;
            int *targ = (int *)arg;
1419
            ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &sarg);
A
aliguori 已提交
1420
            *targ = 0;
A
aurel32 已提交
1421
            if (sarg & TIOCM_CTS)
A
aliguori 已提交
1422
                *targ |= CHR_TIOCM_CTS;
A
aurel32 已提交
1423
            if (sarg & TIOCM_CAR)
A
aliguori 已提交
1424
                *targ |= CHR_TIOCM_CAR;
A
aurel32 已提交
1425
            if (sarg & TIOCM_DSR)
A
aliguori 已提交
1426
                *targ |= CHR_TIOCM_DSR;
A
aurel32 已提交
1427
            if (sarg & TIOCM_RI)
A
aliguori 已提交
1428
                *targ |= CHR_TIOCM_RI;
A
aurel32 已提交
1429
            if (sarg & TIOCM_DTR)
A
aliguori 已提交
1430
                *targ |= CHR_TIOCM_DTR;
A
aurel32 已提交
1431
            if (sarg & TIOCM_RTS)
A
aliguori 已提交
1432 1433 1434 1435 1436 1437 1438
                *targ |= CHR_TIOCM_RTS;
        }
        break;
    case CHR_IOCTL_SERIAL_SET_TIOCM:
        {
            int sarg = *(int *)arg;
            int targ = 0;
1439
            ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMGET, &targ);
A
aurel32 已提交
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
            targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
                     | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
            if (sarg & CHR_TIOCM_CTS)
                targ |= TIOCM_CTS;
            if (sarg & CHR_TIOCM_CAR)
                targ |= TIOCM_CAR;
            if (sarg & CHR_TIOCM_DSR)
                targ |= TIOCM_DSR;
            if (sarg & CHR_TIOCM_RI)
                targ |= TIOCM_RI;
            if (sarg & CHR_TIOCM_DTR)
A
aliguori 已提交
1451
                targ |= TIOCM_DTR;
A
aurel32 已提交
1452
            if (sarg & CHR_TIOCM_RTS)
A
aliguori 已提交
1453
                targ |= TIOCM_RTS;
1454
            ioctl(g_io_channel_unix_get_fd(s->fd_in), TIOCMSET, &targ);
A
aliguori 已提交
1455 1456 1457 1458 1459 1460 1461 1462
        }
        break;
    default:
        return -ENOTSUP;
    }
    return 0;
}

1463 1464 1465 1466 1467 1468
static void qemu_chr_close_tty(CharDriverState *chr)
{
    FDCharDriver *s = chr->opaque;
    int fd = -1;

    if (s) {
1469
        fd = g_io_channel_unix_get_fd(s->fd_in);
1470 1471 1472 1473 1474 1475 1476 1477 1478
    }

    fd_chr_close(chr);

    if (fd >= 0) {
        close(fd);
    }
}

1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
static CharDriverState *qemu_chr_open_tty_fd(int fd)
{
    CharDriverState *chr;

    tty_serial_init(fd, 115200, 'N', 8, 1);
    chr = qemu_chr_open_fd(fd, fd);
    chr->chr_ioctl = tty_serial_ioctl;
    chr->chr_close = qemu_chr_close_tty;
    return chr;
}
A
aliguori 已提交
1489 1490 1491
#endif /* __linux__ || __sun__ */

#if defined(__linux__)
1492 1493 1494

#define HAVE_CHARDEV_PARPORT 1

A
aliguori 已提交
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
typedef struct {
    int fd;
    int mode;
} ParallelCharDriver;

static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
{
    if (s->mode != mode) {
	int m = mode;
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
            return 0;
	s->mode = mode;
    }
    return 1;
}

static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
{
    ParallelCharDriver *drv = chr->opaque;
    int fd = drv->fd;
    uint8_t b;

    switch(cmd) {
    case CHR_IOCTL_PP_READ_DATA:
        if (ioctl(fd, PPRDATA, &b) < 0)
            return -ENOTSUP;
        *(uint8_t *)arg = b;
        break;
    case CHR_IOCTL_PP_WRITE_DATA:
        b = *(uint8_t *)arg;
        if (ioctl(fd, PPWDATA, &b) < 0)
            return -ENOTSUP;
        break;
    case CHR_IOCTL_PP_READ_CONTROL:
        if (ioctl(fd, PPRCONTROL, &b) < 0)
            return -ENOTSUP;
	/* Linux gives only the lowest bits, and no way to know data
	   direction! For better compatibility set the fixed upper
	   bits. */
        *(uint8_t *)arg = b | 0xc0;
        break;
    case CHR_IOCTL_PP_WRITE_CONTROL:
        b = *(uint8_t *)arg;
        if (ioctl(fd, PPWCONTROL, &b) < 0)
            return -ENOTSUP;
        break;
    case CHR_IOCTL_PP_READ_STATUS:
        if (ioctl(fd, PPRSTATUS, &b) < 0)
            return -ENOTSUP;
        *(uint8_t *)arg = b;
        break;
    case CHR_IOCTL_PP_DATA_DIR:
        if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
            return -ENOTSUP;
        break;
    case CHR_IOCTL_PP_EPP_READ_ADDR:
	if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
	    struct ParallelIOArg *parg = arg;
	    int n = read(fd, parg->buffer, parg->count);
	    if (n != parg->count) {
		return -EIO;
	    }
	}
        break;
    case CHR_IOCTL_PP_EPP_READ:
	if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
	    struct ParallelIOArg *parg = arg;
	    int n = read(fd, parg->buffer, parg->count);
	    if (n != parg->count) {
		return -EIO;
	    }
	}
        break;
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
	if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
	    struct ParallelIOArg *parg = arg;
	    int n = write(fd, parg->buffer, parg->count);
	    if (n != parg->count) {
		return -EIO;
	    }
	}
        break;
    case CHR_IOCTL_PP_EPP_WRITE:
	if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
	    struct ParallelIOArg *parg = arg;
	    int n = write(fd, parg->buffer, parg->count);
	    if (n != parg->count) {
		return -EIO;
	    }
	}
        break;
    default:
        return -ENOTSUP;
    }
    return 0;
}

static void pp_close(CharDriverState *chr)
{
    ParallelCharDriver *drv = chr->opaque;
    int fd = drv->fd;

    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
    ioctl(fd, PPRELEASE);
    close(fd);
1600
    g_free(drv);
1601
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
A
aliguori 已提交
1602 1603
}

1604
static CharDriverState *qemu_chr_open_pp_fd(int fd)
A
aliguori 已提交
1605 1606 1607 1608 1609 1610
{
    CharDriverState *chr;
    ParallelCharDriver *drv;

    if (ioctl(fd, PPCLAIM) < 0) {
        close(fd);
1611
        return NULL;
A
aliguori 已提交
1612 1613
    }

1614
    drv = g_malloc0(sizeof(ParallelCharDriver));
A
aliguori 已提交
1615 1616 1617
    drv->fd = fd;
    drv->mode = IEEE1284_MODE_COMPAT;

1618
    chr = qemu_chr_alloc();
A
aliguori 已提交
1619 1620 1621 1622 1623
    chr->chr_write = null_chr_write;
    chr->chr_ioctl = pp_ioctl;
    chr->chr_close = pp_close;
    chr->opaque = drv;

1624
    return chr;
A
aliguori 已提交
1625 1626 1627
}
#endif /* __linux__ */

A
Aurelien Jarno 已提交
1628
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1629 1630 1631

#define HAVE_CHARDEV_PARPORT 1

1632 1633
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
{
1634
    int fd = (int)(intptr_t)chr->opaque;
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
    uint8_t b;

    switch(cmd) {
    case CHR_IOCTL_PP_READ_DATA:
        if (ioctl(fd, PPIGDATA, &b) < 0)
            return -ENOTSUP;
        *(uint8_t *)arg = b;
        break;
    case CHR_IOCTL_PP_WRITE_DATA:
        b = *(uint8_t *)arg;
        if (ioctl(fd, PPISDATA, &b) < 0)
            return -ENOTSUP;
        break;
    case CHR_IOCTL_PP_READ_CONTROL:
        if (ioctl(fd, PPIGCTRL, &b) < 0)
            return -ENOTSUP;
        *(uint8_t *)arg = b;
        break;
    case CHR_IOCTL_PP_WRITE_CONTROL:
        b = *(uint8_t *)arg;
        if (ioctl(fd, PPISCTRL, &b) < 0)
            return -ENOTSUP;
        break;
    case CHR_IOCTL_PP_READ_STATUS:
        if (ioctl(fd, PPIGSTATUS, &b) < 0)
            return -ENOTSUP;
        *(uint8_t *)arg = b;
        break;
    default:
        return -ENOTSUP;
    }
    return 0;
}

1669
static CharDriverState *qemu_chr_open_pp_fd(int fd)
1670 1671 1672
{
    CharDriverState *chr;

1673
    chr = qemu_chr_alloc();
1674
    chr->opaque = (void *)(intptr_t)fd;
1675 1676
    chr->chr_write = null_chr_write;
    chr->chr_ioctl = pp_ioctl;
1677
    chr->explicit_be_open = true;
1678
    return chr;
1679 1680 1681
}
#endif

A
aliguori 已提交
1682 1683 1684 1685 1686
#else /* _WIN32 */

typedef struct {
    int max_size;
    HANDLE hcom, hrecv, hsend;
1687
    OVERLAPPED orecv;
A
aliguori 已提交
1688 1689
    BOOL fpipe;
    DWORD len;
1690 1691 1692

    /* Protected by the CharDriverState chr_write_lock.  */
    OVERLAPPED osend;
A
aliguori 已提交
1693 1694
} WinCharState;

F
Fabien Chouteau 已提交
1695 1696 1697 1698 1699 1700 1701 1702
typedef struct {
    HANDLE  hStdIn;
    HANDLE  hInputReadyEvent;
    HANDLE  hInputDoneEvent;
    HANDLE  hInputThread;
    uint8_t win_stdio_buf;
} WinStdioCharState;

A
aliguori 已提交
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
#define NSENDBUF 2048
#define NRECVBUF 2048
#define MAXCONNECT 1
#define NTIMEOUT 5000

static int win_chr_poll(void *opaque);
static int win_chr_pipe_poll(void *opaque);

static void win_chr_close(CharDriverState *chr)
{
    WinCharState *s = chr->opaque;

    if (s->hsend) {
        CloseHandle(s->hsend);
        s->hsend = NULL;
    }
    if (s->hrecv) {
        CloseHandle(s->hrecv);
        s->hrecv = NULL;
    }
    if (s->hcom) {
        CloseHandle(s->hcom);
        s->hcom = NULL;
    }
    if (s->fpipe)
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
    else
        qemu_del_polling_cb(win_chr_poll, chr);
1731

1732
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
A
aliguori 已提交
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
}

static int win_chr_init(CharDriverState *chr, const char *filename)
{
    WinCharState *s = chr->opaque;
    COMMCONFIG comcfg;
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
    COMSTAT comstat;
    DWORD size;
    DWORD err;

    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (!s->hsend) {
        fprintf(stderr, "Failed CreateEvent\n");
        goto fail;
    }
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (!s->hrecv) {
        fprintf(stderr, "Failed CreateEvent\n");
        goto fail;
    }

    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
    if (s->hcom == INVALID_HANDLE_VALUE) {
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
        s->hcom = NULL;
        goto fail;
    }

    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
        fprintf(stderr, "Failed SetupComm\n");
        goto fail;
    }

    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
    size = sizeof(COMMCONFIG);
    GetDefaultCommConfig(filename, &comcfg, &size);
    comcfg.dcb.DCBlength = sizeof(DCB);
    CommConfigDialog(filename, NULL, &comcfg);

    if (!SetCommState(s->hcom, &comcfg.dcb)) {
        fprintf(stderr, "Failed SetCommState\n");
        goto fail;
    }

    if (!SetCommMask(s->hcom, EV_ERR)) {
        fprintf(stderr, "Failed SetCommMask\n");
        goto fail;
    }

    cto.ReadIntervalTimeout = MAXDWORD;
    if (!SetCommTimeouts(s->hcom, &cto)) {
        fprintf(stderr, "Failed SetCommTimeouts\n");
        goto fail;
    }

    if (!ClearCommError(s->hcom, &err, &comstat)) {
        fprintf(stderr, "Failed ClearCommError\n");
        goto fail;
    }
    qemu_add_polling_cb(win_chr_poll, chr);
    return 0;

 fail:
    win_chr_close(chr);
    return -1;
}

1802
/* Called with chr_write_lock held.  */
A
aliguori 已提交
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
{
    WinCharState *s = chr->opaque;
    DWORD len, ret, size, err;

    len = len1;
    ZeroMemory(&s->osend, sizeof(s->osend));
    s->osend.hEvent = s->hsend;
    while (len > 0) {
        if (s->hsend)
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
        else
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
        if (!ret) {
            err = GetLastError();
            if (err == ERROR_IO_PENDING) {
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
                if (ret) {
                    buf += size;
                    len -= size;
                } else {
                    break;
                }
            } else {
                break;
            }
        } else {
            buf += size;
            len -= size;
        }
    }
    return len1 - len;
}

static int win_chr_read_poll(CharDriverState *chr)
{
    WinCharState *s = chr->opaque;

1841
    s->max_size = qemu_chr_be_can_write(chr);
A
aliguori 已提交
1842 1843 1844 1845 1846 1847 1848
    return s->max_size;
}

static void win_chr_readfile(CharDriverState *chr)
{
    WinCharState *s = chr->opaque;
    int ret, err;
1849
    uint8_t buf[READ_BUF_LEN];
A
aliguori 已提交
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
    DWORD size;

    ZeroMemory(&s->orecv, sizeof(s->orecv));
    s->orecv.hEvent = s->hrecv;
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
    if (!ret) {
        err = GetLastError();
        if (err == ERROR_IO_PENDING) {
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
        }
    }

    if (size > 0) {
1863
        qemu_chr_be_write(chr, buf, size);
A
aliguori 已提交
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
    }
}

static void win_chr_read(CharDriverState *chr)
{
    WinCharState *s = chr->opaque;

    if (s->len > s->max_size)
        s->len = s->max_size;
    if (s->len == 0)
        return;

    win_chr_readfile(chr);
}

static int win_chr_poll(void *opaque)
{
    CharDriverState *chr = opaque;
    WinCharState *s = chr->opaque;
    COMSTAT status;
    DWORD comerr;

    ClearCommError(s->hcom, &comerr, &status);
    if (status.cbInQue > 0) {
        s->len = status.cbInQue;
        win_chr_read_poll(chr);
        win_chr_read(chr);
        return 1;
    }
    return 0;
}

1896
static CharDriverState *qemu_chr_open_win_path(const char *filename)
A
aliguori 已提交
1897 1898 1899 1900
{
    CharDriverState *chr;
    WinCharState *s;

1901
    chr = qemu_chr_alloc();
1902
    s = g_malloc0(sizeof(WinCharState));
A
aliguori 已提交
1903 1904 1905 1906 1907
    chr->opaque = s;
    chr->chr_write = win_chr_write;
    chr->chr_close = win_chr_close;

    if (win_chr_init(chr, filename) < 0) {
1908 1909
        g_free(s);
        g_free(chr);
1910
        return NULL;
A
aliguori 已提交
1911
    }
1912
    return chr;
A
aliguori 已提交
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993
}

static int win_chr_pipe_poll(void *opaque)
{
    CharDriverState *chr = opaque;
    WinCharState *s = chr->opaque;
    DWORD size;

    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
    if (size > 0) {
        s->len = size;
        win_chr_read_poll(chr);
        win_chr_read(chr);
        return 1;
    }
    return 0;
}

static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
{
    WinCharState *s = chr->opaque;
    OVERLAPPED ov;
    int ret;
    DWORD size;
    char openname[256];

    s->fpipe = TRUE;

    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (!s->hsend) {
        fprintf(stderr, "Failed CreateEvent\n");
        goto fail;
    }
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (!s->hrecv) {
        fprintf(stderr, "Failed CreateEvent\n");
        goto fail;
    }

    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
                              PIPE_WAIT,
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
    if (s->hcom == INVALID_HANDLE_VALUE) {
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
        s->hcom = NULL;
        goto fail;
    }

    ZeroMemory(&ov, sizeof(ov));
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    ret = ConnectNamedPipe(s->hcom, &ov);
    if (ret) {
        fprintf(stderr, "Failed ConnectNamedPipe\n");
        goto fail;
    }

    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
    if (!ret) {
        fprintf(stderr, "Failed GetOverlappedResult\n");
        if (ov.hEvent) {
            CloseHandle(ov.hEvent);
            ov.hEvent = NULL;
        }
        goto fail;
    }

    if (ov.hEvent) {
        CloseHandle(ov.hEvent);
        ov.hEvent = NULL;
    }
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
    return 0;

 fail:
    win_chr_close(chr);
    return -1;
}


1994
static CharDriverState *qemu_chr_open_pipe(ChardevHostdev *opts)
A
aliguori 已提交
1995
{
1996
    const char *filename = opts->device;
A
aliguori 已提交
1997 1998 1999
    CharDriverState *chr;
    WinCharState *s;

2000
    chr = qemu_chr_alloc();
2001
    s = g_malloc0(sizeof(WinCharState));
A
aliguori 已提交
2002 2003 2004 2005 2006
    chr->opaque = s;
    chr->chr_write = win_chr_write;
    chr->chr_close = win_chr_close;

    if (win_chr_pipe_init(chr, filename) < 0) {
2007 2008
        g_free(s);
        g_free(chr);
2009
        return NULL;
A
aliguori 已提交
2010
    }
2011
    return chr;
A
aliguori 已提交
2012 2013
}

2014
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
A
aliguori 已提交
2015 2016 2017 2018
{
    CharDriverState *chr;
    WinCharState *s;

2019
    chr = qemu_chr_alloc();
2020
    s = g_malloc0(sizeof(WinCharState));
A
aliguori 已提交
2021 2022 2023
    s->hcom = fd_out;
    chr->opaque = s;
    chr->chr_write = win_chr_write;
2024
    return chr;
A
aliguori 已提交
2025 2026
}

2027
static CharDriverState *qemu_chr_open_win_con(void)
A
aliguori 已提交
2028
{
2029
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
A
aliguori 已提交
2030 2031
}

F
Fabien Chouteau 已提交
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    HANDLE  hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD   dwSize;
    int     len1;

    len1 = len;

    while (len1 > 0) {
        if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
            break;
        }
        buf  += dwSize;
        len1 -= dwSize;
    }

    return len - len1;
}

static void win_stdio_wait_func(void *opaque)
{
    CharDriverState   *chr   = opaque;
    WinStdioCharState *stdio = chr->opaque;
    INPUT_RECORD       buf[4];
    int                ret;
    DWORD              dwSize;
    int                i;

2060
    ret = ReadConsoleInput(stdio->hStdIn, buf, ARRAY_SIZE(buf), &dwSize);
F
Fabien Chouteau 已提交
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167

    if (!ret) {
        /* Avoid error storm */
        qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
        return;
    }

    for (i = 0; i < dwSize; i++) {
        KEY_EVENT_RECORD *kev = &buf[i].Event.KeyEvent;

        if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
            int j;
            if (kev->uChar.AsciiChar != 0) {
                for (j = 0; j < kev->wRepeatCount; j++) {
                    if (qemu_chr_be_can_write(chr)) {
                        uint8_t c = kev->uChar.AsciiChar;
                        qemu_chr_be_write(chr, &c, 1);
                    }
                }
            }
        }
    }
}

static DWORD WINAPI win_stdio_thread(LPVOID param)
{
    CharDriverState   *chr   = param;
    WinStdioCharState *stdio = chr->opaque;
    int                ret;
    DWORD              dwSize;

    while (1) {

        /* Wait for one byte */
        ret = ReadFile(stdio->hStdIn, &stdio->win_stdio_buf, 1, &dwSize, NULL);

        /* Exit in case of error, continue if nothing read */
        if (!ret) {
            break;
        }
        if (!dwSize) {
            continue;
        }

        /* Some terminal emulator returns \r\n for Enter, just pass \n */
        if (stdio->win_stdio_buf == '\r') {
            continue;
        }

        /* Signal the main thread and wait until the byte was eaten */
        if (!SetEvent(stdio->hInputReadyEvent)) {
            break;
        }
        if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
            != WAIT_OBJECT_0) {
            break;
        }
    }

    qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
    return 0;
}

static void win_stdio_thread_wait_func(void *opaque)
{
    CharDriverState   *chr   = opaque;
    WinStdioCharState *stdio = chr->opaque;

    if (qemu_chr_be_can_write(chr)) {
        qemu_chr_be_write(chr, &stdio->win_stdio_buf, 1);
    }

    SetEvent(stdio->hInputDoneEvent);
}

static void qemu_chr_set_echo_win_stdio(CharDriverState *chr, bool echo)
{
    WinStdioCharState *stdio  = chr->opaque;
    DWORD              dwMode = 0;

    GetConsoleMode(stdio->hStdIn, &dwMode);

    if (echo) {
        SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
    } else {
        SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
    }
}

static void win_stdio_close(CharDriverState *chr)
{
    WinStdioCharState *stdio = chr->opaque;

    if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
        CloseHandle(stdio->hInputReadyEvent);
    }
    if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
        CloseHandle(stdio->hInputDoneEvent);
    }
    if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
        TerminateThread(stdio->hInputThread, 0);
    }

    g_free(chr->opaque);
    g_free(chr);
}

2168
static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)
F
Fabien Chouteau 已提交
2169 2170 2171 2172 2173 2174
{
    CharDriverState   *chr;
    WinStdioCharState *stdio;
    DWORD              dwMode;
    int                is_console = 0;

2175
    chr   = qemu_chr_alloc();
F
Fabien Chouteau 已提交
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
    stdio = g_malloc0(sizeof(WinStdioCharState));

    stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);
    if (stdio->hStdIn == INVALID_HANDLE_VALUE) {
        fprintf(stderr, "cannot open stdio: invalid handle\n");
        exit(1);
    }

    is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;

    chr->opaque    = stdio;
    chr->chr_write = win_stdio_write;
    chr->chr_close = win_stdio_close;

2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
    if (is_console) {
        if (qemu_add_wait_object(stdio->hStdIn,
                                 win_stdio_wait_func, chr)) {
            fprintf(stderr, "qemu_add_wait_object: failed\n");
        }
    } else {
        DWORD   dwId;
            
        stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
        stdio->hInputDoneEvent  = CreateEvent(NULL, FALSE, FALSE, NULL);
        stdio->hInputThread     = CreateThread(NULL, 0, win_stdio_thread,
                                               chr, 0, &dwId);

        if (stdio->hInputThread == INVALID_HANDLE_VALUE
            || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
            || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
            fprintf(stderr, "cannot create stdio thread or event\n");
            exit(1);
        }
        if (qemu_add_wait_object(stdio->hInputReadyEvent,
                                 win_stdio_thread_wait_func, chr)) {
            fprintf(stderr, "qemu_add_wait_object: failed\n");
F
Fabien Chouteau 已提交
2212 2213 2214 2215 2216
        }
    }

    dwMode |= ENABLE_LINE_INPUT;

2217
    if (is_console) {
F
Fabien Chouteau 已提交
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
        /* set the terminal in raw mode */
        /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
        dwMode |= ENABLE_PROCESSED_INPUT;
    }

    SetConsoleMode(stdio->hStdIn, dwMode);

    chr->chr_set_echo = qemu_chr_set_echo_win_stdio;
    qemu_chr_fe_set_echo(chr, false);

2228
    return chr;
F
Fabien Chouteau 已提交
2229
}
A
aliguori 已提交
2230 2231
#endif /* !_WIN32 */

2232

A
aliguori 已提交
2233 2234 2235 2236 2237
/***********************************************************/
/* UDP Net console */

typedef struct {
    int fd;
2238
    GIOChannel *chan;
2239
    uint8_t buf[READ_BUF_LEN];
A
aliguori 已提交
2240 2241 2242 2243 2244
    int bufcnt;
    int bufptr;
    int max_size;
} NetCharDriver;

2245
/* Called with chr_write_lock held.  */
A
aliguori 已提交
2246 2247 2248
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    NetCharDriver *s = chr->opaque;
2249 2250 2251 2252 2253 2254 2255 2256 2257
    gsize bytes_written;
    GIOStatus status;

    status = g_io_channel_write_chars(s->chan, (const gchar *)buf, len, &bytes_written, NULL);
    if (status == G_IO_STATUS_EOF) {
        return 0;
    } else if (status != G_IO_STATUS_NORMAL) {
        return -1;
    }
A
aliguori 已提交
2258

2259
    return bytes_written;
A
aliguori 已提交
2260 2261 2262 2263 2264 2265 2266
}

static int udp_chr_read_poll(void *opaque)
{
    CharDriverState *chr = opaque;
    NetCharDriver *s = chr->opaque;

2267
    s->max_size = qemu_chr_be_can_write(chr);
A
aliguori 已提交
2268 2269 2270 2271 2272

    /* If there were any stray characters in the queue process them
     * first
     */
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2273
        qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
A
aliguori 已提交
2274
        s->bufptr++;
2275
        s->max_size = qemu_chr_be_can_write(chr);
A
aliguori 已提交
2276 2277 2278 2279
    }
    return s->max_size;
}

2280
static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
A
aliguori 已提交
2281 2282 2283
{
    CharDriverState *chr = opaque;
    NetCharDriver *s = chr->opaque;
2284 2285
    gsize bytes_read = 0;
    GIOStatus status;
A
aliguori 已提交
2286

2287 2288 2289
    if (s->max_size == 0) {
        return TRUE;
    }
2290 2291 2292
    status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),
                                     &bytes_read, NULL);
    s->bufcnt = bytes_read;
A
aliguori 已提交
2293
    s->bufptr = s->bufcnt;
2294
    if (status != G_IO_STATUS_NORMAL) {
2295
        remove_fd_in_watch(chr);
2296 2297
        return FALSE;
    }
A
aliguori 已提交
2298 2299 2300

    s->bufptr = 0;
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2301
        qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
A
aliguori 已提交
2302
        s->bufptr++;
2303
        s->max_size = qemu_chr_be_can_write(chr);
A
aliguori 已提交
2304
    }
2305 2306

    return TRUE;
A
aliguori 已提交
2307 2308 2309 2310 2311 2312
}

static void udp_chr_update_read_handler(CharDriverState *chr)
{
    NetCharDriver *s = chr->opaque;

2313
    remove_fd_in_watch(chr);
2314
    if (s->chan) {
2315 2316
        chr->fd_in_tag = io_add_watch_poll(s->chan, udp_chr_read_poll,
                                           udp_chr_read, chr);
A
aliguori 已提交
2317 2318 2319
    }
}

2320 2321 2322
static void udp_chr_close(CharDriverState *chr)
{
    NetCharDriver *s = chr->opaque;
2323 2324

    remove_fd_in_watch(chr);
2325 2326
    if (s->chan) {
        g_io_channel_unref(s->chan);
2327 2328
        closesocket(s->fd);
    }
2329
    g_free(s);
2330
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2331 2332
}

G
Gerd Hoffmann 已提交
2333
static CharDriverState *qemu_chr_open_udp_fd(int fd)
A
aliguori 已提交
2334 2335 2336 2337
{
    CharDriverState *chr = NULL;
    NetCharDriver *s = NULL;

2338
    chr = qemu_chr_alloc();
2339
    s = g_malloc0(sizeof(NetCharDriver));
A
aliguori 已提交
2340 2341

    s->fd = fd;
2342
    s->chan = io_channel_from_socket(s->fd);
A
aliguori 已提交
2343 2344 2345 2346 2347
    s->bufcnt = 0;
    s->bufptr = 0;
    chr->opaque = s;
    chr->chr_write = udp_chr_write;
    chr->chr_update_read_handler = udp_chr_update_read_handler;
2348
    chr->chr_close = udp_chr_close;
2349 2350
    /* be isn't opened until we get a connection */
    chr->explicit_be_open = true;
2351
    return chr;
G
Gerd Hoffmann 已提交
2352
}
A
aliguori 已提交
2353

G
Gerd Hoffmann 已提交
2354 2355 2356 2357 2358 2359 2360
static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
{
    Error *local_err = NULL;
    int fd = -1;

    fd = inet_dgram_opts(opts, &local_err);
    if (fd < 0) {
2361 2362
        qerror_report_err(local_err);
        error_free(local_err);
G
Gerd Hoffmann 已提交
2363
        return NULL;
2364
    }
G
Gerd Hoffmann 已提交
2365
    return qemu_chr_open_udp_fd(fd);
A
aliguori 已提交
2366 2367 2368 2369 2370 2371
}

/***********************************************************/
/* TCP Net console */

typedef struct {
2372 2373

    GIOChannel *chan, *listen_chan;
2374
    guint listen_tag;
A
aliguori 已提交
2375 2376 2377 2378 2379 2380
    int fd, listen_fd;
    int connected;
    int max_size;
    int do_telnetopt;
    int do_nodelay;
    int is_unix;
2381 2382
    int *read_msgfds;
    int read_msgfds_num;
2383 2384
    int *write_msgfds;
    int write_msgfds_num;
A
aliguori 已提交
2385 2386
} TCPCharDriver;

2387
static gboolean tcp_chr_accept(GIOChannel *chan, GIOCondition cond, void *opaque);
A
aliguori 已提交
2388

2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
#ifndef _WIN32
static int unix_send_msgfds(CharDriverState *chr, const uint8_t *buf, int len)
{
    TCPCharDriver *s = chr->opaque;
    struct msghdr msgh;
    struct iovec iov;
    int r;

    size_t fd_size = s->write_msgfds_num * sizeof(int);
    char control[CMSG_SPACE(fd_size)];
    struct cmsghdr *cmsg;

    memset(&msgh, 0, sizeof(msgh));
    memset(control, 0, sizeof(control));

    /* set the payload */
    iov.iov_base = (uint8_t *) buf;
    iov.iov_len = len;

    msgh.msg_iov = &iov;
    msgh.msg_iovlen = 1;

    msgh.msg_control = control;
    msgh.msg_controllen = sizeof(control);

    cmsg = CMSG_FIRSTHDR(&msgh);

    cmsg->cmsg_len = CMSG_LEN(fd_size);
    cmsg->cmsg_level = SOL_SOCKET;
    cmsg->cmsg_type = SCM_RIGHTS;
    memcpy(CMSG_DATA(cmsg), s->write_msgfds, fd_size);

    do {
        r = sendmsg(s->fd, &msgh, 0);
    } while (r < 0 && errno == EINTR);

    /* free the written msgfds, no matter what */
    if (s->write_msgfds_num) {
        g_free(s->write_msgfds);
        s->write_msgfds = 0;
        s->write_msgfds_num = 0;
    }

    return r;
}
#endif

2436
/* Called with chr_write_lock held.  */
A
aliguori 已提交
2437 2438 2439 2440
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    TCPCharDriver *s = chr->opaque;
    if (s->connected) {
2441 2442 2443 2444 2445 2446 2447 2448
#ifndef _WIN32
        if (s->is_unix && s->write_msgfds_num) {
            return unix_send_msgfds(chr, buf, len);
        } else
#endif
        {
            return io_channel_send(s->chan, buf, len);
        }
2449
    } else {
2450
        /* XXX: indicate an error ? */
2451
        return len;
A
aliguori 已提交
2452 2453 2454 2455 2456 2457 2458 2459 2460
    }
}

static int tcp_chr_read_poll(void *opaque)
{
    CharDriverState *chr = opaque;
    TCPCharDriver *s = chr->opaque;
    if (!s->connected)
        return 0;
2461
    s->max_size = qemu_chr_be_can_write(chr);
A
aliguori 已提交
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
    return s->max_size;
}

#define IAC 255
#define IAC_BREAK 243
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
                                      TCPCharDriver *s,
                                      uint8_t *buf, int *size)
{
    /* Handle any telnet client's basic IAC options to satisfy char by
     * char mode with no echo.  All IAC options will be removed from
     * the buf and the do_telnetopt variable will be used to track the
     * state of the width of the IAC information.
     *
     * IAC commands come in sets of 3 bytes with the exception of the
     * "IAC BREAK" command and the double IAC.
     */

    int i;
    int j = 0;

    for (i = 0; i < *size; i++) {
        if (s->do_telnetopt > 1) {
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
                /* Double IAC means send an IAC */
                if (j != i)
                    buf[j] = buf[i];
                j++;
                s->do_telnetopt = 1;
            } else {
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
                    /* Handle IAC break commands by sending a serial break */
2494
                    qemu_chr_be_event(chr, CHR_EVENT_BREAK);
A
aliguori 已提交
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514
                    s->do_telnetopt++;
                }
                s->do_telnetopt++;
            }
            if (s->do_telnetopt >= 4) {
                s->do_telnetopt = 1;
            }
        } else {
            if ((unsigned char)buf[i] == IAC) {
                s->do_telnetopt = 2;
            } else {
                if (j != i)
                    buf[j] = buf[i];
                j++;
            }
        }
    }
    *size = j;
}

2515
static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
2516 2517
{
    TCPCharDriver *s = chr->opaque;
2518 2519 2520
    int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;

    if (to_copy) {
2521 2522
        int i;

2523 2524
        memcpy(fds, s->read_msgfds, to_copy * sizeof(int));

2525 2526 2527 2528 2529
        /* Close unused fds */
        for (i = to_copy; i < s->read_msgfds_num; i++) {
            close(s->read_msgfds[i]);
        }

2530 2531 2532 2533 2534 2535
        g_free(s->read_msgfds);
        s->read_msgfds = 0;
        s->read_msgfds_num = 0;
    }

    return to_copy;
2536 2537
}

2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)
{
    TCPCharDriver *s = chr->opaque;

    /* clear old pending fd array */
    if (s->write_msgfds) {
        g_free(s->write_msgfds);
    }

    if (num) {
        s->write_msgfds = g_malloc(num * sizeof(int));
        memcpy(s->write_msgfds, fds, num * sizeof(int));
    }

    s->write_msgfds_num = num;

    return 0;
}

A
Anthony Liguori 已提交
2557
#ifndef _WIN32
2558 2559 2560 2561 2562 2563
static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
{
    TCPCharDriver *s = chr->opaque;
    struct cmsghdr *cmsg;

    for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2564
        int fd_size, i;
2565

2566
        if (cmsg->cmsg_len < CMSG_LEN(sizeof(int)) ||
2567
            cmsg->cmsg_level != SOL_SOCKET ||
2568
            cmsg->cmsg_type != SCM_RIGHTS) {
2569
            continue;
2570
        }
2571

2572 2573 2574
        fd_size = cmsg->cmsg_len - CMSG_LEN(0);

        if (!fd_size) {
2575
            continue;
2576
        }
2577

2578 2579 2580 2581
        /* close and clean read_msgfds */
        for (i = 0; i < s->read_msgfds_num; i++) {
            close(s->read_msgfds[i]);
        }
2582

2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603
        if (s->read_msgfds_num) {
            g_free(s->read_msgfds);
        }

        s->read_msgfds_num = fd_size / sizeof(int);
        s->read_msgfds = g_malloc(fd_size);
        memcpy(s->read_msgfds, CMSG_DATA(cmsg), fd_size);

        for (i = 0; i < s->read_msgfds_num; i++) {
            int fd = s->read_msgfds[i];
            if (fd < 0) {
                continue;
            }

            /* O_NONBLOCK is preserved across SCM_RIGHTS so reset it */
            qemu_set_block(fd);

    #ifndef MSG_CMSG_CLOEXEC
            qemu_set_cloexec(fd);
    #endif
        }
2604 2605 2606
    }
}

2607 2608 2609
static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
{
    TCPCharDriver *s = chr->opaque;
B
Blue Swirl 已提交
2610
    struct msghdr msg = { NULL, };
2611
    struct iovec iov[1];
2612 2613 2614 2615
    union {
        struct cmsghdr cmsg;
        char control[CMSG_SPACE(sizeof(int))];
    } msg_control;
2616
    int flags = 0;
2617
    ssize_t ret;
2618 2619 2620 2621 2622 2623

    iov[0].iov_base = buf;
    iov[0].iov_len = len;

    msg.msg_iov = iov;
    msg.msg_iovlen = 1;
2624 2625 2626
    msg.msg_control = &msg_control;
    msg.msg_controllen = sizeof(msg_control);

2627 2628 2629 2630 2631
#ifdef MSG_CMSG_CLOEXEC
    flags |= MSG_CMSG_CLOEXEC;
#endif
    ret = recvmsg(s->fd, &msg, flags);
    if (ret > 0 && s->is_unix) {
2632
        unix_process_msgfd(chr, &msg);
2633
    }
2634

2635
    return ret;
2636 2637 2638 2639 2640
}
#else
static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
{
    TCPCharDriver *s = chr->opaque;
B
Blue Swirl 已提交
2641
    return qemu_recv(s->fd, buf, len, 0);
2642 2643 2644
}
#endif

2645 2646 2647 2648 2649 2650
static GSource *tcp_chr_add_watch(CharDriverState *chr, GIOCondition cond)
{
    TCPCharDriver *s = chr->opaque;
    return g_io_create_watch(s->chan, cond);
}

2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667
static void tcp_chr_disconnect(CharDriverState *chr)
{
    TCPCharDriver *s = chr->opaque;

    s->connected = 0;
    if (s->listen_chan) {
        s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN,
                                       tcp_chr_accept, chr);
    }
    remove_fd_in_watch(chr);
    g_io_channel_unref(s->chan);
    s->chan = NULL;
    closesocket(s->fd);
    s->fd = -1;
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
}

2668
static gboolean tcp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)
A
aliguori 已提交
2669 2670 2671
{
    CharDriverState *chr = opaque;
    TCPCharDriver *s = chr->opaque;
2672
    uint8_t buf[READ_BUF_LEN];
A
aliguori 已提交
2673 2674
    int len, size;

2675
    if (!s->connected || s->max_size <= 0) {
2676
        return TRUE;
2677
    }
A
aliguori 已提交
2678 2679 2680
    len = sizeof(buf);
    if (len > s->max_size)
        len = s->max_size;
2681
    size = tcp_chr_recv(chr, (void *)buf, len);
A
aliguori 已提交
2682 2683
    if (size == 0) {
        /* connection closed */
2684
        tcp_chr_disconnect(chr);
A
aliguori 已提交
2685 2686 2687 2688
    } else if (size > 0) {
        if (s->do_telnetopt)
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
        if (size > 0)
2689
            qemu_chr_be_write(chr, buf, size);
A
aliguori 已提交
2690
    }
2691 2692

    return TRUE;
A
aliguori 已提交
2693 2694
}

2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712
static int tcp_chr_sync_read(CharDriverState *chr, const uint8_t *buf, int len)
{
    TCPCharDriver *s = chr->opaque;
    int size;

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

    size = tcp_chr_recv(chr, (void *) buf, len);
    if (size == 0) {
        /* connection closed */
        tcp_chr_disconnect(chr);
    }

    return size;
}

B
Blue Swirl 已提交
2713 2714 2715
#ifndef _WIN32
CharDriverState *qemu_chr_open_eventfd(int eventfd)
{
2716 2717 2718 2719 2720 2721 2722
    CharDriverState *chr = qemu_chr_open_fd(eventfd, eventfd);

    if (chr) {
        chr->avail_connections = 1;
    }

    return chr;
2723
}
B
Blue Swirl 已提交
2724
#endif
2725

2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
static gboolean tcp_chr_chan_close(GIOChannel *channel, GIOCondition cond,
                                   void *opaque)
{
    CharDriverState *chr = opaque;

    if (cond != G_IO_HUP) {
        return FALSE;
    }

    /* connection closed */
    tcp_chr_disconnect(chr);
    if (chr->fd_hup_tag) {
        g_source_remove(chr->fd_hup_tag);
        chr->fd_hup_tag = 0;
    }

    return TRUE;
}

A
aliguori 已提交
2745 2746 2747 2748 2749 2750
static void tcp_chr_connect(void *opaque)
{
    CharDriverState *chr = opaque;
    TCPCharDriver *s = chr->opaque;

    s->connected = 1;
2751
    if (s->chan) {
2752 2753
        chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
                                           tcp_chr_read, chr);
2754 2755
        chr->fd_hup_tag = g_io_add_watch(s->chan, G_IO_HUP, tcp_chr_chan_close,
                                         chr);
2756
    }
2757
    qemu_chr_be_generic_open(chr);
A
aliguori 已提交
2758 2759
}

2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770
static void tcp_chr_update_read_handler(CharDriverState *chr)
{
    TCPCharDriver *s = chr->opaque;

    remove_fd_in_watch(chr);
    if (s->chan) {
        chr->fd_in_tag = io_add_watch_poll(s->chan, tcp_chr_read_poll,
                                           tcp_chr_read, chr);
    }
}

A
aliguori 已提交
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
static void tcp_chr_telnet_init(int fd)
{
    char buf[3];
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
    send(fd, (char *)buf, 3, 0);
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
    send(fd, (char *)buf, 3, 0);
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
    send(fd, (char *)buf, 3, 0);
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
    send(fd, (char *)buf, 3, 0);
}

2786 2787 2788 2789 2790 2791
static int tcp_chr_add_client(CharDriverState *chr, int fd)
{
    TCPCharDriver *s = chr->opaque;
    if (s->fd != -1)
	return -1;

2792
    qemu_set_nonblock(fd);
2793 2794 2795
    if (s->do_nodelay)
        socket_set_nodelay(fd);
    s->fd = fd;
2796
    s->chan = io_channel_from_socket(fd);
2797 2798 2799 2800
    if (s->listen_tag) {
        g_source_remove(s->listen_tag);
        s->listen_tag = 0;
    }
2801 2802 2803 2804 2805
    tcp_chr_connect(chr);

    return 0;
}

2806
static gboolean tcp_chr_accept(GIOChannel *channel, GIOCondition cond, void *opaque)
A
aliguori 已提交
2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828
{
    CharDriverState *chr = opaque;
    TCPCharDriver *s = chr->opaque;
    struct sockaddr_in saddr;
#ifndef _WIN32
    struct sockaddr_un uaddr;
#endif
    struct sockaddr *addr;
    socklen_t len;
    int fd;

    for(;;) {
#ifndef _WIN32
	if (s->is_unix) {
	    len = sizeof(uaddr);
	    addr = (struct sockaddr *)&uaddr;
	} else
#endif
	{
	    len = sizeof(saddr);
	    addr = (struct sockaddr *)&saddr;
	}
K
Kevin Wolf 已提交
2829
        fd = qemu_accept(s->listen_fd, addr, &len);
A
aliguori 已提交
2830
        if (fd < 0 && errno != EINTR) {
2831
            s->listen_tag = 0;
2832
            return FALSE;
A
aliguori 已提交
2833 2834 2835 2836 2837 2838
        } else if (fd >= 0) {
            if (s->do_telnetopt)
                tcp_chr_telnet_init(fd);
            break;
        }
    }
2839 2840
    if (tcp_chr_add_client(chr, fd) < 0)
	close(fd);
2841 2842

    return TRUE;
A
aliguori 已提交
2843 2844 2845 2846 2847
}

static void tcp_chr_close(CharDriverState *chr)
{
    TCPCharDriver *s = chr->opaque;
2848
    int i;
2849
    if (s->fd >= 0) {
2850
        remove_fd_in_watch(chr);
2851 2852 2853
        if (s->chan) {
            g_io_channel_unref(s->chan);
        }
A
aliguori 已提交
2854
        closesocket(s->fd);
2855 2856
    }
    if (s->listen_fd >= 0) {
2857 2858
        if (s->listen_tag) {
            g_source_remove(s->listen_tag);
2859
            s->listen_tag = 0;
2860 2861 2862 2863
        }
        if (s->listen_chan) {
            g_io_channel_unref(s->listen_chan);
        }
A
aliguori 已提交
2864
        closesocket(s->listen_fd);
2865
    }
2866 2867 2868 2869 2870 2871
    if (s->read_msgfds_num) {
        for (i = 0; i < s->read_msgfds_num; i++) {
            close(s->read_msgfds[i]);
        }
        g_free(s->read_msgfds);
    }
2872 2873 2874
    if (s->write_msgfds_num) {
        g_free(s->write_msgfds);
    }
2875
    g_free(s);
2876
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
A
aliguori 已提交
2877 2878
}

2879 2880 2881 2882
static CharDriverState *qemu_chr_open_socket_fd(int fd, bool do_nodelay,
                                                bool is_listen, bool is_telnet,
                                                bool is_waitconnect,
                                                Error **errp)
A
aliguori 已提交
2883 2884 2885
{
    CharDriverState *chr = NULL;
    TCPCharDriver *s = NULL;
2886 2887 2888 2889 2890 2891 2892
    char host[NI_MAXHOST], serv[NI_MAXSERV];
    const char *left = "", *right = "";
    struct sockaddr_storage ss;
    socklen_t ss_len = sizeof(ss);

    memset(&ss, 0, ss_len);
    if (getsockname(fd, (struct sockaddr *) &ss, &ss_len) != 0) {
2893
        error_setg_errno(errp, errno, "getsockname");
2894 2895 2896
        return NULL;
    }

2897
    chr = qemu_chr_alloc();
2898 2899 2900 2901 2902
    s = g_malloc0(sizeof(TCPCharDriver));

    s->connected = 0;
    s->fd = -1;
    s->listen_fd = -1;
2903 2904
    s->read_msgfds = 0;
    s->read_msgfds_num = 0;
2905 2906
    s->write_msgfds = 0;
    s->write_msgfds_num = 0;
2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925

    chr->filename = g_malloc(256);
    switch (ss.ss_family) {
#ifndef _WIN32
    case AF_UNIX:
        s->is_unix = 1;
        snprintf(chr->filename, 256, "unix:%s%s",
                 ((struct sockaddr_un *)(&ss))->sun_path,
                 is_listen ? ",server" : "");
        break;
#endif
    case AF_INET6:
        left  = "[";
        right = "]";
        /* fall through */
    case AF_INET:
        s->do_nodelay = do_nodelay;
        getnameinfo((struct sockaddr *) &ss, ss_len, host, sizeof(host),
                    serv, sizeof(serv), NI_NUMERICHOST | NI_NUMERICSERV);
2926
        snprintf(chr->filename, 256, "%s:%s%s%s:%s%s",
2927 2928 2929 2930 2931 2932 2933 2934
                 is_telnet ? "telnet" : "tcp",
                 left, host, right, serv,
                 is_listen ? ",server" : "");
        break;
    }

    chr->opaque = s;
    chr->chr_write = tcp_chr_write;
2935
    chr->chr_sync_read = tcp_chr_sync_read;
2936
    chr->chr_close = tcp_chr_close;
2937
    chr->get_msgfds = tcp_get_msgfds;
2938
    chr->set_msgfds = tcp_set_msgfds;
2939
    chr->chr_add_client = tcp_chr_add_client;
2940
    chr->chr_add_watch = tcp_chr_add_watch;
2941
    chr->chr_update_read_handler = tcp_chr_update_read_handler;
2942 2943
    /* be isn't opened until we get a connection */
    chr->explicit_be_open = true;
2944 2945 2946

    if (is_listen) {
        s->listen_fd = fd;
2947 2948
        s->listen_chan = io_channel_from_socket(s->listen_fd);
        s->listen_tag = g_io_add_watch(s->listen_chan, G_IO_IN, tcp_chr_accept, chr);
2949 2950 2951 2952 2953 2954 2955
        if (is_telnet) {
            s->do_telnetopt = 1;
        }
    } else {
        s->connected = 1;
        s->fd = fd;
        socket_set_nodelay(fd);
2956
        s->chan = io_channel_from_socket(s->fd);
2957 2958 2959 2960
        tcp_chr_connect(chr);
    }

    if (is_listen && is_waitconnect) {
2961 2962
        fprintf(stderr, "QEMU waiting for connection on: %s\n",
                chr->filename);
2963
        tcp_chr_accept(s->listen_chan, G_IO_IN, chr);
2964
        qemu_set_nonblock(s->listen_fd);
2965 2966 2967 2968 2969 2970 2971
    }
    return chr;
}

static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
{
    CharDriverState *chr = NULL;
2972
    Error *local_err = NULL;
2973
    int fd = -1;
2974 2975 2976 2977 2978 2979

    bool is_listen      = qemu_opt_get_bool(opts, "server", false);
    bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);
    bool is_telnet      = qemu_opt_get_bool(opts, "telnet", false);
    bool do_nodelay     = !qemu_opt_get_bool(opts, "delay", true);
    bool is_unix        = qemu_opt_get(opts, "path") != NULL;
A
aliguori 已提交
2980

2981 2982
    if (is_unix) {
        if (is_listen) {
2983
            fd = unix_listen_opts(opts, &local_err);
2984
        } else {
2985
            fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2986 2987 2988
        }
    } else {
        if (is_listen) {
2989
            fd = inet_listen_opts(opts, 0, &local_err);
2990
        } else {
2991
            fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2992 2993
        }
    }
2994
    if (fd < 0) {
A
aliguori 已提交
2995
        goto fail;
2996
    }
A
aliguori 已提交
2997 2998

    if (!is_waitconnect)
2999
        qemu_set_nonblock(fd);
A
aliguori 已提交
3000

3001 3002
    chr = qemu_chr_open_socket_fd(fd, do_nodelay, is_listen, is_telnet,
                                  is_waitconnect, &local_err);
3003
    if (local_err) {
3004
        goto fail;
A
aliguori 已提交
3005
    }
3006
    return chr;
3007

3008

A
aliguori 已提交
3009
 fail:
3010 3011 3012 3013 3014
    if (local_err) {
        qerror_report_err(local_err);
        error_free(local_err);
    }
    if (fd >= 0) {
A
aliguori 已提交
3015
        closesocket(fd);
3016
    }
3017 3018 3019 3020
    if (chr) {
        g_free(chr->opaque);
        g_free(chr);
    }
3021
    return NULL;
A
aliguori 已提交
3022 3023
}

3024
/*********************************************************/
3025
/* Ring buffer chardev */
3026 3027 3028 3029 3030 3031

typedef struct {
    size_t size;
    size_t prod;
    size_t cons;
    uint8_t *cbuf;
3032
} RingBufCharDriver;
3033

3034
static size_t ringbuf_count(const CharDriverState *chr)
3035
{
3036
    const RingBufCharDriver *d = chr->opaque;
3037

3038
    return d->prod - d->cons;
3039 3040
}

3041
/* Called with chr_write_lock held.  */
3042
static int ringbuf_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3043
{
3044
    RingBufCharDriver *d = chr->opaque;
3045 3046 3047 3048 3049 3050 3051
    int i;

    if (!buf || (len < 0)) {
        return -1;
    }

    for (i = 0; i < len; i++ ) {
3052 3053
        d->cbuf[d->prod++ & (d->size - 1)] = buf[i];
        if (d->prod - d->cons > d->size) {
3054 3055 3056 3057 3058 3059 3060
            d->cons = d->prod - d->size;
        }
    }

    return 0;
}

3061
static int ringbuf_chr_read(CharDriverState *chr, uint8_t *buf, int len)
3062
{
3063
    RingBufCharDriver *d = chr->opaque;
3064 3065
    int i;

3066
    qemu_mutex_lock(&chr->chr_write_lock);
3067 3068
    for (i = 0; i < len && d->cons != d->prod; i++) {
        buf[i] = d->cbuf[d->cons++ & (d->size - 1)];
3069
    }
3070
    qemu_mutex_unlock(&chr->chr_write_lock);
3071 3072 3073 3074

    return i;
}

3075
static void ringbuf_chr_close(struct CharDriverState *chr)
3076
{
3077
    RingBufCharDriver *d = chr->opaque;
3078 3079 3080 3081 3082 3083

    g_free(d->cbuf);
    g_free(d);
    chr->opaque = NULL;
}

3084 3085
static CharDriverState *qemu_chr_open_ringbuf(ChardevRingbuf *opts,
                                              Error **errp)
3086 3087
{
    CharDriverState *chr;
3088
    RingBufCharDriver *d;
3089

3090
    chr = qemu_chr_alloc();
3091 3092
    d = g_malloc(sizeof(*d));

3093
    d->size = opts->has_size ? opts->size : 65536;
3094 3095 3096

    /* The size must be power of 2 */
    if (d->size & (d->size - 1)) {
3097
        error_setg(errp, "size of ringbuf chardev must be power of two");
3098 3099 3100 3101 3102 3103 3104 3105
        goto fail;
    }

    d->prod = 0;
    d->cons = 0;
    d->cbuf = g_malloc0(d->size);

    chr->opaque = d;
3106 3107
    chr->chr_write = ringbuf_chr_write;
    chr->chr_close = ringbuf_chr_close;
3108 3109 3110 3111 3112 3113 3114 3115 3116

    return chr;

fail:
    g_free(d);
    g_free(chr);
    return NULL;
}

3117
bool chr_is_ringbuf(const CharDriverState *chr)
3118
{
3119
    return chr->chr_write == ringbuf_chr_write;
3120 3121
}

3122
void qmp_ringbuf_write(const char *device, const char *data,
3123
                       bool has_format, enum DataFormat format,
3124 3125 3126
                       Error **errp)
{
    CharDriverState *chr;
3127
    const uint8_t *write_data;
3128
    int ret;
3129
    gsize write_count;
3130 3131 3132

    chr = qemu_chr_find(device);
    if (!chr) {
3133
        error_setg(errp, "Device '%s' not found", device);
3134 3135 3136
        return;
    }

3137 3138
    if (!chr_is_ringbuf(chr)) {
        error_setg(errp,"%s is not a ringbuf device", device);
3139 3140 3141 3142 3143 3144 3145
        return;
    }

    if (has_format && (format == DATA_FORMAT_BASE64)) {
        write_data = g_base64_decode(data, &write_count);
    } else {
        write_data = (uint8_t *)data;
3146
        write_count = strlen(data);
3147 3148
    }

3149
    ret = ringbuf_chr_write(chr, write_data, write_count);
3150

3151 3152 3153 3154
    if (write_data != (uint8_t *)data) {
        g_free((void *)write_data);
    }

3155 3156 3157 3158 3159 3160
    if (ret < 0) {
        error_setg(errp, "Failed to write to device %s", device);
        return;
    }
}

3161
char *qmp_ringbuf_read(const char *device, int64_t size,
3162 3163
                       bool has_format, enum DataFormat format,
                       Error **errp)
3164 3165
{
    CharDriverState *chr;
3166
    uint8_t *read_data;
3167
    size_t count;
3168
    char *data;
3169 3170 3171

    chr = qemu_chr_find(device);
    if (!chr) {
3172
        error_setg(errp, "Device '%s' not found", device);
3173 3174 3175
        return NULL;
    }

3176 3177
    if (!chr_is_ringbuf(chr)) {
        error_setg(errp,"%s is not a ringbuf device", device);
3178 3179 3180 3181 3182 3183 3184 3185
        return NULL;
    }

    if (size <= 0) {
        error_setg(errp, "size must be greater than zero");
        return NULL;
    }

3186
    count = ringbuf_count(chr);
3187
    size = size > count ? count : size;
3188
    read_data = g_malloc(size + 1);
3189

3190
    ringbuf_chr_read(chr, read_data, size);
3191 3192

    if (has_format && (format == DATA_FORMAT_BASE64)) {
3193
        data = g_base64_encode(read_data, size);
3194
        g_free(read_data);
3195
    } else {
3196 3197 3198 3199 3200 3201 3202
        /*
         * FIXME should read only complete, valid UTF-8 characters up
         * to @size bytes.  Invalid sequences should be replaced by a
         * suitable replacement character.  Except when (and only
         * when) ring buffer lost characters since last read, initial
         * continuation characters should be dropped.
         */
3203
        read_data[size] = 0;
3204
        data = (char *)read_data;
3205 3206
    }

3207
    return data;
3208 3209
}

G
Gerd Hoffmann 已提交
3210
QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
3211
{
G
Gerd Hoffmann 已提交
3212
    char host[65], port[33], width[8], height[8];
3213
    int pos;
3214
    const char *p;
3215
    QemuOpts *opts;
3216
    Error *local_err = NULL;
3217

3218
    opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
3219
    if (local_err) {
3220 3221
        qerror_report_err(local_err);
        error_free(local_err);
3222
        return NULL;
3223
    }
3224

G
Gerd Hoffmann 已提交
3225 3226 3227
    if (strstart(filename, "mon:", &p)) {
        filename = p;
        qemu_opt_set(opts, "mux", "on");
3228 3229 3230 3231 3232 3233 3234 3235
        if (strcmp(filename, "stdio") == 0) {
            /* Monitor is muxed to stdio: do not exit on Ctrl+C by default
             * but pass it to the guest.  Handle this only for compat syntax,
             * for -chardev syntax we have special option for this.
             * This is what -nographic did, redirecting+muxing serial+monitor
             * to stdio causing Ctrl+C to be passed to guest. */
            qemu_opt_set(opts, "signal", "off");
        }
G
Gerd Hoffmann 已提交
3236 3237
    }

3238 3239 3240
    if (strcmp(filename, "null")    == 0 ||
        strcmp(filename, "pty")     == 0 ||
        strcmp(filename, "msmouse") == 0 ||
3241
        strcmp(filename, "braille") == 0 ||
3242
        strcmp(filename, "stdio")   == 0) {
G
Gerd Hoffmann 已提交
3243
        qemu_opt_set(opts, "backend", filename);
3244 3245
        return opts;
    }
G
Gerd Hoffmann 已提交
3246 3247 3248
    if (strstart(filename, "vc", &p)) {
        qemu_opt_set(opts, "backend", "vc");
        if (*p == ':') {
3249
            if (sscanf(p+1, "%7[0-9]x%7[0-9]", width, height) == 2) {
G
Gerd Hoffmann 已提交
3250 3251 3252
                /* pixels */
                qemu_opt_set(opts, "width", width);
                qemu_opt_set(opts, "height", height);
3253
            } else if (sscanf(p+1, "%7[0-9]Cx%7[0-9]C", width, height) == 2) {
G
Gerd Hoffmann 已提交
3254 3255 3256 3257 3258 3259 3260 3261 3262
                /* chars */
                qemu_opt_set(opts, "cols", width);
                qemu_opt_set(opts, "rows", height);
            } else {
                goto fail;
            }
        }
        return opts;
    }
3263 3264 3265 3266
    if (strcmp(filename, "con:") == 0) {
        qemu_opt_set(opts, "backend", "console");
        return opts;
    }
3267 3268 3269 3270 3271
    if (strstart(filename, "COM", NULL)) {
        qemu_opt_set(opts, "backend", "serial");
        qemu_opt_set(opts, "path", filename);
        return opts;
    }
3272 3273 3274 3275 3276 3277 3278 3279 3280 3281
    if (strstart(filename, "file:", &p)) {
        qemu_opt_set(opts, "backend", "file");
        qemu_opt_set(opts, "path", p);
        return opts;
    }
    if (strstart(filename, "pipe:", &p)) {
        qemu_opt_set(opts, "backend", "pipe");
        qemu_opt_set(opts, "path", p);
        return opts;
    }
3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299
    if (strstart(filename, "tcp:", &p) ||
        strstart(filename, "telnet:", &p)) {
        if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
            host[0] = 0;
            if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
                goto fail;
        }
        qemu_opt_set(opts, "backend", "socket");
        qemu_opt_set(opts, "host", host);
        qemu_opt_set(opts, "port", port);
        if (p[pos] == ',') {
            if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
                goto fail;
        }
        if (strstart(filename, "telnet:", &p))
            qemu_opt_set(opts, "telnet", "on");
        return opts;
    }
G
Gerd Hoffmann 已提交
3300 3301 3302 3303
    if (strstart(filename, "udp:", &p)) {
        qemu_opt_set(opts, "backend", "udp");
        if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
            host[0] = 0;
3304
            if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
G
Gerd Hoffmann 已提交
3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322
                goto fail;
            }
        }
        qemu_opt_set(opts, "host", host);
        qemu_opt_set(opts, "port", port);
        if (p[pos] == '@') {
            p += pos + 1;
            if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
                host[0] = 0;
                if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
                    goto fail;
                }
            }
            qemu_opt_set(opts, "localaddr", host);
            qemu_opt_set(opts, "localport", port);
        }
        return opts;
    }
3323 3324 3325 3326 3327 3328
    if (strstart(filename, "unix:", &p)) {
        qemu_opt_set(opts, "backend", "socket");
        if (qemu_opts_do_parse(opts, p, "path") != 0)
            goto fail;
        return opts;
    }
3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339
    if (strstart(filename, "/dev/parport", NULL) ||
        strstart(filename, "/dev/ppi", NULL)) {
        qemu_opt_set(opts, "backend", "parport");
        qemu_opt_set(opts, "path", filename);
        return opts;
    }
    if (strstart(filename, "/dev/", NULL)) {
        qemu_opt_set(opts, "backend", "tty");
        qemu_opt_set(opts, "path", filename);
        return opts;
    }
3340

3341
fail:
3342 3343 3344 3345
    qemu_opts_del(opts);
    return NULL;
}

3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358
static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,
                                    Error **errp)
{
    const char *path = qemu_opt_get(opts, "path");

    if (path == NULL) {
        error_setg(errp, "chardev: file: no filename given");
        return;
    }
    backend->file = g_new0(ChardevFile, 1);
    backend->file->out = g_strdup(path);
}

3359 3360 3361 3362 3363
static void qemu_chr_parse_stdio(QemuOpts *opts, ChardevBackend *backend,
                                 Error **errp)
{
    backend->stdio = g_new0(ChardevStdio, 1);
    backend->stdio->has_signal = true;
3364
    backend->stdio->signal = qemu_opt_get_bool(opts, "signal", true);
3365 3366
}

3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379
static void qemu_chr_parse_serial(QemuOpts *opts, ChardevBackend *backend,
                                  Error **errp)
{
    const char *device = qemu_opt_get(opts, "path");

    if (device == NULL) {
        error_setg(errp, "chardev: serial/tty: no device path given");
        return;
    }
    backend->serial = g_new0(ChardevHostdev, 1);
    backend->serial->device = g_strdup(device);
}

3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392
static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,
                                    Error **errp)
{
    const char *device = qemu_opt_get(opts, "path");

    if (device == NULL) {
        error_setg(errp, "chardev: parallel: no device path given");
        return;
    }
    backend->parallel = g_new0(ChardevHostdev, 1);
    backend->parallel->device = g_strdup(device);
}

3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405
static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,
                                Error **errp)
{
    const char *device = qemu_opt_get(opts, "path");

    if (device == NULL) {
        error_setg(errp, "chardev: pipe: no device path given");
        return;
    }
    backend->pipe = g_new0(ChardevHostdev, 1);
    backend->pipe->device = g_strdup(device);
}

3406 3407
static void qemu_chr_parse_ringbuf(QemuOpts *opts, ChardevBackend *backend,
                                   Error **errp)
3408 3409 3410
{
    int val;

3411
    backend->ringbuf = g_new0(ChardevRingbuf, 1);
3412

3413
    val = qemu_opt_get_size(opts, "size", 0);
3414
    if (val != 0) {
3415 3416
        backend->ringbuf->has_size = true;
        backend->ringbuf->size = val;
3417 3418 3419
    }
}

3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432
static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,
                               Error **errp)
{
    const char *chardev = qemu_opt_get(opts, "chardev");

    if (chardev == NULL) {
        error_setg(errp, "chardev: mux: no chardev given");
        return;
    }
    backend->mux = g_new0(ChardevMux, 1);
    backend->mux->chardev = g_strdup(chardev);
}

3433
typedef struct CharDriver {
3434
    const char *name;
3435
    /* old, pre qapi */
3436
    CharDriverState *(*open)(QemuOpts *opts);
3437
    /* new, qapi-based */
3438
    ChardevBackendKind kind;
3439
    void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp);
3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453
} CharDriver;

static GSList *backends;

void register_char_driver(const char *name, CharDriverState *(*open)(QemuOpts *))
{
    CharDriver *s;

    s = g_malloc0(sizeof(*s));
    s->name = g_strdup(name);
    s->open = open;

    backends = g_slist_append(backends, s);
}
3454

3455
void register_char_driver_qapi(const char *name, ChardevBackendKind kind,
3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467
        void (*parse)(QemuOpts *opts, ChardevBackend *backend, Error **errp))
{
    CharDriver *s;

    s = g_malloc0(sizeof(*s));
    s->name = g_strdup(name);
    s->kind = kind;
    s->parse = parse;

    backends = g_slist_append(backends, s);
}

3468
CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
3469 3470
                                    void (*init)(struct CharDriverState *s),
                                    Error **errp)
3471
{
3472
    Error *local_err = NULL;
3473
    CharDriver *cd;
3474
    CharDriverState *chr;
3475
    GSList *i;
3476 3477

    if (qemu_opts_id(opts) == NULL) {
3478
        error_setg(errp, "chardev: no id specified");
G
Gerd Hoffmann 已提交
3479
        goto err;
3480 3481
    }

3482
    if (qemu_opt_get(opts, "backend") == NULL) {
3483
        error_setg(errp, "chardev: \"%s\" missing backend",
3484
                   qemu_opts_id(opts));
G
Gerd Hoffmann 已提交
3485
        goto err;
3486
    }
3487 3488 3489 3490
    for (i = backends; i; i = i->next) {
        cd = i->data;

        if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {
3491
            break;
3492
        }
3493
    }
3494
    if (i == NULL) {
3495
        error_setg(errp, "chardev: backend \"%s\" not found",
3496
                   qemu_opt_get(opts, "backend"));
3497
        goto err;
3498 3499
    }

3500 3501 3502 3503 3504
    if (!cd->open) {
        /* using new, qapi init */
        ChardevBackend *backend = g_new0(ChardevBackend, 1);
        ChardevReturn *ret = NULL;
        const char *id = qemu_opts_id(opts);
3505
        char *bid = NULL;
3506 3507 3508 3509

        if (qemu_opt_get_bool(opts, "mux", 0)) {
            bid = g_strdup_printf("%s-base", id);
        }
3510 3511 3512 3513

        chr = NULL;
        backend->kind = cd->kind;
        if (cd->parse) {
3514 3515 3516
            cd->parse(opts, backend, &local_err);
            if (local_err) {
                error_propagate(errp, local_err);
3517 3518 3519
                goto qapi_out;
            }
        }
3520
        ret = qmp_chardev_add(bid ? bid : id, backend, errp);
3521
        if (!ret) {
3522 3523
            goto qapi_out;
        }
3524 3525 3526 3527 3528 3529 3530 3531 3532

        if (bid) {
            qapi_free_ChardevBackend(backend);
            qapi_free_ChardevReturn(ret);
            backend = g_new0(ChardevBackend, 1);
            backend->mux = g_new0(ChardevMux, 1);
            backend->kind = CHARDEV_BACKEND_KIND_MUX;
            backend->mux->chardev = g_strdup(bid);
            ret = qmp_chardev_add(id, backend, errp);
3533
            if (!ret) {
3534 3535 3536 3537 3538
                chr = qemu_chr_find(bid);
                qemu_chr_delete(chr);
                chr = NULL;
                goto qapi_out;
            }
3539 3540
        }

3541
        chr = qemu_chr_find(id);
3542
        chr->opts = opts;
3543 3544 3545 3546

    qapi_out:
        qapi_free_ChardevBackend(backend);
        qapi_free_ChardevReturn(ret);
3547
        g_free(bid);
3548 3549 3550
        return chr;
    }

3551
    chr = cd->open(opts);
3552
    if (!chr) {
3553
        error_setg(errp, "chardev: opening backend \"%s\" failed",
3554
                   qemu_opt_get(opts, "backend"));
G
Gerd Hoffmann 已提交
3555
        goto err;
3556 3557 3558
    }

    if (!chr->filename)
3559
        chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
3560
    chr->init = init;
3561 3562 3563 3564 3565 3566
    /* if we didn't create the chardev via qmp_chardev_add, we
     * need to send the OPENED event here
     */
    if (!chr->explicit_be_open) {
        qemu_chr_be_event(chr, CHR_EVENT_OPENED);
    }
B
Blue Swirl 已提交
3567
    QTAILQ_INSERT_TAIL(&chardevs, chr, next);
G
Gerd Hoffmann 已提交
3568 3569 3570 3571

    if (qemu_opt_get_bool(opts, "mux", 0)) {
        CharDriverState *base = chr;
        int len = strlen(qemu_opts_id(opts)) + 6;
3572
        base->label = g_malloc(len);
G
Gerd Hoffmann 已提交
3573 3574 3575
        snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
        chr = qemu_chr_open_mux(base);
        chr->filename = base->filename;
3576
        chr->avail_connections = MAX_MUX;
B
Blue Swirl 已提交
3577
        QTAILQ_INSERT_TAIL(&chardevs, chr, next);
3578 3579
    } else {
        chr->avail_connections = 1;
G
Gerd Hoffmann 已提交
3580
    }
3581
    chr->label = g_strdup(qemu_opts_id(opts));
G
Gerd Hoffmann 已提交
3582
    chr->opts = opts;
3583
    return chr;
G
Gerd Hoffmann 已提交
3584 3585 3586 3587

err:
    qemu_opts_del(opts);
    return NULL;
3588 3589
}

3590
CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
A
aliguori 已提交
3591 3592 3593
{
    const char *p;
    CharDriverState *chr;
3594
    QemuOpts *opts;
3595
    Error *err = NULL;
3596

G
Gerd Hoffmann 已提交
3597 3598 3599 3600
    if (strstart(filename, "chardev:", &p)) {
        return qemu_chr_find(p);
    }

3601
    opts = qemu_chr_parse_compat(label, filename);
G
Gerd Hoffmann 已提交
3602 3603
    if (!opts)
        return NULL;
A
aliguori 已提交
3604

3605
    chr = qemu_chr_new_from_opts(opts, init, &err);
3606
    if (err) {
3607
        error_report("%s", error_get_pretty(err));
3608 3609
        error_free(err);
    }
G
Gerd Hoffmann 已提交
3610
    if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
3611
        qemu_chr_fe_claim_no_fail(chr);
G
Gerd Hoffmann 已提交
3612
        monitor_init(chr, MONITOR_USE_READLINE);
A
aliguori 已提交
3613 3614 3615 3616
    }
    return chr;
}

3617
void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
P
Paolo Bonzini 已提交
3618 3619 3620 3621 3622 3623
{
    if (chr->chr_set_echo) {
        chr->chr_set_echo(chr, echo);
    }
}

3624
void qemu_chr_fe_set_open(struct CharDriverState *chr, int fe_open)
3625
{
3626
    if (chr->fe_open == fe_open) {
H
Hans de Goede 已提交
3627 3628
        return;
    }
3629
    chr->fe_open = fe_open;
3630 3631
    if (chr->chr_set_fe_open) {
        chr->chr_set_fe_open(chr, fe_open);
3632 3633 3634
    }
}

M
Marc-André Lureau 已提交
3635 3636 3637 3638 3639 3640 3641
void qemu_chr_fe_event(struct CharDriverState *chr, int event)
{
    if (chr->chr_fe_event) {
        chr->chr_fe_event(chr, event);
    }
}

3642 3643
int qemu_chr_fe_add_watch(CharDriverState *s, GIOCondition cond,
                          GIOFunc func, void *user_data)
A
Anthony Liguori 已提交
3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659
{
    GSource *src;
    guint tag;

    if (s->chr_add_watch == NULL) {
        return -ENOSYS;
    }

    src = s->chr_add_watch(s, cond);
    g_source_set_callback(src, (GSourceFunc)func, user_data, NULL);
    tag = g_source_attach(src, NULL);
    g_source_unref(src);

    return tag;
}

3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682
int qemu_chr_fe_claim(CharDriverState *s)
{
    if (s->avail_connections < 1) {
        return -1;
    }
    s->avail_connections--;
    return 0;
}

void qemu_chr_fe_claim_no_fail(CharDriverState *s)
{
    if (qemu_chr_fe_claim(s) != 0) {
        fprintf(stderr, "%s: error chardev \"%s\" already used\n",
                __func__, s->label);
        exit(1);
    }
}

void qemu_chr_fe_release(CharDriverState *s)
{
    s->avail_connections++;
}

3683
void qemu_chr_delete(CharDriverState *chr)
A
aliguori 已提交
3684
{
B
Blue Swirl 已提交
3685
    QTAILQ_REMOVE(&chardevs, chr, next);
G
Gerd Hoffmann 已提交
3686
    if (chr->chr_close) {
A
aliguori 已提交
3687
        chr->chr_close(chr);
G
Gerd Hoffmann 已提交
3688
    }
3689 3690
    g_free(chr->filename);
    g_free(chr->label);
G
Gerd Hoffmann 已提交
3691 3692 3693
    if (chr->opts) {
        qemu_opts_del(chr->opts);
    }
3694
    g_free(chr);
A
aliguori 已提交
3695 3696
}

L
Luiz Capitulino 已提交
3697
ChardevInfoList *qmp_query_chardev(Error **errp)
A
aliguori 已提交
3698
{
L
Luiz Capitulino 已提交
3699
    ChardevInfoList *chr_list = NULL;
A
aliguori 已提交
3700 3701
    CharDriverState *chr;

B
Blue Swirl 已提交
3702
    QTAILQ_FOREACH(chr, &chardevs, next) {
L
Luiz Capitulino 已提交
3703 3704 3705 3706 3707 3708 3709
        ChardevInfoList *info = g_malloc0(sizeof(*info));
        info->value = g_malloc0(sizeof(*info->value));
        info->value->label = g_strdup(chr->label);
        info->value->filename = g_strdup(chr->filename);

        info->next = chr_list;
        chr_list = info;
A
aliguori 已提交
3710
    }
3711

L
Luiz Capitulino 已提交
3712
    return chr_list;
A
aliguori 已提交
3713
}
G
Gerd Hoffmann 已提交
3714

3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733
ChardevBackendInfoList *qmp_query_chardev_backends(Error **errp)
{
    ChardevBackendInfoList *backend_list = NULL;
    CharDriver *c = NULL;
    GSList *i = NULL;

    for (i = backends; i; i = i->next) {
        ChardevBackendInfoList *info = g_malloc0(sizeof(*info));
        c = i->data;
        info->value = g_malloc0(sizeof(*info->value));
        info->value->name = g_strdup(c->name);

        info->next = backend_list;
        backend_list = info;
    }

    return backend_list;
}

G
Gerd Hoffmann 已提交
3734 3735 3736 3737
CharDriverState *qemu_chr_find(const char *name)
{
    CharDriverState *chr;

B
Blue Swirl 已提交
3738
    QTAILQ_FOREACH(chr, &chardevs, next) {
G
Gerd Hoffmann 已提交
3739 3740 3741 3742 3743 3744
        if (strcmp(chr->label, name) != 0)
            continue;
        return chr;
    }
    return NULL;
}
A
Anthony Liguori 已提交
3745 3746 3747 3748 3749

/* Get a character (serial) device interface.  */
CharDriverState *qemu_char_get_next_serial(void)
{
    static int next_serial;
3750
    CharDriverState *chr;
A
Anthony Liguori 已提交
3751 3752

    /* FIXME: This function needs to go away: use chardev properties!  */
3753 3754 3755 3756 3757 3758 3759

    while (next_serial < MAX_SERIAL_PORTS && serial_hds[next_serial]) {
        chr = serial_hds[next_serial++];
        qemu_chr_fe_claim_no_fail(chr);
        return chr;
    }
    return NULL;
A
Anthony Liguori 已提交
3760 3761
}

3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829
QemuOptsList qemu_chardev_opts = {
    .name = "chardev",
    .implied_opt_name = "backend",
    .head = QTAILQ_HEAD_INITIALIZER(qemu_chardev_opts.head),
    .desc = {
        {
            .name = "backend",
            .type = QEMU_OPT_STRING,
        },{
            .name = "path",
            .type = QEMU_OPT_STRING,
        },{
            .name = "host",
            .type = QEMU_OPT_STRING,
        },{
            .name = "port",
            .type = QEMU_OPT_STRING,
        },{
            .name = "localaddr",
            .type = QEMU_OPT_STRING,
        },{
            .name = "localport",
            .type = QEMU_OPT_STRING,
        },{
            .name = "to",
            .type = QEMU_OPT_NUMBER,
        },{
            .name = "ipv4",
            .type = QEMU_OPT_BOOL,
        },{
            .name = "ipv6",
            .type = QEMU_OPT_BOOL,
        },{
            .name = "wait",
            .type = QEMU_OPT_BOOL,
        },{
            .name = "server",
            .type = QEMU_OPT_BOOL,
        },{
            .name = "delay",
            .type = QEMU_OPT_BOOL,
        },{
            .name = "telnet",
            .type = QEMU_OPT_BOOL,
        },{
            .name = "width",
            .type = QEMU_OPT_NUMBER,
        },{
            .name = "height",
            .type = QEMU_OPT_NUMBER,
        },{
            .name = "cols",
            .type = QEMU_OPT_NUMBER,
        },{
            .name = "rows",
            .type = QEMU_OPT_NUMBER,
        },{
            .name = "mux",
            .type = QEMU_OPT_BOOL,
        },{
            .name = "signal",
            .type = QEMU_OPT_BOOL,
        },{
            .name = "name",
            .type = QEMU_OPT_STRING,
        },{
            .name = "debug",
            .type = QEMU_OPT_NUMBER,
3830
        },{
3831
            .name = "size",
3832
            .type = QEMU_OPT_SIZE,
3833 3834 3835
        },{
            .name = "chardev",
            .type = QEMU_OPT_STRING,
3836 3837 3838 3839
        },
        { /* end of list */ }
    },
};
3840

3841 3842 3843 3844 3845 3846
#ifdef _WIN32

static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
{
    HANDLE out;

3847
    if (file->has_in) {
3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860
        error_setg(errp, "input file not supported");
        return NULL;
    }

    out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
                     OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (out == INVALID_HANDLE_VALUE) {
        error_setg(errp, "open %s failed", file->out);
        return NULL;
    }
    return qemu_chr_open_win_file(out);
}

3861 3862
static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
                                                Error **errp)
3863
{
3864 3865 3866 3867 3868 3869 3870 3871
    return qemu_chr_open_win_path(serial->device);
}

static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
                                                  Error **errp)
{
    error_setg(errp, "character device backend type 'parallel' not supported");
    return NULL;
3872 3873
}

3874 3875 3876 3877 3878 3879 3880 3881 3882
#else /* WIN32 */

static int qmp_chardev_open_file_source(char *src, int flags,
                                        Error **errp)
{
    int fd = -1;

    TFR(fd = qemu_open(src, flags, 0666));
    if (fd == -1) {
3883
        error_setg_file_open(errp, errno, src);
3884 3885 3886 3887 3888 3889
    }
    return fd;
}

static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)
{
3890
    int flags, in = -1, out;
3891 3892 3893

    flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;
    out = qmp_chardev_open_file_source(file->out, flags, errp);
3894
    if (out < 0) {
3895 3896 3897
        return NULL;
    }

3898
    if (file->has_in) {
3899 3900
        flags = O_RDONLY;
        in = qmp_chardev_open_file_source(file->in, flags, errp);
3901
        if (in < 0) {
3902 3903 3904 3905 3906 3907 3908 3909
            qemu_close(out);
            return NULL;
        }
    }

    return qemu_chr_open_fd(in, out);
}

3910 3911
static CharDriverState *qmp_chardev_open_serial(ChardevHostdev *serial,
                                                Error **errp)
3912 3913
{
#ifdef HAVE_CHARDEV_TTY
3914 3915 3916
    int fd;

    fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);
3917
    if (fd < 0) {
3918
        return NULL;
3919
    }
3920
    qemu_set_nonblock(fd);
3921 3922 3923 3924
    return qemu_chr_open_tty_fd(fd);
#else
    error_setg(errp, "character device backend type 'serial' not supported");
    return NULL;
3925
#endif
3926 3927 3928 3929 3930
}

static CharDriverState *qmp_chardev_open_parallel(ChardevHostdev *parallel,
                                                  Error **errp)
{
3931
#ifdef HAVE_CHARDEV_PARPORT
3932 3933 3934
    int fd;

    fd = qmp_chardev_open_file_source(parallel->device, O_RDWR, errp);
3935
    if (fd < 0) {
3936 3937
        return NULL;
    }
3938 3939 3940 3941 3942
    return qemu_chr_open_pp_fd(fd);
#else
    error_setg(errp, "character device backend type 'parallel' not supported");
    return NULL;
#endif
3943 3944
}

3945 3946
#endif /* WIN32 */

3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961
static CharDriverState *qmp_chardev_open_socket(ChardevSocket *sock,
                                                Error **errp)
{
    SocketAddress *addr = sock->addr;
    bool do_nodelay     = sock->has_nodelay ? sock->nodelay : false;
    bool is_listen      = sock->has_server  ? sock->server  : true;
    bool is_telnet      = sock->has_telnet  ? sock->telnet  : false;
    bool is_waitconnect = sock->has_wait    ? sock->wait    : false;
    int fd;

    if (is_listen) {
        fd = socket_listen(addr, errp);
    } else {
        fd = socket_connect(addr, errp, NULL, NULL);
    }
3962
    if (fd < 0) {
3963 3964 3965 3966 3967 3968
        return NULL;
    }
    return qemu_chr_open_socket_fd(fd, do_nodelay, is_listen,
                                   is_telnet, is_waitconnect, errp);
}

3969 3970
static CharDriverState *qmp_chardev_open_udp(ChardevUdp *udp,
                                             Error **errp)
G
Gerd Hoffmann 已提交
3971 3972 3973
{
    int fd;

3974
    fd = socket_dgram(udp->remote, udp->local, errp);
3975
    if (fd < 0) {
G
Gerd Hoffmann 已提交
3976 3977 3978 3979 3980
        return NULL;
    }
    return qemu_chr_open_udp_fd(fd);
}

3981 3982 3983 3984
ChardevReturn *qmp_chardev_add(const char *id, ChardevBackend *backend,
                               Error **errp)
{
    ChardevReturn *ret = g_new0(ChardevReturn, 1);
3985
    CharDriverState *base, *chr = NULL;
3986 3987 3988 3989 3990 3991 3992 3993 3994

    chr = qemu_chr_find(id);
    if (chr) {
        error_setg(errp, "Chardev '%s' already exists", id);
        g_free(ret);
        return NULL;
    }

    switch (backend->kind) {
3995 3996 3997
    case CHARDEV_BACKEND_KIND_FILE:
        chr = qmp_chardev_open_file(backend->file, errp);
        break;
3998 3999 4000 4001 4002
    case CHARDEV_BACKEND_KIND_SERIAL:
        chr = qmp_chardev_open_serial(backend->serial, errp);
        break;
    case CHARDEV_BACKEND_KIND_PARALLEL:
        chr = qmp_chardev_open_parallel(backend->parallel, errp);
4003
        break;
4004 4005 4006
    case CHARDEV_BACKEND_KIND_PIPE:
        chr = qemu_chr_open_pipe(backend->pipe);
        break;
4007 4008 4009
    case CHARDEV_BACKEND_KIND_SOCKET:
        chr = qmp_chardev_open_socket(backend->socket, errp);
        break;
4010 4011
    case CHARDEV_BACKEND_KIND_UDP:
        chr = qmp_chardev_open_udp(backend->udp, errp);
G
Gerd Hoffmann 已提交
4012
        break;
4013 4014
#ifdef HAVE_CHARDEV_TTY
    case CHARDEV_BACKEND_KIND_PTY:
G
Gerd Hoffmann 已提交
4015
        chr = qemu_chr_open_pty(id, ret);
4016 4017
        break;
#endif
4018
    case CHARDEV_BACKEND_KIND_NULL:
4019
        chr = qemu_chr_open_null();
4020
        break;
4021 4022 4023 4024 4025 4026 4027 4028 4029
    case CHARDEV_BACKEND_KIND_MUX:
        base = qemu_chr_find(backend->mux->chardev);
        if (base == NULL) {
            error_setg(errp, "mux: base chardev %s not found",
                       backend->mux->chardev);
            break;
        }
        chr = qemu_chr_open_mux(base);
        break;
4030 4031 4032
    case CHARDEV_BACKEND_KIND_MSMOUSE:
        chr = qemu_chr_open_msmouse();
        break;
4033 4034 4035 4036 4037
#ifdef CONFIG_BRLAPI
    case CHARDEV_BACKEND_KIND_BRAILLE:
        chr = chr_baum_init();
        break;
#endif
4038 4039 4040
    case CHARDEV_BACKEND_KIND_STDIO:
        chr = qemu_chr_open_stdio(backend->stdio);
        break;
4041 4042 4043 4044
#ifdef _WIN32
    case CHARDEV_BACKEND_KIND_CONSOLE:
        chr = qemu_chr_open_win_con();
        break;
4045 4046 4047 4048 4049 4050 4051 4052
#endif
#ifdef CONFIG_SPICE
    case CHARDEV_BACKEND_KIND_SPICEVMC:
        chr = qemu_chr_open_spice_vmc(backend->spicevmc->type);
        break;
    case CHARDEV_BACKEND_KIND_SPICEPORT:
        chr = qemu_chr_open_spice_port(backend->spiceport->fqdn);
        break;
4053
#endif
G
Gerd Hoffmann 已提交
4054 4055 4056
    case CHARDEV_BACKEND_KIND_VC:
        chr = vc_init(backend->vc);
        break;
4057
    case CHARDEV_BACKEND_KIND_RINGBUF:
4058
    case CHARDEV_BACKEND_KIND_MEMORY:
4059
        chr = qemu_chr_open_ringbuf(backend->ringbuf, errp);
4060
        break;
4061 4062 4063 4064 4065
    default:
        error_setg(errp, "unknown chardev backend (%d)", backend->kind);
        break;
    }

4066 4067 4068 4069 4070 4071 4072
    /*
     * Character backend open hasn't been fully converted to the Error
     * API.  Some opens fail without setting an error.  Set a generic
     * error then.
     * TODO full conversion to Error API
     */
    if (chr == NULL && errp && !*errp) {
4073 4074 4075 4076
        error_setg(errp, "Failed to create chardev");
    }
    if (chr) {
        chr->label = g_strdup(id);
4077 4078
        chr->avail_connections =
            (backend->kind == CHARDEV_BACKEND_KIND_MUX) ? MAX_MUX : 1;
4079 4080 4081
        if (!chr->filename) {
            chr->filename = g_strdup(ChardevBackendKind_lookup[backend->kind]);
        }
4082 4083 4084
        if (!chr->explicit_be_open) {
            qemu_chr_be_event(chr, CHR_EVENT_OPENED);
        }
4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108
        QTAILQ_INSERT_TAIL(&chardevs, chr, next);
        return ret;
    } else {
        g_free(ret);
        return NULL;
    }
}

void qmp_chardev_remove(const char *id, Error **errp)
{
    CharDriverState *chr;

    chr = qemu_chr_find(id);
    if (NULL == chr) {
        error_setg(errp, "Chardev '%s' not found", id);
        return;
    }
    if (chr->chr_can_read || chr->chr_read ||
        chr->chr_event || chr->handler_opaque) {
        error_setg(errp, "Chardev '%s' is busy", id);
        return;
    }
    qemu_chr_delete(chr);
}
4109 4110 4111

static void register_types(void)
{
4112
    register_char_driver_qapi("null", CHARDEV_BACKEND_KIND_NULL, NULL);
4113 4114
    register_char_driver("socket", qemu_chr_open_socket);
    register_char_driver("udp", qemu_chr_open_udp);
4115
    register_char_driver_qapi("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,
4116
                              qemu_chr_parse_ringbuf);
4117 4118
    register_char_driver_qapi("file", CHARDEV_BACKEND_KIND_FILE,
                              qemu_chr_parse_file_out);
4119 4120
    register_char_driver_qapi("stdio", CHARDEV_BACKEND_KIND_STDIO,
                              qemu_chr_parse_stdio);
4121 4122 4123 4124
    register_char_driver_qapi("serial", CHARDEV_BACKEND_KIND_SERIAL,
                              qemu_chr_parse_serial);
    register_char_driver_qapi("tty", CHARDEV_BACKEND_KIND_SERIAL,
                              qemu_chr_parse_serial);
4125 4126 4127 4128
    register_char_driver_qapi("parallel", CHARDEV_BACKEND_KIND_PARALLEL,
                              qemu_chr_parse_parallel);
    register_char_driver_qapi("parport", CHARDEV_BACKEND_KIND_PARALLEL,
                              qemu_chr_parse_parallel);
G
Gerd Hoffmann 已提交
4129
    register_char_driver_qapi("pty", CHARDEV_BACKEND_KIND_PTY, NULL);
4130
    register_char_driver_qapi("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL);
4131 4132
    register_char_driver_qapi("pipe", CHARDEV_BACKEND_KIND_PIPE,
                              qemu_chr_parse_pipe);
4133 4134
    register_char_driver_qapi("mux", CHARDEV_BACKEND_KIND_MUX,
                              qemu_chr_parse_mux);
4135 4136 4137
    /* Bug-compatibility: */
    register_char_driver_qapi("memory", CHARDEV_BACKEND_KIND_MEMORY,
                              qemu_chr_parse_ringbuf);
4138 4139 4140 4141 4142
    /* this must be done after machine init, since we register FEs with muxes
     * as part of realize functions like serial_isa_realizefn when -nographic
     * is specified
     */
    qemu_add_machine_init_done_notifier(&muxes_realize_notify);
4143 4144 4145
}

type_init(register_types);