net: Untangle nested qemu_send_packet (Jan Kiszka)
[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 <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
31
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
34
35 #ifndef _WIN32
36 #include <sys/times.h>
37 #include <sys/wait.h>
38 #include <termios.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/resource.h>
42 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <net/if.h>
45 #ifdef __NetBSD__
46 #include <net/if_tap.h>
47 #endif
48 #ifdef __linux__
49 #include <linux/if_tun.h>
50 #endif
51 #include <arpa/inet.h>
52 #include <dirent.h>
53 #include <netdb.h>
54 #include <sys/select.h>
55 #ifdef HOST_BSD
56 #include <sys/stat.h>
57 #if defined(__FreeBSD__) || defined(__DragonFly__)
58 #include <libutil.h>
59 #else
60 #include <util.h>
61 #endif
62 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
63 #include <freebsd/stdlib.h>
64 #else
65 #ifdef __linux__
66 #include <pty.h>
67 #include <malloc.h>
68 #include <linux/rtc.h>
69
70 /* For the benefit of older linux systems which don't supply it,
71    we use a local copy of hpet.h. */
72 /* #include <linux/hpet.h> */
73 #include "hpet.h"
74
75 #include <linux/ppdev.h>
76 #include <linux/parport.h>
77 #endif
78 #ifdef __sun__
79 #include <sys/stat.h>
80 #include <sys/ethernet.h>
81 #include <sys/sockio.h>
82 #include <netinet/arp.h>
83 #include <netinet/in.h>
84 #include <netinet/in_systm.h>
85 #include <netinet/ip.h>
86 #include <netinet/ip_icmp.h> // must come after ip.h
87 #include <netinet/udp.h>
88 #include <netinet/tcp.h>
89 #include <net/if.h>
90 #include <syslog.h>
91 #include <stropts.h>
92 #endif
93 #endif
94 #endif
95
96 #if defined(__OpenBSD__)
97 #include <util.h>
98 #endif
99
100 #if defined(CONFIG_VDE)
101 #include <libvdeplug.h>
102 #endif
103
104 #ifdef _WIN32
105 #include <windows.h>
106 #include <malloc.h>
107 #include <sys/timeb.h>
108 #include <mmsystem.h>
109 #define getopt_long_only getopt_long
110 #define memalign(align, size) malloc(size)
111 #endif
112
113 #include "qemu-common.h"
114 #include "net.h"
115 #include "monitor.h"
116 #include "sysemu.h"
117 #include "qemu-timer.h"
118 #include "qemu-char.h"
119 #include "audio/audio.h"
120 #include "qemu_socket.h"
121 #include "qemu-log.h"
122
123 #if defined(CONFIG_SLIRP)
124 #include "libslirp.h"
125 #endif
126
127
128 static VLANState *first_vlan;
129
130 /***********************************************************/
131 /* network device redirectors */
132
133 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
134 static void hex_dump(FILE *f, const uint8_t *buf, int size)
135 {
136     int len, i, j, c;
137
138     for(i=0;i<size;i+=16) {
139         len = size - i;
140         if (len > 16)
141             len = 16;
142         fprintf(f, "%08x ", i);
143         for(j=0;j<16;j++) {
144             if (j < len)
145                 fprintf(f, " %02x", buf[i+j]);
146             else
147                 fprintf(f, "   ");
148         }
149         fprintf(f, " ");
150         for(j=0;j<len;j++) {
151             c = buf[i+j];
152             if (c < ' ' || c > '~')
153                 c = '.';
154             fprintf(f, "%c", c);
155         }
156         fprintf(f, "\n");
157     }
158 }
159 #endif
160
161 static int parse_macaddr(uint8_t *macaddr, const char *p)
162 {
163     int i;
164     char *last_char;
165     long int offset;
166
167     errno = 0;
168     offset = strtol(p, &last_char, 0);    
169     if (0 == errno && '\0' == *last_char &&
170             offset >= 0 && offset <= 0xFFFFFF) {
171         macaddr[3] = (offset & 0xFF0000) >> 16;
172         macaddr[4] = (offset & 0xFF00) >> 8;
173         macaddr[5] = offset & 0xFF;
174         return 0;
175     } else {
176         for(i = 0; i < 6; i++) {
177             macaddr[i] = strtol(p, (char **)&p, 16);
178             if (i == 5) {
179                 if (*p != '\0')
180                     return -1;
181             } else {
182                 if (*p != ':' && *p != '-')
183                     return -1;
184                 p++;
185             }
186         }
187         return 0;    
188     }
189
190     return -1;
191 }
192
193 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
194 {
195     const char *p, *p1;
196     int len;
197     p = *pp;
198     p1 = strchr(p, sep);
199     if (!p1)
200         return -1;
201     len = p1 - p;
202     p1++;
203     if (buf_size > 0) {
204         if (len > buf_size - 1)
205             len = buf_size - 1;
206         memcpy(buf, p, len);
207         buf[len] = '\0';
208     }
209     *pp = p1;
210     return 0;
211 }
212
213 int parse_host_src_port(struct sockaddr_in *haddr,
214                         struct sockaddr_in *saddr,
215                         const char *input_str)
216 {
217     char *str = strdup(input_str);
218     char *host_str = str;
219     char *src_str;
220     const char *src_str2;
221     char *ptr;
222
223     /*
224      * Chop off any extra arguments at the end of the string which
225      * would start with a comma, then fill in the src port information
226      * if it was provided else use the "any address" and "any port".
227      */
228     if ((ptr = strchr(str,',')))
229         *ptr = '\0';
230
231     if ((src_str = strchr(input_str,'@'))) {
232         *src_str = '\0';
233         src_str++;
234     }
235
236     if (parse_host_port(haddr, host_str) < 0)
237         goto fail;
238
239     src_str2 = src_str;
240     if (!src_str || *src_str == '\0')
241         src_str2 = ":0";
242
243     if (parse_host_port(saddr, src_str2) < 0)
244         goto fail;
245
246     free(str);
247     return(0);
248
249 fail:
250     free(str);
251     return -1;
252 }
253
254 int parse_host_port(struct sockaddr_in *saddr, const char *str)
255 {
256     char buf[512];
257     struct hostent *he;
258     const char *p, *r;
259     int port;
260
261     p = str;
262     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
263         return -1;
264     saddr->sin_family = AF_INET;
265     if (buf[0] == '\0') {
266         saddr->sin_addr.s_addr = 0;
267     } else {
268         if (qemu_isdigit(buf[0])) {
269             if (!inet_aton(buf, &saddr->sin_addr))
270                 return -1;
271         } else {
272             if ((he = gethostbyname(buf)) == NULL)
273                 return - 1;
274             saddr->sin_addr = *(struct in_addr *)he->h_addr;
275         }
276     }
277     port = strtol(p, (char **)&r, 0);
278     if (r == p)
279         return -1;
280     saddr->sin_port = htons(port);
281     return 0;
282 }
283
284 #if !defined(_WIN32) && 0
285 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
286 {
287     const char *p;
288     int len;
289
290     len = MIN(108, strlen(str));
291     p = strchr(str, ',');
292     if (p)
293         len = MIN(len, p - str);
294
295     memset(uaddr, 0, sizeof(*uaddr));
296
297     uaddr->sun_family = AF_UNIX;
298     memcpy(uaddr->sun_path, str, len);
299
300     return 0;
301 }
302 #endif
303
304 void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6])
305 {
306     snprintf(vc->info_str, sizeof(vc->info_str),
307              "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
308              vc->model,
309              macaddr[0], macaddr[1], macaddr[2],
310              macaddr[3], macaddr[4], macaddr[5]);
311 }
312
313 static char *assign_name(VLANClientState *vc1, const char *model)
314 {
315     VLANState *vlan;
316     char buf[256];
317     int id = 0;
318
319     for (vlan = first_vlan; vlan; vlan = vlan->next) {
320         VLANClientState *vc;
321
322         for (vc = vlan->first_client; vc; vc = vc->next)
323             if (vc != vc1 && strcmp(vc->model, model) == 0)
324                 id++;
325     }
326
327     snprintf(buf, sizeof(buf), "%s.%d", model, id);
328
329     return strdup(buf);
330 }
331
332 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
333                                       const char *model,
334                                       const char *name,
335                                       IOReadHandler *fd_read,
336                                       IOCanRWHandler *fd_can_read,
337                                       NetCleanup *cleanup,
338                                       void *opaque)
339 {
340     VLANClientState *vc, **pvc;
341     vc = qemu_mallocz(sizeof(VLANClientState));
342     vc->model = strdup(model);
343     if (name)
344         vc->name = strdup(name);
345     else
346         vc->name = assign_name(vc, model);
347     vc->fd_read = fd_read;
348     vc->fd_can_read = fd_can_read;
349     vc->cleanup = cleanup;
350     vc->opaque = opaque;
351     vc->vlan = vlan;
352
353     vc->next = NULL;
354     pvc = &vlan->first_client;
355     while (*pvc != NULL)
356         pvc = &(*pvc)->next;
357     *pvc = vc;
358     return vc;
359 }
360
361 void qemu_del_vlan_client(VLANClientState *vc)
362 {
363     VLANClientState **pvc = &vc->vlan->first_client;
364
365     while (*pvc != NULL)
366         if (*pvc == vc) {
367             *pvc = vc->next;
368             if (vc->cleanup) {
369                 vc->cleanup(vc);
370             }
371             free(vc->name);
372             free(vc->model);
373             qemu_free(vc);
374             break;
375         } else
376             pvc = &(*pvc)->next;
377 }
378
379 VLANClientState *qemu_find_vlan_client(VLANState *vlan, void *opaque)
380 {
381     VLANClientState **pvc = &vlan->first_client;
382
383     while (*pvc != NULL)
384         if ((*pvc)->opaque == opaque)
385             return *pvc;
386         else
387             pvc = &(*pvc)->next;
388
389     return NULL;
390 }
391
392 int qemu_can_send_packet(VLANClientState *vc1)
393 {
394     VLANState *vlan = vc1->vlan;
395     VLANClientState *vc;
396
397     for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
398         if (vc != vc1) {
399             if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
400                 return 1;
401         }
402     }
403     return 0;
404 }
405
406 static void
407 qemu_deliver_packet(VLANClientState *sender, const uint8_t *buf, int size)
408 {
409     VLANClientState *vc;
410
411     for (vc = sender->vlan->first_client; vc != NULL; vc = vc->next) {
412         if (vc != sender && !vc->link_down) {
413             vc->fd_read(vc->opaque, buf, size);
414         }
415     }
416 }
417
418 void qemu_send_packet(VLANClientState *vc, const uint8_t *buf, int size)
419 {
420     VLANState *vlan = vc->vlan;
421     VLANPacket *packet;
422
423     if (vc->link_down)
424         return;
425
426 #ifdef DEBUG_NET
427     printf("vlan %d send:\n", vlan->id);
428     hex_dump(stdout, buf, size);
429 #endif
430     if (vlan->delivering) {
431         packet = qemu_malloc(sizeof(VLANPacket) + size);
432         packet->next = vlan->send_queue;
433         packet->sender = vc;
434         packet->size = size;
435         memcpy(packet->data, buf, size);
436         vlan->send_queue = packet;
437     } else {
438         vlan->delivering = 1;
439         qemu_deliver_packet(vc, buf, size);
440         while ((packet = vlan->send_queue) != NULL) {
441             qemu_deliver_packet(packet->sender, packet->data, packet->size);
442             vlan->send_queue = packet->next;
443             qemu_free(packet);
444         }
445         vlan->delivering = 0;
446     }
447 }
448
449 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
450                                int iovcnt)
451 {
452     uint8_t buffer[4096];
453     size_t offset = 0;
454     int i;
455
456     for (i = 0; i < iovcnt; i++) {
457         size_t len;
458
459         len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
460         memcpy(buffer + offset, iov[i].iov_base, len);
461         offset += len;
462     }
463
464     vc->fd_read(vc->opaque, buffer, offset);
465
466     return offset;
467 }
468
469 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
470 {
471     size_t offset = 0;
472     int i;
473
474     for (i = 0; i < iovcnt; i++)
475         offset += iov[i].iov_len;
476     return offset;
477 }
478
479 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
480                           int iovcnt)
481 {
482     VLANState *vlan = vc1->vlan;
483     VLANClientState *vc;
484     ssize_t max_len = 0;
485
486     if (vc1->link_down)
487         return calc_iov_length(iov, iovcnt);
488
489     for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
490         ssize_t len = 0;
491
492         if (vc == vc1)
493             continue;
494
495         if (vc->link_down)
496             len = calc_iov_length(iov, iovcnt);
497         if (vc->fd_readv)
498             len = vc->fd_readv(vc->opaque, iov, iovcnt);
499         else if (vc->fd_read)
500             len = vc_sendv_compat(vc, iov, iovcnt);
501
502         max_len = MAX(max_len, len);
503     }
504
505     return max_len;
506 }
507
508 #if defined(CONFIG_SLIRP)
509
510 /* slirp network adapter */
511
512 static int slirp_inited;
513 static int slirp_restrict;
514 static char *slirp_ip;
515 static VLANClientState *slirp_vc;
516
517 int slirp_can_output(void)
518 {
519     return !slirp_vc || qemu_can_send_packet(slirp_vc);
520 }
521
522 void slirp_output(const uint8_t *pkt, int pkt_len)
523 {
524 #ifdef DEBUG_SLIRP
525     printf("slirp output:\n");
526     hex_dump(stdout, pkt, pkt_len);
527 #endif
528     if (!slirp_vc)
529         return;
530     qemu_send_packet(slirp_vc, pkt, pkt_len);
531 }
532
533 int slirp_is_inited(void)
534 {
535     return slirp_inited;
536 }
537
538 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
539 {
540 #ifdef DEBUG_SLIRP
541     printf("slirp input:\n");
542     hex_dump(stdout, buf, size);
543 #endif
544     slirp_input(buf, size);
545 }
546
547 static int net_slirp_init(VLANState *vlan, const char *model, const char *name)
548 {
549     if (!slirp_inited) {
550         slirp_inited = 1;
551         slirp_init(slirp_restrict, slirp_ip);
552     }
553     slirp_vc = qemu_new_vlan_client(vlan, model, name,
554                                     slirp_receive, NULL, NULL, NULL);
555     slirp_vc->info_str[0] = '\0';
556     return 0;
557 }
558
559 void net_slirp_redir(const char *redir_str)
560 {
561     int is_udp;
562     char buf[256], *r;
563     const char *p;
564     struct in_addr guest_addr;
565     int host_port, guest_port;
566
567     if (!slirp_inited) {
568         slirp_inited = 1;
569         slirp_init(slirp_restrict, slirp_ip);
570     }
571
572     p = redir_str;
573     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
574         goto fail;
575     if (!strcmp(buf, "tcp")) {
576         is_udp = 0;
577     } else if (!strcmp(buf, "udp")) {
578         is_udp = 1;
579     } else {
580         goto fail;
581     }
582
583     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
584         goto fail;
585     host_port = strtol(buf, &r, 0);
586     if (r == buf)
587         goto fail;
588
589     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
590         goto fail;
591     if (buf[0] == '\0') {
592         pstrcpy(buf, sizeof(buf), "10.0.2.15");
593     }
594     if (!inet_aton(buf, &guest_addr))
595         goto fail;
596
597     guest_port = strtol(p, &r, 0);
598     if (r == p)
599         goto fail;
600
601     if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
602         fprintf(stderr, "qemu: could not set up redirection\n");
603         exit(1);
604     }
605     return;
606  fail:
607     fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
608     exit(1);
609 }
610
611 #ifndef _WIN32
612
613 static char smb_dir[1024];
614
615 static void erase_dir(char *dir_name)
616 {
617     DIR *d;
618     struct dirent *de;
619     char filename[1024];
620
621     /* erase all the files in the directory */
622     if ((d = opendir(dir_name)) != NULL) {
623         for(;;) {
624             de = readdir(d);
625             if (!de)
626                 break;
627             if (strcmp(de->d_name, ".") != 0 &&
628                 strcmp(de->d_name, "..") != 0) {
629                 snprintf(filename, sizeof(filename), "%s/%s",
630                          smb_dir, de->d_name);
631                 if (unlink(filename) != 0)  /* is it a directory? */
632                     erase_dir(filename);
633             }
634         }
635         closedir(d);
636         rmdir(dir_name);
637     }
638 }
639
640 /* automatic user mode samba server configuration */
641 static void smb_exit(void)
642 {
643     erase_dir(smb_dir);
644 }
645
646 /* automatic user mode samba server configuration */
647 void net_slirp_smb(const char *exported_dir)
648 {
649     char smb_conf[1024];
650     char smb_cmdline[1024];
651     FILE *f;
652
653     if (!slirp_inited) {
654         slirp_inited = 1;
655         slirp_init(slirp_restrict, slirp_ip);
656     }
657
658     /* XXX: better tmp dir construction */
659     snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
660     if (mkdir(smb_dir, 0700) < 0) {
661         fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
662         exit(1);
663     }
664     snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
665
666     f = fopen(smb_conf, "w");
667     if (!f) {
668         fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
669         exit(1);
670     }
671     fprintf(f,
672             "[global]\n"
673             "private dir=%s\n"
674             "smb ports=0\n"
675             "socket address=127.0.0.1\n"
676             "pid directory=%s\n"
677             "lock directory=%s\n"
678             "log file=%s/log.smbd\n"
679             "smb passwd file=%s/smbpasswd\n"
680             "security = share\n"
681             "[qemu]\n"
682             "path=%s\n"
683             "read only=no\n"
684             "guest ok=yes\n",
685             smb_dir,
686             smb_dir,
687             smb_dir,
688             smb_dir,
689             smb_dir,
690             exported_dir
691             );
692     fclose(f);
693     atexit(smb_exit);
694
695     snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
696              SMBD_COMMAND, smb_conf);
697
698     slirp_add_exec(0, smb_cmdline, 4, 139);
699 }
700
701 #endif /* !defined(_WIN32) */
702 void do_info_slirp(Monitor *mon)
703 {
704     slirp_stats();
705 }
706
707 struct VMChannel {
708     CharDriverState *hd;
709     int port;
710 };
711
712 static int vmchannel_can_read(void *opaque)
713 {
714     struct VMChannel *vmc = (struct VMChannel*)opaque;
715     return slirp_socket_can_recv(4, vmc->port);
716 }
717
718 static void vmchannel_read(void *opaque, const uint8_t *buf, int size)
719 {
720     struct VMChannel *vmc = (struct VMChannel*)opaque;
721     slirp_socket_recv(4, vmc->port, buf, size);
722 }
723
724 #endif /* CONFIG_SLIRP */
725
726 #if !defined(_WIN32)
727
728 typedef struct TAPState {
729     VLANClientState *vc;
730     int fd;
731     char down_script[1024];
732     char down_script_arg[128];
733 } TAPState;
734
735 static int launch_script(const char *setup_script, const char *ifname, int fd);
736
737 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
738                                int iovcnt)
739 {
740     TAPState *s = opaque;
741     ssize_t len;
742
743     do {
744         len = writev(s->fd, iov, iovcnt);
745     } while (len == -1 && (errno == EINTR || errno == EAGAIN));
746
747     return len;
748 }
749
750 static void tap_receive(void *opaque, const uint8_t *buf, int size)
751 {
752     TAPState *s = opaque;
753     int ret;
754     for(;;) {
755         ret = write(s->fd, buf, size);
756         if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
757         } else {
758             break;
759         }
760     }
761 }
762
763 static void tap_send(void *opaque)
764 {
765     TAPState *s = opaque;
766     uint8_t buf[4096];
767     int size;
768
769 #ifdef __sun__
770     struct strbuf sbuf;
771     int f = 0;
772     sbuf.maxlen = sizeof(buf);
773     sbuf.buf = (char *)buf;
774     size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
775 #else
776     size = read(s->fd, buf, sizeof(buf));
777 #endif
778     if (size > 0) {
779         qemu_send_packet(s->vc, buf, size);
780     }
781 }
782
783 static void tap_cleanup(VLANClientState *vc)
784 {
785     TAPState *s = vc->opaque;
786
787     if (s->down_script[0])
788         launch_script(s->down_script, s->down_script_arg, s->fd);
789
790     qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
791     close(s->fd);
792     qemu_free(s);
793 }
794
795 /* fd support */
796
797 static TAPState *net_tap_fd_init(VLANState *vlan,
798                                  const char *model,
799                                  const char *name,
800                                  int fd)
801 {
802     TAPState *s;
803
804     s = qemu_mallocz(sizeof(TAPState));
805     s->fd = fd;
806     s->vc = qemu_new_vlan_client(vlan, model, name, tap_receive,
807                                  NULL, tap_cleanup, s);
808     s->vc->fd_readv = tap_receive_iov;
809     qemu_set_fd_handler(s->fd, tap_send, NULL, s);
810     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
811     return s;
812 }
813
814 #if defined (HOST_BSD) || defined (__FreeBSD_kernel__)
815 static int tap_open(char *ifname, int ifname_size)
816 {
817     int fd;
818     char *dev;
819     struct stat s;
820
821     TFR(fd = open("/dev/tap", O_RDWR));
822     if (fd < 0) {
823         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
824         return -1;
825     }
826
827     fstat(fd, &s);
828     dev = devname(s.st_rdev, S_IFCHR);
829     pstrcpy(ifname, ifname_size, dev);
830
831     fcntl(fd, F_SETFL, O_NONBLOCK);
832     return fd;
833 }
834 #elif defined(__sun__)
835 #define TUNNEWPPA       (('T'<<16) | 0x0001)
836 /*
837  * Allocate TAP device, returns opened fd.
838  * Stores dev name in the first arg(must be large enough).
839  */
840 static int tap_alloc(char *dev, size_t dev_size)
841 {
842     int tap_fd, if_fd, ppa = -1;
843     static int ip_fd = 0;
844     char *ptr;
845
846     static int arp_fd = 0;
847     int ip_muxid, arp_muxid;
848     struct strioctl  strioc_if, strioc_ppa;
849     int link_type = I_PLINK;;
850     struct lifreq ifr;
851     char actual_name[32] = "";
852
853     memset(&ifr, 0x0, sizeof(ifr));
854
855     if( *dev ){
856        ptr = dev;
857        while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
858        ppa = atoi(ptr);
859     }
860
861     /* Check if IP device was opened */
862     if( ip_fd )
863        close(ip_fd);
864
865     TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
866     if (ip_fd < 0) {
867        syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
868        return -1;
869     }
870
871     TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
872     if (tap_fd < 0) {
873        syslog(LOG_ERR, "Can't open /dev/tap");
874        return -1;
875     }
876
877     /* Assign a new PPA and get its unit number. */
878     strioc_ppa.ic_cmd = TUNNEWPPA;
879     strioc_ppa.ic_timout = 0;
880     strioc_ppa.ic_len = sizeof(ppa);
881     strioc_ppa.ic_dp = (char *)&ppa;
882     if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
883        syslog (LOG_ERR, "Can't assign new interface");
884
885     TFR(if_fd = open("/dev/tap", O_RDWR, 0));
886     if (if_fd < 0) {
887        syslog(LOG_ERR, "Can't open /dev/tap (2)");
888        return -1;
889     }
890     if(ioctl(if_fd, I_PUSH, "ip") < 0){
891        syslog(LOG_ERR, "Can't push IP module");
892        return -1;
893     }
894
895     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
896         syslog(LOG_ERR, "Can't get flags\n");
897
898     snprintf (actual_name, 32, "tap%d", ppa);
899     pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
900
901     ifr.lifr_ppa = ppa;
902     /* Assign ppa according to the unit number returned by tun device */
903
904     if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
905         syslog (LOG_ERR, "Can't set PPA %d", ppa);
906     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
907         syslog (LOG_ERR, "Can't get flags\n");
908     /* Push arp module to if_fd */
909     if (ioctl (if_fd, I_PUSH, "arp") < 0)
910         syslog (LOG_ERR, "Can't push ARP module (2)");
911
912     /* Push arp module to ip_fd */
913     if (ioctl (ip_fd, I_POP, NULL) < 0)
914         syslog (LOG_ERR, "I_POP failed\n");
915     if (ioctl (ip_fd, I_PUSH, "arp") < 0)
916         syslog (LOG_ERR, "Can't push ARP module (3)\n");
917     /* Open arp_fd */
918     TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
919     if (arp_fd < 0)
920        syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
921
922     /* Set ifname to arp */
923     strioc_if.ic_cmd = SIOCSLIFNAME;
924     strioc_if.ic_timout = 0;
925     strioc_if.ic_len = sizeof(ifr);
926     strioc_if.ic_dp = (char *)&ifr;
927     if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
928         syslog (LOG_ERR, "Can't set ifname to arp\n");
929     }
930
931     if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
932        syslog(LOG_ERR, "Can't link TAP device to IP");
933        return -1;
934     }
935
936     if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
937         syslog (LOG_ERR, "Can't link TAP device to ARP");
938
939     close (if_fd);
940
941     memset(&ifr, 0x0, sizeof(ifr));
942     pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
943     ifr.lifr_ip_muxid  = ip_muxid;
944     ifr.lifr_arp_muxid = arp_muxid;
945
946     if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
947     {
948       ioctl (ip_fd, I_PUNLINK , arp_muxid);
949       ioctl (ip_fd, I_PUNLINK, ip_muxid);
950       syslog (LOG_ERR, "Can't set multiplexor id");
951     }
952
953     snprintf(dev, dev_size, "tap%d", ppa);
954     return tap_fd;
955 }
956
957 static int tap_open(char *ifname, int ifname_size)
958 {
959     char  dev[10]="";
960     int fd;
961     if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
962        fprintf(stderr, "Cannot allocate TAP device\n");
963        return -1;
964     }
965     pstrcpy(ifname, ifname_size, dev);
966     fcntl(fd, F_SETFL, O_NONBLOCK);
967     return fd;
968 }
969 #elif defined (_AIX)
970 static int tap_open(char *ifname, int ifname_size)
971 {
972     fprintf (stderr, "no tap on AIX\n");
973     return -1;
974 }
975 #else
976 static int tap_open(char *ifname, int ifname_size)
977 {
978     struct ifreq ifr;
979     int fd, ret;
980
981     TFR(fd = open("/dev/net/tun", O_RDWR));
982     if (fd < 0) {
983         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
984         return -1;
985     }
986     memset(&ifr, 0, sizeof(ifr));
987     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
988     if (ifname[0] != '\0')
989         pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
990     else
991         pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
992     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
993     if (ret != 0) {
994         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
995         close(fd);
996         return -1;
997     }
998     pstrcpy(ifname, ifname_size, ifr.ifr_name);
999     fcntl(fd, F_SETFL, O_NONBLOCK);
1000     return fd;
1001 }
1002 #endif
1003
1004 static int launch_script(const char *setup_script, const char *ifname, int fd)
1005 {
1006     int pid, status;
1007     char *args[3];
1008     char **parg;
1009
1010         /* try to launch network script */
1011         pid = fork();
1012         if (pid >= 0) {
1013             if (pid == 0) {
1014                 int open_max = sysconf (_SC_OPEN_MAX), i;
1015                 for (i = 0; i < open_max; i++)
1016                     if (i != STDIN_FILENO &&
1017                         i != STDOUT_FILENO &&
1018                         i != STDERR_FILENO &&
1019                         i != fd)
1020                         close(i);
1021
1022                 parg = args;
1023                 *parg++ = (char *)setup_script;
1024                 *parg++ = (char *)ifname;
1025                 *parg++ = NULL;
1026                 execv(setup_script, args);
1027                 _exit(1);
1028             }
1029             while (waitpid(pid, &status, 0) != pid);
1030             if (!WIFEXITED(status) ||
1031                 WEXITSTATUS(status) != 0) {
1032                 fprintf(stderr, "%s: could not launch network script\n",
1033                         setup_script);
1034                 return -1;
1035             }
1036         }
1037     return 0;
1038 }
1039
1040 static int net_tap_init(VLANState *vlan, const char *model,
1041                         const char *name, const char *ifname1,
1042                         const char *setup_script, const char *down_script)
1043 {
1044     TAPState *s;
1045     int fd;
1046     char ifname[128];
1047
1048     if (ifname1 != NULL)
1049         pstrcpy(ifname, sizeof(ifname), ifname1);
1050     else
1051         ifname[0] = '\0';
1052     TFR(fd = tap_open(ifname, sizeof(ifname)));
1053     if (fd < 0)
1054         return -1;
1055
1056     if (!setup_script || !strcmp(setup_script, "no"))
1057         setup_script = "";
1058     if (setup_script[0] != '\0') {
1059         if (launch_script(setup_script, ifname, fd))
1060             return -1;
1061     }
1062     s = net_tap_fd_init(vlan, model, name, fd);
1063     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1064              "ifname=%s,script=%s,downscript=%s",
1065              ifname, setup_script, down_script);
1066     if (down_script && strcmp(down_script, "no")) {
1067         snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1068         snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1069     }
1070     return 0;
1071 }
1072
1073 #endif /* !_WIN32 */
1074
1075 #if defined(CONFIG_VDE)
1076 typedef struct VDEState {
1077     VLANClientState *vc;
1078     VDECONN *vde;
1079 } VDEState;
1080
1081 static void vde_to_qemu(void *opaque)
1082 {
1083     VDEState *s = opaque;
1084     uint8_t buf[4096];
1085     int size;
1086
1087     size = vde_recv(s->vde, buf, sizeof(buf), 0);
1088     if (size > 0) {
1089         qemu_send_packet(s->vc, buf, size);
1090     }
1091 }
1092
1093 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
1094 {
1095     VDEState *s = opaque;
1096     int ret;
1097     for(;;) {
1098         ret = vde_send(s->vde, buf, size, 0);
1099         if (ret < 0 && errno == EINTR) {
1100         } else {
1101             break;
1102         }
1103     }
1104 }
1105
1106 static void vde_cleanup(VLANClientState *vc)
1107 {
1108     VDEState *s = vc->opaque;
1109     qemu_set_fd_handler(vde_datafd(s->vde), NULL, NULL, NULL);
1110     vde_close(s->vde);
1111     qemu_free(s);
1112 }
1113
1114 static int net_vde_init(VLANState *vlan, const char *model,
1115                         const char *name, const char *sock,
1116                         int port, const char *group, int mode)
1117 {
1118     VDEState *s;
1119     char *init_group = strlen(group) ? (char *)group : NULL;
1120     char *init_sock = strlen(sock) ? (char *)sock : NULL;
1121
1122     struct vde_open_args args = {
1123         .port = port,
1124         .group = init_group,
1125         .mode = mode,
1126     };
1127
1128     s = qemu_mallocz(sizeof(VDEState));
1129     s->vde = vde_open(init_sock, "QEMU", &args);
1130     if (!s->vde){
1131         free(s);
1132         return -1;
1133     }
1134     s->vc = qemu_new_vlan_client(vlan, model, name, vde_from_qemu,
1135                                  NULL, vde_cleanup, s);
1136     qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1137     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1138              sock, vde_datafd(s->vde));
1139     return 0;
1140 }
1141 #endif
1142
1143 /* network connection */
1144 typedef struct NetSocketState {
1145     VLANClientState *vc;
1146     int fd;
1147     int state; /* 0 = getting length, 1 = getting data */
1148     unsigned int index;
1149     unsigned int packet_len;
1150     uint8_t buf[4096];
1151     struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1152 } NetSocketState;
1153
1154 typedef struct NetSocketListenState {
1155     VLANState *vlan;
1156     char *model;
1157     char *name;
1158     int fd;
1159 } NetSocketListenState;
1160
1161 /* XXX: we consider we can send the whole packet without blocking */
1162 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1163 {
1164     NetSocketState *s = opaque;
1165     uint32_t len;
1166     len = htonl(size);
1167
1168     send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1169     send_all(s->fd, buf, size);
1170 }
1171
1172 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1173 {
1174     NetSocketState *s = opaque;
1175     sendto(s->fd, buf, size, 0,
1176            (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1177 }
1178
1179 static void net_socket_send(void *opaque)
1180 {
1181     NetSocketState *s = opaque;
1182     int size, err;
1183     unsigned l;
1184     uint8_t buf1[4096];
1185     const uint8_t *buf;
1186
1187     size = recv(s->fd, buf1, sizeof(buf1), 0);
1188     if (size < 0) {
1189         err = socket_error();
1190         if (err != EWOULDBLOCK)
1191             goto eoc;
1192     } else if (size == 0) {
1193         /* end of connection */
1194     eoc:
1195         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1196         closesocket(s->fd);
1197         return;
1198     }
1199     buf = buf1;
1200     while (size > 0) {
1201         /* reassemble a packet from the network */
1202         switch(s->state) {
1203         case 0:
1204             l = 4 - s->index;
1205             if (l > size)
1206                 l = size;
1207             memcpy(s->buf + s->index, buf, l);
1208             buf += l;
1209             size -= l;
1210             s->index += l;
1211             if (s->index == 4) {
1212                 /* got length */
1213                 s->packet_len = ntohl(*(uint32_t *)s->buf);
1214                 s->index = 0;
1215                 s->state = 1;
1216             }
1217             break;
1218         case 1:
1219             l = s->packet_len - s->index;
1220             if (l > size)
1221                 l = size;
1222             if (s->index + l <= sizeof(s->buf)) {
1223                 memcpy(s->buf + s->index, buf, l);
1224             } else {
1225                 fprintf(stderr, "serious error: oversized packet received,"
1226                     "connection terminated.\n");
1227                 s->state = 0;
1228                 goto eoc;
1229             }
1230
1231             s->index += l;
1232             buf += l;
1233             size -= l;
1234             if (s->index >= s->packet_len) {
1235                 qemu_send_packet(s->vc, s->buf, s->packet_len);
1236                 s->index = 0;
1237                 s->state = 0;
1238             }
1239             break;
1240         }
1241     }
1242 }
1243
1244 static void net_socket_send_dgram(void *opaque)
1245 {
1246     NetSocketState *s = opaque;
1247     int size;
1248
1249     size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1250     if (size < 0)
1251         return;
1252     if (size == 0) {
1253         /* end of connection */
1254         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1255         return;
1256     }
1257     qemu_send_packet(s->vc, s->buf, size);
1258 }
1259
1260 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1261 {
1262     struct ip_mreq imr;
1263     int fd;
1264     int val, ret;
1265     if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1266         fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1267                 inet_ntoa(mcastaddr->sin_addr),
1268                 (int)ntohl(mcastaddr->sin_addr.s_addr));
1269         return -1;
1270
1271     }
1272     fd = socket(PF_INET, SOCK_DGRAM, 0);
1273     if (fd < 0) {
1274         perror("socket(PF_INET, SOCK_DGRAM)");
1275         return -1;
1276     }
1277
1278     val = 1;
1279     ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1280                    (const char *)&val, sizeof(val));
1281     if (ret < 0) {
1282         perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1283         goto fail;
1284     }
1285
1286     ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1287     if (ret < 0) {
1288         perror("bind");
1289         goto fail;
1290     }
1291
1292     /* Add host to multicast group */
1293     imr.imr_multiaddr = mcastaddr->sin_addr;
1294     imr.imr_interface.s_addr = htonl(INADDR_ANY);
1295
1296     ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1297                      (const char *)&imr, sizeof(struct ip_mreq));
1298     if (ret < 0) {
1299         perror("setsockopt(IP_ADD_MEMBERSHIP)");
1300         goto fail;
1301     }
1302
1303     /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1304     val = 1;
1305     ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1306                    (const char *)&val, sizeof(val));
1307     if (ret < 0) {
1308         perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1309         goto fail;
1310     }
1311
1312     socket_set_nonblock(fd);
1313     return fd;
1314 fail:
1315     if (fd >= 0)
1316         closesocket(fd);
1317     return -1;
1318 }
1319
1320 static void net_socket_cleanup(VLANClientState *vc)
1321 {
1322     NetSocketState *s = vc->opaque;
1323     qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1324     close(s->fd);
1325     qemu_free(s);
1326 }
1327
1328 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1329                                                 const char *model,
1330                                                 const char *name,
1331                                                 int fd, int is_connected)
1332 {
1333     struct sockaddr_in saddr;
1334     int newfd;
1335     socklen_t saddr_len;
1336     NetSocketState *s;
1337
1338     /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1339      * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1340      * by ONLY ONE process: we must "clone" this dgram socket --jjo
1341      */
1342
1343     if (is_connected) {
1344         if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1345             /* must be bound */
1346             if (saddr.sin_addr.s_addr==0) {
1347                 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1348                         fd);
1349                 return NULL;
1350             }
1351             /* clone dgram socket */
1352             newfd = net_socket_mcast_create(&saddr);
1353             if (newfd < 0) {
1354                 /* error already reported by net_socket_mcast_create() */
1355                 close(fd);
1356                 return NULL;
1357             }
1358             /* clone newfd to fd, close newfd */
1359             dup2(newfd, fd);
1360             close(newfd);
1361
1362         } else {
1363             fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1364                     fd, strerror(errno));
1365             return NULL;
1366         }
1367     }
1368
1369     s = qemu_mallocz(sizeof(NetSocketState));
1370     s->fd = fd;
1371
1372     s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive_dgram,
1373                                  NULL, net_socket_cleanup, s);
1374     qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1375
1376     /* mcast: save bound address as dst */
1377     if (is_connected) s->dgram_dst=saddr;
1378
1379     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1380             "socket: fd=%d (%s mcast=%s:%d)",
1381             fd, is_connected? "cloned" : "",
1382             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1383     return s;
1384 }
1385
1386 static void net_socket_connect(void *opaque)
1387 {
1388     NetSocketState *s = opaque;
1389     qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1390 }
1391
1392 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1393                                                  const char *model,
1394                                                  const char *name,
1395                                                  int fd, int is_connected)
1396 {
1397     NetSocketState *s;
1398     s = qemu_mallocz(sizeof(NetSocketState));
1399     s->fd = fd;
1400     s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive,
1401                                  NULL, net_socket_cleanup, s);
1402     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1403              "socket: fd=%d", fd);
1404     if (is_connected) {
1405         net_socket_connect(s);
1406     } else {
1407         qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1408     }
1409     return s;
1410 }
1411
1412 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1413                                           const char *model, const char *name,
1414                                           int fd, int is_connected)
1415 {
1416     int so_type=-1, optlen=sizeof(so_type);
1417
1418     if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1419         (socklen_t *)&optlen)< 0) {
1420         fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1421         return NULL;
1422     }
1423     switch(so_type) {
1424     case SOCK_DGRAM:
1425         return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1426     case SOCK_STREAM:
1427         return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1428     default:
1429         /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1430         fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1431         return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1432     }
1433     return NULL;
1434 }
1435
1436 static void net_socket_accept(void *opaque)
1437 {
1438     NetSocketListenState *s = opaque;
1439     NetSocketState *s1;
1440     struct sockaddr_in saddr;
1441     socklen_t len;
1442     int fd;
1443
1444     for(;;) {
1445         len = sizeof(saddr);
1446         fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1447         if (fd < 0 && errno != EINTR) {
1448             return;
1449         } else if (fd >= 0) {
1450             break;
1451         }
1452     }
1453     s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1454     if (!s1) {
1455         closesocket(fd);
1456     } else {
1457         snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1458                  "socket: connection from %s:%d",
1459                  inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1460     }
1461 }
1462
1463 static int net_socket_listen_init(VLANState *vlan,
1464                                   const char *model,
1465                                   const char *name,
1466                                   const char *host_str)
1467 {
1468     NetSocketListenState *s;
1469     int fd, val, ret;
1470     struct sockaddr_in saddr;
1471
1472     if (parse_host_port(&saddr, host_str) < 0)
1473         return -1;
1474
1475     s = qemu_mallocz(sizeof(NetSocketListenState));
1476
1477     fd = socket(PF_INET, SOCK_STREAM, 0);
1478     if (fd < 0) {
1479         perror("socket");
1480         return -1;
1481     }
1482     socket_set_nonblock(fd);
1483
1484     /* allow fast reuse */
1485     val = 1;
1486     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1487
1488     ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1489     if (ret < 0) {
1490         perror("bind");
1491         return -1;
1492     }
1493     ret = listen(fd, 0);
1494     if (ret < 0) {
1495         perror("listen");
1496         return -1;
1497     }
1498     s->vlan = vlan;
1499     s->model = strdup(model);
1500     s->name = name ? strdup(name) : NULL;
1501     s->fd = fd;
1502     qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1503     return 0;
1504 }
1505
1506 static int net_socket_connect_init(VLANState *vlan,
1507                                    const char *model,
1508                                    const char *name,
1509                                    const char *host_str)
1510 {
1511     NetSocketState *s;
1512     int fd, connected, ret, err;
1513     struct sockaddr_in saddr;
1514
1515     if (parse_host_port(&saddr, host_str) < 0)
1516         return -1;
1517
1518     fd = socket(PF_INET, SOCK_STREAM, 0);
1519     if (fd < 0) {
1520         perror("socket");
1521         return -1;
1522     }
1523     socket_set_nonblock(fd);
1524
1525     connected = 0;
1526     for(;;) {
1527         ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1528         if (ret < 0) {
1529             err = socket_error();
1530             if (err == EINTR || err == EWOULDBLOCK) {
1531             } else if (err == EINPROGRESS) {
1532                 break;
1533 #ifdef _WIN32
1534             } else if (err == WSAEALREADY) {
1535                 break;
1536 #endif
1537             } else {
1538                 perror("connect");
1539                 closesocket(fd);
1540                 return -1;
1541             }
1542         } else {
1543             connected = 1;
1544             break;
1545         }
1546     }
1547     s = net_socket_fd_init(vlan, model, name, fd, connected);
1548     if (!s)
1549         return -1;
1550     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1551              "socket: connect to %s:%d",
1552              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1553     return 0;
1554 }
1555
1556 static int net_socket_mcast_init(VLANState *vlan,
1557                                  const char *model,
1558                                  const char *name,
1559                                  const char *host_str)
1560 {
1561     NetSocketState *s;
1562     int fd;
1563     struct sockaddr_in saddr;
1564
1565     if (parse_host_port(&saddr, host_str) < 0)
1566         return -1;
1567
1568
1569     fd = net_socket_mcast_create(&saddr);
1570     if (fd < 0)
1571         return -1;
1572
1573     s = net_socket_fd_init(vlan, model, name, fd, 0);
1574     if (!s)
1575         return -1;
1576
1577     s->dgram_dst = saddr;
1578
1579     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1580              "socket: mcast=%s:%d",
1581              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1582     return 0;
1583
1584 }
1585
1586 typedef struct DumpState {
1587     VLANClientState *pcap_vc;
1588     int fd;
1589     int pcap_caplen;
1590 } DumpState;
1591
1592 #define PCAP_MAGIC 0xa1b2c3d4
1593
1594 struct pcap_file_hdr {
1595     uint32_t magic;
1596     uint16_t version_major;
1597     uint16_t version_minor;
1598     int32_t thiszone;
1599     uint32_t sigfigs;
1600     uint32_t snaplen;
1601     uint32_t linktype;
1602 };
1603
1604 struct pcap_sf_pkthdr {
1605     struct {
1606         int32_t tv_sec;
1607         int32_t tv_usec;
1608     } ts;
1609     uint32_t caplen;
1610     uint32_t len;
1611 };
1612
1613 static void dump_receive(void *opaque, const uint8_t *buf, int size)
1614 {
1615     DumpState *s = opaque;
1616     struct pcap_sf_pkthdr hdr;
1617     int64_t ts;
1618     int caplen;
1619
1620     /* Early return in case of previous error. */
1621     if (s->fd < 0) {
1622         return;
1623     }
1624
1625     ts = muldiv64 (qemu_get_clock(vm_clock),1000000, ticks_per_sec);
1626     caplen = size > s->pcap_caplen ? s->pcap_caplen : size;
1627
1628     hdr.ts.tv_sec = ts / 1000000000LL;
1629     hdr.ts.tv_usec = ts % 1000000;
1630     hdr.caplen = caplen;
1631     hdr.len = size;
1632     if (write(s->fd, &hdr, sizeof(hdr)) != sizeof(hdr) ||
1633         write(s->fd, buf, caplen) != caplen) {
1634         qemu_log("-net dump write error - stop dump\n");
1635         close(s->fd);
1636         s->fd = -1;
1637     }
1638 }
1639
1640 static void net_dump_cleanup(VLANClientState *vc)
1641 {
1642     DumpState *s = vc->opaque;
1643
1644     close(s->fd);
1645     qemu_free(s);
1646 }
1647
1648 static int net_dump_init(VLANState *vlan, const char *device,
1649                          const char *name, const char *filename, int len)
1650 {
1651     struct pcap_file_hdr hdr;
1652     DumpState *s;
1653
1654     s = qemu_malloc(sizeof(DumpState));
1655
1656     s->fd = open(filename, O_CREAT | O_WRONLY, 0644);
1657     if (s->fd < 0) {
1658         fprintf(stderr, "-net dump: can't open %s\n", filename);
1659         return -1;
1660     }
1661
1662     s->pcap_caplen = len;
1663
1664     hdr.magic = PCAP_MAGIC;
1665     hdr.version_major = 2;
1666     hdr.version_minor = 4;
1667     hdr.thiszone = 0;
1668     hdr.sigfigs = 0;
1669     hdr.snaplen = s->pcap_caplen;
1670     hdr.linktype = 1;
1671
1672     if (write(s->fd, &hdr, sizeof(hdr)) < sizeof(hdr)) {
1673         perror("-net dump write error");
1674         close(s->fd);
1675         qemu_free(s);
1676         return -1;
1677     }
1678
1679     s->pcap_vc = qemu_new_vlan_client(vlan, device, name, dump_receive, NULL,
1680                                       net_dump_cleanup, s);
1681     snprintf(s->pcap_vc->info_str, sizeof(s->pcap_vc->info_str),
1682              "dump to %s (len=%d)", filename, len);
1683     return 0;
1684 }
1685
1686 /* find or alloc a new VLAN */
1687 VLANState *qemu_find_vlan(int id)
1688 {
1689     VLANState **pvlan, *vlan;
1690     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1691         if (vlan->id == id)
1692             return vlan;
1693     }
1694     vlan = qemu_mallocz(sizeof(VLANState));
1695     vlan->id = id;
1696     vlan->next = NULL;
1697     pvlan = &first_vlan;
1698     while (*pvlan != NULL)
1699         pvlan = &(*pvlan)->next;
1700     *pvlan = vlan;
1701     return vlan;
1702 }
1703
1704 static int nic_get_free_idx(void)
1705 {
1706     int index;
1707
1708     for (index = 0; index < MAX_NICS; index++)
1709         if (!nd_table[index].used)
1710             return index;
1711     return -1;
1712 }
1713
1714 void qemu_check_nic_model(NICInfo *nd, const char *model)
1715 {
1716     const char *models[2];
1717
1718     models[0] = model;
1719     models[1] = NULL;
1720
1721     qemu_check_nic_model_list(nd, models, model);
1722 }
1723
1724 void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
1725                                const char *default_model)
1726 {
1727     int i, exit_status = 0;
1728
1729     if (!nd->model)
1730         nd->model = strdup(default_model);
1731
1732     if (strcmp(nd->model, "?") != 0) {
1733         for (i = 0 ; models[i]; i++)
1734             if (strcmp(nd->model, models[i]) == 0)
1735                 return;
1736
1737         fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
1738         exit_status = 1;
1739     }
1740
1741     fprintf(stderr, "qemu: Supported NIC models: ");
1742     for (i = 0 ; models[i]; i++)
1743         fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1744
1745     exit(exit_status);
1746 }
1747
1748 int net_client_init(const char *device, const char *p)
1749 {
1750     static const char * const fd_params[] = {
1751         "vlan", "name", "fd", NULL
1752     };
1753     char buf[1024];
1754     int vlan_id, ret;
1755     VLANState *vlan;
1756     char *name = NULL;
1757
1758     vlan_id = 0;
1759     if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1760         vlan_id = strtol(buf, NULL, 0);
1761     }
1762     vlan = qemu_find_vlan(vlan_id);
1763
1764     if (get_param_value(buf, sizeof(buf), "name", p)) {
1765         name = strdup(buf);
1766     }
1767     if (!strcmp(device, "nic")) {
1768         static const char * const nic_params[] = {
1769             "vlan", "name", "macaddr", "model", NULL
1770         };
1771         NICInfo *nd;
1772         uint8_t *macaddr;
1773         int idx = nic_get_free_idx();
1774
1775         if (check_params(buf, sizeof(buf), nic_params, p) < 0) {
1776             fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1777                     buf, p);
1778             return -1;
1779         }
1780         if (idx == -1 || nb_nics >= MAX_NICS) {
1781             fprintf(stderr, "Too Many NICs\n");
1782             ret = -1;
1783             goto out;
1784         }
1785         nd = &nd_table[idx];
1786         macaddr = nd->macaddr;
1787         macaddr[0] = 0x52;
1788         macaddr[1] = 0x54;
1789         macaddr[2] = 0x00;
1790         macaddr[3] = 0x12;
1791         macaddr[4] = 0x34;
1792         macaddr[5] = 0x56 + idx;
1793
1794         if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1795             if (parse_macaddr(macaddr, buf) < 0) {
1796                 fprintf(stderr, "invalid syntax for ethernet address\n");
1797                 ret = -1;
1798                 goto out;
1799             }
1800         }
1801         if (get_param_value(buf, sizeof(buf), "model", p)) {
1802             nd->model = strdup(buf);
1803         }
1804         nd->vlan = vlan;
1805         nd->name = name;
1806         nd->used = 1;
1807         name = NULL;
1808         nb_nics++;
1809         vlan->nb_guest_devs++;
1810         ret = idx;
1811     } else
1812     if (!strcmp(device, "none")) {
1813         if (*p != '\0') {
1814             fprintf(stderr, "qemu: 'none' takes no parameters\n");
1815             return -1;
1816         }
1817         /* does nothing. It is needed to signal that no network cards
1818            are wanted */
1819         ret = 0;
1820     } else
1821 #ifdef CONFIG_SLIRP
1822     if (!strcmp(device, "user")) {
1823         static const char * const slirp_params[] = {
1824             "vlan", "name", "hostname", "restrict", "ip", NULL
1825         };
1826         if (check_params(buf, sizeof(buf), slirp_params, p) < 0) {
1827             fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1828                     buf, p);
1829             return -1;
1830         }
1831         if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1832             pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1833         }
1834         if (get_param_value(buf, sizeof(buf), "restrict", p)) {
1835             slirp_restrict = (buf[0] == 'y') ? 1 : 0;
1836         }
1837         if (get_param_value(buf, sizeof(buf), "ip", p)) {
1838             slirp_ip = strdup(buf);
1839         }
1840         vlan->nb_host_devs++;
1841         ret = net_slirp_init(vlan, device, name);
1842     } else if (!strcmp(device, "channel")) {
1843         long port;
1844         char name[20], *devname;
1845         struct VMChannel *vmc;
1846
1847         port = strtol(p, &devname, 10);
1848         devname++;
1849         if (port < 1 || port > 65535) {
1850             fprintf(stderr, "vmchannel wrong port number\n");
1851             ret = -1;
1852             goto out;
1853         }
1854         vmc = malloc(sizeof(struct VMChannel));
1855         snprintf(name, 20, "vmchannel%ld", port);
1856         vmc->hd = qemu_chr_open(name, devname, NULL);
1857         if (!vmc->hd) {
1858             fprintf(stderr, "qemu: could not open vmchannel device"
1859                     "'%s'\n", devname);
1860             ret = -1;
1861             goto out;
1862         }
1863         vmc->port = port;
1864         slirp_add_exec(3, vmc->hd, 4, port);
1865         qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,
1866                 NULL, vmc);
1867         ret = 0;
1868     } else
1869 #endif
1870 #ifdef _WIN32
1871     if (!strcmp(device, "tap")) {
1872         static const char * const tap_params[] = {
1873             "vlan", "name", "ifname", NULL
1874         };
1875         char ifname[64];
1876
1877         if (check_params(buf, sizeof(buf), tap_params, p) < 0) {
1878             fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1879                     buf, p);
1880             return -1;
1881         }
1882         if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1883             fprintf(stderr, "tap: no interface name\n");
1884             ret = -1;
1885             goto out;
1886         }
1887         vlan->nb_host_devs++;
1888         ret = tap_win32_init(vlan, device, name, ifname);
1889     } else
1890 #elif defined (_AIX)
1891 #else
1892     if (!strcmp(device, "tap")) {
1893         char ifname[64];
1894         char setup_script[1024], down_script[1024];
1895         int fd;
1896         vlan->nb_host_devs++;
1897         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1898             if (check_params(buf, sizeof(buf), fd_params, p) < 0) {
1899                 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1900                         buf, p);
1901                 return -1;
1902             }
1903             fd = strtol(buf, NULL, 0);
1904             fcntl(fd, F_SETFL, O_NONBLOCK);
1905             net_tap_fd_init(vlan, device, name, fd);
1906             ret = 0;
1907         } else {
1908             static const char * const tap_params[] = {
1909                 "vlan", "name", "ifname", "script", "downscript", NULL
1910             };
1911             if (check_params(buf, sizeof(buf), tap_params, p) < 0) {
1912                 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1913                         buf, p);
1914                 return -1;
1915             }
1916             if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1917                 ifname[0] = '\0';
1918             }
1919             if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1920                 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1921             }
1922             if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1923                 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1924             }
1925             ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
1926         }
1927     } else
1928 #endif
1929     if (!strcmp(device, "socket")) {
1930         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1931             int fd;
1932             if (check_params(buf, sizeof(buf), fd_params, p) < 0) {
1933                 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1934                         buf, p);
1935                 return -1;
1936             }
1937             fd = strtol(buf, NULL, 0);
1938             ret = -1;
1939             if (net_socket_fd_init(vlan, device, name, fd, 1))
1940                 ret = 0;
1941         } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1942             static const char * const listen_params[] = {
1943                 "vlan", "name", "listen", NULL
1944             };
1945             if (check_params(buf, sizeof(buf), listen_params, p) < 0) {
1946                 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1947                         buf, p);
1948                 return -1;
1949             }
1950             ret = net_socket_listen_init(vlan, device, name, buf);
1951         } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1952             static const char * const connect_params[] = {
1953                 "vlan", "name", "connect", NULL
1954             };
1955             if (check_params(buf, sizeof(buf), connect_params, p) < 0) {
1956                 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1957                         buf, p);
1958                 return -1;
1959             }
1960             ret = net_socket_connect_init(vlan, device, name, buf);
1961         } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1962             static const char * const mcast_params[] = {
1963                 "vlan", "name", "mcast", NULL
1964             };
1965             if (check_params(buf, sizeof(buf), mcast_params, p) < 0) {
1966                 fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1967                         buf, p);
1968                 return -1;
1969             }
1970             ret = net_socket_mcast_init(vlan, device, name, buf);
1971         } else {
1972             fprintf(stderr, "Unknown socket options: %s\n", p);
1973             ret = -1;
1974             goto out;
1975         }
1976         vlan->nb_host_devs++;
1977     } else
1978 #ifdef CONFIG_VDE
1979     if (!strcmp(device, "vde")) {
1980         static const char * const vde_params[] = {
1981             "vlan", "name", "sock", "port", "group", "mode", NULL
1982         };
1983         char vde_sock[1024], vde_group[512];
1984         int vde_port, vde_mode;
1985
1986         if (check_params(buf, sizeof(buf), vde_params, p) < 0) {
1987             fprintf(stderr, "qemu: invalid parameter '%s' in '%s'\n",
1988                     buf, p);
1989             return -1;
1990         }
1991         vlan->nb_host_devs++;
1992         if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1993             vde_sock[0] = '\0';
1994         }
1995         if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1996             vde_port = strtol(buf, NULL, 10);
1997         } else {
1998             vde_port = 0;
1999         }
2000         if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
2001             vde_group[0] = '\0';
2002         }
2003         if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
2004             vde_mode = strtol(buf, NULL, 8);
2005         } else {
2006             vde_mode = 0700;
2007         }
2008         ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
2009     } else
2010 #endif
2011     if (!strcmp(device, "dump")) {
2012         int len = 65536;
2013
2014         if (get_param_value(buf, sizeof(buf), "len", p) > 0) {
2015             len = strtol(buf, NULL, 0);
2016         }
2017         if (!get_param_value(buf, sizeof(buf), "file", p)) {
2018             snprintf(buf, sizeof(buf), "qemu-vlan%d.pcap", vlan_id);
2019         }
2020         ret = net_dump_init(vlan, device, name, buf, len);
2021     } else {
2022         fprintf(stderr, "Unknown network device: %s\n", device);
2023         ret = -1;
2024         goto out;
2025     }
2026     if (ret < 0) {
2027         fprintf(stderr, "Could not initialize device '%s'\n", device);
2028     }
2029 out:
2030     if (name)
2031         free(name);
2032     return ret;
2033 }
2034
2035 void net_client_uninit(NICInfo *nd)
2036 {
2037     nd->vlan->nb_guest_devs--;
2038     nb_nics--;
2039     nd->used = 0;
2040     free((void *)nd->model);
2041 }
2042
2043 static int net_host_check_device(const char *device)
2044 {
2045     int i;
2046     const char *valid_param_list[] = { "tap", "socket", "dump"
2047 #ifdef CONFIG_SLIRP
2048                                        ,"user"
2049 #endif
2050 #ifdef CONFIG_VDE
2051                                        ,"vde"
2052 #endif
2053     };
2054     for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
2055         if (!strncmp(valid_param_list[i], device,
2056                      strlen(valid_param_list[i])))
2057             return 1;
2058     }
2059
2060     return 0;
2061 }
2062
2063 void net_host_device_add(Monitor *mon, const char *device, const char *opts)
2064 {
2065     if (!net_host_check_device(device)) {
2066         monitor_printf(mon, "invalid host network device %s\n", device);
2067         return;
2068     }
2069     if (net_client_init(device, opts ? : "") < 0) {
2070         monitor_printf(mon, "adding host network device %s failed\n", device);
2071     }
2072 }
2073
2074 void net_host_device_remove(Monitor *mon, int vlan_id, const char *device)
2075 {
2076     VLANState *vlan;
2077     VLANClientState *vc;
2078
2079     vlan = qemu_find_vlan(vlan_id);
2080
2081     for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
2082         if (!strcmp(vc->name, device)) {
2083             break;
2084         }
2085     }
2086
2087     if (!vc) {
2088         monitor_printf(mon, "can't find device %s\n", device);
2089         return;
2090     }
2091     if (!net_host_check_device(vc->model)) {
2092         monitor_printf(mon, "invalid host network device %s\n", device);
2093         return;
2094     }
2095     qemu_del_vlan_client(vc);
2096 }
2097
2098 int net_client_parse(const char *str)
2099 {
2100     const char *p;
2101     char *q;
2102     char device[64];
2103
2104     p = str;
2105     q = device;
2106     while (*p != '\0' && *p != ',') {
2107         if ((q - device) < sizeof(device) - 1)
2108             *q++ = *p;
2109         p++;
2110     }
2111     *q = '\0';
2112     if (*p == ',')
2113         p++;
2114
2115     return net_client_init(device, p);
2116 }
2117
2118 void do_info_network(Monitor *mon)
2119 {
2120     VLANState *vlan;
2121     VLANClientState *vc;
2122
2123     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2124         monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
2125         for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2126             monitor_printf(mon, "  %s: %s\n", vc->name, vc->info_str);
2127     }
2128 }
2129
2130 int do_set_link(Monitor *mon, const char *name, const char *up_or_down)
2131 {
2132     VLANState *vlan;
2133     VLANClientState *vc = NULL;
2134
2135     for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
2136         for (vc = vlan->first_client; vc != NULL; vc = vc->next)
2137             if (strcmp(vc->name, name) == 0)
2138                 goto done;
2139 done:
2140
2141     if (!vc) {
2142         monitor_printf(mon, "could not find network device '%s'", name);
2143         return 0;
2144     }
2145
2146     if (strcmp(up_or_down, "up") == 0)
2147         vc->link_down = 0;
2148     else if (strcmp(up_or_down, "down") == 0)
2149         vc->link_down = 1;
2150     else
2151         monitor_printf(mon, "invalid link status '%s'; only 'up' or 'down' "
2152                        "valid\n", up_or_down);
2153
2154     if (vc->link_status_changed)
2155         vc->link_status_changed(vc);
2156
2157     return 1;
2158 }
2159
2160 void net_cleanup(void)
2161 {
2162     VLANState *vlan;
2163
2164     /* close network clients */
2165     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2166         VLANClientState *vc = vlan->first_client;
2167
2168         while (vc) {
2169             VLANClientState *next = vc->next;
2170
2171             qemu_del_vlan_client(vc);
2172
2173             vc = next;
2174         }
2175     }
2176 }
2177
2178 void net_client_check(void)
2179 {
2180     VLANState *vlan;
2181
2182     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2183         if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
2184             continue;
2185         if (vlan->nb_guest_devs == 0)
2186             fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
2187         if (vlan->nb_host_devs == 0)
2188             fprintf(stderr,
2189                     "Warning: vlan %d is not connected to host network\n",
2190                     vlan->id);
2191     }
2192 }