kvm: configure: run kernel configure even with --with-patched-kernel
[qemu-kvm/fedora.git] / net.c
blobd753fa0a6b85fa2ab50945b96535d80b740a7986
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 HOST_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 HOST_BSD
56 #include <sys/stat.h>
57 #if defined(__FreeBSD__) || defined(__DragonFly__)
58 #include <libutil.h>
59 #else
60 #include <util.h>
61 #endif
62 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
63 #include <freebsd/stdlib.h>
64 #else
65 #ifdef __linux__
66 #include <pty.h>
67 #include <malloc.h>
68 #include <linux/rtc.h>
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 #ifdef _WIN32
105 #include <windows.h>
106 #include <malloc.h>
107 #include <sys/timeb.h>
108 #include <mmsystem.h>
109 #define getopt_long_only getopt_long
110 #define memalign(align, size) malloc(size)
111 #endif
113 // FIXME: #include "qemu-kvm.h"
114 #include "qemu-common.h"
115 #include "net.h"
116 #include "monitor.h"
117 #include "sysemu.h"
118 #include "qemu-timer.h"
119 #include "qemu-char.h"
120 #include "audio/audio.h"
121 #include "qemu_socket.h"
123 #if defined(CONFIG_SLIRP)
124 #include "libslirp.h"
125 #endif
128 static VLANState *first_vlan;
130 /***********************************************************/
131 /* network device redirectors */
133 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
134 static void hex_dump(FILE *f, const uint8_t *buf, int size)
136 int len, i, j, c;
138 for(i=0;i<size;i+=16) {
139 len = size - i;
140 if (len > 16)
141 len = 16;
142 fprintf(f, "%08x ", i);
143 for(j=0;j<16;j++) {
144 if (j < len)
145 fprintf(f, " %02x", buf[i+j]);
146 else
147 fprintf(f, " ");
149 fprintf(f, " ");
150 for(j=0;j<len;j++) {
151 c = buf[i+j];
152 if (c < ' ' || c > '~')
153 c = '.';
154 fprintf(f, "%c", c);
156 fprintf(f, "\n");
159 #endif
161 static int parse_macaddr(uint8_t *macaddr, const char *p)
163 int i;
164 char *last_char;
165 long int offset;
167 errno = 0;
168 offset = strtol(p, &last_char, 0);
169 if (0 == errno && '\0' == *last_char &&
170 offset >= 0 && offset <= 0xFFFFFF) {
171 macaddr[3] = (offset & 0xFF0000) >> 16;
172 macaddr[4] = (offset & 0xFF00) >> 8;
173 macaddr[5] = offset & 0xFF;
174 return 0;
175 } else {
176 for(i = 0; i < 6; i++) {
177 macaddr[i] = strtol(p, (char **)&p, 16);
178 if (i == 5) {
179 if (*p != '\0')
180 return -1;
181 } else {
182 if (*p != ':' && *p != '-')
183 return -1;
184 p++;
187 return 0;
190 return -1;
193 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
195 const char *p, *p1;
196 int len;
197 p = *pp;
198 p1 = strchr(p, sep);
199 if (!p1)
200 return -1;
201 len = p1 - p;
202 p1++;
203 if (buf_size > 0) {
204 if (len > buf_size - 1)
205 len = buf_size - 1;
206 memcpy(buf, p, len);
207 buf[len] = '\0';
209 *pp = p1;
210 return 0;
213 int parse_host_src_port(struct sockaddr_in *haddr,
214 struct sockaddr_in *saddr,
215 const char *input_str)
217 char *str = strdup(input_str);
218 char *host_str = str;
219 char *src_str;
220 const char *src_str2;
221 char *ptr;
224 * Chop off any extra arguments at the end of the string which
225 * would start with a comma, then fill in the src port information
226 * if it was provided else use the "any address" and "any port".
228 if ((ptr = strchr(str,',')))
229 *ptr = '\0';
231 if ((src_str = strchr(input_str,'@'))) {
232 *src_str = '\0';
233 src_str++;
236 if (parse_host_port(haddr, host_str) < 0)
237 goto fail;
239 src_str2 = src_str;
240 if (!src_str || *src_str == '\0')
241 src_str2 = ":0";
243 if (parse_host_port(saddr, src_str2) < 0)
244 goto fail;
246 free(str);
247 return(0);
249 fail:
250 free(str);
251 return -1;
254 int parse_host_port(struct sockaddr_in *saddr, const char *str)
256 char buf[512];
257 struct hostent *he;
258 const char *p, *r;
259 int port;
261 p = str;
262 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
263 return -1;
264 saddr->sin_family = AF_INET;
265 if (buf[0] == '\0') {
266 saddr->sin_addr.s_addr = 0;
267 } else {
268 if (qemu_isdigit(buf[0])) {
269 if (!inet_aton(buf, &saddr->sin_addr))
270 return -1;
271 } else {
272 if ((he = gethostbyname(buf)) == NULL)
273 return - 1;
274 saddr->sin_addr = *(struct in_addr *)he->h_addr;
277 port = strtol(p, (char **)&r, 0);
278 if (r == p)
279 return -1;
280 saddr->sin_port = htons(port);
281 return 0;
284 #if !defined(_WIN32) && 0
285 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
287 const char *p;
288 int len;
290 len = MIN(108, strlen(str));
291 p = strchr(str, ',');
292 if (p)
293 len = MIN(len, p - str);
295 memset(uaddr, 0, sizeof(*uaddr));
297 uaddr->sun_family = AF_UNIX;
298 memcpy(uaddr->sun_path, str, len);
300 return 0;
302 #endif
304 void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6])
306 snprintf(vc->info_str, sizeof(vc->info_str),
307 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
308 vc->model,
309 macaddr[0], macaddr[1], macaddr[2],
310 macaddr[3], macaddr[4], macaddr[5]);
313 static char *assign_name(VLANClientState *vc1, const char *model)
315 VLANState *vlan;
316 char buf[256];
317 int id = 0;
319 for (vlan = first_vlan; vlan; vlan = vlan->next) {
320 VLANClientState *vc;
322 for (vc = vlan->first_client; vc; vc = vc->next)
323 if (vc != vc1 && strcmp(vc->model, model) == 0)
324 id++;
327 snprintf(buf, sizeof(buf), "%s.%d", model, id);
329 return strdup(buf);
332 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
333 const char *model,
334 const char *name,
335 IOReadHandler *fd_read,
336 IOCanRWHandler *fd_can_read,
337 void *opaque)
339 VLANClientState *vc, **pvc;
340 vc = qemu_mallocz(sizeof(VLANClientState));
341 vc->model = strdup(model);
342 if (name)
343 vc->name = strdup(name);
344 else
345 vc->name = assign_name(vc, model);
346 vc->fd_read = fd_read;
347 vc->fd_can_read = fd_can_read;
348 vc->opaque = opaque;
349 vc->vlan = vlan;
351 vc->next = NULL;
352 pvc = &vlan->first_client;
353 while (*pvc != NULL)
354 pvc = &(*pvc)->next;
355 *pvc = vc;
356 return vc;
359 void qemu_del_vlan_client(VLANClientState *vc)
361 VLANClientState **pvc = &vc->vlan->first_client;
363 while (*pvc != NULL)
364 if (*pvc == vc) {
365 *pvc = vc->next;
366 free(vc->name);
367 free(vc->model);
368 free(vc);
369 break;
370 } else
371 pvc = &(*pvc)->next;
374 VLANClientState *qemu_find_vlan_client(VLANState *vlan, void *opaque)
376 VLANClientState **pvc = &vlan->first_client;
378 while (*pvc != NULL)
379 if ((*pvc)->opaque == opaque)
380 return *pvc;
381 else
382 pvc = &(*pvc)->next;
384 return NULL;
387 int qemu_can_send_packet(VLANClientState *vc1)
389 VLANState *vlan = vc1->vlan;
390 VLANClientState *vc;
392 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
393 if (vc != vc1) {
394 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
395 return 1;
398 return 0;
401 int qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
403 VLANState *vlan = vc1->vlan;
404 VLANClientState *vc;
405 int ret = -EAGAIN;
407 if (vc1->link_down)
408 return 0;
410 #ifdef DEBUG_NET
411 printf("vlan %d send:\n", vlan->id);
412 hex_dump(stdout, buf, size);
413 #endif
414 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
415 if (vc != vc1 && !vc->link_down) {
416 if (!vc->fd_can_read || vc->fd_can_read(vc->opaque)) {
417 vc->fd_read(vc->opaque, buf, size);
418 ret = 0;
422 return ret;
425 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
426 int iovcnt)
428 uint8_t buffer[4096];
429 size_t offset = 0;
430 int i;
432 for (i = 0; i < iovcnt; i++) {
433 size_t len;
435 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
436 memcpy(buffer + offset, iov[i].iov_base, len);
437 offset += len;
440 vc->fd_read(vc->opaque, buffer, offset);
442 return offset;
445 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
447 size_t offset = 0;
448 int i;
450 for (i = 0; i < iovcnt; i++)
451 offset += iov[i].iov_len;
452 return offset;
455 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
456 int iovcnt)
458 VLANState *vlan = vc1->vlan;
459 VLANClientState *vc;
460 ssize_t max_len = 0;
462 if (vc1->link_down)
463 return calc_iov_length(iov, iovcnt);
465 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
466 ssize_t len = 0;
468 if (vc == vc1)
469 continue;
471 if (vc->link_down)
472 len = calc_iov_length(iov, iovcnt);
473 if (vc->fd_readv)
474 len = vc->fd_readv(vc->opaque, iov, iovcnt);
475 else if (vc->fd_read)
476 len = vc_sendv_compat(vc, iov, iovcnt);
478 max_len = MAX(max_len, len);
481 return max_len;
484 #if defined(CONFIG_SLIRP)
486 /* slirp network adapter */
488 static int slirp_inited;
489 static int slirp_restrict;
490 static char *slirp_ip;
491 static VLANClientState *slirp_vc;
493 int slirp_can_output(void)
495 return !slirp_vc || qemu_can_send_packet(slirp_vc);
498 void slirp_output(const uint8_t *pkt, int pkt_len)
500 #ifdef DEBUG_SLIRP
501 printf("slirp output:\n");
502 hex_dump(stdout, pkt, pkt_len);
503 #endif
504 if (!slirp_vc)
505 return;
506 qemu_send_packet(slirp_vc, pkt, pkt_len);
509 int slirp_is_inited(void)
511 return slirp_inited;
514 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
516 #ifdef DEBUG_SLIRP
517 printf("slirp input:\n");
518 hex_dump(stdout, buf, size);
519 #endif
520 slirp_input(buf, size);
523 static int net_slirp_init(VLANState *vlan, const char *model, const char *name)
525 if (!slirp_inited) {
526 slirp_inited = 1;
527 slirp_init(slirp_restrict, slirp_ip);
529 slirp_vc = qemu_new_vlan_client(vlan, model, name,
530 slirp_receive, NULL, NULL);
531 slirp_vc->info_str[0] = '\0';
532 return 0;
535 void net_slirp_redir(const char *redir_str)
537 int is_udp;
538 char buf[256], *r;
539 const char *p;
540 struct in_addr guest_addr;
541 int host_port, guest_port;
543 if (!slirp_inited) {
544 slirp_inited = 1;
545 slirp_init(slirp_restrict, slirp_ip);
548 p = redir_str;
549 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
550 goto fail;
551 if (!strcmp(buf, "tcp")) {
552 is_udp = 0;
553 } else if (!strcmp(buf, "udp")) {
554 is_udp = 1;
555 } else {
556 goto fail;
559 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
560 goto fail;
561 host_port = strtol(buf, &r, 0);
562 if (r == buf)
563 goto fail;
565 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
566 goto fail;
567 if (buf[0] == '\0') {
568 pstrcpy(buf, sizeof(buf), "10.0.2.15");
570 if (!inet_aton(buf, &guest_addr))
571 goto fail;
573 guest_port = strtol(p, &r, 0);
574 if (r == p)
575 goto fail;
577 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
578 fprintf(stderr, "qemu: could not set up redirection\n");
579 exit(1);
581 return;
582 fail:
583 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
584 exit(1);
587 #ifndef _WIN32
589 static char smb_dir[1024];
591 static void erase_dir(char *dir_name)
593 DIR *d;
594 struct dirent *de;
595 char filename[1024];
597 /* erase all the files in the directory */
598 if ((d = opendir(dir_name)) != NULL) {
599 for(;;) {
600 de = readdir(d);
601 if (!de)
602 break;
603 if (strcmp(de->d_name, ".") != 0 &&
604 strcmp(de->d_name, "..") != 0) {
605 snprintf(filename, sizeof(filename), "%s/%s",
606 smb_dir, de->d_name);
607 if (unlink(filename) != 0) /* is it a directory? */
608 erase_dir(filename);
611 closedir(d);
612 rmdir(dir_name);
616 /* automatic user mode samba server configuration */
617 static void smb_exit(void)
619 erase_dir(smb_dir);
622 /* automatic user mode samba server configuration */
623 void net_slirp_smb(const char *exported_dir)
625 char smb_conf[1024];
626 char smb_cmdline[1024];
627 FILE *f;
629 if (!slirp_inited) {
630 slirp_inited = 1;
631 slirp_init(slirp_restrict, slirp_ip);
634 /* XXX: better tmp dir construction */
635 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
636 if (mkdir(smb_dir, 0700) < 0) {
637 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
638 exit(1);
640 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
642 f = fopen(smb_conf, "w");
643 if (!f) {
644 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
645 exit(1);
647 fprintf(f,
648 "[global]\n"
649 "private dir=%s\n"
650 "smb ports=0\n"
651 "socket address=127.0.0.1\n"
652 "pid directory=%s\n"
653 "lock directory=%s\n"
654 "log file=%s/log.smbd\n"
655 "smb passwd file=%s/smbpasswd\n"
656 "security = share\n"
657 "[qemu]\n"
658 "path=%s\n"
659 "read only=no\n"
660 "guest ok=yes\n",
661 smb_dir,
662 smb_dir,
663 smb_dir,
664 smb_dir,
665 smb_dir,
666 exported_dir
668 fclose(f);
669 atexit(smb_exit);
671 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
672 SMBD_COMMAND, smb_conf);
674 slirp_add_exec(0, smb_cmdline, 4, 139);
677 #endif /* !defined(_WIN32) */
678 void do_info_slirp(Monitor *mon)
680 slirp_stats();
683 struct VMChannel {
684 CharDriverState *hd;
685 int port;
688 static int vmchannel_can_read(void *opaque)
690 struct VMChannel *vmc = (struct VMChannel*)opaque;
691 return slirp_socket_can_recv(4, vmc->port);
694 static void vmchannel_read(void *opaque, const uint8_t *buf, int size)
696 struct VMChannel *vmc = (struct VMChannel*)opaque;
697 slirp_socket_recv(4, vmc->port, buf, size);
700 #endif /* CONFIG_SLIRP */
702 #ifdef _WIN32
704 int tap_has_vnet_hdr(void *opaque)
706 return 0;
709 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
713 #else /* !defined(_WIN32) */
715 /* Maximum GSO packet size (64k) plus plenty of room for
716 * the ethernet and virtio_net headers
718 #define TAP_BUFSIZE (4096 + 65536)
720 #ifdef IFF_VNET_HDR
721 #include <linux/virtio_net.h>
722 #endif
724 typedef struct TAPState {
725 VLANClientState *vc;
726 int fd;
727 char down_script[1024];
728 char down_script_arg[128];
729 char buf[TAP_BUFSIZE];
730 int size;
731 unsigned int has_vnet_hdr : 1;
732 unsigned int using_vnet_hdr : 1;
733 } TAPState;
735 #ifdef HAVE_IOVEC
736 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
737 int iovcnt)
739 TAPState *s = opaque;
740 ssize_t len;
742 do {
743 len = writev(s->fd, iov, iovcnt);
744 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
746 return len;
748 #endif
750 static void tap_receive(void *opaque, const uint8_t *buf, int size)
752 struct iovec iov[2];
753 int i = 0;
755 #ifdef IFF_VNET_HDR
756 TAPState *s = opaque;
757 struct virtio_net_hdr hdr = { 0, };
759 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
760 iov[i].iov_base = &hdr;
761 iov[i].iov_len = sizeof(hdr);
762 i++;
764 #endif
766 iov[i].iov_base = (char *) buf;
767 iov[i].iov_len = size;
768 i++;
770 tap_receive_iov(opaque, iov, i);
773 static int tap_can_send(void *opaque)
775 TAPState *s = opaque;
776 VLANClientState *vc;
777 int can_receive = 0;
779 /* Check to see if any of our clients can receive a packet */
780 for (vc = s->vc->vlan->first_client; vc; vc = vc->next) {
781 /* Skip ourselves */
782 if (vc == s->vc)
783 continue;
785 if (!vc->fd_can_read) {
786 /* no fd_can_read handler, they always can receive */
787 can_receive = 1;
788 } else
789 can_receive = vc->fd_can_read(vc->opaque);
791 /* Once someone can receive, we try to send a packet */
792 if (can_receive)
793 break;
796 return can_receive;
799 static int tap_send_packet(TAPState *s)
801 uint8_t *buf = (uint8_t *)s->buf;
802 int size = s->size;
804 #ifdef IFF_VNET_HDR
805 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
806 buf += sizeof(struct virtio_net_hdr);
807 size -= sizeof(struct virtio_net_hdr);
809 #endif
811 return qemu_send_packet(s->vc, buf, size);
814 static void tap_send(void *opaque)
816 TAPState *s = opaque;
818 /* First try to send any buffered packet */
819 if (s->size > 0) {
820 int err;
822 /* If noone can receive the packet, buffer it */
823 err = tap_send_packet(s);
824 if (err == -EAGAIN)
825 return;
828 /* Read packets until we hit EAGAIN */
829 do {
830 #ifdef __sun__
831 struct strbuf sbuf;
832 int f = 0;
833 sbuf.maxlen = sizeof(s->buf);
834 sbuf.buf = s->buf;
835 s->size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
836 #else
837 // FIXME: kvm_sleep_begin();
838 s->size = read(s->fd, s->buf, sizeof(s->buf));
839 // FIXME: kvm_sleep_end();
840 #endif
842 if (s->size == -1 && errno == EINTR)
843 continue;
845 if (s->size > 0) {
846 int err;
848 /* If noone can receive the packet, buffer it */
849 err = tap_send_packet(s);
850 if (err == -EAGAIN)
851 break;
853 } while (s->size > 0);
856 int tap_has_vnet_hdr(void *opaque)
858 VLANClientState *vc = opaque;
859 TAPState *s = vc->opaque;
861 return s ? s->has_vnet_hdr : 0;
864 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
866 VLANClientState *vc = opaque;
867 TAPState *s = vc->opaque;
869 if (!s || !s->has_vnet_hdr)
870 return;
872 s->using_vnet_hdr = using_vnet_hdr != 0;
875 static int tap_probe_vnet_hdr(int fd)
877 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
878 struct ifreq ifr;
880 if (ioctl(fd, TUNGETIFF, &ifr) != 0) {
881 fprintf(stderr, "TUNGETIFF ioctl() failed: %s\n", strerror(errno));
882 return 0;
885 return ifr.ifr_flags & IFF_VNET_HDR;
886 #else
887 return 0;
888 #endif
891 #ifdef TUNSETOFFLOAD
892 static void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6,
893 int ecn)
895 TAPState *s = vc->opaque;
896 unsigned int offload = 0;
898 if (csum) {
899 offload |= TUN_F_CSUM;
900 if (tso4)
901 offload |= TUN_F_TSO4;
902 if (tso6)
903 offload |= TUN_F_TSO6;
904 if ((tso4 || tso6) && ecn)
905 offload |= TUN_F_TSO_ECN;
908 if (ioctl(s->fd, TUNSETOFFLOAD, offload) != 0)
909 fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n",
910 strerror(errno));
912 #endif /* TUNSETOFFLOAD */
914 /* fd support */
916 static TAPState *net_tap_fd_init(VLANState *vlan,
917 const char *model,
918 const char *name,
919 int fd,
920 int vnet_hdr)
922 TAPState *s;
924 s = qemu_mallocz(sizeof(TAPState));
925 s->fd = fd;
926 s->has_vnet_hdr = vnet_hdr != 0;
927 s->vc = qemu_new_vlan_client(vlan, model, name, tap_receive, NULL, s);
928 #ifdef HAVE_IOVEC
929 s->vc->fd_readv = tap_receive_iov;
930 #endif
931 #ifdef TUNSETOFFLOAD
932 s->vc->set_offload = tap_set_offload;
933 #endif
934 qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
935 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
936 return s;
939 #if defined (HOST_BSD) || defined (__FreeBSD_kernel__)
940 static int tap_open(char *ifname, int ifname_size)
942 int fd;
943 char *dev;
944 struct stat s;
946 TFR(fd = open("/dev/tap", O_RDWR));
947 if (fd < 0) {
948 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
949 return -1;
952 fstat(fd, &s);
953 dev = devname(s.st_rdev, S_IFCHR);
954 pstrcpy(ifname, ifname_size, dev);
956 fcntl(fd, F_SETFL, O_NONBLOCK);
957 return fd;
959 #elif defined(__sun__)
960 #define TUNNEWPPA (('T'<<16) | 0x0001)
962 * Allocate TAP device, returns opened fd.
963 * Stores dev name in the first arg(must be large enough).
965 int tap_alloc(char *dev, size_t dev_size)
967 int tap_fd, if_fd, ppa = -1;
968 static int ip_fd = 0;
969 char *ptr;
971 static int arp_fd = 0;
972 int ip_muxid, arp_muxid;
973 struct strioctl strioc_if, strioc_ppa;
974 int link_type = I_PLINK;;
975 struct lifreq ifr;
976 char actual_name[32] = "";
978 memset(&ifr, 0x0, sizeof(ifr));
980 if( *dev ){
981 ptr = dev;
982 while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
983 ppa = atoi(ptr);
986 /* Check if IP device was opened */
987 if( ip_fd )
988 close(ip_fd);
990 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
991 if (ip_fd < 0) {
992 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
993 return -1;
996 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
997 if (tap_fd < 0) {
998 syslog(LOG_ERR, "Can't open /dev/tap");
999 return -1;
1002 /* Assign a new PPA and get its unit number. */
1003 strioc_ppa.ic_cmd = TUNNEWPPA;
1004 strioc_ppa.ic_timout = 0;
1005 strioc_ppa.ic_len = sizeof(ppa);
1006 strioc_ppa.ic_dp = (char *)&ppa;
1007 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
1008 syslog (LOG_ERR, "Can't assign new interface");
1010 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
1011 if (if_fd < 0) {
1012 syslog(LOG_ERR, "Can't open /dev/tap (2)");
1013 return -1;
1015 if(ioctl(if_fd, I_PUSH, "ip") < 0){
1016 syslog(LOG_ERR, "Can't push IP module");
1017 return -1;
1020 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
1021 syslog(LOG_ERR, "Can't get flags\n");
1023 snprintf (actual_name, 32, "tap%d", ppa);
1024 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1026 ifr.lifr_ppa = ppa;
1027 /* Assign ppa according to the unit number returned by tun device */
1029 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
1030 syslog (LOG_ERR, "Can't set PPA %d", ppa);
1031 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
1032 syslog (LOG_ERR, "Can't get flags\n");
1033 /* Push arp module to if_fd */
1034 if (ioctl (if_fd, I_PUSH, "arp") < 0)
1035 syslog (LOG_ERR, "Can't push ARP module (2)");
1037 /* Push arp module to ip_fd */
1038 if (ioctl (ip_fd, I_POP, NULL) < 0)
1039 syslog (LOG_ERR, "I_POP failed\n");
1040 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
1041 syslog (LOG_ERR, "Can't push ARP module (3)\n");
1042 /* Open arp_fd */
1043 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
1044 if (arp_fd < 0)
1045 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
1047 /* Set ifname to arp */
1048 strioc_if.ic_cmd = SIOCSLIFNAME;
1049 strioc_if.ic_timout = 0;
1050 strioc_if.ic_len = sizeof(ifr);
1051 strioc_if.ic_dp = (char *)&ifr;
1052 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
1053 syslog (LOG_ERR, "Can't set ifname to arp\n");
1056 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
1057 syslog(LOG_ERR, "Can't link TAP device to IP");
1058 return -1;
1061 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
1062 syslog (LOG_ERR, "Can't link TAP device to ARP");
1064 close (if_fd);
1066 memset(&ifr, 0x0, sizeof(ifr));
1067 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1068 ifr.lifr_ip_muxid = ip_muxid;
1069 ifr.lifr_arp_muxid = arp_muxid;
1071 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
1073 ioctl (ip_fd, I_PUNLINK , arp_muxid);
1074 ioctl (ip_fd, I_PUNLINK, ip_muxid);
1075 syslog (LOG_ERR, "Can't set multiplexor id");
1078 snprintf(dev, dev_size, "tap%d", ppa);
1079 return tap_fd;
1082 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1084 char dev[10]="";
1085 int fd;
1086 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
1087 fprintf(stderr, "Cannot allocate TAP device\n");
1088 return -1;
1090 pstrcpy(ifname, ifname_size, dev);
1091 fcntl(fd, F_SETFL, O_NONBLOCK);
1092 return fd;
1094 #elif defined (_AIX)
1095 static int tap_open(char *ifname, int ifname_size)
1097 fprintf (stderr, "no tap on AIX\n");
1098 return -1;
1100 #else
1101 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1103 struct ifreq ifr;
1104 int fd, ret;
1106 TFR(fd = open("/dev/net/tun", O_RDWR));
1107 if (fd < 0) {
1108 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1109 return -1;
1111 memset(&ifr, 0, sizeof(ifr));
1112 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1114 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
1116 unsigned int features;
1118 if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&
1119 features & IFF_VNET_HDR) {
1120 *vnet_hdr = 1;
1121 ifr.ifr_flags |= IFF_VNET_HDR;
1124 #endif
1126 if (ifname[0] != '\0')
1127 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
1128 else
1129 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
1130 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1131 if (ret != 0) {
1132 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1133 close(fd);
1134 return -1;
1136 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1137 fcntl(fd, F_SETFL, O_NONBLOCK);
1138 return fd;
1140 #endif
1142 static int launch_script(const char *setup_script, const char *ifname, int fd)
1144 int pid, status;
1145 char *args[3];
1146 char **parg;
1148 /* try to launch network script */
1149 pid = fork();
1150 if (pid >= 0) {
1151 if (pid == 0) {
1152 int open_max = sysconf (_SC_OPEN_MAX), i;
1153 for (i = 0; i < open_max; i++)
1154 if (i != STDIN_FILENO &&
1155 i != STDOUT_FILENO &&
1156 i != STDERR_FILENO &&
1157 i != fd)
1158 close(i);
1160 parg = args;
1161 *parg++ = (char *)setup_script;
1162 *parg++ = (char *)ifname;
1163 *parg++ = NULL;
1164 execv(setup_script, args);
1165 _exit(1);
1167 while (waitpid(pid, &status, 0) != pid);
1168 if (!WIFEXITED(status) ||
1169 WEXITSTATUS(status) != 0) {
1170 fprintf(stderr, "%s: could not launch network script\n",
1171 setup_script);
1172 return -1;
1175 return 0;
1178 static int net_tap_init(VLANState *vlan, const char *model,
1179 const char *name, const char *ifname1,
1180 const char *setup_script, const char *down_script)
1182 TAPState *s;
1183 int fd;
1184 int vnet_hdr;
1185 char ifname[128];
1187 if (ifname1 != NULL)
1188 pstrcpy(ifname, sizeof(ifname), ifname1);
1189 else
1190 ifname[0] = '\0';
1191 vnet_hdr = 0;
1192 TFR(fd = tap_open(ifname, sizeof(ifname), &vnet_hdr));
1193 if (fd < 0)
1194 return -1;
1196 if (!setup_script || !strcmp(setup_script, "no"))
1197 setup_script = "";
1198 if (setup_script[0] != '\0') {
1199 if (launch_script(setup_script, ifname, fd))
1200 return -1;
1202 s = net_tap_fd_init(vlan, model, name, fd, vnet_hdr);
1203 if (!s)
1204 return -1;
1206 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1207 "ifname=%s,script=%s,downscript=%s",
1208 ifname, setup_script, down_script);
1209 if (down_script && strcmp(down_script, "no")) {
1210 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1211 snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1213 return 0;
1216 #endif /* !_WIN32 */
1218 #if defined(CONFIG_VDE)
1219 typedef struct VDEState {
1220 VLANClientState *vc;
1221 VDECONN *vde;
1222 } VDEState;
1224 static void vde_to_qemu(void *opaque)
1226 VDEState *s = opaque;
1227 uint8_t buf[4096];
1228 int size;
1230 size = vde_recv(s->vde, buf, sizeof(buf), 0);
1231 if (size > 0) {
1232 qemu_send_packet(s->vc, buf, size);
1236 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
1238 VDEState *s = opaque;
1239 int ret;
1240 for(;;) {
1241 ret = vde_send(s->vde, buf, size, 0);
1242 if (ret < 0 && errno == EINTR) {
1243 } else {
1244 break;
1249 static int net_vde_init(VLANState *vlan, const char *model,
1250 const char *name, const char *sock,
1251 int port, const char *group, int mode)
1253 VDEState *s;
1254 char *init_group = strlen(group) ? (char *)group : NULL;
1255 char *init_sock = strlen(sock) ? (char *)sock : NULL;
1257 struct vde_open_args args = {
1258 .port = port,
1259 .group = init_group,
1260 .mode = mode,
1263 s = qemu_mallocz(sizeof(VDEState));
1264 s->vde = vde_open(init_sock, "QEMU", &args);
1265 if (!s->vde){
1266 free(s);
1267 return -1;
1269 s->vc = qemu_new_vlan_client(vlan, model, name, vde_from_qemu, NULL, s);
1270 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1271 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1272 sock, vde_datafd(s->vde));
1273 return 0;
1275 #endif
1277 /* network connection */
1278 typedef struct NetSocketState {
1279 VLANClientState *vc;
1280 int fd;
1281 int state; /* 0 = getting length, 1 = getting data */
1282 unsigned int index;
1283 unsigned int packet_len;
1284 uint8_t buf[4096];
1285 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1286 } NetSocketState;
1288 typedef struct NetSocketListenState {
1289 VLANState *vlan;
1290 char *model;
1291 char *name;
1292 int fd;
1293 } NetSocketListenState;
1295 /* XXX: we consider we can send the whole packet without blocking */
1296 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1298 NetSocketState *s = opaque;
1299 uint32_t len;
1300 len = htonl(size);
1302 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1303 send_all(s->fd, buf, size);
1306 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1308 NetSocketState *s = opaque;
1309 sendto(s->fd, buf, size, 0,
1310 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1313 static void net_socket_send(void *opaque)
1315 NetSocketState *s = opaque;
1316 int size, err;
1317 unsigned l;
1318 uint8_t buf1[4096];
1319 const uint8_t *buf;
1321 size = recv(s->fd, buf1, sizeof(buf1), 0);
1322 if (size < 0) {
1323 err = socket_error();
1324 if (err != EWOULDBLOCK)
1325 goto eoc;
1326 } else if (size == 0) {
1327 /* end of connection */
1328 eoc:
1329 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1330 closesocket(s->fd);
1331 return;
1333 buf = buf1;
1334 while (size > 0) {
1335 /* reassemble a packet from the network */
1336 switch(s->state) {
1337 case 0:
1338 l = 4 - s->index;
1339 if (l > size)
1340 l = size;
1341 memcpy(s->buf + s->index, buf, l);
1342 buf += l;
1343 size -= l;
1344 s->index += l;
1345 if (s->index == 4) {
1346 /* got length */
1347 s->packet_len = ntohl(*(uint32_t *)s->buf);
1348 s->index = 0;
1349 s->state = 1;
1351 break;
1352 case 1:
1353 l = s->packet_len - s->index;
1354 if (l > size)
1355 l = size;
1356 if (s->index + l <= sizeof(s->buf)) {
1357 memcpy(s->buf + s->index, buf, l);
1358 } else {
1359 fprintf(stderr, "serious error: oversized packet received,"
1360 "connection terminated.\n");
1361 s->state = 0;
1362 goto eoc;
1365 s->index += l;
1366 buf += l;
1367 size -= l;
1368 if (s->index >= s->packet_len) {
1369 qemu_send_packet(s->vc, s->buf, s->packet_len);
1370 s->index = 0;
1371 s->state = 0;
1373 break;
1378 static void net_socket_send_dgram(void *opaque)
1380 NetSocketState *s = opaque;
1381 int size;
1383 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1384 if (size < 0)
1385 return;
1386 if (size == 0) {
1387 /* end of connection */
1388 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1389 return;
1391 qemu_send_packet(s->vc, s->buf, size);
1394 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1396 struct ip_mreq imr;
1397 int fd;
1398 int val, ret;
1399 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1400 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1401 inet_ntoa(mcastaddr->sin_addr),
1402 (int)ntohl(mcastaddr->sin_addr.s_addr));
1403 return -1;
1406 fd = socket(PF_INET, SOCK_DGRAM, 0);
1407 if (fd < 0) {
1408 perror("socket(PF_INET, SOCK_DGRAM)");
1409 return -1;
1412 val = 1;
1413 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1414 (const char *)&val, sizeof(val));
1415 if (ret < 0) {
1416 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1417 goto fail;
1420 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1421 if (ret < 0) {
1422 perror("bind");
1423 goto fail;
1426 /* Add host to multicast group */
1427 imr.imr_multiaddr = mcastaddr->sin_addr;
1428 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1430 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1431 (const char *)&imr, sizeof(struct ip_mreq));
1432 if (ret < 0) {
1433 perror("setsockopt(IP_ADD_MEMBERSHIP)");
1434 goto fail;
1437 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1438 val = 1;
1439 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1440 (const char *)&val, sizeof(val));
1441 if (ret < 0) {
1442 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1443 goto fail;
1446 socket_set_nonblock(fd);
1447 return fd;
1448 fail:
1449 if (fd >= 0)
1450 closesocket(fd);
1451 return -1;
1454 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1455 const char *model,
1456 const char *name,
1457 int fd, int is_connected)
1459 struct sockaddr_in saddr;
1460 int newfd;
1461 socklen_t saddr_len;
1462 NetSocketState *s;
1464 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1465 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1466 * by ONLY ONE process: we must "clone" this dgram socket --jjo
1469 if (is_connected) {
1470 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1471 /* must be bound */
1472 if (saddr.sin_addr.s_addr==0) {
1473 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1474 fd);
1475 return NULL;
1477 /* clone dgram socket */
1478 newfd = net_socket_mcast_create(&saddr);
1479 if (newfd < 0) {
1480 /* error already reported by net_socket_mcast_create() */
1481 close(fd);
1482 return NULL;
1484 /* clone newfd to fd, close newfd */
1485 dup2(newfd, fd);
1486 close(newfd);
1488 } else {
1489 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1490 fd, strerror(errno));
1491 return NULL;
1495 s = qemu_mallocz(sizeof(NetSocketState));
1496 s->fd = fd;
1498 s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive_dgram, NULL, s);
1499 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1501 /* mcast: save bound address as dst */
1502 if (is_connected) s->dgram_dst=saddr;
1504 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1505 "socket: fd=%d (%s mcast=%s:%d)",
1506 fd, is_connected? "cloned" : "",
1507 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1508 return s;
1511 static void net_socket_connect(void *opaque)
1513 NetSocketState *s = opaque;
1514 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1517 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1518 const char *model,
1519 const char *name,
1520 int fd, int is_connected)
1522 NetSocketState *s;
1523 s = qemu_mallocz(sizeof(NetSocketState));
1524 s->fd = fd;
1525 s->vc = qemu_new_vlan_client(vlan, model, name,
1526 net_socket_receive, NULL, s);
1527 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1528 "socket: fd=%d", fd);
1529 if (is_connected) {
1530 net_socket_connect(s);
1531 } else {
1532 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1534 return s;
1537 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1538 const char *model, const char *name,
1539 int fd, int is_connected)
1541 int so_type=-1, optlen=sizeof(so_type);
1543 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1544 (socklen_t *)&optlen)< 0) {
1545 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1546 return NULL;
1548 switch(so_type) {
1549 case SOCK_DGRAM:
1550 return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1551 case SOCK_STREAM:
1552 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1553 default:
1554 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1555 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1556 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1558 return NULL;
1561 static void net_socket_accept(void *opaque)
1563 NetSocketListenState *s = opaque;
1564 NetSocketState *s1;
1565 struct sockaddr_in saddr;
1566 socklen_t len;
1567 int fd;
1569 for(;;) {
1570 len = sizeof(saddr);
1571 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1572 if (fd < 0 && errno != EINTR) {
1573 return;
1574 } else if (fd >= 0) {
1575 break;
1578 s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1579 if (!s1) {
1580 closesocket(fd);
1581 } else {
1582 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1583 "socket: connection from %s:%d",
1584 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1588 static int net_socket_listen_init(VLANState *vlan,
1589 const char *model,
1590 const char *name,
1591 const char *host_str)
1593 NetSocketListenState *s;
1594 int fd, val, ret;
1595 struct sockaddr_in saddr;
1597 if (parse_host_port(&saddr, host_str) < 0)
1598 return -1;
1600 s = qemu_mallocz(sizeof(NetSocketListenState));
1602 fd = socket(PF_INET, SOCK_STREAM, 0);
1603 if (fd < 0) {
1604 perror("socket");
1605 return -1;
1607 socket_set_nonblock(fd);
1609 /* allow fast reuse */
1610 val = 1;
1611 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1613 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1614 if (ret < 0) {
1615 perror("bind");
1616 return -1;
1618 ret = listen(fd, 0);
1619 if (ret < 0) {
1620 perror("listen");
1621 return -1;
1623 s->vlan = vlan;
1624 s->model = strdup(model);
1625 s->name = strdup(name);
1626 s->fd = fd;
1627 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1628 return 0;
1631 static int net_socket_connect_init(VLANState *vlan,
1632 const char *model,
1633 const char *name,
1634 const char *host_str)
1636 NetSocketState *s;
1637 int fd, connected, ret, err;
1638 struct sockaddr_in saddr;
1640 if (parse_host_port(&saddr, host_str) < 0)
1641 return -1;
1643 fd = socket(PF_INET, SOCK_STREAM, 0);
1644 if (fd < 0) {
1645 perror("socket");
1646 return -1;
1648 socket_set_nonblock(fd);
1650 connected = 0;
1651 for(;;) {
1652 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1653 if (ret < 0) {
1654 err = socket_error();
1655 if (err == EINTR || err == EWOULDBLOCK) {
1656 } else if (err == EINPROGRESS) {
1657 break;
1658 #ifdef _WIN32
1659 } else if (err == WSAEALREADY) {
1660 break;
1661 #endif
1662 } else {
1663 perror("connect");
1664 closesocket(fd);
1665 return -1;
1667 } else {
1668 connected = 1;
1669 break;
1672 s = net_socket_fd_init(vlan, model, name, fd, connected);
1673 if (!s)
1674 return -1;
1675 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1676 "socket: connect to %s:%d",
1677 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1678 return 0;
1681 static int net_socket_mcast_init(VLANState *vlan,
1682 const char *model,
1683 const char *name,
1684 const char *host_str)
1686 NetSocketState *s;
1687 int fd;
1688 struct sockaddr_in saddr;
1690 if (parse_host_port(&saddr, host_str) < 0)
1691 return -1;
1694 fd = net_socket_mcast_create(&saddr);
1695 if (fd < 0)
1696 return -1;
1698 s = net_socket_fd_init(vlan, model, name, fd, 0);
1699 if (!s)
1700 return -1;
1702 s->dgram_dst = saddr;
1704 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1705 "socket: mcast=%s:%d",
1706 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1707 return 0;
1711 /* find or alloc a new VLAN */
1712 VLANState *qemu_find_vlan(int id)
1714 VLANState **pvlan, *vlan;
1715 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1716 if (vlan->id == id)
1717 return vlan;
1719 vlan = qemu_mallocz(sizeof(VLANState));
1720 vlan->id = id;
1721 vlan->next = NULL;
1722 pvlan = &first_vlan;
1723 while (*pvlan != NULL)
1724 pvlan = &(*pvlan)->next;
1725 *pvlan = vlan;
1726 return vlan;
1729 static int nic_get_free_idx(void)
1731 int index;
1733 for (index = 0; index < MAX_NICS; index++)
1734 if (!nd_table[index].used)
1735 return index;
1736 return -1;
1739 void qemu_check_nic_model(NICInfo *nd, const char *model)
1741 const char *models[2];
1743 models[0] = model;
1744 models[1] = NULL;
1746 qemu_check_nic_model_list(nd, models, model);
1749 void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
1750 const char *default_model)
1752 int i, exit_status = 0;
1754 if (!nd->model)
1755 nd->model = strdup(default_model);
1757 if (strcmp(nd->model, "?") != 0) {
1758 for (i = 0 ; models[i]; i++)
1759 if (strcmp(nd->model, models[i]) == 0)
1760 return;
1762 fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
1763 exit_status = 1;
1766 fprintf(stderr, "qemu: Supported NIC models: ");
1767 for (i = 0 ; models[i]; i++)
1768 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1770 exit(exit_status);
1773 int net_client_init(const char *device, const char *p)
1775 char buf[1024];
1776 int vlan_id, ret;
1777 VLANState *vlan;
1778 char *name = NULL;
1780 vlan_id = 0;
1781 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1782 vlan_id = strtol(buf, NULL, 0);
1784 vlan = qemu_find_vlan(vlan_id);
1785 if (!vlan) {
1786 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
1787 return -1;
1789 if (get_param_value(buf, sizeof(buf), "name", p)) {
1790 name = strdup(buf);
1792 if (!strcmp(device, "nic")) {
1793 NICInfo *nd;
1794 uint8_t *macaddr;
1795 int idx = nic_get_free_idx();
1797 if (idx == -1 || nb_nics >= MAX_NICS) {
1798 fprintf(stderr, "Too Many NICs\n");
1799 return -1;
1801 nd = &nd_table[idx];
1802 macaddr = nd->macaddr;
1803 macaddr[0] = 0x52;
1804 macaddr[1] = 0x54;
1805 macaddr[2] = 0x00;
1806 macaddr[3] = 0x12;
1807 macaddr[4] = 0x34;
1808 macaddr[5] = 0x56 + idx;
1810 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1811 if (parse_macaddr(macaddr, buf) < 0) {
1812 fprintf(stderr, "invalid syntax for ethernet address\n");
1813 return -1;
1816 if (get_param_value(buf, sizeof(buf), "model", p)) {
1817 nd->model = strdup(buf);
1819 nd->vlan = vlan;
1820 nd->name = name;
1821 nd->used = 1;
1822 name = NULL;
1823 nb_nics++;
1824 vlan->nb_guest_devs++;
1825 ret = idx;
1826 } else
1827 if (!strcmp(device, "none")) {
1828 /* does nothing. It is needed to signal that no network cards
1829 are wanted */
1830 ret = 0;
1831 } else
1832 #ifdef CONFIG_SLIRP
1833 if (!strcmp(device, "user")) {
1834 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1835 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1837 if (get_param_value(buf, sizeof(buf), "restrict", p)) {
1838 slirp_restrict = (buf[0] == 'y') ? 1 : 0;
1840 if (get_param_value(buf, sizeof(buf), "ip", p)) {
1841 slirp_ip = strdup(buf);
1843 vlan->nb_host_devs++;
1844 ret = net_slirp_init(vlan, device, name);
1845 } else if (!strcmp(device, "channel")) {
1846 long port;
1847 char name[20], *devname;
1848 struct VMChannel *vmc;
1850 port = strtol(p, &devname, 10);
1851 devname++;
1852 if (port < 1 || port > 65535) {
1853 fprintf(stderr, "vmchannel wrong port number\n");
1854 return -1;
1856 vmc = malloc(sizeof(struct VMChannel));
1857 snprintf(name, 20, "vmchannel%ld", port);
1858 vmc->hd = qemu_chr_open(name, devname, NULL);
1859 if (!vmc->hd) {
1860 fprintf(stderr, "qemu: could not open vmchannel device"
1861 "'%s'\n", devname);
1862 return -1;
1864 vmc->port = port;
1865 slirp_add_exec(3, vmc->hd, 4, port);
1866 qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,
1867 NULL, vmc);
1868 ret = 0;
1869 } else
1870 #endif
1871 #ifdef _WIN32
1872 if (!strcmp(device, "tap")) {
1873 char ifname[64];
1874 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1875 fprintf(stderr, "tap: no interface name\n");
1876 return -1;
1878 vlan->nb_host_devs++;
1879 ret = tap_win32_init(vlan, device, name, ifname);
1880 } else
1881 #elif defined (_AIX)
1882 #else
1883 if (!strcmp(device, "tap")) {
1884 char ifname[64];
1885 char setup_script[1024], down_script[1024];
1886 int fd;
1887 vlan->nb_host_devs++;
1888 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1889 fd = strtol(buf, NULL, 0);
1890 fcntl(fd, F_SETFL, O_NONBLOCK);
1891 ret = -1;
1892 if (net_tap_fd_init(vlan, device, name, fd,
1893 tap_probe_vnet_hdr(fd)))
1894 ret = 0;
1895 } else {
1896 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1897 ifname[0] = '\0';
1899 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1900 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1902 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1903 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1905 ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
1907 } else
1908 #endif
1909 if (!strcmp(device, "socket")) {
1910 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1911 int fd;
1912 fd = strtol(buf, NULL, 0);
1913 ret = -1;
1914 if (net_socket_fd_init(vlan, device, name, fd, 1))
1915 ret = 0;
1916 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1917 ret = net_socket_listen_init(vlan, device, name, buf);
1918 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1919 ret = net_socket_connect_init(vlan, device, name, buf);
1920 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1921 ret = net_socket_mcast_init(vlan, device, name, buf);
1922 } else {
1923 fprintf(stderr, "Unknown socket options: %s\n", p);
1924 return -1;
1926 vlan->nb_host_devs++;
1927 } else
1928 #ifdef CONFIG_VDE
1929 if (!strcmp(device, "vde")) {
1930 char vde_sock[1024], vde_group[512];
1931 int vde_port, vde_mode;
1932 vlan->nb_host_devs++;
1933 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1934 vde_sock[0] = '\0';
1936 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1937 vde_port = strtol(buf, NULL, 10);
1938 } else {
1939 vde_port = 0;
1941 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1942 vde_group[0] = '\0';
1944 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1945 vde_mode = strtol(buf, NULL, 8);
1946 } else {
1947 vde_mode = 0700;
1949 ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
1950 } else
1951 #endif
1953 fprintf(stderr, "Unknown network device: %s\n", device);
1954 if (name)
1955 free(name);
1956 return -1;
1958 if (ret < 0) {
1959 fprintf(stderr, "Could not initialize device '%s'\n", device);
1961 if (name)
1962 free(name);
1963 return ret;
1966 void net_client_uninit(NICInfo *nd)
1968 nd->vlan->nb_guest_devs--;
1969 nb_nics--;
1970 nd->used = 0;
1971 free((void *)nd->model);
1974 static int net_host_check_device(const char *device)
1976 int i;
1977 const char *valid_param_list[] = { "tap", "socket"
1978 #ifdef CONFIG_SLIRP
1979 ,"user"
1980 #endif
1981 #ifdef CONFIG_VDE
1982 ,"vde"
1983 #endif
1985 for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
1986 if (!strncmp(valid_param_list[i], device,
1987 strlen(valid_param_list[i])))
1988 return 1;
1991 return 0;
1994 void net_host_device_add(Monitor *mon, const char *device, const char *opts)
1996 if (!net_host_check_device(device)) {
1997 monitor_printf(mon, "invalid host network device %s\n", device);
1998 return;
2000 net_client_init(device, opts);
2003 void net_host_device_remove(Monitor *mon, int vlan_id, const char *device)
2005 VLANState *vlan;
2006 VLANClientState *vc;
2008 vlan = qemu_find_vlan(vlan_id);
2009 if (!vlan) {
2010 monitor_printf(mon, "can't find vlan %d\n", vlan_id);
2011 return;
2014 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2015 if (!strcmp(vc->name, device))
2016 break;
2018 if (!vc) {
2019 monitor_printf(mon, "can't find device %s\n", device);
2020 return;
2022 qemu_del_vlan_client(vc);
2025 int net_client_parse(const char *str)
2027 const char *p;
2028 char *q;
2029 char device[64];
2031 p = str;
2032 q = device;
2033 while (*p != '\0' && *p != ',') {
2034 if ((q - device) < sizeof(device) - 1)
2035 *q++ = *p;
2036 p++;
2038 *q = '\0';
2039 if (*p == ',')
2040 p++;
2042 return net_client_init(device, p);
2045 void do_info_network(Monitor *mon)
2047 VLANState *vlan;
2048 VLANClientState *vc;
2050 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2051 monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
2052 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2053 monitor_printf(mon, " %s: %s\n", vc->name, vc->info_str);
2057 int do_set_link(Monitor *mon, const char *name, const char *up_or_down)
2059 VLANState *vlan;
2060 VLANClientState *vc = NULL;
2062 for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
2063 for (vc = vlan->first_client; vc != NULL; vc = vc->next)
2064 if (strcmp(vc->name, name) == 0)
2065 goto done;
2066 done:
2068 if (!vc) {
2069 monitor_printf(mon, "could not find network device '%s'", name);
2070 return 0;
2073 if (strcmp(up_or_down, "up") == 0)
2074 vc->link_down = 0;
2075 else if (strcmp(up_or_down, "down") == 0)
2076 vc->link_down = 1;
2077 else
2078 monitor_printf(mon, "invalid link status '%s'; only 'up' or 'down' "
2079 "valid\n", up_or_down);
2081 if (vc->link_status_changed)
2082 vc->link_status_changed(vc);
2084 return 1;
2087 void net_cleanup(void)
2089 VLANState *vlan;
2091 #if !defined(_WIN32)
2092 /* close network clients */
2093 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2094 VLANClientState *vc;
2096 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2097 if (vc->fd_read == tap_receive) {
2098 TAPState *s = vc->opaque;
2100 if (s->down_script[0])
2101 launch_script(s->down_script, s->down_script_arg, s->fd);
2103 #if defined(CONFIG_VDE)
2104 if (vc->fd_read == vde_from_qemu) {
2105 VDEState *s = vc->opaque;
2106 vde_close(s->vde);
2108 #endif
2111 #endif
2114 void net_client_check(void)
2116 VLANState *vlan;
2118 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2119 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
2120 continue;
2121 if (vlan->nb_guest_devs == 0)
2122 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
2123 if (vlan->nb_host_devs == 0)
2124 fprintf(stderr,
2125 "Warning: vlan %d is not connected to host network\n",
2126 vlan->id);