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