• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "tcpdump.h"
33 
34 /* Needed early for HOST_BSD etc. */
35 #include "config-host.h"
36 
37 #ifndef _WIN32
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #ifdef __NetBSD__
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef CONFIG_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
71 
72 /* For the benefit of older linux systems which don't supply it,
73    we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
75 #include "hpet.h"
76 
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
79 #endif
80 #ifdef __sun__
81 #include <sys/stat.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
91 #include <net/if.h>
92 #include <syslog.h>
93 #include <stropts.h>
94 #endif
95 #endif
96 #endif
97 
98 #if defined(__OpenBSD__)
99 #include <util.h>
100 #endif
101 
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
104 #endif
105 
106 #ifdef _WIN32
107 #include <windows.h>
108 #include <malloc.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
113 #endif
114 
115 #include "qemu-common.h"
116 #include "net.h"
117 #include "monitor.h"
118 #include "sysemu.h"
119 #include "qemu-timer.h"
120 #include "qemu-char.h"
121 #include "audio/audio.h"
122 #include "qemu_socket.h"
123 #include "qemu-log.h"
124 
125 #if defined(CONFIG_SLIRP)
126 #include "libslirp.h"
127 #endif
128 
129 #if defined(CONFIG_SHAPER)
130 #include "shaper.h"
131 #endif
132 
133 #include "android/android.h"
134 #include "telephony/modem_driver.h"
135 
136 static VLANState *first_vlan;
137 
138 /* see http://en.wikipedia.org/wiki/List_of_device_bandwidths or a complete list */
139 const NetworkSpeed  android_netspeeds[] = {
140     { "gsm", "GSM/CSD", 14400, 14400 },
141     { "hscsd", "HSCSD", 14400, 43200 },
142     { "gprs", "GPRS", 40000, 80000 },
143     { "edge", "EDGE/EGPRS", 118400, 236800 },
144     { "umts", "UMTS/3G", 128000, 1920000 },
145     { "hsdpa", "HSDPA", 348000, 14400000 },
146     { "full", "no limit", 0, 0 },
147     { NULL, NULL, 0, 0 }
148 };
149 
150 const NetworkLatency  android_netdelays[] = {
151     /* FIXME: these numbers are totally imaginary */
152     { "gprs", "GPRS", 150, 550 },
153     { "edge", "EDGE/EGPRS", 80, 400 },
154     { "umts", "UMTS/3G", 35, 200 },
155     { "none", "no latency", 0, 0 },
156     { NULL, NULL, 0, 0 }
157 };
158 
159 /***********************************************************/
160 /* network device redirectors */
161 
162 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
hex_dump(FILE * f,const uint8_t * buf,int size)163 static void hex_dump(FILE *f, const uint8_t *buf, int size)
164 {
165     int len, i, j, c;
166 
167     for(i=0;i<size;i+=16) {
168         len = size - i;
169         if (len > 16)
170             len = 16;
171         fprintf(f, "%08x ", i);
172         for(j=0;j<16;j++) {
173             if (j < len)
174                 fprintf(f, " %02x", buf[i+j]);
175             else
176                 fprintf(f, "   ");
177         }
178         fprintf(f, " ");
179         for(j=0;j<len;j++) {
180             c = buf[i+j];
181             if (c < ' ' || c > '~')
182                 c = '.';
183             fprintf(f, "%c", c);
184         }
185         fprintf(f, "\n");
186     }
187 }
188 #endif
189 
parse_macaddr(uint8_t * macaddr,const char * p)190 static int parse_macaddr(uint8_t *macaddr, const char *p)
191 {
192     int i;
193     char *last_char;
194     long int offset;
195 
196     errno = 0;
197     offset = strtol(p, &last_char, 0);
198     if (0 == errno && '\0' == *last_char &&
199             offset >= 0 && offset <= 0xFFFFFF) {
200         macaddr[3] = (offset & 0xFF0000) >> 16;
201         macaddr[4] = (offset & 0xFF00) >> 8;
202         macaddr[5] = offset & 0xFF;
203         return 0;
204     } else {
205         for(i = 0; i < 6; i++) {
206             macaddr[i] = strtol(p, (char **)&p, 16);
207             if (i == 5) {
208                 if (*p != '\0')
209                     return -1;
210             } else {
211                 if (*p != ':' && *p != '-')
212                     return -1;
213                 p++;
214             }
215         }
216         return 0;
217     }
218 
219     return -1;
220 }
221 
get_str_sep(char * buf,int buf_size,const char ** pp,int sep)222 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
223 {
224     const char *p, *p1;
225     int len;
226     p = *pp;
227     p1 = strchr(p, sep);
228     if (!p1)
229         return -1;
230     len = p1 - p;
231     p1++;
232     if (buf_size > 0) {
233         if (len > buf_size - 1)
234             len = buf_size - 1;
235         memcpy(buf, p, len);
236         buf[len] = '\0';
237     }
238     *pp = p1;
239     return 0;
240 }
241 
parse_host_src_port(SockAddress * haddr,SockAddress * saddr,const char * input_str)242 int parse_host_src_port(SockAddress *haddr,
243                         SockAddress *saddr,
244                         const char *input_str)
245 {
246     char *str = strdup(input_str);
247     char *host_str = str;
248     char *src_str;
249     const char *src_str2;
250     char *ptr;
251 
252     /*
253      * Chop off any extra arguments at the end of the string which
254      * would start with a comma, then fill in the src port information
255      * if it was provided else use the "any address" and "any port".
256      */
257     if ((ptr = strchr(str,',')))
258         *ptr = '\0';
259 
260     if ((src_str = strchr(input_str,'@'))) {
261         *src_str = '\0';
262         src_str++;
263     }
264 
265     if (parse_host_port(haddr, host_str) < 0)
266         goto fail;
267 
268     src_str2 = src_str;
269     if (!src_str || *src_str == '\0')
270         src_str2 = ":0";
271 
272     if (parse_host_port(saddr, src_str2) < 0)
273         goto fail;
274 
275     free(str);
276     return(0);
277 
278 fail:
279     free(str);
280     return -1;
281 }
282 
parse_host_port(SockAddress * saddr,const char * str)283 int parse_host_port(SockAddress *saddr, const char *str)
284 {
285     char buf[512];
286     const char *p, *r;
287     uint32_t ip;
288     int port;
289 
290     p = str;
291     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
292         return -1;
293 
294     if (buf[0] == '\0') {
295         ip = 0;
296     } else {
297         if (qemu_isdigit(buf[0])) {
298             if (inet_strtoip(buf, &ip) < 0)
299                 return -1;
300         } else {
301             if (sock_address_init_resolve(saddr, buf, 0, 0) < 0)
302                 return - 1;
303             ip = sock_address_get_ip(saddr);
304         }
305     }
306     port = strtol(p, (char **)&r, 0);
307     if (r == p)
308         return -1;
309     sock_address_init_inet(saddr, ip, port);
310     return 0;
311 }
312 
313 #if !defined(_WIN32) && 0
parse_unix_path(struct sockaddr_un * uaddr,const char * str)314 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
315 {
316     const char *p;
317     int len;
318 
319     len = MIN(108, strlen(str));
320     p = strchr(str, ',');
321     if (p)
322 	len = MIN(len, p - str);
323 
324     memset(uaddr, 0, sizeof(*uaddr));
325 
326     uaddr->sun_family = AF_UNIX;
327     memcpy(uaddr->sun_path, str, len);
328 
329     return 0;
330 }
331 #endif
332 
qemu_format_nic_info_str(VLANClientState * vc,uint8_t macaddr[6])333 void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6])
334 {
335     snprintf(vc->info_str, sizeof(vc->info_str),
336              "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
337              vc->model,
338              macaddr[0], macaddr[1], macaddr[2],
339              macaddr[3], macaddr[4], macaddr[5]);
340 }
341 
assign_name(VLANClientState * vc1,const char * model)342 static char *assign_name(VLANClientState *vc1, const char *model)
343 {
344     VLANState *vlan;
345     char buf[256];
346     int id = 0;
347 
348     for (vlan = first_vlan; vlan; vlan = vlan->next) {
349         VLANClientState *vc;
350 
351         for (vc = vlan->first_client; vc; vc = vc->next)
352             if (vc != vc1 && strcmp(vc->model, model) == 0)
353                 id++;
354     }
355 
356     snprintf(buf, sizeof(buf), "%s.%d", model, id);
357 
358     return strdup(buf);
359 }
360 
qemu_new_vlan_client(VLANState * vlan,const char * model,const char * name,NetCanReceive * can_receive,NetReceive * receive,NetReceiveIOV * receive_iov,NetCleanup * cleanup,void * opaque)361 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
362                                       const char *model,
363                                       const char *name,
364                                       NetCanReceive *can_receive,
365                                       NetReceive *receive,
366                                       NetReceiveIOV *receive_iov,
367                                       NetCleanup *cleanup,
368                                       void *opaque)
369 {
370     VLANClientState *vc, **pvc;
371     vc = qemu_mallocz(sizeof(VLANClientState));
372     vc->model = strdup(model);
373     if (name)
374         vc->name = strdup(name);
375     else
376         vc->name = assign_name(vc, model);
377     vc->can_receive = can_receive;
378     vc->receive = receive;
379     vc->receive_iov = receive_iov;
380     vc->cleanup = cleanup;
381     vc->opaque = opaque;
382     vc->vlan = vlan;
383 
384     vc->next = NULL;
385     pvc = &vlan->first_client;
386     while (*pvc != NULL)
387         pvc = &(*pvc)->next;
388     *pvc = vc;
389     return vc;
390 }
391 
qemu_del_vlan_client(VLANClientState * vc)392 void qemu_del_vlan_client(VLANClientState *vc)
393 {
394     VLANClientState **pvc = &vc->vlan->first_client;
395 
396     while (*pvc != NULL)
397         if (*pvc == vc) {
398             *pvc = vc->next;
399             if (vc->cleanup) {
400                 vc->cleanup(vc);
401             }
402             free(vc->name);
403             free(vc->model);
404             qemu_free(vc);
405             break;
406         } else
407             pvc = &(*pvc)->next;
408 }
409 
qemu_find_vlan_client(VLANState * vlan,void * opaque)410 VLANClientState *qemu_find_vlan_client(VLANState *vlan, void *opaque)
411 {
412     VLANClientState **pvc = &vlan->first_client;
413 
414     while (*pvc != NULL)
415         if ((*pvc)->opaque == opaque)
416             return *pvc;
417         else
418             pvc = &(*pvc)->next;
419 
420     return NULL;
421 }
422 
qemu_can_send_packet(VLANClientState * sender)423 int qemu_can_send_packet(VLANClientState *sender)
424 {
425     VLANState *vlan = sender->vlan;
426     VLANClientState *vc;
427 
428     for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
429         if (vc == sender) {
430             continue;
431         }
432 
433         /* no can_receive() handler, they can always receive */
434         if (!vc->can_receive || vc->can_receive(vc)) {
435             return 1;
436         }
437     }
438     return 0;
439 }
440 
441 static int
qemu_deliver_packet(VLANClientState * sender,const uint8_t * buf,int size)442 qemu_deliver_packet(VLANClientState *sender, const uint8_t *buf, int size)
443 {
444     VLANClientState *vc;
445     int ret = -1;
446 
447     sender->vlan->delivering = 1;
448 
449     for (vc = sender->vlan->first_client; vc != NULL; vc = vc->next) {
450         ssize_t len;
451 
452         if (vc == sender) {
453             continue;
454         }
455 
456         if (vc->link_down) {
457             ret = size;
458             continue;
459         }
460 
461         len = vc->receive(vc, buf, size);
462 
463         ret = (ret >= 0) ? ret : len;
464     }
465 
466     sender->vlan->delivering = 0;
467 
468     return ret;
469 }
470 
qemu_flush_queued_packets(VLANClientState * vc)471 void qemu_flush_queued_packets(VLANClientState *vc)
472 {
473     VLANPacket *packet;
474 
475     while ((packet = vc->vlan->send_queue) != NULL) {
476         int ret;
477 
478         vc->vlan->send_queue = packet->next;
479 
480         ret = qemu_deliver_packet(packet->sender, packet->data, packet->size);
481         if (ret == 0 && packet->sent_cb != NULL) {
482             packet->next = vc->vlan->send_queue;
483             vc->vlan->send_queue = packet;
484             break;
485         }
486 
487         if (packet->sent_cb)
488             packet->sent_cb(packet->sender);
489 
490         qemu_free(packet);
491     }
492 }
493 
qemu_enqueue_packet(VLANClientState * sender,const uint8_t * buf,int size,NetPacketSent * sent_cb)494 static void qemu_enqueue_packet(VLANClientState *sender,
495                                 const uint8_t *buf, int size,
496                                 NetPacketSent *sent_cb)
497 {
498     VLANPacket *packet;
499 
500     packet = qemu_malloc(sizeof(VLANPacket) + size);
501     packet->next = sender->vlan->send_queue;
502     packet->sender = sender;
503     packet->size = size;
504     packet->sent_cb = sent_cb;
505     memcpy(packet->data, buf, size);
506     sender->vlan->send_queue = packet;
507 }
508 
qemu_send_packet_async(VLANClientState * sender,const uint8_t * buf,int size,NetPacketSent * sent_cb)509 ssize_t qemu_send_packet_async(VLANClientState *sender,
510                                const uint8_t *buf, int size,
511                                NetPacketSent *sent_cb)
512 {
513     int ret;
514 
515     if (sender->link_down) {
516         return size;
517     }
518 
519 #ifdef DEBUG_NET
520     printf("vlan %d send:\n", sender->vlan->id);
521     hex_dump(stdout, buf, size);
522 #endif
523 
524     if (sender->vlan->delivering) {
525         qemu_enqueue_packet(sender, buf, size, NULL);
526         return size;
527     }
528 
529     ret = qemu_deliver_packet(sender, buf, size);
530     if (ret == 0 && sent_cb != NULL) {
531         qemu_enqueue_packet(sender, buf, size, sent_cb);
532         return 0;
533     }
534 
535     qemu_flush_queued_packets(sender);
536 
537     return ret;
538 }
539 
qemu_send_packet(VLANClientState * vc,const uint8_t * buf,int size)540 void qemu_send_packet(VLANClientState *vc, const uint8_t *buf, int size)
541 {
542     qemu_send_packet_async(vc, buf, size, NULL);
543 }
544 
vc_sendv_compat(VLANClientState * vc,const struct iovec * iov,int iovcnt)545 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
546                                int iovcnt)
547 {
548     uint8_t buffer[4096];
549     size_t offset = 0;
550     int i;
551 
552     for (i = 0; i < iovcnt; i++) {
553         size_t len;
554 
555         len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
556         memcpy(buffer + offset, iov[i].iov_base, len);
557         offset += len;
558     }
559 
560     return vc->receive(vc, buffer, offset);
561 }
562 
calc_iov_length(const struct iovec * iov,int iovcnt)563 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
564 {
565     size_t offset = 0;
566     int i;
567 
568     for (i = 0; i < iovcnt; i++)
569         offset += iov[i].iov_len;
570     return offset;
571 }
572 
qemu_deliver_packet_iov(VLANClientState * sender,const struct iovec * iov,int iovcnt)573 static int qemu_deliver_packet_iov(VLANClientState *sender,
574                                    const struct iovec *iov, int iovcnt)
575 {
576     VLANClientState *vc;
577     int ret = -1;
578 
579     sender->vlan->delivering = 1;
580 
581     for (vc = sender->vlan->first_client; vc != NULL; vc = vc->next) {
582         ssize_t len;
583 
584         if (vc == sender) {
585             continue;
586         }
587 
588         if (vc->link_down) {
589             ret = calc_iov_length(iov, iovcnt);
590             continue;
591         }
592 
593         if (vc->receive_iov) {
594             len = vc->receive_iov(vc, iov, iovcnt);
595         } else {
596             len = vc_sendv_compat(vc, iov, iovcnt);
597         }
598 
599         ret = (ret >= 0) ? ret : len;
600     }
601 
602     sender->vlan->delivering = 0;
603 
604     return ret;
605 }
606 
qemu_enqueue_packet_iov(VLANClientState * sender,const struct iovec * iov,int iovcnt,NetPacketSent * sent_cb)607 static ssize_t qemu_enqueue_packet_iov(VLANClientState *sender,
608                                        const struct iovec *iov, int iovcnt,
609                                        NetPacketSent *sent_cb)
610 {
611     VLANPacket *packet;
612     size_t max_len = 0;
613     int i;
614 
615     max_len = calc_iov_length(iov, iovcnt);
616 
617     packet = qemu_malloc(sizeof(VLANPacket) + max_len);
618     packet->next = sender->vlan->send_queue;
619     packet->sender = sender;
620     packet->sent_cb = sent_cb;
621     packet->size = 0;
622 
623     for (i = 0; i < iovcnt; i++) {
624         size_t len = iov[i].iov_len;
625 
626         memcpy(packet->data + packet->size, iov[i].iov_base, len);
627         packet->size += len;
628     }
629 
630     sender->vlan->send_queue = packet;
631 
632     return packet->size;
633 }
634 
qemu_sendv_packet_async(VLANClientState * sender,const struct iovec * iov,int iovcnt,NetPacketSent * sent_cb)635 ssize_t qemu_sendv_packet_async(VLANClientState *sender,
636                                 const struct iovec *iov, int iovcnt,
637                                 NetPacketSent *sent_cb)
638 {
639     int ret;
640 
641     if (sender->link_down) {
642         return calc_iov_length(iov, iovcnt);
643     }
644 
645     if (sender->vlan->delivering) {
646         return qemu_enqueue_packet_iov(sender, iov, iovcnt, NULL);
647     }
648 
649     ret = qemu_deliver_packet_iov(sender, iov, iovcnt);
650     if (ret == 0 && sent_cb != NULL) {
651         qemu_enqueue_packet_iov(sender, iov, iovcnt, sent_cb);
652         return 0;
653     }
654 
655     qemu_flush_queued_packets(sender);
656 
657     return ret;
658 }
659 
660 ssize_t
qemu_sendv_packet(VLANClientState * vc,const struct iovec * iov,int iovcnt)661 qemu_sendv_packet(VLANClientState *vc, const struct iovec *iov, int iovcnt)
662 {
663     return qemu_sendv_packet_async(vc, iov, iovcnt, NULL);
664 }
665 
config_error(Monitor * mon,const char * fmt,...)666 static void config_error(Monitor *mon, const char *fmt, ...)
667 {
668     va_list ap;
669 
670     va_start(ap, fmt);
671     if (mon) {
672         monitor_vprintf(mon, fmt, ap);
673     } else {
674         fprintf(stderr, "qemu: ");
675         vfprintf(stderr, fmt, ap);
676         exit(1);
677     }
678     va_end(ap);
679 }
680 
681 #if defined(CONFIG_SLIRP)
682 
683 /* slirp network adapter */
684 
685 struct slirp_config_str {
686     struct slirp_config_str *next;
687     const char *str;
688 };
689 
690 static int slirp_inited;
691 static struct slirp_config_str *slirp_redirs;
692 #ifndef _WIN32
693 static const char *slirp_smb_export;
694 #endif
695 static VLANClientState *slirp_vc;
696 
697 #ifndef _WIN32
698 static void slirp_smb(const char *exported_dir);
699 #endif
700 static void slirp_redirection(Monitor *mon, const char *redir_str);
701 
702 double   qemu_net_upload_speed   = 0.;
703 double   qemu_net_download_speed = 0.;
704 int      qemu_net_min_latency = 0;
705 int      qemu_net_max_latency = 0;
706 int      qemu_net_disable = 0;
707 
708 int
ip_packet_is_internal(const uint8_t * data,size_t size)709 ip_packet_is_internal( const uint8_t*  data, size_t  size )
710 {
711     const uint8_t*  end = data + size;
712 
713     /* must have room for Mac + IP header */
714     if (data + 40 > end)
715         return 0;
716 
717     if (data[12] != 0x08 || data[13] != 0x00 )
718         return 0;
719 
720     /* must have valid IP header */
721     data += 14;
722     if ((data[0] >> 4) != 4 || (data[0] & 15) < 5)
723         return 0;
724 
725     /* internal if both source and dest addresses are in 10.x.x.x */
726     return ( data[12] == 10 && data[16] == 10);
727 }
728 
729 #ifdef CONFIG_SHAPER
730 
731 NetShaper  slirp_shaper_in;
732 NetShaper  slirp_shaper_out;
733 NetDelay   slirp_delay_in;
734 
735 static void
slirp_delay_in_cb(void * data,size_t size,void * opaque)736 slirp_delay_in_cb( void*   data,
737                    size_t  size,
738                    void*   opaque )
739 {
740     slirp_input( (const uint8_t*)data, (int)size );
741     opaque = opaque;
742 }
743 
744 static void
slirp_shaper_in_cb(void * data,size_t size,void * opaque)745 slirp_shaper_in_cb( void*   data,
746                     size_t  size,
747                     void*   opaque )
748 {
749     netdelay_send_aux( slirp_delay_in, data, size, opaque );
750 }
751 
752 static void
slirp_shaper_out_cb(void * data,size_t size,void * opaque)753 slirp_shaper_out_cb( void*   data,
754                      size_t  size,
755                      void*   opaque )
756 {
757     qemu_send_packet( slirp_vc, (const uint8_t*)data, (int)size );
758 }
759 
760 void
slirp_init_shapers(void)761 slirp_init_shapers( void )
762 {
763     slirp_delay_in   = netdelay_create( slirp_delay_in_cb );
764     slirp_shaper_in  = netshaper_create( 1, slirp_shaper_in_cb );
765     slirp_shaper_out = netshaper_create( 1, slirp_shaper_out_cb );
766 
767     netdelay_set_latency( slirp_delay_in, qemu_net_min_latency, qemu_net_max_latency );
768     netshaper_set_rate( slirp_shaper_out, qemu_net_download_speed );
769     netshaper_set_rate( slirp_shaper_in,  qemu_net_upload_speed  );
770 }
771 
772 #endif /* CONFIG_SHAPER */
773 
774 
slirp_can_output(void)775 int slirp_can_output(void)
776 {
777 #ifdef CONFIG_SHAPER
778     return !slirp_vc ||
779            ( netshaper_can_send(slirp_shaper_out) &&
780              qemu_can_send_packet(slirp_vc) );
781 #else
782     return !slirp_vc || qemu_can_send_packet(slirp_vc);
783 #endif
784 }
785 
slirp_output(const uint8_t * pkt,int pkt_len)786 void slirp_output(const uint8_t *pkt, int pkt_len)
787 {
788 #ifdef DEBUG_SLIRP
789     printf("slirp output:\n");
790     hex_dump(stdout, pkt, pkt_len);
791 #endif
792     if (qemu_tcpdump_active)
793         qemu_tcpdump_packet(pkt, pkt_len);
794 
795     if (!slirp_vc)
796         return;
797 
798 #ifdef CONFIG_SHAPER
799     netshaper_send(slirp_shaper_out, (void*)pkt, pkt_len);
800 #else
801     qemu_send_packet(slirp_vc, pkt, pkt_len);
802 #endif
803 }
804 
slirp_is_inited(void)805 int slirp_is_inited(void)
806 {
807     return slirp_inited;
808 }
809 
slirp_receive(VLANClientState * vc,const uint8_t * buf,size_t size)810 static ssize_t slirp_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
811 {
812 #ifdef DEBUG_SLIRP
813     printf("slirp input:\n");
814     hex_dump(stdout, buf, size);
815 #endif
816     if (qemu_tcpdump_active)
817         qemu_tcpdump_packet(buf, size);
818 
819 #ifdef CONFIG_SHAPER
820     netshaper_send(slirp_shaper_in, (char*)buf, size);
821 #else
822     slirp_input(buf, size);
823 #endif
824     return size;
825 }
826 
827 static int slirp_in_use;
828 
net_slirp_cleanup(VLANClientState * vc)829 static void net_slirp_cleanup(VLANClientState *vc)
830 {
831     slirp_in_use = 0;
832 }
833 
net_slirp_init(VLANState * vlan,const char * model,const char * name,int restricted,const char * ip)834 static int net_slirp_init(VLANState *vlan, const char *model, const char *name,
835                           int restricted, const char *ip)
836 {
837     if (slirp_in_use) {
838         /* slirp only supports a single instance so far */
839         return -1;
840     }
841     if (!slirp_inited) {
842         slirp_inited = 1;
843         slirp_init(restricted, ip);
844 
845         while (slirp_redirs) {
846             struct slirp_config_str *config = slirp_redirs;
847 
848             slirp_redirection(NULL, config->str);
849             slirp_redirs = config->next;
850             qemu_free(config);
851         }
852 #ifndef _WIN32
853         if (slirp_smb_export) {
854             slirp_smb(slirp_smb_export);
855         }
856 #endif
857         slirp_init_shapers();
858     }
859 
860     slirp_vc = qemu_new_vlan_client(vlan, model, name, NULL, slirp_receive,
861                                     NULL, net_slirp_cleanup, NULL);
862     slirp_vc->info_str[0] = '\0';
863     slirp_in_use = 1;
864     return 0;
865 }
866 
net_slirp_redir_print(void * opaque,int is_udp,const SockAddress * laddr,const SockAddress * faddr)867 static void net_slirp_redir_print(void *opaque, int is_udp,
868                                   const SockAddress *laddr,
869                                   const SockAddress *faddr)
870 {
871     Monitor *mon = (Monitor *)opaque;
872     uint32_t h_addr;
873     uint32_t g_addr;
874     char buf[16];
875 
876     h_addr = sock_address_get_ip(faddr);
877     g_addr = sock_address_get_ip(laddr);
878 
879     monitor_printf(mon, "  %s |", is_udp ? "udp" : "tcp" );
880     snprintf(buf, 15, "%d.%d.%d.%d", (h_addr >> 24) & 0xff,
881                                      (h_addr >> 16) & 0xff,
882                                      (h_addr >> 8) & 0xff,
883                                      (h_addr) & 0xff);
884     monitor_printf(mon, " %15s |", buf);
885     monitor_printf(mon, " %5d |", sock_address_get_port(faddr));
886 
887     snprintf(buf, 15, "%d.%d.%d.%d", (g_addr >> 24) & 0xff,
888                                      (g_addr >> 16) & 0xff,
889                                      (g_addr >> 8) & 0xff,
890                                      (g_addr) & 0xff);
891     monitor_printf(mon, " %15s |", buf);
892     monitor_printf(mon, " %5d\n", sock_address_get_port(laddr));
893 
894 }
895 
net_slirp_redir_list(Monitor * mon)896 static void net_slirp_redir_list(Monitor *mon)
897 {
898     if (!mon)
899         return;
900 
901     monitor_printf(mon, " Prot |    Host Addr    | HPort |    Guest Addr   | GPort\n");
902     monitor_printf(mon, "      |                 |       |                 |      \n");
903     slirp_redir_loop(net_slirp_redir_print, mon);
904 }
905 
net_slirp_redir_rm(Monitor * mon,const char * port_str)906 static void net_slirp_redir_rm(Monitor *mon, const char *port_str)
907 {
908     int host_port;
909     char buf[256] = "";
910     const char *p = port_str;
911     int is_udp = 0;
912     int n;
913 
914     if (!mon)
915         return;
916 
917     if (!port_str || !port_str[0])
918         goto fail_syntax;
919 
920     get_str_sep(buf, sizeof(buf), &p, ':');
921 
922     if (!strcmp(buf, "tcp") || buf[0] == '\0') {
923         is_udp = 0;
924     } else if (!strcmp(buf, "udp")) {
925         is_udp = 1;
926     } else {
927         goto fail_syntax;
928     }
929 
930     host_port = atoi(p);
931 
932     n = slirp_redir_rm(is_udp, host_port);
933 
934     monitor_printf(mon, "removed %d redirections to %s port %d\n", n,
935                         is_udp ? "udp" : "tcp", host_port);
936     return;
937 
938  fail_syntax:
939     monitor_printf(mon, "invalid format\n");
940 }
941 
slirp_redirection(Monitor * mon,const char * redir_str)942 static void slirp_redirection(Monitor *mon, const char *redir_str)
943 {
944     uint32_t guest_addr;
945     int host_port, guest_port;
946     const char *p;
947     char buf[256], *r;
948     int is_udp;
949 
950     p = redir_str;
951     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
952         goto fail_syntax;
953     }
954     if (!strcmp(buf, "tcp") || buf[0] == '\0') {
955         is_udp = 0;
956     } else if (!strcmp(buf, "udp")) {
957         is_udp = 1;
958     } else {
959         goto fail_syntax;
960     }
961 
962     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
963         goto fail_syntax;
964     }
965     host_port = strtol(buf, &r, 0);
966     if (r == buf) {
967         goto fail_syntax;
968     }
969 
970     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
971         goto fail_syntax;
972     }
973     if (buf[0] == '\0') {
974         pstrcpy(buf, sizeof(buf), "10.0.2.15");
975     }
976     if (inet_strtoip(buf, &guest_addr) < 0) {
977         goto fail_syntax;
978     }
979 
980     guest_port = strtol(p, &r, 0);
981     if (r == p) {
982         goto fail_syntax;
983     }
984 
985     if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
986         config_error(mon, "could not set up redirection '%s'\n", redir_str);
987     }
988     return;
989 
990  fail_syntax:
991     config_error(mon, "invalid redirection format '%s'\n", redir_str);
992 }
993 
net_slirp_redir(Monitor * mon,const char * redir_str,const char * redir_opt2)994 void net_slirp_redir(Monitor *mon, const char *redir_str, const char *redir_opt2)
995 {
996     struct slirp_config_str *config;
997 
998     if (!slirp_inited) {
999         if (mon) {
1000             monitor_printf(mon, "user mode network stack not in use\n");
1001         } else {
1002             config = qemu_malloc(sizeof(*config));
1003             config->str = redir_str;
1004             config->next = slirp_redirs;
1005             slirp_redirs = config;
1006         }
1007         return;
1008     }
1009 
1010     if (!strcmp(redir_str, "remove")) {
1011         net_slirp_redir_rm(mon, redir_opt2);
1012         return;
1013     }
1014 
1015     if (!strcmp(redir_str, "list")) {
1016         net_slirp_redir_list(mon);
1017         return;
1018     }
1019 
1020     slirp_redirection(mon, redir_str);
1021 }
1022 
1023 #ifndef _WIN32
1024 
1025 static char smb_dir[1024];
1026 
erase_dir(char * dir_name)1027 static void erase_dir(char *dir_name)
1028 {
1029     DIR *d;
1030     struct dirent *de;
1031     char filename[1024];
1032 
1033     /* erase all the files in the directory */
1034     if ((d = opendir(dir_name)) != NULL) {
1035         for(;;) {
1036             de = readdir(d);
1037             if (!de)
1038                 break;
1039             if (strcmp(de->d_name, ".") != 0 &&
1040                 strcmp(de->d_name, "..") != 0) {
1041                 snprintf(filename, sizeof(filename), "%s/%s",
1042                          smb_dir, de->d_name);
1043                 if (unlink(filename) != 0)  /* is it a directory? */
1044                     erase_dir(filename);
1045             }
1046         }
1047         closedir(d);
1048         rmdir(dir_name);
1049     }
1050 }
1051 
1052 /* automatic user mode samba server configuration */
smb_exit(void)1053 static void smb_exit(void)
1054 {
1055     erase_dir(smb_dir);
1056 }
1057 
slirp_smb(const char * exported_dir)1058 static void slirp_smb(const char *exported_dir)
1059 {
1060     char smb_conf[1024];
1061     char smb_cmdline[1024];
1062     FILE *f;
1063 
1064     /* XXX: better tmp dir construction */
1065     snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%ld", (long)getpid());
1066     if (mkdir(smb_dir, 0700) < 0) {
1067         fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1068         exit(1);
1069     }
1070     snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1071 
1072     f = fopen(smb_conf, "w");
1073     if (!f) {
1074         fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1075         exit(1);
1076     }
1077     fprintf(f,
1078             "[global]\n"
1079             "private dir=%s\n"
1080             "smb ports=0\n"
1081             "socket address=127.0.0.1\n"
1082             "pid directory=%s\n"
1083             "lock directory=%s\n"
1084             "log file=%s/log.smbd\n"
1085             "smb passwd file=%s/smbpasswd\n"
1086             "security = share\n"
1087             "[qemu]\n"
1088             "path=%s\n"
1089             "read only=no\n"
1090             "guest ok=yes\n",
1091             smb_dir,
1092             smb_dir,
1093             smb_dir,
1094             smb_dir,
1095             smb_dir,
1096             exported_dir
1097             );
1098     fclose(f);
1099     atexit(smb_exit);
1100 
1101     snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
1102              SMBD_COMMAND, smb_conf);
1103 
1104     slirp_add_exec(0, smb_cmdline, 4, 139);
1105 }
1106 
1107 /* automatic user mode samba server configuration */
net_slirp_smb(const char * exported_dir)1108 void net_slirp_smb(const char *exported_dir)
1109 {
1110     if (slirp_smb_export) {
1111         fprintf(stderr, "-smb given twice\n");
1112         exit(1);
1113     }
1114     slirp_smb_export = exported_dir;
1115     if (slirp_inited) {
1116         slirp_smb(exported_dir);
1117     }
1118 }
1119 
1120 #endif /* !defined(_WIN32) */
1121 
do_info_slirp(Monitor * mon)1122 void do_info_slirp(Monitor *mon)
1123 {
1124     //slirp_stats();
1125 }
1126 
1127 struct VMChannel {
1128     CharDriverState *hd;
1129     int port;
1130 };
1131 
vmchannel_can_read(void * opaque)1132 static int vmchannel_can_read(void *opaque)
1133 {
1134     struct VMChannel *vmc = (struct VMChannel*)opaque;
1135     return slirp_socket_can_recv(4, vmc->port);
1136 }
1137 
vmchannel_read(void * opaque,const uint8_t * buf,int size)1138 static void vmchannel_read(void *opaque, const uint8_t *buf, int size)
1139 {
1140     struct VMChannel *vmc = (struct VMChannel*)opaque;
1141     slirp_socket_recv(4, vmc->port, buf, size);
1142 }
1143 
1144 #endif /* CONFIG_SLIRP */
1145 
1146 #if !defined(_WIN32)
1147 
1148 typedef struct TAPState {
1149     VLANClientState *vc;
1150     int fd;
1151     char down_script[1024];
1152     char down_script_arg[128];
1153     uint8_t buf[4096];
1154 } TAPState;
1155 
1156 static int launch_script(const char *setup_script, const char *ifname, int fd);
1157 
tap_receive_iov(VLANClientState * vc,const struct iovec * iov,int iovcnt)1158 static ssize_t tap_receive_iov(VLANClientState *vc, const struct iovec *iov,
1159                                int iovcnt)
1160 {
1161     TAPState *s = vc->opaque;
1162     ssize_t len;
1163 
1164     do {
1165         len = writev(s->fd, iov, iovcnt);
1166     } while (len == -1 && (errno == EINTR || errno == EAGAIN));
1167 
1168     return len;
1169 }
1170 
tap_receive(VLANClientState * vc,const uint8_t * buf,size_t size)1171 static ssize_t tap_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1172 {
1173     TAPState *s = vc->opaque;
1174     ssize_t len;
1175 
1176     do {
1177         len = write(s->fd, buf, size);
1178     } while (len == -1 && (errno == EINTR || errno == EAGAIN));
1179 
1180     return len;
1181 }
1182 
tap_can_send(void * opaque)1183 static int tap_can_send(void *opaque)
1184 {
1185     TAPState *s = opaque;
1186 
1187     return qemu_can_send_packet(s->vc);
1188 }
1189 
1190 #ifdef __sun__
tap_read_packet(int tapfd,uint8_t * buf,int maxlen)1191 static ssize_t tap_read_packet(int tapfd, uint8_t *buf, int maxlen)
1192 {
1193     struct strbuf sbuf;
1194     int f = 0;
1195 
1196     sbuf.maxlen = maxlen;
1197     sbuf.buf = (char *)buf;
1198 
1199     return getmsg(tapfd, NULL, &sbuf, &f) >= 0 ? sbuf.len : -1;
1200 }
1201 #else
tap_read_packet(int tapfd,uint8_t * buf,int maxlen)1202 static ssize_t tap_read_packet(int tapfd, uint8_t *buf, int maxlen)
1203 {
1204     return read(tapfd, buf, maxlen);
1205 }
1206 #endif
1207 
1208 static void tap_send(void *opaque);
1209 
tap_send_completed(VLANClientState * vc)1210 static void tap_send_completed(VLANClientState *vc)
1211 {
1212     TAPState *s = vc->opaque;
1213 
1214     qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
1215 }
1216 
tap_send(void * opaque)1217 static void tap_send(void *opaque)
1218 {
1219     TAPState *s = opaque;
1220     int size;
1221 
1222     do {
1223         size = tap_read_packet(s->fd, s->buf, sizeof(s->buf));
1224         if (size <= 0) {
1225             break;
1226         }
1227 
1228         size = qemu_send_packet_async(s->vc, s->buf, size, tap_send_completed);
1229         if (size == 0) {
1230             qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
1231         }
1232     } while (size > 0);
1233 }
1234 
tap_cleanup(VLANClientState * vc)1235 static void tap_cleanup(VLANClientState *vc)
1236 {
1237     TAPState *s = vc->opaque;
1238 
1239     if (s->down_script[0])
1240         launch_script(s->down_script, s->down_script_arg, s->fd);
1241 
1242     qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1243     close(s->fd);
1244     qemu_free(s);
1245 }
1246 
1247 /* fd support */
1248 
net_tap_fd_init(VLANState * vlan,const char * model,const char * name,int fd)1249 static TAPState *net_tap_fd_init(VLANState *vlan,
1250                                  const char *model,
1251                                  const char *name,
1252                                  int fd)
1253 {
1254     TAPState *s;
1255 
1256     s = qemu_mallocz(sizeof(TAPState));
1257     s->fd = fd;
1258     s->vc = qemu_new_vlan_client(vlan, model, name, NULL, tap_receive,
1259                                  tap_receive_iov, tap_cleanup, s);
1260     qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
1261     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
1262     return s;
1263 }
1264 
1265 #if defined (CONFIG_BSD) || defined (__FreeBSD_kernel__)
tap_open(char * ifname,int ifname_size)1266 static int tap_open(char *ifname, int ifname_size)
1267 {
1268     int fd;
1269     char *dev;
1270     struct stat s;
1271 
1272     TFR(fd = open("/dev/tap", O_RDWR));
1273     if (fd < 0) {
1274         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1275         return -1;
1276     }
1277 
1278     fstat(fd, &s);
1279     dev = devname(s.st_rdev, S_IFCHR);
1280     pstrcpy(ifname, ifname_size, dev);
1281 
1282     fcntl(fd, F_SETFL, O_NONBLOCK);
1283     return fd;
1284 }
1285 #elif defined(__sun__)
1286 #define TUNNEWPPA       (('T'<<16) | 0x0001)
1287 /*
1288  * Allocate TAP device, returns opened fd.
1289  * Stores dev name in the first arg(must be large enough).
1290  */
tap_alloc(char * dev,size_t dev_size)1291 static int tap_alloc(char *dev, size_t dev_size)
1292 {
1293     int tap_fd, if_fd, ppa = -1;
1294     static int ip_fd = 0;
1295     char *ptr;
1296 
1297     static int arp_fd = 0;
1298     int ip_muxid, arp_muxid;
1299     struct strioctl  strioc_if, strioc_ppa;
1300     int link_type = I_PLINK;;
1301     struct lifreq ifr;
1302     char actual_name[32] = "";
1303 
1304     memset(&ifr, 0x0, sizeof(ifr));
1305 
1306     if( *dev ){
1307        ptr = dev;
1308        while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
1309        ppa = atoi(ptr);
1310     }
1311 
1312     /* Check if IP device was opened */
1313     if( ip_fd )
1314        close(ip_fd);
1315 
1316     TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
1317     if (ip_fd < 0) {
1318        syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
1319        return -1;
1320     }
1321 
1322     TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
1323     if (tap_fd < 0) {
1324        syslog(LOG_ERR, "Can't open /dev/tap");
1325        return -1;
1326     }
1327 
1328     /* Assign a new PPA and get its unit number. */
1329     strioc_ppa.ic_cmd = TUNNEWPPA;
1330     strioc_ppa.ic_timout = 0;
1331     strioc_ppa.ic_len = sizeof(ppa);
1332     strioc_ppa.ic_dp = (char *)&ppa;
1333     if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
1334        syslog (LOG_ERR, "Can't assign new interface");
1335 
1336     TFR(if_fd = open("/dev/tap", O_RDWR, 0));
1337     if (if_fd < 0) {
1338        syslog(LOG_ERR, "Can't open /dev/tap (2)");
1339        return -1;
1340     }
1341     if(ioctl(if_fd, I_PUSH, "ip") < 0){
1342        syslog(LOG_ERR, "Can't push IP module");
1343        return -1;
1344     }
1345 
1346     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
1347 	syslog(LOG_ERR, "Can't get flags\n");
1348 
1349     snprintf (actual_name, 32, "tap%d", ppa);
1350     pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1351 
1352     ifr.lifr_ppa = ppa;
1353     /* Assign ppa according to the unit number returned by tun device */
1354 
1355     if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
1356         syslog (LOG_ERR, "Can't set PPA %d", ppa);
1357     if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
1358         syslog (LOG_ERR, "Can't get flags\n");
1359     /* Push arp module to if_fd */
1360     if (ioctl (if_fd, I_PUSH, "arp") < 0)
1361         syslog (LOG_ERR, "Can't push ARP module (2)");
1362 
1363     /* Push arp module to ip_fd */
1364     if (ioctl (ip_fd, I_POP, NULL) < 0)
1365         syslog (LOG_ERR, "I_POP failed\n");
1366     if (ioctl (ip_fd, I_PUSH, "arp") < 0)
1367         syslog (LOG_ERR, "Can't push ARP module (3)\n");
1368     /* Open arp_fd */
1369     TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
1370     if (arp_fd < 0)
1371        syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
1372 
1373     /* Set ifname to arp */
1374     strioc_if.ic_cmd = SIOCSLIFNAME;
1375     strioc_if.ic_timout = 0;
1376     strioc_if.ic_len = sizeof(ifr);
1377     strioc_if.ic_dp = (char *)&ifr;
1378     if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
1379         syslog (LOG_ERR, "Can't set ifname to arp\n");
1380     }
1381 
1382     if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
1383        syslog(LOG_ERR, "Can't link TAP device to IP");
1384        return -1;
1385     }
1386 
1387     if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
1388         syslog (LOG_ERR, "Can't link TAP device to ARP");
1389 
1390     close (if_fd);
1391 
1392     memset(&ifr, 0x0, sizeof(ifr));
1393     pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1394     ifr.lifr_ip_muxid  = ip_muxid;
1395     ifr.lifr_arp_muxid = arp_muxid;
1396 
1397     if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
1398     {
1399       ioctl (ip_fd, I_PUNLINK , arp_muxid);
1400       ioctl (ip_fd, I_PUNLINK, ip_muxid);
1401       syslog (LOG_ERR, "Can't set multiplexor id");
1402     }
1403 
1404     snprintf(dev, dev_size, "tap%d", ppa);
1405     return tap_fd;
1406 }
1407 
tap_open(char * ifname,int ifname_size)1408 static int tap_open(char *ifname, int ifname_size)
1409 {
1410     char  dev[10]="";
1411     int fd;
1412     if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
1413        fprintf(stderr, "Cannot allocate TAP device\n");
1414        return -1;
1415     }
1416     pstrcpy(ifname, ifname_size, dev);
1417     fcntl(fd, F_SETFL, O_NONBLOCK);
1418     return fd;
1419 }
1420 #elif defined (_AIX)
tap_open(char * ifname,int ifname_size)1421 static int tap_open(char *ifname, int ifname_size)
1422 {
1423     fprintf (stderr, "no tap on AIX\n");
1424     return -1;
1425 }
1426 #else
tap_open(char * ifname,int ifname_size)1427 static int tap_open(char *ifname, int ifname_size)
1428 {
1429     struct ifreq ifr;
1430     int fd, ret;
1431 
1432     TFR(fd = open("/dev/net/tun", O_RDWR));
1433     if (fd < 0) {
1434         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1435         return -1;
1436     }
1437     memset(&ifr, 0, sizeof(ifr));
1438     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1439     if (ifname[0] != '\0')
1440         pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
1441     else
1442         pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
1443     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1444     if (ret != 0) {
1445         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1446         close(fd);
1447         return -1;
1448     }
1449     pstrcpy(ifname, ifname_size, ifr.ifr_name);
1450     fcntl(fd, F_SETFL, O_NONBLOCK);
1451     return fd;
1452 }
1453 #endif
1454 
launch_script(const char * setup_script,const char * ifname,int fd)1455 static int launch_script(const char *setup_script, const char *ifname, int fd)
1456 {
1457     sigset_t oldmask, mask;
1458     int pid, status;
1459     char *args[3];
1460     char **parg;
1461 
1462     sigemptyset(&mask);
1463     sigaddset(&mask, SIGCHLD);
1464     sigprocmask(SIG_BLOCK, &mask, &oldmask);
1465 
1466     /* try to launch network script */
1467     pid = fork();
1468     if (pid == 0) {
1469         int open_max = sysconf(_SC_OPEN_MAX), i;
1470 
1471         for (i = 0; i < open_max; i++) {
1472             if (i != STDIN_FILENO &&
1473                 i != STDOUT_FILENO &&
1474                 i != STDERR_FILENO &&
1475                 i != fd) {
1476                 close(i);
1477             }
1478         }
1479         parg = args;
1480         *parg++ = (char *)setup_script;
1481         *parg++ = (char *)ifname;
1482         *parg++ = NULL;
1483         execv(setup_script, args);
1484         _exit(1);
1485     } else if (pid > 0) {
1486         while (waitpid(pid, &status, 0) != pid) {
1487             /* loop */
1488         }
1489         sigprocmask(SIG_SETMASK, &oldmask, NULL);
1490 
1491         if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1492             return 0;
1493         }
1494     }
1495     fprintf(stderr, "%s: could not launch network script\n", setup_script);
1496     return -1;
1497 }
1498 
net_tap_init(VLANState * vlan,const char * model,const char * name,const char * ifname1,const char * setup_script,const char * down_script)1499 static int net_tap_init(VLANState *vlan, const char *model,
1500                         const char *name, const char *ifname1,
1501                         const char *setup_script, const char *down_script)
1502 {
1503     TAPState *s;
1504     int fd;
1505     char ifname[128];
1506 
1507     if (ifname1 != NULL)
1508         pstrcpy(ifname, sizeof(ifname), ifname1);
1509     else
1510         ifname[0] = '\0';
1511     TFR(fd = tap_open(ifname, sizeof(ifname)));
1512     if (fd < 0)
1513         return -1;
1514 
1515     if (!setup_script || !strcmp(setup_script, "no"))
1516         setup_script = "";
1517     if (setup_script[0] != '\0') {
1518 	if (launch_script(setup_script, ifname, fd))
1519 	    return -1;
1520     }
1521     s = net_tap_fd_init(vlan, model, name, fd);
1522     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1523              "ifname=%s,script=%s,downscript=%s",
1524              ifname, setup_script, down_script);
1525     if (down_script && strcmp(down_script, "no")) {
1526         snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1527         snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1528     }
1529     return 0;
1530 }
1531 
1532 #endif /* !_WIN32 */
1533 
1534 #if defined(CONFIG_VDE)
1535 typedef struct VDEState {
1536     VLANClientState *vc;
1537     VDECONN *vde;
1538 } VDEState;
1539 
vde_to_qemu(void * opaque)1540 static void vde_to_qemu(void *opaque)
1541 {
1542     VDEState *s = opaque;
1543     uint8_t buf[4096];
1544     int size;
1545 
1546     size = vde_recv(s->vde, (char *)buf, sizeof(buf), 0);
1547     if (size > 0) {
1548         qemu_send_packet(s->vc, buf, size);
1549     }
1550 }
1551 
vde_receive(VLANClientState * vc,const uint8_t * buf,size_t size)1552 static ssize_t vde_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1553 {
1554     VDEState *s = vc->opaque;
1555     ssize_t ret;
1556 
1557     do {
1558       ret = vde_send(s->vde, (const char *)buf, size, 0);
1559     } while (ret < 0 && errno == EINTR);
1560 
1561     return ret;
1562 }
1563 
vde_cleanup(VLANClientState * vc)1564 static void vde_cleanup(VLANClientState *vc)
1565 {
1566     VDEState *s = vc->opaque;
1567     qemu_set_fd_handler(vde_datafd(s->vde), NULL, NULL, NULL);
1568     vde_close(s->vde);
1569     qemu_free(s);
1570 }
1571 
net_vde_init(VLANState * vlan,const char * model,const char * name,const char * sock,int port,const char * group,int mode)1572 static int net_vde_init(VLANState *vlan, const char *model,
1573                         const char *name, const char *sock,
1574                         int port, const char *group, int mode)
1575 {
1576     VDEState *s;
1577     char *init_group = strlen(group) ? (char *)group : NULL;
1578     char *init_sock = strlen(sock) ? (char *)sock : NULL;
1579 
1580     struct vde_open_args args = {
1581         .port = port,
1582         .group = init_group,
1583         .mode = mode,
1584     };
1585 
1586     s = qemu_mallocz(sizeof(VDEState));
1587     s->vde = vde_open(init_sock, (char *)"QEMU", &args);
1588     if (!s->vde){
1589         free(s);
1590         return -1;
1591     }
1592     s->vc = qemu_new_vlan_client(vlan, model, name, NULL, vde_receive,
1593                                  NULL, vde_cleanup, s);
1594     qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1595     snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1596              sock, vde_datafd(s->vde));
1597     return 0;
1598 }
1599 #endif
1600 
1601 /* network connection */
1602 typedef struct NetSocketState {
1603     VLANClientState *vc;
1604     int fd;
1605     int state; /* 0 = getting length, 1 = getting data */
1606     unsigned int index;
1607     unsigned int packet_len;
1608     uint8_t buf[4096];
1609     SockAddress  dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1610 } NetSocketState;
1611 
1612 typedef struct NetSocketListenState {
1613     VLANState *vlan;
1614     char *model;
1615     char *name;
1616     int fd;
1617 } NetSocketListenState;
1618 
1619 /* XXX: we consider we can send the whole packet without blocking */
net_socket_receive(VLANClientState * vc,const uint8_t * buf,size_t size)1620 static ssize_t net_socket_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1621 {
1622     NetSocketState *s = vc->opaque;
1623     uint32_t len;
1624     len = htonl(size);
1625 
1626     socket_send(s->fd, (const uint8_t *)&len, sizeof(len));
1627     return socket_send(s->fd, buf, size);
1628 }
1629 
net_socket_receive_dgram(VLANClientState * vc,const uint8_t * buf,size_t size)1630 static ssize_t net_socket_receive_dgram(VLANClientState *vc, const uint8_t *buf, size_t size)
1631 {
1632     NetSocketState *s = vc->opaque;
1633 
1634     return socket_sendto(s->fd, buf, size, &s->dgram_dst);
1635 }
1636 
net_socket_send(void * opaque)1637 static void net_socket_send(void *opaque)
1638 {
1639     NetSocketState *s = opaque;
1640     int size, err;
1641     unsigned l;
1642     uint8_t buf1[4096];
1643     const uint8_t *buf;
1644 
1645     size = recv(s->fd, (void *)buf1, sizeof(buf1), 0);
1646     if (size < 0) {
1647         err = socket_error();
1648         if (err != EWOULDBLOCK && err != EAGAIN)
1649             goto eoc;
1650     } else if (size == 0) {
1651         /* end of connection */
1652     eoc:
1653         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1654         closesocket(s->fd);
1655         return;
1656     }
1657     buf = buf1;
1658     while (size > 0) {
1659         /* reassemble a packet from the network */
1660         switch(s->state) {
1661         case 0:
1662             l = 4 - s->index;
1663             if (l > size)
1664                 l = size;
1665             memcpy(s->buf + s->index, buf, l);
1666             buf += l;
1667             size -= l;
1668             s->index += l;
1669             if (s->index == 4) {
1670                 /* got length */
1671                 s->packet_len = ntohl(*(uint32_t *)s->buf);
1672                 s->index = 0;
1673                 s->state = 1;
1674             }
1675             break;
1676         case 1:
1677             l = s->packet_len - s->index;
1678             if (l > size)
1679                 l = size;
1680             if (s->index + l <= sizeof(s->buf)) {
1681                 memcpy(s->buf + s->index, buf, l);
1682             } else {
1683                 fprintf(stderr, "serious error: oversized packet received,"
1684                     "connection terminated.\n");
1685                 s->state = 0;
1686                 goto eoc;
1687             }
1688 
1689             s->index += l;
1690             buf += l;
1691             size -= l;
1692             if (s->index >= s->packet_len) {
1693                 qemu_send_packet(s->vc, s->buf, s->packet_len);
1694                 s->index = 0;
1695                 s->state = 0;
1696             }
1697             break;
1698         }
1699     }
1700 }
1701 
net_socket_send_dgram(void * opaque)1702 static void net_socket_send_dgram(void *opaque)
1703 {
1704     NetSocketState *s = opaque;
1705     int size;
1706 
1707     size = recv(s->fd, (void *)s->buf, sizeof(s->buf), 0);
1708     if (size < 0)
1709         return;
1710     if (size == 0) {
1711         /* end of connection */
1712         qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1713         return;
1714     }
1715     qemu_send_packet(s->vc, s->buf, size);
1716 }
1717 
net_socket_mcast_create(SockAddress * mcastaddr)1718 static int net_socket_mcast_create(SockAddress *mcastaddr)
1719 {
1720     int fd;
1721     int ret;
1722     if (!IN_MULTICAST(sock_address_get_ip(mcastaddr))) {
1723 	fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1724 		sock_address_to_string(mcastaddr),
1725                 sock_address_get_ip(mcastaddr));
1726 	return -1;
1727 
1728     }
1729     fd = socket_create_inet(SOCKET_DGRAM);
1730     if (fd < 0) {
1731         perror("socket(PF_INET, SOCK_DGRAM)");
1732         return -1;
1733     }
1734 
1735     ret = socket_set_xreuseaddr(fd);
1736     if (ret < 0) {
1737 	perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1738 	goto fail;
1739     }
1740 
1741     ret = socket_bind(fd, mcastaddr);
1742     if (ret < 0) {
1743         perror("bind");
1744         goto fail;
1745     }
1746 
1747     /* Add host to multicast group */
1748     ret = socket_mcast_inet_add_membership(fd, sock_address_get_ip(mcastaddr));
1749     if (ret < 0) {
1750 	perror("setsockopt(IP_ADD_MEMBERSHIP)");
1751 	goto fail;
1752     }
1753 
1754     /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1755     ret = socket_mcast_inet_set_loop(fd, 1);
1756     if (ret < 0) {
1757 	perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1758 	goto fail;
1759     }
1760 
1761     socket_set_nonblock(fd);
1762     return fd;
1763 fail:
1764     if (fd >= 0)
1765         socket_close(fd);
1766     return -1;
1767 }
1768 
net_socket_cleanup(VLANClientState * vc)1769 static void net_socket_cleanup(VLANClientState *vc)
1770 {
1771     NetSocketState *s = vc->opaque;
1772     qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1773     socket_close(s->fd);
1774     qemu_free(s);
1775 }
1776 
net_socket_fd_init_dgram(VLANState * vlan,const char * model,const char * name,int fd,int is_connected)1777 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1778                                                 const char *model,
1779                                                 const char *name,
1780                                                 int fd, int is_connected)
1781 {
1782     SockAddress  saddr;
1783     int newfd;
1784     NetSocketState *s;
1785 
1786     /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1787      * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1788      * by ONLY ONE process: we must "clone" this dgram socket --jjo
1789      */
1790 
1791     if (is_connected) {
1792 	if (socket_get_address(fd, &saddr) == 0) {
1793 	    /* must be bound */
1794 	    if (sock_address_get_ip(&saddr) == 0) {
1795 		fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1796 			fd);
1797 		return NULL;
1798 	    }
1799 	    /* clone dgram socket */
1800 	    newfd = net_socket_mcast_create(&saddr);
1801 	    if (newfd < 0) {
1802 		/* error already reported by net_socket_mcast_create() */
1803 		socket_close(fd);
1804 		return NULL;
1805 	    }
1806 	    /* clone newfd to fd, close newfd */
1807 	    dup2(newfd, fd);
1808 	    socket_close(newfd);
1809 
1810 	} else {
1811 	    fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1812 		    fd, strerror(errno));
1813 	    return NULL;
1814 	}
1815     }
1816 
1817     s = qemu_mallocz(sizeof(NetSocketState));
1818     s->fd = fd;
1819 
1820     s->vc = qemu_new_vlan_client(vlan, model, name, NULL, net_socket_receive_dgram,
1821                                  NULL, net_socket_cleanup, s);
1822     qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1823 
1824     /* mcast: save bound address as dst */
1825     if (is_connected) s->dgram_dst=saddr;
1826 
1827     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1828 	    "socket: fd=%d (%s mcast=%s)",
1829 	    fd, is_connected? "cloned" : "",
1830 	    sock_address_to_string(&saddr));
1831     return s;
1832 }
1833 
net_socket_connect(void * opaque)1834 static void net_socket_connect(void *opaque)
1835 {
1836     NetSocketState *s = opaque;
1837     qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1838 }
1839 
net_socket_fd_init_stream(VLANState * vlan,const char * model,const char * name,int fd,int is_connected)1840 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1841                                                  const char *model,
1842                                                  const char *name,
1843                                                  int fd, int is_connected)
1844 {
1845     NetSocketState *s;
1846     s = qemu_mallocz(sizeof(NetSocketState));
1847     s->fd = fd;
1848     s->vc = qemu_new_vlan_client(vlan, model, name, NULL, net_socket_receive,
1849                                  NULL, net_socket_cleanup, s);
1850     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1851              "socket: fd=%d", fd);
1852     if (is_connected) {
1853         net_socket_connect(s);
1854     } else {
1855         qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1856     }
1857     return s;
1858 }
1859 
net_socket_fd_init(VLANState * vlan,const char * model,const char * name,int fd,int is_connected)1860 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1861                                           const char *model, const char *name,
1862                                           int fd, int is_connected)
1863 {
1864     SocketType  so_type = socket_get_type(fd);
1865 
1866     switch(so_type) {
1867     case SOCKET_DGRAM:
1868         return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1869     case SOCKET_STREAM:
1870         return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1871     default:
1872         /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1873         fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1874         return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1875     }
1876     return NULL;
1877 }
1878 
net_socket_accept(void * opaque)1879 static void net_socket_accept(void *opaque)
1880 {
1881     NetSocketListenState *s = opaque;
1882     NetSocketState *s1;
1883     SockAddress  saddr;
1884     int fd;
1885 
1886     for(;;) {
1887         fd = socket_accept(s->fd, &saddr);
1888         if (fd < 0) {
1889             return;
1890         } else if (fd >= 0) {
1891             break;
1892         }
1893     }
1894     s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1895     if (!s1) {
1896         socket_close(fd);
1897     } else {
1898         snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1899                  "socket: connection from %s", sock_address_to_string(&saddr));
1900     }
1901 }
1902 
net_socket_listen_init(VLANState * vlan,const char * model,const char * name,const char * host_str)1903 static int net_socket_listen_init(VLANState *vlan,
1904                                   const char *model,
1905                                   const char *name,
1906                                   const char *host_str)
1907 {
1908     NetSocketListenState *s;
1909     int fd, ret;
1910     SockAddress  saddr;
1911 
1912     if (parse_host_port(&saddr, host_str) < 0)
1913         return -1;
1914 
1915     s = qemu_mallocz(sizeof(NetSocketListenState));
1916 
1917     fd = socket_create_inet(SOCKET_STREAM);
1918     if (fd < 0) {
1919         perror("socket");
1920         return -1;
1921     }
1922     socket_set_nonblock(fd);
1923 
1924     /* allow fast reuse */
1925     socket_set_xreuseaddr(fd);
1926 
1927     ret = socket_bind(fd, &saddr);
1928     if (ret < 0) {
1929         perror("bind");
1930         return -1;
1931     }
1932     ret = socket_listen(fd, 0);
1933     if (ret < 0) {
1934         perror("listen");
1935         return -1;
1936     }
1937     s->vlan = vlan;
1938     s->model = strdup(model);
1939     s->name = name ? strdup(name) : NULL;
1940     s->fd = fd;
1941     qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1942     return 0;
1943 }
1944 
net_socket_connect_init(VLANState * vlan,const char * model,const char * name,const char * host_str)1945 static int net_socket_connect_init(VLANState *vlan,
1946                                    const char *model,
1947                                    const char *name,
1948                                    const char *host_str)
1949 {
1950     NetSocketState *s;
1951     int fd, connected, ret, err;
1952     SockAddress saddr;
1953 
1954     if (parse_host_port(&saddr, host_str) < 0)
1955         return -1;
1956 
1957     fd = socket_create_inet(SOCKET_STREAM);
1958     if (fd < 0) {
1959         perror("socket");
1960         return -1;
1961     }
1962     socket_set_nonblock(fd);
1963 
1964     connected = 0;
1965     for(;;) {
1966         ret = socket_connect(fd, &saddr);
1967         if (ret < 0) {
1968             err = socket_error();
1969             if (err == EWOULDBLOCK || err == EAGAIN) {
1970             } else if (err == EINPROGRESS || err == EALREADY) {
1971                 break;
1972             } else {
1973                 perror("connect");
1974                 socket_close(fd);
1975                 return -1;
1976             }
1977         } else {
1978             connected = 1;
1979             break;
1980         }
1981     }
1982     s = net_socket_fd_init(vlan, model, name, fd, connected);
1983     if (!s)
1984         return -1;
1985     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1986              "socket: connect to %s",
1987              sock_address_to_string(&saddr));
1988     return 0;
1989 }
1990 
net_socket_mcast_init(VLANState * vlan,const char * model,const char * name,const char * host_str)1991 static int net_socket_mcast_init(VLANState *vlan,
1992                                  const char *model,
1993                                  const char *name,
1994                                  const char *host_str)
1995 {
1996     NetSocketState *s;
1997     int fd;
1998     SockAddress saddr;
1999 
2000     if (parse_host_port(&saddr, host_str) < 0)
2001         return -1;
2002 
2003 
2004     fd = net_socket_mcast_create(&saddr);
2005     if (fd < 0)
2006 	return -1;
2007 
2008     s = net_socket_fd_init(vlan, model, name, fd, 0);
2009     if (!s)
2010         return -1;
2011 
2012     s->dgram_dst = saddr;
2013 
2014     snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2015              "socket: mcast=%s",
2016              sock_address_to_string(&saddr));
2017     return 0;
2018 
2019 }
2020 
2021 typedef struct DumpState {
2022     VLANClientState *pcap_vc;
2023     int fd;
2024     int pcap_caplen;
2025 } DumpState;
2026 
2027 #define PCAP_MAGIC 0xa1b2c3d4
2028 
2029 struct pcap_file_hdr {
2030     uint32_t magic;
2031     uint16_t version_major;
2032     uint16_t version_minor;
2033     int32_t thiszone;
2034     uint32_t sigfigs;
2035     uint32_t snaplen;
2036     uint32_t linktype;
2037 };
2038 
2039 struct pcap_sf_pkthdr {
2040     struct {
2041         int32_t tv_sec;
2042         int32_t tv_usec;
2043     } ts;
2044     uint32_t caplen;
2045     uint32_t len;
2046 };
2047 
dump_receive(VLANClientState * vc,const uint8_t * buf,size_t size)2048 static ssize_t dump_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
2049 {
2050     DumpState *s = vc->opaque;
2051     struct pcap_sf_pkthdr hdr;
2052     int64_t ts;
2053     int caplen;
2054 
2055     /* Early return in case of previous error. */
2056     if (s->fd < 0) {
2057         return size;
2058     }
2059 
2060     ts = muldiv64(qemu_get_clock(vm_clock), 1000000, get_ticks_per_sec());
2061     caplen = size > s->pcap_caplen ? s->pcap_caplen : size;
2062 
2063     hdr.ts.tv_sec = ts / 1000000;
2064     hdr.ts.tv_usec = ts % 1000000;
2065     hdr.caplen = caplen;
2066     hdr.len = size;
2067     if (write(s->fd, &hdr, sizeof(hdr)) != sizeof(hdr) ||
2068         write(s->fd, buf, caplen) != caplen) {
2069         qemu_log("-net dump write error - stop dump\n");
2070         close(s->fd);
2071         s->fd = -1;
2072     }
2073 
2074     return size;
2075 }
2076 
net_dump_cleanup(VLANClientState * vc)2077 static void net_dump_cleanup(VLANClientState *vc)
2078 {
2079     DumpState *s = vc->opaque;
2080 
2081     close(s->fd);
2082     qemu_free(s);
2083 }
2084 
net_dump_init(Monitor * mon,VLANState * vlan,const char * device,const char * name,const char * filename,int len)2085 static int net_dump_init(Monitor *mon, VLANState *vlan, const char *device,
2086                          const char *name, const char *filename, int len)
2087 {
2088     struct pcap_file_hdr hdr;
2089     DumpState *s;
2090 
2091     s = qemu_malloc(sizeof(DumpState));
2092 
2093     s->fd = open(filename, O_CREAT | O_WRONLY, 0644);
2094     if (s->fd < 0) {
2095         config_error(mon, "-net dump: can't open %s\n", filename);
2096         return -1;
2097     }
2098 
2099     s->pcap_caplen = len;
2100 
2101     hdr.magic = PCAP_MAGIC;
2102     hdr.version_major = 2;
2103     hdr.version_minor = 4;
2104     hdr.thiszone = 0;
2105     hdr.sigfigs = 0;
2106     hdr.snaplen = s->pcap_caplen;
2107     hdr.linktype = 1;
2108 
2109     if (write(s->fd, &hdr, sizeof(hdr)) < sizeof(hdr)) {
2110         config_error(mon, "-net dump write error: %s\n", strerror(errno));
2111         close(s->fd);
2112         qemu_free(s);
2113         return -1;
2114     }
2115 
2116     s->pcap_vc = qemu_new_vlan_client(vlan, device, name, NULL, dump_receive, NULL,
2117                                       net_dump_cleanup, s);
2118     snprintf(s->pcap_vc->info_str, sizeof(s->pcap_vc->info_str),
2119              "dump to %s (len=%d)", filename, len);
2120     return 0;
2121 }
2122 
2123 /* find or alloc a new VLAN */
qemu_find_vlan(int id)2124 VLANState *qemu_find_vlan(int id)
2125 {
2126     VLANState **pvlan, *vlan;
2127     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2128         if (vlan->id == id)
2129             return vlan;
2130     }
2131     vlan = qemu_mallocz(sizeof(VLANState));
2132     vlan->id = id;
2133     vlan->next = NULL;
2134     pvlan = &first_vlan;
2135     while (*pvlan != NULL)
2136         pvlan = &(*pvlan)->next;
2137     *pvlan = vlan;
2138     return vlan;
2139 }
2140 
nic_get_free_idx(void)2141 static int nic_get_free_idx(void)
2142 {
2143     int index;
2144 
2145     for (index = 0; index < MAX_NICS; index++)
2146         if (!nd_table[index].used)
2147             return index;
2148     return -1;
2149 }
2150 
qemu_check_nic_model(NICInfo * nd,const char * model)2151 void qemu_check_nic_model(NICInfo *nd, const char *model)
2152 {
2153     const char *models[2];
2154 
2155     models[0] = model;
2156     models[1] = NULL;
2157 
2158     qemu_check_nic_model_list(nd, models, model);
2159 }
2160 
qemu_check_nic_model_list(NICInfo * nd,const char * const * models,const char * default_model)2161 void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
2162                                const char *default_model)
2163 {
2164     int i, exit_status = 0;
2165 
2166     if (!nd->model)
2167         nd->model = strdup(default_model);
2168 
2169     if (strcmp(nd->model, "?") != 0) {
2170         for (i = 0 ; models[i]; i++)
2171             if (strcmp(nd->model, models[i]) == 0)
2172                 return;
2173 
2174         fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
2175         exit_status = 1;
2176     }
2177 
2178     fprintf(stderr, "qemu: Supported NIC models: ");
2179     for (i = 0 ; models[i]; i++)
2180         fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
2181 
2182     exit(exit_status);
2183 }
2184 
net_client_init(Monitor * mon,const char * device,const char * p)2185 int net_client_init(Monitor *mon, const char *device, const char *p)
2186 {
2187     static const char * const fd_params[] = {
2188         "vlan", "name", "fd", NULL
2189     };
2190     char buf[1024];
2191     int vlan_id, ret;
2192     VLANState *vlan;
2193     char *name = NULL;
2194 
2195     vlan_id = 0;
2196     if (get_param_value(buf, sizeof(buf), "vlan", p)) {
2197         vlan_id = strtol(buf, NULL, 0);
2198     }
2199     vlan = qemu_find_vlan(vlan_id);
2200 
2201     if (get_param_value(buf, sizeof(buf), "name", p)) {
2202         name = qemu_strdup(buf);
2203     }
2204     if (!strcmp(device, "nic")) {
2205         static const char * const nic_params[] = {
2206             "vlan", "name", "macaddr", "model", NULL
2207         };
2208         NICInfo *nd;
2209         uint8_t *macaddr;
2210         int idx = nic_get_free_idx();
2211 
2212         if (check_params(buf, sizeof(buf), nic_params, p) < 0) {
2213             config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);
2214             ret = -1;
2215             goto out;
2216         }
2217         if (idx == -1 || nb_nics >= MAX_NICS) {
2218             config_error(mon, "Too Many NICs\n");
2219             ret = -1;
2220             goto out;
2221         }
2222         nd = &nd_table[idx];
2223         macaddr = nd->macaddr;
2224         macaddr[0] = 0x52;
2225         macaddr[1] = 0x54;
2226         macaddr[2] = 0x00;
2227         macaddr[3] = 0x12;
2228         macaddr[4] = 0x34;
2229         macaddr[5] = 0x56 + idx;
2230 
2231         if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
2232             if (parse_macaddr(macaddr, buf) < 0) {
2233                 config_error(mon, "invalid syntax for ethernet address\n");
2234                 ret = -1;
2235                 goto out;
2236             }
2237         }
2238         if (get_param_value(buf, sizeof(buf), "model", p)) {
2239             nd->model = strdup(buf);
2240         }
2241         nd->vlan = vlan;
2242         nd->name = name;
2243         nd->used = 1;
2244         name = NULL;
2245         nb_nics++;
2246         vlan->nb_guest_devs++;
2247         ret = idx;
2248     } else
2249     if (!strcmp(device, "none")) {
2250         if (*p != '\0') {
2251             config_error(mon, "'none' takes no parameters\n");
2252             ret = -1;
2253             goto out;
2254         }
2255         /* does nothing. It is needed to signal that no network cards
2256            are wanted */
2257         ret = 0;
2258     } else
2259 #ifdef CONFIG_SLIRP
2260     if (!strcmp(device, "user")) {
2261         static const char * const slirp_params[] = {
2262             "vlan", "name", "hostname", "restrict", "ip", NULL
2263         };
2264         int restricted = 0;
2265         char *ip = NULL;
2266 
2267         if (check_params(buf, sizeof(buf), slirp_params, p) < 0) {
2268             config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);
2269             ret = -1;
2270             goto out;
2271         }
2272         if (get_param_value(buf, sizeof(buf), "hostname", p)) {
2273             pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
2274         }
2275         if (get_param_value(buf, sizeof(buf), "restrict", p)) {
2276             restricted = (buf[0] == 'y') ? 1 : 0;
2277         }
2278         if (get_param_value(buf, sizeof(buf), "ip", p)) {
2279             ip = qemu_strdup(buf);
2280         }
2281         vlan->nb_host_devs++;
2282         ret = net_slirp_init(vlan, device, name, restricted, ip);
2283         qemu_free(ip);
2284     } else if (!strcmp(device, "channel")) {
2285         long port;
2286         char name[20], *devname;
2287         struct VMChannel *vmc;
2288 
2289         port = strtol(p, &devname, 10);
2290         devname++;
2291         if (port < 1 || port > 65535) {
2292             config_error(mon, "vmchannel wrong port number\n");
2293             ret = -1;
2294             goto out;
2295         }
2296         vmc = malloc(sizeof(struct VMChannel));
2297         snprintf(name, 20, "vmchannel%ld", port);
2298         vmc->hd = qemu_chr_open(name, devname, NULL);
2299         if (!vmc->hd) {
2300             config_error(mon, "could not open vmchannel device '%s'\n",
2301                          devname);
2302             ret = -1;
2303             goto out;
2304         }
2305         vmc->port = port;
2306         slirp_add_exec(3, vmc->hd, 4, port);
2307         qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,
2308                 NULL, vmc);
2309         ret = 0;
2310     } else
2311 #endif
2312 #ifdef _WIN32
2313     if (!strcmp(device, "tap")) {
2314         static const char * const tap_params[] = {
2315             "vlan", "name", "ifname", NULL
2316         };
2317         char ifname[64];
2318 
2319         if (check_params(buf, sizeof(buf), tap_params, p) < 0) {
2320             config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);
2321             ret = -1;
2322             goto out;
2323         }
2324         if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
2325             config_error(mon, "tap: no interface name\n");
2326             ret = -1;
2327             goto out;
2328         }
2329         vlan->nb_host_devs++;
2330         ret = tap_win32_init(vlan, device, name, ifname);
2331     } else
2332 #elif defined (_AIX)
2333 #else
2334     if (!strcmp(device, "tap")) {
2335         char ifname[64], chkbuf[64];
2336         char setup_script[1024], down_script[1024];
2337         int fd;
2338         vlan->nb_host_devs++;
2339         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2340             if (check_params(chkbuf, sizeof(chkbuf), fd_params, p) < 0) {
2341                 config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2342                 ret = -1;
2343                 goto out;
2344             }
2345             fd = strtol(buf, NULL, 0);
2346             fcntl(fd, F_SETFL, O_NONBLOCK);
2347             net_tap_fd_init(vlan, device, name, fd);
2348             ret = 0;
2349         } else {
2350             static const char * const tap_params[] = {
2351                 "vlan", "name", "ifname", "script", "downscript", NULL
2352             };
2353             if (check_params(chkbuf, sizeof(chkbuf), tap_params, p) < 0) {
2354                 config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2355                 ret = -1;
2356                 goto out;
2357             }
2358             if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
2359                 ifname[0] = '\0';
2360             }
2361             if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2362                 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2363             }
2364             if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
2365                 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
2366             }
2367             ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
2368         }
2369     } else
2370 #endif
2371     if (!strcmp(device, "socket")) {
2372         char chkbuf[64];
2373         if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2374             int fd;
2375             if (check_params(chkbuf, sizeof(chkbuf), fd_params, p) < 0) {
2376                 config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2377                 ret = -1;
2378                 goto out;
2379             }
2380             fd = strtol(buf, NULL, 0);
2381             ret = -1;
2382             if (net_socket_fd_init(vlan, device, name, fd, 1))
2383                 ret = 0;
2384         } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2385             static const char * const listen_params[] = {
2386                 "vlan", "name", "listen", NULL
2387             };
2388             if (check_params(chkbuf, sizeof(chkbuf), listen_params, p) < 0) {
2389                 config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2390                 ret = -1;
2391                 goto out;
2392             }
2393             ret = net_socket_listen_init(vlan, device, name, buf);
2394         } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2395             static const char * const connect_params[] = {
2396                 "vlan", "name", "connect", NULL
2397             };
2398             if (check_params(chkbuf, sizeof(chkbuf), connect_params, p) < 0) {
2399                 config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2400                 ret = -1;
2401                 goto out;
2402             }
2403             ret = net_socket_connect_init(vlan, device, name, buf);
2404         } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
2405             static const char * const mcast_params[] = {
2406                 "vlan", "name", "mcast", NULL
2407             };
2408             if (check_params(chkbuf, sizeof(chkbuf), mcast_params, p) < 0) {
2409                 config_error(mon, "invalid parameter '%s' in '%s'\n", chkbuf, p);
2410                 ret = -1;
2411                 goto out;
2412             }
2413             ret = net_socket_mcast_init(vlan, device, name, buf);
2414         } else {
2415             config_error(mon, "Unknown socket options: %s\n", p);
2416             ret = -1;
2417             goto out;
2418         }
2419         vlan->nb_host_devs++;
2420     } else
2421 #ifdef CONFIG_VDE
2422     if (!strcmp(device, "vde")) {
2423         static const char * const vde_params[] = {
2424             "vlan", "name", "sock", "port", "group", "mode", NULL
2425         };
2426         char vde_sock[1024], vde_group[512];
2427 	int vde_port, vde_mode;
2428 
2429         if (check_params(buf, sizeof(buf), vde_params, p) < 0) {
2430             config_error(mon, "invalid parameter '%s' in '%s'\n", buf, p);
2431             ret = -1;
2432             goto out;
2433         }
2434         vlan->nb_host_devs++;
2435         if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
2436 	    vde_sock[0] = '\0';
2437 	}
2438 	if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
2439 	    vde_port = strtol(buf, NULL, 10);
2440 	} else {
2441 	    vde_port = 0;
2442 	}
2443 	if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
2444 	    vde_group[0] = '\0';
2445 	}
2446 	if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
2447 	    vde_mode = strtol(buf, NULL, 8);
2448 	} else {
2449 	    vde_mode = 0700;
2450 	}
2451 	ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
2452     } else
2453 #endif
2454     if (!strcmp(device, "dump")) {
2455         int len = 65536;
2456 
2457         if (get_param_value(buf, sizeof(buf), "len", p) > 0) {
2458             len = strtol(buf, NULL, 0);
2459         }
2460         if (!get_param_value(buf, sizeof(buf), "file", p)) {
2461             snprintf(buf, sizeof(buf), "qemu-vlan%d.pcap", vlan_id);
2462         }
2463         ret = net_dump_init(mon, vlan, device, name, buf, len);
2464     } else {
2465         config_error(mon, "Unknown network device: %s\n", device);
2466         ret = -1;
2467         goto out;
2468     }
2469     if (ret < 0) {
2470         config_error(mon, "Could not initialize device '%s'\n", device);
2471     }
2472 out:
2473     qemu_free(name);
2474     return ret;
2475 }
2476 
net_client_uninit(NICInfo * nd)2477 void net_client_uninit(NICInfo *nd)
2478 {
2479     nd->vlan->nb_guest_devs--;
2480     nb_nics--;
2481     nd->used = 0;
2482     free((void *)nd->model);
2483 }
2484 
net_host_check_device(const char * device)2485 static int net_host_check_device(const char *device)
2486 {
2487     int i;
2488     const char *valid_param_list[] = { "tap", "socket", "dump"
2489 #ifdef CONFIG_SLIRP
2490                                        ,"user"
2491 #endif
2492 #ifdef CONFIG_VDE
2493                                        ,"vde"
2494 #endif
2495     };
2496     for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
2497         if (!strncmp(valid_param_list[i], device,
2498                      strlen(valid_param_list[i])))
2499             return 1;
2500     }
2501 
2502     return 0;
2503 }
2504 
net_host_device_add(Monitor * mon,const char * device,const char * opts)2505 void net_host_device_add(Monitor *mon, const char *device, const char *opts)
2506 {
2507     if (!net_host_check_device(device)) {
2508         monitor_printf(mon, "invalid host network device %s\n", device);
2509         return;
2510     }
2511     if (net_client_init(mon, device, opts ? opts : "") < 0) {
2512         monitor_printf(mon, "adding host network device %s failed\n", device);
2513     }
2514 }
2515 
net_host_device_remove(Monitor * mon,int vlan_id,const char * device)2516 void net_host_device_remove(Monitor *mon, int vlan_id, const char *device)
2517 {
2518     VLANState *vlan;
2519     VLANClientState *vc;
2520 
2521     vlan = qemu_find_vlan(vlan_id);
2522 
2523     for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
2524         if (!strcmp(vc->name, device)) {
2525             break;
2526         }
2527     }
2528 
2529     if (!vc) {
2530         monitor_printf(mon, "can't find device %s\n", device);
2531         return;
2532     }
2533     if (!net_host_check_device(vc->model)) {
2534         monitor_printf(mon, "invalid host network device %s\n", device);
2535         return;
2536     }
2537     qemu_del_vlan_client(vc);
2538 }
2539 
net_client_parse(const char * str)2540 int net_client_parse(const char *str)
2541 {
2542     const char *p;
2543     char *q;
2544     char device[64];
2545 
2546     p = str;
2547     q = device;
2548     while (*p != '\0' && *p != ',') {
2549         if ((q - device) < sizeof(device) - 1)
2550             *q++ = *p;
2551         p++;
2552     }
2553     *q = '\0';
2554     if (*p == ',')
2555         p++;
2556 
2557     return net_client_init(NULL, device, p);
2558 }
2559 
do_info_network(Monitor * mon)2560 void do_info_network(Monitor *mon)
2561 {
2562     VLANState *vlan;
2563     VLANClientState *vc;
2564 
2565     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2566         monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
2567         for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2568             monitor_printf(mon, "  %s: %s\n", vc->name, vc->info_str);
2569     }
2570 }
2571 
do_set_link(Monitor * mon,const char * name,const char * up_or_down)2572 int do_set_link(Monitor *mon, const char *name, const char *up_or_down)
2573 {
2574     VLANState *vlan;
2575     VLANClientState *vc = NULL;
2576 
2577     for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
2578         for (vc = vlan->first_client; vc != NULL; vc = vc->next)
2579             if (strcmp(vc->name, name) == 0)
2580                 goto done;
2581 done:
2582 
2583     if (!vc) {
2584         monitor_printf(mon, "could not find network device '%s'", name);
2585         return 0;
2586     }
2587 
2588     if (strcmp(up_or_down, "up") == 0)
2589         vc->link_down = 0;
2590     else if (strcmp(up_or_down, "down") == 0)
2591         vc->link_down = 1;
2592     else
2593         monitor_printf(mon, "invalid link status '%s'; only 'up' or 'down' "
2594                        "valid\n", up_or_down);
2595 
2596     if (vc->link_status_changed)
2597         vc->link_status_changed(vc);
2598 
2599     return 1;
2600 }
2601 
net_cleanup(void)2602 void net_cleanup(void)
2603 {
2604     VLANState *vlan;
2605 
2606     /* close network clients */
2607     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2608         VLANClientState *vc = vlan->first_client;
2609 
2610         while (vc) {
2611             VLANClientState *next = vc->next;
2612 
2613             qemu_del_vlan_client(vc);
2614 
2615             vc = next;
2616         }
2617     }
2618 }
2619 
net_client_check(void)2620 void net_client_check(void)
2621 {
2622     VLANState *vlan;
2623 
2624     for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2625         if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
2626             continue;
2627         if (vlan->nb_guest_devs == 0)
2628             fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
2629         if (vlan->nb_host_devs == 0)
2630             fprintf(stderr,
2631                     "Warning: vlan %d is not connected to host network\n",
2632                     vlan->id);
2633     }
2634 }
2635 
2636 int
android_parse_network_speed(const char * speed)2637 android_parse_network_speed(const char*  speed)
2638 {
2639     int          n;
2640     char*  end;
2641     double       sp;
2642 
2643     if (speed == NULL || speed[0] == 0) {
2644         speed = DEFAULT_NETSPEED;
2645     }
2646 
2647     for (n = 0; android_netspeeds[n].name != NULL; n++) {
2648         if (!strcmp(android_netspeeds[n].name, speed)) {
2649             qemu_net_download_speed = android_netspeeds[n].download;
2650             qemu_net_upload_speed   = android_netspeeds[n].upload;
2651             return 0;
2652         }
2653     }
2654 
2655     /* is this a number ? */
2656     sp = strtod(speed, &end);
2657     if (end == speed) {
2658         return -1;
2659     }
2660 
2661     qemu_net_download_speed = qemu_net_upload_speed = sp*1000.;
2662     if (*end == ':') {
2663         speed = end+1;
2664         sp = strtod(speed, &end);
2665         if (end > speed) {
2666             qemu_net_download_speed = sp*1000.;
2667         }
2668     }
2669 
2670     if (android_modem)
2671         amodem_set_data_network_type( android_modem,
2672                                       android_parse_network_type(speed) );
2673     return 0;
2674 }
2675 
2676 
2677 int
android_parse_network_latency(const char * delay)2678 android_parse_network_latency(const char*  delay)
2679 {
2680     int  n;
2681     char*  end;
2682     double  sp;
2683 
2684     if (delay == NULL || delay[0] == 0)
2685         delay = DEFAULT_NETDELAY;
2686 
2687     for (n = 0; android_netdelays[n].name != NULL; n++) {
2688         if ( !strcmp( android_netdelays[n].name, delay ) ) {
2689             qemu_net_min_latency = android_netdelays[n].min_ms;
2690             qemu_net_max_latency = android_netdelays[n].max_ms;
2691             return 0;
2692         }
2693     }
2694 
2695     /* is this a number ? */
2696     sp = strtod(delay, &end);
2697     if (end == delay) {
2698         return -1;
2699     }
2700 
2701     qemu_net_min_latency = qemu_net_max_latency = (int)sp;
2702     if (*end == ':') {
2703         delay = (const char*)end+1;
2704         sp = strtod(delay, &end);
2705         if (end > delay) {
2706             qemu_net_max_latency = (int)sp;
2707         }
2708     }
2709     return 0;
2710 }
2711