Statistics
| Branch: | Revision:

root / net.c @ 7a9f6e4a

History | View | Annotate | Download (44.5 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 "audio/audio.h"
31

    
32
#include <unistd.h>
33
#include <fcntl.h>
34
#include <signal.h>
35
#include <time.h>
36
#include <errno.h>
37
#include <sys/time.h>
38
#include <zlib.h>
39

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

    
75
/* For the benefit of older linux systems which don't supply it,
76
   we use a local copy of hpet.h. */
77
/* #include <linux/hpet.h> */
78
#include "hpet.h"
79

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

    
101
#include "qemu_socket.h"
102

    
103
#if defined(CONFIG_SLIRP)
104
#include "libslirp.h"
105
#endif
106

    
107
#if defined(__OpenBSD__)
108
#include <util.h>
109
#endif
110

    
111
#if defined(CONFIG_VDE)
112
#include <libvdeplug.h>
113
#endif
114

    
115
#ifdef _WIN32
116
#include <malloc.h>
117
#include <sys/timeb.h>
118
#include <mmsystem.h>
119
#define getopt_long_only getopt_long
120
#define memalign(align, size) malloc(size)
121
#endif
122

    
123
static VLANState *first_vlan;
124

    
125
/***********************************************************/
126
/* network device redirectors */
127

    
128
#if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
129
static void hex_dump(FILE *f, const uint8_t *buf, int size)
130
{
131
    int len, i, j, c;
132

    
133
    for(i=0;i<size;i+=16) {
134
        len = size - i;
135
        if (len > 16)
136
            len = 16;
137
        fprintf(f, "%08x ", i);
138
        for(j=0;j<16;j++) {
139
            if (j < len)
140
                fprintf(f, " %02x", buf[i+j]);
141
            else
142
                fprintf(f, "   ");
143
        }
144
        fprintf(f, " ");
145
        for(j=0;j<len;j++) {
146
            c = buf[i+j];
147
            if (c < ' ' || c > '~')
148
                c = '.';
149
            fprintf(f, "%c", c);
150
        }
151
        fprintf(f, "\n");
152
    }
153
}
154
#endif
155

    
156
static int parse_macaddr(uint8_t *macaddr, const char *p)
157
{
158
    int i;
159
    char *last_char;
160
    long int offset;
161

    
162
    errno = 0;
163
    offset = strtol(p, &last_char, 0);    
164
    if (0 == errno && '\0' == *last_char &&
165
            offset >= 0 && offset <= 0xFFFFFF) {
166
        macaddr[3] = (offset & 0xFF0000) >> 16;
167
        macaddr[4] = (offset & 0xFF00) >> 8;
168
        macaddr[5] = offset & 0xFF;
169
        return 0;
170
    } else {
171
        for(i = 0; i < 6; i++) {
172
            macaddr[i] = strtol(p, (char **)&p, 16);
173
            if (i == 5) {
174
                if (*p != '\0')
175
                    return -1;
176
            } else {
177
                if (*p != ':' && *p != '-')
178
                    return -1;
179
                p++;
180
            }
181
        }
182
        return 0;    
183
    }
184

    
185
    return -1;
186
}
187

    
188
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
189
{
190
    const char *p, *p1;
191
    int len;
192
    p = *pp;
193
    p1 = strchr(p, sep);
194
    if (!p1)
195
        return -1;
196
    len = p1 - p;
197
    p1++;
198
    if (buf_size > 0) {
199
        if (len > buf_size - 1)
200
            len = buf_size - 1;
201
        memcpy(buf, p, len);
202
        buf[len] = '\0';
203
    }
204
    *pp = p1;
205
    return 0;
206
}
207

    
208
int parse_host_src_port(struct sockaddr_in *haddr,
209
                        struct sockaddr_in *saddr,
210
                        const char *input_str)
211
{
212
    char *str = strdup(input_str);
213
    char *host_str = str;
214
    char *src_str;
215
    const char *src_str2;
216
    char *ptr;
217

    
218
    /*
219
     * Chop off any extra arguments at the end of the string which
220
     * would start with a comma, then fill in the src port information
221
     * if it was provided else use the "any address" and "any port".
222
     */
223
    if ((ptr = strchr(str,',')))
224
        *ptr = '\0';
225

    
226
    if ((src_str = strchr(input_str,'@'))) {
227
        *src_str = '\0';
228
        src_str++;
229
    }
230

    
231
    if (parse_host_port(haddr, host_str) < 0)
232
        goto fail;
233

    
234
    src_str2 = src_str;
235
    if (!src_str || *src_str == '\0')
236
        src_str2 = ":0";
237

    
238
    if (parse_host_port(saddr, src_str2) < 0)
239
        goto fail;
240

    
241
    free(str);
242
    return(0);
243

    
244
fail:
245
    free(str);
246
    return -1;
247
}
248

    
249
int parse_host_port(struct sockaddr_in *saddr, const char *str)
250
{
251
    char buf[512];
252
    struct hostent *he;
253
    const char *p, *r;
254
    int port;
255

    
256
    p = str;
257
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
258
        return -1;
259
    saddr->sin_family = AF_INET;
260
    if (buf[0] == '\0') {
261
        saddr->sin_addr.s_addr = 0;
262
    } else {
263
        if (qemu_isdigit(buf[0])) {
264
            if (!inet_aton(buf, &saddr->sin_addr))
265
                return -1;
266
        } else {
267
            if ((he = gethostbyname(buf)) == NULL)
268
                return - 1;
269
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
270
        }
271
    }
272
    port = strtol(p, (char **)&r, 0);
273
    if (r == p)
274
        return -1;
275
    saddr->sin_port = htons(port);
276
    return 0;
277
}
278

    
279
#if !defined(_WIN32) && 0
280
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
281
{
282
    const char *p;
283
    int len;
284

    
285
    len = MIN(108, strlen(str));
286
    p = strchr(str, ',');
287
    if (p)
288
        len = MIN(len, p - str);
289

    
290
    memset(uaddr, 0, sizeof(*uaddr));
291

    
292
    uaddr->sun_family = AF_UNIX;
293
    memcpy(uaddr->sun_path, str, len);
294

    
295
    return 0;
296
}
297
#endif
298

    
299
void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6])
300
{
301
    snprintf(vc->info_str, sizeof(vc->info_str),
302
             "macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
303
             macaddr[0], macaddr[1], macaddr[2],
304
             macaddr[3], macaddr[4], macaddr[5]);
305
}
306

    
307
static char *assign_name(VLANClientState *vc1, const char *model)
308
{
309
    VLANState *vlan;
310
    char buf[256];
311
    int id = 0;
312

    
313
    for (vlan = first_vlan; vlan; vlan = vlan->next) {
314
        VLANClientState *vc;
315

    
316
        for (vc = vlan->first_client; vc; vc = vc->next)
317
            if (vc != vc1 && strcmp(vc->model, model) == 0)
318
                id++;
319
    }
320

    
321
    snprintf(buf, sizeof(buf), "%s.%d", model, id);
322

    
323
    return strdup(buf);
324
}
325

    
326
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
327
                                      const char *model,
328
                                      const char *name,
329
                                      IOReadHandler *fd_read,
330
                                      IOCanRWHandler *fd_can_read,
331
                                      void *opaque)
332
{
333
    VLANClientState *vc, **pvc;
334
    vc = qemu_mallocz(sizeof(VLANClientState));
335
    if (!vc)
336
        return NULL;
337
    vc->model = strdup(model);
338
    if (name)
339
        vc->name = strdup(name);
340
    else
341
        vc->name = assign_name(vc, model);
342
    vc->fd_read = fd_read;
343
    vc->fd_can_read = fd_can_read;
344
    vc->opaque = opaque;
345
    vc->vlan = vlan;
346

    
347
    vc->next = NULL;
348
    pvc = &vlan->first_client;
349
    while (*pvc != NULL)
350
        pvc = &(*pvc)->next;
351
    *pvc = vc;
352
    return vc;
353
}
354

    
355
void qemu_del_vlan_client(VLANClientState *vc)
356
{
357
    VLANClientState **pvc = &vc->vlan->first_client;
358

    
359
    while (*pvc != NULL)
360
        if (*pvc == vc) {
361
            *pvc = vc->next;
362
            free(vc->name);
363
            free(vc->model);
364
            free(vc);
365
            break;
366
        } else
367
            pvc = &(*pvc)->next;
368
}
369

    
370
int qemu_can_send_packet(VLANClientState *vc1)
371
{
372
    VLANState *vlan = vc1->vlan;
373
    VLANClientState *vc;
374

    
375
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
376
        if (vc != vc1) {
377
            if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
378
                return 1;
379
        }
380
    }
381
    return 0;
382
}
383

    
384
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
385
{
386
    VLANState *vlan = vc1->vlan;
387
    VLANClientState *vc;
388

    
389
#ifdef DEBUG_NET
390
    printf("vlan %d send:\n", vlan->id);
391
    hex_dump(stdout, buf, size);
392
#endif
393
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
394
        if (vc != vc1) {
395
            vc->fd_read(vc->opaque, buf, size);
396
        }
397
    }
398
}
399

    
400
static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
401
                               int iovcnt)
402
{
403
    uint8_t buffer[4096];
404
    size_t offset = 0;
405
    int i;
406

    
407
    for (i = 0; i < iovcnt; i++) {
408
        size_t len;
409

    
410
        len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
411
        memcpy(buffer + offset, iov[i].iov_base, len);
412
        offset += len;
413
    }
414

    
415
    vc->fd_read(vc->opaque, buffer, offset);
416

    
417
    return offset;
418
}
419

    
420
ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
421
                          int iovcnt)
422
{
423
    VLANState *vlan = vc1->vlan;
424
    VLANClientState *vc;
425
    ssize_t max_len = 0;
426

    
427
    for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
428
        ssize_t len = 0;
429

    
430
        if (vc == vc1)
431
            continue;
432

    
433
        if (vc->fd_readv)
434
            len = vc->fd_readv(vc->opaque, iov, iovcnt);
435
        else if (vc->fd_read)
436
            len = vc_sendv_compat(vc, iov, iovcnt);
437

    
438
        max_len = MAX(max_len, len);
439
    }
440

    
441
    return max_len;
442
}
443

    
444
#if defined(CONFIG_SLIRP)
445

    
446
/* slirp network adapter */
447

    
448
static int slirp_inited;
449
static VLANClientState *slirp_vc;
450

    
451
int slirp_can_output(void)
452
{
453
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
454
}
455

    
456
void slirp_output(const uint8_t *pkt, int pkt_len)
457
{
458
#ifdef DEBUG_SLIRP
459
    printf("slirp output:\n");
460
    hex_dump(stdout, pkt, pkt_len);
461
#endif
462
    if (!slirp_vc)
463
        return;
464
    qemu_send_packet(slirp_vc, pkt, pkt_len);
465
}
466

    
467
int slirp_is_inited(void)
468
{
469
    return slirp_inited;
470
}
471

    
472
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
473
{
474
#ifdef DEBUG_SLIRP
475
    printf("slirp input:\n");
476
    hex_dump(stdout, buf, size);
477
#endif
478
    slirp_input(buf, size);
479
}
480

    
481
static int net_slirp_init(VLANState *vlan, const char *model, const char *name)
482
{
483
    if (!slirp_inited) {
484
        slirp_inited = 1;
485
        slirp_init();
486
    }
487
    slirp_vc = qemu_new_vlan_client(vlan, model, name,
488
                                    slirp_receive, NULL, NULL);
489
    slirp_vc->info_str[0] = '\0';
490
    return 0;
491
}
492

    
493
void net_slirp_redir(const char *redir_str)
494
{
495
    int is_udp;
496
    char buf[256], *r;
497
    const char *p;
498
    struct in_addr guest_addr;
499
    int host_port, guest_port;
500

    
501
    if (!slirp_inited) {
502
        slirp_inited = 1;
503
        slirp_init();
504
    }
505

    
506
    p = redir_str;
507
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
508
        goto fail;
509
    if (!strcmp(buf, "tcp")) {
510
        is_udp = 0;
511
    } else if (!strcmp(buf, "udp")) {
512
        is_udp = 1;
513
    } else {
514
        goto fail;
515
    }
516

    
517
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
518
        goto fail;
519
    host_port = strtol(buf, &r, 0);
520
    if (r == buf)
521
        goto fail;
522

    
523
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
524
        goto fail;
525
    if (buf[0] == '\0') {
526
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
527
    }
528
    if (!inet_aton(buf, &guest_addr))
529
        goto fail;
530

    
531
    guest_port = strtol(p, &r, 0);
532
    if (r == p)
533
        goto fail;
534

    
535
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
536
        fprintf(stderr, "qemu: could not set up redirection\n");
537
        exit(1);
538
    }
539
    return;
540
 fail:
541
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
542
    exit(1);
543
}
544

    
545
#ifndef _WIN32
546

    
547
static char smb_dir[1024];
548

    
549
static void erase_dir(char *dir_name)
550
{
551
    DIR *d;
552
    struct dirent *de;
553
    char filename[1024];
554

    
555
    /* erase all the files in the directory */
556
    if ((d = opendir(dir_name)) != 0) {
557
        for(;;) {
558
            de = readdir(d);
559
            if (!de)
560
                break;
561
            if (strcmp(de->d_name, ".") != 0 &&
562
                strcmp(de->d_name, "..") != 0) {
563
                snprintf(filename, sizeof(filename), "%s/%s",
564
                         smb_dir, de->d_name);
565
                if (unlink(filename) != 0)  /* is it a directory? */
566
                    erase_dir(filename);
567
            }
568
        }
569
        closedir(d);
570
        rmdir(dir_name);
571
    }
572
}
573

    
574
/* automatic user mode samba server configuration */
575
static void smb_exit(void)
576
{
577
    erase_dir(smb_dir);
578
}
579

    
580
/* automatic user mode samba server configuration */
581
void net_slirp_smb(const char *exported_dir)
582
{
583
    char smb_conf[1024];
584
    char smb_cmdline[1024];
585
    FILE *f;
586

    
587
    if (!slirp_inited) {
588
        slirp_inited = 1;
589
        slirp_init();
590
    }
591

    
592
    /* XXX: better tmp dir construction */
593
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
594
    if (mkdir(smb_dir, 0700) < 0) {
595
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
596
        exit(1);
597
    }
598
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
599

    
600
    f = fopen(smb_conf, "w");
601
    if (!f) {
602
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
603
        exit(1);
604
    }
605
    fprintf(f,
606
            "[global]\n"
607
            "private dir=%s\n"
608
            "smb ports=0\n"
609
            "socket address=127.0.0.1\n"
610
            "pid directory=%s\n"
611
            "lock directory=%s\n"
612
            "log file=%s/log.smbd\n"
613
            "smb passwd file=%s/smbpasswd\n"
614
            "security = share\n"
615
            "[qemu]\n"
616
            "path=%s\n"
617
            "read only=no\n"
618
            "guest ok=yes\n",
619
            smb_dir,
620
            smb_dir,
621
            smb_dir,
622
            smb_dir,
623
            smb_dir,
624
            exported_dir
625
            );
626
    fclose(f);
627
    atexit(smb_exit);
628

    
629
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
630
             SMBD_COMMAND, smb_conf);
631

    
632
    slirp_add_exec(0, smb_cmdline, 4, 139);
633
}
634

    
635
#endif /* !defined(_WIN32) */
636
void do_info_slirp(void)
637
{
638
    slirp_stats();
639
}
640

    
641
#endif /* CONFIG_SLIRP */
642

    
643
#if !defined(_WIN32)
644

    
645
typedef struct TAPState {
646
    VLANClientState *vc;
647
    int fd;
648
    char down_script[1024];
649
} TAPState;
650

    
651
#ifdef HAVE_IOVEC
652
static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
653
                               int iovcnt)
654
{
655
    TAPState *s = opaque;
656
    ssize_t len;
657

    
658
    do {
659
        len = writev(s->fd, iov, iovcnt);
660
    } while (len == -1 && (errno == EINTR || errno == EAGAIN));
661

    
662
    return len;
663
}
664
#endif
665

    
666
static void tap_receive(void *opaque, const uint8_t *buf, int size)
667
{
668
    TAPState *s = opaque;
669
    int ret;
670
    for(;;) {
671
        ret = write(s->fd, buf, size);
672
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
673
        } else {
674
            break;
675
        }
676
    }
677
}
678

    
679
static void tap_send(void *opaque)
680
{
681
    TAPState *s = opaque;
682
    uint8_t buf[4096];
683
    int size;
684

    
685
#ifdef __sun__
686
    struct strbuf sbuf;
687
    int f = 0;
688
    sbuf.maxlen = sizeof(buf);
689
    sbuf.buf = buf;
690
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
691
#else
692
    size = read(s->fd, buf, sizeof(buf));
693
#endif
694
    if (size > 0) {
695
        qemu_send_packet(s->vc, buf, size);
696
    }
697
}
698

    
699
/* fd support */
700

    
701
static TAPState *net_tap_fd_init(VLANState *vlan,
702
                                 const char *model,
703
                                 const char *name,
704
                                 int fd)
705
{
706
    TAPState *s;
707

    
708
    s = qemu_mallocz(sizeof(TAPState));
709
    if (!s)
710
        return NULL;
711
    s->fd = fd;
712
    s->vc = qemu_new_vlan_client(vlan, model, name, tap_receive, NULL, s);
713
#ifdef HAVE_IOVEC
714
    s->vc->fd_readv = tap_receive_iov;
715
#endif
716
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
717
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
718
    return s;
719
}
720

    
721
#if defined (_BSD) || defined (__FreeBSD_kernel__)
722
static int tap_open(char *ifname, int ifname_size)
723
{
724
    int fd;
725
    char *dev;
726
    struct stat s;
727

    
728
    TFR(fd = open("/dev/tap", O_RDWR));
729
    if (fd < 0) {
730
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
731
        return -1;
732
    }
733

    
734
    fstat(fd, &s);
735
    dev = devname(s.st_rdev, S_IFCHR);
736
    pstrcpy(ifname, ifname_size, dev);
737

    
738
    fcntl(fd, F_SETFL, O_NONBLOCK);
739
    return fd;
740
}
741
#elif defined(__sun__)
742
#define TUNNEWPPA       (('T'<<16) | 0x0001)
743
/*
744
 * Allocate TAP device, returns opened fd.
745
 * Stores dev name in the first arg(must be large enough).
746
 */
747
int tap_alloc(char *dev, size_t dev_size)
748
{
749
    int tap_fd, if_fd, ppa = -1;
750
    static int ip_fd = 0;
751
    char *ptr;
752

    
753
    static int arp_fd = 0;
754
    int ip_muxid, arp_muxid;
755
    struct strioctl  strioc_if, strioc_ppa;
756
    int link_type = I_PLINK;;
757
    struct lifreq ifr;
758
    char actual_name[32] = "";
759

    
760
    memset(&ifr, 0x0, sizeof(ifr));
761

    
762
    if( *dev ){
763
       ptr = dev;
764
       while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
765
       ppa = atoi(ptr);
766
    }
767

    
768
    /* Check if IP device was opened */
769
    if( ip_fd )
770
       close(ip_fd);
771

    
772
    TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
773
    if (ip_fd < 0) {
774
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
775
       return -1;
776
    }
777

    
778
    TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
779
    if (tap_fd < 0) {
780
       syslog(LOG_ERR, "Can't open /dev/tap");
781
       return -1;
782
    }
783

    
784
    /* Assign a new PPA and get its unit number. */
785
    strioc_ppa.ic_cmd = TUNNEWPPA;
786
    strioc_ppa.ic_timout = 0;
787
    strioc_ppa.ic_len = sizeof(ppa);
788
    strioc_ppa.ic_dp = (char *)&ppa;
789
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
790
       syslog (LOG_ERR, "Can't assign new interface");
791

    
792
    TFR(if_fd = open("/dev/tap", O_RDWR, 0));
793
    if (if_fd < 0) {
794
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
795
       return -1;
796
    }
797
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
798
       syslog(LOG_ERR, "Can't push IP module");
799
       return -1;
800
    }
801

    
802
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
803
        syslog(LOG_ERR, "Can't get flags\n");
804

    
805
    snprintf (actual_name, 32, "tap%d", ppa);
806
    pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
807

    
808
    ifr.lifr_ppa = ppa;
809
    /* Assign ppa according to the unit number returned by tun device */
810

    
811
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
812
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
813
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
814
        syslog (LOG_ERR, "Can't get flags\n");
815
    /* Push arp module to if_fd */
816
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
817
        syslog (LOG_ERR, "Can't push ARP module (2)");
818

    
819
    /* Push arp module to ip_fd */
820
    if (ioctl (ip_fd, I_POP, NULL) < 0)
821
        syslog (LOG_ERR, "I_POP failed\n");
822
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
823
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
824
    /* Open arp_fd */
825
    TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
826
    if (arp_fd < 0)
827
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
828

    
829
    /* Set ifname to arp */
830
    strioc_if.ic_cmd = SIOCSLIFNAME;
831
    strioc_if.ic_timout = 0;
832
    strioc_if.ic_len = sizeof(ifr);
833
    strioc_if.ic_dp = (char *)&ifr;
834
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
835
        syslog (LOG_ERR, "Can't set ifname to arp\n");
836
    }
837

    
838
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
839
       syslog(LOG_ERR, "Can't link TAP device to IP");
840
       return -1;
841
    }
842

    
843
    if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
844
        syslog (LOG_ERR, "Can't link TAP device to ARP");
845

    
846
    close (if_fd);
847

    
848
    memset(&ifr, 0x0, sizeof(ifr));
849
    pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
850
    ifr.lifr_ip_muxid  = ip_muxid;
851
    ifr.lifr_arp_muxid = arp_muxid;
852

    
853
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
854
    {
855
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
856
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
857
      syslog (LOG_ERR, "Can't set multiplexor id");
858
    }
859

    
860
    snprintf(dev, dev_size, "tap%d", ppa);
861
    return tap_fd;
862
}
863

    
864
static int tap_open(char *ifname, int ifname_size)
865
{
866
    char  dev[10]="";
867
    int fd;
868
    if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
869
       fprintf(stderr, "Cannot allocate TAP device\n");
870
       return -1;
871
    }
872
    pstrcpy(ifname, ifname_size, dev);
873
    fcntl(fd, F_SETFL, O_NONBLOCK);
874
    return fd;
875
}
876
#elif defined (_AIX)
877
static int tap_open(char *ifname, int ifname_size)
878
{
879
    fprintf (stderr, "no tap on AIX\n");
880
    return -1;
881
}
882
#else
883
static int tap_open(char *ifname, int ifname_size)
884
{
885
    struct ifreq ifr;
886
    int fd, ret;
887

    
888
    TFR(fd = open("/dev/net/tun", O_RDWR));
889
    if (fd < 0) {
890
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
891
        return -1;
892
    }
893
    memset(&ifr, 0, sizeof(ifr));
894
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
895
    if (ifname[0] != '\0')
896
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
897
    else
898
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
899
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
900
    if (ret != 0) {
901
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
902
        close(fd);
903
        return -1;
904
    }
905
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
906
    fcntl(fd, F_SETFL, O_NONBLOCK);
907
    return fd;
908
}
909
#endif
910

    
911
static int launch_script(const char *setup_script, const char *ifname, int fd)
912
{
913
    int pid, status;
914
    char *args[3];
915
    char **parg;
916

    
917
        /* try to launch network script */
918
        pid = fork();
919
        if (pid >= 0) {
920
            if (pid == 0) {
921
                int open_max = sysconf (_SC_OPEN_MAX), i;
922
                for (i = 0; i < open_max; i++)
923
                    if (i != STDIN_FILENO &&
924
                        i != STDOUT_FILENO &&
925
                        i != STDERR_FILENO &&
926
                        i != fd)
927
                        close(i);
928

    
929
                parg = args;
930
                *parg++ = (char *)setup_script;
931
                *parg++ = (char *)ifname;
932
                *parg++ = NULL;
933
                execv(setup_script, args);
934
                _exit(1);
935
            }
936
            while (waitpid(pid, &status, 0) != pid);
937
            if (!WIFEXITED(status) ||
938
                WEXITSTATUS(status) != 0) {
939
                fprintf(stderr, "%s: could not launch network script\n",
940
                        setup_script);
941
                return -1;
942
            }
943
        }
944
    return 0;
945
}
946

    
947
static int net_tap_init(VLANState *vlan, const char *model,
948
                        const char *name, const char *ifname1,
949
                        const char *setup_script, const char *down_script)
950
{
951
    TAPState *s;
952
    int fd;
953
    char ifname[128];
954

    
955
    if (ifname1 != NULL)
956
        pstrcpy(ifname, sizeof(ifname), ifname1);
957
    else
958
        ifname[0] = '\0';
959
    TFR(fd = tap_open(ifname, sizeof(ifname)));
960
    if (fd < 0)
961
        return -1;
962

    
963
    if (!setup_script || !strcmp(setup_script, "no"))
964
        setup_script = "";
965
    if (setup_script[0] != '\0') {
966
        if (launch_script(setup_script, ifname, fd))
967
            return -1;
968
    }
969
    s = net_tap_fd_init(vlan, model, name, fd);
970
    if (!s)
971
        return -1;
972
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
973
             "ifname=%s,script=%s,downscript=%s",
974
             ifname, setup_script, down_script);
975
    if (down_script && strcmp(down_script, "no"))
976
        snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
977
    return 0;
978
}
979

    
980
#endif /* !_WIN32 */
981

    
982
#if defined(CONFIG_VDE)
983
typedef struct VDEState {
984
    VLANClientState *vc;
985
    VDECONN *vde;
986
} VDEState;
987

    
988
static void vde_to_qemu(void *opaque)
989
{
990
    VDEState *s = opaque;
991
    uint8_t buf[4096];
992
    int size;
993

    
994
    size = vde_recv(s->vde, buf, sizeof(buf), 0);
995
    if (size > 0) {
996
        qemu_send_packet(s->vc, buf, size);
997
    }
998
}
999

    
1000
static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
1001
{
1002
    VDEState *s = opaque;
1003
    int ret;
1004
    for(;;) {
1005
        ret = vde_send(s->vde, buf, size, 0);
1006
        if (ret < 0 && errno == EINTR) {
1007
        } else {
1008
            break;
1009
        }
1010
    }
1011
}
1012

    
1013
static int net_vde_init(VLANState *vlan, const char *model,
1014
                        const char *name, const char *sock,
1015
                        int port, const char *group, int mode)
1016
{
1017
    VDEState *s;
1018
    char *init_group = strlen(group) ? (char *)group : NULL;
1019
    char *init_sock = strlen(sock) ? (char *)sock : NULL;
1020

    
1021
    struct vde_open_args args = {
1022
        .port = port,
1023
        .group = init_group,
1024
        .mode = mode,
1025
    };
1026

    
1027
    s = qemu_mallocz(sizeof(VDEState));
1028
    if (!s)
1029
        return -1;
1030
    s->vde = vde_open(init_sock, "QEMU", &args);
1031
    if (!s->vde){
1032
        free(s);
1033
        return -1;
1034
    }
1035
    s->vc = qemu_new_vlan_client(vlan, model, name, vde_from_qemu, NULL, s);
1036
    qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1037
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1038
             sock, vde_datafd(s->vde));
1039
    return 0;
1040
}
1041
#endif
1042

    
1043
/* network connection */
1044
typedef struct NetSocketState {
1045
    VLANClientState *vc;
1046
    int fd;
1047
    int state; /* 0 = getting length, 1 = getting data */
1048
    int index;
1049
    int packet_len;
1050
    uint8_t buf[4096];
1051
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1052
} NetSocketState;
1053

    
1054
typedef struct NetSocketListenState {
1055
    VLANState *vlan;
1056
    char *model;
1057
    char *name;
1058
    int fd;
1059
} NetSocketListenState;
1060

    
1061
/* XXX: we consider we can send the whole packet without blocking */
1062
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1063
{
1064
    NetSocketState *s = opaque;
1065
    uint32_t len;
1066
    len = htonl(size);
1067

    
1068
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1069
    send_all(s->fd, buf, size);
1070
}
1071

    
1072
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1073
{
1074
    NetSocketState *s = opaque;
1075
    sendto(s->fd, buf, size, 0,
1076
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1077
}
1078

    
1079
static void net_socket_send(void *opaque)
1080
{
1081
    NetSocketState *s = opaque;
1082
    int l, size, err;
1083
    uint8_t buf1[4096];
1084
    const uint8_t *buf;
1085

    
1086
    size = recv(s->fd, buf1, sizeof(buf1), 0);
1087
    if (size < 0) {
1088
        err = socket_error();
1089
        if (err != EWOULDBLOCK)
1090
            goto eoc;
1091
    } else if (size == 0) {
1092
        /* end of connection */
1093
    eoc:
1094
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1095
        closesocket(s->fd);
1096
        return;
1097
    }
1098
    buf = buf1;
1099
    while (size > 0) {
1100
        /* reassemble a packet from the network */
1101
        switch(s->state) {
1102
        case 0:
1103
            l = 4 - s->index;
1104
            if (l > size)
1105
                l = size;
1106
            memcpy(s->buf + s->index, buf, l);
1107
            buf += l;
1108
            size -= l;
1109
            s->index += l;
1110
            if (s->index == 4) {
1111
                /* got length */
1112
                s->packet_len = ntohl(*(uint32_t *)s->buf);
1113
                s->index = 0;
1114
                s->state = 1;
1115
            }
1116
            break;
1117
        case 1:
1118
            l = s->packet_len - s->index;
1119
            if (l > size)
1120
                l = size;
1121
            memcpy(s->buf + s->index, buf, l);
1122
            s->index += l;
1123
            buf += l;
1124
            size -= l;
1125
            if (s->index >= s->packet_len) {
1126
                qemu_send_packet(s->vc, s->buf, s->packet_len);
1127
                s->index = 0;
1128
                s->state = 0;
1129
            }
1130
            break;
1131
        }
1132
    }
1133
}
1134

    
1135
static void net_socket_send_dgram(void *opaque)
1136
{
1137
    NetSocketState *s = opaque;
1138
    int size;
1139

    
1140
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1141
    if (size < 0)
1142
        return;
1143
    if (size == 0) {
1144
        /* end of connection */
1145
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1146
        return;
1147
    }
1148
    qemu_send_packet(s->vc, s->buf, size);
1149
}
1150

    
1151
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1152
{
1153
    struct ip_mreq imr;
1154
    int fd;
1155
    int val, ret;
1156
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1157
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1158
                inet_ntoa(mcastaddr->sin_addr),
1159
                (int)ntohl(mcastaddr->sin_addr.s_addr));
1160
        return -1;
1161

    
1162
    }
1163
    fd = socket(PF_INET, SOCK_DGRAM, 0);
1164
    if (fd < 0) {
1165
        perror("socket(PF_INET, SOCK_DGRAM)");
1166
        return -1;
1167
    }
1168

    
1169
    val = 1;
1170
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1171
                   (const char *)&val, sizeof(val));
1172
    if (ret < 0) {
1173
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1174
        goto fail;
1175
    }
1176

    
1177
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1178
    if (ret < 0) {
1179
        perror("bind");
1180
        goto fail;
1181
    }
1182

    
1183
    /* Add host to multicast group */
1184
    imr.imr_multiaddr = mcastaddr->sin_addr;
1185
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
1186

    
1187
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1188
                     (const char *)&imr, sizeof(struct ip_mreq));
1189
    if (ret < 0) {
1190
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
1191
        goto fail;
1192
    }
1193

    
1194
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1195
    val = 1;
1196
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1197
                   (const char *)&val, sizeof(val));
1198
    if (ret < 0) {
1199
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1200
        goto fail;
1201
    }
1202

    
1203
    socket_set_nonblock(fd);
1204
    return fd;
1205
fail:
1206
    if (fd >= 0)
1207
        closesocket(fd);
1208
    return -1;
1209
}
1210

    
1211
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1212
                                                const char *model,
1213
                                                const char *name,
1214
                                                int fd, int is_connected)
1215
{
1216
    struct sockaddr_in saddr;
1217
    int newfd;
1218
    socklen_t saddr_len;
1219
    NetSocketState *s;
1220

    
1221
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1222
     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1223
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
1224
     */
1225

    
1226
    if (is_connected) {
1227
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1228
            /* must be bound */
1229
            if (saddr.sin_addr.s_addr==0) {
1230
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1231
                        fd);
1232
                return NULL;
1233
            }
1234
            /* clone dgram socket */
1235
            newfd = net_socket_mcast_create(&saddr);
1236
            if (newfd < 0) {
1237
                /* error already reported by net_socket_mcast_create() */
1238
                close(fd);
1239
                return NULL;
1240
            }
1241
            /* clone newfd to fd, close newfd */
1242
            dup2(newfd, fd);
1243
            close(newfd);
1244

    
1245
        } else {
1246
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1247
                    fd, strerror(errno));
1248
            return NULL;
1249
        }
1250
    }
1251

    
1252
    s = qemu_mallocz(sizeof(NetSocketState));
1253
    if (!s)
1254
        return NULL;
1255
    s->fd = fd;
1256

    
1257
    s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive_dgram, NULL, s);
1258
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1259

    
1260
    /* mcast: save bound address as dst */
1261
    if (is_connected) s->dgram_dst=saddr;
1262

    
1263
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1264
            "socket: fd=%d (%s mcast=%s:%d)",
1265
            fd, is_connected? "cloned" : "",
1266
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1267
    return s;
1268
}
1269

    
1270
static void net_socket_connect(void *opaque)
1271
{
1272
    NetSocketState *s = opaque;
1273
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1274
}
1275

    
1276
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1277
                                                 const char *model,
1278
                                                 const char *name,
1279
                                                 int fd, int is_connected)
1280
{
1281
    NetSocketState *s;
1282
    s = qemu_mallocz(sizeof(NetSocketState));
1283
    if (!s)
1284
        return NULL;
1285
    s->fd = fd;
1286
    s->vc = qemu_new_vlan_client(vlan, model, name,
1287
                                 net_socket_receive, NULL, s);
1288
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1289
             "socket: fd=%d", fd);
1290
    if (is_connected) {
1291
        net_socket_connect(s);
1292
    } else {
1293
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1294
    }
1295
    return s;
1296
}
1297

    
1298
static NetSocketState *net_socket_fd_init(VLANState *vlan,
1299
                                          const char *model, const char *name,
1300
                                          int fd, int is_connected)
1301
{
1302
    int so_type=-1, optlen=sizeof(so_type);
1303

    
1304
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1305
        (socklen_t *)&optlen)< 0) {
1306
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1307
        return NULL;
1308
    }
1309
    switch(so_type) {
1310
    case SOCK_DGRAM:
1311
        return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1312
    case SOCK_STREAM:
1313
        return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1314
    default:
1315
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1316
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1317
        return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1318
    }
1319
    return NULL;
1320
}
1321

    
1322
static void net_socket_accept(void *opaque)
1323
{
1324
    NetSocketListenState *s = opaque;
1325
    NetSocketState *s1;
1326
    struct sockaddr_in saddr;
1327
    socklen_t len;
1328
    int fd;
1329

    
1330
    for(;;) {
1331
        len = sizeof(saddr);
1332
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1333
        if (fd < 0 && errno != EINTR) {
1334
            return;
1335
        } else if (fd >= 0) {
1336
            break;
1337
        }
1338
    }
1339
    s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1340
    if (!s1) {
1341
        closesocket(fd);
1342
    } else {
1343
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1344
                 "socket: connection from %s:%d",
1345
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1346
    }
1347
}
1348

    
1349
static int net_socket_listen_init(VLANState *vlan,
1350
                                  const char *model,
1351
                                  const char *name,
1352
                                  const char *host_str)
1353
{
1354
    NetSocketListenState *s;
1355
    int fd, val, ret;
1356
    struct sockaddr_in saddr;
1357

    
1358
    if (parse_host_port(&saddr, host_str) < 0)
1359
        return -1;
1360

    
1361
    s = qemu_mallocz(sizeof(NetSocketListenState));
1362
    if (!s)
1363
        return -1;
1364

    
1365
    fd = socket(PF_INET, SOCK_STREAM, 0);
1366
    if (fd < 0) {
1367
        perror("socket");
1368
        return -1;
1369
    }
1370
    socket_set_nonblock(fd);
1371

    
1372
    /* allow fast reuse */
1373
    val = 1;
1374
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1375

    
1376
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1377
    if (ret < 0) {
1378
        perror("bind");
1379
        return -1;
1380
    }
1381
    ret = listen(fd, 0);
1382
    if (ret < 0) {
1383
        perror("listen");
1384
        return -1;
1385
    }
1386
    s->vlan = vlan;
1387
    s->model = strdup(model);
1388
    s->name = strdup(name);
1389
    s->fd = fd;
1390
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1391
    return 0;
1392
}
1393

    
1394
static int net_socket_connect_init(VLANState *vlan,
1395
                                   const char *model,
1396
                                   const char *name,
1397
                                   const char *host_str)
1398
{
1399
    NetSocketState *s;
1400
    int fd, connected, ret, err;
1401
    struct sockaddr_in saddr;
1402

    
1403
    if (parse_host_port(&saddr, host_str) < 0)
1404
        return -1;
1405

    
1406
    fd = socket(PF_INET, SOCK_STREAM, 0);
1407
    if (fd < 0) {
1408
        perror("socket");
1409
        return -1;
1410
    }
1411
    socket_set_nonblock(fd);
1412

    
1413
    connected = 0;
1414
    for(;;) {
1415
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1416
        if (ret < 0) {
1417
            err = socket_error();
1418
            if (err == EINTR || err == EWOULDBLOCK) {
1419
            } else if (err == EINPROGRESS) {
1420
                break;
1421
#ifdef _WIN32
1422
            } else if (err == WSAEALREADY) {
1423
                break;
1424
#endif
1425
            } else {
1426
                perror("connect");
1427
                closesocket(fd);
1428
                return -1;
1429
            }
1430
        } else {
1431
            connected = 1;
1432
            break;
1433
        }
1434
    }
1435
    s = net_socket_fd_init(vlan, model, name, fd, connected);
1436
    if (!s)
1437
        return -1;
1438
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1439
             "socket: connect to %s:%d",
1440
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1441
    return 0;
1442
}
1443

    
1444
static int net_socket_mcast_init(VLANState *vlan,
1445
                                 const char *model,
1446
                                 const char *name,
1447
                                 const char *host_str)
1448
{
1449
    NetSocketState *s;
1450
    int fd;
1451
    struct sockaddr_in saddr;
1452

    
1453
    if (parse_host_port(&saddr, host_str) < 0)
1454
        return -1;
1455

    
1456

    
1457
    fd = net_socket_mcast_create(&saddr);
1458
    if (fd < 0)
1459
        return -1;
1460

    
1461
    s = net_socket_fd_init(vlan, model, name, fd, 0);
1462
    if (!s)
1463
        return -1;
1464

    
1465
    s->dgram_dst = saddr;
1466

    
1467
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1468
             "socket: mcast=%s:%d",
1469
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1470
    return 0;
1471

    
1472
}
1473

    
1474
/* find or alloc a new VLAN */
1475
VLANState *qemu_find_vlan(int id)
1476
{
1477
    VLANState **pvlan, *vlan;
1478
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1479
        if (vlan->id == id)
1480
            return vlan;
1481
    }
1482
    vlan = qemu_mallocz(sizeof(VLANState));
1483
    if (!vlan)
1484
        return NULL;
1485
    vlan->id = id;
1486
    vlan->next = NULL;
1487
    pvlan = &first_vlan;
1488
    while (*pvlan != NULL)
1489
        pvlan = &(*pvlan)->next;
1490
    *pvlan = vlan;
1491
    return vlan;
1492
}
1493

    
1494
int net_client_init(const char *device, const char *p)
1495
{
1496
    char buf[1024];
1497
    int vlan_id, ret;
1498
    VLANState *vlan;
1499
    char *name = NULL;
1500

    
1501
    vlan_id = 0;
1502
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1503
        vlan_id = strtol(buf, NULL, 0);
1504
    }
1505
    vlan = qemu_find_vlan(vlan_id);
1506
    if (!vlan) {
1507
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
1508
        return -1;
1509
    }
1510
    if (get_param_value(buf, sizeof(buf), "name", p)) {
1511
        name = strdup(buf);
1512
    }
1513
    if (!strcmp(device, "nic")) {
1514
        NICInfo *nd;
1515
        uint8_t *macaddr;
1516

    
1517
        if (nb_nics >= MAX_NICS) {
1518
            fprintf(stderr, "Too Many NICs\n");
1519
            return -1;
1520
        }
1521
        nd = &nd_table[nb_nics];
1522
        macaddr = nd->macaddr;
1523
        macaddr[0] = 0x52;
1524
        macaddr[1] = 0x54;
1525
        macaddr[2] = 0x00;
1526
        macaddr[3] = 0x12;
1527
        macaddr[4] = 0x34;
1528
        macaddr[5] = 0x56 + nb_nics;
1529

    
1530
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1531
            if (parse_macaddr(macaddr, buf) < 0) {
1532
                fprintf(stderr, "invalid syntax for ethernet address\n");
1533
                return -1;
1534
            }
1535
        }
1536
        if (get_param_value(buf, sizeof(buf), "model", p)) {
1537
            nd->model = strdup(buf);
1538
        }
1539
        nd->vlan = vlan;
1540
        nd->name = name;
1541
        name = NULL;
1542
        nb_nics++;
1543
        vlan->nb_guest_devs++;
1544
        ret = 0;
1545
    } else
1546
    if (!strcmp(device, "none")) {
1547
        /* does nothing. It is needed to signal that no network cards
1548
           are wanted */
1549
        ret = 0;
1550
    } else
1551
#ifdef CONFIG_SLIRP
1552
    if (!strcmp(device, "user")) {
1553
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1554
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1555
        }
1556
        vlan->nb_host_devs++;
1557
        ret = net_slirp_init(vlan, device, name);
1558
    } else
1559
#endif
1560
#ifdef _WIN32
1561
    if (!strcmp(device, "tap")) {
1562
        char ifname[64];
1563
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1564
            fprintf(stderr, "tap: no interface name\n");
1565
            return -1;
1566
        }
1567
        vlan->nb_host_devs++;
1568
        ret = tap_win32_init(vlan, device, name, ifname);
1569
    } else
1570
#elif defined (_AIX)
1571
#else
1572
    if (!strcmp(device, "tap")) {
1573
        char ifname[64];
1574
        char setup_script[1024], down_script[1024];
1575
        int fd;
1576
        vlan->nb_host_devs++;
1577
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1578
            fd = strtol(buf, NULL, 0);
1579
            fcntl(fd, F_SETFL, O_NONBLOCK);
1580
            ret = -1;
1581
            if (net_tap_fd_init(vlan, device, name, fd))
1582
                ret = 0;
1583
        } else {
1584
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1585
                ifname[0] = '\0';
1586
            }
1587
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1588
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1589
            }
1590
            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1591
                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1592
            }
1593
            ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
1594
        }
1595
    } else
1596
#endif
1597
    if (!strcmp(device, "socket")) {
1598
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1599
            int fd;
1600
            fd = strtol(buf, NULL, 0);
1601
            ret = -1;
1602
            if (net_socket_fd_init(vlan, device, name, fd, 1))
1603
                ret = 0;
1604
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1605
            ret = net_socket_listen_init(vlan, device, name, buf);
1606
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1607
            ret = net_socket_connect_init(vlan, device, name, buf);
1608
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1609
            ret = net_socket_mcast_init(vlan, device, name, buf);
1610
        } else {
1611
            fprintf(stderr, "Unknown socket options: %s\n", p);
1612
            return -1;
1613
        }
1614
        vlan->nb_host_devs++;
1615
    } else
1616
#ifdef CONFIG_VDE
1617
    if (!strcmp(device, "vde")) {
1618
        char vde_sock[1024], vde_group[512];
1619
        int vde_port, vde_mode;
1620
        vlan->nb_host_devs++;
1621
        if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1622
            vde_sock[0] = '\0';
1623
        }
1624
        if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1625
            vde_port = strtol(buf, NULL, 10);
1626
        } else {
1627
            vde_port = 0;
1628
        }
1629
        if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1630
            vde_group[0] = '\0';
1631
        }
1632
        if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1633
            vde_mode = strtol(buf, NULL, 8);
1634
        } else {
1635
            vde_mode = 0700;
1636
        }
1637
        ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
1638
    } else
1639
#endif
1640
    {
1641
        fprintf(stderr, "Unknown network device: %s\n", device);
1642
        if (name)
1643
            free(name);
1644
        return -1;
1645
    }
1646
    if (ret < 0) {
1647
        fprintf(stderr, "Could not initialize device '%s'\n", device);
1648
    }
1649
    if (name)
1650
        free(name);
1651
    return ret;
1652
}
1653

    
1654
int net_client_parse(const char *str)
1655
{
1656
    const char *p;
1657
    char *q;
1658
    char device[64];
1659

    
1660
    p = str;
1661
    q = device;
1662
    while (*p != '\0' && *p != ',') {
1663
        if ((q - device) < sizeof(device) - 1)
1664
            *q++ = *p;
1665
        p++;
1666
    }
1667
    *q = '\0';
1668
    if (*p == ',')
1669
        p++;
1670

    
1671
    return net_client_init(device, p);
1672
}
1673

    
1674
void do_info_network(void)
1675
{
1676
    VLANState *vlan;
1677
    VLANClientState *vc;
1678

    
1679
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1680
        term_printf("VLAN %d devices:\n", vlan->id);
1681
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
1682
            term_printf("  %s: %s\n", vc->name, vc->info_str);
1683
    }
1684
}
1685

    
1686
void net_cleanup(void)
1687
{
1688
    VLANState *vlan;
1689

    
1690
#if !defined(_WIN32)
1691
    /* close network clients */
1692
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1693
        VLANClientState *vc;
1694

    
1695
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1696
            if (vc->fd_read == tap_receive) {
1697
                char ifname[64];
1698
                TAPState *s = vc->opaque;
1699

    
1700
                if (strcmp(vc->model, "tap") == 0 &&
1701
                    sscanf(vc->info_str, "ifname=%63s ", ifname) == 1 &&
1702
                    s->down_script[0])
1703
                    launch_script(s->down_script, ifname, s->fd);
1704
            }
1705
#if defined(CONFIG_VDE)
1706
            if (vc->fd_read == vde_from_qemu) {
1707
                VDEState *s = vc->opaque;
1708
                vde_close(s->vde);
1709
            }
1710
#endif
1711
        }
1712
    }
1713
#endif
1714
}
1715

    
1716
void net_client_check(void)
1717
{
1718
    VLANState *vlan;
1719

    
1720
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1721
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
1722
            continue;
1723
        if (vlan->nb_guest_devs == 0)
1724
            fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
1725
        if (vlan->nb_host_devs == 0)
1726
            fprintf(stderr,
1727
                    "Warning: vlan %d is not connected to host network\n",
1728
                    vlan->id);
1729
    }
1730
}