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