Statistics
| Branch: | Revision:

root / qemu-char.c @ 58650218

History | View | Annotate | Download (75.1 kB)

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

    
35
#include <unistd.h>
36
#include <fcntl.h>
37
#include <time.h>
38
#include <errno.h>
39
#include <sys/time.h>
40
#include <zlib.h>
41

    
42
#ifndef _WIN32
43
#include <sys/times.h>
44
#include <sys/wait.h>
45
#include <termios.h>
46
#include <sys/mman.h>
47
#include <sys/ioctl.h>
48
#include <sys/resource.h>
49
#include <sys/socket.h>
50
#include <netinet/in.h>
51
#include <net/if.h>
52
#include <arpa/inet.h>
53
#include <dirent.h>
54
#include <netdb.h>
55
#include <sys/select.h>
56
#ifdef CONFIG_BSD
57
#include <sys/stat.h>
58
#if defined(__GLIBC__)
59
#include <pty.h>
60
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
61
#include <libutil.h>
62
#else
63
#include <util.h>
64
#endif
65
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
66
#include <dev/ppbus/ppi.h>
67
#include <dev/ppbus/ppbconf.h>
68
#elif defined(__DragonFly__)
69
#include <dev/misc/ppi/ppi.h>
70
#include <bus/ppbus/ppbconf.h>
71
#endif
72
#else
73
#ifdef __linux__
74
#include <pty.h>
75

    
76
#include <linux/ppdev.h>
77
#include <linux/parport.h>
78
#endif
79
#ifdef __sun__
80
#include <sys/stat.h>
81
#include <sys/ethernet.h>
82
#include <sys/sockio.h>
83
#include <netinet/arp.h>
84
#include <netinet/in.h>
85
#include <netinet/in_systm.h>
86
#include <netinet/ip.h>
87
#include <netinet/ip_icmp.h> // must come after ip.h
88
#include <netinet/udp.h>
89
#include <netinet/tcp.h>
90
#include <net/if.h>
91
#include <syslog.h>
92
#include <stropts.h>
93
#endif
94
#endif
95
#endif
96

    
97
#include "qemu/sockets.h"
98
#include "ui/qemu-spice.h"
99

    
100
#define READ_BUF_LEN 4096
101

    
102
/***********************************************************/
103
/* character device */
104

    
105
static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
106
    QTAILQ_HEAD_INITIALIZER(chardevs);
107

    
108
void qemu_chr_be_event(CharDriverState *s, int event)
109
{
110
    /* Keep track if the char device is open */
111
    switch (event) {
112
        case CHR_EVENT_OPENED:
113
            s->opened = 1;
114
            break;
115
        case CHR_EVENT_CLOSED:
116
            s->opened = 0;
117
            break;
118
    }
119

    
120
    if (!s->chr_event)
121
        return;
122
    s->chr_event(s->handler_opaque, event);
123
}
124

    
125
static void qemu_chr_fire_open_event(void *opaque)
126
{
127
    CharDriverState *s = opaque;
128
    qemu_chr_be_event(s, CHR_EVENT_OPENED);
129
    qemu_free_timer(s->open_timer);
130
    s->open_timer = NULL;
131
}
132

    
133
void qemu_chr_generic_open(CharDriverState *s)
134
{
135
    if (s->open_timer == NULL) {
136
        s->open_timer = qemu_new_timer_ms(rt_clock,
137
                                          qemu_chr_fire_open_event, s);
138
        qemu_mod_timer(s->open_timer, qemu_get_clock_ms(rt_clock) - 1);
139
    }
140
}
141

    
142
int qemu_chr_fe_write(CharDriverState *s, const uint8_t *buf, int len)
143
{
144
    return s->chr_write(s, buf, len);
145
}
146

    
147
int qemu_chr_fe_ioctl(CharDriverState *s, int cmd, void *arg)
148
{
149
    if (!s->chr_ioctl)
150
        return -ENOTSUP;
151
    return s->chr_ioctl(s, cmd, arg);
152
}
153

    
154
int qemu_chr_be_can_write(CharDriverState *s)
155
{
156
    if (!s->chr_can_read)
157
        return 0;
158
    return s->chr_can_read(s->handler_opaque);
159
}
160

    
161
void qemu_chr_be_write(CharDriverState *s, uint8_t *buf, int len)
162
{
163
    if (s->chr_read) {
164
        s->chr_read(s->handler_opaque, buf, len);
165
    }
166
}
167

    
168
int qemu_chr_fe_get_msgfd(CharDriverState *s)
169
{
170
    return s->get_msgfd ? s->get_msgfd(s) : -1;
171
}
172

    
173
int qemu_chr_add_client(CharDriverState *s, int fd)
174
{
175
    return s->chr_add_client ? s->chr_add_client(s, fd) : -1;
176
}
177

    
178
void qemu_chr_accept_input(CharDriverState *s)
179
{
180
    if (s->chr_accept_input)
181
        s->chr_accept_input(s);
182
    qemu_notify_event();
183
}
184

    
185
void qemu_chr_fe_printf(CharDriverState *s, const char *fmt, ...)
186
{
187
    char buf[READ_BUF_LEN];
188
    va_list ap;
189
    va_start(ap, fmt);
190
    vsnprintf(buf, sizeof(buf), fmt, ap);
191
    qemu_chr_fe_write(s, (uint8_t *)buf, strlen(buf));
192
    va_end(ap);
193
}
194

    
195
void qemu_chr_add_handlers(CharDriverState *s,
196
                           IOCanReadHandler *fd_can_read,
197
                           IOReadHandler *fd_read,
198
                           IOEventHandler *fd_event,
199
                           void *opaque)
200
{
201
    if (!opaque && !fd_can_read && !fd_read && !fd_event) {
202
        /* chr driver being released. */
203
        ++s->avail_connections;
204
    }
205
    s->chr_can_read = fd_can_read;
206
    s->chr_read = fd_read;
207
    s->chr_event = fd_event;
208
    s->handler_opaque = opaque;
209
    if (s->chr_update_read_handler)
210
        s->chr_update_read_handler(s);
211

    
212
    /* We're connecting to an already opened device, so let's make sure we
213
       also get the open event */
214
    if (s->opened) {
215
        qemu_chr_generic_open(s);
216
    }
217
}
218

    
219
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
220
{
221
    return len;
222
}
223

    
224
static CharDriverState *qemu_chr_open_null(QemuOpts *opts)
225
{
226
    CharDriverState *chr;
227

    
228
    chr = g_malloc0(sizeof(CharDriverState));
229
    chr->chr_write = null_chr_write;
230
    return chr;
231
}
232

    
233
/* MUX driver for serial I/O splitting */
234
#define MAX_MUX 4
235
#define MUX_BUFFER_SIZE 32        /* Must be a power of 2.  */
236
#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
237
typedef struct {
238
    IOCanReadHandler *chr_can_read[MAX_MUX];
239
    IOReadHandler *chr_read[MAX_MUX];
240
    IOEventHandler *chr_event[MAX_MUX];
241
    void *ext_opaque[MAX_MUX];
242
    CharDriverState *drv;
243
    int focus;
244
    int mux_cnt;
245
    int term_got_escape;
246
    int max_size;
247
    /* Intermediate input buffer allows to catch escape sequences even if the
248
       currently active device is not accepting any input - but only until it
249
       is full as well. */
250
    unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
251
    int prod[MAX_MUX];
252
    int cons[MAX_MUX];
253
    int timestamps;
254
    int linestart;
255
    int64_t timestamps_start;
256
} MuxDriver;
257

    
258

    
259
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
260
{
261
    MuxDriver *d = chr->opaque;
262
    int ret;
263
    if (!d->timestamps) {
264
        ret = d->drv->chr_write(d->drv, buf, len);
265
    } else {
266
        int i;
267

    
268
        ret = 0;
269
        for (i = 0; i < len; i++) {
270
            if (d->linestart) {
271
                char buf1[64];
272
                int64_t ti;
273
                int secs;
274

    
275
                ti = qemu_get_clock_ms(rt_clock);
276
                if (d->timestamps_start == -1)
277
                    d->timestamps_start = ti;
278
                ti -= d->timestamps_start;
279
                secs = ti / 1000;
280
                snprintf(buf1, sizeof(buf1),
281
                         "[%02d:%02d:%02d.%03d] ",
282
                         secs / 3600,
283
                         (secs / 60) % 60,
284
                         secs % 60,
285
                         (int)(ti % 1000));
286
                d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
287
                d->linestart = 0;
288
            }
289
            ret += d->drv->chr_write(d->drv, buf+i, 1);
290
            if (buf[i] == '\n') {
291
                d->linestart = 1;
292
            }
293
        }
294
    }
295
    return ret;
296
}
297

    
298
static const char * const mux_help[] = {
299
    "% h    print this help\n\r",
300
    "% x    exit emulator\n\r",
301
    "% s    save disk data back to file (if -snapshot)\n\r",
302
    "% t    toggle console timestamps\n\r"
303
    "% b    send break (magic sysrq)\n\r",
304
    "% c    switch between console and monitor\n\r",
305
    "% %  sends %\n\r",
306
    NULL
307
};
308

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

    
316
    if (term_escape_char > 0 && term_escape_char < 26) {
317
        snprintf(cbuf, sizeof(cbuf), "\n\r");
318
        snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
319
    } else {
320
        snprintf(cbuf, sizeof(cbuf),
321
                 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
322
                 term_escape_char);
323
    }
324
    chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
325
    for (i = 0; mux_help[i] != NULL; i++) {
326
        for (j=0; mux_help[i][j] != '\0'; j++) {
327
            if (mux_help[i][j] == '%')
328
                chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
329
            else
330
                chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
331
        }
332
    }
333
}
334

    
335
static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
336
{
337
    if (d->chr_event[mux_nr])
338
        d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
339
}
340

    
341
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
342
{
343
    if (d->term_got_escape) {
344
        d->term_got_escape = 0;
345
        if (ch == term_escape_char)
346
            goto send_char;
347
        switch(ch) {
348
        case '?':
349
        case 'h':
350
            mux_print_help(chr);
351
            break;
352
        case 'x':
353
            {
354
                 const char *term =  "QEMU: Terminated\n\r";
355
                 chr->chr_write(chr,(uint8_t *)term,strlen(term));
356
                 exit(0);
357
                 break;
358
            }
359
        case 's':
360
            bdrv_commit_all();
361
            break;
362
        case 'b':
363
            qemu_chr_be_event(chr, CHR_EVENT_BREAK);
364
            break;
365
        case 'c':
366
            /* Switch to the next registered device */
367
            mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
368
            d->focus++;
369
            if (d->focus >= d->mux_cnt)
370
                d->focus = 0;
371
            mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
372
            break;
373
        case 't':
374
            d->timestamps = !d->timestamps;
375
            d->timestamps_start = -1;
376
            d->linestart = 0;
377
            break;
378
        }
379
    } else if (ch == term_escape_char) {
380
        d->term_got_escape = 1;
381
    } else {
382
    send_char:
383
        return 1;
384
    }
385
    return 0;
386
}
387

    
388
static void mux_chr_accept_input(CharDriverState *chr)
389
{
390
    MuxDriver *d = chr->opaque;
391
    int m = d->focus;
392

    
393
    while (d->prod[m] != d->cons[m] &&
394
           d->chr_can_read[m] &&
395
           d->chr_can_read[m](d->ext_opaque[m])) {
396
        d->chr_read[m](d->ext_opaque[m],
397
                       &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
398
    }
399
}
400

    
401
static int mux_chr_can_read(void *opaque)
402
{
403
    CharDriverState *chr = opaque;
404
    MuxDriver *d = chr->opaque;
405
    int m = d->focus;
406

    
407
    if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
408
        return 1;
409
    if (d->chr_can_read[m])
410
        return d->chr_can_read[m](d->ext_opaque[m]);
411
    return 0;
412
}
413

    
414
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
415
{
416
    CharDriverState *chr = opaque;
417
    MuxDriver *d = chr->opaque;
418
    int m = d->focus;
419
    int i;
420

    
421
    mux_chr_accept_input (opaque);
422

    
423
    for(i = 0; i < size; i++)
424
        if (mux_proc_byte(chr, d, buf[i])) {
425
            if (d->prod[m] == d->cons[m] &&
426
                d->chr_can_read[m] &&
427
                d->chr_can_read[m](d->ext_opaque[m]))
428
                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
429
            else
430
                d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
431
        }
432
}
433

    
434
static void mux_chr_event(void *opaque, int event)
435
{
436
    CharDriverState *chr = opaque;
437
    MuxDriver *d = chr->opaque;
438
    int i;
439

    
440
    /* Send the event to all registered listeners */
441
    for (i = 0; i < d->mux_cnt; i++)
442
        mux_chr_send_event(d, i, event);
443
}
444

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

    
449
    if (d->mux_cnt >= MAX_MUX) {
450
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
451
        return;
452
    }
453
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
454
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
455
    d->chr_read[d->mux_cnt] = chr->chr_read;
456
    d->chr_event[d->mux_cnt] = chr->chr_event;
457
    /* Fix up the real driver with mux routines */
458
    if (d->mux_cnt == 0) {
459
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
460
                              mux_chr_event, chr);
461
    }
462
    if (d->focus != -1) {
463
        mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
464
    }
465
    d->focus = d->mux_cnt;
466
    d->mux_cnt++;
467
    mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
468
}
469

    
470
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
471
{
472
    CharDriverState *chr;
473
    MuxDriver *d;
474

    
475
    chr = g_malloc0(sizeof(CharDriverState));
476
    d = g_malloc0(sizeof(MuxDriver));
477

    
478
    chr->opaque = d;
479
    d->drv = drv;
480
    d->focus = -1;
481
    chr->chr_write = mux_chr_write;
482
    chr->chr_update_read_handler = mux_chr_update_read_handler;
483
    chr->chr_accept_input = mux_chr_accept_input;
484
    /* Frontend guest-open / -close notification is not support with muxes */
485
    chr->chr_guest_open = NULL;
486
    chr->chr_guest_close = NULL;
487

    
488
    /* Muxes are always open on creation */
489
    qemu_chr_generic_open(chr);
490

    
491
    return chr;
492
}
493

    
494

    
495
#ifdef _WIN32
496
int send_all(int fd, const void *buf, int len1)
497
{
498
    int ret, len;
499

    
500
    len = len1;
501
    while (len > 0) {
502
        ret = send(fd, buf, len, 0);
503
        if (ret < 0) {
504
            errno = WSAGetLastError();
505
            if (errno != WSAEWOULDBLOCK) {
506
                return -1;
507
            }
508
        } else if (ret == 0) {
509
            break;
510
        } else {
511
            buf += ret;
512
            len -= ret;
513
        }
514
    }
515
    return len1 - len;
516
}
517

    
518
#else
519

    
520
int send_all(int fd, const void *_buf, int len1)
521
{
522
    int ret, len;
523
    const uint8_t *buf = _buf;
524

    
525
    len = len1;
526
    while (len > 0) {
527
        ret = write(fd, buf, len);
528
        if (ret < 0) {
529
            if (errno != EINTR && errno != EAGAIN)
530
                return -1;
531
        } else if (ret == 0) {
532
            break;
533
        } else {
534
            buf += ret;
535
            len -= ret;
536
        }
537
    }
538
    return len1 - len;
539
}
540
#endif /* !_WIN32 */
541

    
542
#define STDIO_MAX_CLIENTS 1
543
static int stdio_nb_clients;
544

    
545
#ifndef _WIN32
546

    
547
typedef struct {
548
    int fd_in, fd_out;
549
    int max_size;
550
} FDCharDriver;
551

    
552

    
553
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
554
{
555
    FDCharDriver *s = chr->opaque;
556
    return send_all(s->fd_out, buf, len);
557
}
558

    
559
static int fd_chr_read_poll(void *opaque)
560
{
561
    CharDriverState *chr = opaque;
562
    FDCharDriver *s = chr->opaque;
563

    
564
    s->max_size = qemu_chr_be_can_write(chr);
565
    return s->max_size;
566
}
567

    
568
static void fd_chr_read(void *opaque)
569
{
570
    CharDriverState *chr = opaque;
571
    FDCharDriver *s = chr->opaque;
572
    int size, len;
573
    uint8_t buf[READ_BUF_LEN];
574

    
575
    len = sizeof(buf);
576
    if (len > s->max_size)
577
        len = s->max_size;
578
    if (len == 0)
579
        return;
580
    size = read(s->fd_in, buf, len);
581
    if (size == 0) {
582
        /* FD has been closed. Remove it from the active list.  */
583
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
584
        qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
585
        return;
586
    }
587
    if (size > 0) {
588
        qemu_chr_be_write(chr, buf, size);
589
    }
590
}
591

    
592
static void fd_chr_update_read_handler(CharDriverState *chr)
593
{
594
    FDCharDriver *s = chr->opaque;
595

    
596
    if (s->fd_in >= 0) {
597
        if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
598
        } else {
599
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
600
                                 fd_chr_read, NULL, chr);
601
        }
602
    }
603
}
604

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

    
609
    if (s->fd_in >= 0) {
610
        if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
611
        } else {
612
            qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
613
        }
614
    }
615

    
616
    g_free(s);
617
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
618
}
619

    
620
/* open a character device to a unix fd */
621
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
622
{
623
    CharDriverState *chr;
624
    FDCharDriver *s;
625

    
626
    chr = g_malloc0(sizeof(CharDriverState));
627
    s = g_malloc0(sizeof(FDCharDriver));
628
    s->fd_in = fd_in;
629
    s->fd_out = fd_out;
630
    chr->opaque = s;
631
    chr->chr_write = fd_chr_write;
632
    chr->chr_update_read_handler = fd_chr_update_read_handler;
633
    chr->chr_close = fd_chr_close;
634

    
635
    qemu_chr_generic_open(chr);
636

    
637
    return chr;
638
}
639

    
640
static CharDriverState *qemu_chr_open_file_out(QemuOpts *opts)
641
{
642
    int fd_out;
643

    
644
    TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
645
                      O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
646
    if (fd_out < 0) {
647
        return NULL;
648
    }
649
    return qemu_chr_open_fd(-1, fd_out);
650
}
651

    
652
static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)
653
{
654
    int fd_in, fd_out;
655
    char filename_in[256], filename_out[256];
656
    const char *filename = qemu_opt_get(opts, "path");
657

    
658
    if (filename == NULL) {
659
        fprintf(stderr, "chardev: pipe: no filename given\n");
660
        return NULL;
661
    }
662

    
663
    snprintf(filename_in, 256, "%s.in", filename);
664
    snprintf(filename_out, 256, "%s.out", filename);
665
    TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
666
    TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
667
    if (fd_in < 0 || fd_out < 0) {
668
        if (fd_in >= 0)
669
            close(fd_in);
670
        if (fd_out >= 0)
671
            close(fd_out);
672
        TFR(fd_in = fd_out = qemu_open(filename, O_RDWR | O_BINARY));
673
        if (fd_in < 0) {
674
            return NULL;
675
        }
676
    }
677
    return qemu_chr_open_fd(fd_in, fd_out);
678
}
679

    
680

    
681
/* for STDIO, we handle the case where several clients use it
682
   (nographic mode) */
683

    
684
#define TERM_FIFO_MAX_SIZE 1
685

    
686
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
687
static int term_fifo_size;
688

    
689
static int stdio_read_poll(void *opaque)
690
{
691
    CharDriverState *chr = opaque;
692

    
693
    /* try to flush the queue if needed */
694
    if (term_fifo_size != 0 && qemu_chr_be_can_write(chr) > 0) {
695
        qemu_chr_be_write(chr, term_fifo, 1);
696
        term_fifo_size = 0;
697
    }
698
    /* see if we can absorb more chars */
699
    if (term_fifo_size == 0)
700
        return 1;
701
    else
702
        return 0;
703
}
704

    
705
static void stdio_read(void *opaque)
706
{
707
    int size;
708
    uint8_t buf[1];
709
    CharDriverState *chr = opaque;
710

    
711
    size = read(0, buf, 1);
712
    if (size == 0) {
713
        /* stdin has been closed. Remove it from the active list.  */
714
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
715
        qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
716
        return;
717
    }
718
    if (size > 0) {
719
        if (qemu_chr_be_can_write(chr) > 0) {
720
            qemu_chr_be_write(chr, buf, 1);
721
        } else if (term_fifo_size == 0) {
722
            term_fifo[term_fifo_size++] = buf[0];
723
        }
724
    }
725
}
726

    
727
/* init terminal so that we can grab keys */
728
static struct termios oldtty;
729
static int old_fd0_flags;
730
static bool stdio_allow_signal;
731

    
732
static void term_exit(void)
733
{
734
    tcsetattr (0, TCSANOW, &oldtty);
735
    fcntl(0, F_SETFL, old_fd0_flags);
736
}
737

    
738
static void qemu_chr_set_echo_stdio(CharDriverState *chr, bool echo)
739
{
740
    struct termios tty;
741

    
742
    tty = oldtty;
743
    if (!echo) {
744
        tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
745
                          |INLCR|IGNCR|ICRNL|IXON);
746
        tty.c_oflag |= OPOST;
747
        tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
748
        tty.c_cflag &= ~(CSIZE|PARENB);
749
        tty.c_cflag |= CS8;
750
        tty.c_cc[VMIN] = 1;
751
        tty.c_cc[VTIME] = 0;
752
    }
753
    /* if graphical mode, we allow Ctrl-C handling */
754
    if (!stdio_allow_signal)
755
        tty.c_lflag &= ~ISIG;
756

    
757
    tcsetattr (0, TCSANOW, &tty);
758
}
759

    
760
static void qemu_chr_close_stdio(struct CharDriverState *chr)
761
{
762
    term_exit();
763
    stdio_nb_clients--;
764
    qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
765
    fd_chr_close(chr);
766
}
767

    
768
static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)
769
{
770
    CharDriverState *chr;
771

    
772
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS) {
773
        return NULL;
774
    }
775
    if (stdio_nb_clients == 0) {
776
        old_fd0_flags = fcntl(0, F_GETFL);
777
        tcgetattr (0, &oldtty);
778
        fcntl(0, F_SETFL, O_NONBLOCK);
779
        atexit(term_exit);
780
    }
781

    
782
    chr = qemu_chr_open_fd(0, 1);
783
    chr->chr_close = qemu_chr_close_stdio;
784
    chr->chr_set_echo = qemu_chr_set_echo_stdio;
785
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
786
    stdio_nb_clients++;
787
    stdio_allow_signal = qemu_opt_get_bool(opts, "signal",
788
                                           display_type != DT_NOGRAPHIC);
789
    qemu_chr_fe_set_echo(chr, false);
790

    
791
    return chr;
792
}
793

    
794
#ifdef __sun__
795
/* Once Solaris has openpty(), this is going to be removed. */
796
static int openpty(int *amaster, int *aslave, char *name,
797
                   struct termios *termp, struct winsize *winp)
798
{
799
        const char *slave;
800
        int mfd = -1, sfd = -1;
801

    
802
        *amaster = *aslave = -1;
803

    
804
        mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
805
        if (mfd < 0)
806
                goto err;
807

    
808
        if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
809
                goto err;
810

    
811
        if ((slave = ptsname(mfd)) == NULL)
812
                goto err;
813

    
814
        if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
815
                goto err;
816

    
817
        if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
818
            (termp != NULL && tcgetattr(sfd, termp) < 0))
819
                goto err;
820

    
821
        if (amaster)
822
                *amaster = mfd;
823
        if (aslave)
824
                *aslave = sfd;
825
        if (winp)
826
                ioctl(sfd, TIOCSWINSZ, winp);
827

    
828
        return 0;
829

    
830
err:
831
        if (sfd != -1)
832
                close(sfd);
833
        close(mfd);
834
        return -1;
835
}
836

    
837
static void cfmakeraw (struct termios *termios_p)
838
{
839
        termios_p->c_iflag &=
840
                ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
841
        termios_p->c_oflag &= ~OPOST;
842
        termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
843
        termios_p->c_cflag &= ~(CSIZE|PARENB);
844
        termios_p->c_cflag |= CS8;
845

    
846
        termios_p->c_cc[VMIN] = 0;
847
        termios_p->c_cc[VTIME] = 0;
848
}
849
#endif
850

    
851
#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
852
    || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
853
    || defined(__GLIBC__)
854

    
855
typedef struct {
856
    int fd;
857
    int connected;
858
    int polling;
859
    int read_bytes;
860
    QEMUTimer *timer;
861
} PtyCharDriver;
862

    
863
static void pty_chr_update_read_handler(CharDriverState *chr);
864
static void pty_chr_state(CharDriverState *chr, int connected);
865

    
866
static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
867
{
868
    PtyCharDriver *s = chr->opaque;
869

    
870
    if (!s->connected) {
871
        /* guest sends data, check for (re-)connect */
872
        pty_chr_update_read_handler(chr);
873
        return 0;
874
    }
875
    return send_all(s->fd, buf, len);
876
}
877

    
878
static int pty_chr_read_poll(void *opaque)
879
{
880
    CharDriverState *chr = opaque;
881
    PtyCharDriver *s = chr->opaque;
882

    
883
    s->read_bytes = qemu_chr_be_can_write(chr);
884
    return s->read_bytes;
885
}
886

    
887
static void pty_chr_read(void *opaque)
888
{
889
    CharDriverState *chr = opaque;
890
    PtyCharDriver *s = chr->opaque;
891
    int size, len;
892
    uint8_t buf[READ_BUF_LEN];
893

    
894
    len = sizeof(buf);
895
    if (len > s->read_bytes)
896
        len = s->read_bytes;
897
    if (len == 0)
898
        return;
899
    size = read(s->fd, buf, len);
900
    if ((size == -1 && errno == EIO) ||
901
        (size == 0)) {
902
        pty_chr_state(chr, 0);
903
        return;
904
    }
905
    if (size > 0) {
906
        pty_chr_state(chr, 1);
907
        qemu_chr_be_write(chr, buf, size);
908
    }
909
}
910

    
911
static void pty_chr_update_read_handler(CharDriverState *chr)
912
{
913
    PtyCharDriver *s = chr->opaque;
914

    
915
    qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
916
                         pty_chr_read, NULL, chr);
917
    s->polling = 1;
918
    /*
919
     * Short timeout here: just need wait long enougth that qemu makes
920
     * it through the poll loop once.  When reconnected we want a
921
     * short timeout so we notice it almost instantly.  Otherwise
922
     * read() gives us -EIO instantly, making pty_chr_state() reset the
923
     * timeout to the normal (much longer) poll interval before the
924
     * timer triggers.
925
     */
926
    qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 10);
927
}
928

    
929
static void pty_chr_state(CharDriverState *chr, int connected)
930
{
931
    PtyCharDriver *s = chr->opaque;
932

    
933
    if (!connected) {
934
        qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
935
        s->connected = 0;
936
        s->polling = 0;
937
        /* (re-)connect poll interval for idle guests: once per second.
938
         * We check more frequently in case the guests sends data to
939
         * the virtual device linked to our pty. */
940
        qemu_mod_timer(s->timer, qemu_get_clock_ms(rt_clock) + 1000);
941
    } else {
942
        if (!s->connected)
943
            qemu_chr_generic_open(chr);
944
        s->connected = 1;
945
    }
946
}
947

    
948
static void pty_chr_timer(void *opaque)
949
{
950
    struct CharDriverState *chr = opaque;
951
    PtyCharDriver *s = chr->opaque;
952

    
953
    if (s->connected)
954
        return;
955
    if (s->polling) {
956
        /* If we arrive here without polling being cleared due
957
         * read returning -EIO, then we are (re-)connected */
958
        pty_chr_state(chr, 1);
959
        return;
960
    }
961

    
962
    /* Next poll ... */
963
    pty_chr_update_read_handler(chr);
964
}
965

    
966
static void pty_chr_close(struct CharDriverState *chr)
967
{
968
    PtyCharDriver *s = chr->opaque;
969

    
970
    qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
971
    close(s->fd);
972
    qemu_del_timer(s->timer);
973
    qemu_free_timer(s->timer);
974
    g_free(s);
975
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
976
}
977

    
978
static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
979
{
980
    CharDriverState *chr;
981
    PtyCharDriver *s;
982
    struct termios tty;
983
    const char *label;
984
    int master_fd, slave_fd, len;
985
#if defined(__OpenBSD__) || defined(__DragonFly__)
986
    char pty_name[PATH_MAX];
987
#define q_ptsname(x) pty_name
988
#else
989
    char *pty_name = NULL;
990
#define q_ptsname(x) ptsname(x)
991
#endif
992

    
993
    if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {
994
        return NULL;
995
    }
996

    
997
    /* Set raw attributes on the pty. */
998
    tcgetattr(slave_fd, &tty);
999
    cfmakeraw(&tty);
1000
    tcsetattr(slave_fd, TCSAFLUSH, &tty);
1001
    close(slave_fd);
1002

    
1003
    chr = g_malloc0(sizeof(CharDriverState));
1004

    
1005
    len = strlen(q_ptsname(master_fd)) + 5;
1006
    chr->filename = g_malloc(len);
1007
    snprintf(chr->filename, len, "pty:%s", q_ptsname(master_fd));
1008
    qemu_opt_set(opts, "path", q_ptsname(master_fd));
1009

    
1010
    label = qemu_opts_id(opts);
1011
    fprintf(stderr, "char device%s%s redirected to %s\n",
1012
            label ? " " : "",
1013
            label ?: "",
1014
            q_ptsname(master_fd));
1015

    
1016
    s = g_malloc0(sizeof(PtyCharDriver));
1017
    chr->opaque = s;
1018
    chr->chr_write = pty_chr_write;
1019
    chr->chr_update_read_handler = pty_chr_update_read_handler;
1020
    chr->chr_close = pty_chr_close;
1021

    
1022
    s->fd = master_fd;
1023
    s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr);
1024

    
1025
    return chr;
1026
}
1027

    
1028
static void tty_serial_init(int fd, int speed,
1029
                            int parity, int data_bits, int stop_bits)
1030
{
1031
    struct termios tty;
1032
    speed_t spd;
1033

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

    
1040
#define check_speed(val) if (speed <= val) { spd = B##val; break; }
1041
    speed = speed * 10 / 11;
1042
    do {
1043
        check_speed(50);
1044
        check_speed(75);
1045
        check_speed(110);
1046
        check_speed(134);
1047
        check_speed(150);
1048
        check_speed(200);
1049
        check_speed(300);
1050
        check_speed(600);
1051
        check_speed(1200);
1052
        check_speed(1800);
1053
        check_speed(2400);
1054
        check_speed(4800);
1055
        check_speed(9600);
1056
        check_speed(19200);
1057
        check_speed(38400);
1058
        /* Non-Posix values follow. They may be unsupported on some systems. */
1059
        check_speed(57600);
1060
        check_speed(115200);
1061
#ifdef B230400
1062
        check_speed(230400);
1063
#endif
1064
#ifdef B460800
1065
        check_speed(460800);
1066
#endif
1067
#ifdef B500000
1068
        check_speed(500000);
1069
#endif
1070
#ifdef B576000
1071
        check_speed(576000);
1072
#endif
1073
#ifdef B921600
1074
        check_speed(921600);
1075
#endif
1076
#ifdef B1000000
1077
        check_speed(1000000);
1078
#endif
1079
#ifdef B1152000
1080
        check_speed(1152000);
1081
#endif
1082
#ifdef B1500000
1083
        check_speed(1500000);
1084
#endif
1085
#ifdef B2000000
1086
        check_speed(2000000);
1087
#endif
1088
#ifdef B2500000
1089
        check_speed(2500000);
1090
#endif
1091
#ifdef B3000000
1092
        check_speed(3000000);
1093
#endif
1094
#ifdef B3500000
1095
        check_speed(3500000);
1096
#endif
1097
#ifdef B4000000
1098
        check_speed(4000000);
1099
#endif
1100
        spd = B115200;
1101
    } while (0);
1102

    
1103
    cfsetispeed(&tty, spd);
1104
    cfsetospeed(&tty, spd);
1105

    
1106
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1107
                          |INLCR|IGNCR|ICRNL|IXON);
1108
    tty.c_oflag |= OPOST;
1109
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1110
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1111
    switch(data_bits) {
1112
    default:
1113
    case 8:
1114
        tty.c_cflag |= CS8;
1115
        break;
1116
    case 7:
1117
        tty.c_cflag |= CS7;
1118
        break;
1119
    case 6:
1120
        tty.c_cflag |= CS6;
1121
        break;
1122
    case 5:
1123
        tty.c_cflag |= CS5;
1124
        break;
1125
    }
1126
    switch(parity) {
1127
    default:
1128
    case 'N':
1129
        break;
1130
    case 'E':
1131
        tty.c_cflag |= PARENB;
1132
        break;
1133
    case 'O':
1134
        tty.c_cflag |= PARENB | PARODD;
1135
        break;
1136
    }
1137
    if (stop_bits == 2)
1138
        tty.c_cflag |= CSTOPB;
1139

    
1140
    tcsetattr (fd, TCSANOW, &tty);
1141
}
1142

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

    
1147
    switch(cmd) {
1148
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1149
        {
1150
            QEMUSerialSetParams *ssp = arg;
1151
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1152
                            ssp->data_bits, ssp->stop_bits);
1153
        }
1154
        break;
1155
    case CHR_IOCTL_SERIAL_SET_BREAK:
1156
        {
1157
            int enable = *(int *)arg;
1158
            if (enable)
1159
                tcsendbreak(s->fd_in, 1);
1160
        }
1161
        break;
1162
    case CHR_IOCTL_SERIAL_GET_TIOCM:
1163
        {
1164
            int sarg = 0;
1165
            int *targ = (int *)arg;
1166
            ioctl(s->fd_in, TIOCMGET, &sarg);
1167
            *targ = 0;
1168
            if (sarg & TIOCM_CTS)
1169
                *targ |= CHR_TIOCM_CTS;
1170
            if (sarg & TIOCM_CAR)
1171
                *targ |= CHR_TIOCM_CAR;
1172
            if (sarg & TIOCM_DSR)
1173
                *targ |= CHR_TIOCM_DSR;
1174
            if (sarg & TIOCM_RI)
1175
                *targ |= CHR_TIOCM_RI;
1176
            if (sarg & TIOCM_DTR)
1177
                *targ |= CHR_TIOCM_DTR;
1178
            if (sarg & TIOCM_RTS)
1179
                *targ |= CHR_TIOCM_RTS;
1180
        }
1181
        break;
1182
    case CHR_IOCTL_SERIAL_SET_TIOCM:
1183
        {
1184
            int sarg = *(int *)arg;
1185
            int targ = 0;
1186
            ioctl(s->fd_in, TIOCMGET, &targ);
1187
            targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1188
                     | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1189
            if (sarg & CHR_TIOCM_CTS)
1190
                targ |= TIOCM_CTS;
1191
            if (sarg & CHR_TIOCM_CAR)
1192
                targ |= TIOCM_CAR;
1193
            if (sarg & CHR_TIOCM_DSR)
1194
                targ |= TIOCM_DSR;
1195
            if (sarg & CHR_TIOCM_RI)
1196
                targ |= TIOCM_RI;
1197
            if (sarg & CHR_TIOCM_DTR)
1198
                targ |= TIOCM_DTR;
1199
            if (sarg & CHR_TIOCM_RTS)
1200
                targ |= TIOCM_RTS;
1201
            ioctl(s->fd_in, TIOCMSET, &targ);
1202
        }
1203
        break;
1204
    default:
1205
        return -ENOTSUP;
1206
    }
1207
    return 0;
1208
}
1209

    
1210
static void qemu_chr_close_tty(CharDriverState *chr)
1211
{
1212
    FDCharDriver *s = chr->opaque;
1213
    int fd = -1;
1214

    
1215
    if (s) {
1216
        fd = s->fd_in;
1217
    }
1218

    
1219
    fd_chr_close(chr);
1220

    
1221
    if (fd >= 0) {
1222
        close(fd);
1223
    }
1224
}
1225

    
1226
static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
1227
{
1228
    const char *filename = qemu_opt_get(opts, "path");
1229
    CharDriverState *chr;
1230
    int fd;
1231

    
1232
    TFR(fd = qemu_open(filename, O_RDWR | O_NONBLOCK));
1233
    if (fd < 0) {
1234
        return NULL;
1235
    }
1236
    tty_serial_init(fd, 115200, 'N', 8, 1);
1237
    chr = qemu_chr_open_fd(fd, fd);
1238
    chr->chr_ioctl = tty_serial_ioctl;
1239
    chr->chr_close = qemu_chr_close_tty;
1240
    return chr;
1241
}
1242
#else  /* ! __linux__ && ! __sun__ */
1243
static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
1244
{
1245
    return NULL;
1246
}
1247
#endif /* __linux__ || __sun__ */
1248

    
1249
#if defined(__linux__)
1250
typedef struct {
1251
    int fd;
1252
    int mode;
1253
} ParallelCharDriver;
1254

    
1255
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1256
{
1257
    if (s->mode != mode) {
1258
        int m = mode;
1259
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
1260
            return 0;
1261
        s->mode = mode;
1262
    }
1263
    return 1;
1264
}
1265

    
1266
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1267
{
1268
    ParallelCharDriver *drv = chr->opaque;
1269
    int fd = drv->fd;
1270
    uint8_t b;
1271

    
1272
    switch(cmd) {
1273
    case CHR_IOCTL_PP_READ_DATA:
1274
        if (ioctl(fd, PPRDATA, &b) < 0)
1275
            return -ENOTSUP;
1276
        *(uint8_t *)arg = b;
1277
        break;
1278
    case CHR_IOCTL_PP_WRITE_DATA:
1279
        b = *(uint8_t *)arg;
1280
        if (ioctl(fd, PPWDATA, &b) < 0)
1281
            return -ENOTSUP;
1282
        break;
1283
    case CHR_IOCTL_PP_READ_CONTROL:
1284
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1285
            return -ENOTSUP;
1286
        /* Linux gives only the lowest bits, and no way to know data
1287
           direction! For better compatibility set the fixed upper
1288
           bits. */
1289
        *(uint8_t *)arg = b | 0xc0;
1290
        break;
1291
    case CHR_IOCTL_PP_WRITE_CONTROL:
1292
        b = *(uint8_t *)arg;
1293
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1294
            return -ENOTSUP;
1295
        break;
1296
    case CHR_IOCTL_PP_READ_STATUS:
1297
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1298
            return -ENOTSUP;
1299
        *(uint8_t *)arg = b;
1300
        break;
1301
    case CHR_IOCTL_PP_DATA_DIR:
1302
        if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1303
            return -ENOTSUP;
1304
        break;
1305
    case CHR_IOCTL_PP_EPP_READ_ADDR:
1306
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1307
            struct ParallelIOArg *parg = arg;
1308
            int n = read(fd, parg->buffer, parg->count);
1309
            if (n != parg->count) {
1310
                return -EIO;
1311
            }
1312
        }
1313
        break;
1314
    case CHR_IOCTL_PP_EPP_READ:
1315
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1316
            struct ParallelIOArg *parg = arg;
1317
            int n = read(fd, parg->buffer, parg->count);
1318
            if (n != parg->count) {
1319
                return -EIO;
1320
            }
1321
        }
1322
        break;
1323
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1324
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1325
            struct ParallelIOArg *parg = arg;
1326
            int n = write(fd, parg->buffer, parg->count);
1327
            if (n != parg->count) {
1328
                return -EIO;
1329
            }
1330
        }
1331
        break;
1332
    case CHR_IOCTL_PP_EPP_WRITE:
1333
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1334
            struct ParallelIOArg *parg = arg;
1335
            int n = write(fd, parg->buffer, parg->count);
1336
            if (n != parg->count) {
1337
                return -EIO;
1338
            }
1339
        }
1340
        break;
1341
    default:
1342
        return -ENOTSUP;
1343
    }
1344
    return 0;
1345
}
1346

    
1347
static void pp_close(CharDriverState *chr)
1348
{
1349
    ParallelCharDriver *drv = chr->opaque;
1350
    int fd = drv->fd;
1351

    
1352
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1353
    ioctl(fd, PPRELEASE);
1354
    close(fd);
1355
    g_free(drv);
1356
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1357
}
1358

    
1359
static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1360
{
1361
    const char *filename = qemu_opt_get(opts, "path");
1362
    CharDriverState *chr;
1363
    ParallelCharDriver *drv;
1364
    int fd;
1365

    
1366
    TFR(fd = qemu_open(filename, O_RDWR));
1367
    if (fd < 0) {
1368
        return NULL;
1369
    }
1370

    
1371
    if (ioctl(fd, PPCLAIM) < 0) {
1372
        close(fd);
1373
        return NULL;
1374
    }
1375

    
1376
    drv = g_malloc0(sizeof(ParallelCharDriver));
1377
    drv->fd = fd;
1378
    drv->mode = IEEE1284_MODE_COMPAT;
1379

    
1380
    chr = g_malloc0(sizeof(CharDriverState));
1381
    chr->chr_write = null_chr_write;
1382
    chr->chr_ioctl = pp_ioctl;
1383
    chr->chr_close = pp_close;
1384
    chr->opaque = drv;
1385

    
1386
    qemu_chr_generic_open(chr);
1387

    
1388
    return chr;
1389
}
1390
#endif /* __linux__ */
1391

    
1392
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1393
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1394
{
1395
    int fd = (int)(intptr_t)chr->opaque;
1396
    uint8_t b;
1397

    
1398
    switch(cmd) {
1399
    case CHR_IOCTL_PP_READ_DATA:
1400
        if (ioctl(fd, PPIGDATA, &b) < 0)
1401
            return -ENOTSUP;
1402
        *(uint8_t *)arg = b;
1403
        break;
1404
    case CHR_IOCTL_PP_WRITE_DATA:
1405
        b = *(uint8_t *)arg;
1406
        if (ioctl(fd, PPISDATA, &b) < 0)
1407
            return -ENOTSUP;
1408
        break;
1409
    case CHR_IOCTL_PP_READ_CONTROL:
1410
        if (ioctl(fd, PPIGCTRL, &b) < 0)
1411
            return -ENOTSUP;
1412
        *(uint8_t *)arg = b;
1413
        break;
1414
    case CHR_IOCTL_PP_WRITE_CONTROL:
1415
        b = *(uint8_t *)arg;
1416
        if (ioctl(fd, PPISCTRL, &b) < 0)
1417
            return -ENOTSUP;
1418
        break;
1419
    case CHR_IOCTL_PP_READ_STATUS:
1420
        if (ioctl(fd, PPIGSTATUS, &b) < 0)
1421
            return -ENOTSUP;
1422
        *(uint8_t *)arg = b;
1423
        break;
1424
    default:
1425
        return -ENOTSUP;
1426
    }
1427
    return 0;
1428
}
1429

    
1430
static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1431
{
1432
    const char *filename = qemu_opt_get(opts, "path");
1433
    CharDriverState *chr;
1434
    int fd;
1435

    
1436
    fd = qemu_open(filename, O_RDWR);
1437
    if (fd < 0) {
1438
        return NULL;
1439
    }
1440

    
1441
    chr = g_malloc0(sizeof(CharDriverState));
1442
    chr->opaque = (void *)(intptr_t)fd;
1443
    chr->chr_write = null_chr_write;
1444
    chr->chr_ioctl = pp_ioctl;
1445
    return chr;
1446
}
1447
#endif
1448

    
1449
#else /* _WIN32 */
1450

    
1451
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1452

    
1453
typedef struct {
1454
    int max_size;
1455
    HANDLE hcom, hrecv, hsend;
1456
    OVERLAPPED orecv, osend;
1457
    BOOL fpipe;
1458
    DWORD len;
1459
} WinCharState;
1460

    
1461
typedef struct {
1462
    HANDLE  hStdIn;
1463
    HANDLE  hInputReadyEvent;
1464
    HANDLE  hInputDoneEvent;
1465
    HANDLE  hInputThread;
1466
    uint8_t win_stdio_buf;
1467
} WinStdioCharState;
1468

    
1469
#define NSENDBUF 2048
1470
#define NRECVBUF 2048
1471
#define MAXCONNECT 1
1472
#define NTIMEOUT 5000
1473

    
1474
static int win_chr_poll(void *opaque);
1475
static int win_chr_pipe_poll(void *opaque);
1476

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

    
1481
    if (s->hsend) {
1482
        CloseHandle(s->hsend);
1483
        s->hsend = NULL;
1484
    }
1485
    if (s->hrecv) {
1486
        CloseHandle(s->hrecv);
1487
        s->hrecv = NULL;
1488
    }
1489
    if (s->hcom) {
1490
        CloseHandle(s->hcom);
1491
        s->hcom = NULL;
1492
    }
1493
    if (s->fpipe)
1494
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
1495
    else
1496
        qemu_del_polling_cb(win_chr_poll, chr);
1497

    
1498
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
1499
}
1500

    
1501
static int win_chr_init(CharDriverState *chr, const char *filename)
1502
{
1503
    WinCharState *s = chr->opaque;
1504
    COMMCONFIG comcfg;
1505
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1506
    COMSTAT comstat;
1507
    DWORD size;
1508
    DWORD err;
1509

    
1510
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1511
    if (!s->hsend) {
1512
        fprintf(stderr, "Failed CreateEvent\n");
1513
        goto fail;
1514
    }
1515
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1516
    if (!s->hrecv) {
1517
        fprintf(stderr, "Failed CreateEvent\n");
1518
        goto fail;
1519
    }
1520

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

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

    
1534
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1535
    size = sizeof(COMMCONFIG);
1536
    GetDefaultCommConfig(filename, &comcfg, &size);
1537
    comcfg.dcb.DCBlength = sizeof(DCB);
1538
    CommConfigDialog(filename, NULL, &comcfg);
1539

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

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

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

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

    
1563
 fail:
1564
    win_chr_close(chr);
1565
    return -1;
1566
}
1567

    
1568
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1569
{
1570
    WinCharState *s = chr->opaque;
1571
    DWORD len, ret, size, err;
1572

    
1573
    len = len1;
1574
    ZeroMemory(&s->osend, sizeof(s->osend));
1575
    s->osend.hEvent = s->hsend;
1576
    while (len > 0) {
1577
        if (s->hsend)
1578
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1579
        else
1580
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
1581
        if (!ret) {
1582
            err = GetLastError();
1583
            if (err == ERROR_IO_PENDING) {
1584
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1585
                if (ret) {
1586
                    buf += size;
1587
                    len -= size;
1588
                } else {
1589
                    break;
1590
                }
1591
            } else {
1592
                break;
1593
            }
1594
        } else {
1595
            buf += size;
1596
            len -= size;
1597
        }
1598
    }
1599
    return len1 - len;
1600
}
1601

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

    
1606
    s->max_size = qemu_chr_be_can_write(chr);
1607
    return s->max_size;
1608
}
1609

    
1610
static void win_chr_readfile(CharDriverState *chr)
1611
{
1612
    WinCharState *s = chr->opaque;
1613
    int ret, err;
1614
    uint8_t buf[READ_BUF_LEN];
1615
    DWORD size;
1616

    
1617
    ZeroMemory(&s->orecv, sizeof(s->orecv));
1618
    s->orecv.hEvent = s->hrecv;
1619
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1620
    if (!ret) {
1621
        err = GetLastError();
1622
        if (err == ERROR_IO_PENDING) {
1623
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1624
        }
1625
    }
1626

    
1627
    if (size > 0) {
1628
        qemu_chr_be_write(chr, buf, size);
1629
    }
1630
}
1631

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

    
1636
    if (s->len > s->max_size)
1637
        s->len = s->max_size;
1638
    if (s->len == 0)
1639
        return;
1640

    
1641
    win_chr_readfile(chr);
1642
}
1643

    
1644
static int win_chr_poll(void *opaque)
1645
{
1646
    CharDriverState *chr = opaque;
1647
    WinCharState *s = chr->opaque;
1648
    COMSTAT status;
1649
    DWORD comerr;
1650

    
1651
    ClearCommError(s->hcom, &comerr, &status);
1652
    if (status.cbInQue > 0) {
1653
        s->len = status.cbInQue;
1654
        win_chr_read_poll(chr);
1655
        win_chr_read(chr);
1656
        return 1;
1657
    }
1658
    return 0;
1659
}
1660

    
1661
static CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1662
{
1663
    const char *filename = qemu_opt_get(opts, "path");
1664
    CharDriverState *chr;
1665
    WinCharState *s;
1666

    
1667
    chr = g_malloc0(sizeof(CharDriverState));
1668
    s = g_malloc0(sizeof(WinCharState));
1669
    chr->opaque = s;
1670
    chr->chr_write = win_chr_write;
1671
    chr->chr_close = win_chr_close;
1672

    
1673
    if (win_chr_init(chr, filename) < 0) {
1674
        g_free(s);
1675
        g_free(chr);
1676
        return NULL;
1677
    }
1678
    qemu_chr_generic_open(chr);
1679
    return chr;
1680
}
1681

    
1682
static int win_chr_pipe_poll(void *opaque)
1683
{
1684
    CharDriverState *chr = opaque;
1685
    WinCharState *s = chr->opaque;
1686
    DWORD size;
1687

    
1688
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1689
    if (size > 0) {
1690
        s->len = size;
1691
        win_chr_read_poll(chr);
1692
        win_chr_read(chr);
1693
        return 1;
1694
    }
1695
    return 0;
1696
}
1697

    
1698
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1699
{
1700
    WinCharState *s = chr->opaque;
1701
    OVERLAPPED ov;
1702
    int ret;
1703
    DWORD size;
1704
    char openname[256];
1705

    
1706
    s->fpipe = TRUE;
1707

    
1708
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1709
    if (!s->hsend) {
1710
        fprintf(stderr, "Failed CreateEvent\n");
1711
        goto fail;
1712
    }
1713
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1714
    if (!s->hrecv) {
1715
        fprintf(stderr, "Failed CreateEvent\n");
1716
        goto fail;
1717
    }
1718

    
1719
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1720
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1721
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1722
                              PIPE_WAIT,
1723
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1724
    if (s->hcom == INVALID_HANDLE_VALUE) {
1725
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1726
        s->hcom = NULL;
1727
        goto fail;
1728
    }
1729

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

    
1738
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1739
    if (!ret) {
1740
        fprintf(stderr, "Failed GetOverlappedResult\n");
1741
        if (ov.hEvent) {
1742
            CloseHandle(ov.hEvent);
1743
            ov.hEvent = NULL;
1744
        }
1745
        goto fail;
1746
    }
1747

    
1748
    if (ov.hEvent) {
1749
        CloseHandle(ov.hEvent);
1750
        ov.hEvent = NULL;
1751
    }
1752
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
1753
    return 0;
1754

    
1755
 fail:
1756
    win_chr_close(chr);
1757
    return -1;
1758
}
1759

    
1760

    
1761
static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
1762
{
1763
    const char *filename = qemu_opt_get(opts, "path");
1764
    CharDriverState *chr;
1765
    WinCharState *s;
1766

    
1767
    chr = g_malloc0(sizeof(CharDriverState));
1768
    s = g_malloc0(sizeof(WinCharState));
1769
    chr->opaque = s;
1770
    chr->chr_write = win_chr_write;
1771
    chr->chr_close = win_chr_close;
1772

    
1773
    if (win_chr_pipe_init(chr, filename) < 0) {
1774
        g_free(s);
1775
        g_free(chr);
1776
        return NULL;
1777
    }
1778
    qemu_chr_generic_open(chr);
1779
    return chr;
1780
}
1781

    
1782
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1783
{
1784
    CharDriverState *chr;
1785
    WinCharState *s;
1786

    
1787
    chr = g_malloc0(sizeof(CharDriverState));
1788
    s = g_malloc0(sizeof(WinCharState));
1789
    s->hcom = fd_out;
1790
    chr->opaque = s;
1791
    chr->chr_write = win_chr_write;
1792
    qemu_chr_generic_open(chr);
1793
    return chr;
1794
}
1795

    
1796
static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
1797
{
1798
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1799
}
1800

    
1801
static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
1802
{
1803
    const char *file_out = qemu_opt_get(opts, "path");
1804
    HANDLE fd_out;
1805

    
1806
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1807
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1808
    if (fd_out == INVALID_HANDLE_VALUE) {
1809
        return NULL;
1810
    }
1811

    
1812
    return qemu_chr_open_win_file(fd_out);
1813
}
1814

    
1815
static int win_stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1816
{
1817
    HANDLE  hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
1818
    DWORD   dwSize;
1819
    int     len1;
1820

    
1821
    len1 = len;
1822

    
1823
    while (len1 > 0) {
1824
        if (!WriteFile(hStdOut, buf, len1, &dwSize, NULL)) {
1825
            break;
1826
        }
1827
        buf  += dwSize;
1828
        len1 -= dwSize;
1829
    }
1830

    
1831
    return len - len1;
1832
}
1833

    
1834
static void win_stdio_wait_func(void *opaque)
1835
{
1836
    CharDriverState   *chr   = opaque;
1837
    WinStdioCharState *stdio = chr->opaque;
1838
    INPUT_RECORD       buf[4];
1839
    int                ret;
1840
    DWORD              dwSize;
1841
    int                i;
1842

    
1843
    ret = ReadConsoleInput(stdio->hStdIn, buf, sizeof(buf) / sizeof(*buf),
1844
                           &dwSize);
1845

    
1846
    if (!ret) {
1847
        /* Avoid error storm */
1848
        qemu_del_wait_object(stdio->hStdIn, NULL, NULL);
1849
        return;
1850
    }
1851

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

    
1855
        if (buf[i].EventType == KEY_EVENT && kev->bKeyDown) {
1856
            int j;
1857
            if (kev->uChar.AsciiChar != 0) {
1858
                for (j = 0; j < kev->wRepeatCount; j++) {
1859
                    if (qemu_chr_be_can_write(chr)) {
1860
                        uint8_t c = kev->uChar.AsciiChar;
1861
                        qemu_chr_be_write(chr, &c, 1);
1862
                    }
1863
                }
1864
            }
1865
        }
1866
    }
1867
}
1868

    
1869
static DWORD WINAPI win_stdio_thread(LPVOID param)
1870
{
1871
    CharDriverState   *chr   = param;
1872
    WinStdioCharState *stdio = chr->opaque;
1873
    int                ret;
1874
    DWORD              dwSize;
1875

    
1876
    while (1) {
1877

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

    
1881
        /* Exit in case of error, continue if nothing read */
1882
        if (!ret) {
1883
            break;
1884
        }
1885
        if (!dwSize) {
1886
            continue;
1887
        }
1888

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

    
1894
        /* Signal the main thread and wait until the byte was eaten */
1895
        if (!SetEvent(stdio->hInputReadyEvent)) {
1896
            break;
1897
        }
1898
        if (WaitForSingleObject(stdio->hInputDoneEvent, INFINITE)
1899
            != WAIT_OBJECT_0) {
1900
            break;
1901
        }
1902
    }
1903

    
1904
    qemu_del_wait_object(stdio->hInputReadyEvent, NULL, NULL);
1905
    return 0;
1906
}
1907

    
1908
static void win_stdio_thread_wait_func(void *opaque)
1909
{
1910
    CharDriverState   *chr   = opaque;
1911
    WinStdioCharState *stdio = chr->opaque;
1912

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

    
1917
    SetEvent(stdio->hInputDoneEvent);
1918
}
1919

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

    
1925
    GetConsoleMode(stdio->hStdIn, &dwMode);
1926

    
1927
    if (echo) {
1928
        SetConsoleMode(stdio->hStdIn, dwMode | ENABLE_ECHO_INPUT);
1929
    } else {
1930
        SetConsoleMode(stdio->hStdIn, dwMode & ~ENABLE_ECHO_INPUT);
1931
    }
1932
}
1933

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

    
1938
    if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {
1939
        CloseHandle(stdio->hInputReadyEvent);
1940
    }
1941
    if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {
1942
        CloseHandle(stdio->hInputDoneEvent);
1943
    }
1944
    if (stdio->hInputThread != INVALID_HANDLE_VALUE) {
1945
        TerminateThread(stdio->hInputThread, 0);
1946
    }
1947

    
1948
    g_free(chr->opaque);
1949
    g_free(chr);
1950
    stdio_nb_clients--;
1951
}
1952

    
1953
static CharDriverState *qemu_chr_open_win_stdio(QemuOpts *opts)
1954
{
1955
    CharDriverState   *chr;
1956
    WinStdioCharState *stdio;
1957
    DWORD              dwMode;
1958
    int                is_console = 0;
1959

    
1960
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS
1961
        || ((display_type != DT_NOGRAPHIC) && (stdio_nb_clients != 0))) {
1962
        return NULL;
1963
    }
1964

    
1965
    chr   = g_malloc0(sizeof(CharDriverState));
1966
    stdio = g_malloc0(sizeof(WinStdioCharState));
1967

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

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

    
1976
    chr->opaque    = stdio;
1977
    chr->chr_write = win_stdio_write;
1978
    chr->chr_close = win_stdio_close;
1979

    
1980
    if (stdio_nb_clients == 0) {
1981
        if (is_console) {
1982
            if (qemu_add_wait_object(stdio->hStdIn,
1983
                                     win_stdio_wait_func, chr)) {
1984
                fprintf(stderr, "qemu_add_wait_object: failed\n");
1985
            }
1986
        } else {
1987
            DWORD   dwId;
1988

    
1989
            stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
1990
            stdio->hInputDoneEvent  = CreateEvent(NULL, FALSE, FALSE, NULL);
1991
            stdio->hInputThread     = CreateThread(NULL, 0, win_stdio_thread,
1992
                                            chr, 0, &dwId);
1993

    
1994
            if (stdio->hInputThread == INVALID_HANDLE_VALUE
1995
                || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE
1996
                || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {
1997
                fprintf(stderr, "cannot create stdio thread or event\n");
1998
                exit(1);
1999
            }
2000
            if (qemu_add_wait_object(stdio->hInputReadyEvent,
2001
                                     win_stdio_thread_wait_func, chr)) {
2002
                fprintf(stderr, "qemu_add_wait_object: failed\n");
2003
            }
2004
        }
2005
    }
2006

    
2007
    dwMode |= ENABLE_LINE_INPUT;
2008

    
2009
    stdio_clients[stdio_nb_clients++] = chr;
2010
    if (stdio_nb_clients == 1 && is_console) {
2011
        /* set the terminal in raw mode */
2012
        /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */
2013
        dwMode |= ENABLE_PROCESSED_INPUT;
2014
    }
2015

    
2016
    SetConsoleMode(stdio->hStdIn, dwMode);
2017

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

    
2021
    return chr;
2022
}
2023
#endif /* !_WIN32 */
2024

    
2025
/***********************************************************/
2026
/* UDP Net console */
2027

    
2028
typedef struct {
2029
    int fd;
2030
    uint8_t buf[READ_BUF_LEN];
2031
    int bufcnt;
2032
    int bufptr;
2033
    int max_size;
2034
} NetCharDriver;
2035

    
2036
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2037
{
2038
    NetCharDriver *s = chr->opaque;
2039

    
2040
    return send(s->fd, (const void *)buf, len, 0);
2041
}
2042

    
2043
static int udp_chr_read_poll(void *opaque)
2044
{
2045
    CharDriverState *chr = opaque;
2046
    NetCharDriver *s = chr->opaque;
2047

    
2048
    s->max_size = qemu_chr_be_can_write(chr);
2049

    
2050
    /* If there were any stray characters in the queue process them
2051
     * first
2052
     */
2053
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2054
        qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2055
        s->bufptr++;
2056
        s->max_size = qemu_chr_be_can_write(chr);
2057
    }
2058
    return s->max_size;
2059
}
2060

    
2061
static void udp_chr_read(void *opaque)
2062
{
2063
    CharDriverState *chr = opaque;
2064
    NetCharDriver *s = chr->opaque;
2065

    
2066
    if (s->max_size == 0)
2067
        return;
2068
    s->bufcnt = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);
2069
    s->bufptr = s->bufcnt;
2070
    if (s->bufcnt <= 0)
2071
        return;
2072

    
2073
    s->bufptr = 0;
2074
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2075
        qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);
2076
        s->bufptr++;
2077
        s->max_size = qemu_chr_be_can_write(chr);
2078
    }
2079
}
2080

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

    
2085
    if (s->fd >= 0) {
2086
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2087
                             udp_chr_read, NULL, chr);
2088
    }
2089
}
2090

    
2091
static void udp_chr_close(CharDriverState *chr)
2092
{
2093
    NetCharDriver *s = chr->opaque;
2094
    if (s->fd >= 0) {
2095
        qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2096
        closesocket(s->fd);
2097
    }
2098
    g_free(s);
2099
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2100
}
2101

    
2102
static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
2103
{
2104
    CharDriverState *chr = NULL;
2105
    NetCharDriver *s = NULL;
2106
    Error *local_err = NULL;
2107
    int fd = -1;
2108

    
2109
    chr = g_malloc0(sizeof(CharDriverState));
2110
    s = g_malloc0(sizeof(NetCharDriver));
2111

    
2112
    fd = inet_dgram_opts(opts, &local_err);
2113
    if (fd < 0) {
2114
        goto return_err;
2115
    }
2116

    
2117
    s->fd = fd;
2118
    s->bufcnt = 0;
2119
    s->bufptr = 0;
2120
    chr->opaque = s;
2121
    chr->chr_write = udp_chr_write;
2122
    chr->chr_update_read_handler = udp_chr_update_read_handler;
2123
    chr->chr_close = udp_chr_close;
2124
    return chr;
2125

    
2126
return_err:
2127
    if (local_err) {
2128
        qerror_report_err(local_err);
2129
        error_free(local_err);
2130
    }
2131
    g_free(chr);
2132
    g_free(s);
2133
    if (fd >= 0) {
2134
        closesocket(fd);
2135
    }
2136
    return NULL;
2137
}
2138

    
2139
/***********************************************************/
2140
/* TCP Net console */
2141

    
2142
typedef struct {
2143
    int fd, listen_fd;
2144
    int connected;
2145
    int max_size;
2146
    int do_telnetopt;
2147
    int do_nodelay;
2148
    int is_unix;
2149
    int msgfd;
2150
} TCPCharDriver;
2151

    
2152
static void tcp_chr_accept(void *opaque);
2153

    
2154
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2155
{
2156
    TCPCharDriver *s = chr->opaque;
2157
    if (s->connected) {
2158
        return send_all(s->fd, buf, len);
2159
    } else {
2160
        /* XXX: indicate an error ? */
2161
        return len;
2162
    }
2163
}
2164

    
2165
static int tcp_chr_read_poll(void *opaque)
2166
{
2167
    CharDriverState *chr = opaque;
2168
    TCPCharDriver *s = chr->opaque;
2169
    if (!s->connected)
2170
        return 0;
2171
    s->max_size = qemu_chr_be_can_write(chr);
2172
    return s->max_size;
2173
}
2174

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

    
2190
    int i;
2191
    int j = 0;
2192

    
2193
    for (i = 0; i < *size; i++) {
2194
        if (s->do_telnetopt > 1) {
2195
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2196
                /* Double IAC means send an IAC */
2197
                if (j != i)
2198
                    buf[j] = buf[i];
2199
                j++;
2200
                s->do_telnetopt = 1;
2201
            } else {
2202
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2203
                    /* Handle IAC break commands by sending a serial break */
2204
                    qemu_chr_be_event(chr, CHR_EVENT_BREAK);
2205
                    s->do_telnetopt++;
2206
                }
2207
                s->do_telnetopt++;
2208
            }
2209
            if (s->do_telnetopt >= 4) {
2210
                s->do_telnetopt = 1;
2211
            }
2212
        } else {
2213
            if ((unsigned char)buf[i] == IAC) {
2214
                s->do_telnetopt = 2;
2215
            } else {
2216
                if (j != i)
2217
                    buf[j] = buf[i];
2218
                j++;
2219
            }
2220
        }
2221
    }
2222
    *size = j;
2223
}
2224

    
2225
static int tcp_get_msgfd(CharDriverState *chr)
2226
{
2227
    TCPCharDriver *s = chr->opaque;
2228
    int fd = s->msgfd;
2229
    s->msgfd = -1;
2230
    return fd;
2231
}
2232

    
2233
#ifndef _WIN32
2234
static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
2235
{
2236
    TCPCharDriver *s = chr->opaque;
2237
    struct cmsghdr *cmsg;
2238

    
2239
    for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
2240
        int fd;
2241

    
2242
        if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2243
            cmsg->cmsg_level != SOL_SOCKET ||
2244
            cmsg->cmsg_type != SCM_RIGHTS)
2245
            continue;
2246

    
2247
        fd = *((int *)CMSG_DATA(cmsg));
2248
        if (fd < 0)
2249
            continue;
2250

    
2251
#ifndef MSG_CMSG_CLOEXEC
2252
        qemu_set_cloexec(fd);
2253
#endif
2254
        if (s->msgfd != -1)
2255
            close(s->msgfd);
2256
        s->msgfd = fd;
2257
    }
2258
}
2259

    
2260
static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2261
{
2262
    TCPCharDriver *s = chr->opaque;
2263
    struct msghdr msg = { NULL, };
2264
    struct iovec iov[1];
2265
    union {
2266
        struct cmsghdr cmsg;
2267
        char control[CMSG_SPACE(sizeof(int))];
2268
    } msg_control;
2269
    int flags = 0;
2270
    ssize_t ret;
2271

    
2272
    iov[0].iov_base = buf;
2273
    iov[0].iov_len = len;
2274

    
2275
    msg.msg_iov = iov;
2276
    msg.msg_iovlen = 1;
2277
    msg.msg_control = &msg_control;
2278
    msg.msg_controllen = sizeof(msg_control);
2279

    
2280
#ifdef MSG_CMSG_CLOEXEC
2281
    flags |= MSG_CMSG_CLOEXEC;
2282
#endif
2283
    ret = recvmsg(s->fd, &msg, flags);
2284
    if (ret > 0 && s->is_unix) {
2285
        unix_process_msgfd(chr, &msg);
2286
    }
2287

    
2288
    return ret;
2289
}
2290
#else
2291
static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2292
{
2293
    TCPCharDriver *s = chr->opaque;
2294
    return qemu_recv(s->fd, buf, len, 0);
2295
}
2296
#endif
2297

    
2298
static void tcp_chr_read(void *opaque)
2299
{
2300
    CharDriverState *chr = opaque;
2301
    TCPCharDriver *s = chr->opaque;
2302
    uint8_t buf[READ_BUF_LEN];
2303
    int len, size;
2304

    
2305
    if (!s->connected || s->max_size <= 0)
2306
        return;
2307
    len = sizeof(buf);
2308
    if (len > s->max_size)
2309
        len = s->max_size;
2310
    size = tcp_chr_recv(chr, (void *)buf, len);
2311
    if (size == 0) {
2312
        /* connection closed */
2313
        s->connected = 0;
2314
        if (s->listen_fd >= 0) {
2315
            qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2316
        }
2317
        qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2318
        closesocket(s->fd);
2319
        s->fd = -1;
2320
        qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2321
    } else if (size > 0) {
2322
        if (s->do_telnetopt)
2323
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2324
        if (size > 0)
2325
            qemu_chr_be_write(chr, buf, size);
2326
    }
2327
}
2328

    
2329
#ifndef _WIN32
2330
CharDriverState *qemu_chr_open_eventfd(int eventfd)
2331
{
2332
    return qemu_chr_open_fd(eventfd, eventfd);
2333
}
2334
#endif
2335

    
2336
static void tcp_chr_connect(void *opaque)
2337
{
2338
    CharDriverState *chr = opaque;
2339
    TCPCharDriver *s = chr->opaque;
2340

    
2341
    s->connected = 1;
2342
    if (s->fd >= 0) {
2343
        qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2344
                             tcp_chr_read, NULL, chr);
2345
    }
2346
    qemu_chr_generic_open(chr);
2347
}
2348

    
2349
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2350
static void tcp_chr_telnet_init(int fd)
2351
{
2352
    char buf[3];
2353
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2354
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2355
    send(fd, (char *)buf, 3, 0);
2356
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2357
    send(fd, (char *)buf, 3, 0);
2358
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2359
    send(fd, (char *)buf, 3, 0);
2360
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2361
    send(fd, (char *)buf, 3, 0);
2362
}
2363

    
2364
static void socket_set_nodelay(int fd)
2365
{
2366
    int val = 1;
2367
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2368
}
2369

    
2370
static int tcp_chr_add_client(CharDriverState *chr, int fd)
2371
{
2372
    TCPCharDriver *s = chr->opaque;
2373
    if (s->fd != -1)
2374
        return -1;
2375

    
2376
    socket_set_nonblock(fd);
2377
    if (s->do_nodelay)
2378
        socket_set_nodelay(fd);
2379
    s->fd = fd;
2380
    qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2381
    tcp_chr_connect(chr);
2382

    
2383
    return 0;
2384
}
2385

    
2386
static void tcp_chr_accept(void *opaque)
2387
{
2388
    CharDriverState *chr = opaque;
2389
    TCPCharDriver *s = chr->opaque;
2390
    struct sockaddr_in saddr;
2391
#ifndef _WIN32
2392
    struct sockaddr_un uaddr;
2393
#endif
2394
    struct sockaddr *addr;
2395
    socklen_t len;
2396
    int fd;
2397

    
2398
    for(;;) {
2399
#ifndef _WIN32
2400
        if (s->is_unix) {
2401
            len = sizeof(uaddr);
2402
            addr = (struct sockaddr *)&uaddr;
2403
        } else
2404
#endif
2405
        {
2406
            len = sizeof(saddr);
2407
            addr = (struct sockaddr *)&saddr;
2408
        }
2409
        fd = qemu_accept(s->listen_fd, addr, &len);
2410
        if (fd < 0 && errno != EINTR) {
2411
            return;
2412
        } else if (fd >= 0) {
2413
            if (s->do_telnetopt)
2414
                tcp_chr_telnet_init(fd);
2415
            break;
2416
        }
2417
    }
2418
    if (tcp_chr_add_client(chr, fd) < 0)
2419
        close(fd);
2420
}
2421

    
2422
static void tcp_chr_close(CharDriverState *chr)
2423
{
2424
    TCPCharDriver *s = chr->opaque;
2425
    if (s->fd >= 0) {
2426
        qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2427
        closesocket(s->fd);
2428
    }
2429
    if (s->listen_fd >= 0) {
2430
        qemu_set_fd_handler2(s->listen_fd, NULL, NULL, NULL, NULL);
2431
        closesocket(s->listen_fd);
2432
    }
2433
    g_free(s);
2434
    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
2435
}
2436

    
2437
static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2438
{
2439
    CharDriverState *chr = NULL;
2440
    TCPCharDriver *s = NULL;
2441
    Error *local_err = NULL;
2442
    int fd = -1;
2443
    int is_listen;
2444
    int is_waitconnect;
2445
    int do_nodelay;
2446
    int is_unix;
2447
    int is_telnet;
2448

    
2449
    is_listen      = qemu_opt_get_bool(opts, "server", 0);
2450
    is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2451
    is_telnet      = qemu_opt_get_bool(opts, "telnet", 0);
2452
    do_nodelay     = !qemu_opt_get_bool(opts, "delay", 1);
2453
    is_unix        = qemu_opt_get(opts, "path") != NULL;
2454
    if (!is_listen)
2455
        is_waitconnect = 0;
2456

    
2457
    chr = g_malloc0(sizeof(CharDriverState));
2458
    s = g_malloc0(sizeof(TCPCharDriver));
2459

    
2460
    if (is_unix) {
2461
        if (is_listen) {
2462
            fd = unix_listen_opts(opts, &local_err);
2463
        } else {
2464
            fd = unix_connect_opts(opts, &local_err, NULL, NULL);
2465
        }
2466
    } else {
2467
        if (is_listen) {
2468
            fd = inet_listen_opts(opts, 0, &local_err);
2469
        } else {
2470
            fd = inet_connect_opts(opts, &local_err, NULL, NULL);
2471
        }
2472
    }
2473
    if (fd < 0) {
2474
        goto fail;
2475
    }
2476

    
2477
    if (!is_waitconnect)
2478
        socket_set_nonblock(fd);
2479

    
2480
    s->connected = 0;
2481
    s->fd = -1;
2482
    s->listen_fd = -1;
2483
    s->msgfd = -1;
2484
    s->is_unix = is_unix;
2485
    s->do_nodelay = do_nodelay && !is_unix;
2486

    
2487
    chr->opaque = s;
2488
    chr->chr_write = tcp_chr_write;
2489
    chr->chr_close = tcp_chr_close;
2490
    chr->get_msgfd = tcp_get_msgfd;
2491
    chr->chr_add_client = tcp_chr_add_client;
2492

    
2493
    if (is_listen) {
2494
        s->listen_fd = fd;
2495
        qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);
2496
        if (is_telnet)
2497
            s->do_telnetopt = 1;
2498

    
2499
    } else {
2500
        s->connected = 1;
2501
        s->fd = fd;
2502
        socket_set_nodelay(fd);
2503
        tcp_chr_connect(chr);
2504
    }
2505

    
2506
    /* for "info chardev" monitor command */
2507
    chr->filename = g_malloc(256);
2508
    if (is_unix) {
2509
        snprintf(chr->filename, 256, "unix:%s%s",
2510
                 qemu_opt_get(opts, "path"),
2511
                 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2512
    } else if (is_telnet) {
2513
        snprintf(chr->filename, 256, "telnet:%s:%s%s",
2514
                 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2515
                 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2516
    } else {
2517
        snprintf(chr->filename, 256, "tcp:%s:%s%s",
2518
                 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2519
                 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2520
    }
2521

    
2522
    if (is_listen && is_waitconnect) {
2523
        printf("QEMU waiting for connection on: %s\n",
2524
               chr->filename);
2525
        tcp_chr_accept(chr);
2526
        socket_set_nonblock(s->listen_fd);
2527
    }
2528
    return chr;
2529

    
2530
 fail:
2531
    if (local_err) {
2532
        qerror_report_err(local_err);
2533
        error_free(local_err);
2534
    }
2535
    if (fd >= 0) {
2536
        closesocket(fd);
2537
    }
2538
    g_free(s);
2539
    g_free(chr);
2540
    return NULL;
2541
}
2542

    
2543
/***********************************************************/
2544
/* Memory chardev */
2545
typedef struct {
2546
    size_t outbuf_size;
2547
    size_t outbuf_capacity;
2548
    uint8_t *outbuf;
2549
} MemoryDriver;
2550

    
2551
static int mem_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2552
{
2553
    MemoryDriver *d = chr->opaque;
2554

    
2555
    /* TODO: the QString implementation has the same code, we should
2556
     * introduce a generic way to do this in cutils.c */
2557
    if (d->outbuf_capacity < d->outbuf_size + len) {
2558
        /* grow outbuf */
2559
        d->outbuf_capacity += len;
2560
        d->outbuf_capacity *= 2;
2561
        d->outbuf = g_realloc(d->outbuf, d->outbuf_capacity);
2562
    }
2563

    
2564
    memcpy(d->outbuf + d->outbuf_size, buf, len);
2565
    d->outbuf_size += len;
2566

    
2567
    return len;
2568
}
2569

    
2570
void qemu_chr_init_mem(CharDriverState *chr)
2571
{
2572
    MemoryDriver *d;
2573

    
2574
    d = g_malloc(sizeof(*d));
2575
    d->outbuf_size = 0;
2576
    d->outbuf_capacity = 4096;
2577
    d->outbuf = g_malloc0(d->outbuf_capacity);
2578

    
2579
    memset(chr, 0, sizeof(*chr));
2580
    chr->opaque = d;
2581
    chr->chr_write = mem_chr_write;
2582
}
2583

    
2584
QString *qemu_chr_mem_to_qs(CharDriverState *chr)
2585
{
2586
    MemoryDriver *d = chr->opaque;
2587
    return qstring_from_substr((char *) d->outbuf, 0, d->outbuf_size - 1);
2588
}
2589

    
2590
/* NOTE: this driver can not be closed with qemu_chr_delete()! */
2591
void qemu_chr_close_mem(CharDriverState *chr)
2592
{
2593
    MemoryDriver *d = chr->opaque;
2594

    
2595
    g_free(d->outbuf);
2596
    g_free(chr->opaque);
2597
    chr->opaque = NULL;
2598
    chr->chr_write = NULL;
2599
}
2600

    
2601
size_t qemu_chr_mem_osize(const CharDriverState *chr)
2602
{
2603
    const MemoryDriver *d = chr->opaque;
2604
    return d->outbuf_size;
2605
}
2606

    
2607
QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2608
{
2609
    char host[65], port[33], width[8], height[8];
2610
    int pos;
2611
    const char *p;
2612
    QemuOpts *opts;
2613
    Error *local_err = NULL;
2614

    
2615
    opts = qemu_opts_create(qemu_find_opts("chardev"), label, 1, &local_err);
2616
    if (error_is_set(&local_err)) {
2617
        qerror_report_err(local_err);
2618
        error_free(local_err);
2619
        return NULL;
2620
    }
2621

    
2622
    if (strstart(filename, "mon:", &p)) {
2623
        filename = p;
2624
        qemu_opt_set(opts, "mux", "on");
2625
    }
2626

    
2627
    if (strcmp(filename, "null")    == 0 ||
2628
        strcmp(filename, "pty")     == 0 ||
2629
        strcmp(filename, "msmouse") == 0 ||
2630
        strcmp(filename, "braille") == 0 ||
2631
        strcmp(filename, "stdio")   == 0) {
2632
        qemu_opt_set(opts, "backend", filename);
2633
        return opts;
2634
    }
2635
    if (strstart(filename, "vc", &p)) {
2636
        qemu_opt_set(opts, "backend", "vc");
2637
        if (*p == ':') {
2638
            if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2639
                /* pixels */
2640
                qemu_opt_set(opts, "width", width);
2641
                qemu_opt_set(opts, "height", height);
2642
            } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2643
                /* chars */
2644
                qemu_opt_set(opts, "cols", width);
2645
                qemu_opt_set(opts, "rows", height);
2646
            } else {
2647
                goto fail;
2648
            }
2649
        }
2650
        return opts;
2651
    }
2652
    if (strcmp(filename, "con:") == 0) {
2653
        qemu_opt_set(opts, "backend", "console");
2654
        return opts;
2655
    }
2656
    if (strstart(filename, "COM", NULL)) {
2657
        qemu_opt_set(opts, "backend", "serial");
2658
        qemu_opt_set(opts, "path", filename);
2659
        return opts;
2660
    }
2661
    if (strstart(filename, "file:", &p)) {
2662
        qemu_opt_set(opts, "backend", "file");
2663
        qemu_opt_set(opts, "path", p);
2664
        return opts;
2665
    }
2666
    if (strstart(filename, "pipe:", &p)) {
2667
        qemu_opt_set(opts, "backend", "pipe");
2668
        qemu_opt_set(opts, "path", p);
2669
        return opts;
2670
    }
2671
    if (strstart(filename, "tcp:", &p) ||
2672
        strstart(filename, "telnet:", &p)) {
2673
        if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2674
            host[0] = 0;
2675
            if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2676
                goto fail;
2677
        }
2678
        qemu_opt_set(opts, "backend", "socket");
2679
        qemu_opt_set(opts, "host", host);
2680
        qemu_opt_set(opts, "port", port);
2681
        if (p[pos] == ',') {
2682
            if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2683
                goto fail;
2684
        }
2685
        if (strstart(filename, "telnet:", &p))
2686
            qemu_opt_set(opts, "telnet", "on");
2687
        return opts;
2688
    }
2689
    if (strstart(filename, "udp:", &p)) {
2690
        qemu_opt_set(opts, "backend", "udp");
2691
        if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2692
            host[0] = 0;
2693
            if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
2694
                goto fail;
2695
            }
2696
        }
2697
        qemu_opt_set(opts, "host", host);
2698
        qemu_opt_set(opts, "port", port);
2699
        if (p[pos] == '@') {
2700
            p += pos + 1;
2701
            if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2702
                host[0] = 0;
2703
                if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2704
                    goto fail;
2705
                }
2706
            }
2707
            qemu_opt_set(opts, "localaddr", host);
2708
            qemu_opt_set(opts, "localport", port);
2709
        }
2710
        return opts;
2711
    }
2712
    if (strstart(filename, "unix:", &p)) {
2713
        qemu_opt_set(opts, "backend", "socket");
2714
        if (qemu_opts_do_parse(opts, p, "path") != 0)
2715
            goto fail;
2716
        return opts;
2717
    }
2718
    if (strstart(filename, "/dev/parport", NULL) ||
2719
        strstart(filename, "/dev/ppi", NULL)) {
2720
        qemu_opt_set(opts, "backend", "parport");
2721
        qemu_opt_set(opts, "path", filename);
2722
        return opts;
2723
    }
2724
    if (strstart(filename, "/dev/", NULL)) {
2725
        qemu_opt_set(opts, "backend", "tty");
2726
        qemu_opt_set(opts, "path", filename);
2727
        return opts;
2728
    }
2729

    
2730
fail:
2731
    qemu_opts_del(opts);
2732
    return NULL;
2733
}
2734

    
2735
static const struct {
2736
    const char *name;
2737
    CharDriverState *(*open)(QemuOpts *opts);
2738
} backend_table[] = {
2739
    { .name = "null",      .open = qemu_chr_open_null },
2740
    { .name = "socket",    .open = qemu_chr_open_socket },
2741
    { .name = "udp",       .open = qemu_chr_open_udp },
2742
    { .name = "msmouse",   .open = qemu_chr_open_msmouse },
2743
    { .name = "vc",        .open = text_console_init },
2744
#ifdef _WIN32
2745
    { .name = "file",      .open = qemu_chr_open_win_file_out },
2746
    { .name = "pipe",      .open = qemu_chr_open_win_pipe },
2747
    { .name = "console",   .open = qemu_chr_open_win_con },
2748
    { .name = "serial",    .open = qemu_chr_open_win },
2749
    { .name = "stdio",     .open = qemu_chr_open_win_stdio },
2750
#else
2751
    { .name = "file",      .open = qemu_chr_open_file_out },
2752
    { .name = "pipe",      .open = qemu_chr_open_pipe },
2753
    { .name = "pty",       .open = qemu_chr_open_pty },
2754
    { .name = "stdio",     .open = qemu_chr_open_stdio },
2755
#endif
2756
#ifdef CONFIG_BRLAPI
2757
    { .name = "braille",   .open = chr_baum_init },
2758
#endif
2759
#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2760
    || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
2761
    || defined(__FreeBSD_kernel__)
2762
    { .name = "tty",       .open = qemu_chr_open_tty },
2763
#endif
2764
#if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) \
2765
    || defined(__FreeBSD_kernel__)
2766
    { .name = "parport",   .open = qemu_chr_open_pp },
2767
#endif
2768
#ifdef CONFIG_SPICE
2769
    { .name = "spicevmc",     .open = qemu_chr_open_spice },
2770
#if SPICE_SERVER_VERSION >= 0x000c02
2771
    { .name = "spiceport",    .open = qemu_chr_open_spice_port },
2772
#endif
2773
#endif
2774
};
2775

    
2776
CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,
2777
                                    void (*init)(struct CharDriverState *s))
2778
{
2779
    CharDriverState *chr;
2780
    int i;
2781

    
2782
    if (qemu_opts_id(opts) == NULL) {
2783
        fprintf(stderr, "chardev: no id specified\n");
2784
        return NULL;
2785
    }
2786

    
2787
    if (qemu_opt_get(opts, "backend") == NULL) {
2788
        fprintf(stderr, "chardev: \"%s\" missing backend\n",
2789
                qemu_opts_id(opts));
2790
        return NULL;
2791
    }
2792
    for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
2793
        if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
2794
            break;
2795
    }
2796
    if (i == ARRAY_SIZE(backend_table)) {
2797
        fprintf(stderr, "chardev: backend \"%s\" not found\n",
2798
                qemu_opt_get(opts, "backend"));
2799
        return NULL;
2800
    }
2801

    
2802
    chr = backend_table[i].open(opts);
2803
    if (!chr) {
2804
        fprintf(stderr, "chardev: opening backend \"%s\" failed\n",
2805
                qemu_opt_get(opts, "backend"));
2806
        return NULL;
2807
    }
2808

    
2809
    if (!chr->filename)
2810
        chr->filename = g_strdup(qemu_opt_get(opts, "backend"));
2811
    chr->init = init;
2812
    QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2813

    
2814
    if (qemu_opt_get_bool(opts, "mux", 0)) {
2815
        CharDriverState *base = chr;
2816
        int len = strlen(qemu_opts_id(opts)) + 6;
2817
        base->label = g_malloc(len);
2818
        snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
2819
        chr = qemu_chr_open_mux(base);
2820
        chr->filename = base->filename;
2821
        chr->avail_connections = MAX_MUX;
2822
        QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2823
    } else {
2824
        chr->avail_connections = 1;
2825
    }
2826
    chr->label = g_strdup(qemu_opts_id(opts));
2827
    return chr;
2828
}
2829

    
2830
CharDriverState *qemu_chr_new(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2831
{
2832
    const char *p;
2833
    CharDriverState *chr;
2834
    QemuOpts *opts;
2835

    
2836
    if (strstart(filename, "chardev:", &p)) {
2837
        return qemu_chr_find(p);
2838
    }
2839

    
2840
    opts = qemu_chr_parse_compat(label, filename);
2841
    if (!opts)
2842
        return NULL;
2843

    
2844
    chr = qemu_chr_new_from_opts(opts, init);
2845
    if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
2846
        monitor_init(chr, MONITOR_USE_READLINE);
2847
    }
2848
    qemu_opts_del(opts);
2849
    return chr;
2850
}
2851

    
2852
void qemu_chr_fe_set_echo(struct CharDriverState *chr, bool echo)
2853
{
2854
    if (chr->chr_set_echo) {
2855
        chr->chr_set_echo(chr, echo);
2856
    }
2857
}
2858

    
2859
void qemu_chr_fe_open(struct CharDriverState *chr)
2860
{
2861
    if (chr->chr_guest_open) {
2862
        chr->chr_guest_open(chr);
2863
    }
2864
}
2865

    
2866
void qemu_chr_fe_close(struct CharDriverState *chr)
2867
{
2868
    if (chr->chr_guest_close) {
2869
        chr->chr_guest_close(chr);
2870
    }
2871
}
2872

    
2873
void qemu_chr_delete(CharDriverState *chr)
2874
{
2875
    QTAILQ_REMOVE(&chardevs, chr, next);
2876
    if (chr->chr_close)
2877
        chr->chr_close(chr);
2878
    g_free(chr->filename);
2879
    g_free(chr->label);
2880
    g_free(chr);
2881
}
2882

    
2883
ChardevInfoList *qmp_query_chardev(Error **errp)
2884
{
2885
    ChardevInfoList *chr_list = NULL;
2886
    CharDriverState *chr;
2887

    
2888
    QTAILQ_FOREACH(chr, &chardevs, next) {
2889
        ChardevInfoList *info = g_malloc0(sizeof(*info));
2890
        info->value = g_malloc0(sizeof(*info->value));
2891
        info->value->label = g_strdup(chr->label);
2892
        info->value->filename = g_strdup(chr->filename);
2893

    
2894
        info->next = chr_list;
2895
        chr_list = info;
2896
    }
2897

    
2898
    return chr_list;
2899
}
2900

    
2901
CharDriverState *qemu_chr_find(const char *name)
2902
{
2903
    CharDriverState *chr;
2904

    
2905
    QTAILQ_FOREACH(chr, &chardevs, next) {
2906
        if (strcmp(chr->label, name) != 0)
2907
            continue;
2908
        return chr;
2909
    }
2910
    return NULL;
2911
}
2912

    
2913
/* Get a character (serial) device interface.  */
2914
CharDriverState *qemu_char_get_next_serial(void)
2915
{
2916
    static int next_serial;
2917

    
2918
    /* FIXME: This function needs to go away: use chardev properties!  */
2919
    return serial_hds[next_serial++];
2920
}
2921