net: pass VLANClientState* as first arg to receive handlers
[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                                       NetCanReceive *can_receive,
336                                       NetReceive *receive,
337                                       NetReceiveIOV *receive_iov,
338                                       NetCleanup *cleanup,
339                                       void *opaque)
340 {
341     VLANClientState *vc, **pvc;
342     vc = qemu_mallocz(sizeof(VLANClientState));
343     vc->model = strdup(model);
344     if (name)
345         vc->name = strdup(name);
346     else
347         vc->name = assign_name(vc, model);
348     vc->can_receive = can_receive;
349     vc->receive = receive;
350     vc->receive_iov = receive_iov;
351     vc->cleanup = cleanup;
352     vc->opaque = opaque;
353     vc->vlan = vlan;
354
355     vc->next = NULL;
356     pvc = &vlan->first_client;
357     while (*pvc != NULL)
358         pvc = &(*pvc)->next;
359     *pvc = vc;
360     return vc;
361 }
362
363 void qemu_del_vlan_client(VLANClientState *vc)
364 {
365     VLANClientState **pvc = &vc->vlan->first_client;
366
367     while (*pvc != NULL)
368         if (*pvc == vc) {
369             *pvc = vc->next;
370             if (vc->cleanup) {
371                 vc->cleanup(vc);
372             }
373             free(vc->name);
374             free(vc->model);
375             qemu_free(vc);
376             break;
377         } else
378             pvc = &(*pvc)->next;
379 }
380
381 VLANClientState *qemu_find_vlan_client(VLANState *vlan, void *opaque)
382 {
383     VLANClientState **pvc = &vlan->first_client;
384
385     while (*pvc != NULL)
386         if ((*pvc)->opaque == opaque)
387             return *pvc;
388         else
389             pvc = &(*pvc)->next;
390
391     return NULL;
392 }
393
394 int qemu_can_send_packet(VLANClientState *sender)
395 {
396     VLANState *vlan = sender->vlan;
397     VLANClientState *vc;
398
399     for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
400         if (vc == sender) {
401             continue;
402         }
403
404         /* no can_receive() handler, they can always receive */
405         if (!vc->can_receive || vc->can_receive(vc)) {
406             return 1;
407         }
408     }
409     return 0;
410 }
411
412 static void
413 qemu_deliver_packet(VLANClientState *sender, const uint8_t *buf, int size)
414 {
415     VLANClientState *vc;
416
417     for (vc = sender->vlan->first_client; vc != NULL; vc = vc->next) {
418         if (vc != sender && !vc->link_down) {
419             vc->receive(vc, buf, size);
420         }
421     }
422 }
423
424 void qemu_send_packet(VLANClientState *vc, const uint8_t *buf, int size)
425 {
426     VLANState *vlan = vc->vlan;
427     VLANPacket *packet;
428
429     if (vc->link_down)
430         return;
431
432 #ifdef DEBUG_NET
433     printf("vlan %d send:\n", vlan->id);
434     hex_dump(stdout, buf, size);
435 #endif
436     if (vlan->delivering) {
437         packet = qemu_malloc(sizeof(VLANPacket) + size);
438         packet->next = vlan->send_queue;
439         packet->sender = vc;
440         packet->size = size;
441         memcpy(packet->data, buf, size);
442         vlan->send_queue = packet;
443     } else {
444         vlan->delivering = 1;
445         qemu_deliver_packet(vc, buf, size);
446         while ((packet = vlan->send_queue) != NULL) {
447             vlan->send_queue = packet->next;
448             qemu_deliver_packet(packet->sender, packet->data, packet->size);
449             qemu_free(packet);
450         }
451         vlan->delivering = 0;
452     }
453 }
454
455 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
456                                int iovcnt)
457 {
458     uint8_t buffer[4096];
459     size_t offset = 0;
460     int i;
461
462     for (i = 0; i < iovcnt; i++) {
463         size_t len;
464
465         len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
466         memcpy(buffer + offset, iov[i].iov_base, len);
467         offset += len;
468     }
469
470     vc->receive(vc, buffer, offset);
471
472     return offset;
473 }
474
475 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
476 {
477     size_t offset = 0;
478     int i;
479
480     for (i = 0; i < iovcnt; i++)
481         offset += iov[i].iov_len;
482     return offset;
483 }
484
485 ssize_t qemu_sendv_packet(VLANClientState *sender, const struct iovec *iov,
486                           int iovcnt)
487 {
488     VLANState *vlan = sender->vlan;
489     VLANClientState *vc;
490     VLANPacket *packet;
491     ssize_t max_len = 0;
492     int i;
493
494     if (sender->link_down)
495         return calc_iov_length(iov, iovcnt);
496
497     if (vlan->delivering) {
498         max_len = calc_iov_length(iov, iovcnt);
499
500         packet = qemu_malloc(sizeof(VLANPacket) + max_len);
501         packet->next = vlan->send_queue;
502         packet->sender = sender;
503         packet->size = 0;
504         for (i = 0; i < iovcnt; i++) {
505             size_t len = iov[i].iov_len;
506
507             memcpy(packet->data + packet->size, iov[i].iov_base, len);
508             packet->size += len;
509         }
510         vlan->send_queue = packet;
511     } else {
512         vlan->delivering = 1;
513
514         for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
515             ssize_t len = 0;
516
517             if (vc == sender) {
518                 continue;
519             }
520             if (vc->link_down) {
521                 len = calc_iov_length(iov, iovcnt);
522             } else if (vc->receive_iov) {
523                 len = vc->receive_iov(vc, iov, iovcnt);
524             } else if (vc->receive) {
525                 len = vc_sendv_compat(vc, iov, iovcnt);
526             }
527             max_len = MAX(max_len, len);
528         }
529
530         while ((packet = vlan->send_queue) != NULL) {
531             vlan->send_queue = packet->next;
532             qemu_deliver_packet(packet->sender, packet->data, packet->size);
533             qemu_free(packet);
534         }
535         vlan->delivering = 0;
536     }
537
538     return max_len;
539 }
540
541 static void config_error(Monitor *mon, const char *fmt, ...)
542 {
543     va_list ap;
544
545     va_start(ap, fmt);
546     if (mon) {
547         monitor_vprintf(mon, fmt, ap);
548     } else {
549         fprintf(stderr, "qemu: ");
550         vfprintf(stderr, fmt, ap);
551         exit(1);
552     }
553     va_end(ap);
554 }
555
556 #if defined(CONFIG_SLIRP)
557
558 /* slirp network adapter */
559
560 struct slirp_config_str {
561     struct slirp_config_str *next;
562     const char *str;
563 };
564
565 static int slirp_inited;
566 static struct slirp_config_str *slirp_redirs;
567 #ifndef _WIN32
568 static const char *slirp_smb_export;
569 #endif
570 static VLANClientState *slirp_vc;
571
572 static void slirp_smb(const char *exported_dir);
573 static void slirp_redirection(Monitor *mon, const char *redir_str);
574
575 int slirp_can_output(void)
576 {
577     return !slirp_vc || qemu_can_send_packet(slirp_vc);
578 }
579
580 void slirp_output(const uint8_t *pkt, int pkt_len)
581 {
582 #ifdef DEBUG_SLIRP
583     printf("slirp output:\n");
584     hex_dump(stdout, pkt, pkt_len);
585 #endif
586     if (!slirp_vc)
587         return;
588     qemu_send_packet(slirp_vc, pkt, pkt_len);
589 }
590
591 int slirp_is_inited(void)
592 {
593     return slirp_inited;
594 }
595
596 static void slirp_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
597 {
598 #ifdef DEBUG_SLIRP
599     printf("slirp input:\n");
600     hex_dump(stdout, buf, size);
601 #endif
602     slirp_input(buf, size);
603 }
604
605 static int slirp_in_use;
606
607 static void net_slirp_cleanup(VLANClientState *vc)
608 {
609     slirp_in_use = 0;
610 }
611
612 static int net_slirp_init(VLANState *vlan, const char *model, const char *name,
613                           int restricted, const char *ip)
614 {
615     if (slirp_in_use) {
616         /* slirp only supports a single instance so far */
617         return -1;
618     }
619     if (!slirp_inited) {
620         slirp_inited = 1;
621         slirp_init(restricted, ip);
622
623         while (slirp_redirs) {
624             struct slirp_config_str *config = slirp_redirs;
625
626             slirp_redirection(NULL, config->str);
627             slirp_redirs = config->next;
628             qemu_free(config);
629         }
630 #ifndef _WIN32
631         if (slirp_smb_export) {
632             slirp_smb(slirp_smb_export);
633         }
634 #endif
635     }
636
637     slirp_vc = qemu_new_vlan_client(vlan, model, name, NULL, slirp_receive,
638                                     NULL, net_slirp_cleanup, NULL);
639     slirp_vc->info_str[0] = '\0';
640     slirp_in_use = 1;
641     return 0;
642 }
643
644 static void net_slirp_redir_print(void *opaque, int is_udp,
645                                   struct in_addr *laddr, u_int lport,
646                                   struct in_addr *faddr, u_int fport)
647 {
648     Monitor *mon = (Monitor *)opaque;
649     uint32_t h_addr;
650     uint32_t g_addr;
651     char buf[16];
652
653     h_addr = ntohl(faddr->s_addr);
654     g_addr = ntohl(laddr->s_addr);
655
656     monitor_printf(mon, "  %s |", is_udp ? "udp" : "tcp" );
657     snprintf(buf, 15, "%d.%d.%d.%d", (h_addr >> 24) & 0xff,
658                                      (h_addr >> 16) & 0xff,
659                                      (h_addr >> 8) & 0xff,
660                                      (h_addr) & 0xff);
661     monitor_printf(mon, " %15s |", buf);
662     monitor_printf(mon, " %5d |", fport);
663
664     snprintf(buf, 15, "%d.%d.%d.%d", (g_addr >> 24) & 0xff,
665                                      (g_addr >> 16) & 0xff,
666                                      (g_addr >> 8) & 0xff,
667                                      (g_addr) & 0xff);
668     monitor_printf(mon, " %15s |", buf);
669     monitor_printf(mon, " %5d\n", lport);
670
671 }
672
673 static void net_slirp_redir_list(Monitor *mon)
674 {
675     if (!mon)
676         return;
677
678     monitor_printf(mon, " Prot |    Host Addr    | HPort |    Guest Addr   | GPort\n");
679     monitor_printf(mon, "      |                 |       |                 |      \n");
680     slirp_redir_loop(net_slirp_redir_print, mon);
681 }
682
683 static void net_slirp_redir_rm(Monitor *mon, const char *port_str)
684 {
685     int host_port;
686     char buf[256] = "";
687     const char *p = port_str;
688     int is_udp = 0;
689     int n;
690
691     if (!mon)
692         return;
693
694     if (!port_str || !port_str[0])
695         goto fail_syntax;
696
697     get_str_sep(buf, sizeof(buf), &p, ':');
698
699     if (!strcmp(buf, "tcp") || buf[0] == '\0') {
700         is_udp = 0;
701     } else if (!strcmp(buf, "udp")) {
702         is_udp = 1;
703     } else {
704         goto fail_syntax;
705     }
706
707     host_port = atoi(p);
708
709     n = slirp_redir_rm(is_udp, host_port);
710
711     monitor_printf(mon, "removed %d redirections to %s port %d\n", n,
712                         is_udp ? "udp" : "tcp", host_port);
713     return;
714
715  fail_syntax:
716     monitor_printf(mon, "invalid format\n");
717 }
718
719 static void slirp_redirection(Monitor *mon, const char *redir_str)
720 {
721     struct in_addr guest_addr;
722     int host_port, guest_port;
723     const char *p;
724     char buf[256], *r;
725     int is_udp;
726
727     p = redir_str;
728     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
729         goto fail_syntax;
730     }
731     if (!strcmp(buf, "tcp") || buf[0] == '\0') {
732         is_udp = 0;
733     } else if (!strcmp(buf, "udp")) {
734         is_udp = 1;
735     } else {
736         goto fail_syntax;
737     }
738
739     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
740         goto fail_syntax;
741     }
742     host_port = strtol(buf, &r, 0);
743     if (r == buf) {
744         goto fail_syntax;
745     }
746
747     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
748         goto fail_syntax;
749     }
750     if (buf[0] == '\0') {
751         pstrcpy(buf, sizeof(buf), "10.0.2.15");
752     }
753     if (!inet_aton(buf, &guest_addr)) {
754         goto fail_syntax;
755     }
756
757     guest_port = strtol(p, &r, 0);
758     if (r == p) {
759         goto fail_syntax;
760     }
761
762     if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
763         config_error(mon, "could not set up redirection '%s'\n", redir_str);
764     }
765     return;
766
767  fail_syntax:
768     config_error(mon, "invalid redirection format '%s'\n", redir_str);
769 }
770
771 void net_slirp_redir(Monitor *mon, const char *redir_str, const char *redir_opt2)
772 {
773     struct slirp_config_str *config;
774
775     if (!slirp_inited) {
776         if (mon) {
777             monitor_printf(mon, "user mode network stack not in use\n");
778         } else {
779             config = qemu_malloc(sizeof(*config));
780             config->str = redir_str;
781             config->next = slirp_redirs;
782             slirp_redirs = config;
783         }
784         return;
785     }
786
787     if (!strcmp(redir_str, "remove")) {
788         net_slirp_redir_rm(mon, redir_opt2);
789         return;
790     }
791
792     if (!strcmp(redir_str, "list")) {
793         net_slirp_redir_list(mon);
794         return;
795     }
796
797     slirp_redirection(mon, redir_str);
798 }
799
800 #ifndef _WIN32
801
802 static char smb_dir[1024];
803
804 static void erase_dir(char *dir_name)
805 {
806     DIR *d;
807     struct dirent *de;
808     char filename[1024];
809
810     /* erase all the files in the directory */
811     if ((d = opendir(dir_name)) != NULL) {
812         for(;;) {
813             de = readdir(d);
814             if (!de)
815                 break;
816             if (strcmp(de->d_name, ".") != 0 &&
817                 strcmp(de->d_name, "..") != 0) {
818                 snprintf(filename, sizeof(filename), "%s/%s",
819                          smb_dir, de->d_name);
820                 if (unlink(filename) != 0)  /* is it a directory? */
821                     erase_dir(filename);
822             }
823         }
824         closedir(d);
825         rmdir(dir_name);
826     }
827 }
828
829 /* automatic user mode samba server configuration */
830 static void smb_exit(void)
831 {
832     erase_dir(smb_dir);
833 }
834
835 static void slirp_smb(const char *exported_dir)
836 {
837     char smb_conf[1024];
838     char smb_cmdline[1024];
839     FILE *f;
840
841     /* XXX: better tmp dir construction */
842     snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
843     if (mkdir(smb_dir, 0700) < 0) {
844         fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
845         exit(1);
846     }
847     snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
848
849     f = fopen(smb_conf, "w");
850     if (!f) {
851         fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
852         exit(1);
853     }
854     fprintf(f,
855             "[global]\n"
856             "private dir=%s\n"
857             "smb ports=0\n"
858             "socket address=127.0.0.1\n"
859             "pid directory=%s\n"
860             "lock directory=%s\n"
861             "log file=%s/log.smbd\n"
862             "smb passwd file=%s/smbpasswd\n"
863             "security = share\n"
864             "[qemu]\n"
865             "path=%s\n"
866             "read only=no\n"
867             "guest ok=yes\n",
868             smb_dir,
869             smb_dir,
870             smb_dir,
871             smb_dir,
872             smb_dir,
873             exported_dir
874             );
875     fclose(f);
876     atexit(smb_exit);
877
878     snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
879              SMBD_COMMAND, smb_conf);
880
881     slirp_add_exec(0, smb_cmdline, 4, 139);
882 }
883
884 /* automatic user mode samba server configuration */
885 void net_slirp_smb(const char *exported_dir)
886 {
887     if (slirp_smb_export) {
888         fprintf(stderr, "-smb given twice\n");
889         exit(1);
890     }
891     slirp_smb_export = exported_dir;
892     if (slirp_inited) {
893         slirp_smb(exported_dir);
894     }
895 }
896
897 #endif /* !defined(_WIN32) */
898
899 void do_info_slirp(Monitor *mon)
900 {
901     slirp_stats();
902 }
903
904 struct VMChannel {
905     CharDriverState *hd;
906     int port;
907 };
908
909 static int vmchannel_can_read(void *opaque)
910 {
911     struct VMChannel *vmc = (struct VMChannel*)opaque;
912     return slirp_socket_can_recv(4, vmc->port);
913 }
914
915 static void vmchannel_read(void *opaque, const uint8_t *buf, int size)
916 {
917     struct VMChannel *vmc = (struct VMChannel*)opaque;
918     slirp_socket_recv(4, vmc->port, buf, size);
919 }
920
921 #endif /* CONFIG_SLIRP */
922
923 #if !defined(_WIN32)
924
925 typedef struct TAPState {
926     VLANClientState *vc;
927     int fd;
928     char down_script[1024];
929     char down_script_arg[128];
930     uint8_t buf[4096];
931 } TAPState;
932
933 static int launch_script(const char *setup_script, const char *ifname, int fd);
934
935 static ssize_t tap_receive_iov(VLANClientState *vc, const struct iovec *iov,
936                                int iovcnt)
937 {
938     TAPState *s = vc->opaque;
939     ssize_t len;
940
941     do {
942         len = writev(s->fd, iov, iovcnt);
943     } while (len == -1 && (errno == EINTR || errno == EAGAIN));
944
945     return len;
946 }
947
948 static void tap_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
949 {
950     TAPState *s = vc->opaque;
951     int ret;
952     for(;;) {
953         ret = write(s->fd, buf, size);
954         if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
955         } else {
956             break;
957         }
958     }
959 }
960
961 static int tap_can_send(void *opaque)
962 {
963     TAPState *s = opaque;
964
965     return qemu_can_send_packet(s->vc);
966 }
967
968 #ifdef __sun__
969 static ssize_t tap_read_packet(int tapfd, uint8_t *buf, int maxlen)
970 {
971     struct strbuf sbuf;
972     int f = 0;
973
974     sbuf.maxlen = maxlen;
975     sbuf.buf = (char *)buf;
976
977     return getmsg(tapfd, NULL, &sbuf, &f) >= 0 ? sbuf.len : -1;
978 }
979 #else
980 static ssize_t tap_read_packet(int tapfd, uint8_t *buf, int maxlen)
981 {
982     return read(tapfd, buf, maxlen);
983 }
984 #endif
985
986 static void tap_send(void *opaque)
987 {
988     TAPState *s = opaque;
989     int size;
990
991     size = tap_read_packet(s->fd, s->buf, sizeof(s->buf));
992     if (size > 0) {
993         qemu_send_packet(s->vc, s->buf, size);
994     }
995 }
996
997 static void tap_cleanup(VLANClientState *vc)
998 {
999     TAPState *s = vc->opaque;
1000
1001     if (s->down_script[0])
1002         launch_script(s->down_script, s->down_script_arg, s->fd);
1003
1004     qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1005     close(s->fd);
1006     qemu_free(s);
1007 }
1008
1009 /* fd support */
1010
1011 static TAPState *net_tap_fd_init(VLANState *vlan,
1012                                  const char *model,
1013                                  const char *name,
1014                                  int fd)
1015 {
1016     TAPState *s;
1017
1018     s = qemu_mallocz(sizeof(TAPState));
1019     s->fd = fd;
1020     s->vc = qemu_new_vlan_client(vlan, model, name, NULL, tap_receive,
1021                                  tap_receive_iov, tap_cleanup, s);
1022     qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
1023     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
1024     return s;
1025 }
1026
1027 #if defined (HOST_BSD) || defined (__FreeBSD_kernel__)
1028 static int tap_open(char *ifname, int ifname_size)
1029 {
1030     int fd;
1031     char *dev;
1032     struct stat s;
1033
1034     TFR(fd = open("/dev/tap", O_RDWR));
1035     if (fd < 0) {
1036         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1037         return -1;
1038     }
1039
1040     fstat(fd, &s);
1041     dev = devname(s.st_rdev, S_IFCHR);
1042     pstrcpy(ifname, ifname_size, dev);
1043
1044     fcntl(fd, F_SETFL, O_NONBLOCK);
1045     return fd;
1046 }
1047 #elif defined(__sun__)
1048 #define TUNNEWPPA       (('T'<<16) | 0x0001)
1049 /*
1050  * Allocate TAP device, returns opened fd.
1051  * Stores dev name in the first arg(must be large enough).
1052  */
1053 static int tap_alloc(char *dev, size_t dev_size)
1054 {
1055     int tap_fd, if_fd, ppa = -1;
1056     static int ip_fd = 0;
1057     char *ptr;
1058
1059     static int arp_fd = 0;
1060     int ip_muxid, arp_muxid;
1061     struct strioctl  strioc_if, strioc_ppa;
1062     int link_type = I_PLINK;;
1063     struct lifreq ifr;
1064     char actual_name[32] = "";
1065
1066     memset(&ifr, 0x0, sizeof(ifr));
1067
1068     if( *dev ){
1069        ptr = dev;
1070        while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
1071        ppa = atoi(ptr);
1072     }
1073
1074     /* Check if IP device was opened */
1075     if( ip_fd )
1076        close(ip_fd);
1077
1078     TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
1079     if (ip_fd < 0) {
1080        syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
1081        return -1;
1082     }
1083
1084     TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
1085     if (tap_fd < 0) {
1086        syslog(LOG_ERR, "Can't open /dev/tap");
1087        return -1;
1088     }
1089
1090     /* Assign a new PPA and get its unit number. */
1091     strioc_ppa.ic_cmd = TUNNEWPPA;
1092     strioc_ppa.ic_timout = 0;
1093     strioc_ppa.ic_len = sizeof(ppa);
1094     strioc_ppa.ic_dp = (char *)&ppa;
1095     if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
1096        syslog (LOG_ERR, "Can't assign new interface");
1097
1098     TFR(if_fd = open("/dev/tap", O_RDWR, 0));
1099     if (if_fd < 0) {
1100        syslog(LOG_ERR, "Can't open /dev/tap (2)");
1101        return -1;
1102     }
1103     if(ioctl(if_fd, I_PUSH, "ip") < 0){
1104        syslog(LOG_ERR, "Can't push IP module");
1105        return -1;
1106     }
1107
1108     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
1109         syslog(LOG_ERR, "Can't get flags\n");
1110
1111     snprintf (actual_name, 32, "tap%d", ppa);
1112     pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1113
1114     ifr.lifr_ppa = ppa;
1115     /* Assign ppa according to the unit number returned by tun device */
1116
1117     if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
1118         syslog (LOG_ERR, "Can't set PPA %d", ppa);
1119     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
1120         syslog (LOG_ERR, "Can't get flags\n");
1121     /* Push arp module to if_fd */
1122     if (ioctl (if_fd, I_PUSH, "arp") < 0)
1123         syslog (LOG_ERR, "Can't push ARP module (2)");
1124
1125     /* Push arp module to ip_fd */
1126     if (ioctl (ip_fd, I_POP, NULL) < 0)
1127         syslog (LOG_ERR, "I_POP failed\n");
1128     if (ioctl (ip_fd, I_PUSH, "arp") < 0)
1129         syslog (LOG_ERR, "Can't push ARP module (3)\n");
1130     /* Open arp_fd */
1131     TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
1132     if (arp_fd < 0)
1133        syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
1134
1135     /* Set ifname to arp */
1136     strioc_if.ic_cmd = SIOCSLIFNAME;
1137     strioc_if.ic_timout = 0;
1138     strioc_if.ic_len = sizeof(ifr);
1139     strioc_if.ic_dp = (char *)&ifr;
1140     if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
1141         syslog (LOG_ERR, "Can't set ifname to arp\n");
1142     }
1143
1144     if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
1145        syslog(LOG_ERR, "Can't link TAP device to IP");
1146        return -1;
1147     }
1148
1149     if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
1150         syslog (LOG_ERR, "Can't link TAP device to ARP");
1151
1152     close (if_fd);
1153
1154     memset(&ifr, 0x0, sizeof(ifr));
1155     pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1156     ifr.lifr_ip_muxid  = ip_muxid;
1157     ifr.lifr_arp_muxid = arp_muxid;
1158
1159     if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
1160     {
1161       ioctl (ip_fd, I_PUNLINK , arp_muxid);
1162       ioctl (ip_fd, I_PUNLINK, ip_muxid);
1163       syslog (LOG_ERR, "Can't set multiplexor id");
1164     }
1165
1166     snprintf(dev, dev_size, "tap%d", ppa);
1167     return tap_fd;
1168 }
1169
1170 static int tap_open(char *ifname, int ifname_size)
1171 {
1172     char  dev[10]="";
1173     int fd;
1174     if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
1175        fprintf(stderr, "Cannot allocate TAP device\n");
1176        return -1;
1177     }
1178     pstrcpy(ifname, ifname_size, dev);
1179     fcntl(fd, F_SETFL, O_NONBLOCK);
1180     return fd;
1181 }
1182 #elif defined (_AIX)
1183 static int tap_open(char *ifname, int ifname_size)
1184 {
1185     fprintf (stderr, "no tap on AIX\n");
1186     return -1;
1187 }
1188 #else
1189 static int tap_open(char *ifname, int ifname_size)
1190 {
1191     struct ifreq ifr;
1192     int fd, ret;
1193
1194     TFR(fd = open("/dev/net/tun", O_RDWR));
1195     if (fd < 0) {
1196         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1197         return -1;
1198     }
1199     memset(&ifr, 0, sizeof(ifr));
1200     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1201     if (ifname[0] != '\0')
1202         pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
1203     else
1204         pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
1205     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1206     if (ret != 0) {
1207         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1208         close(fd);
1209         return -1;
1210     }
1211     pstrcpy(ifname, ifname_size, ifr.ifr_name);
1212     fcntl(fd, F_SETFL, O_NONBLOCK);
1213     return fd;
1214 }
1215 #endif
1216
1217 static int launch_script(const char *setup_script, const char *ifname, int fd)
1218 {
1219     sigset_t oldmask, mask;
1220     int pid, status;
1221     char *args[3];
1222     char **parg;
1223
1224     sigemptyset(&mask);
1225     sigaddset(&mask, SIGCHLD);
1226     sigprocmask(SIG_BLOCK, &mask, &oldmask);
1227
1228     /* try to launch network script */
1229     pid = fork();
1230     if (pid == 0) {
1231         int open_max = sysconf(_SC_OPEN_MAX), i;
1232
1233         for (i = 0; i < open_max; i++) {
1234             if (i != STDIN_FILENO &&
1235                 i != STDOUT_FILENO &&
1236                 i != STDERR_FILENO &&
1237                 i != fd) {
1238                 close(i);
1239             }
1240         }
1241         parg = args;
1242         *parg++ = (char *)setup_script;
1243         *parg++ = (char *)ifname;
1244         *parg++ = NULL;
1245         execv(setup_script, args);
1246         _exit(1);
1247     } else if (pid > 0) {
1248         while (waitpid(pid, &status, 0) != pid) {
1249             /* loop */
1250         }
1251         sigprocmask(SIG_SETMASK, &oldmask, NULL);
1252
1253         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1254             return 0;
1255         }
1256     }
1257     fprintf(stderr, "%s: could not launch network script\n", setup_script);
1258     return -1;
1259 }
1260
1261 static int net_tap_init(VLANState *vlan, const char *model,
1262                         const char *name, const char *ifname1,
1263                         const char *setup_script, const char *down_script)
1264 {
1265     TAPState *s;
1266     int fd;
1267     char ifname[128];
1268
1269     if (ifname1 != NULL)
1270         pstrcpy(ifname, sizeof(ifname), ifname1);
1271     else
1272         ifname[0] = '\0';
1273     TFR(fd = tap_open(ifname, sizeof(ifname)));
1274     if (fd < 0)
1275         return -1;
1276
1277     if (!setup_script || !strcmp(setup_script, "no"))
1278         setup_script = "";
1279     if (setup_script[0] != '\0') {
1280         if (launch_script(setup_script, ifname, fd))
1281             return -1;
1282     }
1283     s = net_tap_fd_init(vlan, model, name, fd);
1284     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1285              "ifname=%s,script=%s,downscript=%s",
1286              ifname, setup_script, down_script);
1287     if (down_script && strcmp(down_script, "no")) {
1288         snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1289         snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1290     }
1291     return 0;
1292 }
1293
1294 #endif /* !_WIN32 */
1295
1296 #if defined(CONFIG_VDE)
1297 typedef struct VDEState {
1298     VLANClientState *vc;
1299     VDECONN *vde;
1300 } VDEState;
1301
1302 static void vde_to_qemu(void *opaque)
1303 {
1304     VDEState *s = opaque;
1305     uint8_t buf[4096];
1306     int size;
1307
1308     size = vde_recv(s->vde, (char *)buf, sizeof(buf), 0);
1309     if (size > 0) {
1310         qemu_send_packet(s->vc, buf, size);
1311     }
1312 }
1313
1314 static void vde_receive(VLANClientState *vc, const uint8_t *buf, int size)
1315 {
1316     VDEState *s = vc->opaque;
1317     int ret;
1318     for(;;) {
1319         ret = vde_send(s->vde, (const char *)buf, size, 0);
1320         if (ret < 0 && errno == EINTR) {
1321         } else {
1322             break;
1323         }
1324     }
1325 }
1326
1327 static void vde_cleanup(VLANClientState *vc)
1328 {
1329     VDEState *s = vc->opaque;
1330     qemu_set_fd_handler(vde_datafd(s->vde), NULL, NULL, NULL);
1331     vde_close(s->vde);
1332     qemu_free(s);
1333 }
1334
1335 static int net_vde_init(VLANState *vlan, const char *model,
1336                         const char *name, const char *sock,
1337                         int port, const char *group, int mode)
1338 {
1339     VDEState *s;
1340     char *init_group = strlen(group) ? (char *)group : NULL;
1341     char *init_sock = strlen(sock) ? (char *)sock : NULL;
1342
1343     struct vde_open_args args = {
1344         .port = port,
1345         .group = init_group,
1346         .mode = mode,
1347     };
1348
1349     s = qemu_mallocz(sizeof(VDEState));
1350     s->vde = vde_open(init_sock, (char *)"QEMU", &args);
1351     if (!s->vde){
1352         free(s);
1353         return -1;
1354     }
1355     s->vc = qemu_new_vlan_client(vlan, model, name, NULL, vde_receive,
1356                                  NULL, vde_cleanup, s);
1357     qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1358     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1359              sock, vde_datafd(s->vde));
1360     return 0;
1361 }
1362 #endif
1363
1364 /* network connection */
1365 typedef struct NetSocketState {
1366     VLANClientState *vc;
1367     int fd;
1368     int state; /* 0 = getting length, 1 = getting data */
1369     unsigned int index;
1370     unsigned int packet_len;
1371     uint8_t buf[4096];
1372     struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1373 } NetSocketState;
1374
1375 typedef struct NetSocketListenState {
1376     VLANState *vlan;
1377     char *model;
1378     char *name;
1379     int fd;
1380 } NetSocketListenState;
1381
1382 /* XXX: we consider we can send the whole packet without blocking */
1383 static void net_socket_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1384 {
1385     NetSocketState *s = vc->opaque;
1386     uint32_t len;
1387     len = htonl(size);
1388
1389     send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1390     send_all(s->fd, buf, size);
1391 }
1392
1393 static void net_socket_receive_dgram(VLANClientState *vc, const uint8_t *buf, size_t size)
1394 {
1395     NetSocketState *s = vc->opaque;
1396     sendto(s->fd, buf, size, 0,
1397            (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1398 }
1399
1400 static void net_socket_send(void *opaque)
1401 {
1402     NetSocketState *s = opaque;
1403     int size, err;
1404     unsigned l;
1405     uint8_t buf1[4096];
1406     const uint8_t *buf;
1407
1408     size = recv(s->fd, buf1, sizeof(buf1), 0);
1409     if (size < 0) {
1410         err = socket_error();
1411         if (err != EWOULDBLOCK)
1412             goto eoc;
1413     } else if (size == 0) {
1414         /* end of connection */
1415     eoc:
1416         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1417         closesocket(s->fd);
1418         return;
1419     }
1420     buf = buf1;
1421     while (size > 0) {
1422         /* reassemble a packet from the network */
1423         switch(s->state) {
1424         case 0:
1425             l = 4 - s->index;
1426             if (l > size)
1427                 l = size;
1428             memcpy(s->buf + s->index, buf, l);
1429             buf += l;
1430             size -= l;
1431             s->index += l;
1432             if (s->index == 4) {
1433                 /* got length */
1434                 s->packet_len = ntohl(*(uint32_t *)s->buf);
1435                 s->index = 0;
1436                 s->state = 1;
1437             }
1438             break;
1439         case 1:
1440             l = s->packet_len - s->index;
1441             if (l > size)
1442                 l = size;
1443             if (s->index + l <= sizeof(s->buf)) {
1444                 memcpy(s->buf + s->index, buf, l);
1445             } else {
1446                 fprintf(stderr, "serious error: oversized packet received,"
1447                     "connection terminated.\n");
1448                 s->state = 0;
1449                 goto eoc;
1450             }
1451
1452             s->index += l;
1453             buf += l;
1454             size -= l;
1455             if (s->index >= s->packet_len) {
1456                 qemu_send_packet(s->vc, s->buf, s->packet_len);
1457                 s->index = 0;
1458                 s->state = 0;
1459             }
1460             break;
1461         }
1462     }
1463 }
1464
1465 static void net_socket_send_dgram(void *opaque)
1466 {
1467     NetSocketState *s = opaque;
1468     int size;
1469
1470     size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1471     if (size < 0)
1472         return;
1473     if (size == 0) {
1474         /* end of connection */
1475         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1476         return;
1477     }
1478     qemu_send_packet(s->vc, s->buf, size);
1479 }
1480
1481 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1482 {
1483     struct ip_mreq imr;
1484     int fd;
1485     int val, ret;
1486     if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1487         fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1488                 inet_ntoa(mcastaddr->sin_addr),
1489                 (int)ntohl(mcastaddr->sin_addr.s_addr));
1490         return -1;
1491
1492     }
1493     fd = socket(PF_INET, SOCK_DGRAM, 0);
1494     if (fd < 0) {
1495         perror("socket(PF_INET, SOCK_DGRAM)");
1496         return -1;
1497     }
1498
1499     val = 1;
1500     ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1501                    (const char *)&val, sizeof(val));
1502     if (ret < 0) {
1503         perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1504         goto fail;
1505     }
1506
1507     ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1508     if (ret < 0) {
1509         perror("bind");
1510         goto fail;
1511     }
1512
1513     /* Add host to multicast group */
1514     imr.imr_multiaddr = mcastaddr->sin_addr;
1515     imr.imr_interface.s_addr = htonl(INADDR_ANY);
1516
1517     ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1518                      (const char *)&imr, sizeof(struct ip_mreq));
1519     if (ret < 0) {
1520         perror("setsockopt(IP_ADD_MEMBERSHIP)");
1521         goto fail;
1522     }
1523
1524     /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1525     val = 1;
1526     ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1527                    (const char *)&val, sizeof(val));
1528     if (ret < 0) {
1529         perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1530         goto fail;
1531     }
1532
1533     socket_set_nonblock(fd);
1534     return fd;
1535 fail:
1536     if (fd >= 0)
1537         closesocket(fd);
1538     return -1;
1539 }
1540
1541 static void net_socket_cleanup(VLANClientState *vc)
1542 {
1543     NetSocketState *s = vc->opaque;
1544     qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1545     close(s->fd);
1546     qemu_free(s);
1547 }
1548
1549 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1550                                                 const char *model,
1551                                                 const char *name,
1552                                                 int fd, int is_connected)
1553 {
1554     struct sockaddr_in saddr;
1555     int newfd;
1556     socklen_t saddr_len;
1557     NetSocketState *s;
1558
1559     /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1560      * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1561      * by ONLY ONE process: we must "clone" this dgram socket --jjo
1562      */
1563
1564     if (is_connected) {
1565         if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1566             /* must be bound */
1567             if (saddr.sin_addr.s_addr==0) {
1568                 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1569                         fd);
1570                 return NULL;
1571             }
1572             /* clone dgram socket */
1573             newfd = net_socket_mcast_create(&saddr);
1574             if (newfd < 0) {
1575                 /* error already reported by net_socket_mcast_create() */
1576                 close(fd);
1577                 return NULL;
1578             }
1579             /* clone newfd to fd, close newfd */
1580             dup2(newfd, fd);
1581             close(newfd);
1582
1583         } else {
1584             fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1585                     fd, strerror(errno));
1586             return NULL;
1587         }
1588     }
1589
1590     s = qemu_mallocz(sizeof(NetSocketState));
1591     s->fd = fd;
1592
1593     s->vc = qemu_new_vlan_client(vlan, model, name, NULL, net_socket_receive_dgram,
1594                                  NULL, net_socket_cleanup, s);
1595     qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1596
1597     /* mcast: save bound address as dst */
1598     if (is_connected) s->dgram_dst=saddr;
1599
1600     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1601             "socket: fd=%d (%s mcast=%s:%d)",
1602             fd, is_connected? "cloned" : "",
1603             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1604     return s;
1605 }
1606
1607 static void net_socket_connect(void *opaque)
1608 {
1609     NetSocketState *s = opaque;
1610     qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1611 }
1612
1613 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1614                                                  const char *model,
1615                                                  const char *name,
1616                                                  int fd, int is_connected)
1617 {
1618     NetSocketState *s;
1619     s = qemu_mallocz(sizeof(NetSocketState));
1620     s->fd = fd;
1621     s->vc = qemu_new_vlan_client(vlan, model, name, NULL, net_socket_receive,
1622                                  NULL, net_socket_cleanup, s);
1623     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1624              "socket: fd=%d", fd);
1625     if (is_connected) {
1626         net_socket_connect(s);
1627     } else {
1628         qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1629     }
1630     return s;
1631 }
1632
1633 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1634                                           const char *model, const char *name,
1635                                           int fd, int is_connected)
1636 {
1637     int so_type=-1, optlen=sizeof(so_type);
1638
1639     if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1640         (socklen_t *)&optlen)< 0) {
1641         fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1642         return NULL;
1643     }
1644     switch(so_type) {
1645     case SOCK_DGRAM:
1646         return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1647     case SOCK_STREAM:
1648         return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1649     default:
1650         /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1651         fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1652         return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1653     }
1654     return NULL;
1655 }
1656
1657 static void net_socket_accept(void *opaque)
1658 {
1659     NetSocketListenState *s = opaque;
1660     NetSocketState *s1;
1661     struct sockaddr_in saddr;
1662     socklen_t len;
1663     int fd;
1664
1665     for(;;) {
1666         len = sizeof(saddr);
1667         fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1668         if (fd < 0 && errno != EINTR) {
1669             return;
1670         } else if (fd >= 0) {
1671             break;
1672         }
1673     }
1674     s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1675     if (!s1) {
1676         closesocket(fd);
1677     } else {
1678         snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1679                  "socket: connection from %s:%d",
1680                  inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1681     }
1682 }
1683
1684 static int net_socket_listen_init(VLANState *vlan,
1685                                   const char *model,
1686                                   const char *name,
1687                                   const char *host_str)
1688 {
1689     NetSocketListenState *s;
1690     int fd, val, ret;
1691     struct sockaddr_in saddr;
1692
1693     if (parse_host_port(&saddr, host_str) < 0)
1694         return -1;
1695
1696     s = qemu_mallocz(sizeof(NetSocketListenState));
1697
1698     fd = socket(PF_INET, SOCK_STREAM, 0);
1699     if (fd < 0) {
1700         perror("socket");
1701         return -1;
1702     }
1703     socket_set_nonblock(fd);
1704
1705     /* allow fast reuse */
1706     val = 1;
1707     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1708
1709     ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1710     if (ret < 0) {
1711         perror("bind");
1712         return -1;
1713     }
1714     ret = listen(fd, 0);
1715     if (ret < 0) {
1716         perror("listen");
1717         return -1;
1718     }
1719     s->vlan = vlan;
1720     s->model = strdup(model);
1721     s->name = name ? strdup(name) : NULL;
1722     s->fd = fd;
1723     qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1724     return 0;
1725 }
1726
1727 static int net_socket_connect_init(VLANState *vlan,
1728                                    const char *model,
1729                                    const char *name,
1730                                    const char *host_str)
1731 {
1732     NetSocketState *s;
1733     int fd, connected, ret, err;
1734     struct sockaddr_in saddr;
1735
1736     if (parse_host_port(&saddr, host_str) < 0)
1737         return -1;
1738
1739     fd = socket(PF_INET, SOCK_STREAM, 0);
1740     if (fd < 0) {
1741         perror("socket");
1742         return -1;
1743     }
1744     socket_set_nonblock(fd);
1745
1746     connected = 0;
1747     for(;;) {
1748         ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1749         if (ret < 0) {
1750             err = socket_error();
1751             if (err == EINTR || err == EWOULDBLOCK) {
1752             } else if (err == EINPROGRESS) {
1753                 break;
1754 #ifdef _WIN32
1755             } else if (err == WSAEALREADY) {
1756                 break;
1757 #endif
1758             } else {
1759                 perror("connect");
1760                 closesocket(fd);
1761                 return -1;
1762             }
1763         } else {
1764             connected = 1;
1765             break;
1766         }
1767     }
1768     s = net_socket_fd_init(vlan, model, name, fd, connected);
1769     if (!s)
1770         return -1;
1771     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1772              "socket: connect to %s:%d",
1773              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1774     return 0;
1775 }
1776
1777 static int net_socket_mcast_init(VLANState *vlan,
1778                                  const char *model,
1779                                  const char *name,
1780                                  const char *host_str)
1781 {
1782     NetSocketState *s;
1783     int fd;
1784     struct sockaddr_in saddr;
1785
1786     if (parse_host_port(&saddr, host_str) < 0)
1787         return -1;
1788
1789
1790     fd = net_socket_mcast_create(&saddr);
1791     if (fd < 0)
1792         return -1;
1793
1794     s = net_socket_fd_init(vlan, model, name, fd, 0);
1795     if (!s)
1796         return -1;
1797
1798     s->dgram_dst = saddr;
1799
1800     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1801              "socket: mcast=%s:%d",
1802              inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1803     return 0;
1804
1805 }
1806
1807 typedef struct DumpState {
1808     VLANClientState *pcap_vc;
1809     int fd;
1810     int pcap_caplen;
1811 } DumpState;
1812
1813 #define PCAP_MAGIC 0xa1b2c3d4
1814
1815 struct pcap_file_hdr {
1816     uint32_t magic;
1817     uint16_t version_major;
1818     uint16_t version_minor;
1819     int32_t thiszone;
1820     uint32_t sigfigs;
1821     uint32_t snaplen;
1822     uint32_t linktype;
1823 };
1824
1825 struct pcap_sf_pkthdr {
1826     struct {
1827         int32_t tv_sec;
1828         int32_t tv_usec;
1829     } ts;
1830     uint32_t caplen;
1831     uint32_t len;
1832 };
1833
1834 static void dump_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1835 {
1836     DumpState *s = vc->opaque;
1837     struct pcap_sf_pkthdr hdr;
1838     int64_t ts;
1839     int caplen;
1840
1841     /* Early return in case of previous error. */
1842     if (s->fd < 0) {
1843         return;
1844     }
1845
1846     ts = muldiv64(qemu_get_clock(vm_clock), 1000000, ticks_per_sec);
1847     caplen = size > s->pcap_caplen ? s->pcap_caplen : size;
1848
1849     hdr.ts.tv_sec = ts / 1000000;
1850     hdr.ts.tv_usec = ts % 1000000;
1851     hdr.caplen = caplen;
1852     hdr.len = size;
1853     if (write(s->fd, &hdr, sizeof(hdr)) != sizeof(hdr) ||
1854         write(s->fd, buf, caplen) != caplen) {
1855         qemu_log("-net dump write error - stop dump\n");
1856         close(s->fd);
1857         s->fd = -1;
1858     }
1859 }
1860
1861 static void net_dump_cleanup(VLANClientState *vc)
1862 {
1863     DumpState *s = vc->opaque;
1864
1865     close(s->fd);
1866     qemu_free(s);
1867 }
1868
1869 static int net_dump_init(Monitor *mon, VLANState *vlan, const char *device,
1870                          const char *name, const char *filename, int len)
1871 {
1872     struct pcap_file_hdr hdr;
1873     DumpState *s;
1874
1875     s = qemu_malloc(sizeof(DumpState));
1876
1877     s->fd = open(filename, O_CREAT | O_WRONLY, 0644);
1878     if (s->fd < 0) {
1879         config_error(mon, "-net dump: can't open %s\n", filename);
1880         return -1;
1881     }
1882
1883     s->pcap_caplen = len;
1884
1885     hdr.magic = PCAP_MAGIC;
1886     hdr.version_major = 2;
1887     hdr.version_minor = 4;
1888     hdr.thiszone = 0;
1889     hdr.sigfigs = 0;
1890     hdr.snaplen = s->pcap_caplen;
1891     hdr.linktype = 1;
1892
1893     if (write(s->fd, &hdr, sizeof(hdr)) < sizeof(hdr)) {
1894         config_error(mon, "-net dump write error: %s\n", strerror(errno));
1895         close(s->fd);
1896         qemu_free(s);
1897         return -1;
1898     }
1899
1900     s->pcap_vc = qemu_new_vlan_client(vlan, device, name, NULL, dump_receive, NULL,
1901                                       net_dump_cleanup, s);
1902     snprintf(s->pcap_vc->info_str, sizeof(s->pcap_vc->info_str),
1903              "dump to %s (len=%d)", filename, len);
1904     return 0;
1905 }
1906
1907 /* find or alloc a new VLAN */
1908 VLANState *qemu_find_vlan(int id)
1909 {
1910     VLANState **pvlan, *vlan;
1911     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1912         if (vlan->id == id)
1913             return vlan;
1914     }
1915     vlan = qemu_mallocz(sizeof(VLANState));
1916     vlan->id = id;
1917     vlan->next = NULL;
1918     pvlan = &first_vlan;
1919     while (*pvlan != NULL)
1920         pvlan = &(*pvlan)->next;
1921     *pvlan = vlan;
1922     return vlan;
1923 }
1924
1925 static int nic_get_free_idx(void)
1926 {
1927     int index;
1928
1929     for (index = 0; index < MAX_NICS; index++)
1930         if (!nd_table[index].used)
1931             return index;
1932     return -1;
1933 }
1934
1935 void qemu_check_nic_model(NICInfo *nd, const char *model)
1936 {
1937     const char *models[2];
1938
1939     models[0] = model;
1940     models[1] = NULL;
1941
1942     qemu_check_nic_model_list(nd, models, model);
1943 }
1944
1945 void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
1946                                const char *default_model)
1947 {
1948     int i, exit_status = 0;
1949
1950     if (!nd->model)
1951         nd->model = strdup(default_model);
1952
1953     if (strcmp(nd->model, "?") != 0) {
1954         for (i = 0 ; models[i]; i++)
1955             if (strcmp(nd->model, models[i]) == 0)
1956                 return;
1957
1958         fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
1959         exit_status = 1;
1960     }
1961
1962     fprintf(stderr, "qemu: Supported NIC models: ");
1963     for (i = 0 ; models[i]; i++)
1964         fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1965
1966     exit(exit_status);
1967 }
1968
1969 int net_client_init(Monitor *mon, const char *device, const char *p)
1970 {
1971     static const char * const fd_params[] = {
1972         "vlan", "name", "fd", NULL
1973     };
1974     char buf[1024];
1975     int vlan_id, ret;
1976     VLANState *vlan;
1977     char *name = NULL;
1978
1979     vlan_id = 0;
1980     if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1981         vlan_id = strtol(buf, NULL, 0);
1982     }
1983     vlan = qemu_find_vlan(vlan_id);
1984
1985     if (get_param_value(buf, sizeof(buf), "name", p)) {
1986         name = qemu_strdup(buf);
1987     }
1988     if (!strcmp(device, "nic")) {
1989         static const char * const nic_params[] = {
1990             "vlan", "name", "macaddr", "model", NULL
1991         };
1992         NICInfo *nd;
1993         uint8_t *macaddr;
1994         int idx = nic_get_free_idx();
1995
1996         if (check_params(buf, sizeof(buf), nic_params, p) < 0) {
1997             config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);
1998             ret = -1;
1999             goto out;
2000         }
2001         if (idx == -1 || nb_nics >= MAX_NICS) {
2002             config_error(mon, "Too Many NICs\n");
2003             ret = -1;
2004             goto out;
2005         }
2006         nd = &nd_table[idx];
2007         macaddr = nd->macaddr;
2008         macaddr[0] = 0x52;
2009         macaddr[1] = 0x54;
2010         macaddr[2] = 0x00;
2011         macaddr[3] = 0x12;
2012         macaddr[4] = 0x34;
2013         macaddr[5] = 0x56 + idx;
2014
2015         if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
2016             if (parse_macaddr(macaddr, buf) < 0) {
2017                 config_error(mon, "invalid syntax for ethernet address\n");
2018                 ret = -1;
2019                 goto out;
2020             }
2021         }
2022         if (get_param_value(buf, sizeof(buf), "model", p)) {
2023             nd->model = strdup(buf);
2024         }
2025         nd->vlan = vlan;
2026         nd->name = name;
2027         nd->used = 1;
2028         name = NULL;
2029         nb_nics++;
2030         vlan->nb_guest_devs++;
2031         ret = idx;
2032     } else
2033     if (!strcmp(device, "none")) {
2034         if (*p != '\0') {
2035             config_error(mon, "'none' takes no parameters\n");
2036             ret = -1;
2037             goto out;
2038         }
2039         /* does nothing. It is needed to signal that no network cards
2040            are wanted */
2041         ret = 0;
2042     } else
2043 #ifdef CONFIG_SLIRP
2044     if (!strcmp(device, "user")) {
2045         static const char * const slirp_params[] = {
2046             "vlan", "name", "hostname", "restrict", "ip", NULL
2047         };
2048         int restricted = 0;
2049         char *ip = NULL;
2050
2051         if (check_params(buf, sizeof(buf), slirp_params, p) < 0) {
2052             config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);
2053             ret = -1;
2054             goto out;
2055         }
2056         if (get_param_value(buf, sizeof(buf), "hostname", p)) {
2057             pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
2058         }
2059         if (get_param_value(buf, sizeof(buf), "restrict", p)) {
2060             restricted = (buf[0] == 'y') ? 1 : 0;
2061         }
2062         if (get_param_value(buf, sizeof(buf), "ip", p)) {
2063             ip = qemu_strdup(buf);
2064         }
2065         vlan->nb_host_devs++;
2066         ret = net_slirp_init(vlan, device, name, restricted, ip);
2067         qemu_free(ip);
2068     } else if (!strcmp(device, "channel")) {
2069         long port;
2070         char name[20], *devname;
2071         struct VMChannel *vmc;
2072
2073         port = strtol(p, &devname, 10);
2074         devname++;
2075         if (port < 1 || port > 65535) {
2076             config_error(mon, "vmchannel wrong port number\n");
2077             ret = -1;
2078             goto out;
2079         }
2080         vmc = malloc(sizeof(struct VMChannel));
2081         snprintf(name, 20, "vmchannel%ld", port);
2082         vmc->hd = qemu_chr_open(name, devname, NULL);
2083         if (!vmc->hd) {
2084             config_error(mon, "could not open vmchannel device '%s'\n",
2085                          devname);
2086             ret = -1;
2087             goto out;
2088         }
2089         vmc->port = port;
2090         slirp_add_exec(3, vmc->hd, 4, port);
2091         qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,
2092                 NULL, vmc);
2093         ret = 0;
2094     } else
2095 #endif
2096 #ifdef _WIN32
2097     if (!strcmp(device, "tap")) {
2098         static const char * const tap_params[] = {
2099             "vlan", "name", "ifname", NULL
2100         };
2101         char ifname[64];
2102
2103         if (check_params(buf, sizeof(buf), tap_params, p) < 0) {
2104             config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);
2105             ret = -1;
2106             goto out;
2107         }
2108         if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
2109             config_error(mon, "tap: no interface name\n");
2110             ret = -1;
2111             goto out;
2112         }
2113         vlan->nb_host_devs++;
2114         ret = tap_win32_init(vlan, device, name, ifname);
2115     } else
2116 #elif defined (_AIX)
2117 #else
2118     if (!strcmp(device, "tap")) {
2119         char ifname[64], chkbuf[64];
2120         char setup_script[1024], down_script[1024];
2121         int fd;
2122         vlan->nb_host_devs++;
2123         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2124             if (check_params(chkbuf, sizeof(chkbuf), fd_params, p) < 0) {
2125                 config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2126                 ret = -1;
2127                 goto out;
2128             }
2129             fd = strtol(buf, NULL, 0);
2130             fcntl(fd, F_SETFL, O_NONBLOCK);
2131             net_tap_fd_init(vlan, device, name, fd);
2132             ret = 0;
2133         } else {
2134             static const char * const tap_params[] = {
2135                 "vlan", "name", "ifname", "script", "downscript", NULL
2136             };
2137             if (check_params(chkbuf, sizeof(chkbuf), tap_params, p) < 0) {
2138                 config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2139                 ret = -1;
2140                 goto out;
2141             }
2142             if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
2143                 ifname[0] = '\0';
2144             }
2145             if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2146                 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2147             }
2148             if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
2149                 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
2150             }
2151             ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
2152         }
2153     } else
2154 #endif
2155     if (!strcmp(device, "socket")) {
2156         char chkbuf[64];
2157         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2158             int fd;
2159             if (check_params(chkbuf, sizeof(chkbuf), fd_params, p) < 0) {
2160                 config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2161                 ret = -1;
2162                 goto out;
2163             }
2164             fd = strtol(buf, NULL, 0);
2165             ret = -1;
2166             if (net_socket_fd_init(vlan, device, name, fd, 1))
2167                 ret = 0;
2168         } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2169             static const char * const listen_params[] = {
2170                 "vlan", "name", "listen", NULL
2171             };
2172             if (check_params(chkbuf, sizeof(chkbuf), listen_params, p) < 0) {
2173                 config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2174                 ret = -1;
2175                 goto out;
2176             }
2177             ret = net_socket_listen_init(vlan, device, name, buf);
2178         } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2179             static const char * const connect_params[] = {
2180                 "vlan", "name", "connect", NULL
2181             };
2182             if (check_params(chkbuf, sizeof(chkbuf), connect_params, p) < 0) {
2183                 config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2184                 ret = -1;
2185                 goto out;
2186             }
2187             ret = net_socket_connect_init(vlan, device, name, buf);
2188         } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
2189             static const char * const mcast_params[] = {
2190                 "vlan", "name", "mcast", NULL
2191             };
2192             if (check_params(chkbuf, sizeof(chkbuf), mcast_params, p) < 0) {
2193                 config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2194                 ret = -1;
2195                 goto out;
2196             }
2197             ret = net_socket_mcast_init(vlan, device, name, buf);
2198         } else {
2199             config_error(mon, "Unknown socket options: %s\n", p);
2200             ret = -1;
2201             goto out;
2202         }
2203         vlan->nb_host_devs++;
2204     } else
2205 #ifdef CONFIG_VDE
2206     if (!strcmp(device, "vde")) {
2207         static const char * const vde_params[] = {
2208             "vlan", "name", "sock", "port", "group", "mode", NULL
2209         };
2210         char vde_sock[1024], vde_group[512];
2211         int vde_port, vde_mode;
2212
2213         if (check_params(buf, sizeof(buf), vde_params, p) < 0) {
2214             config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);
2215             ret = -1;
2216             goto out;
2217         }
2218         vlan->nb_host_devs++;
2219         if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
2220             vde_sock[0] = '\0';
2221         }
2222         if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
2223             vde_port = strtol(buf, NULL, 10);
2224         } else {
2225             vde_port = 0;
2226         }
2227         if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
2228             vde_group[0] = '\0';
2229         }
2230         if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
2231             vde_mode = strtol(buf, NULL, 8);
2232         } else {
2233             vde_mode = 0700;
2234         }
2235         ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
2236     } else
2237 #endif
2238     if (!strcmp(device, "dump")) {
2239         int len = 65536;
2240
2241         if (get_param_value(buf, sizeof(buf), "len", p) > 0) {
2242             len = strtol(buf, NULL, 0);
2243         }
2244         if (!get_param_value(buf, sizeof(buf), "file", p)) {
2245             snprintf(buf, sizeof(buf), "qemu-vlan%d.pcap", vlan_id);
2246         }
2247         ret = net_dump_init(mon, vlan, device, name, buf, len);
2248     } else {
2249         config_error(mon, "Unknown network device: %s\n", device);
2250         ret = -1;
2251         goto out;
2252     }
2253     if (ret < 0) {
2254         config_error(mon, "Could not initialize device '%s'\n", device);
2255     }
2256 out:
2257     qemu_free(name);
2258     return ret;
2259 }
2260
2261 void net_client_uninit(NICInfo *nd)
2262 {
2263     nd->vlan->nb_guest_devs--;
2264     nb_nics--;
2265     nd->used = 0;
2266     free((void *)nd->model);
2267 }
2268
2269 static int net_host_check_device(const char *device)
2270 {
2271     int i;
2272     const char *valid_param_list[] = { "tap", "socket", "dump"
2273 #ifdef CONFIG_SLIRP
2274                                        ,"user"
2275 #endif
2276 #ifdef CONFIG_VDE
2277                                        ,"vde"
2278 #endif
2279     };
2280     for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
2281         if (!strncmp(valid_param_list[i], device,
2282                      strlen(valid_param_list[i])))
2283             return 1;
2284     }
2285
2286     return 0;
2287 }
2288
2289 void net_host_device_add(Monitor *mon, const char *device, const char *opts)
2290 {
2291     if (!net_host_check_device(device)) {
2292         monitor_printf(mon, "invalid host network device %s\n", device);
2293         return;
2294     }
2295     if (net_client_init(mon, device, opts ? opts : "") < 0) {
2296         monitor_printf(mon, "adding host network device %s failed\n", device);
2297     }
2298 }
2299
2300 void net_host_device_remove(Monitor *mon, int vlan_id, const char *device)
2301 {
2302     VLANState *vlan;
2303     VLANClientState *vc;
2304
2305     vlan = qemu_find_vlan(vlan_id);
2306
2307     for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
2308         if (!strcmp(vc->name, device)) {
2309             break;
2310         }
2311     }
2312
2313     if (!vc) {
2314         monitor_printf(mon, "can't find device %s\n", device);
2315         return;
2316     }
2317     if (!net_host_check_device(vc->model)) {
2318         monitor_printf(mon, "invalid host network device %s\n", device);
2319         return;
2320     }
2321     qemu_del_vlan_client(vc);
2322 }
2323
2324 int net_client_parse(const char *str)
2325 {
2326     const char *p;
2327     char *q;
2328     char device[64];
2329
2330     p = str;
2331     q = device;
2332     while (*p != '\0' && *p != ',') {
2333         if ((q - device) < sizeof(device) - 1)
2334             *q++ = *p;
2335         p++;
2336     }
2337     *q = '\0';
2338     if (*p == ',')
2339         p++;
2340
2341     return net_client_init(NULL, device, p);
2342 }
2343
2344 void do_info_network(Monitor *mon)
2345 {
2346     VLANState *vlan;
2347     VLANClientState *vc;
2348
2349     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2350         monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
2351         for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2352             monitor_printf(mon, "  %s: %s\n", vc->name, vc->info_str);
2353     }
2354 }
2355
2356 int do_set_link(Monitor *mon, const char *name, const char *up_or_down)
2357 {
2358     VLANState *vlan;
2359     VLANClientState *vc = NULL;
2360
2361     for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
2362         for (vc = vlan->first_client; vc != NULL; vc = vc->next)
2363             if (strcmp(vc->name, name) == 0)
2364                 goto done;
2365 done:
2366
2367     if (!vc) {
2368         monitor_printf(mon, "could not find network device '%s'", name);
2369         return 0;
2370     }
2371
2372     if (strcmp(up_or_down, "up") == 0)
2373         vc->link_down = 0;
2374     else if (strcmp(up_or_down, "down") == 0)
2375         vc->link_down = 1;
2376     else
2377         monitor_printf(mon, "invalid link status '%s'; only 'up' or 'down' "
2378                        "valid\n", up_or_down);
2379
2380     if (vc->link_status_changed)
2381         vc->link_status_changed(vc);
2382
2383     return 1;
2384 }
2385
2386 void net_cleanup(void)
2387 {
2388     VLANState *vlan;
2389
2390     /* close network clients */
2391     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2392         VLANClientState *vc = vlan->first_client;
2393
2394         while (vc) {
2395             VLANClientState *next = vc->next;
2396
2397             qemu_del_vlan_client(vc);
2398
2399             vc = next;
2400         }
2401     }
2402 }
2403
2404 void net_client_check(void)
2405 {
2406     VLANState *vlan;
2407
2408     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2409         if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
2410             continue;
2411         if (vlan->nb_guest_devs == 0)
2412             fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
2413         if (vlan->nb_host_devs == 0)
2414             fprintf(stderr,
2415                     "Warning: vlan %d is not connected to host network\n",
2416                     vlan->id);
2417     }
2418 }