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