Regenerate bios for pci mmio page alignment
[qemu-kvm/fedora.git] / net.c
blobd352ebb9a4ebd499d6add692e0822f45dffdbe07
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 "qemu-common.h"
25 #include "net.h"
26 #include "console.h"
27 #include "sysemu.h"
28 #include "qemu-timer.h"
29 #include "qemu-char.h"
30 #include "audio/audio.h"
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <signal.h>
35 #include <time.h>
36 #include <errno.h>
37 #include <sys/time.h>
38 #include <zlib.h>
40 #ifndef _WIN32
41 #include <sys/times.h>
42 #include <sys/wait.h>
43 #include <termios.h>
44 #include <sys/mman.h>
45 #include <sys/ioctl.h>
46 #include <sys/resource.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #include <net/if.h>
50 #ifdef __NetBSD__
51 #include <net/if_tap.h>
52 #endif
53 #ifdef __linux__
54 #include <linux/if_tun.h>
55 #endif
56 #include <arpa/inet.h>
57 #include <dirent.h>
58 #include <netdb.h>
59 #include <sys/select.h>
60 #ifdef _BSD
61 #include <sys/stat.h>
62 #ifdef __FreeBSD__
63 #include <libutil.h>
64 #else
65 #include <util.h>
66 #endif
67 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
68 #include <freebsd/stdlib.h>
69 #else
70 #ifdef __linux__
71 #include <pty.h>
72 #include <malloc.h>
73 #include <linux/rtc.h>
75 /* For the benefit of older linux systems which don't supply it,
76 we use a local copy of hpet.h. */
77 /* #include <linux/hpet.h> */
78 #include "hpet.h"
80 #include <linux/ppdev.h>
81 #include <linux/parport.h>
82 #endif
83 #ifdef __sun__
84 #include <sys/stat.h>
85 #include <sys/ethernet.h>
86 #include <sys/sockio.h>
87 #include <netinet/arp.h>
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h> // must come after ip.h
92 #include <netinet/udp.h>
93 #include <netinet/tcp.h>
94 #include <net/if.h>
95 #include <syslog.h>
96 #include <stropts.h>
97 #endif
98 #endif
99 #endif
101 #include "qemu_socket.h"
103 #if defined(CONFIG_SLIRP)
104 #include "libslirp.h"
105 #endif
107 #if defined(__OpenBSD__)
108 #include <util.h>
109 #endif
111 #if defined(CONFIG_VDE)
112 #include <libvdeplug.h>
113 #endif
115 #ifdef _WIN32
116 #include <malloc.h>
117 #include <sys/timeb.h>
118 #include <mmsystem.h>
119 #define getopt_long_only getopt_long
120 #define memalign(align, size) malloc(size)
121 #endif
123 // FIXME: #include "qemu-kvm.h"
125 static VLANState *first_vlan;
127 /***********************************************************/
128 /* network device redirectors */
130 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
131 static void hex_dump(FILE *f, const uint8_t *buf, int size)
133 int len, i, j, c;
135 for(i=0;i<size;i+=16) {
136 len = size - i;
137 if (len > 16)
138 len = 16;
139 fprintf(f, "%08x ", i);
140 for(j=0;j<16;j++) {
141 if (j < len)
142 fprintf(f, " %02x", buf[i+j]);
143 else
144 fprintf(f, " ");
146 fprintf(f, " ");
147 for(j=0;j<len;j++) {
148 c = buf[i+j];
149 if (c < ' ' || c > '~')
150 c = '.';
151 fprintf(f, "%c", c);
153 fprintf(f, "\n");
156 #endif
158 static int parse_macaddr(uint8_t *macaddr, const char *p)
160 int i;
161 char *last_char;
162 long int offset;
164 errno = 0;
165 offset = strtol(p, &last_char, 0);
166 if (0 == errno && '\0' == *last_char &&
167 offset >= 0 && offset <= 0xFFFFFF) {
168 macaddr[3] = (offset & 0xFF0000) >> 16;
169 macaddr[4] = (offset & 0xFF00) >> 8;
170 macaddr[5] = offset & 0xFF;
171 return 0;
172 } else {
173 for(i = 0; i < 6; i++) {
174 macaddr[i] = strtol(p, (char **)&p, 16);
175 if (i == 5) {
176 if (*p != '\0')
177 return -1;
178 } else {
179 if (*p != ':' && *p != '-')
180 return -1;
181 p++;
184 return 0;
187 return -1;
190 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
192 const char *p, *p1;
193 int len;
194 p = *pp;
195 p1 = strchr(p, sep);
196 if (!p1)
197 return -1;
198 len = p1 - p;
199 p1++;
200 if (buf_size > 0) {
201 if (len > buf_size - 1)
202 len = buf_size - 1;
203 memcpy(buf, p, len);
204 buf[len] = '\0';
206 *pp = p1;
207 return 0;
210 int parse_host_src_port(struct sockaddr_in *haddr,
211 struct sockaddr_in *saddr,
212 const char *input_str)
214 char *str = strdup(input_str);
215 char *host_str = str;
216 char *src_str;
217 const char *src_str2;
218 char *ptr;
221 * Chop off any extra arguments at the end of the string which
222 * would start with a comma, then fill in the src port information
223 * if it was provided else use the "any address" and "any port".
225 if ((ptr = strchr(str,',')))
226 *ptr = '\0';
228 if ((src_str = strchr(input_str,'@'))) {
229 *src_str = '\0';
230 src_str++;
233 if (parse_host_port(haddr, host_str) < 0)
234 goto fail;
236 src_str2 = src_str;
237 if (!src_str || *src_str == '\0')
238 src_str2 = ":0";
240 if (parse_host_port(saddr, src_str2) < 0)
241 goto fail;
243 free(str);
244 return(0);
246 fail:
247 free(str);
248 return -1;
251 int parse_host_port(struct sockaddr_in *saddr, const char *str)
253 char buf[512];
254 struct hostent *he;
255 const char *p, *r;
256 int port;
258 p = str;
259 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
260 return -1;
261 saddr->sin_family = AF_INET;
262 if (buf[0] == '\0') {
263 saddr->sin_addr.s_addr = 0;
264 } else {
265 if (qemu_isdigit(buf[0])) {
266 if (!inet_aton(buf, &saddr->sin_addr))
267 return -1;
268 } else {
269 if ((he = gethostbyname(buf)) == NULL)
270 return - 1;
271 saddr->sin_addr = *(struct in_addr *)he->h_addr;
274 port = strtol(p, (char **)&r, 0);
275 if (r == p)
276 return -1;
277 saddr->sin_port = htons(port);
278 return 0;
281 #if !defined(_WIN32) && 0
282 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
284 const char *p;
285 int len;
287 len = MIN(108, strlen(str));
288 p = strchr(str, ',');
289 if (p)
290 len = MIN(len, p - str);
292 memset(uaddr, 0, sizeof(*uaddr));
294 uaddr->sun_family = AF_UNIX;
295 memcpy(uaddr->sun_path, str, len);
297 return 0;
299 #endif
301 void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6])
303 snprintf(vc->info_str, sizeof(vc->info_str),
304 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
305 vc->model,
306 macaddr[0], macaddr[1], macaddr[2],
307 macaddr[3], macaddr[4], macaddr[5]);
310 static char *assign_name(VLANClientState *vc1, const char *model)
312 VLANState *vlan;
313 char buf[256];
314 int id = 0;
316 for (vlan = first_vlan; vlan; vlan = vlan->next) {
317 VLANClientState *vc;
319 for (vc = vlan->first_client; vc; vc = vc->next)
320 if (vc != vc1 && strcmp(vc->model, model) == 0)
321 id++;
324 snprintf(buf, sizeof(buf), "%s.%d", model, id);
326 return strdup(buf);
329 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
330 const char *model,
331 const char *name,
332 IOReadHandler *fd_read,
333 IOCanRWHandler *fd_can_read,
334 void *opaque)
336 VLANClientState *vc, **pvc;
337 vc = qemu_mallocz(sizeof(VLANClientState));
338 vc->model = strdup(model);
339 if (name)
340 vc->name = strdup(name);
341 else
342 vc->name = assign_name(vc, model);
343 vc->fd_read = fd_read;
344 vc->fd_can_read = fd_can_read;
345 vc->opaque = opaque;
346 vc->vlan = vlan;
348 vc->next = NULL;
349 pvc = &vlan->first_client;
350 while (*pvc != NULL)
351 pvc = &(*pvc)->next;
352 *pvc = vc;
353 return vc;
356 void qemu_del_vlan_client(VLANClientState *vc)
358 VLANClientState **pvc = &vc->vlan->first_client;
360 while (*pvc != NULL)
361 if (*pvc == vc) {
362 *pvc = vc->next;
363 free(vc->name);
364 free(vc->model);
365 free(vc);
366 break;
367 } else
368 pvc = &(*pvc)->next;
371 VLANClientState *qemu_find_vlan_client(VLANState *vlan, void *opaque)
373 VLANClientState **pvc = &vlan->first_client;
375 while (*pvc != NULL)
376 if ((*pvc)->opaque == opaque)
377 return *pvc;
378 else
379 pvc = &(*pvc)->next;
381 return NULL;
384 int qemu_can_send_packet(VLANClientState *vc1)
386 VLANState *vlan = vc1->vlan;
387 VLANClientState *vc;
389 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
390 if (vc != vc1) {
391 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
392 return 1;
395 return 0;
398 int qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
400 VLANState *vlan = vc1->vlan;
401 VLANClientState *vc;
402 int ret = -EAGAIN;
404 if (vc1->link_down)
405 return 0;
407 #ifdef DEBUG_NET
408 printf("vlan %d send:\n", vlan->id);
409 hex_dump(stdout, buf, size);
410 #endif
411 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
412 if (vc != vc1 && !vc->link_down) {
413 if (!vc->fd_can_read || vc->fd_can_read(vc->opaque)) {
414 vc->fd_read(vc->opaque, buf, size);
415 ret = 0;
419 return ret;
422 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
423 int iovcnt)
425 uint8_t buffer[4096];
426 size_t offset = 0;
427 int i;
429 for (i = 0; i < iovcnt; i++) {
430 size_t len;
432 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
433 memcpy(buffer + offset, iov[i].iov_base, len);
434 offset += len;
437 vc->fd_read(vc->opaque, buffer, offset);
439 return offset;
442 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
444 size_t offset = 0;
445 int i;
447 for (i = 0; i < iovcnt; i++)
448 offset += iov[i].iov_len;
449 return offset;
452 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
453 int iovcnt)
455 VLANState *vlan = vc1->vlan;
456 VLANClientState *vc;
457 ssize_t max_len = 0;
459 if (vc1->link_down)
460 return calc_iov_length(iov, iovcnt);
462 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
463 ssize_t len = 0;
465 if (vc == vc1)
466 continue;
468 if (vc->link_down)
469 len = calc_iov_length(iov, iovcnt);
470 if (vc->fd_readv)
471 len = vc->fd_readv(vc->opaque, iov, iovcnt);
472 else if (vc->fd_read)
473 len = vc_sendv_compat(vc, iov, iovcnt);
475 max_len = MAX(max_len, len);
478 return max_len;
481 #if defined(CONFIG_SLIRP)
483 /* slirp network adapter */
485 static int slirp_inited;
486 static int slirp_restrict;
487 static char *slirp_ip;
488 static VLANClientState *slirp_vc;
490 int slirp_can_output(void)
492 return !slirp_vc || qemu_can_send_packet(slirp_vc);
495 void slirp_output(const uint8_t *pkt, int pkt_len)
497 #ifdef DEBUG_SLIRP
498 printf("slirp output:\n");
499 hex_dump(stdout, pkt, pkt_len);
500 #endif
501 if (!slirp_vc)
502 return;
503 qemu_send_packet(slirp_vc, pkt, pkt_len);
506 int slirp_is_inited(void)
508 return slirp_inited;
511 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
513 #ifdef DEBUG_SLIRP
514 printf("slirp input:\n");
515 hex_dump(stdout, buf, size);
516 #endif
517 slirp_input(buf, size);
520 static int net_slirp_init(VLANState *vlan, const char *model, const char *name)
522 if (!slirp_inited) {
523 slirp_inited = 1;
524 slirp_init(slirp_restrict, slirp_ip);
526 slirp_vc = qemu_new_vlan_client(vlan, model, name,
527 slirp_receive, NULL, NULL);
528 slirp_vc->info_str[0] = '\0';
529 return 0;
532 void net_slirp_redir(const char *redir_str)
534 int is_udp;
535 char buf[256], *r;
536 const char *p;
537 struct in_addr guest_addr;
538 int host_port, guest_port;
540 if (!slirp_inited) {
541 slirp_inited = 1;
542 slirp_init(slirp_restrict, slirp_ip);
545 p = redir_str;
546 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
547 goto fail;
548 if (!strcmp(buf, "tcp")) {
549 is_udp = 0;
550 } else if (!strcmp(buf, "udp")) {
551 is_udp = 1;
552 } else {
553 goto fail;
556 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
557 goto fail;
558 host_port = strtol(buf, &r, 0);
559 if (r == buf)
560 goto fail;
562 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
563 goto fail;
564 if (buf[0] == '\0') {
565 pstrcpy(buf, sizeof(buf), "10.0.2.15");
567 if (!inet_aton(buf, &guest_addr))
568 goto fail;
570 guest_port = strtol(p, &r, 0);
571 if (r == p)
572 goto fail;
574 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
575 fprintf(stderr, "qemu: could not set up redirection\n");
576 exit(1);
578 return;
579 fail:
580 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
581 exit(1);
584 #ifndef _WIN32
586 static char smb_dir[1024];
588 static void erase_dir(char *dir_name)
590 DIR *d;
591 struct dirent *de;
592 char filename[1024];
594 /* erase all the files in the directory */
595 if ((d = opendir(dir_name)) != 0) {
596 for(;;) {
597 de = readdir(d);
598 if (!de)
599 break;
600 if (strcmp(de->d_name, ".") != 0 &&
601 strcmp(de->d_name, "..") != 0) {
602 snprintf(filename, sizeof(filename), "%s/%s",
603 smb_dir, de->d_name);
604 if (unlink(filename) != 0) /* is it a directory? */
605 erase_dir(filename);
608 closedir(d);
609 rmdir(dir_name);
613 /* automatic user mode samba server configuration */
614 static void smb_exit(void)
616 erase_dir(smb_dir);
619 /* automatic user mode samba server configuration */
620 void net_slirp_smb(const char *exported_dir)
622 char smb_conf[1024];
623 char smb_cmdline[1024];
624 FILE *f;
626 if (!slirp_inited) {
627 slirp_inited = 1;
628 slirp_init(slirp_restrict, slirp_ip);
631 /* XXX: better tmp dir construction */
632 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
633 if (mkdir(smb_dir, 0700) < 0) {
634 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
635 exit(1);
637 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
639 f = fopen(smb_conf, "w");
640 if (!f) {
641 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
642 exit(1);
644 fprintf(f,
645 "[global]\n"
646 "private dir=%s\n"
647 "smb ports=0\n"
648 "socket address=127.0.0.1\n"
649 "pid directory=%s\n"
650 "lock directory=%s\n"
651 "log file=%s/log.smbd\n"
652 "smb passwd file=%s/smbpasswd\n"
653 "security = share\n"
654 "[qemu]\n"
655 "path=%s\n"
656 "read only=no\n"
657 "guest ok=yes\n",
658 smb_dir,
659 smb_dir,
660 smb_dir,
661 smb_dir,
662 smb_dir,
663 exported_dir
665 fclose(f);
666 atexit(smb_exit);
668 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
669 SMBD_COMMAND, smb_conf);
671 slirp_add_exec(0, smb_cmdline, 4, 139);
674 #endif /* !defined(_WIN32) */
675 void do_info_slirp(void)
677 slirp_stats();
680 struct VMChannel {
681 CharDriverState *hd;
682 int port;
683 } *vmchannels;
685 static int vmchannel_can_read(void *opaque)
687 struct VMChannel *vmc = (struct VMChannel*)opaque;
688 return slirp_socket_can_recv(4, vmc->port);
691 static void vmchannel_read(void *opaque, const uint8_t *buf, int size)
693 struct VMChannel *vmc = (struct VMChannel*)opaque;
694 slirp_socket_recv(4, vmc->port, buf, size);
697 #endif /* CONFIG_SLIRP */
699 #ifdef _WIN32
701 int tap_has_vnet_hdr(void *opaque)
703 return 0;
706 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
710 #else /* !defined(_WIN32) */
712 /* Maximum GSO packet size (64k) plus plenty of room for
713 * the ethernet and virtio_net headers
715 #define TAP_BUFSIZE (4096 + 65536)
717 #ifdef IFF_VNET_HDR
718 #include <linux/virtio_net.h>
719 #endif
721 typedef struct TAPState {
722 VLANClientState *vc;
723 int fd;
724 char down_script[1024];
725 char down_script_arg[128];
726 char buf[TAP_BUFSIZE];
727 int size;
728 unsigned int has_vnet_hdr : 1;
729 unsigned int using_vnet_hdr : 1;
730 } TAPState;
732 #ifdef HAVE_IOVEC
733 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
734 int iovcnt)
736 TAPState *s = opaque;
737 ssize_t len;
739 do {
740 len = writev(s->fd, iov, iovcnt);
741 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
743 return len;
745 #endif
747 static void tap_receive(void *opaque, const uint8_t *buf, int size)
749 struct iovec iov[2];
750 int i = 0;
752 #ifdef IFF_VNET_HDR
753 TAPState *s = opaque;
754 struct virtio_net_hdr hdr = { 0, };
756 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
757 iov[i].iov_base = &hdr;
758 iov[i].iov_len = sizeof(hdr);
759 i++;
761 #endif
763 iov[i].iov_base = (char *) buf;
764 iov[i].iov_len = size;
765 i++;
767 tap_receive_iov(opaque, iov, i);
770 static int tap_can_send(void *opaque)
772 TAPState *s = opaque;
773 VLANClientState *vc;
774 int can_receive = 0;
776 /* Check to see if any of our clients can receive a packet */
777 for (vc = s->vc->vlan->first_client; vc; vc = vc->next) {
778 /* Skip ourselves */
779 if (vc == s->vc)
780 continue;
782 if (!vc->fd_can_read) {
783 /* no fd_can_read handler, they always can receive */
784 can_receive = 1;
785 } else
786 can_receive = vc->fd_can_read(vc->opaque);
788 /* Once someone can receive, we try to send a packet */
789 if (can_receive)
790 break;
793 return can_receive;
796 static int tap_send_packet(TAPState *s)
798 uint8_t *buf = (uint8_t *)s->buf;
799 int size = s->size;
801 #ifdef IFF_VNET_HDR
802 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
803 buf += sizeof(struct virtio_net_hdr);
804 size -= sizeof(struct virtio_net_hdr);
806 #endif
808 return qemu_send_packet(s->vc, buf, size);
811 static void tap_send(void *opaque)
813 TAPState *s = opaque;
815 /* First try to send any buffered packet */
816 if (s->size > 0) {
817 int err;
819 /* If noone can receive the packet, buffer it */
820 err = tap_send_packet(s);
821 if (err == -EAGAIN)
822 return;
825 /* Read packets until we hit EAGAIN */
826 do {
827 #ifdef __sun__
828 struct strbuf sbuf;
829 int f = 0;
830 sbuf.maxlen = sizeof(s->buf);
831 sbuf.buf = s->buf;
832 s->size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
833 #else
834 // FIXME: kvm_sleep_begin();
835 s->size = read(s->fd, s->buf, sizeof(s->buf));
836 // FIXME: kvm_sleep_end();
837 #endif
839 if (s->size == -1 && errno == EINTR)
840 continue;
842 if (s->size > 0) {
843 int err;
845 /* If noone can receive the packet, buffer it */
846 err = tap_send_packet(s);
847 if (err == -EAGAIN)
848 break;
850 } while (s->size > 0);
853 int tap_has_vnet_hdr(void *opaque)
855 VLANClientState *vc = opaque;
856 TAPState *s = vc->opaque;
858 return s ? s->has_vnet_hdr : 0;
861 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
863 VLANClientState *vc = opaque;
864 TAPState *s = vc->opaque;
866 if (!s || !s->has_vnet_hdr)
867 return;
869 s->using_vnet_hdr = using_vnet_hdr != 0;
872 static int tap_probe_vnet_hdr(int fd)
874 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
875 struct ifreq ifr;
877 if (ioctl(fd, TUNGETIFF, &ifr) != 0) {
878 fprintf(stderr, "TUNGETIFF ioctl() failed: %s\n", strerror(errno));
879 return 0;
882 return ifr.ifr_flags & IFF_VNET_HDR;
883 #else
884 return 0;
885 #endif
888 #ifdef TUNSETOFFLOAD
889 static void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6,
890 int ecn)
892 TAPState *s = vc->opaque;
893 unsigned int offload = 0;
895 if (csum) {
896 offload |= TUN_F_CSUM;
897 if (tso4)
898 offload |= TUN_F_TSO4;
899 if (tso6)
900 offload |= TUN_F_TSO6;
901 if ((tso4 || tso6) && ecn)
902 offload |= TUN_F_TSO_ECN;
905 if (ioctl(s->fd, TUNSETOFFLOAD, offload) != 0)
906 fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n",
907 strerror(errno));
909 #endif /* TUNSETOFFLOAD */
911 /* fd support */
913 static TAPState *net_tap_fd_init(VLANState *vlan,
914 const char *model,
915 const char *name,
916 int fd,
917 int vnet_hdr)
919 TAPState *s;
921 s = qemu_mallocz(sizeof(TAPState));
922 s->fd = fd;
923 s->has_vnet_hdr = vnet_hdr != 0;
924 s->vc = qemu_new_vlan_client(vlan, model, name, tap_receive, NULL, s);
925 #ifdef HAVE_IOVEC
926 s->vc->fd_readv = tap_receive_iov;
927 #endif
928 #ifdef TUNSETOFFLOAD
929 s->vc->set_offload = tap_set_offload;
930 #endif
931 qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
932 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
933 return s;
936 #if defined (_BSD) || defined (__FreeBSD_kernel__)
937 static int tap_open(char *ifname, int ifname_size)
939 int fd;
940 char *dev;
941 struct stat s;
943 TFR(fd = open("/dev/tap", O_RDWR));
944 if (fd < 0) {
945 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
946 return -1;
949 fstat(fd, &s);
950 dev = devname(s.st_rdev, S_IFCHR);
951 pstrcpy(ifname, ifname_size, dev);
953 fcntl(fd, F_SETFL, O_NONBLOCK);
954 return fd;
956 #elif defined(__sun__)
957 #define TUNNEWPPA (('T'<<16) | 0x0001)
959 * Allocate TAP device, returns opened fd.
960 * Stores dev name in the first arg(must be large enough).
962 int tap_alloc(char *dev, size_t dev_size)
964 int tap_fd, if_fd, ppa = -1;
965 static int ip_fd = 0;
966 char *ptr;
968 static int arp_fd = 0;
969 int ip_muxid, arp_muxid;
970 struct strioctl strioc_if, strioc_ppa;
971 int link_type = I_PLINK;;
972 struct lifreq ifr;
973 char actual_name[32] = "";
975 memset(&ifr, 0x0, sizeof(ifr));
977 if( *dev ){
978 ptr = dev;
979 while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
980 ppa = atoi(ptr);
983 /* Check if IP device was opened */
984 if( ip_fd )
985 close(ip_fd);
987 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
988 if (ip_fd < 0) {
989 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
990 return -1;
993 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
994 if (tap_fd < 0) {
995 syslog(LOG_ERR, "Can't open /dev/tap");
996 return -1;
999 /* Assign a new PPA and get its unit number. */
1000 strioc_ppa.ic_cmd = TUNNEWPPA;
1001 strioc_ppa.ic_timout = 0;
1002 strioc_ppa.ic_len = sizeof(ppa);
1003 strioc_ppa.ic_dp = (char *)&ppa;
1004 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
1005 syslog (LOG_ERR, "Can't assign new interface");
1007 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
1008 if (if_fd < 0) {
1009 syslog(LOG_ERR, "Can't open /dev/tap (2)");
1010 return -1;
1012 if(ioctl(if_fd, I_PUSH, "ip") < 0){
1013 syslog(LOG_ERR, "Can't push IP module");
1014 return -1;
1017 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
1018 syslog(LOG_ERR, "Can't get flags\n");
1020 snprintf (actual_name, 32, "tap%d", ppa);
1021 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1023 ifr.lifr_ppa = ppa;
1024 /* Assign ppa according to the unit number returned by tun device */
1026 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
1027 syslog (LOG_ERR, "Can't set PPA %d", ppa);
1028 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
1029 syslog (LOG_ERR, "Can't get flags\n");
1030 /* Push arp module to if_fd */
1031 if (ioctl (if_fd, I_PUSH, "arp") < 0)
1032 syslog (LOG_ERR, "Can't push ARP module (2)");
1034 /* Push arp module to ip_fd */
1035 if (ioctl (ip_fd, I_POP, NULL) < 0)
1036 syslog (LOG_ERR, "I_POP failed\n");
1037 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
1038 syslog (LOG_ERR, "Can't push ARP module (3)\n");
1039 /* Open arp_fd */
1040 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
1041 if (arp_fd < 0)
1042 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
1044 /* Set ifname to arp */
1045 strioc_if.ic_cmd = SIOCSLIFNAME;
1046 strioc_if.ic_timout = 0;
1047 strioc_if.ic_len = sizeof(ifr);
1048 strioc_if.ic_dp = (char *)&ifr;
1049 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
1050 syslog (LOG_ERR, "Can't set ifname to arp\n");
1053 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
1054 syslog(LOG_ERR, "Can't link TAP device to IP");
1055 return -1;
1058 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
1059 syslog (LOG_ERR, "Can't link TAP device to ARP");
1061 close (if_fd);
1063 memset(&ifr, 0x0, sizeof(ifr));
1064 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1065 ifr.lifr_ip_muxid = ip_muxid;
1066 ifr.lifr_arp_muxid = arp_muxid;
1068 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
1070 ioctl (ip_fd, I_PUNLINK , arp_muxid);
1071 ioctl (ip_fd, I_PUNLINK, ip_muxid);
1072 syslog (LOG_ERR, "Can't set multiplexor id");
1075 snprintf(dev, dev_size, "tap%d", ppa);
1076 return tap_fd;
1079 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1081 char dev[10]="";
1082 int fd;
1083 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
1084 fprintf(stderr, "Cannot allocate TAP device\n");
1085 return -1;
1087 pstrcpy(ifname, ifname_size, dev);
1088 fcntl(fd, F_SETFL, O_NONBLOCK);
1089 return fd;
1091 #elif defined (_AIX)
1092 static int tap_open(char *ifname, int ifname_size)
1094 fprintf (stderr, "no tap on AIX\n");
1095 return -1;
1097 #else
1098 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1100 struct ifreq ifr;
1101 int fd, ret;
1103 TFR(fd = open("/dev/net/tun", O_RDWR));
1104 if (fd < 0) {
1105 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1106 return -1;
1108 memset(&ifr, 0, sizeof(ifr));
1109 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1111 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
1113 unsigned int features;
1115 if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&
1116 features & IFF_VNET_HDR) {
1117 *vnet_hdr = 1;
1118 ifr.ifr_flags |= IFF_VNET_HDR;
1121 #endif
1123 if (ifname[0] != '\0')
1124 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
1125 else
1126 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
1127 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1128 if (ret != 0) {
1129 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1130 close(fd);
1131 return -1;
1133 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1134 fcntl(fd, F_SETFL, O_NONBLOCK);
1135 return fd;
1137 #endif
1139 static int launch_script(const char *setup_script, const char *ifname, int fd)
1141 int pid, status;
1142 char *args[3];
1143 char **parg;
1145 /* try to launch network script */
1146 pid = fork();
1147 if (pid >= 0) {
1148 if (pid == 0) {
1149 int open_max = sysconf (_SC_OPEN_MAX), i;
1150 for (i = 0; i < open_max; i++)
1151 if (i != STDIN_FILENO &&
1152 i != STDOUT_FILENO &&
1153 i != STDERR_FILENO &&
1154 i != fd)
1155 close(i);
1157 parg = args;
1158 *parg++ = (char *)setup_script;
1159 *parg++ = (char *)ifname;
1160 *parg++ = NULL;
1161 execv(setup_script, args);
1162 _exit(1);
1164 while (waitpid(pid, &status, 0) != pid);
1165 if (!WIFEXITED(status) ||
1166 WEXITSTATUS(status) != 0) {
1167 fprintf(stderr, "%s: could not launch network script\n",
1168 setup_script);
1169 return -1;
1172 return 0;
1175 static int net_tap_init(VLANState *vlan, const char *model,
1176 const char *name, const char *ifname1,
1177 const char *setup_script, const char *down_script)
1179 TAPState *s;
1180 int fd;
1181 int vnet_hdr;
1182 char ifname[128];
1184 if (ifname1 != NULL)
1185 pstrcpy(ifname, sizeof(ifname), ifname1);
1186 else
1187 ifname[0] = '\0';
1188 vnet_hdr = 0;
1189 TFR(fd = tap_open(ifname, sizeof(ifname), &vnet_hdr));
1190 if (fd < 0)
1191 return -1;
1193 if (!setup_script || !strcmp(setup_script, "no"))
1194 setup_script = "";
1195 if (setup_script[0] != '\0') {
1196 if (launch_script(setup_script, ifname, fd))
1197 return -1;
1199 s = net_tap_fd_init(vlan, model, name, fd, vnet_hdr);
1200 if (!s)
1201 return -1;
1203 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1204 "ifname=%s,script=%s,downscript=%s",
1205 ifname, setup_script, down_script);
1206 if (down_script && strcmp(down_script, "no")) {
1207 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1208 snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1210 return 0;
1213 #endif /* !_WIN32 */
1215 #if defined(CONFIG_VDE)
1216 typedef struct VDEState {
1217 VLANClientState *vc;
1218 VDECONN *vde;
1219 } VDEState;
1221 static void vde_to_qemu(void *opaque)
1223 VDEState *s = opaque;
1224 uint8_t buf[4096];
1225 int size;
1227 size = vde_recv(s->vde, buf, sizeof(buf), 0);
1228 if (size > 0) {
1229 qemu_send_packet(s->vc, buf, size);
1233 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
1235 VDEState *s = opaque;
1236 int ret;
1237 for(;;) {
1238 ret = vde_send(s->vde, buf, size, 0);
1239 if (ret < 0 && errno == EINTR) {
1240 } else {
1241 break;
1246 static int net_vde_init(VLANState *vlan, const char *model,
1247 const char *name, const char *sock,
1248 int port, const char *group, int mode)
1250 VDEState *s;
1251 char *init_group = strlen(group) ? (char *)group : NULL;
1252 char *init_sock = strlen(sock) ? (char *)sock : NULL;
1254 struct vde_open_args args = {
1255 .port = port,
1256 .group = init_group,
1257 .mode = mode,
1260 s = qemu_mallocz(sizeof(VDEState));
1261 s->vde = vde_open(init_sock, "QEMU", &args);
1262 if (!s->vde){
1263 free(s);
1264 return -1;
1266 s->vc = qemu_new_vlan_client(vlan, model, name, vde_from_qemu, NULL, s);
1267 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1268 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1269 sock, vde_datafd(s->vde));
1270 return 0;
1272 #endif
1274 /* network connection */
1275 typedef struct NetSocketState {
1276 VLANClientState *vc;
1277 int fd;
1278 int state; /* 0 = getting length, 1 = getting data */
1279 int index;
1280 int packet_len;
1281 uint8_t buf[4096];
1282 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1283 } NetSocketState;
1285 typedef struct NetSocketListenState {
1286 VLANState *vlan;
1287 char *model;
1288 char *name;
1289 int fd;
1290 } NetSocketListenState;
1292 /* XXX: we consider we can send the whole packet without blocking */
1293 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1295 NetSocketState *s = opaque;
1296 uint32_t len;
1297 len = htonl(size);
1299 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1300 send_all(s->fd, buf, size);
1303 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1305 NetSocketState *s = opaque;
1306 sendto(s->fd, buf, size, 0,
1307 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1310 static void net_socket_send(void *opaque)
1312 NetSocketState *s = opaque;
1313 int l, size, err;
1314 uint8_t buf1[4096];
1315 const uint8_t *buf;
1317 size = recv(s->fd, buf1, sizeof(buf1), 0);
1318 if (size < 0) {
1319 err = socket_error();
1320 if (err != EWOULDBLOCK)
1321 goto eoc;
1322 } else if (size == 0) {
1323 /* end of connection */
1324 eoc:
1325 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1326 closesocket(s->fd);
1327 return;
1329 buf = buf1;
1330 while (size > 0) {
1331 /* reassemble a packet from the network */
1332 switch(s->state) {
1333 case 0:
1334 l = 4 - s->index;
1335 if (l > size)
1336 l = size;
1337 memcpy(s->buf + s->index, buf, l);
1338 buf += l;
1339 size -= l;
1340 s->index += l;
1341 if (s->index == 4) {
1342 /* got length */
1343 s->packet_len = ntohl(*(uint32_t *)s->buf);
1344 s->index = 0;
1345 s->state = 1;
1347 break;
1348 case 1:
1349 l = s->packet_len - s->index;
1350 if (l > size)
1351 l = size;
1352 memcpy(s->buf + s->index, buf, l);
1353 s->index += l;
1354 buf += l;
1355 size -= l;
1356 if (s->index >= s->packet_len) {
1357 qemu_send_packet(s->vc, s->buf, s->packet_len);
1358 s->index = 0;
1359 s->state = 0;
1361 break;
1366 static void net_socket_send_dgram(void *opaque)
1368 NetSocketState *s = opaque;
1369 int size;
1371 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1372 if (size < 0)
1373 return;
1374 if (size == 0) {
1375 /* end of connection */
1376 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1377 return;
1379 qemu_send_packet(s->vc, s->buf, size);
1382 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1384 struct ip_mreq imr;
1385 int fd;
1386 int val, ret;
1387 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1388 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1389 inet_ntoa(mcastaddr->sin_addr),
1390 (int)ntohl(mcastaddr->sin_addr.s_addr));
1391 return -1;
1394 fd = socket(PF_INET, SOCK_DGRAM, 0);
1395 if (fd < 0) {
1396 perror("socket(PF_INET, SOCK_DGRAM)");
1397 return -1;
1400 val = 1;
1401 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1402 (const char *)&val, sizeof(val));
1403 if (ret < 0) {
1404 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1405 goto fail;
1408 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1409 if (ret < 0) {
1410 perror("bind");
1411 goto fail;
1414 /* Add host to multicast group */
1415 imr.imr_multiaddr = mcastaddr->sin_addr;
1416 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1418 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1419 (const char *)&imr, sizeof(struct ip_mreq));
1420 if (ret < 0) {
1421 perror("setsockopt(IP_ADD_MEMBERSHIP)");
1422 goto fail;
1425 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1426 val = 1;
1427 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1428 (const char *)&val, sizeof(val));
1429 if (ret < 0) {
1430 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1431 goto fail;
1434 socket_set_nonblock(fd);
1435 return fd;
1436 fail:
1437 if (fd >= 0)
1438 closesocket(fd);
1439 return -1;
1442 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1443 const char *model,
1444 const char *name,
1445 int fd, int is_connected)
1447 struct sockaddr_in saddr;
1448 int newfd;
1449 socklen_t saddr_len;
1450 NetSocketState *s;
1452 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1453 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1454 * by ONLY ONE process: we must "clone" this dgram socket --jjo
1457 if (is_connected) {
1458 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1459 /* must be bound */
1460 if (saddr.sin_addr.s_addr==0) {
1461 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1462 fd);
1463 return NULL;
1465 /* clone dgram socket */
1466 newfd = net_socket_mcast_create(&saddr);
1467 if (newfd < 0) {
1468 /* error already reported by net_socket_mcast_create() */
1469 close(fd);
1470 return NULL;
1472 /* clone newfd to fd, close newfd */
1473 dup2(newfd, fd);
1474 close(newfd);
1476 } else {
1477 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1478 fd, strerror(errno));
1479 return NULL;
1483 s = qemu_mallocz(sizeof(NetSocketState));
1484 s->fd = fd;
1486 s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive_dgram, NULL, s);
1487 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1489 /* mcast: save bound address as dst */
1490 if (is_connected) s->dgram_dst=saddr;
1492 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1493 "socket: fd=%d (%s mcast=%s:%d)",
1494 fd, is_connected? "cloned" : "",
1495 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1496 return s;
1499 static void net_socket_connect(void *opaque)
1501 NetSocketState *s = opaque;
1502 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1505 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1506 const char *model,
1507 const char *name,
1508 int fd, int is_connected)
1510 NetSocketState *s;
1511 s = qemu_mallocz(sizeof(NetSocketState));
1512 s->fd = fd;
1513 s->vc = qemu_new_vlan_client(vlan, model, name,
1514 net_socket_receive, NULL, s);
1515 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1516 "socket: fd=%d", fd);
1517 if (is_connected) {
1518 net_socket_connect(s);
1519 } else {
1520 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1522 return s;
1525 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1526 const char *model, const char *name,
1527 int fd, int is_connected)
1529 int so_type=-1, optlen=sizeof(so_type);
1531 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1532 (socklen_t *)&optlen)< 0) {
1533 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1534 return NULL;
1536 switch(so_type) {
1537 case SOCK_DGRAM:
1538 return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1539 case SOCK_STREAM:
1540 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1541 default:
1542 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1543 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1544 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1546 return NULL;
1549 static void net_socket_accept(void *opaque)
1551 NetSocketListenState *s = opaque;
1552 NetSocketState *s1;
1553 struct sockaddr_in saddr;
1554 socklen_t len;
1555 int fd;
1557 for(;;) {
1558 len = sizeof(saddr);
1559 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1560 if (fd < 0 && errno != EINTR) {
1561 return;
1562 } else if (fd >= 0) {
1563 break;
1566 s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1567 if (!s1) {
1568 closesocket(fd);
1569 } else {
1570 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1571 "socket: connection from %s:%d",
1572 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1576 static int net_socket_listen_init(VLANState *vlan,
1577 const char *model,
1578 const char *name,
1579 const char *host_str)
1581 NetSocketListenState *s;
1582 int fd, val, ret;
1583 struct sockaddr_in saddr;
1585 if (parse_host_port(&saddr, host_str) < 0)
1586 return -1;
1588 s = qemu_mallocz(sizeof(NetSocketListenState));
1590 fd = socket(PF_INET, SOCK_STREAM, 0);
1591 if (fd < 0) {
1592 perror("socket");
1593 return -1;
1595 socket_set_nonblock(fd);
1597 /* allow fast reuse */
1598 val = 1;
1599 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1601 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1602 if (ret < 0) {
1603 perror("bind");
1604 return -1;
1606 ret = listen(fd, 0);
1607 if (ret < 0) {
1608 perror("listen");
1609 return -1;
1611 s->vlan = vlan;
1612 s->model = strdup(model);
1613 s->name = strdup(name);
1614 s->fd = fd;
1615 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1616 return 0;
1619 static int net_socket_connect_init(VLANState *vlan,
1620 const char *model,
1621 const char *name,
1622 const char *host_str)
1624 NetSocketState *s;
1625 int fd, connected, ret, err;
1626 struct sockaddr_in saddr;
1628 if (parse_host_port(&saddr, host_str) < 0)
1629 return -1;
1631 fd = socket(PF_INET, SOCK_STREAM, 0);
1632 if (fd < 0) {
1633 perror("socket");
1634 return -1;
1636 socket_set_nonblock(fd);
1638 connected = 0;
1639 for(;;) {
1640 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1641 if (ret < 0) {
1642 err = socket_error();
1643 if (err == EINTR || err == EWOULDBLOCK) {
1644 } else if (err == EINPROGRESS) {
1645 break;
1646 #ifdef _WIN32
1647 } else if (err == WSAEALREADY) {
1648 break;
1649 #endif
1650 } else {
1651 perror("connect");
1652 closesocket(fd);
1653 return -1;
1655 } else {
1656 connected = 1;
1657 break;
1660 s = net_socket_fd_init(vlan, model, name, fd, connected);
1661 if (!s)
1662 return -1;
1663 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1664 "socket: connect to %s:%d",
1665 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1666 return 0;
1669 static int net_socket_mcast_init(VLANState *vlan,
1670 const char *model,
1671 const char *name,
1672 const char *host_str)
1674 NetSocketState *s;
1675 int fd;
1676 struct sockaddr_in saddr;
1678 if (parse_host_port(&saddr, host_str) < 0)
1679 return -1;
1682 fd = net_socket_mcast_create(&saddr);
1683 if (fd < 0)
1684 return -1;
1686 s = net_socket_fd_init(vlan, model, name, fd, 0);
1687 if (!s)
1688 return -1;
1690 s->dgram_dst = saddr;
1692 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1693 "socket: mcast=%s:%d",
1694 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1695 return 0;
1699 /* find or alloc a new VLAN */
1700 VLANState *qemu_find_vlan(int id)
1702 VLANState **pvlan, *vlan;
1703 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1704 if (vlan->id == id)
1705 return vlan;
1707 vlan = qemu_mallocz(sizeof(VLANState));
1708 vlan->id = id;
1709 vlan->next = NULL;
1710 pvlan = &first_vlan;
1711 while (*pvlan != NULL)
1712 pvlan = &(*pvlan)->next;
1713 *pvlan = vlan;
1714 return vlan;
1717 static int nic_get_free_idx(void)
1719 int index;
1721 for (index = 0; index < MAX_NICS; index++)
1722 if (!nd_table[index].used)
1723 return index;
1724 return -1;
1727 void qemu_check_nic_model(NICInfo *nd, const char *model)
1729 const char *models[2];
1731 models[0] = model;
1732 models[1] = NULL;
1734 qemu_check_nic_model_list(nd, models, model);
1737 void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
1738 const char *default_model)
1740 int i, exit_status = 0;
1742 if (!nd->model)
1743 nd->model = strdup(default_model);
1745 if (strcmp(nd->model, "?") != 0) {
1746 for (i = 0 ; models[i]; i++)
1747 if (strcmp(nd->model, models[i]) == 0)
1748 return;
1750 fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
1751 exit_status = 1;
1754 fprintf(stderr, "qemu: Supported NIC models: ");
1755 for (i = 0 ; models[i]; i++)
1756 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1758 exit(exit_status);
1761 int net_client_init(const char *device, const char *p)
1763 char buf[1024];
1764 int vlan_id, ret;
1765 VLANState *vlan;
1766 char *name = NULL;
1768 vlan_id = 0;
1769 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1770 vlan_id = strtol(buf, NULL, 0);
1772 vlan = qemu_find_vlan(vlan_id);
1773 if (!vlan) {
1774 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
1775 return -1;
1777 if (get_param_value(buf, sizeof(buf), "name", p)) {
1778 name = strdup(buf);
1780 if (!strcmp(device, "nic")) {
1781 NICInfo *nd;
1782 uint8_t *macaddr;
1783 int idx = nic_get_free_idx();
1785 if (idx == -1 || nb_nics >= MAX_NICS) {
1786 fprintf(stderr, "Too Many NICs\n");
1787 return -1;
1789 nd = &nd_table[idx];
1790 macaddr = nd->macaddr;
1791 macaddr[0] = 0x52;
1792 macaddr[1] = 0x54;
1793 macaddr[2] = 0x00;
1794 macaddr[3] = 0x12;
1795 macaddr[4] = 0x34;
1796 macaddr[5] = 0x56 + idx;
1798 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1799 if (parse_macaddr(macaddr, buf) < 0) {
1800 fprintf(stderr, "invalid syntax for ethernet address\n");
1801 return -1;
1804 if (get_param_value(buf, sizeof(buf), "model", p)) {
1805 nd->model = strdup(buf);
1807 nd->vlan = vlan;
1808 nd->name = name;
1809 nd->used = 1;
1810 name = NULL;
1811 nb_nics++;
1812 vlan->nb_guest_devs++;
1813 ret = idx;
1814 } else
1815 if (!strcmp(device, "none")) {
1816 /* does nothing. It is needed to signal that no network cards
1817 are wanted */
1818 ret = 0;
1819 } else
1820 #ifdef CONFIG_SLIRP
1821 if (!strcmp(device, "user")) {
1822 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1823 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1825 if (get_param_value(buf, sizeof(buf), "restrict", p)) {
1826 slirp_restrict = (buf[0] == 'y') ? 1 : 0;
1828 if (get_param_value(buf, sizeof(buf), "ip", p)) {
1829 slirp_ip = strdup(buf);
1831 vlan->nb_host_devs++;
1832 ret = net_slirp_init(vlan, device, name);
1833 } else if (!strcmp(device, "channel")) {
1834 long port;
1835 char name[20], *devname;
1836 struct VMChannel *vmc;
1838 port = strtol(p, &devname, 10);
1839 devname++;
1840 if (port < 1 || port > 65535) {
1841 fprintf(stderr, "vmchannel wrong port number\n");
1842 return -1;
1844 vmc = malloc(sizeof(struct VMChannel));
1845 snprintf(name, 20, "vmchannel%ld", port);
1846 vmc->hd = qemu_chr_open(name, devname, NULL);
1847 if (!vmc->hd) {
1848 fprintf(stderr, "qemu: could not open vmchannel device"
1849 "'%s'\n", devname);
1850 return -1;
1852 vmc->port = port;
1853 slirp_add_exec(3, vmc->hd, 4, port);
1854 qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,
1855 NULL, vmc);
1856 ret = 0;
1857 } else
1858 #endif
1859 #ifdef _WIN32
1860 if (!strcmp(device, "tap")) {
1861 char ifname[64];
1862 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1863 fprintf(stderr, "tap: no interface name\n");
1864 return -1;
1866 vlan->nb_host_devs++;
1867 ret = tap_win32_init(vlan, device, name, ifname);
1868 } else
1869 #elif defined (_AIX)
1870 #else
1871 if (!strcmp(device, "tap")) {
1872 char ifname[64];
1873 char setup_script[1024], down_script[1024];
1874 int fd;
1875 vlan->nb_host_devs++;
1876 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1877 fd = strtol(buf, NULL, 0);
1878 fcntl(fd, F_SETFL, O_NONBLOCK);
1879 ret = -1;
1880 if (net_tap_fd_init(vlan, device, name, fd,
1881 tap_probe_vnet_hdr(fd)))
1882 ret = 0;
1883 } else {
1884 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1885 ifname[0] = '\0';
1887 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1888 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1890 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1891 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1893 ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
1895 } else
1896 #endif
1897 if (!strcmp(device, "socket")) {
1898 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1899 int fd;
1900 fd = strtol(buf, NULL, 0);
1901 ret = -1;
1902 if (net_socket_fd_init(vlan, device, name, fd, 1))
1903 ret = 0;
1904 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1905 ret = net_socket_listen_init(vlan, device, name, buf);
1906 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1907 ret = net_socket_connect_init(vlan, device, name, buf);
1908 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1909 ret = net_socket_mcast_init(vlan, device, name, buf);
1910 } else {
1911 fprintf(stderr, "Unknown socket options: %s\n", p);
1912 return -1;
1914 vlan->nb_host_devs++;
1915 } else
1916 #ifdef CONFIG_VDE
1917 if (!strcmp(device, "vde")) {
1918 char vde_sock[1024], vde_group[512];
1919 int vde_port, vde_mode;
1920 vlan->nb_host_devs++;
1921 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1922 vde_sock[0] = '\0';
1924 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1925 vde_port = strtol(buf, NULL, 10);
1926 } else {
1927 vde_port = 0;
1929 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1930 vde_group[0] = '\0';
1932 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1933 vde_mode = strtol(buf, NULL, 8);
1934 } else {
1935 vde_mode = 0700;
1937 ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
1938 } else
1939 #endif
1941 fprintf(stderr, "Unknown network device: %s\n", device);
1942 if (name)
1943 free(name);
1944 return -1;
1946 if (ret < 0) {
1947 fprintf(stderr, "Could not initialize device '%s'\n", device);
1949 if (name)
1950 free(name);
1951 return ret;
1954 void net_client_uninit(NICInfo *nd)
1956 nd->vlan->nb_guest_devs--;
1957 nb_nics--;
1958 nd->used = 0;
1959 free((void *)nd->model);
1962 static int net_host_check_device(const char *device)
1964 int i;
1965 const char *valid_param_list[] = { "tap", "socket"
1966 #ifdef CONFIG_SLIRP
1967 ,"user"
1968 #endif
1969 #ifdef CONFIG_VDE
1970 ,"vde"
1971 #endif
1973 for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
1974 if (!strncmp(valid_param_list[i], device,
1975 strlen(valid_param_list[i])))
1976 return 1;
1979 return 0;
1982 void net_host_device_add(const char *device, const char *opts)
1984 if (!net_host_check_device(device)) {
1985 term_printf("invalid host network device %s\n", device);
1986 return;
1988 net_client_init(device, opts);
1991 void net_host_device_remove(int vlan_id, const char *device)
1993 VLANState *vlan;
1994 VLANClientState *vc;
1996 if (!net_host_check_device(device)) {
1997 term_printf("invalid host network device %s\n", device);
1998 return;
2001 vlan = qemu_find_vlan(vlan_id);
2002 if (!vlan) {
2003 term_printf("can't find vlan %d\n", vlan_id);
2004 return;
2007 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2008 if (!strcmp(vc->name, device))
2009 break;
2011 if (!vc) {
2012 term_printf("can't find device %s\n", device);
2013 return;
2015 qemu_del_vlan_client(vc);
2018 int net_client_parse(const char *str)
2020 const char *p;
2021 char *q;
2022 char device[64];
2024 p = str;
2025 q = device;
2026 while (*p != '\0' && *p != ',') {
2027 if ((q - device) < sizeof(device) - 1)
2028 *q++ = *p;
2029 p++;
2031 *q = '\0';
2032 if (*p == ',')
2033 p++;
2035 return net_client_init(device, p);
2038 void do_info_network(void)
2040 VLANState *vlan;
2041 VLANClientState *vc;
2043 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2044 term_printf("VLAN %d devices:\n", vlan->id);
2045 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2046 term_printf(" %s: %s\n", vc->name, vc->info_str);
2050 int do_set_link(const char *name, const char *up_or_down)
2052 VLANState *vlan;
2053 VLANClientState *vc = NULL;
2055 for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
2056 for (vc = vlan->first_client; vc != NULL; vc = vc->next)
2057 if (strcmp(vc->name, name) == 0)
2058 goto done;
2059 done:
2061 if (!vc) {
2062 term_printf("could not find network device '%s'", name);
2063 return 0;
2066 if (strcmp(up_or_down, "up") == 0)
2067 vc->link_down = 0;
2068 else if (strcmp(up_or_down, "down") == 0)
2069 vc->link_down = 1;
2070 else
2071 term_printf("invalid link status '%s'; only 'up' or 'down' valid\n",
2072 up_or_down);
2074 if (vc->link_status_changed)
2075 vc->link_status_changed(vc);
2077 return 1;
2080 void net_cleanup(void)
2082 VLANState *vlan;
2084 #if !defined(_WIN32)
2085 /* close network clients */
2086 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2087 VLANClientState *vc;
2089 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2090 if (vc->fd_read == tap_receive) {
2091 TAPState *s = vc->opaque;
2093 if (s->down_script[0])
2094 launch_script(s->down_script, s->down_script_arg, s->fd);
2096 #if defined(CONFIG_VDE)
2097 if (vc->fd_read == vde_from_qemu) {
2098 VDEState *s = vc->opaque;
2099 vde_close(s->vde);
2101 #endif
2104 #endif
2107 void net_client_check(void)
2109 VLANState *vlan;
2111 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2112 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
2113 continue;
2114 if (vlan->nb_guest_devs == 0)
2115 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
2116 if (vlan->nb_host_devs == 0)
2117 fprintf(stderr,
2118 "Warning: vlan %d is not connected to host network\n",
2119 vlan->id);