Assign a name to each VLAN client (Mark McLoughlin)
[qemu] / net.c
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 static char *assign_name(VLANClientState *vc1, const char *model)
300 {
301     VLANState *vlan;
302     char buf[256];
303     int id = 0;
304
305     for (vlan = first_vlan; vlan; vlan = vlan->next) {
306         VLANClientState *vc;
307
308         for (vc = vlan->first_client; vc; vc = vc->next)
309             if (vc != vc1 && strcmp(vc->model, model) == 0)
310                 id++;
311     }
312
313     snprintf(buf, sizeof(buf), "%s.%d", model, id);
314
315     return strdup(buf);
316 }
317
318 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
319                                       const char *model,
320                                       IOReadHandler *fd_read,
321                                       IOCanRWHandler *fd_can_read,
322                                       void *opaque)
323 {
324     VLANClientState *vc, **pvc;
325     vc = qemu_mallocz(sizeof(VLANClientState));
326     if (!vc)
327         return NULL;
328     vc->model = strdup(model);
329     vc->name = assign_name(vc, model);
330     vc->fd_read = fd_read;
331     vc->fd_can_read = fd_can_read;
332     vc->opaque = opaque;
333     vc->vlan = vlan;
334
335     vc->next = NULL;
336     pvc = &vlan->first_client;
337     while (*pvc != NULL)
338         pvc = &(*pvc)->next;
339     *pvc = vc;
340     return vc;
341 }
342
343 void qemu_del_vlan_client(VLANClientState *vc)
344 {
345     VLANClientState **pvc = &vc->vlan->first_client;
346
347     while (*pvc != NULL)
348         if (*pvc == vc) {
349             *pvc = vc->next;
350             free(vc->name);
351             free(vc->model);
352             free(vc);
353             break;
354         } else
355             pvc = &(*pvc)->next;
356 }
357
358 int qemu_can_send_packet(VLANClientState *vc1)
359 {
360     VLANState *vlan = vc1->vlan;
361     VLANClientState *vc;
362
363     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
364         if (vc != vc1) {
365             if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
366                 return 1;
367         }
368     }
369     return 0;
370 }
371
372 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
373 {
374     VLANState *vlan = vc1->vlan;
375     VLANClientState *vc;
376
377 #ifdef DEBUG_NET
378     printf("vlan %d send:\n", vlan->id);
379     hex_dump(stdout, buf, size);
380 #endif
381     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
382         if (vc != vc1) {
383             vc->fd_read(vc->opaque, buf, size);
384         }
385     }
386 }
387
388 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
389                                int iovcnt)
390 {
391     uint8_t buffer[4096];
392     size_t offset = 0;
393     int i;
394
395     for (i = 0; i < iovcnt; i++) {
396         size_t len;
397
398         len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
399         memcpy(buffer + offset, iov[i].iov_base, len);
400         offset += len;
401     }
402
403     vc->fd_read(vc->opaque, buffer, offset);
404
405     return offset;
406 }
407
408 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
409                           int iovcnt)
410 {
411     VLANState *vlan = vc1->vlan;
412     VLANClientState *vc;
413     ssize_t max_len = 0;
414
415     for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
416         ssize_t len = 0;
417
418         if (vc == vc1)
419             continue;
420
421         if (vc->fd_readv)
422             len = vc->fd_readv(vc->opaque, iov, iovcnt);
423         else if (vc->fd_read)
424             len = vc_sendv_compat(vc, iov, iovcnt);
425
426         max_len = MAX(max_len, len);
427     }
428
429     return max_len;
430 }
431
432 #if defined(CONFIG_SLIRP)
433
434 /* slirp network adapter */
435
436 static int slirp_inited;
437 static VLANClientState *slirp_vc;
438
439 int slirp_can_output(void)
440 {
441     return !slirp_vc || qemu_can_send_packet(slirp_vc);
442 }
443
444 void slirp_output(const uint8_t *pkt, int pkt_len)
445 {
446 #ifdef DEBUG_SLIRP
447     printf("slirp output:\n");
448     hex_dump(stdout, pkt, pkt_len);
449 #endif
450     if (!slirp_vc)
451         return;
452     qemu_send_packet(slirp_vc, pkt, pkt_len);
453 }
454
455 int slirp_is_inited(void)
456 {
457     return slirp_inited;
458 }
459
460 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
461 {
462 #ifdef DEBUG_SLIRP
463     printf("slirp input:\n");
464     hex_dump(stdout, buf, size);
465 #endif
466     slirp_input(buf, size);
467 }
468
469 static int net_slirp_init(VLANState *vlan, const char *model)
470 {
471     if (!slirp_inited) {
472         slirp_inited = 1;
473         slirp_init();
474     }
475     slirp_vc = qemu_new_vlan_client(vlan, model,
476                                     slirp_receive, NULL, NULL);
477     snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
478     return 0;
479 }
480
481 void net_slirp_redir(const char *redir_str)
482 {
483     int is_udp;
484     char buf[256], *r;
485     const char *p;
486     struct in_addr guest_addr;
487     int host_port, guest_port;
488
489     if (!slirp_inited) {
490         slirp_inited = 1;
491         slirp_init();
492     }
493
494     p = redir_str;
495     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
496         goto fail;
497     if (!strcmp(buf, "tcp")) {
498         is_udp = 0;
499     } else if (!strcmp(buf, "udp")) {
500         is_udp = 1;
501     } else {
502         goto fail;
503     }
504
505     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
506         goto fail;
507     host_port = strtol(buf, &r, 0);
508     if (r == buf)
509         goto fail;
510
511     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
512         goto fail;
513     if (buf[0] == '\0') {
514         pstrcpy(buf, sizeof(buf), "10.0.2.15");
515     }
516     if (!inet_aton(buf, &guest_addr))
517         goto fail;
518
519     guest_port = strtol(p, &r, 0);
520     if (r == p)
521         goto fail;
522
523     if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
524         fprintf(stderr, "qemu: could not set up redirection\n");
525         exit(1);
526     }
527     return;
528  fail:
529     fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
530     exit(1);
531 }
532
533 #ifndef _WIN32
534
535 static char smb_dir[1024];
536
537 static void erase_dir(char *dir_name)
538 {
539     DIR *d;
540     struct dirent *de;
541     char filename[1024];
542
543     /* erase all the files in the directory */
544     if ((d = opendir(dir_name)) != 0) {
545         for(;;) {
546             de = readdir(d);
547             if (!de)
548                 break;
549             if (strcmp(de->d_name, ".") != 0 &&
550                 strcmp(de->d_name, "..") != 0) {
551                 snprintf(filename, sizeof(filename), "%s/%s",
552                          smb_dir, de->d_name);
553                 if (unlink(filename) != 0)  /* is it a directory? */
554                     erase_dir(filename);
555             }
556         }
557         closedir(d);
558         rmdir(dir_name);
559     }
560 }
561
562 /* automatic user mode samba server configuration */
563 static void smb_exit(void)
564 {
565     erase_dir(smb_dir);
566 }
567
568 /* automatic user mode samba server configuration */
569 void net_slirp_smb(const char *exported_dir)
570 {
571     char smb_conf[1024];
572     char smb_cmdline[1024];
573     FILE *f;
574
575     if (!slirp_inited) {
576         slirp_inited = 1;
577         slirp_init();
578     }
579
580     /* XXX: better tmp dir construction */
581     snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
582     if (mkdir(smb_dir, 0700) < 0) {
583         fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
584         exit(1);
585     }
586     snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
587
588     f = fopen(smb_conf, "w");
589     if (!f) {
590         fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
591         exit(1);
592     }
593     fprintf(f,
594             "[global]\n"
595             "private dir=%s\n"
596             "smb ports=0\n"
597             "socket address=127.0.0.1\n"
598             "pid directory=%s\n"
599             "lock directory=%s\n"
600             "log file=%s/log.smbd\n"
601             "smb passwd file=%s/smbpasswd\n"
602             "security = share\n"
603             "[qemu]\n"
604             "path=%s\n"
605             "read only=no\n"
606             "guest ok=yes\n",
607             smb_dir,
608             smb_dir,
609             smb_dir,
610             smb_dir,
611             smb_dir,
612             exported_dir
613             );
614     fclose(f);
615     atexit(smb_exit);
616
617     snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
618              SMBD_COMMAND, smb_conf);
619
620     slirp_add_exec(0, smb_cmdline, 4, 139);
621 }
622
623 #endif /* !defined(_WIN32) */
624 void do_info_slirp(void)
625 {
626     slirp_stats();
627 }
628
629 #endif /* CONFIG_SLIRP */
630
631 #if !defined(_WIN32)
632
633 typedef struct TAPState {
634     VLANClientState *vc;
635     int fd;
636     char down_script[1024];
637 } TAPState;
638
639 #ifdef HAVE_IOVEC
640 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
641                                int iovcnt)
642 {
643     TAPState *s = opaque;
644     ssize_t len;
645
646     do {
647         len = writev(s->fd, iov, iovcnt);
648     } while (len == -1 && (errno == EINTR || errno == EAGAIN));
649
650     return len;
651 }
652 #endif
653
654 static void tap_receive(void *opaque, const uint8_t *buf, int size)
655 {
656     TAPState *s = opaque;
657     int ret;
658     for(;;) {
659         ret = write(s->fd, buf, size);
660         if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
661         } else {
662             break;
663         }
664     }
665 }
666
667 static void tap_send(void *opaque)
668 {
669     TAPState *s = opaque;
670     uint8_t buf[4096];
671     int size;
672
673 #ifdef __sun__
674     struct strbuf sbuf;
675     int f = 0;
676     sbuf.maxlen = sizeof(buf);
677     sbuf.buf = buf;
678     size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
679 #else
680     size = read(s->fd, buf, sizeof(buf));
681 #endif
682     if (size > 0) {
683         qemu_send_packet(s->vc, buf, size);
684     }
685 }
686
687 /* fd support */
688
689 static TAPState *net_tap_fd_init(VLANState *vlan, const char *model, int fd)
690 {
691     TAPState *s;
692
693     s = qemu_mallocz(sizeof(TAPState));
694     if (!s)
695         return NULL;
696     s->fd = fd;
697     s->vc = qemu_new_vlan_client(vlan, model, tap_receive, NULL, s);
698 #ifdef HAVE_IOVEC
699     s->vc->fd_readv = tap_receive_iov;
700 #endif
701     qemu_set_fd_handler(s->fd, tap_send, NULL, s);
702     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
703     return s;
704 }
705
706 #if defined (_BSD) || defined (__FreeBSD_kernel__)
707 static int tap_open(char *ifname, int ifname_size)
708 {
709     int fd;
710     char *dev;
711     struct stat s;
712
713     TFR(fd = open("/dev/tap", O_RDWR));
714     if (fd < 0) {
715         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
716         return -1;
717     }
718
719     fstat(fd, &s);
720     dev = devname(s.st_rdev, S_IFCHR);
721     pstrcpy(ifname, ifname_size, dev);
722
723     fcntl(fd, F_SETFL, O_NONBLOCK);
724     return fd;
725 }
726 #elif defined(__sun__)
727 #define TUNNEWPPA       (('T'<<16) | 0x0001)
728 /*
729  * Allocate TAP device, returns opened fd.
730  * Stores dev name in the first arg(must be large enough).
731  */
732 int tap_alloc(char *dev, size_t dev_size)
733 {
734     int tap_fd, if_fd, ppa = -1;
735     static int ip_fd = 0;
736     char *ptr;
737
738     static int arp_fd = 0;
739     int ip_muxid, arp_muxid;
740     struct strioctl  strioc_if, strioc_ppa;
741     int link_type = I_PLINK;;
742     struct lifreq ifr;
743     char actual_name[32] = "";
744
745     memset(&ifr, 0x0, sizeof(ifr));
746
747     if( *dev ){
748        ptr = dev;
749        while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
750        ppa = atoi(ptr);
751     }
752
753     /* Check if IP device was opened */
754     if( ip_fd )
755        close(ip_fd);
756
757     TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
758     if (ip_fd < 0) {
759        syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
760        return -1;
761     }
762
763     TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
764     if (tap_fd < 0) {
765        syslog(LOG_ERR, "Can't open /dev/tap");
766        return -1;
767     }
768
769     /* Assign a new PPA and get its unit number. */
770     strioc_ppa.ic_cmd = TUNNEWPPA;
771     strioc_ppa.ic_timout = 0;
772     strioc_ppa.ic_len = sizeof(ppa);
773     strioc_ppa.ic_dp = (char *)&ppa;
774     if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
775        syslog (LOG_ERR, "Can't assign new interface");
776
777     TFR(if_fd = open("/dev/tap", O_RDWR, 0));
778     if (if_fd < 0) {
779        syslog(LOG_ERR, "Can't open /dev/tap (2)");
780        return -1;
781     }
782     if(ioctl(if_fd, I_PUSH, "ip") < 0){
783        syslog(LOG_ERR, "Can't push IP module");
784        return -1;
785     }
786
787     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
788         syslog(LOG_ERR, "Can't get flags\n");
789
790     snprintf (actual_name, 32, "tap%d", ppa);
791     pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
792
793     ifr.lifr_ppa = ppa;
794     /* Assign ppa according to the unit number returned by tun device */
795
796     if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
797         syslog (LOG_ERR, "Can't set PPA %d", ppa);
798     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
799         syslog (LOG_ERR, "Can't get flags\n");
800     /* Push arp module to if_fd */
801     if (ioctl (if_fd, I_PUSH, "arp") < 0)
802         syslog (LOG_ERR, "Can't push ARP module (2)");
803
804     /* Push arp module to ip_fd */
805     if (ioctl (ip_fd, I_POP, NULL) < 0)
806         syslog (LOG_ERR, "I_POP failed\n");
807     if (ioctl (ip_fd, I_PUSH, "arp") < 0)
808         syslog (LOG_ERR, "Can't push ARP module (3)\n");
809     /* Open arp_fd */
810     TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
811     if (arp_fd < 0)
812        syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
813
814     /* Set ifname to arp */
815     strioc_if.ic_cmd = SIOCSLIFNAME;
816     strioc_if.ic_timout = 0;
817     strioc_if.ic_len = sizeof(ifr);
818     strioc_if.ic_dp = (char *)&ifr;
819     if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
820         syslog (LOG_ERR, "Can't set ifname to arp\n");
821     }
822
823     if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
824        syslog(LOG_ERR, "Can't link TAP device to IP");
825        return -1;
826     }
827
828     if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
829         syslog (LOG_ERR, "Can't link TAP device to ARP");
830
831     close (if_fd);
832
833     memset(&ifr, 0x0, sizeof(ifr));
834     pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
835     ifr.lifr_ip_muxid  = ip_muxid;
836     ifr.lifr_arp_muxid = arp_muxid;
837
838     if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
839     {
840       ioctl (ip_fd, I_PUNLINK , arp_muxid);
841       ioctl (ip_fd, I_PUNLINK, ip_muxid);
842       syslog (LOG_ERR, "Can't set multiplexor id");
843     }
844
845     snprintf(dev, dev_size, "tap%d", ppa);
846     return tap_fd;
847 }
848
849 static int tap_open(char *ifname, int ifname_size)
850 {
851     char  dev[10]="";
852     int fd;
853     if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
854        fprintf(stderr, "Cannot allocate TAP device\n");
855        return -1;
856     }
857     pstrcpy(ifname, ifname_size, dev);
858     fcntl(fd, F_SETFL, O_NONBLOCK);
859     return fd;
860 }
861 #elif defined (_AIX)
862 static int tap_open(char *ifname, int ifname_size)
863 {
864     fprintf (stderr, "no tap on AIX\n");
865     return -1;
866 }
867 #else
868 static int tap_open(char *ifname, int ifname_size)
869 {
870     struct ifreq ifr;
871     int fd, ret;
872
873     TFR(fd = open("/dev/net/tun", O_RDWR));
874     if (fd < 0) {
875         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
876         return -1;
877     }
878     memset(&ifr, 0, sizeof(ifr));
879     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
880     if (ifname[0] != '\0')
881         pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
882     else
883         pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
884     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
885     if (ret != 0) {
886         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
887         close(fd);
888         return -1;
889     }
890     pstrcpy(ifname, ifname_size, ifr.ifr_name);
891     fcntl(fd, F_SETFL, O_NONBLOCK);
892     return fd;
893 }
894 #endif
895
896 static int launch_script(const char *setup_script, const char *ifname, int fd)
897 {
898     int pid, status;
899     char *args[3];
900     char **parg;
901
902         /* try to launch network script */
903         pid = fork();
904         if (pid >= 0) {
905             if (pid == 0) {
906                 int open_max = sysconf (_SC_OPEN_MAX), i;
907                 for (i = 0; i < open_max; i++)
908                     if (i != STDIN_FILENO &&
909                         i != STDOUT_FILENO &&
910                         i != STDERR_FILENO &&
911                         i != fd)
912                         close(i);
913
914                 parg = args;
915                 *parg++ = (char *)setup_script;
916                 *parg++ = (char *)ifname;
917                 *parg++ = NULL;
918                 execv(setup_script, args);
919                 _exit(1);
920             }
921             while (waitpid(pid, &status, 0) != pid);
922             if (!WIFEXITED(status) ||
923                 WEXITSTATUS(status) != 0) {
924                 fprintf(stderr, "%s: could not launch network script\n",
925                         setup_script);
926                 return -1;
927             }
928         }
929     return 0;
930 }
931
932 static int net_tap_init(VLANState *vlan, const char *model, const char *ifname1,
933                         const char *setup_script, const char *down_script)
934 {
935     TAPState *s;
936     int fd;
937     char ifname[128];
938
939     if (ifname1 != NULL)
940         pstrcpy(ifname, sizeof(ifname), ifname1);
941     else
942         ifname[0] = '\0';
943     TFR(fd = tap_open(ifname, sizeof(ifname)));
944     if (fd < 0)
945         return -1;
946
947     if (!setup_script || !strcmp(setup_script, "no"))
948         setup_script = "";
949     if (setup_script[0] != '\0') {
950         if (launch_script(setup_script, ifname, fd))
951             return -1;
952     }
953     s = net_tap_fd_init(vlan, model, fd);
954     if (!s)
955         return -1;
956     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
957              "tap: ifname=%s setup_script=%s", ifname, setup_script);
958     if (down_script && strcmp(down_script, "no"))
959         snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
960     return 0;
961 }
962
963 #endif /* !_WIN32 */
964
965 #if defined(CONFIG_VDE)
966 typedef struct VDEState {
967     VLANClientState *vc;
968     VDECONN *vde;
969 } VDEState;
970
971 static void vde_to_qemu(void *opaque)
972 {
973     VDEState *s = opaque;
974     uint8_t buf[4096];
975     int size;
976
977     size = vde_recv(s->vde, buf, sizeof(buf), 0);
978     if (size > 0) {
979         qemu_send_packet(s->vc, buf, size);
980     }
981 }
982
983 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
984 {
985     VDEState *s = opaque;
986     int ret;
987     for(;;) {
988         ret = vde_send(s->vde, buf, size, 0);
989         if (ret < 0 && errno == EINTR) {
990         } else {
991             break;
992         }
993     }
994 }
995
996 static int net_vde_init(VLANState *vlan, const char *model, const char *sock,
997                         int port, const char *group, int mode)
998 {
999     VDEState *s;
1000     char *init_group = strlen(group) ? (char *)group : NULL;
1001     char *init_sock = strlen(sock) ? (char *)sock : NULL;
1002
1003     struct vde_open_args args = {
1004         .port = port,
1005         .group = init_group,
1006         .mode = mode,
1007     };
1008
1009     s = qemu_mallocz(sizeof(VDEState));
1010     if (!s)
1011         return -1;
1012     s->vde = vde_open(init_sock, "QEMU", &args);
1013     if (!s->vde){
1014         free(s);
1015         return -1;
1016     }
1017     s->vc = qemu_new_vlan_client(vlan, model, vde_from_qemu, NULL, s);
1018     qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1019     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
1020              sock, vde_datafd(s->vde));
1021     return 0;
1022 }
1023 #endif
1024
1025 /* network connection */
1026 typedef struct NetSocketState {
1027     VLANClientState *vc;
1028     int fd;
1029     int state; /* 0 = getting length, 1 = getting data */
1030     int index;
1031     int packet_len;
1032     uint8_t buf[4096];
1033     struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1034 } NetSocketState;
1035
1036 typedef struct NetSocketListenState {
1037     VLANState *vlan;
1038     char *model;
1039     int fd;
1040 } NetSocketListenState;
1041
1042 /* XXX: we consider we can send the whole packet without blocking */
1043 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1044 {
1045     NetSocketState *s = opaque;
1046     uint32_t len;
1047     len = htonl(size);
1048
1049     send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1050     send_all(s->fd, buf, size);
1051 }
1052
1053 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1054 {
1055     NetSocketState *s = opaque;
1056     sendto(s->fd, buf, size, 0,
1057            (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1058 }
1059
1060 static void net_socket_send(void *opaque)
1061 {
1062     NetSocketState *s = opaque;
1063     int l, size, err;
1064     uint8_t buf1[4096];
1065     const uint8_t *buf;
1066
1067     size = recv(s->fd, buf1, sizeof(buf1), 0);
1068     if (size < 0) {
1069         err = socket_error();
1070         if (err != EWOULDBLOCK)
1071             goto eoc;
1072     } else if (size == 0) {
1073         /* end of connection */
1074     eoc:
1075         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1076         closesocket(s->fd);
1077         return;
1078     }
1079     buf = buf1;
1080     while (size > 0) {
1081         /* reassemble a packet from the network */
1082         switch(s->state) {
1083         case 0:
1084             l = 4 - s->index;
1085             if (l > size)
1086                 l = size;
1087             memcpy(s->buf + s->index, buf, l);
1088             buf += l;
1089             size -= l;
1090             s->index += l;
1091             if (s->index == 4) {
1092                 /* got length */
1093                 s->packet_len = ntohl(*(uint32_t *)s->buf);
1094                 s->index = 0;
1095                 s->state = 1;
1096             }
1097             break;
1098         case 1:
1099             l = s->packet_len - s->index;
1100             if (l > size)
1101                 l = size;
1102             memcpy(s->buf + s->index, buf, l);
1103             s->index += l;
1104             buf += l;
1105             size -= l;
1106             if (s->index >= s->packet_len) {
1107                 qemu_send_packet(s->vc, s->buf, s->packet_len);
1108                 s->index = 0;
1109                 s->state = 0;
1110             }
1111             break;
1112         }
1113     }
1114 }
1115
1116 static void net_socket_send_dgram(void *opaque)
1117 {
1118     NetSocketState *s = opaque;
1119     int size;
1120
1121     size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1122     if (size < 0)
1123         return;
1124     if (size == 0) {
1125         /* end of connection */
1126         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1127         return;
1128     }
1129     qemu_send_packet(s->vc, s->buf, size);
1130 }
1131
1132 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1133 {
1134     struct ip_mreq imr;
1135     int fd;
1136     int val, ret;
1137     if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1138         fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1139                 inet_ntoa(mcastaddr->sin_addr),
1140                 (int)ntohl(mcastaddr->sin_addr.s_addr));
1141         return -1;
1142
1143     }
1144     fd = socket(PF_INET, SOCK_DGRAM, 0);
1145     if (fd < 0) {
1146         perror("socket(PF_INET, SOCK_DGRAM)");
1147         return -1;
1148     }
1149
1150     val = 1;
1151     ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1152                    (const char *)&val, sizeof(val));
1153     if (ret < 0) {
1154         perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1155         goto fail;
1156     }
1157
1158     ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1159     if (ret < 0) {
1160         perror("bind");
1161         goto fail;
1162     }
1163
1164     /* Add host to multicast group */
1165     imr.imr_multiaddr = mcastaddr->sin_addr;
1166     imr.imr_interface.s_addr = htonl(INADDR_ANY);
1167
1168     ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1169                      (const char *)&imr, sizeof(struct ip_mreq));
1170     if (ret < 0) {
1171         perror("setsockopt(IP_ADD_MEMBERSHIP)");
1172         goto fail;
1173     }
1174
1175     /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1176     val = 1;
1177     ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1178                    (const char *)&val, sizeof(val));
1179     if (ret < 0) {
1180         perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1181         goto fail;
1182     }
1183
1184     socket_set_nonblock(fd);
1185     return fd;
1186 fail:
1187     if (fd >= 0)
1188         closesocket(fd);
1189     return -1;
1190 }
1191
1192 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, const char *model,
1193                                                 int fd, int is_connected)
1194 {
1195     struct sockaddr_in saddr;
1196     int newfd;
1197     socklen_t saddr_len;
1198     NetSocketState *s;
1199
1200     /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1201      * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1202      * by ONLY ONE process: we must "clone" this dgram socket --jjo
1203      */
1204
1205     if (is_connected) {
1206         if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1207             /* must be bound */
1208             if (saddr.sin_addr.s_addr==0) {
1209                 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1210                         fd);
1211                 return NULL;
1212             }
1213             /* clone dgram socket */
1214             newfd = net_socket_mcast_create(&saddr);
1215             if (newfd < 0) {
1216                 /* error already reported by net_socket_mcast_create() */
1217                 close(fd);
1218                 return NULL;
1219             }
1220             /* clone newfd to fd, close newfd */
1221             dup2(newfd, fd);
1222             close(newfd);
1223
1224         } else {
1225             fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1226                     fd, strerror(errno));
1227             return NULL;
1228         }
1229     }
1230
1231     s = qemu_mallocz(sizeof(NetSocketState));
1232     if (!s)
1233         return NULL;
1234     s->fd = fd;
1235
1236     s->vc = qemu_new_vlan_client(vlan, model, net_socket_receive_dgram, NULL, s);
1237     qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1238
1239     /* mcast: save bound address as dst */
1240     if (is_connected) s->dgram_dst=saddr;
1241
1242     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1243             "socket: fd=%d (%s mcast=%s:%d)",
1244             fd, is_connected? "cloned" : "",
1245             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1246     return s;
1247 }
1248
1249 static void net_socket_connect(void *opaque)
1250 {
1251     NetSocketState *s = opaque;
1252     qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1253 }
1254
1255 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, const char *model,
1256                                                  int fd, int is_connected)
1257 {
1258     NetSocketState *s;
1259     s = qemu_mallocz(sizeof(NetSocketState));
1260     if (!s)
1261         return NULL;
1262     s->fd = fd;
1263     s->vc = qemu_new_vlan_client(vlan, model,
1264                                  net_socket_receive, NULL, s);
1265     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1266              "socket: fd=%d", fd);
1267     if (is_connected) {
1268         net_socket_connect(s);
1269     } else {
1270         qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1271     }
1272     return s;
1273 }
1274
1275 static NetSocketState *net_socket_fd_init(VLANState *vlan, const char *model,
1276                                           int fd, int is_connected)
1277 {
1278     int so_type=-1, optlen=sizeof(so_type);
1279
1280     if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1281         (socklen_t *)&optlen)< 0) {
1282         fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1283         return NULL;
1284     }
1285     switch(so_type) {
1286     case SOCK_DGRAM:
1287         return net_socket_fd_init_dgram(vlan, model, fd, is_connected);
1288     case SOCK_STREAM:
1289         return net_socket_fd_init_stream(vlan, model, fd, is_connected);
1290     default:
1291         /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1292         fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1293         return net_socket_fd_init_stream(vlan, model, fd, is_connected);
1294     }
1295     return NULL;
1296 }
1297
1298 static void net_socket_accept(void *opaque)
1299 {
1300     NetSocketListenState *s = opaque;
1301     NetSocketState *s1;
1302     struct sockaddr_in saddr;
1303     socklen_t len;
1304     int fd;
1305
1306     for(;;) {
1307         len = sizeof(saddr);
1308         fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1309         if (fd < 0 && errno != EINTR) {
1310             return;
1311         } else if (fd >= 0) {
1312             break;
1313         }
1314     }
1315     s1 = net_socket_fd_init(s->vlan, s->model, fd, 1);
1316     if (!s1) {
1317         closesocket(fd);
1318     } else {
1319         snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1320                  "socket: connection from %s:%d",
1321                  inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1322     }
1323 }
1324
1325 static int net_socket_listen_init(VLANState *vlan, const char *model,
1326                                   const char *host_str)
1327 {
1328     NetSocketListenState *s;
1329     int fd, val, ret;
1330     struct sockaddr_in saddr;
1331
1332     if (parse_host_port(&saddr, host_str) < 0)
1333         return -1;
1334
1335     s = qemu_mallocz(sizeof(NetSocketListenState));
1336     if (!s)
1337         return -1;
1338
1339     fd = socket(PF_INET, SOCK_STREAM, 0);
1340     if (fd < 0) {
1341         perror("socket");
1342         return -1;
1343     }
1344     socket_set_nonblock(fd);
1345
1346     /* allow fast reuse */
1347     val = 1;
1348     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1349
1350     ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1351     if (ret < 0) {
1352         perror("bind");
1353         return -1;
1354     }
1355     ret = listen(fd, 0);
1356     if (ret < 0) {
1357         perror("listen");
1358         return -1;
1359     }
1360     s->vlan = vlan;
1361     s->model = strdup(model);
1362     s->fd = fd;
1363     qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1364     return 0;
1365 }
1366
1367 static int net_socket_connect_init(VLANState *vlan, const char *model,
1368                                    const char *host_str)
1369 {
1370     NetSocketState *s;
1371     int fd, connected, ret, err;
1372     struct sockaddr_in saddr;
1373
1374     if (parse_host_port(&saddr, host_str) < 0)
1375         return -1;
1376
1377     fd = socket(PF_INET, SOCK_STREAM, 0);
1378     if (fd < 0) {
1379         perror("socket");
1380         return -1;
1381     }
1382     socket_set_nonblock(fd);
1383
1384     connected = 0;
1385     for(;;) {
1386         ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1387         if (ret < 0) {
1388             err = socket_error();
1389             if (err == EINTR || err == EWOULDBLOCK) {
1390             } else if (err == EINPROGRESS) {
1391                 break;
1392 #ifdef _WIN32
1393             } else if (err == WSAEALREADY) {
1394                 break;
1395 #endif
1396             } else {
1397                 perror("connect");
1398                 closesocket(fd);
1399                 return -1;
1400             }
1401         } else {
1402             connected = 1;
1403             break;
1404         }
1405     }
1406     s = net_socket_fd_init(vlan, model, fd, connected);
1407     if (!s)
1408         return -1;
1409     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1410              "socket: connect to %s:%d",
1411              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1412     return 0;
1413 }
1414
1415 static int net_socket_mcast_init(VLANState *vlan, const char *model,
1416                                  const char *host_str)
1417 {
1418     NetSocketState *s;
1419     int fd;
1420     struct sockaddr_in saddr;
1421
1422     if (parse_host_port(&saddr, host_str) < 0)
1423         return -1;
1424
1425
1426     fd = net_socket_mcast_create(&saddr);
1427     if (fd < 0)
1428         return -1;
1429
1430     s = net_socket_fd_init(vlan, model, fd, 0);
1431     if (!s)
1432         return -1;
1433
1434     s->dgram_dst = saddr;
1435
1436     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1437              "socket: mcast=%s:%d",
1438              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1439     return 0;
1440
1441 }
1442
1443 /* find or alloc a new VLAN */
1444 VLANState *qemu_find_vlan(int id)
1445 {
1446     VLANState **pvlan, *vlan;
1447     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1448         if (vlan->id == id)
1449             return vlan;
1450     }
1451     vlan = qemu_mallocz(sizeof(VLANState));
1452     if (!vlan)
1453         return NULL;
1454     vlan->id = id;
1455     vlan->next = NULL;
1456     pvlan = &first_vlan;
1457     while (*pvlan != NULL)
1458         pvlan = &(*pvlan)->next;
1459     *pvlan = vlan;
1460     return vlan;
1461 }
1462
1463 int net_client_init(const char *device, const char *p)
1464 {
1465     char buf[1024];
1466     int vlan_id, ret;
1467     VLANState *vlan;
1468
1469     vlan_id = 0;
1470     if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1471         vlan_id = strtol(buf, NULL, 0);
1472     }
1473     vlan = qemu_find_vlan(vlan_id);
1474     if (!vlan) {
1475         fprintf(stderr, "Could not create vlan %d\n", vlan_id);
1476         return -1;
1477     }
1478     if (!strcmp(device, "nic")) {
1479         NICInfo *nd;
1480         uint8_t *macaddr;
1481
1482         if (nb_nics >= MAX_NICS) {
1483             fprintf(stderr, "Too Many NICs\n");
1484             return -1;
1485         }
1486         nd = &nd_table[nb_nics];
1487         macaddr = nd->macaddr;
1488         macaddr[0] = 0x52;
1489         macaddr[1] = 0x54;
1490         macaddr[2] = 0x00;
1491         macaddr[3] = 0x12;
1492         macaddr[4] = 0x34;
1493         macaddr[5] = 0x56 + nb_nics;
1494
1495         if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1496             if (parse_macaddr(macaddr, buf) < 0) {
1497                 fprintf(stderr, "invalid syntax for ethernet address\n");
1498                 return -1;
1499             }
1500         }
1501         if (get_param_value(buf, sizeof(buf), "model", p)) {
1502             nd->model = strdup(buf);
1503         }
1504         nd->vlan = vlan;
1505         nb_nics++;
1506         vlan->nb_guest_devs++;
1507         ret = 0;
1508     } else
1509     if (!strcmp(device, "none")) {
1510         /* does nothing. It is needed to signal that no network cards
1511            are wanted */
1512         ret = 0;
1513     } else
1514 #ifdef CONFIG_SLIRP
1515     if (!strcmp(device, "user")) {
1516         if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1517             pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1518         }
1519         vlan->nb_host_devs++;
1520         ret = net_slirp_init(vlan, device);
1521     } else
1522 #endif
1523 #ifdef _WIN32
1524     if (!strcmp(device, "tap")) {
1525         char ifname[64];
1526         if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1527             fprintf(stderr, "tap: no interface name\n");
1528             return -1;
1529         }
1530         vlan->nb_host_devs++;
1531         ret = tap_win32_init(vlan, device, ifname);
1532     } else
1533 #elif defined (_AIX)
1534 #else
1535     if (!strcmp(device, "tap")) {
1536         char ifname[64];
1537         char setup_script[1024], down_script[1024];
1538         int fd;
1539         vlan->nb_host_devs++;
1540         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1541             fd = strtol(buf, NULL, 0);
1542             fcntl(fd, F_SETFL, O_NONBLOCK);
1543             ret = -1;
1544             if (net_tap_fd_init(vlan, device, fd))
1545                 ret = 0;
1546         } else {
1547             if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1548                 ifname[0] = '\0';
1549             }
1550             if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1551                 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1552             }
1553             if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1554                 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1555             }
1556             ret = net_tap_init(vlan, device, ifname, setup_script, down_script);
1557         }
1558     } else
1559 #endif
1560     if (!strcmp(device, "socket")) {
1561         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1562             int fd;
1563             fd = strtol(buf, NULL, 0);
1564             ret = -1;
1565             if (net_socket_fd_init(vlan, device, fd, 1))
1566                 ret = 0;
1567         } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1568             ret = net_socket_listen_init(vlan, device, buf);
1569         } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1570             ret = net_socket_connect_init(vlan, device, buf);
1571         } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1572             ret = net_socket_mcast_init(vlan, device, buf);
1573         } else {
1574             fprintf(stderr, "Unknown socket options: %s\n", p);
1575             return -1;
1576         }
1577         vlan->nb_host_devs++;
1578     } else
1579 #ifdef CONFIG_VDE
1580     if (!strcmp(device, "vde")) {
1581         char vde_sock[1024], vde_group[512];
1582         int vde_port, vde_mode;
1583         vlan->nb_host_devs++;
1584         if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1585             vde_sock[0] = '\0';
1586         }
1587         if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1588             vde_port = strtol(buf, NULL, 10);
1589         } else {
1590             vde_port = 0;
1591         }
1592         if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1593             vde_group[0] = '\0';
1594         }
1595         if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1596             vde_mode = strtol(buf, NULL, 8);
1597         } else {
1598             vde_mode = 0700;
1599         }
1600         ret = net_vde_init(vlan, device, vde_sock, vde_port, vde_group, vde_mode);
1601     } else
1602 #endif
1603     {
1604         fprintf(stderr, "Unknown network device: %s\n", device);
1605         return -1;
1606     }
1607     if (ret < 0) {
1608         fprintf(stderr, "Could not initialize device '%s'\n", device);
1609     }
1610
1611     return ret;
1612 }
1613
1614 int net_client_parse(const char *str)
1615 {
1616     const char *p;
1617     char *q;
1618     char device[64];
1619
1620     p = str;
1621     q = device;
1622     while (*p != '\0' && *p != ',') {
1623         if ((q - device) < sizeof(device) - 1)
1624             *q++ = *p;
1625         p++;
1626     }
1627     *q = '\0';
1628     if (*p == ',')
1629         p++;
1630
1631     return net_client_init(device, p);
1632 }
1633
1634 void do_info_network(void)
1635 {
1636     VLANState *vlan;
1637     VLANClientState *vc;
1638
1639     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1640         term_printf("VLAN %d devices:\n", vlan->id);
1641         for(vc = vlan->first_client; vc != NULL; vc = vc->next)
1642             term_printf("  %s\n", vc->info_str);
1643     }
1644 }
1645
1646 void net_cleanup(void)
1647 {
1648     VLANState *vlan;
1649
1650 #if !defined(_WIN32)
1651     /* close network clients */
1652     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1653         VLANClientState *vc;
1654
1655         for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1656             if (vc->fd_read == tap_receive) {
1657                 char ifname[64];
1658                 TAPState *s = vc->opaque;
1659
1660                 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
1661                     s->down_script[0])
1662                     launch_script(s->down_script, ifname, s->fd);
1663             }
1664 #if defined(CONFIG_VDE)
1665             if (vc->fd_read == vde_from_qemu) {
1666                 VDEState *s = vc->opaque;
1667                 vde_close(s->vde);
1668             }
1669 #endif
1670         }
1671     }
1672 #endif
1673 }
1674
1675 void net_client_check(void)
1676 {
1677     VLANState *vlan;
1678
1679     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1680         if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
1681             continue;
1682         if (vlan->nb_guest_devs == 0)
1683             fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
1684         if (vlan->nb_host_devs == 0)
1685             fprintf(stderr,
1686                     "Warning: vlan %d is not connected to host network\n",
1687                     vlan->id);
1688     }
1689 }