Fix some build issues for BSD.
[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 "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "block.h"
40 #include "audio/audio.h"
41 #include "migration.h"
42
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <signal.h>
46 #include <time.h>
47 #include <errno.h>
48 #include <sys/time.h>
49 #include <zlib.h>
50
51 #ifndef _WIN32
52 #include <sys/times.h>
53 #include <sys/wait.h>
54 #include <termios.h>
55 #include <sys/mman.h>
56 #include <sys/ioctl.h>
57 #include <sys/resource.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
60 #include <net/if.h>
61 #ifdef __NetBSD__
62 #include <net/if_tap.h>
63 #endif
64 #ifdef __linux__
65 #include <linux/if_tun.h>
66 #endif
67 #include <arpa/inet.h>
68 #include <dirent.h>
69 #include <netdb.h>
70 #include <sys/select.h>
71 #ifdef _BSD
72 #include <sys/stat.h>
73 #ifdef __FreeBSD__
74 #include <libutil.h>
75 #else
76 #include <util.h>
77 #endif
78 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
79 #include <freebsd/stdlib.h>
80 #else
81 #ifdef __linux__
82 #include <pty.h>
83 #include <malloc.h>
84 #include <linux/rtc.h>
85
86 /* For the benefit of older linux systems which don't supply it,
87    we use a local copy of hpet.h. */
88 /* #include <linux/hpet.h> */
89 #include "hpet.h"
90
91 #include <linux/ppdev.h>
92 #include <linux/parport.h>
93 #endif
94 #ifdef __sun__
95 #include <sys/stat.h>
96 #include <sys/ethernet.h>
97 #include <sys/sockio.h>
98 #include <netinet/arp.h>
99 #include <netinet/in.h>
100 #include <netinet/in_systm.h>
101 #include <netinet/ip.h>
102 #include <netinet/ip_icmp.h> // must come after ip.h
103 #include <netinet/udp.h>
104 #include <netinet/tcp.h>
105 #include <net/if.h>
106 #include <syslog.h>
107 #include <stropts.h>
108 #endif
109 #endif
110 #endif
111
112 #include "qemu_socket.h"
113
114 #if defined(CONFIG_SLIRP)
115 #include "libslirp.h"
116 #endif
117
118 #if defined(__OpenBSD__)
119 #include <util.h>
120 #endif
121
122 #if defined(CONFIG_VDE)
123 #include <libvdeplug.h>
124 #endif
125
126 #ifdef _WIN32
127 #include <malloc.h>
128 #include <sys/timeb.h>
129 #include <mmsystem.h>
130 #define getopt_long_only getopt_long
131 #define memalign(align, size) malloc(size)
132 #endif
133
134 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
135 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
136 #ifdef __sun__
137 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
138 #else
139 #define SMBD_COMMAND "/usr/sbin/smbd"
140 #endif
141
142 static VLANState *first_vlan;
143
144 /***********************************************************/
145 /* network device redirectors */
146
147 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
148 static void hex_dump(FILE *f, const uint8_t *buf, int size)
149 {
150     int len, i, j, c;
151
152     for(i=0;i<size;i+=16) {
153         len = size - i;
154         if (len > 16)
155             len = 16;
156         fprintf(f, "%08x ", i);
157         for(j=0;j<16;j++) {
158             if (j < len)
159                 fprintf(f, " %02x", buf[i+j]);
160             else
161                 fprintf(f, "   ");
162         }
163         fprintf(f, " ");
164         for(j=0;j<len;j++) {
165             c = buf[i+j];
166             if (c < ' ' || c > '~')
167                 c = '.';
168             fprintf(f, "%c", c);
169         }
170         fprintf(f, "\n");
171     }
172 }
173 #endif
174
175 static int parse_macaddr(uint8_t *macaddr, const char *p)
176 {
177     int i;
178     char *last_char;
179     long int offset;
180
181     errno = 0;
182     offset = strtol(p, &last_char, 0);    
183     if (0 == errno && '\0' == *last_char &&
184             offset >= 0 && offset <= 0xFFFFFF) {
185         macaddr[3] = (offset & 0xFF0000) >> 16;
186         macaddr[4] = (offset & 0xFF00) >> 8;
187         macaddr[5] = offset & 0xFF;
188         return 0;
189     } else {
190         for(i = 0; i < 6; i++) {
191             macaddr[i] = strtol(p, (char **)&p, 16);
192             if (i == 5) {
193                 if (*p != '\0')
194                     return -1;
195             } else {
196                 if (*p != ':' && *p != '-')
197                     return -1;
198                 p++;
199             }
200         }
201         return 0;    
202     }
203
204     return -1;
205 }
206
207 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
208 {
209     const char *p, *p1;
210     int len;
211     p = *pp;
212     p1 = strchr(p, sep);
213     if (!p1)
214         return -1;
215     len = p1 - p;
216     p1++;
217     if (buf_size > 0) {
218         if (len > buf_size - 1)
219             len = buf_size - 1;
220         memcpy(buf, p, len);
221         buf[len] = '\0';
222     }
223     *pp = p1;
224     return 0;
225 }
226
227 int parse_host_src_port(struct sockaddr_in *haddr,
228                         struct sockaddr_in *saddr,
229                         const char *input_str)
230 {
231     char *str = strdup(input_str);
232     char *host_str = str;
233     char *src_str;
234     const char *src_str2;
235     char *ptr;
236
237     /*
238      * Chop off any extra arguments at the end of the string which
239      * would start with a comma, then fill in the src port information
240      * if it was provided else use the "any address" and "any port".
241      */
242     if ((ptr = strchr(str,',')))
243         *ptr = '\0';
244
245     if ((src_str = strchr(input_str,'@'))) {
246         *src_str = '\0';
247         src_str++;
248     }
249
250     if (parse_host_port(haddr, host_str) < 0)
251         goto fail;
252
253     src_str2 = src_str;
254     if (!src_str || *src_str == '\0')
255         src_str2 = ":0";
256
257     if (parse_host_port(saddr, src_str2) < 0)
258         goto fail;
259
260     free(str);
261     return(0);
262
263 fail:
264     free(str);
265     return -1;
266 }
267
268 int parse_host_port(struct sockaddr_in *saddr, const char *str)
269 {
270     char buf[512];
271     struct hostent *he;
272     const char *p, *r;
273     int port;
274
275     p = str;
276     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
277         return -1;
278     saddr->sin_family = AF_INET;
279     if (buf[0] == '\0') {
280         saddr->sin_addr.s_addr = 0;
281     } else {
282         if (isdigit(buf[0])) {
283             if (!inet_aton(buf, &saddr->sin_addr))
284                 return -1;
285         } else {
286             if ((he = gethostbyname(buf)) == NULL)
287                 return - 1;
288             saddr->sin_addr = *(struct in_addr *)he->h_addr;
289         }
290     }
291     port = strtol(p, (char **)&r, 0);
292     if (r == p)
293         return -1;
294     saddr->sin_port = htons(port);
295     return 0;
296 }
297
298 #ifndef _WIN32
299 int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
300 {
301     const char *p;
302     int len;
303
304     len = MIN(108, strlen(str));
305     p = strchr(str, ',');
306     if (p)
307         len = MIN(len, p - str);
308
309     memset(uaddr, 0, sizeof(*uaddr));
310
311     uaddr->sun_family = AF_UNIX;
312     memcpy(uaddr->sun_path, str, len);
313
314     return 0;
315 }
316 #endif
317
318 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
319                                       IOReadHandler *fd_read,
320                                       IOCanRWHandler *fd_can_read,
321                                       void *opaque)
322 {
323     VLANClientState *vc, **pvc;
324     vc = qemu_mallocz(sizeof(VLANClientState));
325     if (!vc)
326         return NULL;
327     vc->fd_read = fd_read;
328     vc->fd_can_read = fd_can_read;
329     vc->opaque = opaque;
330     vc->vlan = vlan;
331
332     vc->next = NULL;
333     pvc = &vlan->first_client;
334     while (*pvc != NULL)
335         pvc = &(*pvc)->next;
336     *pvc = vc;
337     return vc;
338 }
339
340 void qemu_del_vlan_client(VLANClientState *vc)
341 {
342     VLANClientState **pvc = &vc->vlan->first_client;
343
344     while (*pvc != NULL)
345         if (*pvc == vc) {
346             *pvc = vc->next;
347             free(vc);
348             break;
349         } else
350             pvc = &(*pvc)->next;
351 }
352
353 int qemu_can_send_packet(VLANClientState *vc1)
354 {
355     VLANState *vlan = vc1->vlan;
356     VLANClientState *vc;
357
358     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
359         if (vc != vc1) {
360             if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
361                 return 1;
362         }
363     }
364     return 0;
365 }
366
367 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
368 {
369     VLANState *vlan = vc1->vlan;
370     VLANClientState *vc;
371
372 #ifdef DEBUG_NET
373     printf("vlan %d send:\n", vlan->id);
374     hex_dump(stdout, buf, size);
375 #endif
376     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
377         if (vc != vc1) {
378             vc->fd_read(vc->opaque, buf, size);
379         }
380     }
381 }
382
383 #if defined(CONFIG_SLIRP)
384
385 /* slirp network adapter */
386
387 static int slirp_inited;
388 static VLANClientState *slirp_vc;
389
390 int slirp_can_output(void)
391 {
392     return !slirp_vc || qemu_can_send_packet(slirp_vc);
393 }
394
395 void slirp_output(const uint8_t *pkt, int pkt_len)
396 {
397 #ifdef DEBUG_SLIRP
398     printf("slirp output:\n");
399     hex_dump(stdout, pkt, pkt_len);
400 #endif
401     if (!slirp_vc)
402         return;
403     qemu_send_packet(slirp_vc, pkt, pkt_len);
404 }
405
406 int slirp_is_inited(void)
407 {
408     return slirp_inited;
409 }
410
411 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
412 {
413 #ifdef DEBUG_SLIRP
414     printf("slirp input:\n");
415     hex_dump(stdout, buf, size);
416 #endif
417     slirp_input(buf, size);
418 }
419
420 static int net_slirp_init(VLANState *vlan)
421 {
422     if (!slirp_inited) {
423         slirp_inited = 1;
424         slirp_init();
425     }
426     slirp_vc = qemu_new_vlan_client(vlan,
427                                     slirp_receive, NULL, NULL);
428     snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
429     return 0;
430 }
431
432 void net_slirp_redir(const char *redir_str)
433 {
434     int is_udp;
435     char buf[256], *r;
436     const char *p;
437     struct in_addr guest_addr;
438     int host_port, guest_port;
439
440     if (!slirp_inited) {
441         slirp_inited = 1;
442         slirp_init();
443     }
444
445     p = redir_str;
446     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
447         goto fail;
448     if (!strcmp(buf, "tcp")) {
449         is_udp = 0;
450     } else if (!strcmp(buf, "udp")) {
451         is_udp = 1;
452     } else {
453         goto fail;
454     }
455
456     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
457         goto fail;
458     host_port = strtol(buf, &r, 0);
459     if (r == buf)
460         goto fail;
461
462     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
463         goto fail;
464     if (buf[0] == '\0') {
465         pstrcpy(buf, sizeof(buf), "10.0.2.15");
466     }
467     if (!inet_aton(buf, &guest_addr))
468         goto fail;
469
470     guest_port = strtol(p, &r, 0);
471     if (r == p)
472         goto fail;
473
474     if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
475         fprintf(stderr, "qemu: could not set up redirection\n");
476         exit(1);
477     }
478     return;
479  fail:
480     fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
481     exit(1);
482 }
483
484 #ifndef _WIN32
485
486 static char smb_dir[1024];
487
488 static void erase_dir(char *dir_name)
489 {
490     DIR *d;
491     struct dirent *de;
492     char filename[1024];
493
494     /* erase all the files in the directory */
495     if ((d = opendir(dir_name)) != 0) {
496         for(;;) {
497             de = readdir(d);
498             if (!de)
499                 break;
500             if (strcmp(de->d_name, ".") != 0 &&
501                 strcmp(de->d_name, "..") != 0) {
502                 snprintf(filename, sizeof(filename), "%s/%s",
503                          smb_dir, de->d_name);
504                 if (unlink(filename) != 0)  /* is it a directory? */
505                     erase_dir(filename);
506             }
507         }
508         closedir(d);
509         rmdir(dir_name);
510     }
511 }
512
513 /* automatic user mode samba server configuration */
514 static void smb_exit(void)
515 {
516     erase_dir(smb_dir);
517 }
518
519 /* automatic user mode samba server configuration */
520 void net_slirp_smb(const char *exported_dir)
521 {
522     char smb_conf[1024];
523     char smb_cmdline[1024];
524     FILE *f;
525
526     if (!slirp_inited) {
527         slirp_inited = 1;
528         slirp_init();
529     }
530
531     /* XXX: better tmp dir construction */
532     snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
533     if (mkdir(smb_dir, 0700) < 0) {
534         fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
535         exit(1);
536     }
537     snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
538
539     f = fopen(smb_conf, "w");
540     if (!f) {
541         fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
542         exit(1);
543     }
544     fprintf(f,
545             "[global]\n"
546             "private dir=%s\n"
547             "smb ports=0\n"
548             "socket address=127.0.0.1\n"
549             "pid directory=%s\n"
550             "lock directory=%s\n"
551             "log file=%s/log.smbd\n"
552             "smb passwd file=%s/smbpasswd\n"
553             "security = share\n"
554             "[qemu]\n"
555             "path=%s\n"
556             "read only=no\n"
557             "guest ok=yes\n",
558             smb_dir,
559             smb_dir,
560             smb_dir,
561             smb_dir,
562             smb_dir,
563             exported_dir
564             );
565     fclose(f);
566     atexit(smb_exit);
567
568     snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
569              SMBD_COMMAND, smb_conf);
570
571     slirp_add_exec(0, smb_cmdline, 4, 139);
572 }
573
574 #endif /* !defined(_WIN32) */
575 void do_info_slirp(void)
576 {
577     slirp_stats();
578 }
579
580 #endif /* CONFIG_SLIRP */
581
582 #if !defined(_WIN32)
583
584 typedef struct TAPState {
585     VLANClientState *vc;
586     int fd;
587     char down_script[1024];
588 } TAPState;
589
590 static void tap_receive(void *opaque, const uint8_t *buf, int size)
591 {
592     TAPState *s = opaque;
593     int ret;
594     for(;;) {
595         ret = write(s->fd, buf, size);
596         if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
597         } else {
598             break;
599         }
600     }
601 }
602
603 static void tap_send(void *opaque)
604 {
605     TAPState *s = opaque;
606     uint8_t buf[4096];
607     int size;
608
609 #ifdef __sun__
610     struct strbuf sbuf;
611     int f = 0;
612     sbuf.maxlen = sizeof(buf);
613     sbuf.buf = buf;
614     size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
615 #else
616     size = read(s->fd, buf, sizeof(buf));
617 #endif
618     if (size > 0) {
619         qemu_send_packet(s->vc, buf, size);
620     }
621 }
622
623 /* fd support */
624
625 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
626 {
627     TAPState *s;
628
629     s = qemu_mallocz(sizeof(TAPState));
630     if (!s)
631         return NULL;
632     s->fd = fd;
633     s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
634     qemu_set_fd_handler(s->fd, tap_send, NULL, s);
635     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
636     return s;
637 }
638
639 #if defined (_BSD) || defined (__FreeBSD_kernel__)
640 static int tap_open(char *ifname, int ifname_size)
641 {
642     int fd;
643     char *dev;
644     struct stat s;
645
646     TFR(fd = open("/dev/tap", O_RDWR));
647     if (fd < 0) {
648         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
649         return -1;
650     }
651
652     fstat(fd, &s);
653     dev = devname(s.st_rdev, S_IFCHR);
654     pstrcpy(ifname, ifname_size, dev);
655
656     fcntl(fd, F_SETFL, O_NONBLOCK);
657     return fd;
658 }
659 #elif defined(__sun__)
660 #define TUNNEWPPA       (('T'<<16) | 0x0001)
661 /*
662  * Allocate TAP device, returns opened fd.
663  * Stores dev name in the first arg(must be large enough).
664  */
665 int tap_alloc(char *dev, size_t dev_size)
666 {
667     int tap_fd, if_fd, ppa = -1;
668     static int ip_fd = 0;
669     char *ptr;
670
671     static int arp_fd = 0;
672     int ip_muxid, arp_muxid;
673     struct strioctl  strioc_if, strioc_ppa;
674     int link_type = I_PLINK;;
675     struct lifreq ifr;
676     char actual_name[32] = "";
677
678     memset(&ifr, 0x0, sizeof(ifr));
679
680     if( *dev ){
681        ptr = dev;
682        while( *ptr && !isdigit((int)*ptr) ) ptr++;
683        ppa = atoi(ptr);
684     }
685
686     /* Check if IP device was opened */
687     if( ip_fd )
688        close(ip_fd);
689
690     TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
691     if (ip_fd < 0) {
692        syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
693        return -1;
694     }
695
696     TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
697     if (tap_fd < 0) {
698        syslog(LOG_ERR, "Can't open /dev/tap");
699        return -1;
700     }
701
702     /* Assign a new PPA and get its unit number. */
703     strioc_ppa.ic_cmd = TUNNEWPPA;
704     strioc_ppa.ic_timout = 0;
705     strioc_ppa.ic_len = sizeof(ppa);
706     strioc_ppa.ic_dp = (char *)&ppa;
707     if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
708        syslog (LOG_ERR, "Can't assign new interface");
709
710     TFR(if_fd = open("/dev/tap", O_RDWR, 0));
711     if (if_fd < 0) {
712        syslog(LOG_ERR, "Can't open /dev/tap (2)");
713        return -1;
714     }
715     if(ioctl(if_fd, I_PUSH, "ip") < 0){
716        syslog(LOG_ERR, "Can't push IP module");
717        return -1;
718     }
719
720     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
721         syslog(LOG_ERR, "Can't get flags\n");
722
723     snprintf (actual_name, 32, "tap%d", ppa);
724     pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
725
726     ifr.lifr_ppa = ppa;
727     /* Assign ppa according to the unit number returned by tun device */
728
729     if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
730         syslog (LOG_ERR, "Can't set PPA %d", ppa);
731     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
732         syslog (LOG_ERR, "Can't get flags\n");
733     /* Push arp module to if_fd */
734     if (ioctl (if_fd, I_PUSH, "arp") < 0)
735         syslog (LOG_ERR, "Can't push ARP module (2)");
736
737     /* Push arp module to ip_fd */
738     if (ioctl (ip_fd, I_POP, NULL) < 0)
739         syslog (LOG_ERR, "I_POP failed\n");
740     if (ioctl (ip_fd, I_PUSH, "arp") < 0)
741         syslog (LOG_ERR, "Can't push ARP module (3)\n");
742     /* Open arp_fd */
743     TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
744     if (arp_fd < 0)
745        syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
746
747     /* Set ifname to arp */
748     strioc_if.ic_cmd = SIOCSLIFNAME;
749     strioc_if.ic_timout = 0;
750     strioc_if.ic_len = sizeof(ifr);
751     strioc_if.ic_dp = (char *)&ifr;
752     if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
753         syslog (LOG_ERR, "Can't set ifname to arp\n");
754     }
755
756     if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
757        syslog(LOG_ERR, "Can't link TAP device to IP");
758        return -1;
759     }
760
761     if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
762         syslog (LOG_ERR, "Can't link TAP device to ARP");
763
764     close (if_fd);
765
766     memset(&ifr, 0x0, sizeof(ifr));
767     pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
768     ifr.lifr_ip_muxid  = ip_muxid;
769     ifr.lifr_arp_muxid = arp_muxid;
770
771     if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
772     {
773       ioctl (ip_fd, I_PUNLINK , arp_muxid);
774       ioctl (ip_fd, I_PUNLINK, ip_muxid);
775       syslog (LOG_ERR, "Can't set multiplexor id");
776     }
777
778     snprintf(dev, dev_size, "tap%d", ppa);
779     return tap_fd;
780 }
781
782 static int tap_open(char *ifname, int ifname_size)
783 {
784     char  dev[10]="";
785     int fd;
786     if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
787        fprintf(stderr, "Cannot allocate TAP device\n");
788        return -1;
789     }
790     pstrcpy(ifname, ifname_size, dev);
791     fcntl(fd, F_SETFL, O_NONBLOCK);
792     return fd;
793 }
794 #else
795 static int tap_open(char *ifname, int ifname_size)
796 {
797     struct ifreq ifr;
798     int fd, ret;
799
800     TFR(fd = open("/dev/net/tun", O_RDWR));
801     if (fd < 0) {
802         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
803         return -1;
804     }
805     memset(&ifr, 0, sizeof(ifr));
806     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
807     if (ifname[0] != '\0')
808         pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
809     else
810         pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
811     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
812     if (ret != 0) {
813         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
814         close(fd);
815         return -1;
816     }
817     pstrcpy(ifname, ifname_size, ifr.ifr_name);
818     fcntl(fd, F_SETFL, O_NONBLOCK);
819     return fd;
820 }
821 #endif
822
823 static int launch_script(const char *setup_script, const char *ifname, int fd)
824 {
825     int pid, status;
826     char *args[3];
827     char **parg;
828
829         /* try to launch network script */
830         pid = fork();
831         if (pid >= 0) {
832             if (pid == 0) {
833                 int open_max = sysconf (_SC_OPEN_MAX), i;
834                 for (i = 0; i < open_max; i++)
835                     if (i != STDIN_FILENO &&
836                         i != STDOUT_FILENO &&
837                         i != STDERR_FILENO &&
838                         i != fd)
839                         close(i);
840
841                 parg = args;
842                 *parg++ = (char *)setup_script;
843                 *parg++ = (char *)ifname;
844                 *parg++ = NULL;
845                 execv(setup_script, args);
846                 _exit(1);
847             }
848             while (waitpid(pid, &status, 0) != pid);
849             if (!WIFEXITED(status) ||
850                 WEXITSTATUS(status) != 0) {
851                 fprintf(stderr, "%s: could not launch network script\n",
852                         setup_script);
853                 return -1;
854             }
855         }
856     return 0;
857 }
858
859 static int net_tap_init(VLANState *vlan, const char *ifname1,
860                         const char *setup_script, const char *down_script)
861 {
862     TAPState *s;
863     int fd;
864     char ifname[128];
865
866     if (ifname1 != NULL)
867         pstrcpy(ifname, sizeof(ifname), ifname1);
868     else
869         ifname[0] = '\0';
870     TFR(fd = tap_open(ifname, sizeof(ifname)));
871     if (fd < 0)
872         return -1;
873
874     if (!setup_script || !strcmp(setup_script, "no"))
875         setup_script = "";
876     if (setup_script[0] != '\0') {
877         if (launch_script(setup_script, ifname, fd))
878             return -1;
879     }
880     s = net_tap_fd_init(vlan, fd);
881     if (!s)
882         return -1;
883     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
884              "tap: ifname=%s setup_script=%s", ifname, setup_script);
885     if (down_script && strcmp(down_script, "no"))
886         snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
887     return 0;
888 }
889
890 #endif /* !_WIN32 */
891
892 #if defined(CONFIG_VDE)
893 typedef struct VDEState {
894     VLANClientState *vc;
895     VDECONN *vde;
896 } VDEState;
897
898 static void vde_to_qemu(void *opaque)
899 {
900     VDEState *s = opaque;
901     uint8_t buf[4096];
902     int size;
903
904     size = vde_recv(s->vde, buf, sizeof(buf), 0);
905     if (size > 0) {
906         qemu_send_packet(s->vc, buf, size);
907     }
908 }
909
910 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
911 {
912     VDEState *s = opaque;
913     int ret;
914     for(;;) {
915         ret = vde_send(s->vde, buf, size, 0);
916         if (ret < 0 && errno == EINTR) {
917         } else {
918             break;
919         }
920     }
921 }
922
923 static int net_vde_init(VLANState *vlan, const char *sock, int port,
924                         const char *group, int mode)
925 {
926     VDEState *s;
927     char *init_group = strlen(group) ? (char *)group : NULL;
928     char *init_sock = strlen(sock) ? (char *)sock : NULL;
929
930     struct vde_open_args args = {
931         .port = port,
932         .group = init_group,
933         .mode = mode,
934     };
935
936     s = qemu_mallocz(sizeof(VDEState));
937     if (!s)
938         return -1;
939     s->vde = vde_open(init_sock, "QEMU", &args);
940     if (!s->vde){
941         free(s);
942         return -1;
943     }
944     s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
945     qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
946     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
947              sock, vde_datafd(s->vde));
948     return 0;
949 }
950 #endif
951
952 /* network connection */
953 typedef struct NetSocketState {
954     VLANClientState *vc;
955     int fd;
956     int state; /* 0 = getting length, 1 = getting data */
957     int index;
958     int packet_len;
959     uint8_t buf[4096];
960     struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
961 } NetSocketState;
962
963 typedef struct NetSocketListenState {
964     VLANState *vlan;
965     int fd;
966 } NetSocketListenState;
967
968 /* XXX: we consider we can send the whole packet without blocking */
969 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
970 {
971     NetSocketState *s = opaque;
972     uint32_t len;
973     len = htonl(size);
974
975     send_all(s->fd, (const uint8_t *)&len, sizeof(len));
976     send_all(s->fd, buf, size);
977 }
978
979 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
980 {
981     NetSocketState *s = opaque;
982     sendto(s->fd, buf, size, 0,
983            (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
984 }
985
986 static void net_socket_send(void *opaque)
987 {
988     NetSocketState *s = opaque;
989     int l, size, err;
990     uint8_t buf1[4096];
991     const uint8_t *buf;
992
993     size = recv(s->fd, buf1, sizeof(buf1), 0);
994     if (size < 0) {
995         err = socket_error();
996         if (err != EWOULDBLOCK)
997             goto eoc;
998     } else if (size == 0) {
999         /* end of connection */
1000     eoc:
1001         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1002         closesocket(s->fd);
1003         return;
1004     }
1005     buf = buf1;
1006     while (size > 0) {
1007         /* reassemble a packet from the network */
1008         switch(s->state) {
1009         case 0:
1010             l = 4 - s->index;
1011             if (l > size)
1012                 l = size;
1013             memcpy(s->buf + s->index, buf, l);
1014             buf += l;
1015             size -= l;
1016             s->index += l;
1017             if (s->index == 4) {
1018                 /* got length */
1019                 s->packet_len = ntohl(*(uint32_t *)s->buf);
1020                 s->index = 0;
1021                 s->state = 1;
1022             }
1023             break;
1024         case 1:
1025             l = s->packet_len - s->index;
1026             if (l > size)
1027                 l = size;
1028             memcpy(s->buf + s->index, buf, l);
1029             s->index += l;
1030             buf += l;
1031             size -= l;
1032             if (s->index >= s->packet_len) {
1033                 qemu_send_packet(s->vc, s->buf, s->packet_len);
1034                 s->index = 0;
1035                 s->state = 0;
1036             }
1037             break;
1038         }
1039     }
1040 }
1041
1042 static void net_socket_send_dgram(void *opaque)
1043 {
1044     NetSocketState *s = opaque;
1045     int size;
1046
1047     size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1048     if (size < 0)
1049         return;
1050     if (size == 0) {
1051         /* end of connection */
1052         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1053         return;
1054     }
1055     qemu_send_packet(s->vc, s->buf, size);
1056 }
1057
1058 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1059 {
1060     struct ip_mreq imr;
1061     int fd;
1062     int val, ret;
1063     if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1064         fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1065                 inet_ntoa(mcastaddr->sin_addr),
1066                 (int)ntohl(mcastaddr->sin_addr.s_addr));
1067         return -1;
1068
1069     }
1070     fd = socket(PF_INET, SOCK_DGRAM, 0);
1071     if (fd < 0) {
1072         perror("socket(PF_INET, SOCK_DGRAM)");
1073         return -1;
1074     }
1075
1076     val = 1;
1077     ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1078                    (const char *)&val, sizeof(val));
1079     if (ret < 0) {
1080         perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1081         goto fail;
1082     }
1083
1084     ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1085     if (ret < 0) {
1086         perror("bind");
1087         goto fail;
1088     }
1089
1090     /* Add host to multicast group */
1091     imr.imr_multiaddr = mcastaddr->sin_addr;
1092     imr.imr_interface.s_addr = htonl(INADDR_ANY);
1093
1094     ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1095                      (const char *)&imr, sizeof(struct ip_mreq));
1096     if (ret < 0) {
1097         perror("setsockopt(IP_ADD_MEMBERSHIP)");
1098         goto fail;
1099     }
1100
1101     /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1102     val = 1;
1103     ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1104                    (const char *)&val, sizeof(val));
1105     if (ret < 0) {
1106         perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1107         goto fail;
1108     }
1109
1110     socket_set_nonblock(fd);
1111     return fd;
1112 fail:
1113     if (fd >= 0)
1114         closesocket(fd);
1115     return -1;
1116 }
1117
1118 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
1119                                           int is_connected)
1120 {
1121     struct sockaddr_in saddr;
1122     int newfd;
1123     socklen_t saddr_len;
1124     NetSocketState *s;
1125
1126     /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1127      * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1128      * by ONLY ONE process: we must "clone" this dgram socket --jjo
1129      */
1130
1131     if (is_connected) {
1132         if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1133             /* must be bound */
1134             if (saddr.sin_addr.s_addr==0) {
1135                 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1136                         fd);
1137                 return NULL;
1138             }
1139             /* clone dgram socket */
1140             newfd = net_socket_mcast_create(&saddr);
1141             if (newfd < 0) {
1142                 /* error already reported by net_socket_mcast_create() */
1143                 close(fd);
1144                 return NULL;
1145             }
1146             /* clone newfd to fd, close newfd */
1147             dup2(newfd, fd);
1148             close(newfd);
1149
1150         } else {
1151             fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1152                     fd, strerror(errno));
1153             return NULL;
1154         }
1155     }
1156
1157     s = qemu_mallocz(sizeof(NetSocketState));
1158     if (!s)
1159         return NULL;
1160     s->fd = fd;
1161
1162     s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
1163     qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1164
1165     /* mcast: save bound address as dst */
1166     if (is_connected) s->dgram_dst=saddr;
1167
1168     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1169             "socket: fd=%d (%s mcast=%s:%d)",
1170             fd, is_connected? "cloned" : "",
1171             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1172     return s;
1173 }
1174
1175 static void net_socket_connect(void *opaque)
1176 {
1177     NetSocketState *s = opaque;
1178     qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1179 }
1180
1181 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
1182                                           int is_connected)
1183 {
1184     NetSocketState *s;
1185     s = qemu_mallocz(sizeof(NetSocketState));
1186     if (!s)
1187         return NULL;
1188     s->fd = fd;
1189     s->vc = qemu_new_vlan_client(vlan,
1190                                  net_socket_receive, NULL, s);
1191     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1192              "socket: fd=%d", fd);
1193     if (is_connected) {
1194         net_socket_connect(s);
1195     } else {
1196         qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1197     }
1198     return s;
1199 }
1200
1201 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
1202                                           int is_connected)
1203 {
1204     int so_type=-1, optlen=sizeof(so_type);
1205
1206     if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1207         (socklen_t *)&optlen)< 0) {
1208         fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1209         return NULL;
1210     }
1211     switch(so_type) {
1212     case SOCK_DGRAM:
1213         return net_socket_fd_init_dgram(vlan, fd, is_connected);
1214     case SOCK_STREAM:
1215         return net_socket_fd_init_stream(vlan, fd, is_connected);
1216     default:
1217         /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1218         fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1219         return net_socket_fd_init_stream(vlan, fd, is_connected);
1220     }
1221     return NULL;
1222 }
1223
1224 static void net_socket_accept(void *opaque)
1225 {
1226     NetSocketListenState *s = opaque;
1227     NetSocketState *s1;
1228     struct sockaddr_in saddr;
1229     socklen_t len;
1230     int fd;
1231
1232     for(;;) {
1233         len = sizeof(saddr);
1234         fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1235         if (fd < 0 && errno != EINTR) {
1236             return;
1237         } else if (fd >= 0) {
1238             break;
1239         }
1240     }
1241     s1 = net_socket_fd_init(s->vlan, fd, 1);
1242     if (!s1) {
1243         closesocket(fd);
1244     } else {
1245         snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1246                  "socket: connection from %s:%d",
1247                  inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1248     }
1249 }
1250
1251 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
1252 {
1253     NetSocketListenState *s;
1254     int fd, val, ret;
1255     struct sockaddr_in saddr;
1256
1257     if (parse_host_port(&saddr, host_str) < 0)
1258         return -1;
1259
1260     s = qemu_mallocz(sizeof(NetSocketListenState));
1261     if (!s)
1262         return -1;
1263
1264     fd = socket(PF_INET, SOCK_STREAM, 0);
1265     if (fd < 0) {
1266         perror("socket");
1267         return -1;
1268     }
1269     socket_set_nonblock(fd);
1270
1271     /* allow fast reuse */
1272     val = 1;
1273     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1274
1275     ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1276     if (ret < 0) {
1277         perror("bind");
1278         return -1;
1279     }
1280     ret = listen(fd, 0);
1281     if (ret < 0) {
1282         perror("listen");
1283         return -1;
1284     }
1285     s->vlan = vlan;
1286     s->fd = fd;
1287     qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1288     return 0;
1289 }
1290
1291 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
1292 {
1293     NetSocketState *s;
1294     int fd, connected, ret, err;
1295     struct sockaddr_in saddr;
1296
1297     if (parse_host_port(&saddr, host_str) < 0)
1298         return -1;
1299
1300     fd = socket(PF_INET, SOCK_STREAM, 0);
1301     if (fd < 0) {
1302         perror("socket");
1303         return -1;
1304     }
1305     socket_set_nonblock(fd);
1306
1307     connected = 0;
1308     for(;;) {
1309         ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1310         if (ret < 0) {
1311             err = socket_error();
1312             if (err == EINTR || err == EWOULDBLOCK) {
1313             } else if (err == EINPROGRESS) {
1314                 break;
1315 #ifdef _WIN32
1316             } else if (err == WSAEALREADY) {
1317                 break;
1318 #endif
1319             } else {
1320                 perror("connect");
1321                 closesocket(fd);
1322                 return -1;
1323             }
1324         } else {
1325             connected = 1;
1326             break;
1327         }
1328     }
1329     s = net_socket_fd_init(vlan, fd, connected);
1330     if (!s)
1331         return -1;
1332     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1333              "socket: connect to %s:%d",
1334              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1335     return 0;
1336 }
1337
1338 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
1339 {
1340     NetSocketState *s;
1341     int fd;
1342     struct sockaddr_in saddr;
1343
1344     if (parse_host_port(&saddr, host_str) < 0)
1345         return -1;
1346
1347
1348     fd = net_socket_mcast_create(&saddr);
1349     if (fd < 0)
1350         return -1;
1351
1352     s = net_socket_fd_init(vlan, fd, 0);
1353     if (!s)
1354         return -1;
1355
1356     s->dgram_dst = saddr;
1357
1358     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1359              "socket: mcast=%s:%d",
1360              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1361     return 0;
1362
1363 }
1364
1365 /* find or alloc a new VLAN */
1366 VLANState *qemu_find_vlan(int id)
1367 {
1368     VLANState **pvlan, *vlan;
1369     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1370         if (vlan->id == id)
1371             return vlan;
1372     }
1373     vlan = qemu_mallocz(sizeof(VLANState));
1374     if (!vlan)
1375         return NULL;
1376     vlan->id = id;
1377     vlan->next = NULL;
1378     pvlan = &first_vlan;
1379     while (*pvlan != NULL)
1380         pvlan = &(*pvlan)->next;
1381     *pvlan = vlan;
1382     return vlan;
1383 }
1384
1385 int net_client_init(const char *device, const char *p)
1386 {
1387     char buf[1024];
1388     int vlan_id, ret;
1389     VLANState *vlan;
1390
1391     vlan_id = 0;
1392     if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1393         vlan_id = strtol(buf, NULL, 0);
1394     }
1395     vlan = qemu_find_vlan(vlan_id);
1396     if (!vlan) {
1397         fprintf(stderr, "Could not create vlan %d\n", vlan_id);
1398         return -1;
1399     }
1400     if (!strcmp(device, "nic")) {
1401         NICInfo *nd;
1402         uint8_t *macaddr;
1403
1404         if (nb_nics >= MAX_NICS) {
1405             fprintf(stderr, "Too Many NICs\n");
1406             return -1;
1407         }
1408         nd = &nd_table[nb_nics];
1409         macaddr = nd->macaddr;
1410         macaddr[0] = 0x52;
1411         macaddr[1] = 0x54;
1412         macaddr[2] = 0x00;
1413         macaddr[3] = 0x12;
1414         macaddr[4] = 0x34;
1415         macaddr[5] = 0x56 + nb_nics;
1416
1417         if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1418             if (parse_macaddr(macaddr, buf) < 0) {
1419                 fprintf(stderr, "invalid syntax for ethernet address\n");
1420                 return -1;
1421             }
1422         }
1423         if (get_param_value(buf, sizeof(buf), "model", p)) {
1424             nd->model = strdup(buf);
1425         }
1426         nd->vlan = vlan;
1427         nb_nics++;
1428         vlan->nb_guest_devs++;
1429         ret = 0;
1430     } else
1431     if (!strcmp(device, "none")) {
1432         /* does nothing. It is needed to signal that no network cards
1433            are wanted */
1434         ret = 0;
1435     } else
1436 #ifdef CONFIG_SLIRP
1437     if (!strcmp(device, "user")) {
1438         if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1439             pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1440         }
1441         vlan->nb_host_devs++;
1442         ret = net_slirp_init(vlan);
1443     } else
1444 #endif
1445 #ifdef _WIN32
1446     if (!strcmp(device, "tap")) {
1447         char ifname[64];
1448         if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1449             fprintf(stderr, "tap: no interface name\n");
1450             return -1;
1451         }
1452         vlan->nb_host_devs++;
1453         ret = tap_win32_init(vlan, ifname);
1454     } else
1455 #else
1456     if (!strcmp(device, "tap")) {
1457         char ifname[64];
1458         char setup_script[1024], down_script[1024];
1459         int fd;
1460         vlan->nb_host_devs++;
1461         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1462             fd = strtol(buf, NULL, 0);
1463             fcntl(fd, F_SETFL, O_NONBLOCK);
1464             ret = -1;
1465             if (net_tap_fd_init(vlan, fd))
1466                 ret = 0;
1467         } else {
1468             if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1469                 ifname[0] = '\0';
1470             }
1471             if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1472                 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1473             }
1474             if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1475                 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1476             }
1477             ret = net_tap_init(vlan, ifname, setup_script, down_script);
1478         }
1479     } else
1480 #endif
1481     if (!strcmp(device, "socket")) {
1482         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1483             int fd;
1484             fd = strtol(buf, NULL, 0);
1485             ret = -1;
1486             if (net_socket_fd_init(vlan, fd, 1))
1487                 ret = 0;
1488         } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1489             ret = net_socket_listen_init(vlan, buf);
1490         } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1491             ret = net_socket_connect_init(vlan, buf);
1492         } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1493             ret = net_socket_mcast_init(vlan, buf);
1494         } else {
1495             fprintf(stderr, "Unknown socket options: %s\n", p);
1496             return -1;
1497         }
1498         vlan->nb_host_devs++;
1499     } else
1500 #ifdef CONFIG_VDE
1501     if (!strcmp(device, "vde")) {
1502         char vde_sock[1024], vde_group[512];
1503         int vde_port, vde_mode;
1504         vlan->nb_host_devs++;
1505         if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1506             vde_sock[0] = '\0';
1507         }
1508         if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1509             vde_port = strtol(buf, NULL, 10);
1510         } else {
1511             vde_port = 0;
1512         }
1513         if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1514             vde_group[0] = '\0';
1515         }
1516         if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1517             vde_mode = strtol(buf, NULL, 8);
1518         } else {
1519             vde_mode = 0700;
1520         }
1521         ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
1522     } else
1523 #endif
1524     {
1525         fprintf(stderr, "Unknown network device: %s\n", device);
1526         return -1;
1527     }
1528     if (ret < 0) {
1529         fprintf(stderr, "Could not initialize device '%s'\n", device);
1530     }
1531
1532     return ret;
1533 }
1534
1535 int net_client_parse(const char *str)
1536 {
1537     const char *p;
1538     char *q;
1539     char device[64];
1540
1541     p = str;
1542     q = device;
1543     while (*p != '\0' && *p != ',') {
1544         if ((q - device) < sizeof(device) - 1)
1545             *q++ = *p;
1546         p++;
1547     }
1548     *q = '\0';
1549     if (*p == ',')
1550         p++;
1551
1552     return net_client_init(device, p);
1553 }
1554
1555 void do_info_network(void)
1556 {
1557     VLANState *vlan;
1558     VLANClientState *vc;
1559
1560     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1561         term_printf("VLAN %d devices:\n", vlan->id);
1562         for(vc = vlan->first_client; vc != NULL; vc = vc->next)
1563             term_printf("  %s\n", vc->info_str);
1564     }
1565 }
1566
1567 void net_cleanup(void)
1568 {
1569     VLANState *vlan;
1570
1571 #if !defined(_WIN32)
1572     /* close network clients */
1573     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1574         VLANClientState *vc;
1575
1576         for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1577             if (vc->fd_read == tap_receive) {
1578                 char ifname[64];
1579                 TAPState *s = vc->opaque;
1580
1581                 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
1582                     s->down_script[0])
1583                     launch_script(s->down_script, ifname, s->fd);
1584             }
1585 #if defined(CONFIG_VDE)
1586             if (vc->fd_read == vde_from_qemu) {
1587                 VDEState *s = vc->opaque;
1588                 vde_close(s->vde);
1589             }
1590 #endif
1591         }
1592     }
1593 #endif
1594 }
1595
1596 void net_client_check(void)
1597 {
1598     VLANState *vlan;
1599
1600     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1601         if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
1602             continue;
1603         if (vlan->nb_guest_devs == 0)
1604             fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
1605         if (vlan->nb_host_devs == 0)
1606             fprintf(stderr,
1607                     "Warning: vlan %d is not connected to host network\n",
1608                     vlan->id);
1609     }
1610 }