Merge commit 'mst/for_anthony' into mst
[qemu/aliguori-queue.git] / net.c
blob7c44c1ad5f618df683438aca70b32df8d04e4185
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 #include <arpa/inet.h>
46 #include <dirent.h>
47 #include <netdb.h>
48 #include <sys/select.h>
49 #ifdef CONFIG_BSD
50 #include <sys/stat.h>
51 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
52 #include <libutil.h>
53 #else
54 #include <util.h>
55 #endif
56 #ifdef __linux__
57 #include <pty.h>
58 #include <malloc.h>
59 #include <linux/rtc.h>
61 /* For the benefit of older linux systems which don't supply it,
62 we use a local copy of hpet.h. */
63 /* #include <linux/hpet.h> */
64 #include "hpet.h"
66 #include <linux/ppdev.h>
67 #include <linux/parport.h>
68 #endif
69 #ifdef __sun__
70 #include <sys/stat.h>
71 #include <sys/ethernet.h>
72 #include <sys/sockio.h>
73 #include <netinet/arp.h>
74 #include <netinet/in.h>
75 #include <netinet/in_systm.h>
76 #include <netinet/ip.h>
77 #include <netinet/ip_icmp.h> // must come after ip.h
78 #include <netinet/udp.h>
79 #include <netinet/tcp.h>
80 #include <net/if.h>
81 #include <syslog.h>
82 #include <stropts.h>
83 #endif
84 #endif
85 #endif
87 #if defined(__OpenBSD__)
88 #include <util.h>
89 #endif
91 #if defined(CONFIG_VDE)
92 #include <libvdeplug.h>
93 #endif
95 #include "qemu-common.h"
96 #include "net.h"
97 #include "net/tap.h"
98 #include "monitor.h"
99 #include "sysemu.h"
100 #include "qemu-timer.h"
101 #include "qemu-char.h"
102 #include "audio/audio.h"
103 #include "qemu_socket.h"
104 #include "qemu-log.h"
105 #include "qemu-config.h"
107 #include "slirp/libslirp.h"
109 static QTAILQ_HEAD(, VLANState) vlans;
110 static QTAILQ_HEAD(, VLANClientState) non_vlan_clients;
112 /***********************************************************/
113 /* network device redirectors */
115 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
116 static void hex_dump(FILE *f, const uint8_t *buf, int size)
118 int len, i, j, c;
120 for(i=0;i<size;i+=16) {
121 len = size - i;
122 if (len > 16)
123 len = 16;
124 fprintf(f, "%08x ", i);
125 for(j=0;j<16;j++) {
126 if (j < len)
127 fprintf(f, " %02x", buf[i+j]);
128 else
129 fprintf(f, " ");
131 fprintf(f, " ");
132 for(j=0;j<len;j++) {
133 c = buf[i+j];
134 if (c < ' ' || c > '~')
135 c = '.';
136 fprintf(f, "%c", c);
138 fprintf(f, "\n");
141 #endif
143 static int parse_macaddr(uint8_t *macaddr, const char *p)
145 int i;
146 char *last_char;
147 long int offset;
149 errno = 0;
150 offset = strtol(p, &last_char, 0);
151 if (0 == errno && '\0' == *last_char &&
152 offset >= 0 && offset <= 0xFFFFFF) {
153 macaddr[3] = (offset & 0xFF0000) >> 16;
154 macaddr[4] = (offset & 0xFF00) >> 8;
155 macaddr[5] = offset & 0xFF;
156 return 0;
157 } else {
158 for(i = 0; i < 6; i++) {
159 macaddr[i] = strtol(p, (char **)&p, 16);
160 if (i == 5) {
161 if (*p != '\0')
162 return -1;
163 } else {
164 if (*p != ':' && *p != '-')
165 return -1;
166 p++;
169 return 0;
172 return -1;
175 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
177 const char *p, *p1;
178 int len;
179 p = *pp;
180 p1 = strchr(p, sep);
181 if (!p1)
182 return -1;
183 len = p1 - p;
184 p1++;
185 if (buf_size > 0) {
186 if (len > buf_size - 1)
187 len = buf_size - 1;
188 memcpy(buf, p, len);
189 buf[len] = '\0';
191 *pp = p1;
192 return 0;
195 int parse_host_src_port(struct sockaddr_in *haddr,
196 struct sockaddr_in *saddr,
197 const char *input_str)
199 char *str = strdup(input_str);
200 char *host_str = str;
201 char *src_str;
202 const char *src_str2;
203 char *ptr;
206 * Chop off any extra arguments at the end of the string which
207 * would start with a comma, then fill in the src port information
208 * if it was provided else use the "any address" and "any port".
210 if ((ptr = strchr(str,',')))
211 *ptr = '\0';
213 if ((src_str = strchr(input_str,'@'))) {
214 *src_str = '\0';
215 src_str++;
218 if (parse_host_port(haddr, host_str) < 0)
219 goto fail;
221 src_str2 = src_str;
222 if (!src_str || *src_str == '\0')
223 src_str2 = ":0";
225 if (parse_host_port(saddr, src_str2) < 0)
226 goto fail;
228 free(str);
229 return(0);
231 fail:
232 free(str);
233 return -1;
236 int parse_host_port(struct sockaddr_in *saddr, const char *str)
238 char buf[512];
239 struct hostent *he;
240 const char *p, *r;
241 int port;
243 p = str;
244 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
245 return -1;
246 saddr->sin_family = AF_INET;
247 if (buf[0] == '\0') {
248 saddr->sin_addr.s_addr = 0;
249 } else {
250 if (qemu_isdigit(buf[0])) {
251 if (!inet_aton(buf, &saddr->sin_addr))
252 return -1;
253 } else {
254 if ((he = gethostbyname(buf)) == NULL)
255 return - 1;
256 saddr->sin_addr = *(struct in_addr *)he->h_addr;
259 port = strtol(p, (char **)&r, 0);
260 if (r == p)
261 return -1;
262 saddr->sin_port = htons(port);
263 return 0;
266 void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6])
268 snprintf(vc->info_str, sizeof(vc->info_str),
269 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
270 vc->model,
271 macaddr[0], macaddr[1], macaddr[2],
272 macaddr[3], macaddr[4], macaddr[5]);
275 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
277 static int index = 0;
278 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
280 if (memcmp(macaddr, &zero, sizeof(zero)) != 0)
281 return;
282 macaddr->a[0] = 0x52;
283 macaddr->a[1] = 0x54;
284 macaddr->a[2] = 0x00;
285 macaddr->a[3] = 0x12;
286 macaddr->a[4] = 0x34;
287 macaddr->a[5] = 0x56 + index++;
290 static char *assign_name(VLANClientState *vc1, const char *model)
292 VLANState *vlan;
293 char buf[256];
294 int id = 0;
296 QTAILQ_FOREACH(vlan, &vlans, next) {
297 VLANClientState *vc;
299 QTAILQ_FOREACH(vc, &vlan->clients, next) {
300 if (vc != vc1 && strcmp(vc->model, model) == 0) {
301 id++;
306 snprintf(buf, sizeof(buf), "%s.%d", model, id);
308 return qemu_strdup(buf);
311 static ssize_t qemu_deliver_packet(VLANClientState *sender,
312 unsigned flags,
313 const uint8_t *data,
314 size_t size,
315 void *opaque);
316 static ssize_t qemu_deliver_packet_iov(VLANClientState *sender,
317 unsigned flags,
318 const struct iovec *iov,
319 int iovcnt,
320 void *opaque);
322 VLANClientState *qemu_new_vlan_client(net_client_type type,
323 VLANState *vlan,
324 VLANClientState *peer,
325 const char *model,
326 const char *name,
327 NetCanReceive *can_receive,
328 NetReceive *receive,
329 NetReceive *receive_raw,
330 NetReceiveIOV *receive_iov,
331 NetCleanup *cleanup,
332 void *opaque)
334 VLANClientState *vc;
336 vc = qemu_mallocz(sizeof(VLANClientState));
338 vc->type = type;
339 vc->model = qemu_strdup(model);
340 if (name)
341 vc->name = qemu_strdup(name);
342 else
343 vc->name = assign_name(vc, model);
344 vc->can_receive = can_receive;
345 vc->receive = receive;
346 vc->receive_raw = receive_raw;
347 vc->receive_iov = receive_iov;
348 vc->cleanup = cleanup;
349 vc->opaque = opaque;
351 if (vlan) {
352 assert(!peer);
353 vc->vlan = vlan;
354 QTAILQ_INSERT_TAIL(&vc->vlan->clients, vc, next);
355 } else {
356 if (peer) {
357 vc->peer = peer;
358 peer->peer = vc;
360 QTAILQ_INSERT_TAIL(&non_vlan_clients, vc, next);
362 vc->send_queue = qemu_new_net_queue(qemu_deliver_packet,
363 qemu_deliver_packet_iov,
364 vc);
367 return vc;
370 void qemu_del_vlan_client(VLANClientState *vc)
372 if (vc->vlan) {
373 QTAILQ_REMOVE(&vc->vlan->clients, vc, next);
374 } else {
375 if (vc->send_queue) {
376 qemu_del_net_queue(vc->send_queue);
378 QTAILQ_REMOVE(&non_vlan_clients, vc, next);
379 if (vc->peer) {
380 vc->peer->peer = NULL;
384 if (vc->cleanup) {
385 vc->cleanup(vc);
388 qemu_free(vc->name);
389 qemu_free(vc->model);
390 qemu_free(vc);
393 VLANClientState *qemu_find_vlan_client(VLANState *vlan, void *opaque)
395 VLANClientState *vc;
397 QTAILQ_FOREACH(vc, &vlan->clients, next) {
398 if (vc->opaque == opaque) {
399 return vc;
403 return NULL;
406 static VLANClientState *
407 qemu_find_vlan_client_by_name(Monitor *mon, int vlan_id,
408 const char *client_str)
410 VLANState *vlan;
411 VLANClientState *vc;
413 vlan = qemu_find_vlan(vlan_id, 0);
414 if (!vlan) {
415 monitor_printf(mon, "unknown VLAN %d\n", vlan_id);
416 return NULL;
419 QTAILQ_FOREACH(vc, &vlan->clients, next) {
420 if (!strcmp(vc->name, client_str)) {
421 break;
424 if (!vc) {
425 monitor_printf(mon, "can't find device %s on VLAN %d\n",
426 client_str, vlan_id);
429 return vc;
432 int qemu_can_send_packet(VLANClientState *sender)
434 VLANState *vlan = sender->vlan;
435 VLANClientState *vc;
437 if (sender->peer) {
438 if (sender->peer->receive_disabled) {
439 return 0;
440 } else if (sender->peer->can_receive &&
441 !sender->peer->can_receive(sender->peer)) {
442 return 0;
443 } else {
444 return 1;
448 if (!sender->vlan) {
449 return 1;
452 QTAILQ_FOREACH(vc, &vlan->clients, next) {
453 if (vc == sender) {
454 continue;
457 /* no can_receive() handler, they can always receive */
458 if (!vc->can_receive || vc->can_receive(vc)) {
459 return 1;
462 return 0;
465 static ssize_t qemu_deliver_packet(VLANClientState *sender,
466 unsigned flags,
467 const uint8_t *data,
468 size_t size,
469 void *opaque)
471 VLANClientState *vc = opaque;
472 ssize_t ret;
474 if (vc->link_down) {
475 return size;
478 if (vc->receive_disabled) {
479 return 0;
482 if (flags & QEMU_NET_PACKET_FLAG_RAW && vc->receive_raw) {
483 ret = vc->receive_raw(vc, data, size);
484 } else {
485 ret = vc->receive(vc, data, size);
488 if (ret == 0) {
489 vc->receive_disabled = 1;
492 return ret;
495 static ssize_t qemu_vlan_deliver_packet(VLANClientState *sender,
496 unsigned flags,
497 const uint8_t *buf,
498 size_t size,
499 void *opaque)
501 VLANState *vlan = opaque;
502 VLANClientState *vc;
503 ssize_t ret = -1;
505 QTAILQ_FOREACH(vc, &vlan->clients, next) {
506 ssize_t len;
508 if (vc == sender) {
509 continue;
512 if (vc->link_down) {
513 ret = size;
514 continue;
517 if (vc->receive_disabled) {
518 ret = 0;
519 continue;
522 if (flags & QEMU_NET_PACKET_FLAG_RAW && vc->receive_raw) {
523 len = vc->receive_raw(vc, buf, size);
524 } else {
525 len = vc->receive(vc, buf, size);
528 if (len == 0) {
529 vc->receive_disabled = 1;
532 ret = (ret >= 0) ? ret : len;
536 return ret;
539 void qemu_purge_queued_packets(VLANClientState *vc)
541 NetQueue *queue;
543 if (!vc->peer && !vc->vlan) {
544 return;
547 if (vc->peer) {
548 queue = vc->peer->send_queue;
549 } else {
550 queue = vc->vlan->send_queue;
553 qemu_net_queue_purge(queue, vc);
556 void qemu_flush_queued_packets(VLANClientState *vc)
558 NetQueue *queue;
560 vc->receive_disabled = 0;
562 if (vc->vlan) {
563 queue = vc->vlan->send_queue;
564 } else {
565 queue = vc->send_queue;
568 qemu_net_queue_flush(queue);
571 static ssize_t qemu_send_packet_async_with_flags(VLANClientState *sender,
572 unsigned flags,
573 const uint8_t *buf, int size,
574 NetPacketSent *sent_cb)
576 NetQueue *queue;
578 #ifdef DEBUG_NET
579 printf("qemu_send_packet_async:\n");
580 hex_dump(stdout, buf, size);
581 #endif
583 if (sender->link_down || (!sender->peer && !sender->vlan)) {
584 return size;
587 if (sender->peer) {
588 queue = sender->peer->send_queue;
589 } else {
590 queue = sender->vlan->send_queue;
593 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
596 ssize_t qemu_send_packet_async(VLANClientState *sender,
597 const uint8_t *buf, int size,
598 NetPacketSent *sent_cb)
600 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
601 buf, size, sent_cb);
604 void qemu_send_packet(VLANClientState *vc, const uint8_t *buf, int size)
606 qemu_send_packet_async(vc, buf, size, NULL);
609 ssize_t qemu_send_packet_raw(VLANClientState *vc, const uint8_t *buf, int size)
611 return qemu_send_packet_async_with_flags(vc, QEMU_NET_PACKET_FLAG_RAW,
612 buf, size, NULL);
615 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
616 int iovcnt)
618 uint8_t buffer[4096];
619 size_t offset = 0;
620 int i;
622 for (i = 0; i < iovcnt; i++) {
623 size_t len;
625 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
626 memcpy(buffer + offset, iov[i].iov_base, len);
627 offset += len;
630 return vc->receive(vc, buffer, offset);
633 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
635 size_t offset = 0;
636 int i;
638 for (i = 0; i < iovcnt; i++)
639 offset += iov[i].iov_len;
640 return offset;
643 static ssize_t qemu_deliver_packet_iov(VLANClientState *sender,
644 unsigned flags,
645 const struct iovec *iov,
646 int iovcnt,
647 void *opaque)
649 VLANClientState *vc = opaque;
651 if (vc->link_down) {
652 return calc_iov_length(iov, iovcnt);
655 if (vc->receive_iov) {
656 return vc->receive_iov(vc, iov, iovcnt);
657 } else {
658 return vc_sendv_compat(vc, iov, iovcnt);
662 static ssize_t qemu_vlan_deliver_packet_iov(VLANClientState *sender,
663 unsigned flags,
664 const struct iovec *iov,
665 int iovcnt,
666 void *opaque)
668 VLANState *vlan = opaque;
669 VLANClientState *vc;
670 ssize_t ret = -1;
672 QTAILQ_FOREACH(vc, &vlan->clients, next) {
673 ssize_t len;
675 if (vc == sender) {
676 continue;
679 if (vc->link_down) {
680 ret = calc_iov_length(iov, iovcnt);
681 continue;
684 assert(!(flags & QEMU_NET_PACKET_FLAG_RAW));
686 if (vc->receive_iov) {
687 len = vc->receive_iov(vc, iov, iovcnt);
688 } else {
689 len = vc_sendv_compat(vc, iov, iovcnt);
692 ret = (ret >= 0) ? ret : len;
695 return ret;
698 ssize_t qemu_sendv_packet_async(VLANClientState *sender,
699 const struct iovec *iov, int iovcnt,
700 NetPacketSent *sent_cb)
702 NetQueue *queue;
704 if (sender->link_down || (!sender->peer && !sender->vlan)) {
705 return calc_iov_length(iov, iovcnt);
708 if (sender->peer) {
709 queue = sender->peer->send_queue;
710 } else {
711 queue = sender->vlan->send_queue;
714 return qemu_net_queue_send_iov(queue, sender,
715 QEMU_NET_PACKET_FLAG_NONE,
716 iov, iovcnt, sent_cb);
719 ssize_t
720 qemu_sendv_packet(VLANClientState *vc, const struct iovec *iov, int iovcnt)
722 return qemu_sendv_packet_async(vc, iov, iovcnt, NULL);
725 #if defined(CONFIG_SLIRP)
727 /* slirp network adapter */
729 #define SLIRP_CFG_HOSTFWD 1
730 #define SLIRP_CFG_LEGACY 2
732 struct slirp_config_str {
733 struct slirp_config_str *next;
734 int flags;
735 char str[1024];
736 int legacy_format;
739 typedef struct SlirpState {
740 QTAILQ_ENTRY(SlirpState) entry;
741 VLANClientState *vc;
742 Slirp *slirp;
743 #ifndef _WIN32
744 char smb_dir[128];
745 #endif
746 } SlirpState;
748 static struct slirp_config_str *slirp_configs;
749 const char *legacy_tftp_prefix;
750 const char *legacy_bootp_filename;
751 static QTAILQ_HEAD(slirp_stacks, SlirpState) slirp_stacks =
752 QTAILQ_HEAD_INITIALIZER(slirp_stacks);
754 static int slirp_hostfwd(SlirpState *s, const char *redir_str,
755 int legacy_format);
756 static int slirp_guestfwd(SlirpState *s, const char *config_str,
757 int legacy_format);
759 #ifndef _WIN32
760 static const char *legacy_smb_export;
762 static int slirp_smb(SlirpState *s, const char *exported_dir,
763 struct in_addr vserver_addr);
764 static void slirp_smb_cleanup(SlirpState *s);
765 #else
766 static inline void slirp_smb_cleanup(SlirpState *s) { }
767 #endif
769 int slirp_can_output(void *opaque)
771 SlirpState *s = opaque;
773 return qemu_can_send_packet(s->vc);
776 void slirp_output(void *opaque, const uint8_t *pkt, int pkt_len)
778 SlirpState *s = opaque;
780 #ifdef DEBUG_SLIRP
781 printf("slirp output:\n");
782 hex_dump(stdout, pkt, pkt_len);
783 #endif
784 qemu_send_packet(s->vc, pkt, pkt_len);
787 static ssize_t slirp_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
789 SlirpState *s = vc->opaque;
791 #ifdef DEBUG_SLIRP
792 printf("slirp input:\n");
793 hex_dump(stdout, buf, size);
794 #endif
795 slirp_input(s->slirp, buf, size);
796 return size;
799 static void net_slirp_cleanup(VLANClientState *vc)
801 SlirpState *s = vc->opaque;
803 slirp_cleanup(s->slirp);
804 slirp_smb_cleanup(s);
805 QTAILQ_REMOVE(&slirp_stacks, s, entry);
806 qemu_free(s);
809 static int net_slirp_init(VLANState *vlan, const char *model,
810 const char *name, int restricted,
811 const char *vnetwork, const char *vhost,
812 const char *vhostname, const char *tftp_export,
813 const char *bootfile, const char *vdhcp_start,
814 const char *vnameserver, const char *smb_export,
815 const char *vsmbserver)
817 /* default settings according to historic slirp */
818 struct in_addr net = { .s_addr = htonl(0x0a000200) }; /* 10.0.2.0 */
819 struct in_addr mask = { .s_addr = htonl(0xffffff00) }; /* 255.255.255.0 */
820 struct in_addr host = { .s_addr = htonl(0x0a000202) }; /* 10.0.2.2 */
821 struct in_addr dhcp = { .s_addr = htonl(0x0a00020f) }; /* 10.0.2.15 */
822 struct in_addr dns = { .s_addr = htonl(0x0a000203) }; /* 10.0.2.3 */
823 #ifndef _WIN32
824 struct in_addr smbsrv = { .s_addr = 0 };
825 #endif
826 SlirpState *s;
827 char buf[20];
828 uint32_t addr;
829 int shift;
830 char *end;
831 struct slirp_config_str *config;
833 if (!tftp_export) {
834 tftp_export = legacy_tftp_prefix;
836 if (!bootfile) {
837 bootfile = legacy_bootp_filename;
840 if (vnetwork) {
841 if (get_str_sep(buf, sizeof(buf), &vnetwork, '/') < 0) {
842 if (!inet_aton(vnetwork, &net)) {
843 return -1;
845 addr = ntohl(net.s_addr);
846 if (!(addr & 0x80000000)) {
847 mask.s_addr = htonl(0xff000000); /* class A */
848 } else if ((addr & 0xfff00000) == 0xac100000) {
849 mask.s_addr = htonl(0xfff00000); /* priv. 172.16.0.0/12 */
850 } else if ((addr & 0xc0000000) == 0x80000000) {
851 mask.s_addr = htonl(0xffff0000); /* class B */
852 } else if ((addr & 0xffff0000) == 0xc0a80000) {
853 mask.s_addr = htonl(0xffff0000); /* priv. 192.168.0.0/16 */
854 } else if ((addr & 0xffff0000) == 0xc6120000) {
855 mask.s_addr = htonl(0xfffe0000); /* tests 198.18.0.0/15 */
856 } else if ((addr & 0xe0000000) == 0xe0000000) {
857 mask.s_addr = htonl(0xffffff00); /* class C */
858 } else {
859 mask.s_addr = htonl(0xfffffff0); /* multicast/reserved */
861 } else {
862 if (!inet_aton(buf, &net)) {
863 return -1;
865 shift = strtol(vnetwork, &end, 10);
866 if (*end != '\0') {
867 if (!inet_aton(vnetwork, &mask)) {
868 return -1;
870 } else if (shift < 4 || shift > 32) {
871 return -1;
872 } else {
873 mask.s_addr = htonl(0xffffffff << (32 - shift));
876 net.s_addr &= mask.s_addr;
877 host.s_addr = net.s_addr | (htonl(0x0202) & ~mask.s_addr);
878 dhcp.s_addr = net.s_addr | (htonl(0x020f) & ~mask.s_addr);
879 dns.s_addr = net.s_addr | (htonl(0x0203) & ~mask.s_addr);
882 if (vhost && !inet_aton(vhost, &host)) {
883 return -1;
885 if ((host.s_addr & mask.s_addr) != net.s_addr) {
886 return -1;
889 if (vdhcp_start && !inet_aton(vdhcp_start, &dhcp)) {
890 return -1;
892 if ((dhcp.s_addr & mask.s_addr) != net.s_addr ||
893 dhcp.s_addr == host.s_addr || dhcp.s_addr == dns.s_addr) {
894 return -1;
897 if (vnameserver && !inet_aton(vnameserver, &dns)) {
898 return -1;
900 if ((dns.s_addr & mask.s_addr) != net.s_addr ||
901 dns.s_addr == host.s_addr) {
902 return -1;
905 #ifndef _WIN32
906 if (vsmbserver && !inet_aton(vsmbserver, &smbsrv)) {
907 return -1;
909 #endif
911 s = qemu_mallocz(sizeof(SlirpState));
912 s->slirp = slirp_init(restricted, net, mask, host, vhostname,
913 tftp_export, bootfile, dhcp, dns, s);
914 QTAILQ_INSERT_TAIL(&slirp_stacks, s, entry);
916 for (config = slirp_configs; config; config = config->next) {
917 if (config->flags & SLIRP_CFG_HOSTFWD) {
918 if (slirp_hostfwd(s, config->str,
919 config->flags & SLIRP_CFG_LEGACY) < 0)
920 return -1;
921 } else {
922 if (slirp_guestfwd(s, config->str,
923 config->flags & SLIRP_CFG_LEGACY) < 0)
924 return -1;
927 #ifndef _WIN32
928 if (!smb_export) {
929 smb_export = legacy_smb_export;
931 if (smb_export) {
932 if (slirp_smb(s, smb_export, smbsrv) < 0)
933 return -1;
935 #endif
937 s->vc = qemu_new_vlan_client(NET_CLIENT_TYPE_SLIRP,
938 vlan, NULL, model, name, NULL,
939 slirp_receive, NULL, NULL,
940 net_slirp_cleanup, s);
941 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
942 "net=%s, restricted=%c", inet_ntoa(net), restricted ? 'y' : 'n');
943 return 0;
946 static SlirpState *slirp_lookup(Monitor *mon, const char *vlan,
947 const char *stack)
949 VLANClientState *vc;
951 if (vlan) {
952 vc = qemu_find_vlan_client_by_name(mon, strtol(vlan, NULL, 0), stack);
953 if (!vc) {
954 return NULL;
956 if (strcmp(vc->model, "user")) {
957 monitor_printf(mon, "invalid device specified\n");
958 return NULL;
960 return vc->opaque;
961 } else {
962 if (QTAILQ_EMPTY(&slirp_stacks)) {
963 monitor_printf(mon, "user mode network stack not in use\n");
964 return NULL;
966 return QTAILQ_FIRST(&slirp_stacks);
970 void net_slirp_hostfwd_remove(Monitor *mon, const QDict *qdict)
972 struct in_addr host_addr = { .s_addr = INADDR_ANY };
973 int host_port;
974 char buf[256] = "";
975 const char *src_str, *p;
976 SlirpState *s;
977 int is_udp = 0;
978 int err;
979 const char *arg1 = qdict_get_str(qdict, "arg1");
980 const char *arg2 = qdict_get_try_str(qdict, "arg2");
981 const char *arg3 = qdict_get_try_str(qdict, "arg3");
983 if (arg2) {
984 s = slirp_lookup(mon, arg1, arg2);
985 src_str = arg3;
986 } else {
987 s = slirp_lookup(mon, NULL, NULL);
988 src_str = arg1;
990 if (!s) {
991 return;
994 if (!src_str || !src_str[0])
995 goto fail_syntax;
997 p = src_str;
998 get_str_sep(buf, sizeof(buf), &p, ':');
1000 if (!strcmp(buf, "tcp") || buf[0] == '\0') {
1001 is_udp = 0;
1002 } else if (!strcmp(buf, "udp")) {
1003 is_udp = 1;
1004 } else {
1005 goto fail_syntax;
1008 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1009 goto fail_syntax;
1011 if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
1012 goto fail_syntax;
1015 host_port = atoi(p);
1017 err = slirp_remove_hostfwd(QTAILQ_FIRST(&slirp_stacks)->slirp, is_udp,
1018 host_addr, host_port);
1020 monitor_printf(mon, "host forwarding rule for %s %s\n", src_str,
1021 err ? "removed" : "not found");
1022 return;
1024 fail_syntax:
1025 monitor_printf(mon, "invalid format\n");
1028 static int slirp_hostfwd(SlirpState *s, const char *redir_str,
1029 int legacy_format)
1031 struct in_addr host_addr = { .s_addr = INADDR_ANY };
1032 struct in_addr guest_addr = { .s_addr = 0 };
1033 int host_port, guest_port;
1034 const char *p;
1035 char buf[256];
1036 int is_udp;
1037 char *end;
1039 p = redir_str;
1040 if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1041 goto fail_syntax;
1043 if (!strcmp(buf, "tcp") || buf[0] == '\0') {
1044 is_udp = 0;
1045 } else if (!strcmp(buf, "udp")) {
1046 is_udp = 1;
1047 } else {
1048 goto fail_syntax;
1051 if (!legacy_format) {
1052 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1053 goto fail_syntax;
1055 if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {
1056 goto fail_syntax;
1060 if (get_str_sep(buf, sizeof(buf), &p, legacy_format ? ':' : '-') < 0) {
1061 goto fail_syntax;
1063 host_port = strtol(buf, &end, 0);
1064 if (*end != '\0' || host_port < 1 || host_port > 65535) {
1065 goto fail_syntax;
1068 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1069 goto fail_syntax;
1071 if (buf[0] != '\0' && !inet_aton(buf, &guest_addr)) {
1072 goto fail_syntax;
1075 guest_port = strtol(p, &end, 0);
1076 if (*end != '\0' || guest_port < 1 || guest_port > 65535) {
1077 goto fail_syntax;
1080 if (slirp_add_hostfwd(s->slirp, is_udp, host_addr, host_port, guest_addr,
1081 guest_port) < 0) {
1082 qemu_error("could not set up host forwarding rule '%s'\n",
1083 redir_str);
1084 return -1;
1086 return 0;
1088 fail_syntax:
1089 qemu_error("invalid host forwarding rule '%s'\n", redir_str);
1090 return -1;
1093 void net_slirp_hostfwd_add(Monitor *mon, const QDict *qdict)
1095 const char *redir_str;
1096 SlirpState *s;
1097 const char *arg1 = qdict_get_str(qdict, "arg1");
1098 const char *arg2 = qdict_get_try_str(qdict, "arg2");
1099 const char *arg3 = qdict_get_try_str(qdict, "arg3");
1101 if (arg2) {
1102 s = slirp_lookup(mon, arg1, arg2);
1103 redir_str = arg3;
1104 } else {
1105 s = slirp_lookup(mon, NULL, NULL);
1106 redir_str = arg1;
1108 if (s) {
1109 slirp_hostfwd(s, redir_str, 0);
1114 int net_slirp_redir(const char *redir_str)
1116 struct slirp_config_str *config;
1118 if (QTAILQ_EMPTY(&slirp_stacks)) {
1119 config = qemu_malloc(sizeof(*config));
1120 pstrcpy(config->str, sizeof(config->str), redir_str);
1121 config->flags = SLIRP_CFG_HOSTFWD | SLIRP_CFG_LEGACY;
1122 config->next = slirp_configs;
1123 slirp_configs = config;
1124 return 0;
1127 return slirp_hostfwd(QTAILQ_FIRST(&slirp_stacks), redir_str, 1);
1130 #ifndef _WIN32
1132 /* automatic user mode samba server configuration */
1133 static void slirp_smb_cleanup(SlirpState *s)
1135 char cmd[128];
1137 if (s->smb_dir[0] != '\0') {
1138 snprintf(cmd, sizeof(cmd), "rm -rf %s", s->smb_dir);
1139 system(cmd);
1140 s->smb_dir[0] = '\0';
1144 static int slirp_smb(SlirpState* s, const char *exported_dir,
1145 struct in_addr vserver_addr)
1147 static int instance;
1148 char smb_conf[128];
1149 char smb_cmdline[128];
1150 FILE *f;
1152 snprintf(s->smb_dir, sizeof(s->smb_dir), "/tmp/qemu-smb.%ld-%d",
1153 (long)getpid(), instance++);
1154 if (mkdir(s->smb_dir, 0700) < 0) {
1155 qemu_error("could not create samba server dir '%s'\n", s->smb_dir);
1156 return -1;
1158 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", s->smb_dir, "smb.conf");
1160 f = fopen(smb_conf, "w");
1161 if (!f) {
1162 slirp_smb_cleanup(s);
1163 qemu_error("could not create samba server configuration file '%s'\n",
1164 smb_conf);
1165 return -1;
1167 fprintf(f,
1168 "[global]\n"
1169 "private dir=%s\n"
1170 "smb ports=0\n"
1171 "socket address=127.0.0.1\n"
1172 "pid directory=%s\n"
1173 "lock directory=%s\n"
1174 "log file=%s/log.smbd\n"
1175 "smb passwd file=%s/smbpasswd\n"
1176 "security = share\n"
1177 "[qemu]\n"
1178 "path=%s\n"
1179 "read only=no\n"
1180 "guest ok=yes\n",
1181 s->smb_dir,
1182 s->smb_dir,
1183 s->smb_dir,
1184 s->smb_dir,
1185 s->smb_dir,
1186 exported_dir
1188 fclose(f);
1190 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
1191 SMBD_COMMAND, smb_conf);
1193 if (slirp_add_exec(s->slirp, 0, smb_cmdline, &vserver_addr, 139) < 0) {
1194 slirp_smb_cleanup(s);
1195 qemu_error("conflicting/invalid smbserver address\n");
1196 return -1;
1198 return 0;
1201 /* automatic user mode samba server configuration (legacy interface) */
1202 int net_slirp_smb(const char *exported_dir)
1204 struct in_addr vserver_addr = { .s_addr = 0 };
1206 if (legacy_smb_export) {
1207 fprintf(stderr, "-smb given twice\n");
1208 return -1;
1210 legacy_smb_export = exported_dir;
1211 if (!QTAILQ_EMPTY(&slirp_stacks)) {
1212 return slirp_smb(QTAILQ_FIRST(&slirp_stacks), exported_dir,
1213 vserver_addr);
1215 return 0;
1218 #endif /* !defined(_WIN32) */
1220 struct GuestFwd {
1221 CharDriverState *hd;
1222 struct in_addr server;
1223 int port;
1224 Slirp *slirp;
1227 static int guestfwd_can_read(void *opaque)
1229 struct GuestFwd *fwd = opaque;
1230 return slirp_socket_can_recv(fwd->slirp, fwd->server, fwd->port);
1233 static void guestfwd_read(void *opaque, const uint8_t *buf, int size)
1235 struct GuestFwd *fwd = opaque;
1236 slirp_socket_recv(fwd->slirp, fwd->server, fwd->port, buf, size);
1239 static int slirp_guestfwd(SlirpState *s, const char *config_str,
1240 int legacy_format)
1242 struct in_addr server = { .s_addr = 0 };
1243 struct GuestFwd *fwd;
1244 const char *p;
1245 char buf[128];
1246 char *end;
1247 int port;
1249 p = config_str;
1250 if (legacy_format) {
1251 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1252 goto fail_syntax;
1254 } else {
1255 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1256 goto fail_syntax;
1258 if (strcmp(buf, "tcp") && buf[0] != '\0') {
1259 goto fail_syntax;
1261 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {
1262 goto fail_syntax;
1264 if (buf[0] != '\0' && !inet_aton(buf, &server)) {
1265 goto fail_syntax;
1267 if (get_str_sep(buf, sizeof(buf), &p, '-') < 0) {
1268 goto fail_syntax;
1271 port = strtol(buf, &end, 10);
1272 if (*end != '\0' || port < 1 || port > 65535) {
1273 goto fail_syntax;
1276 fwd = qemu_malloc(sizeof(struct GuestFwd));
1277 snprintf(buf, sizeof(buf), "guestfwd.tcp:%d", port);
1278 fwd->hd = qemu_chr_open(buf, p, NULL);
1279 if (!fwd->hd) {
1280 qemu_error("could not open guest forwarding device '%s'\n", buf);
1281 qemu_free(fwd);
1282 return -1;
1285 if (slirp_add_exec(s->slirp, 3, fwd->hd, &server, port) < 0) {
1286 qemu_error("conflicting/invalid host:port in guest forwarding "
1287 "rule '%s'\n", config_str);
1288 qemu_free(fwd);
1289 return -1;
1291 fwd->server = server;
1292 fwd->port = port;
1293 fwd->slirp = s->slirp;
1295 qemu_chr_add_handlers(fwd->hd, guestfwd_can_read, guestfwd_read,
1296 NULL, fwd);
1297 return 0;
1299 fail_syntax:
1300 qemu_error("invalid guest forwarding rule '%s'\n", config_str);
1301 return -1;
1304 void do_info_usernet(Monitor *mon)
1306 SlirpState *s;
1308 QTAILQ_FOREACH(s, &slirp_stacks, entry) {
1309 monitor_printf(mon, "VLAN %d (%s):\n", s->vc->vlan->id, s->vc->name);
1310 slirp_connection_info(s->slirp, mon);
1314 #endif /* CONFIG_SLIRP */
1316 #if defined(CONFIG_VDE)
1317 typedef struct VDEState {
1318 VLANClientState *vc;
1319 VDECONN *vde;
1320 } VDEState;
1322 static void vde_to_qemu(void *opaque)
1324 VDEState *s = opaque;
1325 uint8_t buf[4096];
1326 int size;
1328 size = vde_recv(s->vde, (char *)buf, sizeof(buf), 0);
1329 if (size > 0) {
1330 qemu_send_packet(s->vc, buf, size);
1334 static ssize_t vde_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1336 VDEState *s = vc->opaque;
1337 ssize_t ret;
1339 do {
1340 ret = vde_send(s->vde, (const char *)buf, size, 0);
1341 } while (ret < 0 && errno == EINTR);
1343 return ret;
1346 static void vde_cleanup(VLANClientState *vc)
1348 VDEState *s = vc->opaque;
1349 qemu_set_fd_handler(vde_datafd(s->vde), NULL, NULL, NULL);
1350 vde_close(s->vde);
1351 qemu_free(s);
1354 static int net_vde_init(VLANState *vlan, const char *model,
1355 const char *name, const char *sock,
1356 int port, const char *group, int mode)
1358 VDEState *s;
1359 char *init_group = (char *)group;
1360 char *init_sock = (char *)sock;
1362 struct vde_open_args args = {
1363 .port = port,
1364 .group = init_group,
1365 .mode = mode,
1368 s = qemu_mallocz(sizeof(VDEState));
1369 s->vde = vde_open(init_sock, (char *)"QEMU", &args);
1370 if (!s->vde){
1371 free(s);
1372 return -1;
1374 s->vc = qemu_new_vlan_client(NET_CLIENT_TYPE_VDE,
1375 vlan, NULL, model, name, NULL,
1376 vde_receive, NULL, NULL,
1377 vde_cleanup, s);
1378 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1379 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1380 sock, vde_datafd(s->vde));
1381 return 0;
1383 #endif
1385 /* network connection */
1386 typedef struct NetSocketState {
1387 VLANClientState *vc;
1388 int fd;
1389 int state; /* 0 = getting length, 1 = getting data */
1390 unsigned int index;
1391 unsigned int packet_len;
1392 uint8_t buf[4096];
1393 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1394 } NetSocketState;
1396 typedef struct NetSocketListenState {
1397 VLANState *vlan;
1398 char *model;
1399 char *name;
1400 int fd;
1401 } NetSocketListenState;
1403 /* XXX: we consider we can send the whole packet without blocking */
1404 static ssize_t net_socket_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1406 NetSocketState *s = vc->opaque;
1407 uint32_t len;
1408 len = htonl(size);
1410 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1411 return send_all(s->fd, buf, size);
1414 static ssize_t net_socket_receive_dgram(VLANClientState *vc, const uint8_t *buf, size_t size)
1416 NetSocketState *s = vc->opaque;
1418 return sendto(s->fd, (const void *)buf, size, 0,
1419 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1422 static void net_socket_send(void *opaque)
1424 NetSocketState *s = opaque;
1425 int size, err;
1426 unsigned l;
1427 uint8_t buf1[4096];
1428 const uint8_t *buf;
1430 size = recv(s->fd, (void *)buf1, sizeof(buf1), 0);
1431 if (size < 0) {
1432 err = socket_error();
1433 if (err != EWOULDBLOCK)
1434 goto eoc;
1435 } else if (size == 0) {
1436 /* end of connection */
1437 eoc:
1438 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1439 closesocket(s->fd);
1440 return;
1442 buf = buf1;
1443 while (size > 0) {
1444 /* reassemble a packet from the network */
1445 switch(s->state) {
1446 case 0:
1447 l = 4 - s->index;
1448 if (l > size)
1449 l = size;
1450 memcpy(s->buf + s->index, buf, l);
1451 buf += l;
1452 size -= l;
1453 s->index += l;
1454 if (s->index == 4) {
1455 /* got length */
1456 s->packet_len = ntohl(*(uint32_t *)s->buf);
1457 s->index = 0;
1458 s->state = 1;
1460 break;
1461 case 1:
1462 l = s->packet_len - s->index;
1463 if (l > size)
1464 l = size;
1465 if (s->index + l <= sizeof(s->buf)) {
1466 memcpy(s->buf + s->index, buf, l);
1467 } else {
1468 fprintf(stderr, "serious error: oversized packet received,"
1469 "connection terminated.\n");
1470 s->state = 0;
1471 goto eoc;
1474 s->index += l;
1475 buf += l;
1476 size -= l;
1477 if (s->index >= s->packet_len) {
1478 qemu_send_packet(s->vc, s->buf, s->packet_len);
1479 s->index = 0;
1480 s->state = 0;
1482 break;
1487 static void net_socket_send_dgram(void *opaque)
1489 NetSocketState *s = opaque;
1490 int size;
1492 size = recv(s->fd, (void *)s->buf, sizeof(s->buf), 0);
1493 if (size < 0)
1494 return;
1495 if (size == 0) {
1496 /* end of connection */
1497 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1498 return;
1500 qemu_send_packet(s->vc, s->buf, size);
1503 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1505 struct ip_mreq imr;
1506 int fd;
1507 int val, ret;
1508 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1509 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1510 inet_ntoa(mcastaddr->sin_addr),
1511 (int)ntohl(mcastaddr->sin_addr.s_addr));
1512 return -1;
1515 fd = socket(PF_INET, SOCK_DGRAM, 0);
1516 if (fd < 0) {
1517 perror("socket(PF_INET, SOCK_DGRAM)");
1518 return -1;
1521 val = 1;
1522 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1523 (const char *)&val, sizeof(val));
1524 if (ret < 0) {
1525 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1526 goto fail;
1529 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1530 if (ret < 0) {
1531 perror("bind");
1532 goto fail;
1535 /* Add host to multicast group */
1536 imr.imr_multiaddr = mcastaddr->sin_addr;
1537 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1539 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1540 (const char *)&imr, sizeof(struct ip_mreq));
1541 if (ret < 0) {
1542 perror("setsockopt(IP_ADD_MEMBERSHIP)");
1543 goto fail;
1546 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1547 val = 1;
1548 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1549 (const char *)&val, sizeof(val));
1550 if (ret < 0) {
1551 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1552 goto fail;
1555 socket_set_nonblock(fd);
1556 return fd;
1557 fail:
1558 if (fd >= 0)
1559 closesocket(fd);
1560 return -1;
1563 static void net_socket_cleanup(VLANClientState *vc)
1565 NetSocketState *s = vc->opaque;
1566 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1567 close(s->fd);
1568 qemu_free(s);
1571 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1572 const char *model,
1573 const char *name,
1574 int fd, int is_connected)
1576 struct sockaddr_in saddr;
1577 int newfd;
1578 socklen_t saddr_len;
1579 NetSocketState *s;
1581 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1582 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1583 * by ONLY ONE process: we must "clone" this dgram socket --jjo
1586 if (is_connected) {
1587 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1588 /* must be bound */
1589 if (saddr.sin_addr.s_addr==0) {
1590 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1591 fd);
1592 return NULL;
1594 /* clone dgram socket */
1595 newfd = net_socket_mcast_create(&saddr);
1596 if (newfd < 0) {
1597 /* error already reported by net_socket_mcast_create() */
1598 close(fd);
1599 return NULL;
1601 /* clone newfd to fd, close newfd */
1602 dup2(newfd, fd);
1603 close(newfd);
1605 } else {
1606 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1607 fd, strerror(errno));
1608 return NULL;
1612 s = qemu_mallocz(sizeof(NetSocketState));
1613 s->fd = fd;
1615 s->vc = qemu_new_vlan_client(NET_CLIENT_TYPE_SOCKET,
1616 vlan, NULL, model, name, NULL,
1617 net_socket_receive_dgram, NULL, NULL,
1618 net_socket_cleanup, s);
1619 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1621 /* mcast: save bound address as dst */
1622 if (is_connected) s->dgram_dst=saddr;
1624 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1625 "socket: fd=%d (%s mcast=%s:%d)",
1626 fd, is_connected? "cloned" : "",
1627 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1628 return s;
1631 static void net_socket_connect(void *opaque)
1633 NetSocketState *s = opaque;
1634 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1637 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1638 const char *model,
1639 const char *name,
1640 int fd, int is_connected)
1642 NetSocketState *s;
1643 s = qemu_mallocz(sizeof(NetSocketState));
1644 s->fd = fd;
1645 s->vc = qemu_new_vlan_client(NET_CLIENT_TYPE_SOCKET,
1646 vlan, NULL, model, name, NULL,
1647 net_socket_receive, NULL, NULL,
1648 net_socket_cleanup, s);
1649 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1650 "socket: fd=%d", fd);
1651 if (is_connected) {
1652 net_socket_connect(s);
1653 } else {
1654 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1656 return s;
1659 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1660 const char *model, const char *name,
1661 int fd, int is_connected)
1663 int so_type = -1, optlen=sizeof(so_type);
1665 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1666 (socklen_t *)&optlen)< 0) {
1667 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1668 return NULL;
1670 switch(so_type) {
1671 case SOCK_DGRAM:
1672 return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1673 case SOCK_STREAM:
1674 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1675 default:
1676 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1677 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1678 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1680 return NULL;
1683 static void net_socket_accept(void *opaque)
1685 NetSocketListenState *s = opaque;
1686 NetSocketState *s1;
1687 struct sockaddr_in saddr;
1688 socklen_t len;
1689 int fd;
1691 for(;;) {
1692 len = sizeof(saddr);
1693 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1694 if (fd < 0 && errno != EINTR) {
1695 return;
1696 } else if (fd >= 0) {
1697 break;
1700 s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1701 if (!s1) {
1702 closesocket(fd);
1703 } else {
1704 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1705 "socket: connection from %s:%d",
1706 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1710 static int net_socket_listen_init(VLANState *vlan,
1711 const char *model,
1712 const char *name,
1713 const char *host_str)
1715 NetSocketListenState *s;
1716 int fd, val, ret;
1717 struct sockaddr_in saddr;
1719 if (parse_host_port(&saddr, host_str) < 0)
1720 return -1;
1722 s = qemu_mallocz(sizeof(NetSocketListenState));
1724 fd = socket(PF_INET, SOCK_STREAM, 0);
1725 if (fd < 0) {
1726 perror("socket");
1727 return -1;
1729 socket_set_nonblock(fd);
1731 /* allow fast reuse */
1732 val = 1;
1733 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1735 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1736 if (ret < 0) {
1737 perror("bind");
1738 return -1;
1740 ret = listen(fd, 0);
1741 if (ret < 0) {
1742 perror("listen");
1743 return -1;
1745 s->vlan = vlan;
1746 s->model = qemu_strdup(model);
1747 s->name = name ? qemu_strdup(name) : NULL;
1748 s->fd = fd;
1749 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1750 return 0;
1753 static int net_socket_connect_init(VLANState *vlan,
1754 const char *model,
1755 const char *name,
1756 const char *host_str)
1758 NetSocketState *s;
1759 int fd, connected, ret, err;
1760 struct sockaddr_in saddr;
1762 if (parse_host_port(&saddr, host_str) < 0)
1763 return -1;
1765 fd = socket(PF_INET, SOCK_STREAM, 0);
1766 if (fd < 0) {
1767 perror("socket");
1768 return -1;
1770 socket_set_nonblock(fd);
1772 connected = 0;
1773 for(;;) {
1774 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1775 if (ret < 0) {
1776 err = socket_error();
1777 if (err == EINTR || err == EWOULDBLOCK) {
1778 } else if (err == EINPROGRESS) {
1779 break;
1780 #ifdef _WIN32
1781 } else if (err == WSAEALREADY) {
1782 break;
1783 #endif
1784 } else {
1785 perror("connect");
1786 closesocket(fd);
1787 return -1;
1789 } else {
1790 connected = 1;
1791 break;
1794 s = net_socket_fd_init(vlan, model, name, fd, connected);
1795 if (!s)
1796 return -1;
1797 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1798 "socket: connect to %s:%d",
1799 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1800 return 0;
1803 static int net_socket_mcast_init(VLANState *vlan,
1804 const char *model,
1805 const char *name,
1806 const char *host_str)
1808 NetSocketState *s;
1809 int fd;
1810 struct sockaddr_in saddr;
1812 if (parse_host_port(&saddr, host_str) < 0)
1813 return -1;
1816 fd = net_socket_mcast_create(&saddr);
1817 if (fd < 0)
1818 return -1;
1820 s = net_socket_fd_init(vlan, model, name, fd, 0);
1821 if (!s)
1822 return -1;
1824 s->dgram_dst = saddr;
1826 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1827 "socket: mcast=%s:%d",
1828 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1829 return 0;
1833 typedef struct DumpState {
1834 VLANClientState *pcap_vc;
1835 int fd;
1836 int pcap_caplen;
1837 } DumpState;
1839 #define PCAP_MAGIC 0xa1b2c3d4
1841 struct pcap_file_hdr {
1842 uint32_t magic;
1843 uint16_t version_major;
1844 uint16_t version_minor;
1845 int32_t thiszone;
1846 uint32_t sigfigs;
1847 uint32_t snaplen;
1848 uint32_t linktype;
1851 struct pcap_sf_pkthdr {
1852 struct {
1853 int32_t tv_sec;
1854 int32_t tv_usec;
1855 } ts;
1856 uint32_t caplen;
1857 uint32_t len;
1860 static ssize_t dump_receive(VLANClientState *vc, const uint8_t *buf, size_t size)
1862 DumpState *s = vc->opaque;
1863 struct pcap_sf_pkthdr hdr;
1864 int64_t ts;
1865 int caplen;
1867 /* Early return in case of previous error. */
1868 if (s->fd < 0) {
1869 return size;
1872 ts = muldiv64(qemu_get_clock(vm_clock), 1000000, get_ticks_per_sec());
1873 caplen = size > s->pcap_caplen ? s->pcap_caplen : size;
1875 hdr.ts.tv_sec = ts / 1000000;
1876 hdr.ts.tv_usec = ts % 1000000;
1877 hdr.caplen = caplen;
1878 hdr.len = size;
1879 if (write(s->fd, &hdr, sizeof(hdr)) != sizeof(hdr) ||
1880 write(s->fd, buf, caplen) != caplen) {
1881 qemu_log("-net dump write error - stop dump\n");
1882 close(s->fd);
1883 s->fd = -1;
1886 return size;
1889 static void net_dump_cleanup(VLANClientState *vc)
1891 DumpState *s = vc->opaque;
1893 close(s->fd);
1894 qemu_free(s);
1897 static int net_dump_init(VLANState *vlan, const char *device,
1898 const char *name, const char *filename, int len)
1900 struct pcap_file_hdr hdr;
1901 DumpState *s;
1903 s = qemu_malloc(sizeof(DumpState));
1905 s->fd = open(filename, O_CREAT | O_WRONLY | O_BINARY, 0644);
1906 if (s->fd < 0) {
1907 qemu_error("-net dump: can't open %s\n", filename);
1908 return -1;
1911 s->pcap_caplen = len;
1913 hdr.magic = PCAP_MAGIC;
1914 hdr.version_major = 2;
1915 hdr.version_minor = 4;
1916 hdr.thiszone = 0;
1917 hdr.sigfigs = 0;
1918 hdr.snaplen = s->pcap_caplen;
1919 hdr.linktype = 1;
1921 if (write(s->fd, &hdr, sizeof(hdr)) < sizeof(hdr)) {
1922 qemu_error("-net dump write error: %s\n", strerror(errno));
1923 close(s->fd);
1924 qemu_free(s);
1925 return -1;
1928 s->pcap_vc = qemu_new_vlan_client(NET_CLIENT_TYPE_DUMP,
1929 vlan, NULL, device, name, NULL,
1930 dump_receive, NULL, NULL,
1931 net_dump_cleanup, s);
1932 snprintf(s->pcap_vc->info_str, sizeof(s->pcap_vc->info_str),
1933 "dump to %s (len=%d)", filename, len);
1934 return 0;
1937 /* find or alloc a new VLAN */
1938 VLANState *qemu_find_vlan(int id, int allocate)
1940 VLANState *vlan;
1942 QTAILQ_FOREACH(vlan, &vlans, next) {
1943 if (vlan->id == id) {
1944 return vlan;
1948 if (!allocate) {
1949 return NULL;
1952 vlan = qemu_mallocz(sizeof(VLANState));
1953 vlan->id = id;
1954 QTAILQ_INIT(&vlan->clients);
1956 vlan->send_queue = qemu_new_net_queue(qemu_vlan_deliver_packet,
1957 qemu_vlan_deliver_packet_iov,
1958 vlan);
1960 QTAILQ_INSERT_TAIL(&vlans, vlan, next);
1962 return vlan;
1965 VLANClientState *qemu_find_netdev(const char *id)
1967 VLANClientState *vc;
1969 QTAILQ_FOREACH(vc, &non_vlan_clients, next) {
1970 if (!strcmp(vc->name, id)) {
1971 return vc;
1975 return NULL;
1978 static int nic_get_free_idx(void)
1980 int index;
1982 for (index = 0; index < MAX_NICS; index++)
1983 if (!nd_table[index].used)
1984 return index;
1985 return -1;
1988 int qemu_show_nic_models(const char *arg, const char *const *models)
1990 int i;
1992 if (!arg || strcmp(arg, "?"))
1993 return 0;
1995 fprintf(stderr, "qemu: Supported NIC models: ");
1996 for (i = 0 ; models[i]; i++)
1997 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1998 return 1;
2001 void qemu_check_nic_model(NICInfo *nd, const char *model)
2003 const char *models[2];
2005 models[0] = model;
2006 models[1] = NULL;
2008 if (qemu_show_nic_models(nd->model, models))
2009 exit(0);
2010 if (qemu_find_nic_model(nd, models, model) < 0)
2011 exit(1);
2014 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
2015 const char *default_model)
2017 int i;
2019 if (!nd->model)
2020 nd->model = qemu_strdup(default_model);
2022 for (i = 0 ; models[i]; i++) {
2023 if (strcmp(nd->model, models[i]) == 0)
2024 return i;
2027 qemu_error("qemu: Unsupported NIC model: %s\n", nd->model);
2028 return -1;
2031 int net_handle_fd_param(Monitor *mon, const char *param)
2033 if (!qemu_isdigit(param[0])) {
2034 int fd;
2036 fd = monitor_get_fd(mon, param);
2037 if (fd == -1) {
2038 qemu_error("No file descriptor named %s found", param);
2039 return -1;
2042 return fd;
2043 } else {
2044 return strtol(param, NULL, 0);
2048 static int net_init_nic(QemuOpts *opts,
2049 Monitor *mon,
2050 const char *name,
2051 VLANState *vlan)
2053 int idx;
2054 NICInfo *nd;
2055 const char *netdev;
2057 idx = nic_get_free_idx();
2058 if (idx == -1 || nb_nics >= MAX_NICS) {
2059 qemu_error("Too Many NICs\n");
2060 return -1;
2063 nd = &nd_table[idx];
2065 memset(nd, 0, sizeof(*nd));
2067 if ((netdev = qemu_opt_get(opts, "netdev"))) {
2068 nd->netdev = qemu_find_netdev(netdev);
2069 if (!nd->netdev) {
2070 qemu_error("netdev '%s' not found\n", netdev);
2071 return -1;
2073 } else {
2074 assert(vlan);
2075 nd->vlan = vlan;
2077 if (name) {
2078 nd->name = qemu_strdup(name);
2080 if (qemu_opt_get(opts, "model")) {
2081 nd->model = qemu_strdup(qemu_opt_get(opts, "model"));
2083 if (qemu_opt_get(opts, "addr")) {
2084 nd->devaddr = qemu_strdup(qemu_opt_get(opts, "addr"));
2087 nd->macaddr[0] = 0x52;
2088 nd->macaddr[1] = 0x54;
2089 nd->macaddr[2] = 0x00;
2090 nd->macaddr[3] = 0x12;
2091 nd->macaddr[4] = 0x34;
2092 nd->macaddr[5] = 0x56 + idx;
2094 if (qemu_opt_get(opts, "macaddr") &&
2095 parse_macaddr(nd->macaddr, qemu_opt_get(opts, "macaddr")) < 0) {
2096 qemu_error("invalid syntax for ethernet address\n");
2097 return -1;
2100 nd->nvectors = qemu_opt_get_number(opts, "vectors", NIC_NVECTORS_UNSPECIFIED);
2101 if (nd->nvectors != NIC_NVECTORS_UNSPECIFIED &&
2102 (nd->nvectors < 0 || nd->nvectors > 0x7ffffff)) {
2103 qemu_error("invalid # of vectors: %d\n", nd->nvectors);
2104 return -1;
2107 nd->used = 1;
2108 if (vlan) {
2109 nd->vlan->nb_guest_devs++;
2111 nb_nics++;
2113 return idx;
2116 #if defined(CONFIG_SLIRP)
2117 static int net_init_slirp_configs(const char *name, const char *value, void *opaque)
2119 struct slirp_config_str *config;
2121 if (strcmp(name, "hostfwd") != 0 && strcmp(name, "guestfwd") != 0) {
2122 return 0;
2125 config = qemu_mallocz(sizeof(*config));
2127 pstrcpy(config->str, sizeof(config->str), value);
2129 if (!strcmp(name, "hostfwd")) {
2130 config->flags = SLIRP_CFG_HOSTFWD;
2133 config->next = slirp_configs;
2134 slirp_configs = config;
2136 return 0;
2139 static int net_init_slirp(QemuOpts *opts,
2140 Monitor *mon,
2141 const char *name,
2142 VLANState *vlan)
2144 struct slirp_config_str *config;
2145 const char *vhost;
2146 const char *vhostname;
2147 const char *vdhcp_start;
2148 const char *vnamesrv;
2149 const char *tftp_export;
2150 const char *bootfile;
2151 const char *smb_export;
2152 const char *vsmbsrv;
2153 char *vnet = NULL;
2154 int restricted = 0;
2155 int ret;
2157 vhost = qemu_opt_get(opts, "host");
2158 vhostname = qemu_opt_get(opts, "hostname");
2159 vdhcp_start = qemu_opt_get(opts, "dhcpstart");
2160 vnamesrv = qemu_opt_get(opts, "dns");
2161 tftp_export = qemu_opt_get(opts, "tftp");
2162 bootfile = qemu_opt_get(opts, "bootfile");
2163 smb_export = qemu_opt_get(opts, "smb");
2164 vsmbsrv = qemu_opt_get(opts, "smbserver");
2166 if (qemu_opt_get(opts, "ip")) {
2167 const char *ip = qemu_opt_get(opts, "ip");
2168 int l = strlen(ip) + strlen("/24") + 1;
2170 vnet = qemu_malloc(l);
2172 /* emulate legacy ip= parameter */
2173 pstrcpy(vnet, l, ip);
2174 pstrcat(vnet, l, "/24");
2177 if (qemu_opt_get(opts, "net")) {
2178 if (vnet) {
2179 qemu_free(vnet);
2181 vnet = qemu_strdup(qemu_opt_get(opts, "net"));
2184 if (qemu_opt_get(opts, "restrict") &&
2185 qemu_opt_get(opts, "restrict")[0] == 'y') {
2186 restricted = 1;
2189 qemu_opt_foreach(opts, net_init_slirp_configs, NULL, 0);
2191 ret = net_slirp_init(vlan, "user", name, restricted, vnet, vhost,
2192 vhostname, tftp_export, bootfile, vdhcp_start,
2193 vnamesrv, smb_export, vsmbsrv);
2195 while (slirp_configs) {
2196 config = slirp_configs;
2197 slirp_configs = config->next;
2198 qemu_free(config);
2201 if (ret != -1 && vlan) {
2202 vlan->nb_host_devs++;
2205 qemu_free(vnet);
2207 return ret;
2209 #endif /* CONFIG_SLIRP */
2211 static int net_init_socket(QemuOpts *opts,
2212 Monitor *mon,
2213 const char *name,
2214 VLANState *vlan)
2216 if (qemu_opt_get(opts, "fd")) {
2217 int fd;
2219 if (qemu_opt_get(opts, "listen") ||
2220 qemu_opt_get(opts, "connect") ||
2221 qemu_opt_get(opts, "mcast")) {
2222 qemu_error("listen=, connect= and mcast= is invalid with fd=\n");
2223 return -1;
2226 fd = net_handle_fd_param(mon, qemu_opt_get(opts, "fd"));
2227 if (fd == -1) {
2228 return -1;
2231 if (!net_socket_fd_init(vlan, "socket", name, fd, 1)) {
2232 close(fd);
2233 return -1;
2235 } else if (qemu_opt_get(opts, "listen")) {
2236 const char *listen;
2238 if (qemu_opt_get(opts, "fd") ||
2239 qemu_opt_get(opts, "connect") ||
2240 qemu_opt_get(opts, "mcast")) {
2241 qemu_error("fd=, connect= and mcast= is invalid with listen=\n");
2242 return -1;
2245 listen = qemu_opt_get(opts, "listen");
2247 if (net_socket_listen_init(vlan, "socket", name, listen) == -1) {
2248 return -1;
2250 } else if (qemu_opt_get(opts, "connect")) {
2251 const char *connect;
2253 if (qemu_opt_get(opts, "fd") ||
2254 qemu_opt_get(opts, "listen") ||
2255 qemu_opt_get(opts, "mcast")) {
2256 qemu_error("fd=, listen= and mcast= is invalid with connect=\n");
2257 return -1;
2260 connect = qemu_opt_get(opts, "connect");
2262 if (net_socket_connect_init(vlan, "socket", name, connect) == -1) {
2263 return -1;
2265 } else if (qemu_opt_get(opts, "mcast")) {
2266 const char *mcast;
2268 if (qemu_opt_get(opts, "fd") ||
2269 qemu_opt_get(opts, "connect") ||
2270 qemu_opt_get(opts, "listen")) {
2271 qemu_error("fd=, connect= and listen= is invalid with mcast=\n");
2272 return -1;
2275 mcast = qemu_opt_get(opts, "mcast");
2277 if (net_socket_mcast_init(vlan, "socket", name, mcast) == -1) {
2278 return -1;
2280 } else {
2281 qemu_error("-socket requires fd=, listen=, connect= or mcast=\n");
2282 return -1;
2285 if (vlan) {
2286 vlan->nb_host_devs++;
2289 return 0;
2292 #ifdef CONFIG_VDE
2293 static int net_init_vde(QemuOpts *opts,
2294 Monitor *mon,
2295 const char *name,
2296 VLANState *vlan)
2298 const char *sock;
2299 const char *group;
2300 int port, mode;
2302 sock = qemu_opt_get(opts, "sock");
2303 group = qemu_opt_get(opts, "group");
2305 port = qemu_opt_get_number(opts, "port", 0);
2306 mode = qemu_opt_get_number(opts, "mode", 0700);
2308 if (net_vde_init(vlan, "vde", name, sock, port, group, mode) == -1) {
2309 return -1;
2312 if (vlan) {
2313 vlan->nb_host_devs++;
2316 return 0;
2318 #endif
2320 static int net_init_dump(QemuOpts *opts,
2321 Monitor *mon,
2322 const char *name,
2323 VLANState *vlan)
2325 int len;
2326 const char *file;
2327 char def_file[128];
2329 assert(vlan);
2331 file = qemu_opt_get(opts, "file");
2332 if (!file) {
2333 snprintf(def_file, sizeof(def_file), "qemu-vlan%d.pcap", vlan->id);
2334 file = def_file;
2337 len = qemu_opt_get_size(opts, "len", 65536);
2339 return net_dump_init(vlan, "dump", name, file, len);
2342 #define NET_COMMON_PARAMS_DESC \
2344 .name = "type", \
2345 .type = QEMU_OPT_STRING, \
2346 .help = "net client type (nic, tap etc.)", \
2347 }, { \
2348 .name = "vlan", \
2349 .type = QEMU_OPT_NUMBER, \
2350 .help = "vlan number", \
2351 }, { \
2352 .name = "name", \
2353 .type = QEMU_OPT_STRING, \
2354 .help = "identifier for monitor commands", \
2357 typedef int (*net_client_init_func)(QemuOpts *opts,
2358 Monitor *mon,
2359 const char *name,
2360 VLANState *vlan);
2362 /* magic number, but compiler will warn if too small */
2363 #define NET_MAX_DESC 20
2365 static struct {
2366 const char *type;
2367 net_client_init_func init;
2368 QemuOptDesc desc[NET_MAX_DESC];
2369 } net_client_types[] = {
2371 .type = "none",
2372 .desc = {
2373 NET_COMMON_PARAMS_DESC,
2374 { /* end of list */ }
2376 }, {
2377 .type = "nic",
2378 .init = net_init_nic,
2379 .desc = {
2380 NET_COMMON_PARAMS_DESC,
2382 .name = "netdev",
2383 .type = QEMU_OPT_STRING,
2384 .help = "id of -netdev to connect to",
2387 .name = "macaddr",
2388 .type = QEMU_OPT_STRING,
2389 .help = "MAC address",
2390 }, {
2391 .name = "model",
2392 .type = QEMU_OPT_STRING,
2393 .help = "device model (e1000, rtl8139, virtio etc.)",
2394 }, {
2395 .name = "addr",
2396 .type = QEMU_OPT_STRING,
2397 .help = "PCI device address",
2398 }, {
2399 .name = "vectors",
2400 .type = QEMU_OPT_NUMBER,
2401 .help = "number of MSI-x vectors, 0 to disable MSI-X",
2403 { /* end of list */ }
2405 #ifdef CONFIG_SLIRP
2406 }, {
2407 .type = "user",
2408 .init = net_init_slirp,
2409 .desc = {
2410 NET_COMMON_PARAMS_DESC,
2412 .name = "hostname",
2413 .type = QEMU_OPT_STRING,
2414 .help = "client hostname reported by the builtin DHCP server",
2415 }, {
2416 .name = "restrict",
2417 .type = QEMU_OPT_STRING,
2418 .help = "isolate the guest from the host (y|yes|n|no)",
2419 }, {
2420 .name = "ip",
2421 .type = QEMU_OPT_STRING,
2422 .help = "legacy parameter, use net= instead",
2423 }, {
2424 .name = "net",
2425 .type = QEMU_OPT_STRING,
2426 .help = "IP address and optional netmask",
2427 }, {
2428 .name = "host",
2429 .type = QEMU_OPT_STRING,
2430 .help = "guest-visible address of the host",
2431 }, {
2432 .name = "tftp",
2433 .type = QEMU_OPT_STRING,
2434 .help = "root directory of the built-in TFTP server",
2435 }, {
2436 .name = "bootfile",
2437 .type = QEMU_OPT_STRING,
2438 .help = "BOOTP filename, for use with tftp=",
2439 }, {
2440 .name = "dhcpstart",
2441 .type = QEMU_OPT_STRING,
2442 .help = "the first of the 16 IPs the built-in DHCP server can assign",
2443 }, {
2444 .name = "dns",
2445 .type = QEMU_OPT_STRING,
2446 .help = "guest-visible address of the virtual nameserver",
2447 }, {
2448 .name = "smb",
2449 .type = QEMU_OPT_STRING,
2450 .help = "root directory of the built-in SMB server",
2451 }, {
2452 .name = "smbserver",
2453 .type = QEMU_OPT_STRING,
2454 .help = "IP address of the built-in SMB server",
2455 }, {
2456 .name = "hostfwd",
2457 .type = QEMU_OPT_STRING,
2458 .help = "guest port number to forward incoming TCP or UDP connections",
2459 }, {
2460 .name = "guestfwd",
2461 .type = QEMU_OPT_STRING,
2462 .help = "IP address and port to forward guest TCP connections",
2464 { /* end of list */ }
2466 #endif
2467 }, {
2468 .type = "tap",
2469 .init = net_init_tap,
2470 .desc = {
2471 NET_COMMON_PARAMS_DESC,
2473 .name = "ifname",
2474 .type = QEMU_OPT_STRING,
2475 .help = "interface name",
2477 #ifndef _WIN32
2479 .name = "fd",
2480 .type = QEMU_OPT_STRING,
2481 .help = "file descriptor of an already opened tap",
2482 }, {
2483 .name = "script",
2484 .type = QEMU_OPT_STRING,
2485 .help = "script to initialize the interface",
2486 }, {
2487 .name = "downscript",
2488 .type = QEMU_OPT_STRING,
2489 .help = "script to shut down the interface",
2490 }, {
2491 .name = "sndbuf",
2492 .type = QEMU_OPT_SIZE,
2493 .help = "send buffer limit"
2494 }, {
2495 .name = "vnet_hdr",
2496 .type = QEMU_OPT_BOOL,
2497 .help = "enable the IFF_VNET_HDR flag on the tap interface"
2499 #endif /* _WIN32 */
2500 { /* end of list */ }
2502 }, {
2503 .type = "socket",
2504 .init = net_init_socket,
2505 .desc = {
2506 NET_COMMON_PARAMS_DESC,
2508 .name = "fd",
2509 .type = QEMU_OPT_STRING,
2510 .help = "file descriptor of an already opened socket",
2511 }, {
2512 .name = "listen",
2513 .type = QEMU_OPT_STRING,
2514 .help = "port number, and optional hostname, to listen on",
2515 }, {
2516 .name = "connect",
2517 .type = QEMU_OPT_STRING,
2518 .help = "port number, and optional hostname, to connect to",
2519 }, {
2520 .name = "mcast",
2521 .type = QEMU_OPT_STRING,
2522 .help = "UDP multicast address and port number",
2524 { /* end of list */ }
2526 #ifdef CONFIG_VDE
2527 }, {
2528 .type = "vde",
2529 .init = net_init_vde,
2530 .desc = {
2531 NET_COMMON_PARAMS_DESC,
2533 .name = "sock",
2534 .type = QEMU_OPT_STRING,
2535 .help = "socket path",
2536 }, {
2537 .name = "port",
2538 .type = QEMU_OPT_NUMBER,
2539 .help = "port number",
2540 }, {
2541 .name = "group",
2542 .type = QEMU_OPT_STRING,
2543 .help = "group owner of socket",
2544 }, {
2545 .name = "mode",
2546 .type = QEMU_OPT_NUMBER,
2547 .help = "permissions for socket",
2549 { /* end of list */ }
2551 #endif
2552 }, {
2553 .type = "dump",
2554 .init = net_init_dump,
2555 .desc = {
2556 NET_COMMON_PARAMS_DESC,
2558 .name = "len",
2559 .type = QEMU_OPT_SIZE,
2560 .help = "per-packet size limit (64k default)",
2561 }, {
2562 .name = "file",
2563 .type = QEMU_OPT_STRING,
2564 .help = "dump file path (default is qemu-vlan0.pcap)",
2566 { /* end of list */ }
2569 { /* end of list */ }
2572 int net_client_init(Monitor *mon, QemuOpts *opts, int is_netdev)
2574 const char *name;
2575 const char *type;
2576 int i;
2578 type = qemu_opt_get(opts, "type");
2579 if (!type) {
2580 qemu_error("No type specified for -net\n");
2581 return -1;
2584 if (is_netdev) {
2585 if (strcmp(type, "tap") != 0 &&
2586 #ifdef CONFIG_SLIRP
2587 strcmp(type, "user") != 0 &&
2588 #endif
2589 #ifdef CONFIG_VDE
2590 strcmp(type, "vde") != 0 &&
2591 #endif
2592 strcmp(type, "socket") != 0) {
2593 qemu_error("The '%s' network backend type is not valid with -netdev\n",
2594 type);
2595 return -1;
2598 if (qemu_opt_get(opts, "vlan")) {
2599 qemu_error("The 'vlan' parameter is not valid with -netdev\n");
2600 return -1;
2602 if (qemu_opt_get(opts, "name")) {
2603 qemu_error("The 'name' parameter is not valid with -netdev\n");
2604 return -1;
2606 if (!qemu_opts_id(opts)) {
2607 qemu_error("The id= parameter is required with -netdev\n");
2608 return -1;
2612 name = qemu_opts_id(opts);
2613 if (!name) {
2614 name = qemu_opt_get(opts, "name");
2617 for (i = 0; net_client_types[i].type != NULL; i++) {
2618 if (!strcmp(net_client_types[i].type, type)) {
2619 VLANState *vlan = NULL;
2621 if (qemu_opts_validate(opts, &net_client_types[i].desc[0]) == -1) {
2622 return -1;
2625 /* Do not add to a vlan if it's a -netdev or a nic with a
2626 * netdev= parameter. */
2627 if (!(is_netdev ||
2628 (strcmp(type, "nic") == 0 && qemu_opt_get(opts, "netdev")))) {
2629 vlan = qemu_find_vlan(qemu_opt_get_number(opts, "vlan", 0), 1);
2632 if (net_client_types[i].init) {
2633 return net_client_types[i].init(opts, mon, name, vlan);
2634 } else {
2635 return 0;
2640 qemu_error("Invalid -net type '%s'\n", type);
2641 return -1;
2644 void net_client_uninit(NICInfo *nd)
2646 if (nd->vlan) {
2647 nd->vlan->nb_guest_devs--;
2649 nb_nics--;
2651 qemu_free(nd->model);
2652 qemu_free(nd->name);
2653 qemu_free(nd->devaddr);
2655 nd->used = 0;
2658 static int net_host_check_device(const char *device)
2660 int i;
2661 const char *valid_param_list[] = { "tap", "socket", "dump"
2662 #ifdef CONFIG_SLIRP
2663 ,"user"
2664 #endif
2665 #ifdef CONFIG_VDE
2666 ,"vde"
2667 #endif
2669 for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
2670 if (!strncmp(valid_param_list[i], device,
2671 strlen(valid_param_list[i])))
2672 return 1;
2675 return 0;
2678 void net_host_device_add(Monitor *mon, const QDict *qdict)
2680 const char *device = qdict_get_str(qdict, "device");
2681 const char *opts_str = qdict_get_try_str(qdict, "opts");
2682 QemuOpts *opts;
2684 if (!net_host_check_device(device)) {
2685 monitor_printf(mon, "invalid host network device %s\n", device);
2686 return;
2689 opts = qemu_opts_parse(&qemu_net_opts, opts_str ? opts_str : "", NULL);
2690 if (!opts) {
2691 monitor_printf(mon, "parsing network options '%s' failed\n",
2692 opts_str ? opts_str : "");
2693 return;
2696 qemu_opt_set(opts, "type", device);
2698 if (net_client_init(mon, opts, 0) < 0) {
2699 monitor_printf(mon, "adding host network device %s failed\n", device);
2703 void net_host_device_remove(Monitor *mon, const QDict *qdict)
2705 VLANClientState *vc;
2706 int vlan_id = qdict_get_int(qdict, "vlan_id");
2707 const char *device = qdict_get_str(qdict, "device");
2709 vc = qemu_find_vlan_client_by_name(mon, vlan_id, device);
2710 if (!vc) {
2711 return;
2713 if (!net_host_check_device(vc->model)) {
2714 monitor_printf(mon, "invalid host network device %s\n", device);
2715 return;
2717 qemu_del_vlan_client(vc);
2720 void net_set_boot_mask(int net_boot_mask)
2722 int i;
2724 /* Only the first four NICs may be bootable */
2725 net_boot_mask = net_boot_mask & 0xF;
2727 for (i = 0; i < nb_nics; i++) {
2728 if (net_boot_mask & (1 << i)) {
2729 nd_table[i].bootable = 1;
2730 net_boot_mask &= ~(1 << i);
2734 if (net_boot_mask) {
2735 fprintf(stderr, "Cannot boot from non-existent NIC\n");
2736 exit(1);
2740 void do_info_network(Monitor *mon)
2742 VLANState *vlan;
2744 QTAILQ_FOREACH(vlan, &vlans, next) {
2745 VLANClientState *vc;
2747 monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
2749 QTAILQ_FOREACH(vc, &vlan->clients, next) {
2750 monitor_printf(mon, " %s: %s\n", vc->name, vc->info_str);
2755 void do_set_link(Monitor *mon, const QDict *qdict)
2757 VLANState *vlan;
2758 VLANClientState *vc = NULL;
2759 const char *name = qdict_get_str(qdict, "name");
2760 const char *up_or_down = qdict_get_str(qdict, "up_or_down");
2762 QTAILQ_FOREACH(vlan, &vlans, next) {
2763 QTAILQ_FOREACH(vc, &vlan->clients, next) {
2764 if (strcmp(vc->name, name) == 0) {
2765 goto done;
2769 done:
2771 if (!vc) {
2772 monitor_printf(mon, "could not find network device '%s'\n", name);
2773 return;
2776 if (strcmp(up_or_down, "up") == 0)
2777 vc->link_down = 0;
2778 else if (strcmp(up_or_down, "down") == 0)
2779 vc->link_down = 1;
2780 else
2781 monitor_printf(mon, "invalid link status '%s'; only 'up' or 'down' "
2782 "valid\n", up_or_down);
2784 if (vc->link_status_changed)
2785 vc->link_status_changed(vc);
2788 void net_cleanup(void)
2790 VLANState *vlan;
2791 VLANClientState *vc, *next_vc;
2793 QTAILQ_FOREACH(vlan, &vlans, next) {
2794 QTAILQ_FOREACH_SAFE(vc, &vlan->clients, next, next_vc) {
2795 qemu_del_vlan_client(vc);
2799 QTAILQ_FOREACH_SAFE(vc, &non_vlan_clients, next, next_vc) {
2800 qemu_del_vlan_client(vc);
2804 static void net_check_clients(void)
2806 VLANState *vlan;
2808 QTAILQ_FOREACH(vlan, &vlans, next) {
2809 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
2810 continue;
2811 if (vlan->nb_guest_devs == 0)
2812 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
2813 if (vlan->nb_host_devs == 0)
2814 fprintf(stderr,
2815 "Warning: vlan %d is not connected to host network\n",
2816 vlan->id);
2820 static int net_init_client(QemuOpts *opts, void *dummy)
2822 if (net_client_init(NULL, opts, 0) < 0)
2823 return -1;
2824 return 0;
2827 static int net_init_netdev(QemuOpts *opts, void *dummy)
2829 return net_client_init(NULL, opts, 1);
2832 int net_init_clients(void)
2834 if (QTAILQ_EMPTY(&qemu_net_opts.head)) {
2835 /* if no clients, we use a default config */
2836 qemu_opts_set(&qemu_net_opts, NULL, "type", "nic");
2837 #ifdef CONFIG_SLIRP
2838 qemu_opts_set(&qemu_net_opts, NULL, "type", "user");
2839 #endif
2842 QTAILQ_INIT(&vlans);
2843 QTAILQ_INIT(&non_vlan_clients);
2845 if (qemu_opts_foreach(&qemu_netdev_opts, net_init_netdev, NULL, 1) == -1)
2846 return -1;
2848 if (qemu_opts_foreach(&qemu_net_opts, net_init_client, NULL, 1) == -1) {
2849 return -1;
2852 net_check_clients();
2854 return 0;
2857 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
2859 #if defined(CONFIG_SLIRP)
2860 /* handle legacy -net channel,port:chr */
2861 if (!strcmp(opts_list->name, "net") &&
2862 !strncmp(optarg, "channel,", strlen("channel,"))) {
2863 int ret;
2865 optarg += strlen("channel,");
2867 if (QTAILQ_EMPTY(&slirp_stacks)) {
2868 struct slirp_config_str *config;
2870 config = qemu_malloc(sizeof(*config));
2871 pstrcpy(config->str, sizeof(config->str), optarg);
2872 config->flags = SLIRP_CFG_LEGACY;
2873 config->next = slirp_configs;
2874 slirp_configs = config;
2875 ret = 0;
2876 } else {
2877 ret = slirp_guestfwd(QTAILQ_FIRST(&slirp_stacks), optarg, 1);
2880 return ret;
2882 #endif
2883 if (!qemu_opts_parse(opts_list, optarg, "type")) {
2884 return -1;
2887 return 0;