Statistics
| Branch: | Revision:

root / qemu-char.c @ d7234f4d

History | View | Annotate | Download (65.2 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 "net.h"
26
#include "monitor.h"
27
#include "console.h"
28
#include "sysemu.h"
29
#include "qemu-timer.h"
30
#include "qemu-char.h"
31
#include "block.h"
32
#include "hw/usb.h"
33
#include "hw/baum.h"
34
#include "hw/msmouse.h"
35
#include "qemu-objects.h"
36

    
37
#include <unistd.h>
38
#include <fcntl.h>
39
#include <signal.h>
40
#include <time.h>
41
#include <errno.h>
42
#include <sys/time.h>
43
#include <zlib.h>
44

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

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

    
100
#include "qemu_socket.h"
101

    
102
#define READ_BUF_LEN 4096
103

    
104
/***********************************************************/
105
/* character device */
106

    
107
static QTAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
108
    QTAILQ_HEAD_INITIALIZER(chardevs);
109

    
110
static void qemu_chr_event(CharDriverState *s, int event)
111
{
112
    if (!s->chr_event)
113
        return;
114
    s->chr_event(s->handler_opaque, event);
115
}
116

    
117
static void qemu_chr_generic_open_bh(void *opaque)
118
{
119
    CharDriverState *s = opaque;
120
    qemu_chr_event(s, CHR_EVENT_OPENED);
121
    qemu_bh_delete(s->bh);
122
    s->bh = NULL;
123
}
124

    
125
void qemu_chr_generic_open(CharDriverState *s)
126
{
127
    if (s->bh == NULL) {
128
        s->bh = qemu_bh_new(qemu_chr_generic_open_bh, s);
129
        qemu_bh_schedule(s->bh);
130
    }
131
}
132

    
133
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
134
{
135
    return s->chr_write(s, buf, len);
136
}
137

    
138
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
139
{
140
    if (!s->chr_ioctl)
141
        return -ENOTSUP;
142
    return s->chr_ioctl(s, cmd, arg);
143
}
144

    
145
int qemu_chr_can_read(CharDriverState *s)
146
{
147
    if (!s->chr_can_read)
148
        return 0;
149
    return s->chr_can_read(s->handler_opaque);
150
}
151

    
152
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
153
{
154
    s->chr_read(s->handler_opaque, buf, len);
155
}
156

    
157
int qemu_chr_get_msgfd(CharDriverState *s)
158
{
159
    return s->get_msgfd ? s->get_msgfd(s) : -1;
160
}
161

    
162
void qemu_chr_accept_input(CharDriverState *s)
163
{
164
    if (s->chr_accept_input)
165
        s->chr_accept_input(s);
166
}
167

    
168
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
169
{
170
    char buf[READ_BUF_LEN];
171
    va_list ap;
172
    va_start(ap, fmt);
173
    vsnprintf(buf, sizeof(buf), fmt, ap);
174
    qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
175
    va_end(ap);
176
}
177

    
178
void qemu_chr_send_event(CharDriverState *s, int event)
179
{
180
    if (s->chr_send_event)
181
        s->chr_send_event(s, event);
182
}
183

    
184
void qemu_chr_add_handlers(CharDriverState *s,
185
                           IOCanReadHandler *fd_can_read,
186
                           IOReadHandler *fd_read,
187
                           IOEventHandler *fd_event,
188
                           void *opaque)
189
{
190
    s->chr_can_read = fd_can_read;
191
    s->chr_read = fd_read;
192
    s->chr_event = fd_event;
193
    s->handler_opaque = opaque;
194
    if (s->chr_update_read_handler)
195
        s->chr_update_read_handler(s);
196
}
197

    
198
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
199
{
200
    return len;
201
}
202

    
203
static CharDriverState *qemu_chr_open_null(QemuOpts *opts)
204
{
205
    CharDriverState *chr;
206

    
207
    chr = qemu_mallocz(sizeof(CharDriverState));
208
    chr->chr_write = null_chr_write;
209
    return chr;
210
}
211

    
212
/* MUX driver for serial I/O splitting */
213
#define MAX_MUX 4
214
#define MUX_BUFFER_SIZE 32        /* Must be a power of 2.  */
215
#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
216
typedef struct {
217
    IOCanReadHandler *chr_can_read[MAX_MUX];
218
    IOReadHandler *chr_read[MAX_MUX];
219
    IOEventHandler *chr_event[MAX_MUX];
220
    void *ext_opaque[MAX_MUX];
221
    CharDriverState *drv;
222
    int focus;
223
    int mux_cnt;
224
    int term_got_escape;
225
    int max_size;
226
    /* Intermediate input buffer allows to catch escape sequences even if the
227
       currently active device is not accepting any input - but only until it
228
       is full as well. */
229
    unsigned char buffer[MAX_MUX][MUX_BUFFER_SIZE];
230
    int prod[MAX_MUX];
231
    int cons[MAX_MUX];
232
    int timestamps;
233
    int linestart;
234
    int64_t timestamps_start;
235
} MuxDriver;
236

    
237

    
238
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
239
{
240
    MuxDriver *d = chr->opaque;
241
    int ret;
242
    if (!d->timestamps) {
243
        ret = d->drv->chr_write(d->drv, buf, len);
244
    } else {
245
        int i;
246

    
247
        ret = 0;
248
        for (i = 0; i < len; i++) {
249
            if (d->linestart) {
250
                char buf1[64];
251
                int64_t ti;
252
                int secs;
253

    
254
                ti = qemu_get_clock(rt_clock);
255
                if (d->timestamps_start == -1)
256
                    d->timestamps_start = ti;
257
                ti -= d->timestamps_start;
258
                secs = ti / 1000;
259
                snprintf(buf1, sizeof(buf1),
260
                         "[%02d:%02d:%02d.%03d] ",
261
                         secs / 3600,
262
                         (secs / 60) % 60,
263
                         secs % 60,
264
                         (int)(ti % 1000));
265
                d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
266
                d->linestart = 0;
267
            }
268
            ret += d->drv->chr_write(d->drv, buf+i, 1);
269
            if (buf[i] == '\n') {
270
                d->linestart = 1;
271
            }
272
        }
273
    }
274
    return ret;
275
}
276

    
277
static const char * const mux_help[] = {
278
    "% h    print this help\n\r",
279
    "% x    exit emulator\n\r",
280
    "% s    save disk data back to file (if -snapshot)\n\r",
281
    "% t    toggle console timestamps\n\r"
282
    "% b    send break (magic sysrq)\n\r",
283
    "% c    switch between console and monitor\n\r",
284
    "% %  sends %\n\r",
285
    NULL
286
};
287

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

    
295
    if (term_escape_char > 0 && term_escape_char < 26) {
296
        snprintf(cbuf, sizeof(cbuf), "\n\r");
297
        snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
298
    } else {
299
        snprintf(cbuf, sizeof(cbuf),
300
                 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
301
                 term_escape_char);
302
    }
303
    chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
304
    for (i = 0; mux_help[i] != NULL; i++) {
305
        for (j=0; mux_help[i][j] != '\0'; j++) {
306
            if (mux_help[i][j] == '%')
307
                chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
308
            else
309
                chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
310
        }
311
    }
312
}
313

    
314
static void mux_chr_send_event(MuxDriver *d, int mux_nr, int event)
315
{
316
    if (d->chr_event[mux_nr])
317
        d->chr_event[mux_nr](d->ext_opaque[mux_nr], event);
318
}
319

    
320
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
321
{
322
    if (d->term_got_escape) {
323
        d->term_got_escape = 0;
324
        if (ch == term_escape_char)
325
            goto send_char;
326
        switch(ch) {
327
        case '?':
328
        case 'h':
329
            mux_print_help(chr);
330
            break;
331
        case 'x':
332
            {
333
                 const char *term =  "QEMU: Terminated\n\r";
334
                 chr->chr_write(chr,(uint8_t *)term,strlen(term));
335
                 exit(0);
336
                 break;
337
            }
338
        case 's':
339
            {
340
                DriveInfo *dinfo;
341
                QTAILQ_FOREACH(dinfo, &drives, next) {
342
                    bdrv_commit(dinfo->bdrv);
343
                }
344
            }
345
            break;
346
        case 'b':
347
            qemu_chr_event(chr, CHR_EVENT_BREAK);
348
            break;
349
        case 'c':
350
            /* Switch to the next registered device */
351
            mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
352
            d->focus++;
353
            if (d->focus >= d->mux_cnt)
354
                d->focus = 0;
355
            mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
356
            break;
357
        case 't':
358
            d->timestamps = !d->timestamps;
359
            d->timestamps_start = -1;
360
            d->linestart = 0;
361
            break;
362
        }
363
    } else if (ch == term_escape_char) {
364
        d->term_got_escape = 1;
365
    } else {
366
    send_char:
367
        return 1;
368
    }
369
    return 0;
370
}
371

    
372
static void mux_chr_accept_input(CharDriverState *chr)
373
{
374
    MuxDriver *d = chr->opaque;
375
    int m = d->focus;
376

    
377
    while (d->prod[m] != d->cons[m] &&
378
           d->chr_can_read[m] &&
379
           d->chr_can_read[m](d->ext_opaque[m])) {
380
        d->chr_read[m](d->ext_opaque[m],
381
                       &d->buffer[m][d->cons[m]++ & MUX_BUFFER_MASK], 1);
382
    }
383
}
384

    
385
static int mux_chr_can_read(void *opaque)
386
{
387
    CharDriverState *chr = opaque;
388
    MuxDriver *d = chr->opaque;
389
    int m = d->focus;
390

    
391
    if ((d->prod[m] - d->cons[m]) < MUX_BUFFER_SIZE)
392
        return 1;
393
    if (d->chr_can_read[m])
394
        return d->chr_can_read[m](d->ext_opaque[m]);
395
    return 0;
396
}
397

    
398
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
399
{
400
    CharDriverState *chr = opaque;
401
    MuxDriver *d = chr->opaque;
402
    int m = d->focus;
403
    int i;
404

    
405
    mux_chr_accept_input (opaque);
406

    
407
    for(i = 0; i < size; i++)
408
        if (mux_proc_byte(chr, d, buf[i])) {
409
            if (d->prod[m] == d->cons[m] &&
410
                d->chr_can_read[m] &&
411
                d->chr_can_read[m](d->ext_opaque[m]))
412
                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
413
            else
414
                d->buffer[m][d->prod[m]++ & MUX_BUFFER_MASK] = buf[i];
415
        }
416
}
417

    
418
static void mux_chr_event(void *opaque, int event)
419
{
420
    CharDriverState *chr = opaque;
421
    MuxDriver *d = chr->opaque;
422
    int i;
423

    
424
    /* Send the event to all registered listeners */
425
    for (i = 0; i < d->mux_cnt; i++)
426
        mux_chr_send_event(d, i, event);
427
}
428

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

    
433
    if (d->mux_cnt >= MAX_MUX) {
434
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
435
        return;
436
    }
437
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
438
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
439
    d->chr_read[d->mux_cnt] = chr->chr_read;
440
    d->chr_event[d->mux_cnt] = chr->chr_event;
441
    /* Fix up the real driver with mux routines */
442
    if (d->mux_cnt == 0) {
443
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
444
                              mux_chr_event, chr);
445
    }
446
    if (d->focus != -1) {
447
        mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_OUT);
448
    }
449
    d->focus = d->mux_cnt;
450
    d->mux_cnt++;
451
    mux_chr_send_event(d, d->focus, CHR_EVENT_MUX_IN);
452
}
453

    
454
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
455
{
456
    CharDriverState *chr;
457
    MuxDriver *d;
458

    
459
    chr = qemu_mallocz(sizeof(CharDriverState));
460
    d = qemu_mallocz(sizeof(MuxDriver));
461

    
462
    chr->opaque = d;
463
    d->drv = drv;
464
    d->focus = -1;
465
    chr->chr_write = mux_chr_write;
466
    chr->chr_update_read_handler = mux_chr_update_read_handler;
467
    chr->chr_accept_input = mux_chr_accept_input;
468
    return chr;
469
}
470

    
471

    
472
#ifdef _WIN32
473
int send_all(int fd, const void *buf, int len1)
474
{
475
    int ret, len;
476

    
477
    len = len1;
478
    while (len > 0) {
479
        ret = send(fd, buf, len, 0);
480
        if (ret < 0) {
481
            errno = WSAGetLastError();
482
            if (errno != WSAEWOULDBLOCK) {
483
                return -1;
484
            }
485
        } else if (ret == 0) {
486
            break;
487
        } else {
488
            buf += ret;
489
            len -= ret;
490
        }
491
    }
492
    return len1 - len;
493
}
494

    
495
#else
496

    
497
static int unix_write(int fd, const uint8_t *buf, int len1)
498
{
499
    int ret, len;
500

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

    
517
int send_all(int fd, const void *buf, int len1)
518
{
519
    return unix_write(fd, buf, len1);
520
}
521
#endif /* !_WIN32 */
522

    
523
#ifndef _WIN32
524

    
525
typedef struct {
526
    int fd_in, fd_out;
527
    int max_size;
528
} FDCharDriver;
529

    
530
#define STDIO_MAX_CLIENTS 1
531
static int stdio_nb_clients = 0;
532

    
533
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
534
{
535
    FDCharDriver *s = chr->opaque;
536
    return send_all(s->fd_out, buf, len);
537
}
538

    
539
static int fd_chr_read_poll(void *opaque)
540
{
541
    CharDriverState *chr = opaque;
542
    FDCharDriver *s = chr->opaque;
543

    
544
    s->max_size = qemu_chr_can_read(chr);
545
    return s->max_size;
546
}
547

    
548
static void fd_chr_read(void *opaque)
549
{
550
    CharDriverState *chr = opaque;
551
    FDCharDriver *s = chr->opaque;
552
    int size, len;
553
    uint8_t buf[READ_BUF_LEN];
554

    
555
    len = sizeof(buf);
556
    if (len > s->max_size)
557
        len = s->max_size;
558
    if (len == 0)
559
        return;
560
    size = read(s->fd_in, buf, len);
561
    if (size == 0) {
562
        /* FD has been closed. Remove it from the active list.  */
563
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
564
        qemu_chr_event(chr, CHR_EVENT_CLOSED);
565
        return;
566
    }
567
    if (size > 0) {
568
        qemu_chr_read(chr, buf, size);
569
    }
570
}
571

    
572
static void fd_chr_update_read_handler(CharDriverState *chr)
573
{
574
    FDCharDriver *s = chr->opaque;
575

    
576
    if (s->fd_in >= 0) {
577
        if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
578
        } else {
579
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
580
                                 fd_chr_read, NULL, chr);
581
        }
582
    }
583
}
584

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

    
589
    if (s->fd_in >= 0) {
590
        if (display_type == DT_NOGRAPHIC && s->fd_in == 0) {
591
        } else {
592
            qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
593
        }
594
    }
595

    
596
    qemu_free(s);
597
    qemu_chr_event(chr, CHR_EVENT_CLOSED);
598
}
599

    
600
/* open a character device to a unix fd */
601
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
602
{
603
    CharDriverState *chr;
604
    FDCharDriver *s;
605

    
606
    chr = qemu_mallocz(sizeof(CharDriverState));
607
    s = qemu_mallocz(sizeof(FDCharDriver));
608
    s->fd_in = fd_in;
609
    s->fd_out = fd_out;
610
    chr->opaque = s;
611
    chr->chr_write = fd_chr_write;
612
    chr->chr_update_read_handler = fd_chr_update_read_handler;
613
    chr->chr_close = fd_chr_close;
614

    
615
    qemu_chr_generic_open(chr);
616

    
617
    return chr;
618
}
619

    
620
static CharDriverState *qemu_chr_open_file_out(QemuOpts *opts)
621
{
622
    int fd_out;
623

    
624
    TFR(fd_out = qemu_open(qemu_opt_get(opts, "path"),
625
                      O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
626
    if (fd_out < 0)
627
        return NULL;
628
    return qemu_chr_open_fd(-1, fd_out);
629
}
630

    
631
static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)
632
{
633
    int fd_in, fd_out;
634
    char filename_in[256], filename_out[256];
635
    const char *filename = qemu_opt_get(opts, "path");
636

    
637
    if (filename == NULL) {
638
        fprintf(stderr, "chardev: pipe: no filename given\n");
639
        return NULL;
640
    }
641

    
642
    snprintf(filename_in, 256, "%s.in", filename);
643
    snprintf(filename_out, 256, "%s.out", filename);
644
    TFR(fd_in = qemu_open(filename_in, O_RDWR | O_BINARY));
645
    TFR(fd_out = qemu_open(filename_out, O_RDWR | O_BINARY));
646
    if (fd_in < 0 || fd_out < 0) {
647
        if (fd_in >= 0)
648
            close(fd_in);
649
        if (fd_out >= 0)
650
            close(fd_out);
651
        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
652
        if (fd_in < 0)
653
            return NULL;
654
    }
655
    return qemu_chr_open_fd(fd_in, fd_out);
656
}
657

    
658

    
659
/* for STDIO, we handle the case where several clients use it
660
   (nographic mode) */
661

    
662
#define TERM_FIFO_MAX_SIZE 1
663

    
664
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
665
static int term_fifo_size;
666

    
667
static int stdio_read_poll(void *opaque)
668
{
669
    CharDriverState *chr = opaque;
670

    
671
    /* try to flush the queue if needed */
672
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
673
        qemu_chr_read(chr, term_fifo, 1);
674
        term_fifo_size = 0;
675
    }
676
    /* see if we can absorb more chars */
677
    if (term_fifo_size == 0)
678
        return 1;
679
    else
680
        return 0;
681
}
682

    
683
static void stdio_read(void *opaque)
684
{
685
    int size;
686
    uint8_t buf[1];
687
    CharDriverState *chr = opaque;
688

    
689
    size = read(0, buf, 1);
690
    if (size == 0) {
691
        /* stdin has been closed. Remove it from the active list.  */
692
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
693
        qemu_chr_event(chr, CHR_EVENT_CLOSED);
694
        return;
695
    }
696
    if (size > 0) {
697
        if (qemu_chr_can_read(chr) > 0) {
698
            qemu_chr_read(chr, buf, 1);
699
        } else if (term_fifo_size == 0) {
700
            term_fifo[term_fifo_size++] = buf[0];
701
        }
702
    }
703
}
704

    
705
/* init terminal so that we can grab keys */
706
static struct termios oldtty;
707
static int old_fd0_flags;
708
static int term_atexit_done;
709

    
710
static void term_exit(void)
711
{
712
    tcsetattr (0, TCSANOW, &oldtty);
713
    fcntl(0, F_SETFL, old_fd0_flags);
714
}
715

    
716
static void term_exit_notifier(Notifier *notifier)
717
{
718
    term_exit();
719
}
720

    
721
static void term_init(QemuOpts *opts)
722
{
723
    struct termios tty;
724
    static Notifier exit_notifier = { .notify = term_exit_notifier };
725

    
726
    tcgetattr (0, &tty);
727
    oldtty = tty;
728
    old_fd0_flags = fcntl(0, F_GETFL);
729

    
730
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
731
                          |INLCR|IGNCR|ICRNL|IXON);
732
    tty.c_oflag |= OPOST;
733
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
734
    /* if graphical mode, we allow Ctrl-C handling */
735
    if (!qemu_opt_get_bool(opts, "signal", display_type != DT_NOGRAPHIC))
736
        tty.c_lflag &= ~ISIG;
737
    tty.c_cflag &= ~(CSIZE|PARENB);
738
    tty.c_cflag |= CS8;
739
    tty.c_cc[VMIN] = 1;
740
    tty.c_cc[VTIME] = 0;
741

    
742
    tcsetattr (0, TCSANOW, &tty);
743

    
744
    if (!term_atexit_done++) {
745
        exit_notifier_add(&exit_notifier);
746
    }
747

    
748
    fcntl(0, F_SETFL, O_NONBLOCK);
749
}
750

    
751
static void qemu_chr_close_stdio(struct CharDriverState *chr)
752
{
753
    term_exit();
754
    stdio_nb_clients--;
755
    qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
756
    fd_chr_close(chr);
757
}
758

    
759
static CharDriverState *qemu_chr_open_stdio(QemuOpts *opts)
760
{
761
    CharDriverState *chr;
762

    
763
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
764
        return NULL;
765
    chr = qemu_chr_open_fd(0, 1);
766
    chr->chr_close = qemu_chr_close_stdio;
767
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
768
    stdio_nb_clients++;
769
    term_init(opts);
770

    
771
    return chr;
772
}
773

    
774
#ifdef __sun__
775
/* Once Solaris has openpty(), this is going to be removed. */
776
static int openpty(int *amaster, int *aslave, char *name,
777
                   struct termios *termp, struct winsize *winp)
778
{
779
        const char *slave;
780
        int mfd = -1, sfd = -1;
781

    
782
        *amaster = *aslave = -1;
783

    
784
        mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
785
        if (mfd < 0)
786
                goto err;
787

    
788
        if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
789
                goto err;
790

    
791
        if ((slave = ptsname(mfd)) == NULL)
792
                goto err;
793

    
794
        if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
795
                goto err;
796

    
797
        if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
798
            (termp != NULL && tcgetattr(sfd, termp) < 0))
799
                goto err;
800

    
801
        if (amaster)
802
                *amaster = mfd;
803
        if (aslave)
804
                *aslave = sfd;
805
        if (winp)
806
                ioctl(sfd, TIOCSWINSZ, winp);
807

    
808
        return 0;
809

    
810
err:
811
        if (sfd != -1)
812
                close(sfd);
813
        close(mfd);
814
        return -1;
815
}
816

    
817
static void cfmakeraw (struct termios *termios_p)
818
{
819
        termios_p->c_iflag &=
820
                ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
821
        termios_p->c_oflag &= ~OPOST;
822
        termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
823
        termios_p->c_cflag &= ~(CSIZE|PARENB);
824
        termios_p->c_cflag |= CS8;
825

    
826
        termios_p->c_cc[VMIN] = 0;
827
        termios_p->c_cc[VTIME] = 0;
828
}
829
#endif
830

    
831
#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
832
    || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
833
    || defined(__GLIBC__)
834

    
835
typedef struct {
836
    int fd;
837
    int connected;
838
    int polling;
839
    int read_bytes;
840
    QEMUTimer *timer;
841
} PtyCharDriver;
842

    
843
static void pty_chr_update_read_handler(CharDriverState *chr);
844
static void pty_chr_state(CharDriverState *chr, int connected);
845

    
846
static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
847
{
848
    PtyCharDriver *s = chr->opaque;
849

    
850
    if (!s->connected) {
851
        /* guest sends data, check for (re-)connect */
852
        pty_chr_update_read_handler(chr);
853
        return 0;
854
    }
855
    return send_all(s->fd, buf, len);
856
}
857

    
858
static int pty_chr_read_poll(void *opaque)
859
{
860
    CharDriverState *chr = opaque;
861
    PtyCharDriver *s = chr->opaque;
862

    
863
    s->read_bytes = qemu_chr_can_read(chr);
864
    return s->read_bytes;
865
}
866

    
867
static void pty_chr_read(void *opaque)
868
{
869
    CharDriverState *chr = opaque;
870
    PtyCharDriver *s = chr->opaque;
871
    int size, len;
872
    uint8_t buf[READ_BUF_LEN];
873

    
874
    len = sizeof(buf);
875
    if (len > s->read_bytes)
876
        len = s->read_bytes;
877
    if (len == 0)
878
        return;
879
    size = read(s->fd, buf, len);
880
    if ((size == -1 && errno == EIO) ||
881
        (size == 0)) {
882
        pty_chr_state(chr, 0);
883
        return;
884
    }
885
    if (size > 0) {
886
        pty_chr_state(chr, 1);
887
        qemu_chr_read(chr, buf, size);
888
    }
889
}
890

    
891
static void pty_chr_update_read_handler(CharDriverState *chr)
892
{
893
    PtyCharDriver *s = chr->opaque;
894

    
895
    qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
896
                         pty_chr_read, NULL, chr);
897
    s->polling = 1;
898
    /*
899
     * Short timeout here: just need wait long enougth that qemu makes
900
     * it through the poll loop once.  When reconnected we want a
901
     * short timeout so we notice it almost instantly.  Otherwise
902
     * read() gives us -EIO instantly, making pty_chr_state() reset the
903
     * timeout to the normal (much longer) poll interval before the
904
     * timer triggers.
905
     */
906
    qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
907
}
908

    
909
static void pty_chr_state(CharDriverState *chr, int connected)
910
{
911
    PtyCharDriver *s = chr->opaque;
912

    
913
    if (!connected) {
914
        qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
915
        s->connected = 0;
916
        s->polling = 0;
917
        /* (re-)connect poll interval for idle guests: once per second.
918
         * We check more frequently in case the guests sends data to
919
         * the virtual device linked to our pty. */
920
        qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
921
    } else {
922
        if (!s->connected)
923
            qemu_chr_generic_open(chr);
924
        s->connected = 1;
925
    }
926
}
927

    
928
static void pty_chr_timer(void *opaque)
929
{
930
    struct CharDriverState *chr = opaque;
931
    PtyCharDriver *s = chr->opaque;
932

    
933
    if (s->connected)
934
        return;
935
    if (s->polling) {
936
        /* If we arrive here without polling being cleared due
937
         * read returning -EIO, then we are (re-)connected */
938
        pty_chr_state(chr, 1);
939
        return;
940
    }
941

    
942
    /* Next poll ... */
943
    pty_chr_update_read_handler(chr);
944
}
945

    
946
static void pty_chr_close(struct CharDriverState *chr)
947
{
948
    PtyCharDriver *s = chr->opaque;
949

    
950
    qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
951
    close(s->fd);
952
    qemu_del_timer(s->timer);
953
    qemu_free_timer(s->timer);
954
    qemu_free(s);
955
    qemu_chr_event(chr, CHR_EVENT_CLOSED);
956
}
957

    
958
static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)
959
{
960
    CharDriverState *chr;
961
    PtyCharDriver *s;
962
    struct termios tty;
963
    int slave_fd, len;
964
#if defined(__OpenBSD__) || defined(__DragonFly__)
965
    char pty_name[PATH_MAX];
966
#define q_ptsname(x) pty_name
967
#else
968
    char *pty_name = NULL;
969
#define q_ptsname(x) ptsname(x)
970
#endif
971

    
972
    chr = qemu_mallocz(sizeof(CharDriverState));
973
    s = qemu_mallocz(sizeof(PtyCharDriver));
974

    
975
    if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
976
        return NULL;
977
    }
978

    
979
    /* Set raw attributes on the pty. */
980
    tcgetattr(slave_fd, &tty);
981
    cfmakeraw(&tty);
982
    tcsetattr(slave_fd, TCSAFLUSH, &tty);
983
    close(slave_fd);
984

    
985
    len = strlen(q_ptsname(s->fd)) + 5;
986
    chr->filename = qemu_malloc(len);
987
    snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
988
    qemu_opt_set(opts, "path", q_ptsname(s->fd));
989
    fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
990

    
991
    chr->opaque = s;
992
    chr->chr_write = pty_chr_write;
993
    chr->chr_update_read_handler = pty_chr_update_read_handler;
994
    chr->chr_close = pty_chr_close;
995

    
996
    s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
997

    
998
    return chr;
999
}
1000

    
1001
static void tty_serial_init(int fd, int speed,
1002
                            int parity, int data_bits, int stop_bits)
1003
{
1004
    struct termios tty;
1005
    speed_t spd;
1006

    
1007
#if 0
1008
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1009
           speed, parity, data_bits, stop_bits);
1010
#endif
1011
    tcgetattr (fd, &tty);
1012
    oldtty = tty;
1013

    
1014
#define check_speed(val) if (speed <= val) { spd = B##val; break; }
1015
    speed = speed * 10 / 11;
1016
    do {
1017
        check_speed(50);
1018
        check_speed(75);
1019
        check_speed(110);
1020
        check_speed(134);
1021
        check_speed(150);
1022
        check_speed(200);
1023
        check_speed(300);
1024
        check_speed(600);
1025
        check_speed(1200);
1026
        check_speed(1800);
1027
        check_speed(2400);
1028
        check_speed(4800);
1029
        check_speed(9600);
1030
        check_speed(19200);
1031
        check_speed(38400);
1032
        /* Non-Posix values follow. They may be unsupported on some systems. */
1033
        check_speed(57600);
1034
        check_speed(115200);
1035
#ifdef B230400
1036
        check_speed(230400);
1037
#endif
1038
#ifdef B460800
1039
        check_speed(460800);
1040
#endif
1041
#ifdef B500000
1042
        check_speed(500000);
1043
#endif
1044
#ifdef B576000
1045
        check_speed(576000);
1046
#endif
1047
#ifdef B921600
1048
        check_speed(921600);
1049
#endif
1050
#ifdef B1000000
1051
        check_speed(1000000);
1052
#endif
1053
#ifdef B1152000
1054
        check_speed(1152000);
1055
#endif
1056
#ifdef B1500000
1057
        check_speed(1500000);
1058
#endif
1059
#ifdef B2000000
1060
        check_speed(2000000);
1061
#endif
1062
#ifdef B2500000
1063
        check_speed(2500000);
1064
#endif
1065
#ifdef B3000000
1066
        check_speed(3000000);
1067
#endif
1068
#ifdef B3500000
1069
        check_speed(3500000);
1070
#endif
1071
#ifdef B4000000
1072
        check_speed(4000000);
1073
#endif
1074
        spd = B115200;
1075
    } while (0);
1076

    
1077
    cfsetispeed(&tty, spd);
1078
    cfsetospeed(&tty, spd);
1079

    
1080
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1081
                          |INLCR|IGNCR|ICRNL|IXON);
1082
    tty.c_oflag |= OPOST;
1083
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1084
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1085
    switch(data_bits) {
1086
    default:
1087
    case 8:
1088
        tty.c_cflag |= CS8;
1089
        break;
1090
    case 7:
1091
        tty.c_cflag |= CS7;
1092
        break;
1093
    case 6:
1094
        tty.c_cflag |= CS6;
1095
        break;
1096
    case 5:
1097
        tty.c_cflag |= CS5;
1098
        break;
1099
    }
1100
    switch(parity) {
1101
    default:
1102
    case 'N':
1103
        break;
1104
    case 'E':
1105
        tty.c_cflag |= PARENB;
1106
        break;
1107
    case 'O':
1108
        tty.c_cflag |= PARENB | PARODD;
1109
        break;
1110
    }
1111
    if (stop_bits == 2)
1112
        tty.c_cflag |= CSTOPB;
1113

    
1114
    tcsetattr (fd, TCSANOW, &tty);
1115
}
1116

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

    
1121
    switch(cmd) {
1122
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1123
        {
1124
            QEMUSerialSetParams *ssp = arg;
1125
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1126
                            ssp->data_bits, ssp->stop_bits);
1127
        }
1128
        break;
1129
    case CHR_IOCTL_SERIAL_SET_BREAK:
1130
        {
1131
            int enable = *(int *)arg;
1132
            if (enable)
1133
                tcsendbreak(s->fd_in, 1);
1134
        }
1135
        break;
1136
    case CHR_IOCTL_SERIAL_GET_TIOCM:
1137
        {
1138
            int sarg = 0;
1139
            int *targ = (int *)arg;
1140
            ioctl(s->fd_in, TIOCMGET, &sarg);
1141
            *targ = 0;
1142
            if (sarg & TIOCM_CTS)
1143
                *targ |= CHR_TIOCM_CTS;
1144
            if (sarg & TIOCM_CAR)
1145
                *targ |= CHR_TIOCM_CAR;
1146
            if (sarg & TIOCM_DSR)
1147
                *targ |= CHR_TIOCM_DSR;
1148
            if (sarg & TIOCM_RI)
1149
                *targ |= CHR_TIOCM_RI;
1150
            if (sarg & TIOCM_DTR)
1151
                *targ |= CHR_TIOCM_DTR;
1152
            if (sarg & TIOCM_RTS)
1153
                *targ |= CHR_TIOCM_RTS;
1154
        }
1155
        break;
1156
    case CHR_IOCTL_SERIAL_SET_TIOCM:
1157
        {
1158
            int sarg = *(int *)arg;
1159
            int targ = 0;
1160
            ioctl(s->fd_in, TIOCMGET, &targ);
1161
            targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1162
                     | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1163
            if (sarg & CHR_TIOCM_CTS)
1164
                targ |= TIOCM_CTS;
1165
            if (sarg & CHR_TIOCM_CAR)
1166
                targ |= TIOCM_CAR;
1167
            if (sarg & CHR_TIOCM_DSR)
1168
                targ |= TIOCM_DSR;
1169
            if (sarg & CHR_TIOCM_RI)
1170
                targ |= TIOCM_RI;
1171
            if (sarg & CHR_TIOCM_DTR)
1172
                targ |= TIOCM_DTR;
1173
            if (sarg & CHR_TIOCM_RTS)
1174
                targ |= TIOCM_RTS;
1175
            ioctl(s->fd_in, TIOCMSET, &targ);
1176
        }
1177
        break;
1178
    default:
1179
        return -ENOTSUP;
1180
    }
1181
    return 0;
1182
}
1183

    
1184
static void tty_exit(void)
1185
{
1186
    tcsetattr(0, TCSANOW, &oldtty);
1187
}
1188

    
1189
static void qemu_chr_close_tty(CharDriverState *chr)
1190
{
1191
    FDCharDriver *s = chr->opaque;
1192
    int fd = -1;
1193

    
1194
    if (s) {
1195
        fd = s->fd_in;
1196
    }
1197

    
1198
    fd_chr_close(chr);
1199

    
1200
    if (fd >= 0) {
1201
        close(fd);
1202
    }
1203
}
1204

    
1205
static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)
1206
{
1207
    const char *filename = qemu_opt_get(opts, "path");
1208
    CharDriverState *chr;
1209
    int fd;
1210

    
1211
    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
1212
    if (fd < 0) {
1213
        return NULL;
1214
    }
1215
    tty_serial_init(fd, 115200, 'N', 8, 1);
1216
    chr = qemu_chr_open_fd(fd, fd);
1217
    if (!chr) {
1218
        close(fd);
1219
        return NULL;
1220
    }
1221
    chr->chr_ioctl = tty_serial_ioctl;
1222
    chr->chr_close = qemu_chr_close_tty;
1223
    if (!term_atexit_done++)
1224
        atexit(tty_exit);
1225
    return chr;
1226
}
1227
#else  /* ! __linux__ && ! __sun__ */
1228
static CharDriverState *qemu_chr_open_pty(void)
1229
{
1230
    return NULL;
1231
}
1232
#endif /* __linux__ || __sun__ */
1233

    
1234
#if defined(__linux__)
1235
typedef struct {
1236
    int fd;
1237
    int mode;
1238
} ParallelCharDriver;
1239

    
1240
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1241
{
1242
    if (s->mode != mode) {
1243
        int m = mode;
1244
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
1245
            return 0;
1246
        s->mode = mode;
1247
    }
1248
    return 1;
1249
}
1250

    
1251
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1252
{
1253
    ParallelCharDriver *drv = chr->opaque;
1254
    int fd = drv->fd;
1255
    uint8_t b;
1256

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

    
1332
static void pp_close(CharDriverState *chr)
1333
{
1334
    ParallelCharDriver *drv = chr->opaque;
1335
    int fd = drv->fd;
1336

    
1337
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1338
    ioctl(fd, PPRELEASE);
1339
    close(fd);
1340
    qemu_free(drv);
1341
    qemu_chr_event(chr, CHR_EVENT_CLOSED);
1342
}
1343

    
1344
static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1345
{
1346
    const char *filename = qemu_opt_get(opts, "path");
1347
    CharDriverState *chr;
1348
    ParallelCharDriver *drv;
1349
    int fd;
1350

    
1351
    TFR(fd = open(filename, O_RDWR));
1352
    if (fd < 0)
1353
        return NULL;
1354

    
1355
    if (ioctl(fd, PPCLAIM) < 0) {
1356
        close(fd);
1357
        return NULL;
1358
    }
1359

    
1360
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
1361
    drv->fd = fd;
1362
    drv->mode = IEEE1284_MODE_COMPAT;
1363

    
1364
    chr = qemu_mallocz(sizeof(CharDriverState));
1365
    chr->chr_write = null_chr_write;
1366
    chr->chr_ioctl = pp_ioctl;
1367
    chr->chr_close = pp_close;
1368
    chr->opaque = drv;
1369

    
1370
    qemu_chr_generic_open(chr);
1371

    
1372
    return chr;
1373
}
1374
#endif /* __linux__ */
1375

    
1376
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1377
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1378
{
1379
    int fd = (int)chr->opaque;
1380
    uint8_t b;
1381

    
1382
    switch(cmd) {
1383
    case CHR_IOCTL_PP_READ_DATA:
1384
        if (ioctl(fd, PPIGDATA, &b) < 0)
1385
            return -ENOTSUP;
1386
        *(uint8_t *)arg = b;
1387
        break;
1388
    case CHR_IOCTL_PP_WRITE_DATA:
1389
        b = *(uint8_t *)arg;
1390
        if (ioctl(fd, PPISDATA, &b) < 0)
1391
            return -ENOTSUP;
1392
        break;
1393
    case CHR_IOCTL_PP_READ_CONTROL:
1394
        if (ioctl(fd, PPIGCTRL, &b) < 0)
1395
            return -ENOTSUP;
1396
        *(uint8_t *)arg = b;
1397
        break;
1398
    case CHR_IOCTL_PP_WRITE_CONTROL:
1399
        b = *(uint8_t *)arg;
1400
        if (ioctl(fd, PPISCTRL, &b) < 0)
1401
            return -ENOTSUP;
1402
        break;
1403
    case CHR_IOCTL_PP_READ_STATUS:
1404
        if (ioctl(fd, PPIGSTATUS, &b) < 0)
1405
            return -ENOTSUP;
1406
        *(uint8_t *)arg = b;
1407
        break;
1408
    default:
1409
        return -ENOTSUP;
1410
    }
1411
    return 0;
1412
}
1413

    
1414
static CharDriverState *qemu_chr_open_pp(QemuOpts *opts)
1415
{
1416
    const char *filename = qemu_opt_get(opts, "path");
1417
    CharDriverState *chr;
1418
    int fd;
1419

    
1420
    fd = open(filename, O_RDWR);
1421
    if (fd < 0)
1422
        return NULL;
1423

    
1424
    chr = qemu_mallocz(sizeof(CharDriverState));
1425
    chr->opaque = (void *)fd;
1426
    chr->chr_write = null_chr_write;
1427
    chr->chr_ioctl = pp_ioctl;
1428
    return chr;
1429
}
1430
#endif
1431

    
1432
#else /* _WIN32 */
1433

    
1434
typedef struct {
1435
    int max_size;
1436
    HANDLE hcom, hrecv, hsend;
1437
    OVERLAPPED orecv, osend;
1438
    BOOL fpipe;
1439
    DWORD len;
1440
} WinCharState;
1441

    
1442
#define NSENDBUF 2048
1443
#define NRECVBUF 2048
1444
#define MAXCONNECT 1
1445
#define NTIMEOUT 5000
1446

    
1447
static int win_chr_poll(void *opaque);
1448
static int win_chr_pipe_poll(void *opaque);
1449

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

    
1454
    if (s->hsend) {
1455
        CloseHandle(s->hsend);
1456
        s->hsend = NULL;
1457
    }
1458
    if (s->hrecv) {
1459
        CloseHandle(s->hrecv);
1460
        s->hrecv = NULL;
1461
    }
1462
    if (s->hcom) {
1463
        CloseHandle(s->hcom);
1464
        s->hcom = NULL;
1465
    }
1466
    if (s->fpipe)
1467
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
1468
    else
1469
        qemu_del_polling_cb(win_chr_poll, chr);
1470

    
1471
    qemu_chr_event(chr, CHR_EVENT_CLOSED);
1472
}
1473

    
1474
static int win_chr_init(CharDriverState *chr, const char *filename)
1475
{
1476
    WinCharState *s = chr->opaque;
1477
    COMMCONFIG comcfg;
1478
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1479
    COMSTAT comstat;
1480
    DWORD size;
1481
    DWORD err;
1482

    
1483
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1484
    if (!s->hsend) {
1485
        fprintf(stderr, "Failed CreateEvent\n");
1486
        goto fail;
1487
    }
1488
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1489
    if (!s->hrecv) {
1490
        fprintf(stderr, "Failed CreateEvent\n");
1491
        goto fail;
1492
    }
1493

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

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

    
1507
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1508
    size = sizeof(COMMCONFIG);
1509
    GetDefaultCommConfig(filename, &comcfg, &size);
1510
    comcfg.dcb.DCBlength = sizeof(DCB);
1511
    CommConfigDialog(filename, NULL, &comcfg);
1512

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

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

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

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

    
1536
 fail:
1537
    win_chr_close(chr);
1538
    return -1;
1539
}
1540

    
1541
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1542
{
1543
    WinCharState *s = chr->opaque;
1544
    DWORD len, ret, size, err;
1545

    
1546
    len = len1;
1547
    ZeroMemory(&s->osend, sizeof(s->osend));
1548
    s->osend.hEvent = s->hsend;
1549
    while (len > 0) {
1550
        if (s->hsend)
1551
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1552
        else
1553
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
1554
        if (!ret) {
1555
            err = GetLastError();
1556
            if (err == ERROR_IO_PENDING) {
1557
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1558
                if (ret) {
1559
                    buf += size;
1560
                    len -= size;
1561
                } else {
1562
                    break;
1563
                }
1564
            } else {
1565
                break;
1566
            }
1567
        } else {
1568
            buf += size;
1569
            len -= size;
1570
        }
1571
    }
1572
    return len1 - len;
1573
}
1574

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

    
1579
    s->max_size = qemu_chr_can_read(chr);
1580
    return s->max_size;
1581
}
1582

    
1583
static void win_chr_readfile(CharDriverState *chr)
1584
{
1585
    WinCharState *s = chr->opaque;
1586
    int ret, err;
1587
    uint8_t buf[READ_BUF_LEN];
1588
    DWORD size;
1589

    
1590
    ZeroMemory(&s->orecv, sizeof(s->orecv));
1591
    s->orecv.hEvent = s->hrecv;
1592
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1593
    if (!ret) {
1594
        err = GetLastError();
1595
        if (err == ERROR_IO_PENDING) {
1596
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1597
        }
1598
    }
1599

    
1600
    if (size > 0) {
1601
        qemu_chr_read(chr, buf, size);
1602
    }
1603
}
1604

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

    
1609
    if (s->len > s->max_size)
1610
        s->len = s->max_size;
1611
    if (s->len == 0)
1612
        return;
1613

    
1614
    win_chr_readfile(chr);
1615
}
1616

    
1617
static int win_chr_poll(void *opaque)
1618
{
1619
    CharDriverState *chr = opaque;
1620
    WinCharState *s = chr->opaque;
1621
    COMSTAT status;
1622
    DWORD comerr;
1623

    
1624
    ClearCommError(s->hcom, &comerr, &status);
1625
    if (status.cbInQue > 0) {
1626
        s->len = status.cbInQue;
1627
        win_chr_read_poll(chr);
1628
        win_chr_read(chr);
1629
        return 1;
1630
    }
1631
    return 0;
1632
}
1633

    
1634
static CharDriverState *qemu_chr_open_win(QemuOpts *opts)
1635
{
1636
    const char *filename = qemu_opt_get(opts, "path");
1637
    CharDriverState *chr;
1638
    WinCharState *s;
1639

    
1640
    chr = qemu_mallocz(sizeof(CharDriverState));
1641
    s = qemu_mallocz(sizeof(WinCharState));
1642
    chr->opaque = s;
1643
    chr->chr_write = win_chr_write;
1644
    chr->chr_close = win_chr_close;
1645

    
1646
    if (win_chr_init(chr, filename) < 0) {
1647
        free(s);
1648
        free(chr);
1649
        return NULL;
1650
    }
1651
    qemu_chr_generic_open(chr);
1652
    return chr;
1653
}
1654

    
1655
static int win_chr_pipe_poll(void *opaque)
1656
{
1657
    CharDriverState *chr = opaque;
1658
    WinCharState *s = chr->opaque;
1659
    DWORD size;
1660

    
1661
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1662
    if (size > 0) {
1663
        s->len = size;
1664
        win_chr_read_poll(chr);
1665
        win_chr_read(chr);
1666
        return 1;
1667
    }
1668
    return 0;
1669
}
1670

    
1671
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1672
{
1673
    WinCharState *s = chr->opaque;
1674
    OVERLAPPED ov;
1675
    int ret;
1676
    DWORD size;
1677
    char openname[256];
1678

    
1679
    s->fpipe = TRUE;
1680

    
1681
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1682
    if (!s->hsend) {
1683
        fprintf(stderr, "Failed CreateEvent\n");
1684
        goto fail;
1685
    }
1686
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1687
    if (!s->hrecv) {
1688
        fprintf(stderr, "Failed CreateEvent\n");
1689
        goto fail;
1690
    }
1691

    
1692
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1693
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1694
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1695
                              PIPE_WAIT,
1696
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1697
    if (s->hcom == INVALID_HANDLE_VALUE) {
1698
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1699
        s->hcom = NULL;
1700
        goto fail;
1701
    }
1702

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

    
1711
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1712
    if (!ret) {
1713
        fprintf(stderr, "Failed GetOverlappedResult\n");
1714
        if (ov.hEvent) {
1715
            CloseHandle(ov.hEvent);
1716
            ov.hEvent = NULL;
1717
        }
1718
        goto fail;
1719
    }
1720

    
1721
    if (ov.hEvent) {
1722
        CloseHandle(ov.hEvent);
1723
        ov.hEvent = NULL;
1724
    }
1725
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
1726
    return 0;
1727

    
1728
 fail:
1729
    win_chr_close(chr);
1730
    return -1;
1731
}
1732

    
1733

    
1734
static CharDriverState *qemu_chr_open_win_pipe(QemuOpts *opts)
1735
{
1736
    const char *filename = qemu_opt_get(opts, "path");
1737
    CharDriverState *chr;
1738
    WinCharState *s;
1739

    
1740
    chr = qemu_mallocz(sizeof(CharDriverState));
1741
    s = qemu_mallocz(sizeof(WinCharState));
1742
    chr->opaque = s;
1743
    chr->chr_write = win_chr_write;
1744
    chr->chr_close = win_chr_close;
1745

    
1746
    if (win_chr_pipe_init(chr, filename) < 0) {
1747
        free(s);
1748
        free(chr);
1749
        return NULL;
1750
    }
1751
    qemu_chr_generic_open(chr);
1752
    return chr;
1753
}
1754

    
1755
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1756
{
1757
    CharDriverState *chr;
1758
    WinCharState *s;
1759

    
1760
    chr = qemu_mallocz(sizeof(CharDriverState));
1761
    s = qemu_mallocz(sizeof(WinCharState));
1762
    s->hcom = fd_out;
1763
    chr->opaque = s;
1764
    chr->chr_write = win_chr_write;
1765
    qemu_chr_generic_open(chr);
1766
    return chr;
1767
}
1768

    
1769
static CharDriverState *qemu_chr_open_win_con(QemuOpts *opts)
1770
{
1771
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1772
}
1773

    
1774
static CharDriverState *qemu_chr_open_win_file_out(QemuOpts *opts)
1775
{
1776
    const char *file_out = qemu_opt_get(opts, "path");
1777
    HANDLE fd_out;
1778

    
1779
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1780
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1781
    if (fd_out == INVALID_HANDLE_VALUE)
1782
        return NULL;
1783

    
1784
    return qemu_chr_open_win_file(fd_out);
1785
}
1786
#endif /* !_WIN32 */
1787

    
1788
/***********************************************************/
1789
/* UDP Net console */
1790

    
1791
typedef struct {
1792
    int fd;
1793
    uint8_t buf[READ_BUF_LEN];
1794
    int bufcnt;
1795
    int bufptr;
1796
    int max_size;
1797
} NetCharDriver;
1798

    
1799
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1800
{
1801
    NetCharDriver *s = chr->opaque;
1802

    
1803
    return send(s->fd, (const void *)buf, len, 0);
1804
}
1805

    
1806
static int udp_chr_read_poll(void *opaque)
1807
{
1808
    CharDriverState *chr = opaque;
1809
    NetCharDriver *s = chr->opaque;
1810

    
1811
    s->max_size = qemu_chr_can_read(chr);
1812

    
1813
    /* If there were any stray characters in the queue process them
1814
     * first
1815
     */
1816
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1817
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1818
        s->bufptr++;
1819
        s->max_size = qemu_chr_can_read(chr);
1820
    }
1821
    return s->max_size;
1822
}
1823

    
1824
static void udp_chr_read(void *opaque)
1825
{
1826
    CharDriverState *chr = opaque;
1827
    NetCharDriver *s = chr->opaque;
1828

    
1829
    if (s->max_size == 0)
1830
        return;
1831
    s->bufcnt = recv(s->fd, (void *)s->buf, sizeof(s->buf), 0);
1832
    s->bufptr = s->bufcnt;
1833
    if (s->bufcnt <= 0)
1834
        return;
1835

    
1836
    s->bufptr = 0;
1837
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1838
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1839
        s->bufptr++;
1840
        s->max_size = qemu_chr_can_read(chr);
1841
    }
1842
}
1843

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

    
1848
    if (s->fd >= 0) {
1849
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
1850
                             udp_chr_read, NULL, chr);
1851
    }
1852
}
1853

    
1854
static void udp_chr_close(CharDriverState *chr)
1855
{
1856
    NetCharDriver *s = chr->opaque;
1857
    if (s->fd >= 0) {
1858
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1859
        closesocket(s->fd);
1860
    }
1861
    qemu_free(s);
1862
    qemu_chr_event(chr, CHR_EVENT_CLOSED);
1863
}
1864

    
1865
static CharDriverState *qemu_chr_open_udp(QemuOpts *opts)
1866
{
1867
    CharDriverState *chr = NULL;
1868
    NetCharDriver *s = NULL;
1869
    int fd = -1;
1870

    
1871
    chr = qemu_mallocz(sizeof(CharDriverState));
1872
    s = qemu_mallocz(sizeof(NetCharDriver));
1873

    
1874
    fd = inet_dgram_opts(opts);
1875
    if (fd < 0) {
1876
        fprintf(stderr, "inet_dgram_opts failed\n");
1877
        goto return_err;
1878
    }
1879

    
1880
    s->fd = fd;
1881
    s->bufcnt = 0;
1882
    s->bufptr = 0;
1883
    chr->opaque = s;
1884
    chr->chr_write = udp_chr_write;
1885
    chr->chr_update_read_handler = udp_chr_update_read_handler;
1886
    chr->chr_close = udp_chr_close;
1887
    return chr;
1888

    
1889
return_err:
1890
    if (chr)
1891
        free(chr);
1892
    if (s)
1893
        free(s);
1894
    if (fd >= 0)
1895
        closesocket(fd);
1896
    return NULL;
1897
}
1898

    
1899
/***********************************************************/
1900
/* TCP Net console */
1901

    
1902
typedef struct {
1903
    int fd, listen_fd;
1904
    int connected;
1905
    int max_size;
1906
    int do_telnetopt;
1907
    int do_nodelay;
1908
    int is_unix;
1909
    int msgfd;
1910
} TCPCharDriver;
1911

    
1912
static void tcp_chr_accept(void *opaque);
1913

    
1914
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1915
{
1916
    TCPCharDriver *s = chr->opaque;
1917
    if (s->connected) {
1918
        return send_all(s->fd, buf, len);
1919
    } else {
1920
        /* XXX: indicate an error ? */
1921
        return len;
1922
    }
1923
}
1924

    
1925
static int tcp_chr_read_poll(void *opaque)
1926
{
1927
    CharDriverState *chr = opaque;
1928
    TCPCharDriver *s = chr->opaque;
1929
    if (!s->connected)
1930
        return 0;
1931
    s->max_size = qemu_chr_can_read(chr);
1932
    return s->max_size;
1933
}
1934

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

    
1950
    int i;
1951
    int j = 0;
1952

    
1953
    for (i = 0; i < *size; i++) {
1954
        if (s->do_telnetopt > 1) {
1955
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
1956
                /* Double IAC means send an IAC */
1957
                if (j != i)
1958
                    buf[j] = buf[i];
1959
                j++;
1960
                s->do_telnetopt = 1;
1961
            } else {
1962
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
1963
                    /* Handle IAC break commands by sending a serial break */
1964
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
1965
                    s->do_telnetopt++;
1966
                }
1967
                s->do_telnetopt++;
1968
            }
1969
            if (s->do_telnetopt >= 4) {
1970
                s->do_telnetopt = 1;
1971
            }
1972
        } else {
1973
            if ((unsigned char)buf[i] == IAC) {
1974
                s->do_telnetopt = 2;
1975
            } else {
1976
                if (j != i)
1977
                    buf[j] = buf[i];
1978
                j++;
1979
            }
1980
        }
1981
    }
1982
    *size = j;
1983
}
1984

    
1985
static int tcp_get_msgfd(CharDriverState *chr)
1986
{
1987
    TCPCharDriver *s = chr->opaque;
1988

    
1989
    return s->msgfd;
1990
}
1991

    
1992
#ifndef _WIN32
1993
static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
1994
{
1995
    TCPCharDriver *s = chr->opaque;
1996
    struct cmsghdr *cmsg;
1997

    
1998
    for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
1999
        int fd;
2000

    
2001
        if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
2002
            cmsg->cmsg_level != SOL_SOCKET ||
2003
            cmsg->cmsg_type != SCM_RIGHTS)
2004
            continue;
2005

    
2006
        fd = *((int *)CMSG_DATA(cmsg));
2007
        if (fd < 0)
2008
            continue;
2009

    
2010
        if (s->msgfd != -1)
2011
            close(s->msgfd);
2012
        s->msgfd = fd;
2013
    }
2014
}
2015

    
2016
static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2017
{
2018
    TCPCharDriver *s = chr->opaque;
2019
    struct msghdr msg = { NULL, };
2020
    struct iovec iov[1];
2021
    union {
2022
        struct cmsghdr cmsg;
2023
        char control[CMSG_SPACE(sizeof(int))];
2024
    } msg_control;
2025
    ssize_t ret;
2026

    
2027
    iov[0].iov_base = buf;
2028
    iov[0].iov_len = len;
2029

    
2030
    msg.msg_iov = iov;
2031
    msg.msg_iovlen = 1;
2032
    msg.msg_control = &msg_control;
2033
    msg.msg_controllen = sizeof(msg_control);
2034

    
2035
    ret = recvmsg(s->fd, &msg, 0);
2036
    if (ret > 0 && s->is_unix)
2037
        unix_process_msgfd(chr, &msg);
2038

    
2039
    return ret;
2040
}
2041
#else
2042
static ssize_t tcp_chr_recv(CharDriverState *chr, char *buf, size_t len)
2043
{
2044
    TCPCharDriver *s = chr->opaque;
2045
    return recv(s->fd, buf, len, 0);
2046
}
2047
#endif
2048

    
2049
static void tcp_chr_read(void *opaque)
2050
{
2051
    CharDriverState *chr = opaque;
2052
    TCPCharDriver *s = chr->opaque;
2053
    uint8_t buf[READ_BUF_LEN];
2054
    int len, size;
2055

    
2056
    if (!s->connected || s->max_size <= 0)
2057
        return;
2058
    len = sizeof(buf);
2059
    if (len > s->max_size)
2060
        len = s->max_size;
2061
    size = tcp_chr_recv(chr, (void *)buf, len);
2062
    if (size == 0) {
2063
        /* connection closed */
2064
        s->connected = 0;
2065
        if (s->listen_fd >= 0) {
2066
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2067
        }
2068
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2069
        closesocket(s->fd);
2070
        s->fd = -1;
2071
        qemu_chr_event(chr, CHR_EVENT_CLOSED);
2072
    } else if (size > 0) {
2073
        if (s->do_telnetopt)
2074
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2075
        if (size > 0)
2076
            qemu_chr_read(chr, buf, size);
2077
        if (s->msgfd != -1) {
2078
            close(s->msgfd);
2079
            s->msgfd = -1;
2080
        }
2081
    }
2082
}
2083

    
2084
static void tcp_chr_connect(void *opaque)
2085
{
2086
    CharDriverState *chr = opaque;
2087
    TCPCharDriver *s = chr->opaque;
2088

    
2089
    s->connected = 1;
2090
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2091
                         tcp_chr_read, NULL, chr);
2092
    qemu_chr_generic_open(chr);
2093
}
2094

    
2095
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2096
static void tcp_chr_telnet_init(int fd)
2097
{
2098
    char buf[3];
2099
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2100
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2101
    send(fd, (char *)buf, 3, 0);
2102
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2103
    send(fd, (char *)buf, 3, 0);
2104
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2105
    send(fd, (char *)buf, 3, 0);
2106
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2107
    send(fd, (char *)buf, 3, 0);
2108
}
2109

    
2110
static void socket_set_nodelay(int fd)
2111
{
2112
    int val = 1;
2113
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2114
}
2115

    
2116
static void tcp_chr_accept(void *opaque)
2117
{
2118
    CharDriverState *chr = opaque;
2119
    TCPCharDriver *s = chr->opaque;
2120
    struct sockaddr_in saddr;
2121
#ifndef _WIN32
2122
    struct sockaddr_un uaddr;
2123
#endif
2124
    struct sockaddr *addr;
2125
    socklen_t len;
2126
    int fd;
2127

    
2128
    for(;;) {
2129
#ifndef _WIN32
2130
        if (s->is_unix) {
2131
            len = sizeof(uaddr);
2132
            addr = (struct sockaddr *)&uaddr;
2133
        } else
2134
#endif
2135
        {
2136
            len = sizeof(saddr);
2137
            addr = (struct sockaddr *)&saddr;
2138
        }
2139
        fd = qemu_accept(s->listen_fd, addr, &len);
2140
        if (fd < 0 && errno != EINTR) {
2141
            return;
2142
        } else if (fd >= 0) {
2143
            if (s->do_telnetopt)
2144
                tcp_chr_telnet_init(fd);
2145
            break;
2146
        }
2147
    }
2148
    socket_set_nonblock(fd);
2149
    if (s->do_nodelay)
2150
        socket_set_nodelay(fd);
2151
    s->fd = fd;
2152
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2153
    tcp_chr_connect(chr);
2154
}
2155

    
2156
static void tcp_chr_close(CharDriverState *chr)
2157
{
2158
    TCPCharDriver *s = chr->opaque;
2159
    if (s->fd >= 0) {
2160
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2161
        closesocket(s->fd);
2162
    }
2163
    if (s->listen_fd >= 0) {
2164
        qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2165
        closesocket(s->listen_fd);
2166
    }
2167
    qemu_free(s);
2168
    qemu_chr_event(chr, CHR_EVENT_CLOSED);
2169
}
2170

    
2171
static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)
2172
{
2173
    CharDriverState *chr = NULL;
2174
    TCPCharDriver *s = NULL;
2175
    int fd = -1;
2176
    int is_listen;
2177
    int is_waitconnect;
2178
    int do_nodelay;
2179
    int is_unix;
2180
    int is_telnet;
2181

    
2182
    is_listen      = qemu_opt_get_bool(opts, "server", 0);
2183
    is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);
2184
    is_telnet      = qemu_opt_get_bool(opts, "telnet", 0);
2185
    do_nodelay     = !qemu_opt_get_bool(opts, "delay", 1);
2186
    is_unix        = qemu_opt_get(opts, "path") != NULL;
2187
    if (!is_listen)
2188
        is_waitconnect = 0;
2189

    
2190
    chr = qemu_mallocz(sizeof(CharDriverState));
2191
    s = qemu_mallocz(sizeof(TCPCharDriver));
2192

    
2193
    if (is_unix) {
2194
        if (is_listen) {
2195
            fd = unix_listen_opts(opts);
2196
        } else {
2197
            fd = unix_connect_opts(opts);
2198
        }
2199
    } else {
2200
        if (is_listen) {
2201
            fd = inet_listen_opts(opts, 0);
2202
        } else {
2203
            fd = inet_connect_opts(opts);
2204
        }
2205
    }
2206
    if (fd < 0)
2207
        goto fail;
2208

    
2209
    if (!is_waitconnect)
2210
        socket_set_nonblock(fd);
2211

    
2212
    s->connected = 0;
2213
    s->fd = -1;
2214
    s->listen_fd = -1;
2215
    s->msgfd = -1;
2216
    s->is_unix = is_unix;
2217
    s->do_nodelay = do_nodelay && !is_unix;
2218

    
2219
    chr->opaque = s;
2220
    chr->chr_write = tcp_chr_write;
2221
    chr->chr_close = tcp_chr_close;
2222
    chr->get_msgfd = tcp_get_msgfd;
2223

    
2224
    if (is_listen) {
2225
        s->listen_fd = fd;
2226
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2227
        if (is_telnet)
2228
            s->do_telnetopt = 1;
2229

    
2230
    } else {
2231
        s->connected = 1;
2232
        s->fd = fd;
2233
        socket_set_nodelay(fd);
2234
        tcp_chr_connect(chr);
2235
    }
2236

    
2237
    /* for "info chardev" monitor command */
2238
    chr->filename = qemu_malloc(256);
2239
    if (is_unix) {
2240
        snprintf(chr->filename, 256, "unix:%s%s",
2241
                 qemu_opt_get(opts, "path"),
2242
                 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2243
    } else if (is_telnet) {
2244
        snprintf(chr->filename, 256, "telnet:%s:%s%s",
2245
                 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2246
                 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2247
    } else {
2248
        snprintf(chr->filename, 256, "tcp:%s:%s%s",
2249
                 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),
2250
                 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");
2251
    }
2252

    
2253
    if (is_listen && is_waitconnect) {
2254
        printf("QEMU waiting for connection on: %s\n",
2255
               chr->filename);
2256
        tcp_chr_accept(chr);
2257
        socket_set_nonblock(s->listen_fd);
2258
    }
2259
    return chr;
2260

    
2261
 fail:
2262
    if (fd >= 0)
2263
        closesocket(fd);
2264
    qemu_free(s);
2265
    qemu_free(chr);
2266
    return NULL;
2267
}
2268

    
2269
QemuOpts *qemu_chr_parse_compat(const char *label, const char *filename)
2270
{
2271
    char host[65], port[33], width[8], height[8];
2272
    int pos;
2273
    const char *p;
2274
    QemuOpts *opts;
2275

    
2276
    opts = qemu_opts_create(&qemu_chardev_opts, label, 1);
2277
    if (NULL == opts)
2278
        return NULL;
2279

    
2280
    if (strstart(filename, "mon:", &p)) {
2281
        filename = p;
2282
        qemu_opt_set(opts, "mux", "on");
2283
    }
2284

    
2285
    if (strcmp(filename, "null")    == 0 ||
2286
        strcmp(filename, "pty")     == 0 ||
2287
        strcmp(filename, "msmouse") == 0 ||
2288
        strcmp(filename, "braille") == 0 ||
2289
        strcmp(filename, "stdio")   == 0) {
2290
        qemu_opt_set(opts, "backend", filename);
2291
        return opts;
2292
    }
2293
    if (strstart(filename, "vc", &p)) {
2294
        qemu_opt_set(opts, "backend", "vc");
2295
        if (*p == ':') {
2296
            if (sscanf(p+1, "%8[0-9]x%8[0-9]", width, height) == 2) {
2297
                /* pixels */
2298
                qemu_opt_set(opts, "width", width);
2299
                qemu_opt_set(opts, "height", height);
2300
            } else if (sscanf(p+1, "%8[0-9]Cx%8[0-9]C", width, height) == 2) {
2301
                /* chars */
2302
                qemu_opt_set(opts, "cols", width);
2303
                qemu_opt_set(opts, "rows", height);
2304
            } else {
2305
                goto fail;
2306
            }
2307
        }
2308
        return opts;
2309
    }
2310
    if (strcmp(filename, "con:") == 0) {
2311
        qemu_opt_set(opts, "backend", "console");
2312
        return opts;
2313
    }
2314
    if (strstart(filename, "COM", NULL)) {
2315
        qemu_opt_set(opts, "backend", "serial");
2316
        qemu_opt_set(opts, "path", filename);
2317
        return opts;
2318
    }
2319
    if (strstart(filename, "file:", &p)) {
2320
        qemu_opt_set(opts, "backend", "file");
2321
        qemu_opt_set(opts, "path", p);
2322
        return opts;
2323
    }
2324
    if (strstart(filename, "pipe:", &p)) {
2325
        qemu_opt_set(opts, "backend", "pipe");
2326
        qemu_opt_set(opts, "path", p);
2327
        return opts;
2328
    }
2329
    if (strstart(filename, "tcp:", &p) ||
2330
        strstart(filename, "telnet:", &p)) {
2331
        if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2332
            host[0] = 0;
2333
            if (sscanf(p, ":%32[^,]%n", port, &pos) < 1)
2334
                goto fail;
2335
        }
2336
        qemu_opt_set(opts, "backend", "socket");
2337
        qemu_opt_set(opts, "host", host);
2338
        qemu_opt_set(opts, "port", port);
2339
        if (p[pos] == ',') {
2340
            if (qemu_opts_do_parse(opts, p+pos+1, NULL) != 0)
2341
                goto fail;
2342
        }
2343
        if (strstart(filename, "telnet:", &p))
2344
            qemu_opt_set(opts, "telnet", "on");
2345
        return opts;
2346
    }
2347
    if (strstart(filename, "udp:", &p)) {
2348
        qemu_opt_set(opts, "backend", "udp");
2349
        if (sscanf(p, "%64[^:]:%32[^@,]%n", host, port, &pos) < 2) {
2350
            host[0] = 0;
2351
            if (sscanf(p, ":%32[^@,]%n", port, &pos) < 1) {
2352
                goto fail;
2353
            }
2354
        }
2355
        qemu_opt_set(opts, "host", host);
2356
        qemu_opt_set(opts, "port", port);
2357
        if (p[pos] == '@') {
2358
            p += pos + 1;
2359
            if (sscanf(p, "%64[^:]:%32[^,]%n", host, port, &pos) < 2) {
2360
                host[0] = 0;
2361
                if (sscanf(p, ":%32[^,]%n", port, &pos) < 1) {
2362
                    goto fail;
2363
                }
2364
            }
2365
            qemu_opt_set(opts, "localaddr", host);
2366
            qemu_opt_set(opts, "localport", port);
2367
        }
2368
        return opts;
2369
    }
2370
    if (strstart(filename, "unix:", &p)) {
2371
        qemu_opt_set(opts, "backend", "socket");
2372
        if (qemu_opts_do_parse(opts, p, "path") != 0)
2373
            goto fail;
2374
        return opts;
2375
    }
2376
    if (strstart(filename, "/dev/parport", NULL) ||
2377
        strstart(filename, "/dev/ppi", NULL)) {
2378
        qemu_opt_set(opts, "backend", "parport");
2379
        qemu_opt_set(opts, "path", filename);
2380
        return opts;
2381
    }
2382
    if (strstart(filename, "/dev/", NULL)) {
2383
        qemu_opt_set(opts, "backend", "tty");
2384
        qemu_opt_set(opts, "path", filename);
2385
        return opts;
2386
    }
2387

    
2388
fail:
2389
    qemu_opts_del(opts);
2390
    return NULL;
2391
}
2392

    
2393
static const struct {
2394
    const char *name;
2395
    CharDriverState *(*open)(QemuOpts *opts);
2396
} backend_table[] = {
2397
    { .name = "null",      .open = qemu_chr_open_null },
2398
    { .name = "socket",    .open = qemu_chr_open_socket },
2399
    { .name = "udp",       .open = qemu_chr_open_udp },
2400
    { .name = "msmouse",   .open = qemu_chr_open_msmouse },
2401
    { .name = "vc",        .open = text_console_init },
2402
#ifdef _WIN32
2403
    { .name = "file",      .open = qemu_chr_open_win_file_out },
2404
    { .name = "pipe",      .open = qemu_chr_open_win_pipe },
2405
    { .name = "console",   .open = qemu_chr_open_win_con },
2406
    { .name = "serial",    .open = qemu_chr_open_win },
2407
#else
2408
    { .name = "file",      .open = qemu_chr_open_file_out },
2409
    { .name = "pipe",      .open = qemu_chr_open_pipe },
2410
    { .name = "pty",       .open = qemu_chr_open_pty },
2411
    { .name = "stdio",     .open = qemu_chr_open_stdio },
2412
#endif
2413
#ifdef CONFIG_BRLAPI
2414
    { .name = "braille",   .open = chr_baum_init },
2415
#endif
2416
#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2417
    || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
2418
    || defined(__FreeBSD_kernel__)
2419
    { .name = "tty",       .open = qemu_chr_open_tty },
2420
#endif
2421
#if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) \
2422
    || defined(__FreeBSD_kernel__)
2423
    { .name = "parport",   .open = qemu_chr_open_pp },
2424
#endif
2425
};
2426

    
2427
CharDriverState *qemu_chr_open_opts(QemuOpts *opts,
2428
                                    void (*init)(struct CharDriverState *s))
2429
{
2430
    CharDriverState *chr;
2431
    int i;
2432

    
2433
    if (qemu_opts_id(opts) == NULL) {
2434
        fprintf(stderr, "chardev: no id specified\n");
2435
        return NULL;
2436
    }
2437

    
2438
    for (i = 0; i < ARRAY_SIZE(backend_table); i++) {
2439
        if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)
2440
            break;
2441
    }
2442
    if (i == ARRAY_SIZE(backend_table)) {
2443
        fprintf(stderr, "chardev: backend \"%s\" not found\n",
2444
                qemu_opt_get(opts, "backend"));
2445
        return NULL;
2446
    }
2447

    
2448
    chr = backend_table[i].open(opts);
2449
    if (!chr) {
2450
        fprintf(stderr, "chardev: opening backend \"%s\" failed\n",
2451
                qemu_opt_get(opts, "backend"));
2452
        return NULL;
2453
    }
2454

    
2455
    if (!chr->filename)
2456
        chr->filename = qemu_strdup(qemu_opt_get(opts, "backend"));
2457
    chr->init = init;
2458
    QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2459

    
2460
    if (qemu_opt_get_bool(opts, "mux", 0)) {
2461
        CharDriverState *base = chr;
2462
        int len = strlen(qemu_opts_id(opts)) + 6;
2463
        base->label = qemu_malloc(len);
2464
        snprintf(base->label, len, "%s-base", qemu_opts_id(opts));
2465
        chr = qemu_chr_open_mux(base);
2466
        chr->filename = base->filename;
2467
        QTAILQ_INSERT_TAIL(&chardevs, chr, next);
2468
    }
2469
    chr->label = qemu_strdup(qemu_opts_id(opts));
2470
    return chr;
2471
}
2472

    
2473
CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2474
{
2475
    const char *p;
2476
    CharDriverState *chr;
2477
    QemuOpts *opts;
2478

    
2479
    if (strstart(filename, "chardev:", &p)) {
2480
        return qemu_chr_find(p);
2481
    }
2482

    
2483
    opts = qemu_chr_parse_compat(label, filename);
2484
    if (!opts)
2485
        return NULL;
2486

    
2487
    chr = qemu_chr_open_opts(opts, init);
2488
    if (chr && qemu_opt_get_bool(opts, "mux", 0)) {
2489
        monitor_init(chr, MONITOR_USE_READLINE);
2490
    }
2491
    return chr;
2492
}
2493

    
2494
void qemu_chr_close(CharDriverState *chr)
2495
{
2496
    QTAILQ_REMOVE(&chardevs, chr, next);
2497
    if (chr->chr_close)
2498
        chr->chr_close(chr);
2499
    qemu_free(chr->filename);
2500
    qemu_free(chr->label);
2501
    qemu_free(chr);
2502
}
2503

    
2504
static void qemu_chr_qlist_iter(QObject *obj, void *opaque)
2505
{
2506
    QDict *chr_dict;
2507
    Monitor *mon = opaque;
2508

    
2509
    chr_dict = qobject_to_qdict(obj);
2510
    monitor_printf(mon, "%s: filename=%s\n", qdict_get_str(chr_dict, "label"),
2511
                                         qdict_get_str(chr_dict, "filename"));
2512
}
2513

    
2514
void qemu_chr_info_print(Monitor *mon, const QObject *ret_data)
2515
{
2516
    qlist_iter(qobject_to_qlist(ret_data), qemu_chr_qlist_iter, mon);
2517
}
2518

    
2519
/**
2520
 * qemu_chr_info(): Character devices information
2521
 *
2522
 * Each device is represented by a QDict. The returned QObject is a QList
2523
 * of all devices.
2524
 *
2525
 * The QDict contains the following:
2526
 *
2527
 * - "label": device's label
2528
 * - "filename": device's file
2529
 *
2530
 * Example:
2531
 *
2532
 * [ { "label": "monitor", "filename", "stdio" },
2533
 *   { "label": "serial0", "filename": "vc" } ]
2534
 */
2535
void qemu_chr_info(Monitor *mon, QObject **ret_data)
2536
{
2537
    QList *chr_list;
2538
    CharDriverState *chr;
2539

    
2540
    chr_list = qlist_new();
2541

    
2542
    QTAILQ_FOREACH(chr, &chardevs, next) {
2543
        QObject *obj = qobject_from_jsonf("{ 'label': %s, 'filename': %s }",
2544
                                          chr->label, chr->filename);
2545
        qlist_append_obj(chr_list, obj);
2546
    }
2547

    
2548
    *ret_data = QOBJECT(chr_list);
2549
}
2550

    
2551
CharDriverState *qemu_chr_find(const char *name)
2552
{
2553
    CharDriverState *chr;
2554

    
2555
    QTAILQ_FOREACH(chr, &chardevs, next) {
2556
        if (strcmp(chr->label, name) != 0)
2557
            continue;
2558
        return chr;
2559
    }
2560
    return NULL;
2561
}