kvm: qemu: fix pci_enable_capabilities to set the CAP feature in pci::status
[kvm-userspace.git] / qemu / net.c
blob9c199d66616963bbbb6fff4ff9c0d1cfe02272b1
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 tap_set_offload(s->vc, 0, 0, 0, 0);
934 #endif
935 qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
936 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
937 return s;
940 #if defined (HOST_BSD) || defined (__FreeBSD_kernel__)
941 static int tap_open(char *ifname, int ifname_size)
943 int fd;
944 char *dev;
945 struct stat s;
947 TFR(fd = open("/dev/tap", O_RDWR));
948 if (fd < 0) {
949 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
950 return -1;
953 fstat(fd, &s);
954 dev = devname(s.st_rdev, S_IFCHR);
955 pstrcpy(ifname, ifname_size, dev);
957 fcntl(fd, F_SETFL, O_NONBLOCK);
958 return fd;
960 #elif defined(__sun__)
961 #define TUNNEWPPA (('T'<<16) | 0x0001)
963 * Allocate TAP device, returns opened fd.
964 * Stores dev name in the first arg(must be large enough).
966 int tap_alloc(char *dev, size_t dev_size)
968 int tap_fd, if_fd, ppa = -1;
969 static int ip_fd = 0;
970 char *ptr;
972 static int arp_fd = 0;
973 int ip_muxid, arp_muxid;
974 struct strioctl strioc_if, strioc_ppa;
975 int link_type = I_PLINK;;
976 struct lifreq ifr;
977 char actual_name[32] = "";
979 memset(&ifr, 0x0, sizeof(ifr));
981 if( *dev ){
982 ptr = dev;
983 while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
984 ppa = atoi(ptr);
987 /* Check if IP device was opened */
988 if( ip_fd )
989 close(ip_fd);
991 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
992 if (ip_fd < 0) {
993 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
994 return -1;
997 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
998 if (tap_fd < 0) {
999 syslog(LOG_ERR, "Can't open /dev/tap");
1000 return -1;
1003 /* Assign a new PPA and get its unit number. */
1004 strioc_ppa.ic_cmd = TUNNEWPPA;
1005 strioc_ppa.ic_timout = 0;
1006 strioc_ppa.ic_len = sizeof(ppa);
1007 strioc_ppa.ic_dp = (char *)&ppa;
1008 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
1009 syslog (LOG_ERR, "Can't assign new interface");
1011 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
1012 if (if_fd < 0) {
1013 syslog(LOG_ERR, "Can't open /dev/tap (2)");
1014 return -1;
1016 if(ioctl(if_fd, I_PUSH, "ip") < 0){
1017 syslog(LOG_ERR, "Can't push IP module");
1018 return -1;
1021 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
1022 syslog(LOG_ERR, "Can't get flags\n");
1024 snprintf (actual_name, 32, "tap%d", ppa);
1025 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1027 ifr.lifr_ppa = ppa;
1028 /* Assign ppa according to the unit number returned by tun device */
1030 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
1031 syslog (LOG_ERR, "Can't set PPA %d", ppa);
1032 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
1033 syslog (LOG_ERR, "Can't get flags\n");
1034 /* Push arp module to if_fd */
1035 if (ioctl (if_fd, I_PUSH, "arp") < 0)
1036 syslog (LOG_ERR, "Can't push ARP module (2)");
1038 /* Push arp module to ip_fd */
1039 if (ioctl (ip_fd, I_POP, NULL) < 0)
1040 syslog (LOG_ERR, "I_POP failed\n");
1041 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
1042 syslog (LOG_ERR, "Can't push ARP module (3)\n");
1043 /* Open arp_fd */
1044 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
1045 if (arp_fd < 0)
1046 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
1048 /* Set ifname to arp */
1049 strioc_if.ic_cmd = SIOCSLIFNAME;
1050 strioc_if.ic_timout = 0;
1051 strioc_if.ic_len = sizeof(ifr);
1052 strioc_if.ic_dp = (char *)&ifr;
1053 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
1054 syslog (LOG_ERR, "Can't set ifname to arp\n");
1057 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
1058 syslog(LOG_ERR, "Can't link TAP device to IP");
1059 return -1;
1062 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
1063 syslog (LOG_ERR, "Can't link TAP device to ARP");
1065 close (if_fd);
1067 memset(&ifr, 0x0, sizeof(ifr));
1068 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1069 ifr.lifr_ip_muxid = ip_muxid;
1070 ifr.lifr_arp_muxid = arp_muxid;
1072 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
1074 ioctl (ip_fd, I_PUNLINK , arp_muxid);
1075 ioctl (ip_fd, I_PUNLINK, ip_muxid);
1076 syslog (LOG_ERR, "Can't set multiplexor id");
1079 snprintf(dev, dev_size, "tap%d", ppa);
1080 return tap_fd;
1083 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1085 char dev[10]="";
1086 int fd;
1087 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
1088 fprintf(stderr, "Cannot allocate TAP device\n");
1089 return -1;
1091 pstrcpy(ifname, ifname_size, dev);
1092 fcntl(fd, F_SETFL, O_NONBLOCK);
1093 return fd;
1095 #elif defined (_AIX)
1096 static int tap_open(char *ifname, int ifname_size)
1098 fprintf (stderr, "no tap on AIX\n");
1099 return -1;
1101 #else
1102 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1104 struct ifreq ifr;
1105 int fd, ret;
1107 TFR(fd = open("/dev/net/tun", O_RDWR));
1108 if (fd < 0) {
1109 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1110 return -1;
1112 memset(&ifr, 0, sizeof(ifr));
1113 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1115 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
1117 unsigned int features;
1119 if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&
1120 features & IFF_VNET_HDR) {
1121 *vnet_hdr = 1;
1122 ifr.ifr_flags |= IFF_VNET_HDR;
1125 #endif
1127 if (ifname[0] != '\0')
1128 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
1129 else
1130 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
1131 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1132 if (ret != 0) {
1133 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1134 close(fd);
1135 return -1;
1137 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1138 fcntl(fd, F_SETFL, O_NONBLOCK);
1139 return fd;
1141 #endif
1143 static int launch_script(const char *setup_script, const char *ifname, int fd)
1145 int pid, status;
1146 char *args[3];
1147 char **parg;
1149 /* try to launch network script */
1150 pid = fork();
1151 if (pid >= 0) {
1152 if (pid == 0) {
1153 int open_max = sysconf (_SC_OPEN_MAX), i;
1154 for (i = 0; i < open_max; i++)
1155 if (i != STDIN_FILENO &&
1156 i != STDOUT_FILENO &&
1157 i != STDERR_FILENO &&
1158 i != fd)
1159 close(i);
1161 parg = args;
1162 *parg++ = (char *)setup_script;
1163 *parg++ = (char *)ifname;
1164 *parg++ = NULL;
1165 execv(setup_script, args);
1166 _exit(1);
1168 while (waitpid(pid, &status, 0) != pid);
1169 if (!WIFEXITED(status) ||
1170 WEXITSTATUS(status) != 0) {
1171 fprintf(stderr, "%s: could not launch network script\n",
1172 setup_script);
1173 return -1;
1176 return 0;
1179 static int net_tap_init(VLANState *vlan, const char *model,
1180 const char *name, const char *ifname1,
1181 const char *setup_script, const char *down_script)
1183 TAPState *s;
1184 int fd;
1185 int vnet_hdr;
1186 char ifname[128];
1188 if (ifname1 != NULL)
1189 pstrcpy(ifname, sizeof(ifname), ifname1);
1190 else
1191 ifname[0] = '\0';
1192 vnet_hdr = 0;
1193 TFR(fd = tap_open(ifname, sizeof(ifname), &vnet_hdr));
1194 if (fd < 0)
1195 return -1;
1197 if (!setup_script || !strcmp(setup_script, "no"))
1198 setup_script = "";
1199 if (setup_script[0] != '\0') {
1200 if (launch_script(setup_script, ifname, fd))
1201 return -1;
1203 s = net_tap_fd_init(vlan, model, name, fd, vnet_hdr);
1204 if (!s)
1205 return -1;
1207 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1208 "ifname=%s,script=%s,downscript=%s",
1209 ifname, setup_script, down_script);
1210 if (down_script && strcmp(down_script, "no")) {
1211 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1212 snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1214 return 0;
1217 #endif /* !_WIN32 */
1219 #if defined(CONFIG_VDE)
1220 typedef struct VDEState {
1221 VLANClientState *vc;
1222 VDECONN *vde;
1223 } VDEState;
1225 static void vde_to_qemu(void *opaque)
1227 VDEState *s = opaque;
1228 uint8_t buf[4096];
1229 int size;
1231 size = vde_recv(s->vde, buf, sizeof(buf), 0);
1232 if (size > 0) {
1233 qemu_send_packet(s->vc, buf, size);
1237 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
1239 VDEState *s = opaque;
1240 int ret;
1241 for(;;) {
1242 ret = vde_send(s->vde, buf, size, 0);
1243 if (ret < 0 && errno == EINTR) {
1244 } else {
1245 break;
1250 static int net_vde_init(VLANState *vlan, const char *model,
1251 const char *name, const char *sock,
1252 int port, const char *group, int mode)
1254 VDEState *s;
1255 char *init_group = strlen(group) ? (char *)group : NULL;
1256 char *init_sock = strlen(sock) ? (char *)sock : NULL;
1258 struct vde_open_args args = {
1259 .port = port,
1260 .group = init_group,
1261 .mode = mode,
1264 s = qemu_mallocz(sizeof(VDEState));
1265 s->vde = vde_open(init_sock, "QEMU", &args);
1266 if (!s->vde){
1267 free(s);
1268 return -1;
1270 s->vc = qemu_new_vlan_client(vlan, model, name, vde_from_qemu, NULL, s);
1271 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1272 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1273 sock, vde_datafd(s->vde));
1274 return 0;
1276 #endif
1278 /* network connection */
1279 typedef struct NetSocketState {
1280 VLANClientState *vc;
1281 int fd;
1282 int state; /* 0 = getting length, 1 = getting data */
1283 unsigned int index;
1284 unsigned int packet_len;
1285 uint8_t buf[4096];
1286 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1287 } NetSocketState;
1289 typedef struct NetSocketListenState {
1290 VLANState *vlan;
1291 char *model;
1292 char *name;
1293 int fd;
1294 } NetSocketListenState;
1296 /* XXX: we consider we can send the whole packet without blocking */
1297 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1299 NetSocketState *s = opaque;
1300 uint32_t len;
1301 len = htonl(size);
1303 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1304 send_all(s->fd, buf, size);
1307 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1309 NetSocketState *s = opaque;
1310 sendto(s->fd, buf, size, 0,
1311 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1314 static void net_socket_send(void *opaque)
1316 NetSocketState *s = opaque;
1317 int size, err;
1318 unsigned l;
1319 uint8_t buf1[4096];
1320 const uint8_t *buf;
1322 size = recv(s->fd, buf1, sizeof(buf1), 0);
1323 if (size < 0) {
1324 err = socket_error();
1325 if (err != EWOULDBLOCK)
1326 goto eoc;
1327 } else if (size == 0) {
1328 /* end of connection */
1329 eoc:
1330 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1331 closesocket(s->fd);
1332 return;
1334 buf = buf1;
1335 while (size > 0) {
1336 /* reassemble a packet from the network */
1337 switch(s->state) {
1338 case 0:
1339 l = 4 - s->index;
1340 if (l > size)
1341 l = size;
1342 memcpy(s->buf + s->index, buf, l);
1343 buf += l;
1344 size -= l;
1345 s->index += l;
1346 if (s->index == 4) {
1347 /* got length */
1348 s->packet_len = ntohl(*(uint32_t *)s->buf);
1349 s->index = 0;
1350 s->state = 1;
1352 break;
1353 case 1:
1354 l = s->packet_len - s->index;
1355 if (l > size)
1356 l = size;
1357 if (s->index + l <= sizeof(s->buf)) {
1358 memcpy(s->buf + s->index, buf, l);
1359 } else {
1360 fprintf(stderr, "serious error: oversized packet received,"
1361 "connection terminated.\n");
1362 s->state = 0;
1363 goto eoc;
1366 s->index += l;
1367 buf += l;
1368 size -= l;
1369 if (s->index >= s->packet_len) {
1370 qemu_send_packet(s->vc, s->buf, s->packet_len);
1371 s->index = 0;
1372 s->state = 0;
1374 break;
1379 static void net_socket_send_dgram(void *opaque)
1381 NetSocketState *s = opaque;
1382 int size;
1384 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1385 if (size < 0)
1386 return;
1387 if (size == 0) {
1388 /* end of connection */
1389 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1390 return;
1392 qemu_send_packet(s->vc, s->buf, size);
1395 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1397 struct ip_mreq imr;
1398 int fd;
1399 int val, ret;
1400 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1401 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1402 inet_ntoa(mcastaddr->sin_addr),
1403 (int)ntohl(mcastaddr->sin_addr.s_addr));
1404 return -1;
1407 fd = socket(PF_INET, SOCK_DGRAM, 0);
1408 if (fd < 0) {
1409 perror("socket(PF_INET, SOCK_DGRAM)");
1410 return -1;
1413 val = 1;
1414 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1415 (const char *)&val, sizeof(val));
1416 if (ret < 0) {
1417 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1418 goto fail;
1421 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1422 if (ret < 0) {
1423 perror("bind");
1424 goto fail;
1427 /* Add host to multicast group */
1428 imr.imr_multiaddr = mcastaddr->sin_addr;
1429 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1431 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1432 (const char *)&imr, sizeof(struct ip_mreq));
1433 if (ret < 0) {
1434 perror("setsockopt(IP_ADD_MEMBERSHIP)");
1435 goto fail;
1438 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1439 val = 1;
1440 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1441 (const char *)&val, sizeof(val));
1442 if (ret < 0) {
1443 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1444 goto fail;
1447 socket_set_nonblock(fd);
1448 return fd;
1449 fail:
1450 if (fd >= 0)
1451 closesocket(fd);
1452 return -1;
1455 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1456 const char *model,
1457 const char *name,
1458 int fd, int is_connected)
1460 struct sockaddr_in saddr;
1461 int newfd;
1462 socklen_t saddr_len;
1463 NetSocketState *s;
1465 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1466 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1467 * by ONLY ONE process: we must "clone" this dgram socket --jjo
1470 if (is_connected) {
1471 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1472 /* must be bound */
1473 if (saddr.sin_addr.s_addr==0) {
1474 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1475 fd);
1476 return NULL;
1478 /* clone dgram socket */
1479 newfd = net_socket_mcast_create(&saddr);
1480 if (newfd < 0) {
1481 /* error already reported by net_socket_mcast_create() */
1482 close(fd);
1483 return NULL;
1485 /* clone newfd to fd, close newfd */
1486 dup2(newfd, fd);
1487 close(newfd);
1489 } else {
1490 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1491 fd, strerror(errno));
1492 return NULL;
1496 s = qemu_mallocz(sizeof(NetSocketState));
1497 s->fd = fd;
1499 s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive_dgram, NULL, s);
1500 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1502 /* mcast: save bound address as dst */
1503 if (is_connected) s->dgram_dst=saddr;
1505 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1506 "socket: fd=%d (%s mcast=%s:%d)",
1507 fd, is_connected? "cloned" : "",
1508 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1509 return s;
1512 static void net_socket_connect(void *opaque)
1514 NetSocketState *s = opaque;
1515 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1518 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1519 const char *model,
1520 const char *name,
1521 int fd, int is_connected)
1523 NetSocketState *s;
1524 s = qemu_mallocz(sizeof(NetSocketState));
1525 s->fd = fd;
1526 s->vc = qemu_new_vlan_client(vlan, model, name,
1527 net_socket_receive, NULL, s);
1528 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1529 "socket: fd=%d", fd);
1530 if (is_connected) {
1531 net_socket_connect(s);
1532 } else {
1533 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1535 return s;
1538 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1539 const char *model, const char *name,
1540 int fd, int is_connected)
1542 int so_type=-1, optlen=sizeof(so_type);
1544 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1545 (socklen_t *)&optlen)< 0) {
1546 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1547 return NULL;
1549 switch(so_type) {
1550 case SOCK_DGRAM:
1551 return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1552 case SOCK_STREAM:
1553 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1554 default:
1555 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1556 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1557 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1559 return NULL;
1562 static void net_socket_accept(void *opaque)
1564 NetSocketListenState *s = opaque;
1565 NetSocketState *s1;
1566 struct sockaddr_in saddr;
1567 socklen_t len;
1568 int fd;
1570 for(;;) {
1571 len = sizeof(saddr);
1572 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1573 if (fd < 0 && errno != EINTR) {
1574 return;
1575 } else if (fd >= 0) {
1576 break;
1579 s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1580 if (!s1) {
1581 closesocket(fd);
1582 } else {
1583 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1584 "socket: connection from %s:%d",
1585 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1589 static int net_socket_listen_init(VLANState *vlan,
1590 const char *model,
1591 const char *name,
1592 const char *host_str)
1594 NetSocketListenState *s;
1595 int fd, val, ret;
1596 struct sockaddr_in saddr;
1598 if (parse_host_port(&saddr, host_str) < 0)
1599 return -1;
1601 s = qemu_mallocz(sizeof(NetSocketListenState));
1603 fd = socket(PF_INET, SOCK_STREAM, 0);
1604 if (fd < 0) {
1605 perror("socket");
1606 return -1;
1608 socket_set_nonblock(fd);
1610 /* allow fast reuse */
1611 val = 1;
1612 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1614 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1615 if (ret < 0) {
1616 perror("bind");
1617 return -1;
1619 ret = listen(fd, 0);
1620 if (ret < 0) {
1621 perror("listen");
1622 return -1;
1624 s->vlan = vlan;
1625 s->model = strdup(model);
1626 s->name = strdup(name);
1627 s->fd = fd;
1628 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1629 return 0;
1632 static int net_socket_connect_init(VLANState *vlan,
1633 const char *model,
1634 const char *name,
1635 const char *host_str)
1637 NetSocketState *s;
1638 int fd, connected, ret, err;
1639 struct sockaddr_in saddr;
1641 if (parse_host_port(&saddr, host_str) < 0)
1642 return -1;
1644 fd = socket(PF_INET, SOCK_STREAM, 0);
1645 if (fd < 0) {
1646 perror("socket");
1647 return -1;
1649 socket_set_nonblock(fd);
1651 connected = 0;
1652 for(;;) {
1653 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1654 if (ret < 0) {
1655 err = socket_error();
1656 if (err == EINTR || err == EWOULDBLOCK) {
1657 } else if (err == EINPROGRESS) {
1658 break;
1659 #ifdef _WIN32
1660 } else if (err == WSAEALREADY) {
1661 break;
1662 #endif
1663 } else {
1664 perror("connect");
1665 closesocket(fd);
1666 return -1;
1668 } else {
1669 connected = 1;
1670 break;
1673 s = net_socket_fd_init(vlan, model, name, fd, connected);
1674 if (!s)
1675 return -1;
1676 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1677 "socket: connect to %s:%d",
1678 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1679 return 0;
1682 static int net_socket_mcast_init(VLANState *vlan,
1683 const char *model,
1684 const char *name,
1685 const char *host_str)
1687 NetSocketState *s;
1688 int fd;
1689 struct sockaddr_in saddr;
1691 if (parse_host_port(&saddr, host_str) < 0)
1692 return -1;
1695 fd = net_socket_mcast_create(&saddr);
1696 if (fd < 0)
1697 return -1;
1699 s = net_socket_fd_init(vlan, model, name, fd, 0);
1700 if (!s)
1701 return -1;
1703 s->dgram_dst = saddr;
1705 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1706 "socket: mcast=%s:%d",
1707 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1708 return 0;
1712 /* find or alloc a new VLAN */
1713 VLANState *qemu_find_vlan(int id)
1715 VLANState **pvlan, *vlan;
1716 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1717 if (vlan->id == id)
1718 return vlan;
1720 vlan = qemu_mallocz(sizeof(VLANState));
1721 vlan->id = id;
1722 vlan->next = NULL;
1723 pvlan = &first_vlan;
1724 while (*pvlan != NULL)
1725 pvlan = &(*pvlan)->next;
1726 *pvlan = vlan;
1727 return vlan;
1730 static int nic_get_free_idx(void)
1732 int index;
1734 for (index = 0; index < MAX_NICS; index++)
1735 if (!nd_table[index].used)
1736 return index;
1737 return -1;
1740 void qemu_check_nic_model(NICInfo *nd, const char *model)
1742 const char *models[2];
1744 models[0] = model;
1745 models[1] = NULL;
1747 qemu_check_nic_model_list(nd, models, model);
1750 void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
1751 const char *default_model)
1753 int i, exit_status = 0;
1755 if (!nd->model)
1756 nd->model = strdup(default_model);
1758 if (strcmp(nd->model, "?") != 0) {
1759 for (i = 0 ; models[i]; i++)
1760 if (strcmp(nd->model, models[i]) == 0)
1761 return;
1763 fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
1764 exit_status = 1;
1767 fprintf(stderr, "qemu: Supported NIC models: ");
1768 for (i = 0 ; models[i]; i++)
1769 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1771 exit(exit_status);
1774 int net_client_init(const char *device, const char *p)
1776 char buf[1024];
1777 int vlan_id, ret;
1778 VLANState *vlan;
1779 char *name = NULL;
1781 vlan_id = 0;
1782 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1783 vlan_id = strtol(buf, NULL, 0);
1785 vlan = qemu_find_vlan(vlan_id);
1786 if (!vlan) {
1787 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
1788 return -1;
1790 if (get_param_value(buf, sizeof(buf), "name", p)) {
1791 name = strdup(buf);
1793 if (!strcmp(device, "nic")) {
1794 NICInfo *nd;
1795 uint8_t *macaddr;
1796 int idx = nic_get_free_idx();
1798 if (idx == -1 || nb_nics >= MAX_NICS) {
1799 fprintf(stderr, "Too Many NICs\n");
1800 return -1;
1802 nd = &nd_table[idx];
1803 macaddr = nd->macaddr;
1804 macaddr[0] = 0x52;
1805 macaddr[1] = 0x54;
1806 macaddr[2] = 0x00;
1807 macaddr[3] = 0x12;
1808 macaddr[4] = 0x34;
1809 macaddr[5] = 0x56 + idx;
1811 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1812 if (parse_macaddr(macaddr, buf) < 0) {
1813 fprintf(stderr, "invalid syntax for ethernet address\n");
1814 return -1;
1817 if (get_param_value(buf, sizeof(buf), "model", p)) {
1818 nd->model = strdup(buf);
1820 nd->vlan = vlan;
1821 nd->name = name;
1822 nd->used = 1;
1823 name = NULL;
1824 nb_nics++;
1825 vlan->nb_guest_devs++;
1826 ret = idx;
1827 } else
1828 if (!strcmp(device, "none")) {
1829 /* does nothing. It is needed to signal that no network cards
1830 are wanted */
1831 ret = 0;
1832 } else
1833 #ifdef CONFIG_SLIRP
1834 if (!strcmp(device, "user")) {
1835 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1836 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1838 if (get_param_value(buf, sizeof(buf), "restrict", p)) {
1839 slirp_restrict = (buf[0] == 'y') ? 1 : 0;
1841 if (get_param_value(buf, sizeof(buf), "ip", p)) {
1842 slirp_ip = strdup(buf);
1844 vlan->nb_host_devs++;
1845 ret = net_slirp_init(vlan, device, name);
1846 } else if (!strcmp(device, "channel")) {
1847 long port;
1848 char name[20], *devname;
1849 struct VMChannel *vmc;
1851 port = strtol(p, &devname, 10);
1852 devname++;
1853 if (port < 1 || port > 65535) {
1854 fprintf(stderr, "vmchannel wrong port number\n");
1855 return -1;
1857 vmc = malloc(sizeof(struct VMChannel));
1858 snprintf(name, 20, "vmchannel%ld", port);
1859 vmc->hd = qemu_chr_open(name, devname, NULL);
1860 if (!vmc->hd) {
1861 fprintf(stderr, "qemu: could not open vmchannel device"
1862 "'%s'\n", devname);
1863 return -1;
1865 vmc->port = port;
1866 slirp_add_exec(3, vmc->hd, 4, port);
1867 qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,
1868 NULL, vmc);
1869 ret = 0;
1870 } else
1871 #endif
1872 #ifdef _WIN32
1873 if (!strcmp(device, "tap")) {
1874 char ifname[64];
1875 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1876 fprintf(stderr, "tap: no interface name\n");
1877 return -1;
1879 vlan->nb_host_devs++;
1880 ret = tap_win32_init(vlan, device, name, ifname);
1881 } else
1882 #elif defined (_AIX)
1883 #else
1884 if (!strcmp(device, "tap")) {
1885 char ifname[64];
1886 char setup_script[1024], down_script[1024];
1887 int fd;
1888 vlan->nb_host_devs++;
1889 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1890 fd = strtol(buf, NULL, 0);
1891 fcntl(fd, F_SETFL, O_NONBLOCK);
1892 ret = -1;
1893 if (net_tap_fd_init(vlan, device, name, fd,
1894 tap_probe_vnet_hdr(fd)))
1895 ret = 0;
1896 } else {
1897 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1898 ifname[0] = '\0';
1900 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1901 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1903 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1904 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1906 ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
1908 } else
1909 #endif
1910 if (!strcmp(device, "socket")) {
1911 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1912 int fd;
1913 fd = strtol(buf, NULL, 0);
1914 ret = -1;
1915 if (net_socket_fd_init(vlan, device, name, fd, 1))
1916 ret = 0;
1917 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1918 ret = net_socket_listen_init(vlan, device, name, buf);
1919 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1920 ret = net_socket_connect_init(vlan, device, name, buf);
1921 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1922 ret = net_socket_mcast_init(vlan, device, name, buf);
1923 } else {
1924 fprintf(stderr, "Unknown socket options: %s\n", p);
1925 return -1;
1927 vlan->nb_host_devs++;
1928 } else
1929 #ifdef CONFIG_VDE
1930 if (!strcmp(device, "vde")) {
1931 char vde_sock[1024], vde_group[512];
1932 int vde_port, vde_mode;
1933 vlan->nb_host_devs++;
1934 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1935 vde_sock[0] = '\0';
1937 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1938 vde_port = strtol(buf, NULL, 10);
1939 } else {
1940 vde_port = 0;
1942 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1943 vde_group[0] = '\0';
1945 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1946 vde_mode = strtol(buf, NULL, 8);
1947 } else {
1948 vde_mode = 0700;
1950 ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
1951 } else
1952 #endif
1954 fprintf(stderr, "Unknown network device: %s\n", device);
1955 if (name)
1956 free(name);
1957 return -1;
1959 if (ret < 0) {
1960 fprintf(stderr, "Could not initialize device '%s'\n", device);
1962 if (name)
1963 free(name);
1964 return ret;
1967 void net_client_uninit(NICInfo *nd)
1969 nd->vlan->nb_guest_devs--;
1970 nb_nics--;
1971 nd->used = 0;
1972 free((void *)nd->model);
1975 static int net_host_check_device(const char *device)
1977 int i;
1978 const char *valid_param_list[] = { "tap", "socket"
1979 #ifdef CONFIG_SLIRP
1980 ,"user"
1981 #endif
1982 #ifdef CONFIG_VDE
1983 ,"vde"
1984 #endif
1986 for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
1987 if (!strncmp(valid_param_list[i], device,
1988 strlen(valid_param_list[i])))
1989 return 1;
1992 return 0;
1995 void net_host_device_add(Monitor *mon, const char *device, const char *opts)
1997 if (!net_host_check_device(device)) {
1998 monitor_printf(mon, "invalid host network device %s\n", device);
1999 return;
2001 net_client_init(device, opts);
2004 void net_host_device_remove(Monitor *mon, int vlan_id, const char *device)
2006 VLANState *vlan;
2007 VLANClientState *vc;
2009 vlan = qemu_find_vlan(vlan_id);
2010 if (!vlan) {
2011 monitor_printf(mon, "can't find vlan %d\n", vlan_id);
2012 return;
2015 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2016 if (!strcmp(vc->name, device))
2017 break;
2019 if (!vc) {
2020 monitor_printf(mon, "can't find device %s\n", device);
2021 return;
2023 qemu_del_vlan_client(vc);
2026 int net_client_parse(const char *str)
2028 const char *p;
2029 char *q;
2030 char device[64];
2032 p = str;
2033 q = device;
2034 while (*p != '\0' && *p != ',') {
2035 if ((q - device) < sizeof(device) - 1)
2036 *q++ = *p;
2037 p++;
2039 *q = '\0';
2040 if (*p == ',')
2041 p++;
2043 return net_client_init(device, p);
2046 void do_info_network(Monitor *mon)
2048 VLANState *vlan;
2049 VLANClientState *vc;
2051 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2052 monitor_printf(mon, "VLAN %d devices:\n", vlan->id);
2053 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2054 monitor_printf(mon, " %s: %s\n", vc->name, vc->info_str);
2058 int do_set_link(Monitor *mon, const char *name, const char *up_or_down)
2060 VLANState *vlan;
2061 VLANClientState *vc = NULL;
2063 for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
2064 for (vc = vlan->first_client; vc != NULL; vc = vc->next)
2065 if (strcmp(vc->name, name) == 0)
2066 goto done;
2067 done:
2069 if (!vc) {
2070 monitor_printf(mon, "could not find network device '%s'", name);
2071 return 0;
2074 if (strcmp(up_or_down, "up") == 0)
2075 vc->link_down = 0;
2076 else if (strcmp(up_or_down, "down") == 0)
2077 vc->link_down = 1;
2078 else
2079 monitor_printf(mon, "invalid link status '%s'; only 'up' or 'down' "
2080 "valid\n", up_or_down);
2082 if (vc->link_status_changed)
2083 vc->link_status_changed(vc);
2085 return 1;
2088 void net_cleanup(void)
2090 #if !defined(_WIN32)
2091 VLANState *vlan;
2093 /* close network clients */
2094 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2095 VLANClientState *vc;
2097 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2098 if (vc->fd_read == tap_receive) {
2099 TAPState *s = vc->opaque;
2101 if (s->down_script[0])
2102 launch_script(s->down_script, s->down_script_arg, s->fd);
2104 #if defined(CONFIG_VDE)
2105 if (vc->fd_read == vde_from_qemu) {
2106 VDEState *s = vc->opaque;
2107 vde_close(s->vde);
2109 #endif
2112 #endif
2115 void net_client_check(void)
2117 VLANState *vlan;
2119 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2120 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
2121 continue;
2122 if (vlan->nb_guest_devs == 0)
2123 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
2124 if (vlan->nb_host_devs == 0)
2125 fprintf(stderr,
2126 "Warning: vlan %d is not connected to host network\n",
2127 vlan->id);