Statistics
| Branch: | Revision:

root / net.c @ 4dda4063

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
             "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
303
             vc->model,
304
             macaddr[0], macaddr[1], macaddr[2],
305
             macaddr[3], macaddr[4], macaddr[5]);
306
}
307

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

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

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

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

    
324
    return strdup(buf);
325
}
326

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

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

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

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

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

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

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

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

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

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

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

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

    
418
    return offset;
419
}
420

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

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

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

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

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

    
442
    return max_len;
443
}
444

    
445
#if defined(CONFIG_SLIRP)
446

    
447
/* slirp network adapter */
448

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

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

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

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

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

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

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

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

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

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

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

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

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

    
546
#ifndef _WIN32
547

    
548
static char smb_dir[1024];
549

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

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

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

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

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

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

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

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

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

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

    
642
#endif /* CONFIG_SLIRP */
643

    
644
#if !defined(_WIN32)
645

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

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

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

    
663
    return len;
664
}
665
#endif
666

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

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

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

    
700
/* fd support */
701

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
847
    close (if_fd);
848

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

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

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

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

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

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

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

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

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

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

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

    
981
#endif /* !_WIN32 */
982

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1457

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

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

    
1466
    s->dgram_dst = saddr;
1467

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

    
1473
}
1474

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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