Statistics
| Branch: | Revision:

root / qemu-char.c @ 2970a6c9

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

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

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

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

    
99
#include "qemu_socket.h"
100

    
101
/***********************************************************/
102
/* character device */
103

    
104
static TAILQ_HEAD(CharDriverStateHead, CharDriverState) chardevs =
105
    TAILQ_HEAD_INITIALIZER(chardevs);
106
static int initial_reset_issued;
107

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

    
115
static void qemu_chr_reset_bh(void *opaque)
116
{
117
    CharDriverState *s = opaque;
118
    qemu_chr_event(s, CHR_EVENT_RESET);
119
    qemu_bh_delete(s->bh);
120
    s->bh = NULL;
121
}
122

    
123
void qemu_chr_reset(CharDriverState *s)
124
{
125
    if (s->bh == NULL && initial_reset_issued) {
126
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
127
        qemu_bh_schedule(s->bh);
128
    }
129
}
130

    
131
void qemu_chr_initial_reset(void)
132
{
133
    CharDriverState *chr;
134

    
135
    initial_reset_issued = 1;
136

    
137
    TAILQ_FOREACH(chr, &chardevs, next) {
138
        qemu_chr_reset(chr);
139
    }
140
}
141

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

    
147
int qemu_chr_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_can_read(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_read(CharDriverState *s, uint8_t *buf, int len)
162
{
163
    s->chr_read(s->handler_opaque, buf, len);
164
}
165

    
166
void qemu_chr_accept_input(CharDriverState *s)
167
{
168
    if (s->chr_accept_input)
169
        s->chr_accept_input(s);
170
}
171

    
172
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
173
{
174
    char buf[4096];
175
    va_list ap;
176
    va_start(ap, fmt);
177
    vsnprintf(buf, sizeof(buf), fmt, ap);
178
    qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
179
    va_end(ap);
180
}
181

    
182
void qemu_chr_send_event(CharDriverState *s, int event)
183
{
184
    if (s->chr_send_event)
185
        s->chr_send_event(s, event);
186
}
187

    
188
void qemu_chr_add_handlers(CharDriverState *s,
189
                           IOCanRWHandler *fd_can_read,
190
                           IOReadHandler *fd_read,
191
                           IOEventHandler *fd_event,
192
                           void *opaque)
193
{
194
    s->chr_can_read = fd_can_read;
195
    s->chr_read = fd_read;
196
    s->chr_event = fd_event;
197
    s->handler_opaque = opaque;
198
    if (s->chr_update_read_handler)
199
        s->chr_update_read_handler(s);
200
}
201

    
202
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
203
{
204
    return len;
205
}
206

    
207
static CharDriverState *qemu_chr_open_null(void)
208
{
209
    CharDriverState *chr;
210

    
211
    chr = qemu_mallocz(sizeof(CharDriverState));
212
    chr->chr_write = null_chr_write;
213
    return chr;
214
}
215

    
216
/* MUX driver for serial I/O splitting */
217
static int term_timestamps;
218
static int64_t term_timestamps_start;
219
#define MAX_MUX 4
220
#define MUX_BUFFER_SIZE 32        /* Must be a power of 2.  */
221
#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
222
typedef struct {
223
    IOCanRWHandler *chr_can_read[MAX_MUX];
224
    IOReadHandler *chr_read[MAX_MUX];
225
    IOEventHandler *chr_event[MAX_MUX];
226
    void *ext_opaque[MAX_MUX];
227
    CharDriverState *drv;
228
    unsigned char buffer[MUX_BUFFER_SIZE];
229
    int prod;
230
    int cons;
231
    int mux_cnt;
232
    int term_got_escape;
233
    int max_size;
234
} MuxDriver;
235

    
236

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

    
246
        ret = 0;
247
        for(i = 0; i < len; i++) {
248
            ret += d->drv->chr_write(d->drv, buf+i, 1);
249
            if (buf[i] == '\n') {
250
                char buf1[64];
251
                int64_t ti;
252
                int secs;
253

    
254
                ti = qemu_get_clock(rt_clock);
255
                if (term_timestamps_start == -1)
256
                    term_timestamps_start = ti;
257
                ti -= term_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
            }
267
        }
268
    }
269
    return ret;
270
}
271

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

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

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

    
309
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
310
{
311
    if (d->term_got_escape) {
312
        d->term_got_escape = 0;
313
        if (ch == term_escape_char)
314
            goto send_char;
315
        switch(ch) {
316
        case '?':
317
        case 'h':
318
            mux_print_help(chr);
319
            break;
320
        case 'x':
321
            {
322
                 const char *term =  "QEMU: Terminated\n\r";
323
                 chr->chr_write(chr,(uint8_t *)term,strlen(term));
324
                 exit(0);
325
                 break;
326
            }
327
        case 's':
328
            {
329
                int i;
330
                for (i = 0; i < nb_drives; i++) {
331
                        bdrv_commit(drives_table[i].bdrv);
332
                }
333
            }
334
            break;
335
        case 'b':
336
            qemu_chr_event(chr, CHR_EVENT_BREAK);
337
            break;
338
        case 'c':
339
            /* Switch to the next registered device */
340
            chr->focus++;
341
            if (chr->focus >= d->mux_cnt)
342
                chr->focus = 0;
343
            break;
344
       case 't':
345
           term_timestamps = !term_timestamps;
346
           term_timestamps_start = -1;
347
           break;
348
        }
349
    } else if (ch == term_escape_char) {
350
        d->term_got_escape = 1;
351
    } else {
352
    send_char:
353
        return 1;
354
    }
355
    return 0;
356
}
357

    
358
static void mux_chr_accept_input(CharDriverState *chr)
359
{
360
    int m = chr->focus;
361
    MuxDriver *d = chr->opaque;
362

    
363
    while (d->prod != d->cons &&
364
           d->chr_can_read[m] &&
365
           d->chr_can_read[m](d->ext_opaque[m])) {
366
        d->chr_read[m](d->ext_opaque[m],
367
                       &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
368
    }
369
}
370

    
371
static int mux_chr_can_read(void *opaque)
372
{
373
    CharDriverState *chr = opaque;
374
    MuxDriver *d = chr->opaque;
375

    
376
    if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
377
        return 1;
378
    if (d->chr_can_read[chr->focus])
379
        return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
380
    return 0;
381
}
382

    
383
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
384
{
385
    CharDriverState *chr = opaque;
386
    MuxDriver *d = chr->opaque;
387
    int m = chr->focus;
388
    int i;
389

    
390
    mux_chr_accept_input (opaque);
391

    
392
    for(i = 0; i < size; i++)
393
        if (mux_proc_byte(chr, d, buf[i])) {
394
            if (d->prod == d->cons &&
395
                d->chr_can_read[m] &&
396
                d->chr_can_read[m](d->ext_opaque[m]))
397
                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
398
            else
399
                d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
400
        }
401
}
402

    
403
static void mux_chr_event(void *opaque, int event)
404
{
405
    CharDriverState *chr = opaque;
406
    MuxDriver *d = chr->opaque;
407
    int i;
408

    
409
    /* Send the event to all registered listeners */
410
    for (i = 0; i < d->mux_cnt; i++)
411
        if (d->chr_event[i])
412
            d->chr_event[i](d->ext_opaque[i], event);
413
}
414

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

    
419
    if (d->mux_cnt >= MAX_MUX) {
420
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
421
        return;
422
    }
423
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
424
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
425
    d->chr_read[d->mux_cnt] = chr->chr_read;
426
    d->chr_event[d->mux_cnt] = chr->chr_event;
427
    /* Fix up the real driver with mux routines */
428
    if (d->mux_cnt == 0) {
429
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
430
                              mux_chr_event, chr);
431
    }
432
    chr->focus = d->mux_cnt;
433
    d->mux_cnt++;
434
}
435

    
436
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
437
{
438
    CharDriverState *chr;
439
    MuxDriver *d;
440

    
441
    chr = qemu_mallocz(sizeof(CharDriverState));
442
    d = qemu_mallocz(sizeof(MuxDriver));
443

    
444
    chr->opaque = d;
445
    d->drv = drv;
446
    chr->focus = -1;
447
    chr->chr_write = mux_chr_write;
448
    chr->chr_update_read_handler = mux_chr_update_read_handler;
449
    chr->chr_accept_input = mux_chr_accept_input;
450
    return chr;
451
}
452

    
453

    
454
#ifdef _WIN32
455
int send_all(int fd, const void *buf, int len1)
456
{
457
    int ret, len;
458

    
459
    len = len1;
460
    while (len > 0) {
461
        ret = send(fd, buf, len, 0);
462
        if (ret < 0) {
463
            errno = WSAGetLastError();
464
            if (errno != WSAEWOULDBLOCK) {
465
                return -1;
466
            }
467
        } else if (ret == 0) {
468
            break;
469
        } else {
470
            buf += ret;
471
            len -= ret;
472
        }
473
    }
474
    return len1 - len;
475
}
476

    
477
#else
478

    
479
static int unix_write(int fd, const uint8_t *buf, int len1)
480
{
481
    int ret, len;
482

    
483
    len = len1;
484
    while (len > 0) {
485
        ret = write(fd, buf, len);
486
        if (ret < 0) {
487
            if (errno != EINTR && errno != EAGAIN)
488
                return -1;
489
        } else if (ret == 0) {
490
            break;
491
        } else {
492
            buf += ret;
493
            len -= ret;
494
        }
495
    }
496
    return len1 - len;
497
}
498

    
499
int send_all(int fd, const void *buf, int len1)
500
{
501
    return unix_write(fd, buf, len1);
502
}
503
#endif /* !_WIN32 */
504

    
505
#ifndef _WIN32
506

    
507
typedef struct {
508
    int fd_in, fd_out;
509
    int max_size;
510
} FDCharDriver;
511

    
512
#define STDIO_MAX_CLIENTS 1
513
static int stdio_nb_clients = 0;
514

    
515
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
516
{
517
    FDCharDriver *s = chr->opaque;
518
    return send_all(s->fd_out, buf, len);
519
}
520

    
521
static int fd_chr_read_poll(void *opaque)
522
{
523
    CharDriverState *chr = opaque;
524
    FDCharDriver *s = chr->opaque;
525

    
526
    s->max_size = qemu_chr_can_read(chr);
527
    return s->max_size;
528
}
529

    
530
static void fd_chr_read(void *opaque)
531
{
532
    CharDriverState *chr = opaque;
533
    FDCharDriver *s = chr->opaque;
534
    int size, len;
535
    uint8_t buf[1024];
536

    
537
    len = sizeof(buf);
538
    if (len > s->max_size)
539
        len = s->max_size;
540
    if (len == 0)
541
        return;
542
    size = read(s->fd_in, buf, len);
543
    if (size == 0) {
544
        /* FD has been closed. Remove it from the active list.  */
545
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
546
        return;
547
    }
548
    if (size > 0) {
549
        qemu_chr_read(chr, buf, size);
550
    }
551
}
552

    
553
static void fd_chr_update_read_handler(CharDriverState *chr)
554
{
555
    FDCharDriver *s = chr->opaque;
556

    
557
    if (s->fd_in >= 0) {
558
        if (nographic && s->fd_in == 0) {
559
        } else {
560
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
561
                                 fd_chr_read, NULL, chr);
562
        }
563
    }
564
}
565

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

    
570
    if (s->fd_in >= 0) {
571
        if (nographic && s->fd_in == 0) {
572
        } else {
573
            qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
574
        }
575
    }
576

    
577
    qemu_free(s);
578
}
579

    
580
/* open a character device to a unix fd */
581
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
582
{
583
    CharDriverState *chr;
584
    FDCharDriver *s;
585

    
586
    chr = qemu_mallocz(sizeof(CharDriverState));
587
    s = qemu_mallocz(sizeof(FDCharDriver));
588
    s->fd_in = fd_in;
589
    s->fd_out = fd_out;
590
    chr->opaque = s;
591
    chr->chr_write = fd_chr_write;
592
    chr->chr_update_read_handler = fd_chr_update_read_handler;
593
    chr->chr_close = fd_chr_close;
594

    
595
    qemu_chr_reset(chr);
596

    
597
    return chr;
598
}
599

    
600
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
601
{
602
    int fd_out;
603

    
604
    TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
605
    if (fd_out < 0)
606
        return NULL;
607
    return qemu_chr_open_fd(-1, fd_out);
608
}
609

    
610
static CharDriverState *qemu_chr_open_pipe(const char *filename)
611
{
612
    int fd_in, fd_out;
613
    char filename_in[256], filename_out[256];
614

    
615
    snprintf(filename_in, 256, "%s.in", filename);
616
    snprintf(filename_out, 256, "%s.out", filename);
617
    TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
618
    TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
619
    if (fd_in < 0 || fd_out < 0) {
620
        if (fd_in >= 0)
621
            close(fd_in);
622
        if (fd_out >= 0)
623
            close(fd_out);
624
        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
625
        if (fd_in < 0)
626
            return NULL;
627
    }
628
    return qemu_chr_open_fd(fd_in, fd_out);
629
}
630

    
631

    
632
/* for STDIO, we handle the case where several clients use it
633
   (nographic mode) */
634

    
635
#define TERM_FIFO_MAX_SIZE 1
636

    
637
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
638
static int term_fifo_size;
639

    
640
static int stdio_read_poll(void *opaque)
641
{
642
    CharDriverState *chr = opaque;
643

    
644
    /* try to flush the queue if needed */
645
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
646
        qemu_chr_read(chr, term_fifo, 1);
647
        term_fifo_size = 0;
648
    }
649
    /* see if we can absorb more chars */
650
    if (term_fifo_size == 0)
651
        return 1;
652
    else
653
        return 0;
654
}
655

    
656
static void stdio_read(void *opaque)
657
{
658
    int size;
659
    uint8_t buf[1];
660
    CharDriverState *chr = opaque;
661

    
662
    size = read(0, buf, 1);
663
    if (size == 0) {
664
        /* stdin has been closed. Remove it from the active list.  */
665
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
666
        return;
667
    }
668
    if (size > 0) {
669
        if (qemu_chr_can_read(chr) > 0) {
670
            qemu_chr_read(chr, buf, 1);
671
        } else if (term_fifo_size == 0) {
672
            term_fifo[term_fifo_size++] = buf[0];
673
        }
674
    }
675
}
676

    
677
/* init terminal so that we can grab keys */
678
static struct termios oldtty;
679
static int old_fd0_flags;
680
static int term_atexit_done;
681

    
682
static void term_exit(void)
683
{
684
    tcsetattr (0, TCSANOW, &oldtty);
685
    fcntl(0, F_SETFL, old_fd0_flags);
686
}
687

    
688
static void term_init(void)
689
{
690
    struct termios tty;
691

    
692
    tcgetattr (0, &tty);
693
    oldtty = tty;
694
    old_fd0_flags = fcntl(0, F_GETFL);
695

    
696
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
697
                          |INLCR|IGNCR|ICRNL|IXON);
698
    tty.c_oflag |= OPOST;
699
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
700
    /* if graphical mode, we allow Ctrl-C handling */
701
    if (nographic)
702
        tty.c_lflag &= ~ISIG;
703
    tty.c_cflag &= ~(CSIZE|PARENB);
704
    tty.c_cflag |= CS8;
705
    tty.c_cc[VMIN] = 1;
706
    tty.c_cc[VTIME] = 0;
707

    
708
    tcsetattr (0, TCSANOW, &tty);
709

    
710
    if (!term_atexit_done++)
711
        atexit(term_exit);
712

    
713
    fcntl(0, F_SETFL, O_NONBLOCK);
714
}
715

    
716
static void qemu_chr_close_stdio(struct CharDriverState *chr)
717
{
718
    term_exit();
719
    stdio_nb_clients--;
720
    qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
721
    fd_chr_close(chr);
722
}
723

    
724
static CharDriverState *qemu_chr_open_stdio(void)
725
{
726
    CharDriverState *chr;
727

    
728
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
729
        return NULL;
730
    chr = qemu_chr_open_fd(0, 1);
731
    chr->chr_close = qemu_chr_close_stdio;
732
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
733
    stdio_nb_clients++;
734
    term_init();
735

    
736
    return chr;
737
}
738

    
739
#ifdef __sun__
740
/* Once Solaris has openpty(), this is going to be removed. */
741
int openpty(int *amaster, int *aslave, char *name,
742
            struct termios *termp, struct winsize *winp)
743
{
744
        const char *slave;
745
        int mfd = -1, sfd = -1;
746

    
747
        *amaster = *aslave = -1;
748

    
749
        mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
750
        if (mfd < 0)
751
                goto err;
752

    
753
        if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
754
                goto err;
755

    
756
        if ((slave = ptsname(mfd)) == NULL)
757
                goto err;
758

    
759
        if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
760
                goto err;
761

    
762
        if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
763
            (termp != NULL && tcgetattr(sfd, termp) < 0))
764
                goto err;
765

    
766
        if (amaster)
767
                *amaster = mfd;
768
        if (aslave)
769
                *aslave = sfd;
770
        if (winp)
771
                ioctl(sfd, TIOCSWINSZ, winp);
772

    
773
        return 0;
774

    
775
err:
776
        if (sfd != -1)
777
                close(sfd);
778
        close(mfd);
779
        return -1;
780
}
781

    
782
void cfmakeraw (struct termios *termios_p)
783
{
784
        termios_p->c_iflag &=
785
                ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
786
        termios_p->c_oflag &= ~OPOST;
787
        termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
788
        termios_p->c_cflag &= ~(CSIZE|PARENB);
789
        termios_p->c_cflag |= CS8;
790

    
791
        termios_p->c_cc[VMIN] = 0;
792
        termios_p->c_cc[VTIME] = 0;
793
}
794
#endif
795

    
796
#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
797
    || defined(__NetBSD__) || defined(__OpenBSD__)
798

    
799
typedef struct {
800
    int fd;
801
    int connected;
802
    int polling;
803
    int read_bytes;
804
    QEMUTimer *timer;
805
} PtyCharDriver;
806

    
807
static void pty_chr_update_read_handler(CharDriverState *chr);
808
static void pty_chr_state(CharDriverState *chr, int connected);
809

    
810
static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
811
{
812
    PtyCharDriver *s = chr->opaque;
813

    
814
    if (!s->connected) {
815
        /* guest sends data, check for (re-)connect */
816
        pty_chr_update_read_handler(chr);
817
        return 0;
818
    }
819
    return send_all(s->fd, buf, len);
820
}
821

    
822
static int pty_chr_read_poll(void *opaque)
823
{
824
    CharDriverState *chr = opaque;
825
    PtyCharDriver *s = chr->opaque;
826

    
827
    s->read_bytes = qemu_chr_can_read(chr);
828
    return s->read_bytes;
829
}
830

    
831
static void pty_chr_read(void *opaque)
832
{
833
    CharDriverState *chr = opaque;
834
    PtyCharDriver *s = chr->opaque;
835
    int size, len;
836
    uint8_t buf[1024];
837

    
838
    len = sizeof(buf);
839
    if (len > s->read_bytes)
840
        len = s->read_bytes;
841
    if (len == 0)
842
        return;
843
    size = read(s->fd, buf, len);
844
    if ((size == -1 && errno == EIO) ||
845
        (size == 0)) {
846
        pty_chr_state(chr, 0);
847
        return;
848
    }
849
    if (size > 0) {
850
        pty_chr_state(chr, 1);
851
        qemu_chr_read(chr, buf, size);
852
    }
853
}
854

    
855
static void pty_chr_update_read_handler(CharDriverState *chr)
856
{
857
    PtyCharDriver *s = chr->opaque;
858

    
859
    qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
860
                         pty_chr_read, NULL, chr);
861
    s->polling = 1;
862
    /*
863
     * Short timeout here: just need wait long enougth that qemu makes
864
     * it through the poll loop once.  When reconnected we want a
865
     * short timeout so we notice it almost instantly.  Otherwise
866
     * read() gives us -EIO instantly, making pty_chr_state() reset the
867
     * timeout to the normal (much longer) poll interval before the
868
     * timer triggers.
869
     */
870
    qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
871
}
872

    
873
static void pty_chr_state(CharDriverState *chr, int connected)
874
{
875
    PtyCharDriver *s = chr->opaque;
876

    
877
    if (!connected) {
878
        qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
879
        s->connected = 0;
880
        s->polling = 0;
881
        /* (re-)connect poll interval for idle guests: once per second.
882
         * We check more frequently in case the guests sends data to
883
         * the virtual device linked to our pty. */
884
        qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
885
    } else {
886
        if (!s->connected)
887
            qemu_chr_reset(chr);
888
        s->connected = 1;
889
    }
890
}
891

    
892
static void pty_chr_timer(void *opaque)
893
{
894
    struct CharDriverState *chr = opaque;
895
    PtyCharDriver *s = chr->opaque;
896

    
897
    if (s->connected)
898
        return;
899
    if (s->polling) {
900
        /* If we arrive here without polling being cleared due
901
         * read returning -EIO, then we are (re-)connected */
902
        pty_chr_state(chr, 1);
903
        return;
904
    }
905

    
906
    /* Next poll ... */
907
    pty_chr_update_read_handler(chr);
908
}
909

    
910
static void pty_chr_close(struct CharDriverState *chr)
911
{
912
    PtyCharDriver *s = chr->opaque;
913

    
914
    qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
915
    close(s->fd);
916
    qemu_free(s);
917
}
918

    
919
static CharDriverState *qemu_chr_open_pty(void)
920
{
921
    CharDriverState *chr;
922
    PtyCharDriver *s;
923
    struct termios tty;
924
    int slave_fd, len;
925
#if defined(__OpenBSD__)
926
    char pty_name[PATH_MAX];
927
#define q_ptsname(x) pty_name
928
#else
929
    char *pty_name = NULL;
930
#define q_ptsname(x) ptsname(x)
931
#endif
932

    
933
    chr = qemu_mallocz(sizeof(CharDriverState));
934
    s = qemu_mallocz(sizeof(PtyCharDriver));
935

    
936
    if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
937
        return NULL;
938
    }
939

    
940
    /* Set raw attributes on the pty. */
941
    tcgetattr(slave_fd, &tty);
942
    cfmakeraw(&tty);
943
    tcsetattr(slave_fd, TCSAFLUSH, &tty);
944
    close(slave_fd);
945

    
946
    len = strlen(q_ptsname(s->fd)) + 5;
947
    chr->filename = qemu_malloc(len);
948
    snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));
949
    fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
950

    
951
    chr->opaque = s;
952
    chr->chr_write = pty_chr_write;
953
    chr->chr_update_read_handler = pty_chr_update_read_handler;
954
    chr->chr_close = pty_chr_close;
955

    
956
    s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
957

    
958
    return chr;
959
}
960

    
961
static void tty_serial_init(int fd, int speed,
962
                            int parity, int data_bits, int stop_bits)
963
{
964
    struct termios tty;
965
    speed_t spd;
966

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

    
973
#define MARGIN 1.1
974
    if (speed <= 50 * MARGIN)
975
        spd = B50;
976
    else if (speed <= 75 * MARGIN)
977
        spd = B75;
978
    else if (speed <= 300 * MARGIN)
979
        spd = B300;
980
    else if (speed <= 600 * MARGIN)
981
        spd = B600;
982
    else if (speed <= 1200 * MARGIN)
983
        spd = B1200;
984
    else if (speed <= 2400 * MARGIN)
985
        spd = B2400;
986
    else if (speed <= 4800 * MARGIN)
987
        spd = B4800;
988
    else if (speed <= 9600 * MARGIN)
989
        spd = B9600;
990
    else if (speed <= 19200 * MARGIN)
991
        spd = B19200;
992
    else if (speed <= 38400 * MARGIN)
993
        spd = B38400;
994
    else if (speed <= 57600 * MARGIN)
995
        spd = B57600;
996
    else if (speed <= 115200 * MARGIN)
997
        spd = B115200;
998
    else
999
        spd = B115200;
1000

    
1001
    cfsetispeed(&tty, spd);
1002
    cfsetospeed(&tty, spd);
1003

    
1004
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1005
                          |INLCR|IGNCR|ICRNL|IXON);
1006
    tty.c_oflag |= OPOST;
1007
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1008
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1009
    switch(data_bits) {
1010
    default:
1011
    case 8:
1012
        tty.c_cflag |= CS8;
1013
        break;
1014
    case 7:
1015
        tty.c_cflag |= CS7;
1016
        break;
1017
    case 6:
1018
        tty.c_cflag |= CS6;
1019
        break;
1020
    case 5:
1021
        tty.c_cflag |= CS5;
1022
        break;
1023
    }
1024
    switch(parity) {
1025
    default:
1026
    case 'N':
1027
        break;
1028
    case 'E':
1029
        tty.c_cflag |= PARENB;
1030
        break;
1031
    case 'O':
1032
        tty.c_cflag |= PARENB | PARODD;
1033
        break;
1034
    }
1035
    if (stop_bits == 2)
1036
        tty.c_cflag |= CSTOPB;
1037

    
1038
    tcsetattr (fd, TCSANOW, &tty);
1039
}
1040

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

    
1045
    switch(cmd) {
1046
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1047
        {
1048
            QEMUSerialSetParams *ssp = arg;
1049
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1050
                            ssp->data_bits, ssp->stop_bits);
1051
        }
1052
        break;
1053
    case CHR_IOCTL_SERIAL_SET_BREAK:
1054
        {
1055
            int enable = *(int *)arg;
1056
            if (enable)
1057
                tcsendbreak(s->fd_in, 1);
1058
        }
1059
        break;
1060
    case CHR_IOCTL_SERIAL_GET_TIOCM:
1061
        {
1062
            int sarg = 0;
1063
            int *targ = (int *)arg;
1064
            ioctl(s->fd_in, TIOCMGET, &sarg);
1065
            *targ = 0;
1066
            if (sarg & TIOCM_CTS)
1067
                *targ |= CHR_TIOCM_CTS;
1068
            if (sarg & TIOCM_CAR)
1069
                *targ |= CHR_TIOCM_CAR;
1070
            if (sarg & TIOCM_DSR)
1071
                *targ |= CHR_TIOCM_DSR;
1072
            if (sarg & TIOCM_RI)
1073
                *targ |= CHR_TIOCM_RI;
1074
            if (sarg & TIOCM_DTR)
1075
                *targ |= CHR_TIOCM_DTR;
1076
            if (sarg & TIOCM_RTS)
1077
                *targ |= CHR_TIOCM_RTS;
1078
        }
1079
        break;
1080
    case CHR_IOCTL_SERIAL_SET_TIOCM:
1081
        {
1082
            int sarg = *(int *)arg;
1083
            int targ = 0;
1084
            ioctl(s->fd_in, TIOCMGET, &targ);
1085
            targ &= ~(CHR_TIOCM_CTS | CHR_TIOCM_CAR | CHR_TIOCM_DSR
1086
                     | CHR_TIOCM_RI | CHR_TIOCM_DTR | CHR_TIOCM_RTS);
1087
            if (sarg & CHR_TIOCM_CTS)
1088
                targ |= TIOCM_CTS;
1089
            if (sarg & CHR_TIOCM_CAR)
1090
                targ |= TIOCM_CAR;
1091
            if (sarg & CHR_TIOCM_DSR)
1092
                targ |= TIOCM_DSR;
1093
            if (sarg & CHR_TIOCM_RI)
1094
                targ |= TIOCM_RI;
1095
            if (sarg & CHR_TIOCM_DTR)
1096
                targ |= TIOCM_DTR;
1097
            if (sarg & CHR_TIOCM_RTS)
1098
                targ |= TIOCM_RTS;
1099
            ioctl(s->fd_in, TIOCMSET, &targ);
1100
        }
1101
        break;
1102
    default:
1103
        return -ENOTSUP;
1104
    }
1105
    return 0;
1106
}
1107

    
1108
static CharDriverState *qemu_chr_open_tty(const char *filename)
1109
{
1110
    CharDriverState *chr;
1111
    int fd;
1112

    
1113
    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
1114
    tty_serial_init(fd, 115200, 'N', 8, 1);
1115
    chr = qemu_chr_open_fd(fd, fd);
1116
    if (!chr) {
1117
        close(fd);
1118
        return NULL;
1119
    }
1120
    chr->chr_ioctl = tty_serial_ioctl;
1121
    qemu_chr_reset(chr);
1122
    return chr;
1123
}
1124
#else  /* ! __linux__ && ! __sun__ */
1125
static CharDriverState *qemu_chr_open_pty(void)
1126
{
1127
    return NULL;
1128
}
1129
#endif /* __linux__ || __sun__ */
1130

    
1131
#if defined(__linux__)
1132
typedef struct {
1133
    int fd;
1134
    int mode;
1135
} ParallelCharDriver;
1136

    
1137
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1138
{
1139
    if (s->mode != mode) {
1140
        int m = mode;
1141
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
1142
            return 0;
1143
        s->mode = mode;
1144
    }
1145
    return 1;
1146
}
1147

    
1148
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1149
{
1150
    ParallelCharDriver *drv = chr->opaque;
1151
    int fd = drv->fd;
1152
    uint8_t b;
1153

    
1154
    switch(cmd) {
1155
    case CHR_IOCTL_PP_READ_DATA:
1156
        if (ioctl(fd, PPRDATA, &b) < 0)
1157
            return -ENOTSUP;
1158
        *(uint8_t *)arg = b;
1159
        break;
1160
    case CHR_IOCTL_PP_WRITE_DATA:
1161
        b = *(uint8_t *)arg;
1162
        if (ioctl(fd, PPWDATA, &b) < 0)
1163
            return -ENOTSUP;
1164
        break;
1165
    case CHR_IOCTL_PP_READ_CONTROL:
1166
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1167
            return -ENOTSUP;
1168
        /* Linux gives only the lowest bits, and no way to know data
1169
           direction! For better compatibility set the fixed upper
1170
           bits. */
1171
        *(uint8_t *)arg = b | 0xc0;
1172
        break;
1173
    case CHR_IOCTL_PP_WRITE_CONTROL:
1174
        b = *(uint8_t *)arg;
1175
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1176
            return -ENOTSUP;
1177
        break;
1178
    case CHR_IOCTL_PP_READ_STATUS:
1179
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1180
            return -ENOTSUP;
1181
        *(uint8_t *)arg = b;
1182
        break;
1183
    case CHR_IOCTL_PP_DATA_DIR:
1184
        if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
1185
            return -ENOTSUP;
1186
        break;
1187
    case CHR_IOCTL_PP_EPP_READ_ADDR:
1188
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1189
            struct ParallelIOArg *parg = arg;
1190
            int n = read(fd, parg->buffer, parg->count);
1191
            if (n != parg->count) {
1192
                return -EIO;
1193
            }
1194
        }
1195
        break;
1196
    case CHR_IOCTL_PP_EPP_READ:
1197
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1198
            struct ParallelIOArg *parg = arg;
1199
            int n = read(fd, parg->buffer, parg->count);
1200
            if (n != parg->count) {
1201
                return -EIO;
1202
            }
1203
        }
1204
        break;
1205
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1206
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1207
            struct ParallelIOArg *parg = arg;
1208
            int n = write(fd, parg->buffer, parg->count);
1209
            if (n != parg->count) {
1210
                return -EIO;
1211
            }
1212
        }
1213
        break;
1214
    case CHR_IOCTL_PP_EPP_WRITE:
1215
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1216
            struct ParallelIOArg *parg = arg;
1217
            int n = write(fd, parg->buffer, parg->count);
1218
            if (n != parg->count) {
1219
                return -EIO;
1220
            }
1221
        }
1222
        break;
1223
    default:
1224
        return -ENOTSUP;
1225
    }
1226
    return 0;
1227
}
1228

    
1229
static void pp_close(CharDriverState *chr)
1230
{
1231
    ParallelCharDriver *drv = chr->opaque;
1232
    int fd = drv->fd;
1233

    
1234
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1235
    ioctl(fd, PPRELEASE);
1236
    close(fd);
1237
    qemu_free(drv);
1238
}
1239

    
1240
static CharDriverState *qemu_chr_open_pp(const char *filename)
1241
{
1242
    CharDriverState *chr;
1243
    ParallelCharDriver *drv;
1244
    int fd;
1245

    
1246
    TFR(fd = open(filename, O_RDWR));
1247
    if (fd < 0)
1248
        return NULL;
1249

    
1250
    if (ioctl(fd, PPCLAIM) < 0) {
1251
        close(fd);
1252
        return NULL;
1253
    }
1254

    
1255
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
1256
    drv->fd = fd;
1257
    drv->mode = IEEE1284_MODE_COMPAT;
1258

    
1259
    chr = qemu_mallocz(sizeof(CharDriverState));
1260
    chr->chr_write = null_chr_write;
1261
    chr->chr_ioctl = pp_ioctl;
1262
    chr->chr_close = pp_close;
1263
    chr->opaque = drv;
1264

    
1265
    qemu_chr_reset(chr);
1266

    
1267
    return chr;
1268
}
1269
#endif /* __linux__ */
1270

    
1271
#if defined(__FreeBSD__)
1272
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1273
{
1274
    int fd = (int)chr->opaque;
1275
    uint8_t b;
1276

    
1277
    switch(cmd) {
1278
    case CHR_IOCTL_PP_READ_DATA:
1279
        if (ioctl(fd, PPIGDATA, &b) < 0)
1280
            return -ENOTSUP;
1281
        *(uint8_t *)arg = b;
1282
        break;
1283
    case CHR_IOCTL_PP_WRITE_DATA:
1284
        b = *(uint8_t *)arg;
1285
        if (ioctl(fd, PPISDATA, &b) < 0)
1286
            return -ENOTSUP;
1287
        break;
1288
    case CHR_IOCTL_PP_READ_CONTROL:
1289
        if (ioctl(fd, PPIGCTRL, &b) < 0)
1290
            return -ENOTSUP;
1291
        *(uint8_t *)arg = b;
1292
        break;
1293
    case CHR_IOCTL_PP_WRITE_CONTROL:
1294
        b = *(uint8_t *)arg;
1295
        if (ioctl(fd, PPISCTRL, &b) < 0)
1296
            return -ENOTSUP;
1297
        break;
1298
    case CHR_IOCTL_PP_READ_STATUS:
1299
        if (ioctl(fd, PPIGSTATUS, &b) < 0)
1300
            return -ENOTSUP;
1301
        *(uint8_t *)arg = b;
1302
        break;
1303
    default:
1304
        return -ENOTSUP;
1305
    }
1306
    return 0;
1307
}
1308

    
1309
static CharDriverState *qemu_chr_open_pp(const char *filename)
1310
{
1311
    CharDriverState *chr;
1312
    int fd;
1313

    
1314
    fd = open(filename, O_RDWR);
1315
    if (fd < 0)
1316
        return NULL;
1317

    
1318
    chr = qemu_mallocz(sizeof(CharDriverState));
1319
    chr->opaque = (void *)fd;
1320
    chr->chr_write = null_chr_write;
1321
    chr->chr_ioctl = pp_ioctl;
1322
    return chr;
1323
}
1324
#endif
1325

    
1326
#else /* _WIN32 */
1327

    
1328
typedef struct {
1329
    int max_size;
1330
    HANDLE hcom, hrecv, hsend;
1331
    OVERLAPPED orecv, osend;
1332
    BOOL fpipe;
1333
    DWORD len;
1334
} WinCharState;
1335

    
1336
#define NSENDBUF 2048
1337
#define NRECVBUF 2048
1338
#define MAXCONNECT 1
1339
#define NTIMEOUT 5000
1340

    
1341
static int win_chr_poll(void *opaque);
1342
static int win_chr_pipe_poll(void *opaque);
1343

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

    
1348
    if (s->hsend) {
1349
        CloseHandle(s->hsend);
1350
        s->hsend = NULL;
1351
    }
1352
    if (s->hrecv) {
1353
        CloseHandle(s->hrecv);
1354
        s->hrecv = NULL;
1355
    }
1356
    if (s->hcom) {
1357
        CloseHandle(s->hcom);
1358
        s->hcom = NULL;
1359
    }
1360
    if (s->fpipe)
1361
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
1362
    else
1363
        qemu_del_polling_cb(win_chr_poll, chr);
1364
}
1365

    
1366
static int win_chr_init(CharDriverState *chr, const char *filename)
1367
{
1368
    WinCharState *s = chr->opaque;
1369
    COMMCONFIG comcfg;
1370
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1371
    COMSTAT comstat;
1372
    DWORD size;
1373
    DWORD err;
1374

    
1375
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1376
    if (!s->hsend) {
1377
        fprintf(stderr, "Failed CreateEvent\n");
1378
        goto fail;
1379
    }
1380
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1381
    if (!s->hrecv) {
1382
        fprintf(stderr, "Failed CreateEvent\n");
1383
        goto fail;
1384
    }
1385

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

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

    
1399
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1400
    size = sizeof(COMMCONFIG);
1401
    GetDefaultCommConfig(filename, &comcfg, &size);
1402
    comcfg.dcb.DCBlength = sizeof(DCB);
1403
    CommConfigDialog(filename, NULL, &comcfg);
1404

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

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

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

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

    
1428
 fail:
1429
    win_chr_close(chr);
1430
    return -1;
1431
}
1432

    
1433
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1434
{
1435
    WinCharState *s = chr->opaque;
1436
    DWORD len, ret, size, err;
1437

    
1438
    len = len1;
1439
    ZeroMemory(&s->osend, sizeof(s->osend));
1440
    s->osend.hEvent = s->hsend;
1441
    while (len > 0) {
1442
        if (s->hsend)
1443
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1444
        else
1445
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
1446
        if (!ret) {
1447
            err = GetLastError();
1448
            if (err == ERROR_IO_PENDING) {
1449
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1450
                if (ret) {
1451
                    buf += size;
1452
                    len -= size;
1453
                } else {
1454
                    break;
1455
                }
1456
            } else {
1457
                break;
1458
            }
1459
        } else {
1460
            buf += size;
1461
            len -= size;
1462
        }
1463
    }
1464
    return len1 - len;
1465
}
1466

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

    
1471
    s->max_size = qemu_chr_can_read(chr);
1472
    return s->max_size;
1473
}
1474

    
1475
static void win_chr_readfile(CharDriverState *chr)
1476
{
1477
    WinCharState *s = chr->opaque;
1478
    int ret, err;
1479
    uint8_t buf[1024];
1480
    DWORD size;
1481

    
1482
    ZeroMemory(&s->orecv, sizeof(s->orecv));
1483
    s->orecv.hEvent = s->hrecv;
1484
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1485
    if (!ret) {
1486
        err = GetLastError();
1487
        if (err == ERROR_IO_PENDING) {
1488
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1489
        }
1490
    }
1491

    
1492
    if (size > 0) {
1493
        qemu_chr_read(chr, buf, size);
1494
    }
1495
}
1496

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

    
1501
    if (s->len > s->max_size)
1502
        s->len = s->max_size;
1503
    if (s->len == 0)
1504
        return;
1505

    
1506
    win_chr_readfile(chr);
1507
}
1508

    
1509
static int win_chr_poll(void *opaque)
1510
{
1511
    CharDriverState *chr = opaque;
1512
    WinCharState *s = chr->opaque;
1513
    COMSTAT status;
1514
    DWORD comerr;
1515

    
1516
    ClearCommError(s->hcom, &comerr, &status);
1517
    if (status.cbInQue > 0) {
1518
        s->len = status.cbInQue;
1519
        win_chr_read_poll(chr);
1520
        win_chr_read(chr);
1521
        return 1;
1522
    }
1523
    return 0;
1524
}
1525

    
1526
static CharDriverState *qemu_chr_open_win(const char *filename)
1527
{
1528
    CharDriverState *chr;
1529
    WinCharState *s;
1530

    
1531
    chr = qemu_mallocz(sizeof(CharDriverState));
1532
    s = qemu_mallocz(sizeof(WinCharState));
1533
    chr->opaque = s;
1534
    chr->chr_write = win_chr_write;
1535
    chr->chr_close = win_chr_close;
1536

    
1537
    if (win_chr_init(chr, filename) < 0) {
1538
        free(s);
1539
        free(chr);
1540
        return NULL;
1541
    }
1542
    qemu_chr_reset(chr);
1543
    return chr;
1544
}
1545

    
1546
static int win_chr_pipe_poll(void *opaque)
1547
{
1548
    CharDriverState *chr = opaque;
1549
    WinCharState *s = chr->opaque;
1550
    DWORD size;
1551

    
1552
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1553
    if (size > 0) {
1554
        s->len = size;
1555
        win_chr_read_poll(chr);
1556
        win_chr_read(chr);
1557
        return 1;
1558
    }
1559
    return 0;
1560
}
1561

    
1562
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
1563
{
1564
    WinCharState *s = chr->opaque;
1565
    OVERLAPPED ov;
1566
    int ret;
1567
    DWORD size;
1568
    char openname[256];
1569

    
1570
    s->fpipe = TRUE;
1571

    
1572
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1573
    if (!s->hsend) {
1574
        fprintf(stderr, "Failed CreateEvent\n");
1575
        goto fail;
1576
    }
1577
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1578
    if (!s->hrecv) {
1579
        fprintf(stderr, "Failed CreateEvent\n");
1580
        goto fail;
1581
    }
1582

    
1583
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1584
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1585
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1586
                              PIPE_WAIT,
1587
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1588
    if (s->hcom == INVALID_HANDLE_VALUE) {
1589
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1590
        s->hcom = NULL;
1591
        goto fail;
1592
    }
1593

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

    
1602
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1603
    if (!ret) {
1604
        fprintf(stderr, "Failed GetOverlappedResult\n");
1605
        if (ov.hEvent) {
1606
            CloseHandle(ov.hEvent);
1607
            ov.hEvent = NULL;
1608
        }
1609
        goto fail;
1610
    }
1611

    
1612
    if (ov.hEvent) {
1613
        CloseHandle(ov.hEvent);
1614
        ov.hEvent = NULL;
1615
    }
1616
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
1617
    return 0;
1618

    
1619
 fail:
1620
    win_chr_close(chr);
1621
    return -1;
1622
}
1623

    
1624

    
1625
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
1626
{
1627
    CharDriverState *chr;
1628
    WinCharState *s;
1629

    
1630
    chr = qemu_mallocz(sizeof(CharDriverState));
1631
    s = qemu_mallocz(sizeof(WinCharState));
1632
    chr->opaque = s;
1633
    chr->chr_write = win_chr_write;
1634
    chr->chr_close = win_chr_close;
1635

    
1636
    if (win_chr_pipe_init(chr, filename) < 0) {
1637
        free(s);
1638
        free(chr);
1639
        return NULL;
1640
    }
1641
    qemu_chr_reset(chr);
1642
    return chr;
1643
}
1644

    
1645
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
1646
{
1647
    CharDriverState *chr;
1648
    WinCharState *s;
1649

    
1650
    chr = qemu_mallocz(sizeof(CharDriverState));
1651
    s = qemu_mallocz(sizeof(WinCharState));
1652
    s->hcom = fd_out;
1653
    chr->opaque = s;
1654
    chr->chr_write = win_chr_write;
1655
    qemu_chr_reset(chr);
1656
    return chr;
1657
}
1658

    
1659
static CharDriverState *qemu_chr_open_win_con(const char *filename)
1660
{
1661
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
1662
}
1663

    
1664
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
1665
{
1666
    HANDLE fd_out;
1667

    
1668
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
1669
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1670
    if (fd_out == INVALID_HANDLE_VALUE)
1671
        return NULL;
1672

    
1673
    return qemu_chr_open_win_file(fd_out);
1674
}
1675
#endif /* !_WIN32 */
1676

    
1677
/***********************************************************/
1678
/* UDP Net console */
1679

    
1680
typedef struct {
1681
    int fd;
1682
    struct sockaddr_in daddr;
1683
    uint8_t buf[1024];
1684
    int bufcnt;
1685
    int bufptr;
1686
    int max_size;
1687
} NetCharDriver;
1688

    
1689
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1690
{
1691
    NetCharDriver *s = chr->opaque;
1692

    
1693
    return sendto(s->fd, buf, len, 0,
1694
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
1695
}
1696

    
1697
static int udp_chr_read_poll(void *opaque)
1698
{
1699
    CharDriverState *chr = opaque;
1700
    NetCharDriver *s = chr->opaque;
1701

    
1702
    s->max_size = qemu_chr_can_read(chr);
1703

    
1704
    /* If there were any stray characters in the queue process them
1705
     * first
1706
     */
1707
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1708
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1709
        s->bufptr++;
1710
        s->max_size = qemu_chr_can_read(chr);
1711
    }
1712
    return s->max_size;
1713
}
1714

    
1715
static void udp_chr_read(void *opaque)
1716
{
1717
    CharDriverState *chr = opaque;
1718
    NetCharDriver *s = chr->opaque;
1719

    
1720
    if (s->max_size == 0)
1721
        return;
1722
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
1723
    s->bufptr = s->bufcnt;
1724
    if (s->bufcnt <= 0)
1725
        return;
1726

    
1727
    s->bufptr = 0;
1728
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
1729
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
1730
        s->bufptr++;
1731
        s->max_size = qemu_chr_can_read(chr);
1732
    }
1733
}
1734

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

    
1739
    if (s->fd >= 0) {
1740
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
1741
                             udp_chr_read, NULL, chr);
1742
    }
1743
}
1744

    
1745
static CharDriverState *qemu_chr_open_udp(const char *def)
1746
{
1747
    CharDriverState *chr = NULL;
1748
    NetCharDriver *s = NULL;
1749
    int fd = -1;
1750
    struct sockaddr_in saddr;
1751

    
1752
    chr = qemu_mallocz(sizeof(CharDriverState));
1753
    s = qemu_mallocz(sizeof(NetCharDriver));
1754

    
1755
    fd = socket(PF_INET, SOCK_DGRAM, 0);
1756
    if (fd < 0) {
1757
        perror("socket(PF_INET, SOCK_DGRAM)");
1758
        goto return_err;
1759
    }
1760

    
1761
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
1762
        printf("Could not parse: %s\n", def);
1763
        goto return_err;
1764
    }
1765

    
1766
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
1767
    {
1768
        perror("bind");
1769
        goto return_err;
1770
    }
1771

    
1772
    s->fd = fd;
1773
    s->bufcnt = 0;
1774
    s->bufptr = 0;
1775
    chr->opaque = s;
1776
    chr->chr_write = udp_chr_write;
1777
    chr->chr_update_read_handler = udp_chr_update_read_handler;
1778
    return chr;
1779

    
1780
return_err:
1781
    if (chr)
1782
        free(chr);
1783
    if (s)
1784
        free(s);
1785
    if (fd >= 0)
1786
        closesocket(fd);
1787
    return NULL;
1788
}
1789

    
1790
/***********************************************************/
1791
/* TCP Net console */
1792

    
1793
typedef struct {
1794
    int fd, listen_fd;
1795
    int connected;
1796
    int max_size;
1797
    int do_telnetopt;
1798
    int do_nodelay;
1799
    int is_unix;
1800
} TCPCharDriver;
1801

    
1802
static void tcp_chr_accept(void *opaque);
1803

    
1804
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1805
{
1806
    TCPCharDriver *s = chr->opaque;
1807
    if (s->connected) {
1808
        return send_all(s->fd, buf, len);
1809
    } else {
1810
        /* XXX: indicate an error ? */
1811
        return len;
1812
    }
1813
}
1814

    
1815
static int tcp_chr_read_poll(void *opaque)
1816
{
1817
    CharDriverState *chr = opaque;
1818
    TCPCharDriver *s = chr->opaque;
1819
    if (!s->connected)
1820
        return 0;
1821
    s->max_size = qemu_chr_can_read(chr);
1822
    return s->max_size;
1823
}
1824

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

    
1840
    int i;
1841
    int j = 0;
1842

    
1843
    for (i = 0; i < *size; i++) {
1844
        if (s->do_telnetopt > 1) {
1845
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
1846
                /* Double IAC means send an IAC */
1847
                if (j != i)
1848
                    buf[j] = buf[i];
1849
                j++;
1850
                s->do_telnetopt = 1;
1851
            } else {
1852
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
1853
                    /* Handle IAC break commands by sending a serial break */
1854
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
1855
                    s->do_telnetopt++;
1856
                }
1857
                s->do_telnetopt++;
1858
            }
1859
            if (s->do_telnetopt >= 4) {
1860
                s->do_telnetopt = 1;
1861
            }
1862
        } else {
1863
            if ((unsigned char)buf[i] == IAC) {
1864
                s->do_telnetopt = 2;
1865
            } else {
1866
                if (j != i)
1867
                    buf[j] = buf[i];
1868
                j++;
1869
            }
1870
        }
1871
    }
1872
    *size = j;
1873
}
1874

    
1875
static void tcp_chr_read(void *opaque)
1876
{
1877
    CharDriverState *chr = opaque;
1878
    TCPCharDriver *s = chr->opaque;
1879
    uint8_t buf[1024];
1880
    int len, size;
1881

    
1882
    if (!s->connected || s->max_size <= 0)
1883
        return;
1884
    len = sizeof(buf);
1885
    if (len > s->max_size)
1886
        len = s->max_size;
1887
    size = recv(s->fd, buf, len, 0);
1888
    if (size == 0) {
1889
        /* connection closed */
1890
        s->connected = 0;
1891
        if (s->listen_fd >= 0) {
1892
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
1893
        }
1894
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1895
        closesocket(s->fd);
1896
        s->fd = -1;
1897
    } else if (size > 0) {
1898
        if (s->do_telnetopt)
1899
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
1900
        if (size > 0)
1901
            qemu_chr_read(chr, buf, size);
1902
    }
1903
}
1904

    
1905
static void tcp_chr_connect(void *opaque)
1906
{
1907
    CharDriverState *chr = opaque;
1908
    TCPCharDriver *s = chr->opaque;
1909

    
1910
    s->connected = 1;
1911
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
1912
                         tcp_chr_read, NULL, chr);
1913
    qemu_chr_reset(chr);
1914
}
1915

    
1916
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
1917
static void tcp_chr_telnet_init(int fd)
1918
{
1919
    char buf[3];
1920
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
1921
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
1922
    send(fd, (char *)buf, 3, 0);
1923
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
1924
    send(fd, (char *)buf, 3, 0);
1925
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
1926
    send(fd, (char *)buf, 3, 0);
1927
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
1928
    send(fd, (char *)buf, 3, 0);
1929
}
1930

    
1931
static void socket_set_nodelay(int fd)
1932
{
1933
    int val = 1;
1934
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1935
}
1936

    
1937
static void tcp_chr_accept(void *opaque)
1938
{
1939
    CharDriverState *chr = opaque;
1940
    TCPCharDriver *s = chr->opaque;
1941
    struct sockaddr_in saddr;
1942
#ifndef _WIN32
1943
    struct sockaddr_un uaddr;
1944
#endif
1945
    struct sockaddr *addr;
1946
    socklen_t len;
1947
    int fd;
1948

    
1949
    for(;;) {
1950
#ifndef _WIN32
1951
        if (s->is_unix) {
1952
            len = sizeof(uaddr);
1953
            addr = (struct sockaddr *)&uaddr;
1954
        } else
1955
#endif
1956
        {
1957
            len = sizeof(saddr);
1958
            addr = (struct sockaddr *)&saddr;
1959
        }
1960
        fd = accept(s->listen_fd, addr, &len);
1961
        if (fd < 0 && errno != EINTR) {
1962
            return;
1963
        } else if (fd >= 0) {
1964
            if (s->do_telnetopt)
1965
                tcp_chr_telnet_init(fd);
1966
            break;
1967
        }
1968
    }
1969
    socket_set_nonblock(fd);
1970
    if (s->do_nodelay)
1971
        socket_set_nodelay(fd);
1972
    s->fd = fd;
1973
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
1974
    tcp_chr_connect(chr);
1975
}
1976

    
1977
static void tcp_chr_close(CharDriverState *chr)
1978
{
1979
    TCPCharDriver *s = chr->opaque;
1980
    if (s->fd >= 0)
1981
        closesocket(s->fd);
1982
    if (s->listen_fd >= 0)
1983
        closesocket(s->listen_fd);
1984
    qemu_free(s);
1985
}
1986

    
1987
static CharDriverState *qemu_chr_open_tcp(const char *host_str,
1988
                                          int is_telnet,
1989
                                          int is_unix)
1990
{
1991
    CharDriverState *chr = NULL;
1992
    TCPCharDriver *s = NULL;
1993
    int fd = -1, offset = 0;
1994
    int is_listen = 0;
1995
    int is_waitconnect = 1;
1996
    int do_nodelay = 0;
1997
    const char *ptr;
1998

    
1999
    ptr = host_str;
2000
    while((ptr = strchr(ptr,','))) {
2001
        ptr++;
2002
        if (!strncmp(ptr,"server",6)) {
2003
            is_listen = 1;
2004
        } else if (!strncmp(ptr,"nowait",6)) {
2005
            is_waitconnect = 0;
2006
        } else if (!strncmp(ptr,"nodelay",6)) {
2007
            do_nodelay = 1;
2008
        } else if (!strncmp(ptr,"to=",3)) {
2009
            /* nothing, inet_listen() parses this one */;
2010
        } else if (!strncmp(ptr,"ipv4",4)) {
2011
            /* nothing, inet_connect() and inet_listen() parse this one */;
2012
        } else if (!strncmp(ptr,"ipv6",4)) {
2013
            /* nothing, inet_connect() and inet_listen() parse this one */;
2014
        } else {
2015
            printf("Unknown option: %s\n", ptr);
2016
            goto fail;
2017
        }
2018
    }
2019
    if (!is_listen)
2020
        is_waitconnect = 0;
2021

    
2022
    chr = qemu_mallocz(sizeof(CharDriverState));
2023
    s = qemu_mallocz(sizeof(TCPCharDriver));
2024

    
2025
    if (is_listen) {
2026
        chr->filename = qemu_malloc(256);
2027
        if (is_unix) {
2028
            pstrcpy(chr->filename, 256, "unix:");
2029
        } else if (is_telnet) {
2030
            pstrcpy(chr->filename, 256, "telnet:");
2031
        } else {
2032
            pstrcpy(chr->filename, 256, "tcp:");
2033
        }
2034
        offset = strlen(chr->filename);
2035
    }
2036
    if (is_unix) {
2037
        if (is_listen) {
2038
            fd = unix_listen(host_str, chr->filename + offset, 256 - offset);
2039
        } else {
2040
            fd = unix_connect(host_str);
2041
        }
2042
    } else {
2043
        if (is_listen) {
2044
            fd = inet_listen(host_str, chr->filename + offset, 256 - offset,
2045
                             SOCK_STREAM, 0);
2046
        } else {
2047
            fd = inet_connect(host_str, SOCK_STREAM);
2048
        }
2049
    }
2050
    if (fd < 0)
2051
        goto fail;
2052

    
2053
    if (!is_waitconnect)
2054
        socket_set_nonblock(fd);
2055

    
2056
    s->connected = 0;
2057
    s->fd = -1;
2058
    s->listen_fd = -1;
2059
    s->is_unix = is_unix;
2060
    s->do_nodelay = do_nodelay && !is_unix;
2061

    
2062
    chr->opaque = s;
2063
    chr->chr_write = tcp_chr_write;
2064
    chr->chr_close = tcp_chr_close;
2065

    
2066
    if (is_listen) {
2067
        s->listen_fd = fd;
2068
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2069
        if (is_telnet)
2070
            s->do_telnetopt = 1;
2071
    } else {
2072
        s->connected = 1;
2073
        s->fd = fd;
2074
        socket_set_nodelay(fd);
2075
        tcp_chr_connect(chr);
2076
    }
2077

    
2078
    if (is_listen && is_waitconnect) {
2079
        printf("QEMU waiting for connection on: %s\n",
2080
               chr->filename ? chr->filename : host_str);
2081
        tcp_chr_accept(chr);
2082
        socket_set_nonblock(s->listen_fd);
2083
    }
2084

    
2085
    return chr;
2086
 fail:
2087
    if (fd >= 0)
2088
        closesocket(fd);
2089
    qemu_free(s);
2090
    qemu_free(chr);
2091
    return NULL;
2092
}
2093

    
2094
CharDriverState *qemu_chr_open(const char *label, const char *filename, void (*init)(struct CharDriverState *s))
2095
{
2096
    const char *p;
2097
    CharDriverState *chr;
2098

    
2099
    if (!strcmp(filename, "vc")) {
2100
        chr = text_console_init(0);
2101
    } else
2102
    if (strstart(filename, "vc:", &p)) {
2103
        chr = text_console_init(p);
2104
    } else
2105
    if (!strcmp(filename, "null")) {
2106
        chr = qemu_chr_open_null();
2107
    } else
2108
    if (strstart(filename, "tcp:", &p)) {
2109
        chr = qemu_chr_open_tcp(p, 0, 0);
2110
    } else
2111
    if (strstart(filename, "telnet:", &p)) {
2112
        chr = qemu_chr_open_tcp(p, 1, 0);
2113
    } else
2114
    if (strstart(filename, "udp:", &p)) {
2115
        chr = qemu_chr_open_udp(p);
2116
    } else
2117
    if (strstart(filename, "mon:", &p)) {
2118
        chr = qemu_chr_open(label, p, NULL);
2119
        if (chr) {
2120
            chr = qemu_chr_open_mux(chr);
2121
            monitor_init(chr, !nographic);
2122
        } else {
2123
            printf("Unable to open driver: %s\n", p);
2124
        }
2125
    } else if (!strcmp(filename, "msmouse")) {
2126
        chr = qemu_chr_open_msmouse();
2127
    } else
2128
#ifndef _WIN32
2129
    if (strstart(filename, "unix:", &p)) {
2130
        chr = qemu_chr_open_tcp(p, 0, 1);
2131
    } else if (strstart(filename, "file:", &p)) {
2132
        chr = qemu_chr_open_file_out(p);
2133
    } else if (strstart(filename, "pipe:", &p)) {
2134
        chr = qemu_chr_open_pipe(p);
2135
    } else if (!strcmp(filename, "pty")) {
2136
        chr = qemu_chr_open_pty();
2137
    } else if (!strcmp(filename, "stdio")) {
2138
        chr = qemu_chr_open_stdio();
2139
    } else
2140
#if defined(__linux__)
2141
    if (strstart(filename, "/dev/parport", NULL)) {
2142
        chr = qemu_chr_open_pp(filename);
2143
    } else
2144
#elif defined(__FreeBSD__)
2145
    if (strstart(filename, "/dev/ppi", NULL)) {
2146
        chr = qemu_chr_open_pp(filename);
2147
    } else
2148
#endif
2149
#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2150
    || defined(__NetBSD__) || defined(__OpenBSD__)
2151
    if (strstart(filename, "/dev/", NULL)) {
2152
        chr = qemu_chr_open_tty(filename);
2153
    } else
2154
#endif
2155
#else /* !_WIN32 */
2156
    if (strstart(filename, "COM", NULL)) {
2157
        chr = qemu_chr_open_win(filename);
2158
    } else
2159
    if (strstart(filename, "pipe:", &p)) {
2160
        chr = qemu_chr_open_win_pipe(p);
2161
    } else
2162
    if (strstart(filename, "con:", NULL)) {
2163
        chr = qemu_chr_open_win_con(filename);
2164
    } else
2165
    if (strstart(filename, "file:", &p)) {
2166
        chr = qemu_chr_open_win_file_out(p);
2167
    } else
2168
#endif
2169
#ifdef CONFIG_BRLAPI
2170
    if (!strcmp(filename, "braille")) {
2171
        chr = chr_baum_init();
2172
    } else
2173
#endif
2174
    {
2175
        chr = NULL;
2176
    }
2177

    
2178
    if (chr) {
2179
        if (!chr->filename)
2180
            chr->filename = qemu_strdup(filename);
2181
        chr->init = init;
2182
        chr->label = qemu_strdup(label);
2183
        TAILQ_INSERT_TAIL(&chardevs, chr, next);
2184
    }
2185
    return chr;
2186
}
2187

    
2188
void qemu_chr_close(CharDriverState *chr)
2189
{
2190
    TAILQ_REMOVE(&chardevs, chr, next);
2191
    if (chr->chr_close)
2192
        chr->chr_close(chr);
2193
    qemu_free(chr->filename);
2194
    qemu_free(chr->label);
2195
    qemu_free(chr);
2196
}
2197

    
2198
void qemu_chr_info(void)
2199
{
2200
    CharDriverState *chr;
2201

    
2202
    TAILQ_FOREACH(chr, &chardevs, next) {
2203
        term_printf("%s: filename=%s\n", chr->label, chr->filename);
2204
    }
2205
}