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