Merge commit '5610c3aaf4196cf714fb9cb57118187963550d1c' into upstream-merge
[qemu-kvm/markmc.git] / net.c
blob92a40441721c6036ad5c5bbc437e35f2f5818dda
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
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>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <sys/times.h>
37 #include <sys/wait.h>
38 #include <termios.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/resource.h>
42 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <net/if.h>
45 #ifdef __NetBSD__
46 #include <net/if_tap.h>
47 #endif
48 #ifdef __linux__
49 #include <linux/if_tun.h>
50 #endif
51 #include <arpa/inet.h>
52 #include <dirent.h>
53 #include <netdb.h>
54 #include <sys/select.h>
55 #ifdef CONFIG_BSD
56 #include <sys/stat.h>
57 #if defined(__FreeBSD__) || defined(__DragonFly__)
58 #include <libutil.h>
59 #else
60 #include <util.h>
61 #endif
62 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
63 #include <freebsd/stdlib.h>
64 #else
65 #ifdef __linux__
66 #include <pty.h>
67 #include <malloc.h>
68 #include <linux/rtc.h>
70 /* For the benefit of older linux systems which don't supply it,
71 we use a local copy of hpet.h. */
72 /* #include <linux/hpet.h> */
73 #include "hpet.h"
75 #include <linux/ppdev.h>
76 #include <linux/parport.h>
77 #endif
78 #ifdef __sun__
79 #include <sys/stat.h>
80 #include <sys/ethernet.h>
81 #include <sys/sockio.h>
82 #include <netinet/arp.h>
83 #include <netinet/in.h>
84 #include <netinet/in_systm.h>
85 #include <netinet/ip.h>
86 #include <netinet/ip_icmp.h> // must come after ip.h
87 #include <netinet/udp.h>
88 #include <netinet/tcp.h>
89 #include <net/if.h>
90 #include <syslog.h>
91 #include <stropts.h>
92 #endif
93 #endif
94 #endif
96 #if defined(__OpenBSD__)
97 #include <util.h>
98 #endif
100 #if defined(CONFIG_VDE)
101 #include <libvdeplug.h>
102 #endif
104 // FIXME: #include "qemu-kvm.h"
105 #include "qemu-common.h"
106 #include "net.h"
107 #include "monitor.h"
108 #include "sysemu.h"
109 #include "qemu-timer.h"
110 #include "qemu-char.h"
111 #include "audio/audio.h"
112 #include "qemu_socket.h"
113 #include "qemu-log.h"
114 #include "qemu-config.h"
116 #include "slirp/libslirp.h"
118 static QTAILQ_HEAD(, VLANState) vlans;
120 /***********************************************************/
121 /* network device redirectors */
123 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
124 static void hex_dump(FILE *f, const uint8_t *buf, int size)
126 int len, i, j, c;
128 for(i=0;i<size;i+=16) {
129 len = size - i;
130 if (len > 16)
131 len = 16;
132 fprintf(f, "%08x ", i);
133 for(j=0;j<16;j++) {
134 if (j < len)
135 fprintf(f, " %02x", buf[i+j]);
136 else
137 fprintf(f, " ");
139 fprintf(f, " ");
140 for(j=0;j<len;j++) {
141 c = buf[i+j];
142 if (c < ' ' || c > '~')
143 c = '.';
144 fprintf(f, "%c", c);
146 fprintf(f, "\n");
149 #endif
151 static int parse_macaddr(uint8_t *macaddr, const char *p)
153 int i;
154 char *last_char;
155 long int offset;
157 errno = 0;
158 offset = strtol(p, &last_char, 0);
159 if (0 == errno && '\0' == *last_char &&
160 offset >= 0 && offset <= 0xFFFFFF) {
161 macaddr[3] = (offset & 0xFF0000) >> 16;
162 macaddr[4] = (offset & 0xFF00) >> 8;
163 macaddr[5] = offset & 0xFF;
164 return 0;
165 } else {
166 for(i = 0; i < 6; i++) {
167 macaddr[i] = strtol(p, (char **)&p, 16);
168 if (i == 5) {
169 if (*p != '\0')
170 return -1;
171 } else {
172 if (*p != ':' && *p != '-')
173 return -1;
174 p++;
177 return 0;
180 return -1;
183 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
185 const char *p, *p1;
186 int len;
187 p = *pp;
188 p1 = strchr(p, sep);
189 if (!p1)
190 return -1;
191 len = p1 - p;
192 p1++;
193 if (buf_size > 0) {
194 if (len > buf_size - 1)
195 len = buf_size - 1;
196 memcpy(buf, p, len);
197 buf[len] = '\0';
199 *pp = p1;
200 return 0;
203 int parse_host_src_port(struct sockaddr_in *haddr,
204 struct sockaddr_in *saddr,
205 const char *input_str)
207 char *str = strdup(input_str);
208 char *host_str = str;
209 char *src_str;
210 const char *src_str2;
211 char *ptr;
214 * Chop off any extra arguments at the end of the string which
215 * would start with a comma, then fill in the src port information
216 * if it was provided else use the "any address" and "any port".
218 if ((ptr = strchr(str,',')))
219 *ptr = '\0';
221 if ((src_str = strchr(input_str,'@'))) {
222 *src_str = '\0';
223 src_str++;
226 if (parse_host_port(haddr, host_str) < 0)
227 goto fail;
229 src_str2 = src_str;
230 if (!src_str || *src_str == '\0')
231 src_str2 = ":0";
233 if (parse_host_port(saddr, src_str2) < 0)
234 goto fail;
236 free(str);
237 return(0);
239 fail:
240 free(str);
241 return -1;
244 int parse_host_port(struct sockaddr_in *saddr, const char *str)
246 char buf[512];
247 struct hostent *he;
248 const char *p, *r;
249 int port;
251 p = str;
252 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
253 return -1;
254 saddr->sin_family = AF_INET;
255 if (buf[0] == '\0') {
256 saddr->sin_addr.s_addr = 0;
257 } else {
258 if (qemu_isdigit(buf[0])) {
259 if (!inet_aton(buf, &saddr->sin_addr))
260 return -1;
261 } else {
262 if ((he = gethostbyname(buf)) == NULL)
263 return - 1;
264 saddr->sin_addr = *(struct in_addr *)he->h_addr;
267 port = strtol(p, (char **)&r, 0);
268 if (r == p)
269 return -1;
270 saddr->sin_port = htons(port);
271 return 0;
274 void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6])
276 snprintf(vc->info_str, sizeof(vc->info_str),
277 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
278 vc->model,
279 macaddr[0], macaddr[1], macaddr[2],
280 macaddr[3], macaddr[4], macaddr[5]);
283 static char *assign_name(VLANClientState *vc1, const char *model)
285 VLANState *vlan;
286 char buf[256];
287 int id = 0;
289 QTAILQ_FOREACH(vlan, &vlans, next) {
290 VLANClientState *vc;
292 QTAILQ_FOREACH(vc, &vlan->clients, next) {
293 if (vc != vc1 && strcmp(vc->model, model) == 0) {
294 id++;
299 snprintf(buf, sizeof(buf), "%s.%d", model, id);
301 return qemu_strdup(buf);
304 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
305 const char *model,
306 const char *name,
307 NetCanReceive *can_receive,
308 NetReceive *receive,
309 NetReceiveIOV *receive_iov,
310 NetCleanup *cleanup,
311 void *opaque)
313 VLANClientState *vc;
315 vc = qemu_mallocz(sizeof(VLANClientState));
317 vc->model = qemu_strdup(model);
318 if (name)
319 vc->name = qemu_strdup(name);
320 else
321 vc->name = assign_name(vc, model);
322 vc->can_receive = can_receive;
323 vc->receive = receive;
324 vc->receive_iov = receive_iov;
325 vc->cleanup = cleanup;
326 vc->opaque = opaque;
328 vc->vlan = vlan;
329 QTAILQ_INSERT_TAIL(&vc->vlan->clients, vc, next);
331 return vc;
334 void qemu_del_vlan_client(VLANClientState *vc)
336 QTAILQ_REMOVE(&vc->vlan->clients, vc, next);
338 if (vc->cleanup) {
339 vc->cleanup(vc);
342 qemu_free(vc->name);
343 qemu_free(vc->model);
344 qemu_free(vc);
347 VLANClientState *qemu_find_vlan_client(VLANState *vlan, void *opaque)
349 VLANClientState *vc;
351 QTAILQ_FOREACH(vc, &vlan->clients, next) {
352 if (vc->opaque == opaque) {
353 return vc;
357 return NULL;
360 static VLANClientState *
361 qemu_find_vlan_client_by_name(Monitor *mon, int vlan_id,
362 const char *client_str)
364 VLANState *vlan;
365 VLANClientState *vc;
367 vlan = qemu_find_vlan(vlan_id, 0);
368 if (!vlan) {
369 monitor_printf(mon, "unknown VLAN %d\n", vlan_id);
370 return NULL;
373 QTAILQ_FOREACH(vc, &vlan->clients, next) {
374 if (!strcmp(vc->name, client_str)) {
375 break;
378 if (!vc) {
379 monitor_printf(mon, "can't find device %s on VLAN %d\n",
380 client_str, vlan_id);
383 return vc;
386 int qemu_can_send_packet(VLANClientState *sender)
388 VLANState *vlan = sender->vlan;
389 VLANClientState *vc;
391 QTAILQ_FOREACH(vc, &vlan->clients, next) {
392 if (vc == sender) {
393 continue;
396 /* no can_receive() handler, they can always receive */
397 if (!vc->can_receive || vc->can_receive(vc)) {
398 return 1;
401 return 0;
404 static int
405 qemu_deliver_packet(VLANClientState *sender, const uint8_t *buf, int size, int raw)
407 VLANClientState *vc;
408 int ret = -1;
410 sender->vlan->delivering = 1;
412 QTAILQ_FOREACH(vc, &sender->vlan->clients, next) {
413 ssize_t len;
415 if (vc == sender) {
416 continue;
419 if (vc->link_down) {
420 ret = size;
421 continue;
424 if (raw && vc->receive_raw) {
425 len = vc->receive_raw(vc, buf, size);
426 } else {
427 len = vc->receive(vc, buf, size);
430 ret = (ret >= 0) ? ret : len;
433 sender->vlan->delivering = 0;
435 return ret;
438 void qemu_purge_queued_packets(VLANClientState *vc)
440 VLANPacket *packet, *next;
442 QTAILQ_FOREACH_SAFE(packet, &vc->vlan->send_queue, entry, next) {
443 if (packet->sender == vc) {
444 QTAILQ_REMOVE(&vc->vlan->send_queue, packet, entry);
445 qemu_free(packet);
450 void qemu_flush_queued_packets(VLANClientState *vc)
452 while (!QTAILQ_EMPTY(&vc->vlan->send_queue)) {
453 VLANPacket *packet;
454 int ret;
456 packet = QTAILQ_FIRST(&vc->vlan->send_queue);
457 QTAILQ_REMOVE(&vc->vlan->send_queue, packet, entry);
459 ret = qemu_deliver_packet(packet->sender, packet->data,
460 packet->size, packet->raw);
461 if (ret == 0 && packet->sent_cb != NULL) {
462 QTAILQ_INSERT_HEAD(&vc->vlan->send_queue, packet, entry);
463 break;
466 if (packet->sent_cb)
467 packet->sent_cb(packet->sender, ret);
469 qemu_free(packet);
473 static void qemu_enqueue_packet(VLANClientState *sender,
474 const uint8_t *buf, int size, int raw,
475 NetPacketSent *sent_cb)
477 VLANPacket *packet;
479 packet = qemu_malloc(sizeof(VLANPacket) + size);
480 packet->sender = sender;
481 packet->size = size;
482 packet->raw = raw;
483 packet->sent_cb = sent_cb;
484 memcpy(packet->data, buf, size);
486 QTAILQ_INSERT_TAIL(&sender->vlan->send_queue, packet, entry);
489 static ssize_t qemu_send_packet_async2(VLANClientState *sender,
490 const uint8_t *buf, int size, int raw,
491 NetPacketSent *sent_cb)
493 int ret;
495 if (sender->link_down) {
496 return size;
499 #ifdef DEBUG_NET
500 printf("vlan %d send:\n", sender->vlan->id);
501 hex_dump(stdout, buf, size);
502 #endif
504 if (sender->vlan->delivering) {
505 qemu_enqueue_packet(sender, buf, size, raw, NULL);
506 return size;
509 ret = qemu_deliver_packet(sender, buf, size, raw);
510 if (ret == 0 && sent_cb != NULL) {
511 qemu_enqueue_packet(sender, buf, size, raw, sent_cb);
512 return 0;
515 qemu_flush_queued_packets(sender);
517 return ret;
520 ssize_t qemu_send_packet_async(VLANClientState *sender,
521 const uint8_t *buf, int size,
522 NetPacketSent *sent_cb)
524 return qemu_send_packet_async2(sender, buf, size, 0, sent_cb);
527 ssize_t qemu_send_packet(VLANClientState *sender, const uint8_t *buf, int size)
529 return qemu_send_packet_async2(sender, buf, size, 0, NULL);
532 ssize_t qemu_send_packet_raw(VLANClientState *sender, const uint8_t *buf, int size)
534 return qemu_send_packet_async2(sender, buf, size, 1, NULL);
537 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
538 int iovcnt)
540 uint8_t buffer[4096];
541 size_t offset = 0;
542 int i;
544 for (i = 0; i < iovcnt; i++) {
545 size_t len;
547 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
548 memcpy(buffer + offset, iov[i].iov_base, len);
549 offset += len;
552 return vc->receive(vc, buffer, offset);
555 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
557 size_t offset = 0;
558 int i;
560 for (i = 0; i < iovcnt; i++)
561 offset += iov[i].iov_len;
562 return offset;
565 static int qemu_deliver_packet_iov(VLANClientState *sender,
566 const struct iovec *iov, int iovcnt)
568 VLANClientState *vc;
569 int ret = -1;
571 sender->vlan->delivering = 1;
573 QTAILQ_FOREACH(vc, &sender->vlan->clients, next) {
574 ssize_t len;
576 if (vc == sender) {
577 continue;
580 if (vc->link_down) {
581 ret = calc_iov_length(iov, iovcnt);
582 continue;
585 if (vc->receive_iov) {
586 len = vc->receive_iov(vc, iov, iovcnt);
587 } else {
588 len = vc_sendv_compat(vc, iov, iovcnt);
591 ret = (ret >= 0) ? ret : len;
594 sender->vlan->delivering = 0;
596 return ret;
599 static ssize_t qemu_enqueue_packet_iov(VLANClientState *sender,
600 const struct iovec *iov, int iovcnt,
601 NetPacketSent *sent_cb)
603 VLANPacket *packet;
604 size_t max_len = 0;
605 int i;
607 max_len = calc_iov_length(iov, iovcnt);
609 packet = qemu_malloc(sizeof(VLANPacket) + max_len);
610 packet->sender = sender;
611 packet->sent_cb = sent_cb;
612 packet->size = 0;
613 packet->raw = 0;
615 for (i = 0; i < iovcnt; i++) {
616 size_t len = iov[i].iov_len;
618 memcpy(packet->data + packet->size, iov[i].iov_base, len);
619 packet->size += len;
622 QTAILQ_INSERT_TAIL(&sender->vlan->send_queue, packet, entry);
624 return packet->size;
627 ssize_t qemu_sendv_packet_async(VLANClientState *sender,
628 const struct iovec *iov, int iovcnt,
629 NetPacketSent *sent_cb)
631 int ret;
633 if (sender->link_down) {
634 return calc_iov_length(iov, iovcnt);
637 if (sender->vlan->delivering) {
638 return qemu_enqueue_packet_iov(sender, iov, iovcnt, NULL);
641 ret = qemu_deliver_packet_iov(sender, iov, iovcnt);
642 if (ret == 0 && sent_cb != NULL) {
643 qemu_enqueue_packet_iov(sender, iov, iovcnt, sent_cb);
644 return 0;
647 qemu_flush_queued_packets(sender);
649 return ret;
652 ssize_t
653 qemu_sendv_packet(VLANClientState *vc, const struct iovec *iov, int iovcnt)
655 return qemu_sendv_packet_async(vc, iov, iovcnt, NULL);
658 #if defined(CONFIG_SLIRP)
660 /* slirp network adapter */
662 #define SLIRP_CFG_HOSTFWD 1
663 #define SLIRP_CFG_LEGACY 2
665 struct slirp_config_str {
666 struct slirp_config_str *next;
667 int flags;
668 char str[1024];
669 int legacy_format;
672 typedef struct SlirpState {
673 QTAILQ_ENTRY(SlirpState) entry;
674 VLANClientState *vc;
675 Slirp *slirp;
676 #ifndef _WIN32
677 char smb_dir[128];
678 #endif
679 } SlirpState;
681 static struct slirp_config_str *slirp_configs;
682 const char *legacy_tftp_prefix;
683 const char *legacy_bootp_filename;
684 static QTAILQ_HEAD(slirp_stacks, SlirpState) slirp_stacks =
685 QTAILQ_HEAD_INITIALIZER(slirp_stacks);
687 static int slirp_hostfwd(SlirpState *s, const char *redir_str,
688 int legacy_format);
689 static int slirp_guestfwd(SlirpState *s, const char *config_str,
690 int legacy_format);
692 #ifndef _WIN32
693 static const char *legacy_smb_export;
695 static int slirp_smb(SlirpState *s, const char *exported_dir,
696 struct in_addr vserver_addr);
697 static void slirp_smb_cleanup(SlirpState *s);
698 #else
699 static inline void slirp_smb_cleanup(SlirpState *s) { }
700 #endif
702 int slirp_can_output(void *opaque)
704 SlirpState *s = opaque;
706 return qemu_can_send_packet(s->vc);
709 void slirp_output(void *opaque, const uint8_t *pkt, int pkt_len)
711 SlirpState *s = opaque;
713 #ifdef DEBUG_SLIRP
714 printf("slirp output:\n");
715 hex_dump(stdout, pkt, pkt_len);
716 #endif
717 qemu_send_packet(s->vc, pkt, pkt_len);
720 static ssize_t slirp_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
722 SlirpState *s = vc->opaque;
724 #ifdef DEBUG_SLIRP
725 printf("slirp input:\n");
726 hex_dump(stdout, buf, size);
727 #endif
728 slirp_input(s->slirp, buf, size);
729 return size;
732 static void net_slirp_cleanup(VLANClientState *vc)
734 SlirpState *s = vc->opaque;
736 slirp_cleanup(s->slirp);
737 slirp_smb_cleanup(s);
738 QTAILQ_REMOVE(&slirp_stacks, s, entry);
739 qemu_free(s);
742 static int net_slirp_init(VLANState *vlan, const char *model,
743 const char *name, int restricted,
744 const char *vnetwork, const char *vhost,
745 const char *vhostname, const char *tftp_export,
746 const char *bootfile, const char *vdhcp_start,
747 const char *vnameserver, const char *smb_export,
748 const char *vsmbserver)
750 /* default settings according to historic slirp */
751 struct in_addr net = { .s_addr = htonl(0x0a000200) }; /* 10.0.2.0 */
752 struct in_addr mask = { .s_addr = htonl(0xffffff00) }; /* 255.255.255.0 */
753 struct in_addr host = { .s_addr = htonl(0x0a000202) }; /* 10.0.2.2 */
754 struct in_addr dhcp = { .s_addr = htonl(0x0a00020f) }; /* 10.0.2.15 */
755 struct in_addr dns = { .s_addr = htonl(0x0a000203) }; /* 10.0.2.3 */
756 #ifndef _WIN32
757 struct in_addr smbsrv = { .s_addr = 0 };
758 #endif
759 SlirpState *s;
760 char buf[20];
761 uint32_t addr;
762 int shift;
763 char *end;
764 struct slirp_config_str *config;
766 if (!tftp_export) {
767 tftp_export = legacy_tftp_prefix;
769 if (!bootfile) {
770 bootfile = legacy_bootp_filename;
773 if (vnetwork) {
774 if (get_str_sep(buf, sizeof(buf), &vnetwork, '/') < 0) {
775 if (!inet_aton(vnetwork, &net)) {
776 return -1;
778 addr = ntohl(net.s_addr);
779 if (!(addr & 0x80000000)) {
780 mask.s_addr = htonl(0xff000000); /* class A */
781 } else if ((addr & 0xfff00000) == 0xac100000) {
782 mask.s_addr = htonl(0xfff00000); /* priv. 172.16.0.0/12 */
783 } else if ((addr & 0xc0000000) == 0x80000000) {
784 mask.s_addr = htonl(0xffff0000); /* class B */
785 } else if ((addr & 0xffff0000) == 0xc0a80000) {
786 mask.s_addr = htonl(0xffff0000); /* priv. 192.168.0.0/16 */
787 } else if ((addr & 0xffff0000) == 0xc6120000) {
788 mask.s_addr = htonl(0xfffe0000); /* tests 198.18.0.0/15 */
789 } else if ((addr & 0xe0000000) == 0xe0000000) {
790 mask.s_addr = htonl(0xffffff00); /* class C */
791 } else {
792 mask.s_addr = htonl(0xfffffff0); /* multicast/reserved */
794 } else {
795 if (!inet_aton(buf, &net)) {
796 return -1;
798 shift = strtol(vnetwork, &end, 10);
799 if (*end != '\0') {
800 if (!inet_aton(vnetwork, &mask)) {
801 return -1;
803 } else if (shift < 4 || shift > 32) {
804 return -1;
805 } else {
806 mask.s_addr = htonl(0xffffffff << (32 - shift));
809 net.s_addr &= mask.s_addr;
810 host.s_addr = net.s_addr | (htonl(0x0202) & ~mask.s_addr);
811 dhcp.s_addr = net.s_addr | (htonl(0x020f) & ~mask.s_addr);
812 dns.s_addr = net.s_addr | (htonl(0x0203) & ~mask.s_addr);
815 if (vhost && !inet_aton(vhost, &host)) {
816 return -1;
818 if ((host.s_addr & mask.s_addr) != net.s_addr) {
819 return -1;
822 if (vdhcp_start && !inet_aton(vdhcp_start, &dhcp)) {
823 return -1;
825 if ((dhcp.s_addr & mask.s_addr) != net.s_addr ||
826 dhcp.s_addr == host.s_addr || dhcp.s_addr == dns.s_addr) {
827 return -1;
830 if (vnameserver && !inet_aton(vnameserver, &dns)) {
831 return -1;
833 if ((dns.s_addr & mask.s_addr) != net.s_addr ||
834 dns.s_addr == host.s_addr) {
835 return -1;
838 #ifndef _WIN32
839 if (vsmbserver && !inet_aton(vsmbserver, &smbsrv)) {
840 return -1;
842 #endif
844 s = qemu_mallocz(sizeof(SlirpState));
845 s->slirp = slirp_init(restricted, net, mask, host, vhostname,
846 tftp_export, bootfile, dhcp, dns, s);
847 QTAILQ_INSERT_TAIL(&slirp_stacks, s, entry);
849 for (config = slirp_configs; config; config = config->next) {
850 if (config->flags & SLIRP_CFG_HOSTFWD) {
851 if (slirp_hostfwd(s, config->str,
852 config->flags & SLIRP_CFG_LEGACY) < 0)
853 return -1;
854 } else {
855 if (slirp_guestfwd(s, config->str,
856 config->flags & SLIRP_CFG_LEGACY) < 0)
857 return -1;
860 #ifndef _WIN32
861 if (!smb_export) {
862 smb_export = legacy_smb_export;
864 if (smb_export) {
865 if (slirp_smb(s, smb_export, smbsrv) < 0)
866 return -1;
868 #endif
870 s->vc = qemu_new_vlan_client(vlan, model, name, NULL, slirp_receive, NULL,
871 net_slirp_cleanup, s);
872 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
873 "net=%s, restricted=%c", inet_ntoa(net), restricted ? 'y' : 'n');
874 return 0;
877 static SlirpState *slirp_lookup(Monitor *mon, const char *vlan,
878 const char *stack)
880 VLANClientState *vc;
882 if (vlan) {
883 vc = qemu_find_vlan_client_by_name(mon, strtol(vlan, NULL, 0), stack);
884 if (!vc) {
885 return NULL;
887 if (strcmp(vc->model, "user")) {
888 monitor_printf(mon, "invalid device specified\n");
889 return NULL;
891 return vc->opaque;
892 } else {
893 if (QTAILQ_EMPTY(&slirp_stacks)) {
894 monitor_printf(mon, "user mode network stack not in use\n");
895 return NULL;
897 return QTAILQ_FIRST(&slirp_stacks);
901 void net_slirp_hostfwd_remove(Monitor *mon, const QDict *qdict)
903 struct in_addr host_addr = { .s_addr = INADDR_ANY };
904 int host_port;
905 char buf[256] = "";
906 const char *src_str, *p;
907 SlirpState *s;
908 int is_udp = 0;
909 int err;
910 const char *arg1 = qdict_get_str(qdict, "arg1");
911 const char *arg2 = qdict_get_try_str(qdict, "arg2");
912 const char *arg3 = qdict_get_try_str(qdict, "arg3");
914 if (arg2) {
915 s = slirp_lookup(mon, arg1, arg2);
916 src_str = arg3;
917 } else {
918 s = slirp_lookup(mon, NULL, NULL);
919 src_str = arg1;
921 if (!s) {
922 return;
925 if (!src_str || !src_str[0])
926 goto fail_syntax;
928 p = src_str;
929 get_str_sep(buf, sizeof(buf), &p, ':');
931 if (!strcmp(buf, "tcp") || buf[0] == '\0') {
932 is_udp = 0;
933 } else if (!strcmp(buf, "udp")) {
934 is_udp = 1;
935 } else {
936 goto fail_syntax;
939 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
940 goto fail_syntax;
942 if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
943 goto fail_syntax;
946 host_port = atoi(p);
948 err = slirp_remove_hostfwd(QTAILQ_FIRST(&slirp_stacks)->slirp, is_udp,
949 host_addr, host_port);
951 monitor_printf(mon, "host forwarding rule for %s %s\n", src_str,
952 err ? "removed" : "not found");
953 return;
955 fail_syntax:
956 monitor_printf(mon, "invalid format\n");
959 static int slirp_hostfwd(SlirpState *s, const char *redir_str,
960 int legacy_format)
962 struct in_addr host_addr = { .s_addr = INADDR_ANY };
963 struct in_addr guest_addr = { .s_addr = 0 };
964 int host_port, guest_port;
965 const char *p;
966 char buf[256];
967 int is_udp;
968 char *end;
970 p = redir_str;
971 if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
972 goto fail_syntax;
974 if (!strcmp(buf, "tcp") || buf[0] == '\0') {
975 is_udp = 0;
976 } else if (!strcmp(buf, "udp")) {
977 is_udp = 1;
978 } else {
979 goto fail_syntax;
982 if (!legacy_format) {
983 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
984 goto fail_syntax;
986 if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
987 goto fail_syntax;
991 if (get_str_sep(buf, sizeof(buf), &p, legacy_format ? ':' : '-') < 0) {
992 goto fail_syntax;
994 host_port = strtol(buf, &end, 0);
995 if (*end != '\0' || host_port < 1 || host_port > 65535) {
996 goto fail_syntax;
999 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1000 goto fail_syntax;
1002 if (buf[0] != '\0' && !inet_aton(buf, &guest_addr)) {
1003 goto fail_syntax;
1006 guest_port = strtol(p, &end, 0);
1007 if (*end != '\0' || guest_port < 1 || guest_port > 65535) {
1008 goto fail_syntax;
1011 if (slirp_add_hostfwd(s->slirp, is_udp, host_addr, host_port, guest_addr,
1012 guest_port) < 0) {
1013 qemu_error("could not set up host forwarding rule '%s'\n",
1014 redir_str);
1015 return -1;
1017 return 0;
1019 fail_syntax:
1020 qemu_error("invalid host forwarding rule '%s'\n", redir_str);
1021 return -1;
1024 void net_slirp_hostfwd_add(Monitor *mon, const QDict *qdict)
1026 const char *redir_str;
1027 SlirpState *s;
1028 const char *arg1 = qdict_get_str(qdict, "arg1");
1029 const char *arg2 = qdict_get_try_str(qdict, "arg2");
1030 const char *arg3 = qdict_get_try_str(qdict, "arg3");
1032 if (arg2) {
1033 s = slirp_lookup(mon, arg1, arg2);
1034 redir_str = arg3;
1035 } else {
1036 s = slirp_lookup(mon, NULL, NULL);
1037 redir_str = arg1;
1039 if (s) {
1040 slirp_hostfwd(s, redir_str, 0);
1045 int net_slirp_redir(const char *redir_str)
1047 struct slirp_config_str *config;
1049 if (QTAILQ_EMPTY(&slirp_stacks)) {
1050 config = qemu_malloc(sizeof(*config));
1051 pstrcpy(config->str, sizeof(config->str), redir_str);
1052 config->flags = SLIRP_CFG_HOSTFWD | SLIRP_CFG_LEGACY;
1053 config->next = slirp_configs;
1054 slirp_configs = config;
1055 return 0;
1058 return slirp_hostfwd(QTAILQ_FIRST(&slirp_stacks), redir_str, 1);
1061 #ifndef _WIN32
1063 /* automatic user mode samba server configuration */
1064 static void slirp_smb_cleanup(SlirpState *s)
1066 char cmd[128];
1068 if (s->smb_dir[0] != '\0') {
1069 snprintf(cmd, sizeof(cmd), "rm -rf %s", s->smb_dir);
1070 system(cmd);
1071 s->smb_dir[0] = '\0';
1075 static int slirp_smb(SlirpState* s, const char *exported_dir,
1076 struct in_addr vserver_addr)
1078 static int instance;
1079 char smb_conf[128];
1080 char smb_cmdline[128];
1081 FILE *f;
1083 snprintf(s->smb_dir, sizeof(s->smb_dir), "/tmp/qemu-smb.%ld-%d",
1084 (long)getpid(), instance++);
1085 if (mkdir(s->smb_dir, 0700) < 0) {
1086 qemu_error("could not create samba server dir '%s'\n", s->smb_dir);
1087 return -1;
1089 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", s->smb_dir, "smb.conf");
1091 f = fopen(smb_conf, "w");
1092 if (!f) {
1093 slirp_smb_cleanup(s);
1094 qemu_error("could not create samba server configuration file '%s'\n",
1095 smb_conf);
1096 return -1;
1098 fprintf(f,
1099 "[global]\n"
1100 "private dir=%s\n"
1101 "smb ports=0\n"
1102 "socket address=127.0.0.1\n"
1103 "pid directory=%s\n"
1104 "lock directory=%s\n"
1105 "log file=%s/log.smbd\n"
1106 "smb passwd file=%s/smbpasswd\n"
1107 "security = share\n"
1108 "[qemu]\n"
1109 "path=%s\n"
1110 "read only=no\n"
1111 "guest ok=yes\n",
1112 s->smb_dir,
1113 s->smb_dir,
1114 s->smb_dir,
1115 s->smb_dir,
1116 s->smb_dir,
1117 exported_dir
1119 fclose(f);
1121 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
1122 SMBD_COMMAND, smb_conf);
1124 if (slirp_add_exec(s->slirp, 0, smb_cmdline, &vserver_addr, 139) < 0) {
1125 slirp_smb_cleanup(s);
1126 qemu_error("conflicting/invalid smbserver address\n");
1127 return -1;
1129 return 0;
1132 /* automatic user mode samba server configuration (legacy interface) */
1133 int net_slirp_smb(const char *exported_dir)
1135 struct in_addr vserver_addr = { .s_addr = 0 };
1137 if (legacy_smb_export) {
1138 fprintf(stderr, "-smb given twice\n");
1139 return -1;
1141 legacy_smb_export = exported_dir;
1142 if (!QTAILQ_EMPTY(&slirp_stacks)) {
1143 return slirp_smb(QTAILQ_FIRST(&slirp_stacks), exported_dir,
1144 vserver_addr);
1146 return 0;
1149 #endif /* !defined(_WIN32) */
1151 struct GuestFwd {
1152 CharDriverState *hd;
1153 struct in_addr server;
1154 int port;
1155 Slirp *slirp;
1158 static int guestfwd_can_read(void *opaque)
1160 struct GuestFwd *fwd = opaque;
1161 return slirp_socket_can_recv(fwd->slirp, fwd->server, fwd->port);
1164 static void guestfwd_read(void *opaque, const uint8_t *buf, int size)
1166 struct GuestFwd *fwd = opaque;
1167 slirp_socket_recv(fwd->slirp, fwd->server, fwd->port, buf, size);
1170 static int slirp_guestfwd(SlirpState *s, const char *config_str,
1171 int legacy_format)
1173 struct in_addr server = { .s_addr = 0 };
1174 struct GuestFwd *fwd;
1175 const char *p;
1176 char buf[128];
1177 char *end;
1178 int port;
1180 p = config_str;
1181 if (legacy_format) {
1182 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1183 goto fail_syntax;
1185 } else {
1186 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1187 goto fail_syntax;
1189 if (strcmp(buf, "tcp") && buf[0] != '\0') {
1190 goto fail_syntax;
1192 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1193 goto fail_syntax;
1195 if (buf[0] != '\0' && !inet_aton(buf, &server)) {
1196 goto fail_syntax;
1198 if (get_str_sep(buf, sizeof(buf), &p, '-') < 0) {
1199 goto fail_syntax;
1202 port = strtol(buf, &end, 10);
1203 if (*end != '\0' || port < 1 || port > 65535) {
1204 goto fail_syntax;
1207 fwd = qemu_malloc(sizeof(struct GuestFwd));
1208 snprintf(buf, sizeof(buf), "guestfwd.tcp:%d", port);
1209 fwd->hd = qemu_chr_open(buf, p, NULL);
1210 if (!fwd->hd) {
1211 qemu_error("could not open guest forwarding device '%s'\n", buf);
1212 qemu_free(fwd);
1213 return -1;
1216 if (slirp_add_exec(s->slirp, 3, fwd->hd, &server, port) < 0) {
1217 qemu_error("conflicting/invalid host:port in guest forwarding "
1218 "rule '%s'\n", config_str);
1219 qemu_free(fwd);
1220 return -1;
1222 fwd->server = server;
1223 fwd->port = port;
1224 fwd->slirp = s->slirp;
1226 qemu_chr_add_handlers(fwd->hd, guestfwd_can_read, guestfwd_read,
1227 NULL, fwd);
1228 return 0;
1230 fail_syntax:
1231 qemu_error("invalid guest forwarding rule '%s'\n", config_str);
1232 return -1;
1235 void do_info_usernet(Monitor *mon)
1237 SlirpState *s;
1239 QTAILQ_FOREACH(s, &slirp_stacks, entry) {
1240 monitor_printf(mon, "VLAN %d (%s):\n", s->vc->vlan->id, s->vc->name);
1241 slirp_connection_info(s->slirp, mon);
1245 #endif /* CONFIG_SLIRP */
1247 #ifdef _WIN32
1249 int tap_has_vnet_hdr(void *opaque)
1251 return 0;
1254 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
1258 int tap_has_ufo(void *opaque)
1260 return 0;
1263 #else /* !defined(_WIN32) */
1265 /* Maximum GSO packet size (64k) plus plenty of room for
1266 * the ethernet and virtio_net headers
1268 #define TAP_BUFSIZE (4096 + 65536)
1270 #ifdef IFF_VNET_HDR
1271 #include <linux/virtio_net.h>
1272 #endif
1274 typedef struct TAPState {
1275 VLANClientState *vc;
1276 int fd;
1277 char down_script[1024];
1278 char down_script_arg[128];
1279 uint8_t buf[TAP_BUFSIZE];
1280 unsigned int read_poll : 1;
1281 unsigned int write_poll : 1;
1282 unsigned int has_vnet_hdr : 1;
1283 unsigned int using_vnet_hdr : 1;
1284 unsigned int has_ufo: 1;
1285 } TAPState;
1287 static int launch_script(const char *setup_script, const char *ifname, int fd);
1289 static int tap_can_send(void *opaque);
1290 static void tap_send(void *opaque);
1291 static void tap_writable(void *opaque);
1293 static void tap_update_fd_handler(TAPState *s)
1295 qemu_set_fd_handler2(s->fd,
1296 s->read_poll ? tap_can_send : NULL,
1297 s->read_poll ? tap_send : NULL,
1298 s->write_poll ? tap_writable : NULL,
1302 static void tap_read_poll(TAPState *s, int enable)
1304 s->read_poll = !!enable;
1305 tap_update_fd_handler(s);
1308 static void tap_write_poll(TAPState *s, int enable)
1310 s->write_poll = !!enable;
1311 tap_update_fd_handler(s);
1314 static void tap_writable(void *opaque)
1316 TAPState *s = opaque;
1318 tap_write_poll(s, 0);
1320 qemu_flush_queued_packets(s->vc);
1323 static ssize_t tap_receive_iov(VLANClientState *vc, const struct iovec *iov,
1324 int iovcnt)
1326 TAPState *s = vc->opaque;
1327 ssize_t len;
1329 do {
1330 len = writev(s->fd, iov, iovcnt);
1331 } while (len == -1 && errno == EINTR);
1333 if (len == -1 && errno == EAGAIN) {
1334 tap_write_poll(s, 1);
1335 return 0;
1338 return len;
1341 static ssize_t tap_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1343 struct iovec iov[2];
1344 int i = 0;
1346 #ifdef IFF_VNET_HDR
1347 TAPState *s = vc->opaque;
1348 struct virtio_net_hdr hdr = { 0, };
1350 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
1351 iov[i].iov_base = &hdr;
1352 iov[i].iov_len = sizeof(hdr);
1353 i++;
1355 #endif
1357 iov[i].iov_base = (char *) buf;
1358 iov[i].iov_len = size;
1359 i++;
1361 return tap_receive_iov(vc, iov, i);
1364 static ssize_t tap_receive_raw(VLANClientState *vc, const uint8_t *buf, size_t size)
1366 struct iovec iov[2];
1367 int i = 0;
1369 #ifdef IFF_VNET_HDR
1370 TAPState *s = vc->opaque;
1371 struct virtio_net_hdr hdr = { 0, };
1373 if (s->has_vnet_hdr && s->using_vnet_hdr) {
1374 iov[i].iov_base = &hdr;
1375 iov[i].iov_len = sizeof(hdr);
1376 i++;
1378 #endif
1380 iov[i].iov_base = (char *) buf;
1381 iov[i].iov_len = size;
1382 i++;
1384 return tap_receive_iov(vc, iov, i);
1387 static int tap_can_send(void *opaque)
1389 TAPState *s = opaque;
1391 return qemu_can_send_packet(s->vc);
1394 #ifdef __sun__
1395 static ssize_t tap_read_packet(int tapfd, uint8_t *buf, int maxlen)
1397 struct strbuf sbuf;
1398 int f = 0;
1400 sbuf.maxlen = maxlen;
1401 sbuf.buf = (char *)buf;
1403 return getmsg(tapfd, NULL, &sbuf, &f) >= 0 ? sbuf.len : -1;
1405 #else
1406 static ssize_t tap_read_packet(int tapfd, uint8_t *buf, int maxlen)
1408 return read(tapfd, buf, maxlen);
1410 #endif
1412 static void tap_send_completed(VLANClientState *vc, ssize_t len)
1414 TAPState *s = vc->opaque;
1415 tap_read_poll(s, 1);
1418 static void tap_send(void *opaque)
1420 TAPState *s = opaque;
1421 int size;
1423 do {
1424 uint8_t *buf = s->buf;
1426 size = tap_read_packet(s->fd, s->buf, sizeof(s->buf));
1427 if (size <= 0) {
1428 break;
1431 #ifdef IFF_VNET_HDR
1432 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
1433 buf += sizeof(struct virtio_net_hdr);
1434 size -= sizeof(struct virtio_net_hdr);
1436 #endif
1438 size = qemu_send_packet_async(s->vc, buf, size, tap_send_completed);
1439 if (size == 0) {
1440 tap_read_poll(s, 0);
1442 } while (size > 0);
1445 #ifdef TUNSETSNDBUF
1446 /* sndbuf should be set to a value lower than the tx queue
1447 * capacity of any destination network interface.
1448 * Ethernet NICs generally have txqueuelen=1000, so 1Mb is
1449 * a good default, given a 1500 byte MTU.
1451 #define TAP_DEFAULT_SNDBUF 1024*1024
1453 static int tap_set_sndbuf(TAPState *s, QemuOpts *opts)
1455 int sndbuf;
1457 sndbuf = qemu_opt_get_size(opts, "sndbuf", TAP_DEFAULT_SNDBUF);
1458 if (!sndbuf) {
1459 sndbuf = INT_MAX;
1462 if (ioctl(s->fd, TUNSETSNDBUF, &sndbuf) == -1 && qemu_opt_get(opts, "sndbuf")) {
1463 qemu_error("TUNSETSNDBUF ioctl failed: %s\n", strerror(errno));
1464 return -1;
1466 return 0;
1468 #else
1469 static int tap_set_sndbuf(TAPState *s, QemuOpts *opts)
1471 return 0;
1473 #endif /* TUNSETSNDBUF */
1475 int tap_has_vnet_hdr(void *opaque)
1477 VLANClientState *vc = opaque;
1478 TAPState *s = vc->opaque;
1480 if (vc->receive != tap_receive)
1481 return 0;
1483 return s ? s->has_vnet_hdr : 0;
1486 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
1488 VLANClientState *vc = opaque;
1489 TAPState *s = vc->opaque;
1491 if (vc->receive != tap_receive)
1492 return;
1494 if (!s || !s->has_vnet_hdr)
1495 return;
1497 s->using_vnet_hdr = using_vnet_hdr != 0;
1500 static int tap_probe_vnet_hdr(int fd)
1502 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
1503 struct ifreq ifr;
1505 if (ioctl(fd, TUNGETIFF, &ifr) != 0) {
1506 fprintf(stderr, "TUNGETIFF ioctl() failed: %s\n", strerror(errno));
1507 return 0;
1510 return ifr.ifr_flags & IFF_VNET_HDR;
1511 #else
1512 return 0;
1513 #endif
1516 int tap_has_ufo(void *opaque)
1518 VLANClientState *vc = opaque;
1519 TAPState *s = vc->opaque;
1521 return s ? s->has_ufo : 0;
1524 #ifdef TUNSETOFFLOAD
1526 #ifndef TUN_F_UFO
1527 #define TUN_F_UFO 0x10
1528 #endif
1530 static void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6,
1531 int ecn, int ufo)
1533 TAPState *s = vc->opaque;
1534 unsigned int offload = 0;
1536 if (csum) {
1537 offload |= TUN_F_CSUM;
1538 if (tso4)
1539 offload |= TUN_F_TSO4;
1540 if (tso6)
1541 offload |= TUN_F_TSO6;
1542 if ((tso4 || tso6) && ecn)
1543 offload |= TUN_F_TSO_ECN;
1544 if (ufo)
1545 offload |= TUN_F_UFO;
1548 if (ioctl(s->fd, TUNSETOFFLOAD, offload) != 0) {
1549 /* Try without UFO */
1550 offload &= ~TUN_F_UFO;
1551 if (ioctl(s->fd, TUNSETOFFLOAD, offload) != 0) {
1552 fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n",
1553 strerror(errno));
1557 #endif /* TUNSETOFFLOAD */
1559 static void tap_cleanup(VLANClientState *vc)
1561 TAPState *s = vc->opaque;
1563 qemu_purge_queued_packets(vc);
1565 if (s->down_script[0])
1566 launch_script(s->down_script, s->down_script_arg, s->fd);
1568 tap_read_poll(s, 0);
1569 tap_write_poll(s, 0);
1570 close(s->fd);
1571 qemu_free(s);
1574 /* fd support */
1576 static TAPState *net_tap_fd_init(VLANState *vlan,
1577 const char *model,
1578 const char *name,
1579 int fd,
1580 int vnet_hdr)
1582 TAPState *s;
1583 unsigned int offload;
1585 s = qemu_mallocz(sizeof(TAPState));
1586 s->fd = fd;
1587 s->has_vnet_hdr = vnet_hdr != 0;
1588 s->vc = qemu_new_vlan_client(vlan, model, name, NULL, tap_receive,
1589 tap_receive_iov, tap_cleanup, s);
1590 s->vc->receive_raw = tap_receive_raw;
1591 #ifdef TUNSETOFFLOAD
1592 s->vc->set_offload = tap_set_offload;
1594 s->has_ufo = 0;
1595 /* Check if tap supports UFO */
1596 offload = TUN_F_CSUM | TUN_F_UFO;
1597 if (ioctl(s->fd, TUNSETOFFLOAD, offload) == 0)
1598 s->has_ufo = 1;
1600 tap_set_offload(s->vc, 0, 0, 0, 0, 0);
1601 #endif
1602 tap_read_poll(s, 1);
1603 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
1604 return s;
1607 #if defined (CONFIG_BSD) || defined (__FreeBSD_kernel__)
1608 static int tap_open(char *ifname, int ifname_size)
1610 int fd;
1611 char *dev;
1612 struct stat s;
1614 TFR(fd = open("/dev/tap", O_RDWR));
1615 if (fd < 0) {
1616 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1617 return -1;
1620 fstat(fd, &s);
1621 dev = devname(s.st_rdev, S_IFCHR);
1622 pstrcpy(ifname, ifname_size, dev);
1624 fcntl(fd, F_SETFL, O_NONBLOCK);
1625 return fd;
1627 #elif defined(__sun__)
1628 #define TUNNEWPPA (('T'<<16) | 0x0001)
1630 * Allocate TAP device, returns opened fd.
1631 * Stores dev name in the first arg(must be large enough).
1633 static int tap_alloc(char *dev, size_t dev_size)
1635 int tap_fd, if_fd, ppa = -1;
1636 static int ip_fd = 0;
1637 char *ptr;
1639 static int arp_fd = 0;
1640 int ip_muxid, arp_muxid;
1641 struct strioctl strioc_if, strioc_ppa;
1642 int link_type = I_PLINK;;
1643 struct lifreq ifr;
1644 char actual_name[32] = "";
1646 memset(&ifr, 0x0, sizeof(ifr));
1648 if( *dev ){
1649 ptr = dev;
1650 while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
1651 ppa = atoi(ptr);
1654 /* Check if IP device was opened */
1655 if( ip_fd )
1656 close(ip_fd);
1658 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
1659 if (ip_fd < 0) {
1660 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
1661 return -1;
1664 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
1665 if (tap_fd < 0) {
1666 syslog(LOG_ERR, "Can't open /dev/tap");
1667 return -1;
1670 /* Assign a new PPA and get its unit number. */
1671 strioc_ppa.ic_cmd = TUNNEWPPA;
1672 strioc_ppa.ic_timout = 0;
1673 strioc_ppa.ic_len = sizeof(ppa);
1674 strioc_ppa.ic_dp = (char *)&ppa;
1675 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
1676 syslog (LOG_ERR, "Can't assign new interface");
1678 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
1679 if (if_fd < 0) {
1680 syslog(LOG_ERR, "Can't open /dev/tap (2)");
1681 return -1;
1683 if(ioctl(if_fd, I_PUSH, "ip") < 0){
1684 syslog(LOG_ERR, "Can't push IP module");
1685 return -1;
1688 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
1689 syslog(LOG_ERR, "Can't get flags\n");
1691 snprintf (actual_name, 32, "tap%d", ppa);
1692 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1694 ifr.lifr_ppa = ppa;
1695 /* Assign ppa according to the unit number returned by tun device */
1697 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
1698 syslog (LOG_ERR, "Can't set PPA %d", ppa);
1699 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
1700 syslog (LOG_ERR, "Can't get flags\n");
1701 /* Push arp module to if_fd */
1702 if (ioctl (if_fd, I_PUSH, "arp") < 0)
1703 syslog (LOG_ERR, "Can't push ARP module (2)");
1705 /* Push arp module to ip_fd */
1706 if (ioctl (ip_fd, I_POP, NULL) < 0)
1707 syslog (LOG_ERR, "I_POP failed\n");
1708 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
1709 syslog (LOG_ERR, "Can't push ARP module (3)\n");
1710 /* Open arp_fd */
1711 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
1712 if (arp_fd < 0)
1713 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
1715 /* Set ifname to arp */
1716 strioc_if.ic_cmd = SIOCSLIFNAME;
1717 strioc_if.ic_timout = 0;
1718 strioc_if.ic_len = sizeof(ifr);
1719 strioc_if.ic_dp = (char *)&ifr;
1720 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
1721 syslog (LOG_ERR, "Can't set ifname to arp\n");
1724 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
1725 syslog(LOG_ERR, "Can't link TAP device to IP");
1726 return -1;
1729 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
1730 syslog (LOG_ERR, "Can't link TAP device to ARP");
1732 close (if_fd);
1734 memset(&ifr, 0x0, sizeof(ifr));
1735 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1736 ifr.lifr_ip_muxid = ip_muxid;
1737 ifr.lifr_arp_muxid = arp_muxid;
1739 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
1741 ioctl (ip_fd, I_PUNLINK , arp_muxid);
1742 ioctl (ip_fd, I_PUNLINK, ip_muxid);
1743 syslog (LOG_ERR, "Can't set multiplexor id");
1746 snprintf(dev, dev_size, "tap%d", ppa);
1747 return tap_fd;
1750 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1752 char dev[10]="";
1753 int fd;
1754 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
1755 fprintf(stderr, "Cannot allocate TAP device\n");
1756 return -1;
1758 pstrcpy(ifname, ifname_size, dev);
1759 fcntl(fd, F_SETFL, O_NONBLOCK);
1760 return fd;
1762 #elif defined (_AIX)
1763 static int tap_open(char *ifname, int ifname_size)
1765 fprintf (stderr, "no tap on AIX\n");
1766 return -1;
1768 #else
1769 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1771 struct ifreq ifr;
1772 int fd, ret;
1774 TFR(fd = open("/dev/net/tun", O_RDWR));
1775 if (fd < 0) {
1776 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1777 return -1;
1779 memset(&ifr, 0, sizeof(ifr));
1780 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1782 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
1784 unsigned int features;
1786 if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&
1787 features & IFF_VNET_HDR) {
1788 *vnet_hdr = 1;
1789 ifr.ifr_flags |= IFF_VNET_HDR;
1792 #endif
1794 if (ifname[0] != '\0')
1795 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
1796 else
1797 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
1798 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1799 if (ret != 0) {
1800 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1801 close(fd);
1802 return -1;
1804 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1805 fcntl(fd, F_SETFL, O_NONBLOCK);
1806 return fd;
1808 #endif
1810 static int launch_script(const char *setup_script, const char *ifname, int fd)
1812 sigset_t oldmask, mask;
1813 int pid, status;
1814 char *args[3];
1815 char **parg;
1817 sigemptyset(&mask);
1818 sigaddset(&mask, SIGCHLD);
1819 sigprocmask(SIG_BLOCK, &mask, &oldmask);
1821 /* try to launch network script */
1822 pid = fork();
1823 if (pid == 0) {
1824 int open_max = sysconf(_SC_OPEN_MAX), i;
1826 for (i = 0; i < open_max; i++) {
1827 if (i != STDIN_FILENO &&
1828 i != STDOUT_FILENO &&
1829 i != STDERR_FILENO &&
1830 i != fd) {
1831 close(i);
1834 parg = args;
1835 *parg++ = (char *)setup_script;
1836 *parg++ = (char *)ifname;
1837 *parg++ = NULL;
1838 execv(setup_script, args);
1839 _exit(1);
1840 } else if (pid > 0) {
1841 while (waitpid(pid, &status, 0) != pid) {
1842 /* loop */
1844 sigprocmask(SIG_SETMASK, &oldmask, NULL);
1846 if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
1847 return 0;
1850 fprintf(stderr, "%s: could not launch network script\n", setup_script);
1851 return -1;
1854 static TAPState *net_tap_init(VLANState *vlan, const char *model,
1855 const char *name, const char *ifname1,
1856 const char *setup_script, const char *down_script)
1858 TAPState *s;
1859 int fd;
1860 int vnet_hdr;
1861 char ifname[128];
1863 if (ifname1 != NULL)
1864 pstrcpy(ifname, sizeof(ifname), ifname1);
1865 else
1866 ifname[0] = '\0';
1867 vnet_hdr = 0;
1868 TFR(fd = tap_open(ifname, sizeof(ifname), &vnet_hdr));
1869 if (fd < 0)
1870 return NULL;
1872 if (!setup_script || !strcmp(setup_script, "no"))
1873 setup_script = "";
1874 if (setup_script[0] != '\0' &&
1875 launch_script(setup_script, ifname, fd)) {
1876 return NULL;
1878 s = net_tap_fd_init(vlan, model, name, fd, vnet_hdr);
1879 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1880 "ifname=%s,script=%s,downscript=%s",
1881 ifname, setup_script, down_script);
1882 if (down_script && strcmp(down_script, "no")) {
1883 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1884 snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1886 return s;
1889 #endif /* !_WIN32 */
1891 #if defined(CONFIG_VDE)
1892 typedef struct VDEState {
1893 VLANClientState *vc;
1894 VDECONN *vde;
1895 } VDEState;
1897 static void vde_to_qemu(void *opaque)
1899 VDEState *s = opaque;
1900 uint8_t buf[4096];
1901 int size;
1903 size = vde_recv(s->vde, (char *)buf, sizeof(buf), 0);
1904 if (size > 0) {
1905 qemu_send_packet(s->vc, buf, size);
1909 static ssize_t vde_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1911 VDEState *s = vc->opaque;
1912 ssize_t ret;
1914 do {
1915 ret = vde_send(s->vde, (const char *)buf, size, 0);
1916 } while (ret < 0 && errno == EINTR);
1918 return ret;
1921 static void vde_cleanup(VLANClientState *vc)
1923 VDEState *s = vc->opaque;
1924 qemu_set_fd_handler(vde_datafd(s->vde), NULL, NULL, NULL);
1925 vde_close(s->vde);
1926 qemu_free(s);
1929 static int net_vde_init(VLANState *vlan, const char *model,
1930 const char *name, const char *sock,
1931 int port, const char *group, int mode)
1933 VDEState *s;
1934 char *init_group = (char *)group;
1935 char *init_sock = (char *)sock;
1937 struct vde_open_args args = {
1938 .port = port,
1939 .group = init_group,
1940 .mode = mode,
1943 s = qemu_mallocz(sizeof(VDEState));
1944 s->vde = vde_open(init_sock, (char *)"QEMU", &args);
1945 if (!s->vde){
1946 free(s);
1947 return -1;
1949 s->vc = qemu_new_vlan_client(vlan, model, name, NULL, vde_receive,
1950 NULL, vde_cleanup, s);
1951 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1952 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1953 sock, vde_datafd(s->vde));
1954 return 0;
1956 #endif
1958 /* network connection */
1959 typedef struct NetSocketState {
1960 VLANClientState *vc;
1961 int fd;
1962 int state; /* 0 = getting length, 1 = getting data */
1963 unsigned int index;
1964 unsigned int packet_len;
1965 uint8_t buf[4096];
1966 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1967 } NetSocketState;
1969 typedef struct NetSocketListenState {
1970 VLANState *vlan;
1971 char *model;
1972 char *name;
1973 int fd;
1974 } NetSocketListenState;
1976 /* XXX: we consider we can send the whole packet without blocking */
1977 static ssize_t net_socket_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1979 NetSocketState *s = vc->opaque;
1980 uint32_t len;
1981 len = htonl(size);
1983 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1984 return send_all(s->fd, buf, size);
1987 static ssize_t net_socket_receive_dgram(VLANClientState *vc, const uint8_t *buf, size_t size)
1989 NetSocketState *s = vc->opaque;
1991 return sendto(s->fd, (const void *)buf, size, 0,
1992 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1995 static void net_socket_send(void *opaque)
1997 NetSocketState *s = opaque;
1998 int size, err;
1999 unsigned l;
2000 uint8_t buf1[4096];
2001 const uint8_t *buf;
2003 size = recv(s->fd, (void *)buf1, sizeof(buf1), 0);
2004 if (size < 0) {
2005 err = socket_error();
2006 if (err != EWOULDBLOCK)
2007 goto eoc;
2008 } else if (size == 0) {
2009 /* end of connection */
2010 eoc:
2011 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2012 closesocket(s->fd);
2013 return;
2015 buf = buf1;
2016 while (size > 0) {
2017 /* reassemble a packet from the network */
2018 switch(s->state) {
2019 case 0:
2020 l = 4 - s->index;
2021 if (l > size)
2022 l = size;
2023 memcpy(s->buf + s->index, buf, l);
2024 buf += l;
2025 size -= l;
2026 s->index += l;
2027 if (s->index == 4) {
2028 /* got length */
2029 s->packet_len = ntohl(*(uint32_t *)s->buf);
2030 s->index = 0;
2031 s->state = 1;
2033 break;
2034 case 1:
2035 l = s->packet_len - s->index;
2036 if (l > size)
2037 l = size;
2038 if (s->index + l <= sizeof(s->buf)) {
2039 memcpy(s->buf + s->index, buf, l);
2040 } else {
2041 fprintf(stderr, "serious error: oversized packet received,"
2042 "connection terminated.\n");
2043 s->state = 0;
2044 goto eoc;
2047 s->index += l;
2048 buf += l;
2049 size -= l;
2050 if (s->index >= s->packet_len) {
2051 qemu_send_packet(s->vc, s->buf, s->packet_len);
2052 s->index = 0;
2053 s->state = 0;
2055 break;
2060 static void net_socket_send_dgram(void *opaque)
2062 NetSocketState *s = opaque;
2063 int size;
2065 size = recv(s->fd, (void *)s->buf, sizeof(s->buf), 0);
2066 if (size < 0)
2067 return;
2068 if (size == 0) {
2069 /* end of connection */
2070 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2071 return;
2073 qemu_send_packet(s->vc, s->buf, size);
2076 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2078 struct ip_mreq imr;
2079 int fd;
2080 int val, ret;
2081 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2082 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2083 inet_ntoa(mcastaddr->sin_addr),
2084 (int)ntohl(mcastaddr->sin_addr.s_addr));
2085 return -1;
2088 fd = socket(PF_INET, SOCK_DGRAM, 0);
2089 if (fd < 0) {
2090 perror("socket(PF_INET, SOCK_DGRAM)");
2091 return -1;
2094 val = 1;
2095 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2096 (const char *)&val, sizeof(val));
2097 if (ret < 0) {
2098 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2099 goto fail;
2102 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2103 if (ret < 0) {
2104 perror("bind");
2105 goto fail;
2108 /* Add host to multicast group */
2109 imr.imr_multiaddr = mcastaddr->sin_addr;
2110 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2112 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2113 (const char *)&imr, sizeof(struct ip_mreq));
2114 if (ret < 0) {
2115 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2116 goto fail;
2119 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2120 val = 1;
2121 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2122 (const char *)&val, sizeof(val));
2123 if (ret < 0) {
2124 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2125 goto fail;
2128 socket_set_nonblock(fd);
2129 return fd;
2130 fail:
2131 if (fd >= 0)
2132 closesocket(fd);
2133 return -1;
2136 static void net_socket_cleanup(VLANClientState *vc)
2138 NetSocketState *s = vc->opaque;
2139 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2140 close(s->fd);
2141 qemu_free(s);
2144 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
2145 const char *model,
2146 const char *name,
2147 int fd, int is_connected)
2149 struct sockaddr_in saddr;
2150 int newfd;
2151 socklen_t saddr_len;
2152 NetSocketState *s;
2154 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2155 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2156 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2159 if (is_connected) {
2160 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2161 /* must be bound */
2162 if (saddr.sin_addr.s_addr==0) {
2163 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2164 fd);
2165 return NULL;
2167 /* clone dgram socket */
2168 newfd = net_socket_mcast_create(&saddr);
2169 if (newfd < 0) {
2170 /* error already reported by net_socket_mcast_create() */
2171 close(fd);
2172 return NULL;
2174 /* clone newfd to fd, close newfd */
2175 dup2(newfd, fd);
2176 close(newfd);
2178 } else {
2179 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2180 fd, strerror(errno));
2181 return NULL;
2185 s = qemu_mallocz(sizeof(NetSocketState));
2186 s->fd = fd;
2188 s->vc = qemu_new_vlan_client(vlan, model, name, NULL, net_socket_receive_dgram,
2189 NULL, net_socket_cleanup, s);
2190 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2192 /* mcast: save bound address as dst */
2193 if (is_connected) s->dgram_dst=saddr;
2195 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2196 "socket: fd=%d (%s mcast=%s:%d)",
2197 fd, is_connected? "cloned" : "",
2198 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2199 return s;
2202 static void net_socket_connect(void *opaque)
2204 NetSocketState *s = opaque;
2205 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2208 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
2209 const char *model,
2210 const char *name,
2211 int fd, int is_connected)
2213 NetSocketState *s;
2214 s = qemu_mallocz(sizeof(NetSocketState));
2215 s->fd = fd;
2216 s->vc = qemu_new_vlan_client(vlan, model, name, NULL, net_socket_receive,
2217 NULL, net_socket_cleanup, s);
2218 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2219 "socket: fd=%d", fd);
2220 if (is_connected) {
2221 net_socket_connect(s);
2222 } else {
2223 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2225 return s;
2228 static NetSocketState *net_socket_fd_init(VLANState *vlan,
2229 const char *model, const char *name,
2230 int fd, int is_connected)
2232 int so_type = -1, optlen=sizeof(so_type);
2234 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
2235 (socklen_t *)&optlen)< 0) {
2236 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
2237 return NULL;
2239 switch(so_type) {
2240 case SOCK_DGRAM:
2241 return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
2242 case SOCK_STREAM:
2243 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
2244 default:
2245 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2246 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2247 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
2249 return NULL;
2252 static void net_socket_accept(void *opaque)
2254 NetSocketListenState *s = opaque;
2255 NetSocketState *s1;
2256 struct sockaddr_in saddr;
2257 socklen_t len;
2258 int fd;
2260 for(;;) {
2261 len = sizeof(saddr);
2262 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2263 if (fd < 0 && errno != EINTR) {
2264 return;
2265 } else if (fd >= 0) {
2266 break;
2269 s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
2270 if (!s1) {
2271 closesocket(fd);
2272 } else {
2273 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2274 "socket: connection from %s:%d",
2275 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2279 static int net_socket_listen_init(VLANState *vlan,
2280 const char *model,
2281 const char *name,
2282 const char *host_str)
2284 NetSocketListenState *s;
2285 int fd, val, ret;
2286 struct sockaddr_in saddr;
2288 if (parse_host_port(&saddr, host_str) < 0)
2289 return -1;
2291 s = qemu_mallocz(sizeof(NetSocketListenState));
2293 fd = socket(PF_INET, SOCK_STREAM, 0);
2294 if (fd < 0) {
2295 perror("socket");
2296 return -1;
2298 socket_set_nonblock(fd);
2300 /* allow fast reuse */
2301 val = 1;
2302 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2304 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2305 if (ret < 0) {
2306 perror("bind");
2307 return -1;
2309 ret = listen(fd, 0);
2310 if (ret < 0) {
2311 perror("listen");
2312 return -1;
2314 s->vlan = vlan;
2315 s->model = qemu_strdup(model);
2316 s->name = name ? qemu_strdup(name) : NULL;
2317 s->fd = fd;
2318 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2319 return 0;
2322 static int net_socket_connect_init(VLANState *vlan,
2323 const char *model,
2324 const char *name,
2325 const char *host_str)
2327 NetSocketState *s;
2328 int fd, connected, ret, err;
2329 struct sockaddr_in saddr;
2331 if (parse_host_port(&saddr, host_str) < 0)
2332 return -1;
2334 fd = socket(PF_INET, SOCK_STREAM, 0);
2335 if (fd < 0) {
2336 perror("socket");
2337 return -1;
2339 socket_set_nonblock(fd);
2341 connected = 0;
2342 for(;;) {
2343 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2344 if (ret < 0) {
2345 err = socket_error();
2346 if (err == EINTR || err == EWOULDBLOCK) {
2347 } else if (err == EINPROGRESS) {
2348 break;
2349 #ifdef _WIN32
2350 } else if (err == WSAEALREADY) {
2351 break;
2352 #endif
2353 } else {
2354 perror("connect");
2355 closesocket(fd);
2356 return -1;
2358 } else {
2359 connected = 1;
2360 break;
2363 s = net_socket_fd_init(vlan, model, name, fd, connected);
2364 if (!s)
2365 return -1;
2366 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2367 "socket: connect to %s:%d",
2368 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2369 return 0;
2372 static int net_socket_mcast_init(VLANState *vlan,
2373 const char *model,
2374 const char *name,
2375 const char *host_str)
2377 NetSocketState *s;
2378 int fd;
2379 struct sockaddr_in saddr;
2381 if (parse_host_port(&saddr, host_str) < 0)
2382 return -1;
2385 fd = net_socket_mcast_create(&saddr);
2386 if (fd < 0)
2387 return -1;
2389 s = net_socket_fd_init(vlan, model, name, fd, 0);
2390 if (!s)
2391 return -1;
2393 s->dgram_dst = saddr;
2395 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2396 "socket: mcast=%s:%d",
2397 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2398 return 0;
2402 typedef struct DumpState {
2403 VLANClientState *pcap_vc;
2404 int fd;
2405 int pcap_caplen;
2406 } DumpState;
2408 #define PCAP_MAGIC 0xa1b2c3d4
2410 struct pcap_file_hdr {
2411 uint32_t magic;
2412 uint16_t version_major;
2413 uint16_t version_minor;
2414 int32_t thiszone;
2415 uint32_t sigfigs;
2416 uint32_t snaplen;
2417 uint32_t linktype;
2420 struct pcap_sf_pkthdr {
2421 struct {
2422 int32_t tv_sec;
2423 int32_t tv_usec;
2424 } ts;
2425 uint32_t caplen;
2426 uint32_t len;
2429 static ssize_t dump_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
2431 DumpState *s = vc->opaque;
2432 struct pcap_sf_pkthdr hdr;
2433 int64_t ts;
2434 int caplen;
2436 /* Early return in case of previous error. */
2437 if (s->fd < 0) {
2438 return size;
2441 ts = muldiv64(qemu_get_clock(vm_clock), 1000000, get_ticks_per_sec());
2442 caplen = size > s->pcap_caplen ? s->pcap_caplen : size;
2444 hdr.ts.tv_sec = ts / 1000000;
2445 hdr.ts.tv_usec = ts % 1000000;
2446 hdr.caplen = caplen;
2447 hdr.len = size;
2448 if (write(s->fd, &hdr, sizeof(hdr)) != sizeof(hdr) ||
2449 write(s->fd, buf, caplen) != caplen) {
2450 qemu_log("-net dump write error - stop dump\n");
2451 close(s->fd);
2452 s->fd = -1;
2455 return size;
2458 static void net_dump_cleanup(VLANClientState *vc)
2460 DumpState *s = vc->opaque;
2462 close(s->fd);
2463 qemu_free(s);
2466 static int net_dump_init(VLANState *vlan, const char *device,
2467 const char *name, const char *filename, int len)
2469 struct pcap_file_hdr hdr;
2470 DumpState *s;
2472 s = qemu_malloc(sizeof(DumpState));
2474 s->fd = open(filename, O_CREAT | O_WRONLY | O_BINARY, 0644);
2475 if (s->fd < 0) {
2476 qemu_error("-net dump: can't open %s\n", filename);
2477 return -1;
2480 s->pcap_caplen = len;
2482 hdr.magic = PCAP_MAGIC;
2483 hdr.version_major = 2;
2484 hdr.version_minor = 4;
2485 hdr.thiszone = 0;
2486 hdr.sigfigs = 0;
2487 hdr.snaplen = s->pcap_caplen;
2488 hdr.linktype = 1;
2490 if (write(s->fd, &hdr, sizeof(hdr)) < sizeof(hdr)) {
2491 qemu_error("-net dump write error: %s\n", strerror(errno));
2492 close(s->fd);
2493 qemu_free(s);
2494 return -1;
2497 s->pcap_vc = qemu_new_vlan_client(vlan, device, name, NULL, dump_receive, NULL,
2498 net_dump_cleanup, s);
2499 snprintf(s->pcap_vc->info_str, sizeof(s->pcap_vc->info_str),
2500 "dump to %s (len=%d)", filename, len);
2501 return 0;
2504 /* find or alloc a new VLAN */
2505 VLANState *qemu_find_vlan(int id, int allocate)
2507 VLANState *vlan;
2509 QTAILQ_FOREACH(vlan, &vlans, next) {
2510 if (vlan->id == id) {
2511 return vlan;
2515 if (!allocate) {
2516 return NULL;
2519 vlan = qemu_mallocz(sizeof(VLANState));
2520 vlan->id = id;
2521 QTAILQ_INIT(&vlan->clients);
2522 QTAILQ_INIT(&vlan->send_queue);
2524 QTAILQ_INSERT_TAIL(&vlans, vlan, next);
2526 return vlan;
2529 static int nic_get_free_idx(void)
2531 int index;
2533 for (index = 0; index < MAX_NICS; index++)
2534 if (!nd_table[index].used)
2535 return index;
2536 return -1;
2539 int qemu_show_nic_models(const char *arg, const char *const *models)
2541 int i;
2543 if (!arg || strcmp(arg, "?"))
2544 return 0;
2546 fprintf(stderr, "qemu: Supported NIC models: ");
2547 for (i = 0 ; models[i]; i++)
2548 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
2549 return 1;
2552 void qemu_check_nic_model(NICInfo *nd, const char *model)
2554 const char *models[2];
2556 models[0] = model;
2557 models[1] = NULL;
2559 if (qemu_show_nic_models(nd->model, models))
2560 exit(0);
2561 if (qemu_find_nic_model(nd, models, model) < 0)
2562 exit(1);
2565 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
2566 const char *default_model)
2568 int i;
2570 if (!nd->model)
2571 nd->model = qemu_strdup(default_model);
2573 for (i = 0 ; models[i]; i++) {
2574 if (strcmp(nd->model, models[i]) == 0)
2575 return i;
2578 qemu_error("qemu: Unsupported NIC model: %s\n", nd->model);
2579 return -1;
2582 static int net_handle_fd_param(Monitor *mon, const char *param)
2584 if (!qemu_isdigit(param[0])) {
2585 int fd;
2587 fd = monitor_get_fd(mon, param);
2588 if (fd == -1) {
2589 qemu_error("No file descriptor named %s found", param);
2590 return -1;
2593 return fd;
2594 } else {
2595 return strtol(param, NULL, 0);
2599 static int net_init_nic(QemuOpts *opts, Monitor *mon, const char *name)
2601 int idx;
2602 NICInfo *nd;
2604 idx = nic_get_free_idx();
2605 if (idx == -1 || nb_nics >= MAX_NICS) {
2606 qemu_error("Too Many NICs\n");
2607 return -1;
2610 nd = &nd_table[idx];
2612 memset(nd, 0, sizeof(*nd));
2614 nd->vlan = qemu_find_vlan(qemu_opt_get_number(opts, "vlan", 0), 1);
2616 if (name) {
2617 nd->name = qemu_strdup(name);
2619 if (qemu_opt_get(opts, "model")) {
2620 nd->model = qemu_strdup(qemu_opt_get(opts, "model"));
2622 if (qemu_opt_get(opts, "addr")) {
2623 nd->devaddr = qemu_strdup(qemu_opt_get(opts, "addr"));
2626 nd->macaddr[0] = 0x52;
2627 nd->macaddr[1] = 0x54;
2628 nd->macaddr[2] = 0x00;
2629 nd->macaddr[3] = 0x12;
2630 nd->macaddr[4] = 0x34;
2631 nd->macaddr[5] = 0x56 + idx;
2633 if (qemu_opt_get(opts, "macaddr") &&
2634 parse_macaddr(nd->macaddr, qemu_opt_get(opts, "macaddr")) < 0) {
2635 qemu_error("invalid syntax for ethernet address\n");
2636 return -1;
2639 nd->nvectors = qemu_opt_get_number(opts, "vectors", NIC_NVECTORS_UNSPECIFIED);
2640 if (nd->nvectors != NIC_NVECTORS_UNSPECIFIED &&
2641 (nd->nvectors < 0 || nd->nvectors > 0x7ffffff)) {
2642 qemu_error("invalid # of vectors: %d\n", nd->nvectors);
2643 return -1;
2646 nd->used = 1;
2647 nd->vlan->nb_guest_devs++;
2648 nb_nics++;
2650 return idx;
2653 #if defined(CONFIG_SLIRP)
2654 static int net_init_slirp_configs(const char *name, const char *value, void *opaque)
2656 struct slirp_config_str *config;
2658 if (strcmp(name, "hostfwd") != 0 && strcmp(name, "guestfwd") != 0) {
2659 return 0;
2662 config = qemu_mallocz(sizeof(*config));
2664 pstrcpy(config->str, sizeof(config->str), value);
2666 if (!strcmp(name, "hostfwd")) {
2667 config->flags = SLIRP_CFG_HOSTFWD;
2670 config->next = slirp_configs;
2671 slirp_configs = config;
2673 return 0;
2676 static int net_init_slirp(QemuOpts *opts, Monitor *mon, const char *name)
2678 VLANState *vlan;
2679 struct slirp_config_str *config;
2680 const char *vhost;
2681 const char *vhostname;
2682 const char *vdhcp_start;
2683 const char *vnamesrv;
2684 const char *tftp_export;
2685 const char *bootfile;
2686 const char *smb_export;
2687 const char *vsmbsrv;
2688 char *vnet = NULL;
2689 int restricted = 0;
2690 int ret;
2692 vlan = qemu_find_vlan(qemu_opt_get_number(opts, "vlan", 0), 1);
2694 vhost = qemu_opt_get(opts, "host");
2695 vhostname = qemu_opt_get(opts, "hostname");
2696 vdhcp_start = qemu_opt_get(opts, "dhcpstart");
2697 vnamesrv = qemu_opt_get(opts, "dns");
2698 tftp_export = qemu_opt_get(opts, "tftp");
2699 bootfile = qemu_opt_get(opts, "bootfile");
2700 smb_export = qemu_opt_get(opts, "smb");
2701 vsmbsrv = qemu_opt_get(opts, "smbserver");
2703 if (qemu_opt_get(opts, "ip")) {
2704 const char *ip = qemu_opt_get(opts, "ip");
2705 int l = strlen(ip) + strlen("/24") + 1;
2707 vnet = qemu_malloc(l);
2709 /* emulate legacy ip= parameter */
2710 pstrcpy(vnet, l, ip);
2711 pstrcat(vnet, l, "/24");
2714 if (qemu_opt_get(opts, "net")) {
2715 if (vnet) {
2716 qemu_free(vnet);
2718 vnet = qemu_strdup(qemu_opt_get(opts, "net"));
2721 if (qemu_opt_get(opts, "restrict") &&
2722 qemu_opt_get(opts, "restrict")[0] == 'y') {
2723 restricted = 1;
2726 qemu_opt_foreach(opts, net_init_slirp_configs, NULL, 0);
2728 ret = net_slirp_init(vlan, "user", name, restricted, vnet, vhost,
2729 vhostname, tftp_export, bootfile, vdhcp_start,
2730 vnamesrv, smb_export, vsmbsrv);
2732 while (slirp_configs) {
2733 config = slirp_configs;
2734 slirp_configs = config->next;
2735 qemu_free(config);
2738 if (ret != -1) {
2739 vlan->nb_host_devs++;
2742 qemu_free(vnet);
2744 return ret;
2746 #endif /* CONFIG_SLIRP */
2748 #ifdef _WIN32
2749 static int net_init_tap_win32(QemuOpts *opts, Monitor *mon, const char *name)
2751 VLANState *vlan;
2752 const char *ifname;
2754 vlan = qemu_find_vlan(qemu_opt_get_number(opts, "vlan", 0), 1);
2756 ifname = qemu_opt_get(opts, "ifname");
2758 if (!ifname) {
2759 qemu_error("tap: no interface name\n");
2760 return -1;
2763 if (tap_win32_init(vlan, "tap", name, ifname) == -1) {
2764 return -1;
2767 vlan->nb_host_devs++;
2769 return 0;
2771 #elif !defined(_AIX)
2772 static int net_init_tap(QemuOpts *opts, Monitor *mon, const char *name)
2774 VLANState *vlan;
2775 TAPState *s;
2777 vlan = qemu_find_vlan(qemu_opt_get_number(opts, "vlan", 0), 1);
2779 if (qemu_opt_get(opts, "fd")) {
2780 int fd;
2782 if (qemu_opt_get(opts, "ifname") ||
2783 qemu_opt_get(opts, "script") ||
2784 qemu_opt_get(opts, "downscript")) {
2785 qemu_error("ifname=, script= and downscript= is invalid with fd=\n");
2786 return -1;
2789 fd = net_handle_fd_param(mon, qemu_opt_get(opts, "fd"));
2790 if (fd == -1) {
2791 return -1;
2794 fcntl(fd, F_SETFL, O_NONBLOCK);
2796 s = net_tap_fd_init(vlan, "tap", name, fd, tap_probe_vnet_hdr(fd));
2797 if (!s) {
2798 close(fd);
2800 } else {
2801 const char *ifname, *script, *downscript;
2803 ifname = qemu_opt_get(opts, "ifname");
2804 script = qemu_opt_get(opts, "script");
2805 downscript = qemu_opt_get(opts, "downscript");
2807 if (!script) {
2808 script = DEFAULT_NETWORK_SCRIPT;
2810 if (!downscript) {
2811 downscript = DEFAULT_NETWORK_DOWN_SCRIPT;
2814 s = net_tap_init(vlan, "tap", name, ifname, script, downscript);
2817 if (!s) {
2818 return -1;
2821 if (tap_set_sndbuf(s, opts) < 0) {
2822 return -1;
2825 vlan->nb_host_devs++;
2827 return 0;
2829 #endif
2831 static int net_init_socket(QemuOpts *opts, Monitor *mon, const char *name)
2833 VLANState *vlan;
2835 vlan = qemu_find_vlan(qemu_opt_get_number(opts, "vlan", 0), 1);
2837 if (qemu_opt_get(opts, "fd")) {
2838 int fd;
2840 if (qemu_opt_get(opts, "listen") ||
2841 qemu_opt_get(opts, "connect") ||
2842 qemu_opt_get(opts, "mcast")) {
2843 qemu_error("listen=, connect= and mcast= is invalid with fd=\n");
2844 return -1;
2847 fd = net_handle_fd_param(mon, qemu_opt_get(opts, "fd"));
2848 if (fd == -1) {
2849 return -1;
2852 if (!net_socket_fd_init(vlan, "socket", name, fd, 1)) {
2853 close(fd);
2854 return -1;
2856 } else if (qemu_opt_get(opts, "listen")) {
2857 const char *listen;
2859 if (qemu_opt_get(opts, "fd") ||
2860 qemu_opt_get(opts, "connect") ||
2861 qemu_opt_get(opts, "mcast")) {
2862 qemu_error("fd=, connect= and mcast= is invalid with listen=\n");
2863 return -1;
2866 listen = qemu_opt_get(opts, "listen");
2868 if (net_socket_listen_init(vlan, "socket", name, listen) == -1) {
2869 return -1;
2871 } else if (qemu_opt_get(opts, "connect")) {
2872 const char *connect;
2874 if (qemu_opt_get(opts, "fd") ||
2875 qemu_opt_get(opts, "listen") ||
2876 qemu_opt_get(opts, "mcast")) {
2877 qemu_error("fd=, listen= and mcast= is invalid with connect=\n");
2878 return -1;
2881 connect = qemu_opt_get(opts, "connect");
2883 if (net_socket_connect_init(vlan, "socket", name, connect) == -1) {
2884 return -1;
2886 } else if (qemu_opt_get(opts, "mcast")) {
2887 const char *mcast;
2889 if (qemu_opt_get(opts, "fd") ||
2890 qemu_opt_get(opts, "connect") ||
2891 qemu_opt_get(opts, "listen")) {
2892 qemu_error("fd=, connect= and listen= is invalid with mcast=\n");
2893 return -1;
2896 mcast = qemu_opt_get(opts, "mcast");
2898 if (net_socket_mcast_init(vlan, "socket", name, mcast) == -1) {
2899 return -1;
2901 } else {
2902 qemu_error("-socket requires fd=, listen=, connect= or mcast=\n");
2903 return -1;
2906 vlan->nb_host_devs++;
2908 return 0;
2911 #ifdef CONFIG_VDE
2912 static int net_init_vde(QemuOpts *opts, Monitor *mon, const char *name)
2914 VLANState *vlan;
2915 const char *sock;
2916 const char *group;
2917 int port, mode;
2919 vlan = qemu_find_vlan(qemu_opt_get_number(opts, "vlan", 0), 1);
2921 sock = qemu_opt_get(opts, "sock");
2922 group = qemu_opt_get(opts, "group");
2924 port = qemu_opt_get_number(opts, "port", 0);
2925 mode = qemu_opt_get_number(opts, "mode", 0700);
2927 if (net_vde_init(vlan, "vde", name, sock, port, group, mode) == -1) {
2928 return -1;
2931 vlan->nb_host_devs++;
2933 return 0;
2935 #endif
2937 static int net_init_dump(QemuOpts *opts, Monitor *mon, const char *name)
2939 VLANState *vlan;
2940 int len;
2941 const char *file;
2942 char def_file[128];
2944 vlan = qemu_find_vlan(qemu_opt_get_number(opts, "vlan", 0), 1);
2946 file = qemu_opt_get(opts, "file");
2947 if (!file) {
2948 snprintf(def_file, sizeof(def_file), "qemu-vlan%d.pcap", vlan->id);
2949 file = def_file;
2952 len = qemu_opt_get_size(opts, "len", 65536);
2954 return net_dump_init(vlan, "dump", name, file, len);
2957 #define NET_COMMON_PARAMS_DESC \
2959 .name = "type", \
2960 .type = QEMU_OPT_STRING, \
2961 .help = "net client type (nic, tap etc.)", \
2962 }, { \
2963 .name = "vlan", \
2964 .type = QEMU_OPT_NUMBER, \
2965 .help = "vlan number", \
2966 }, { \
2967 .name = "name", \
2968 .type = QEMU_OPT_STRING, \
2969 .help = "identifier for monitor commands", \
2972 typedef int (*net_client_init_func)(QemuOpts *opts,
2973 Monitor *mon,
2974 const char *name);
2976 /* magic number, but compiler will warn if too small */
2977 #define NET_MAX_DESC 20
2979 static struct {
2980 const char *type;
2981 net_client_init_func init;
2982 QemuOptDesc desc[NET_MAX_DESC];
2983 } net_client_types[] = {
2985 .type = "none",
2986 .desc = {
2987 NET_COMMON_PARAMS_DESC,
2988 { /* end of list */ }
2990 }, {
2991 .type = "nic",
2992 .init = net_init_nic,
2993 .desc = {
2994 NET_COMMON_PARAMS_DESC,
2996 .name = "macaddr",
2997 .type = QEMU_OPT_STRING,
2998 .help = "MAC address",
2999 }, {
3000 .name = "model",
3001 .type = QEMU_OPT_STRING,
3002 .help = "device model (e1000, rtl8139, virtio etc.)",
3003 }, {
3004 .name = "addr",
3005 .type = QEMU_OPT_STRING,
3006 .help = "PCI device address",
3007 }, {
3008 .name = "vectors",
3009 .type = QEMU_OPT_NUMBER,
3010 .help = "number of MSI-x vectors, 0 to disable MSI-X",
3012 { /* end of list */ }
3014 #ifdef CONFIG_SLIRP
3015 }, {
3016 .type = "user",
3017 .init = net_init_slirp,
3018 .desc = {
3019 NET_COMMON_PARAMS_DESC,
3021 .name = "hostname",
3022 .type = QEMU_OPT_STRING,
3023 .help = "client hostname reported by the builtin DHCP server",
3024 }, {
3025 .name = "restrict",
3026 .type = QEMU_OPT_STRING,
3027 .help = "isolate the guest from the host (y|yes|n|no)",
3028 }, {
3029 .name = "ip",
3030 .type = QEMU_OPT_STRING,
3031 .help = "legacy parameter, use net= instead",
3032 }, {
3033 .name = "net",
3034 .type = QEMU_OPT_STRING,
3035 .help = "IP address and optional netmask",
3036 }, {
3037 .name = "host",
3038 .type = QEMU_OPT_STRING,
3039 .help = "guest-visible address of the host",
3040 }, {
3041 .name = "tftp",
3042 .type = QEMU_OPT_STRING,
3043 .help = "root directory of the built-in TFTP server",
3044 }, {
3045 .name = "bootfile",
3046 .type = QEMU_OPT_STRING,
3047 .help = "BOOTP filename, for use with tftp=",
3048 }, {
3049 .name = "dhcpstart",
3050 .type = QEMU_OPT_STRING,
3051 .help = "the first of the 16 IPs the built-in DHCP server can assign",
3052 }, {
3053 .name = "dns",
3054 .type = QEMU_OPT_STRING,
3055 .help = "guest-visible address of the virtual nameserver",
3056 }, {
3057 .name = "smb",
3058 .type = QEMU_OPT_STRING,
3059 .help = "root directory of the built-in SMB server",
3060 }, {
3061 .name = "smbserver",
3062 .type = QEMU_OPT_STRING,
3063 .help = "IP address of the built-in SMB server",
3064 }, {
3065 .name = "hostfwd",
3066 .type = QEMU_OPT_STRING,
3067 .help = "guest port number to forward incoming TCP or UDP connections",
3068 }, {
3069 .name = "guestfwd",
3070 .type = QEMU_OPT_STRING,
3071 .help = "IP address and port to forward guest TCP connections",
3073 { /* end of list */ }
3075 #endif
3076 #ifdef _WIN32
3077 }, {
3078 .type = "tap",
3079 .init = net_init_tap_win32,
3080 .desc = {
3081 NET_COMMON_PARAMS_DESC,
3083 .name = "ifname",
3084 .type = QEMU_OPT_STRING,
3085 .help = "interface name",
3087 { /* end of list */ }
3089 #elif !defined(_AIX)
3090 }, {
3091 .type = "tap",
3092 .init = net_init_tap,
3093 .desc = {
3094 NET_COMMON_PARAMS_DESC,
3096 .name = "fd",
3097 .type = QEMU_OPT_STRING,
3098 .help = "file descriptor of an already opened tap",
3099 }, {
3100 .name = "ifname",
3101 .type = QEMU_OPT_STRING,
3102 .help = "interface name",
3103 }, {
3104 .name = "script",
3105 .type = QEMU_OPT_STRING,
3106 .help = "script to initialize the interface",
3107 }, {
3108 .name = "downscript",
3109 .type = QEMU_OPT_STRING,
3110 .help = "script to shut down the interface",
3111 #ifdef TUNSETSNDBUF
3112 }, {
3113 .name = "sndbuf",
3114 .type = QEMU_OPT_SIZE,
3115 .help = "send buffer limit"
3116 #endif
3118 { /* end of list */ }
3120 #endif
3121 }, {
3122 .type = "socket",
3123 .init = net_init_socket,
3124 .desc = {
3125 NET_COMMON_PARAMS_DESC,
3127 .name = "fd",
3128 .type = QEMU_OPT_STRING,
3129 .help = "file descriptor of an already opened socket",
3130 }, {
3131 .name = "listen",
3132 .type = QEMU_OPT_STRING,
3133 .help = "port number, and optional hostname, to listen on",
3134 }, {
3135 .name = "connect",
3136 .type = QEMU_OPT_STRING,
3137 .help = "port number, and optional hostname, to connect to",
3138 }, {
3139 .name = "mcast",
3140 .type = QEMU_OPT_STRING,
3141 .help = "UDP multicast address and port number",
3143 { /* end of list */ }
3145 #ifdef CONFIG_VDE
3146 }, {
3147 .type = "vde",
3148 .init = net_init_vde,
3149 .desc = {
3150 NET_COMMON_PARAMS_DESC,
3152 .name = "sock",
3153 .type = QEMU_OPT_STRING,
3154 .help = "socket path",
3155 }, {
3156 .name = "port",
3157 .type = QEMU_OPT_NUMBER,
3158 .help = "port number",
3159 }, {
3160 .name = "group",
3161 .type = QEMU_OPT_STRING,
3162 .help = "group owner of socket",
3163 }, {
3164 .name = "mode",
3165 .type = QEMU_OPT_NUMBER,
3166 .help = "permissions for socket",
3168 { /* end of list */ }
3170 #endif
3171 }, {
3172 .type = "dump",
3173 .init = net_init_dump,
3174 .desc = {
3175 NET_COMMON_PARAMS_DESC,
3177 .name = "len",
3178 .type = QEMU_OPT_SIZE,
3179 .help = "per-packet size limit (64k default)",
3180 }, {
3181 .name = "file",
3182 .type = QEMU_OPT_STRING,
3183 .help = "dump file path (default is qemu-vlan0.pcap)",
3185 { /* end of list */ }
3188 { /* end of list */ }
3191 int net_client_init(Monitor *mon, QemuOpts *opts)
3193 const char *name;
3194 const char *type;
3195 int i;
3197 type = qemu_opt_get(opts, "type");
3198 if (!type) {
3199 qemu_error("No type specified for -net\n");
3200 return -1;
3203 name = qemu_opts_id(opts);
3204 if (!name) {
3205 name = qemu_opt_get(opts, "name");
3208 for (i = 0; net_client_types[i].type != NULL; i++) {
3209 if (!strcmp(net_client_types[i].type, type)) {
3210 if (qemu_opts_validate(opts, &net_client_types[i].desc[0]) == -1) {
3211 return -1;
3214 if (net_client_types[i].init) {
3215 return net_client_types[i].init(opts, mon, name);
3216 } else {
3217 return 0;
3222 qemu_error("Invalid -net type '%s'\n", type);
3223 return -1;
3226 void net_client_uninit(NICInfo *nd)
3228 nd->vlan->nb_guest_devs--;
3229 nb_nics--;
3231 qemu_free(nd->model);
3232 qemu_free(nd->name);
3233 qemu_free(nd->devaddr);
3235 nd->used = 0;
3238 static int net_host_check_device(const char *device)
3240 int i;
3241 const char *valid_param_list[] = { "tap", "socket", "dump"
3242 #ifdef CONFIG_SLIRP
3243 ,"user"
3244 #endif
3245 #ifdef CONFIG_VDE
3246 ,"vde"
3247 #endif
3249 for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
3250 if (!strncmp(valid_param_list[i], device,
3251 strlen(valid_param_list[i])))
3252 return 1;
3255 return 0;
3258 void net_host_device_add(Monitor *mon, const QDict *qdict)
3260 const char *device = qdict_get_str(qdict, "device");
3261 const char *opts_str = qdict_get_try_str(qdict, "opts");
3262 QemuOpts *opts;
3264 if (!net_host_check_device(device)) {
3265 monitor_printf(mon, "invalid host network device %s\n", device);
3266 return;
3269 opts = qemu_opts_parse(&qemu_net_opts, opts_str ? opts_str : "", NULL);
3270 if (!opts) {
3271 monitor_printf(mon, "parsing network options '%s' failed\n",
3272 opts_str ? opts_str : "");
3273 return;
3276 qemu_opt_set(opts, "type", device);
3278 if (net_client_init(mon, opts) < 0) {
3279 monitor_printf(mon, "adding host network device %s failed\n", device);
3283 void net_host_device_remove(Monitor *mon, const QDict *qdict)
3285 VLANClientState *vc;
3286 int vlan_id = qdict_get_int(qdict, "vlan_id");
3287 const char *device = qdict_get_str(qdict, "device");
3289 vc = qemu_find_vlan_client_by_name(mon, vlan_id, device);
3290 if (!vc) {
3291 return;
3293 if (!net_host_check_device(vc->model)) {
3294 monitor_printf(mon, "invalid host network device %s\n", device);
3295 return;
3297 qemu_del_vlan_client(vc);
3300 void net_set_boot_mask(int net_boot_mask)
3302 int i;
3304 /* Only the first four NICs may be bootable */
3305 net_boot_mask = net_boot_mask & 0xF;
3307 for (i = 0; i < nb_nics; i++) {
3308 if (net_boot_mask & (1 << i)) {
3309 nd_table[i].bootable = 1;
3310 net_boot_mask &= ~(1 << i);
3314 if (net_boot_mask) {
3315 fprintf(stderr, "Cannot boot from non-existent NIC\n");
3316 exit(1);
3320 void do_info_network(Monitor *mon)
3322 VLANState *vlan;
3324 QTAILQ_FOREACH(vlan, &vlans, next) {
3325 VLANClientState *vc;
3327 monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
3329 QTAILQ_FOREACH(vc, &vlan->clients, next) {
3330 monitor_printf(mon, " %s: %s\n", vc->name, vc->info_str);
3335 void do_set_link(Monitor *mon, const QDict *qdict)
3337 VLANState *vlan;
3338 VLANClientState *vc = NULL;
3339 const char *name = qdict_get_str(qdict, "name");
3340 const char *up_or_down = qdict_get_str(qdict, "up_or_down");
3342 QTAILQ_FOREACH(vlan, &vlans, next) {
3343 QTAILQ_FOREACH(vc, &vlan->clients, next) {
3344 if (strcmp(vc->name, name) == 0) {
3345 goto done;
3349 done:
3351 if (!vc) {
3352 monitor_printf(mon, "could not find network device '%s'\n", name);
3353 return;
3356 if (strcmp(up_or_down, "up") == 0)
3357 vc->link_down = 0;
3358 else if (strcmp(up_or_down, "down") == 0)
3359 vc->link_down = 1;
3360 else
3361 monitor_printf(mon, "invalid link status '%s'; only 'up' or 'down' "
3362 "valid\n", up_or_down);
3364 if (vc->link_status_changed)
3365 vc->link_status_changed(vc);
3368 void net_cleanup(void)
3370 VLANState *vlan;
3372 QTAILQ_FOREACH(vlan, &vlans, next) {
3373 VLANClientState *vc, *next_vc;
3375 QTAILQ_FOREACH_SAFE(vc, &vlan->clients, next, next_vc) {
3376 qemu_del_vlan_client(vc);
3381 static void net_check_clients(void)
3383 VLANState *vlan;
3385 QTAILQ_FOREACH(vlan, &vlans, next) {
3386 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
3387 continue;
3388 if (vlan->nb_guest_devs == 0)
3389 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
3390 if (vlan->nb_host_devs == 0)
3391 fprintf(stderr,
3392 "Warning: vlan %d is not connected to host network\n",
3393 vlan->id);
3397 static int net_init_client(QemuOpts *opts, void *dummy)
3399 return net_client_init(NULL, opts);
3402 int net_init_clients(void)
3404 if (QTAILQ_EMPTY(&qemu_net_opts.head)) {
3405 /* if no clients, we use a default config */
3406 qemu_opts_set(&qemu_net_opts, NULL, "type", "nic");
3407 #ifdef CONFIG_SLIRP
3408 qemu_opts_set(&qemu_net_opts, NULL, "type", "user");
3409 #endif
3412 QTAILQ_INIT(&vlans);
3414 if (qemu_opts_foreach(&qemu_net_opts, net_init_client, NULL, 1) == -1) {
3415 return -1;
3418 net_check_clients();
3420 return 0;
3423 int net_client_parse(const char *optarg)
3425 #if defined(CONFIG_SLIRP)
3426 /* handle legacy -net channel,port:chr */
3427 if (!strncmp(optarg, "channel,", strlen("channel,"))) {
3428 int ret;
3430 optarg += strlen("channel,");
3432 if (QTAILQ_EMPTY(&slirp_stacks)) {
3433 struct slirp_config_str *config;
3435 config = qemu_malloc(sizeof(*config));
3436 pstrcpy(config->str, sizeof(config->str), optarg);
3437 config->flags = SLIRP_CFG_LEGACY;
3438 config->next = slirp_configs;
3439 slirp_configs = config;
3440 ret = 0;
3441 } else {
3442 ret = slirp_guestfwd(QTAILQ_FIRST(&slirp_stacks), optarg, 1);
3445 return ret;
3447 #endif
3448 if (!qemu_opts_parse(&qemu_net_opts, optarg, "type")) {
3449 return -1;
3452 return 0;