Fix qemu_send_packet
[qemu-kvm/fedora.git] / net.c
blob9841197c36ca825acd0cf04ed67a84232a17276d
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 if (!vc)
339 return NULL;
340 vc->model = strdup(model);
341 if (name)
342 vc->name = strdup(name);
343 else
344 vc->name = assign_name(vc, model);
345 vc->fd_read = fd_read;
346 vc->fd_can_read = fd_can_read;
347 vc->opaque = opaque;
348 vc->vlan = vlan;
350 vc->next = NULL;
351 pvc = &vlan->first_client;
352 while (*pvc != NULL)
353 pvc = &(*pvc)->next;
354 *pvc = vc;
355 return vc;
358 void qemu_del_vlan_client(VLANClientState *vc)
360 VLANClientState **pvc = &vc->vlan->first_client;
362 while (*pvc != NULL)
363 if (*pvc == vc) {
364 *pvc = vc->next;
365 free(vc->name);
366 free(vc->model);
367 free(vc);
368 break;
369 } else
370 pvc = &(*pvc)->next;
373 int qemu_can_send_packet(VLANClientState *vc1)
375 VLANState *vlan = vc1->vlan;
376 VLANClientState *vc;
378 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
379 if (vc != vc1) {
380 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
381 return 1;
384 return 0;
387 int qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
389 VLANState *vlan = vc1->vlan;
390 VLANClientState *vc;
391 int ret = -EAGAIN;
393 if (vc1->link_down)
394 return 0;
396 #ifdef DEBUG_NET
397 printf("vlan %d send:\n", vlan->id);
398 hex_dump(stdout, buf, size);
399 #endif
400 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
401 if (vc != vc1 && !vc->link_down) {
402 if (!vc->fd_can_read || vc->fd_can_read(vc->opaque)) {
403 vc->fd_read(vc->opaque, buf, size);
404 ret = 0;
408 return ret;
411 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
412 int iovcnt)
414 uint8_t buffer[4096];
415 size_t offset = 0;
416 int i;
418 for (i = 0; i < iovcnt; i++) {
419 size_t len;
421 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
422 memcpy(buffer + offset, iov[i].iov_base, len);
423 offset += len;
426 vc->fd_read(vc->opaque, buffer, offset);
428 return offset;
431 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
432 int iovcnt)
434 VLANState *vlan = vc1->vlan;
435 VLANClientState *vc;
436 ssize_t max_len = 0;
438 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
439 ssize_t len = 0;
441 if (vc == vc1)
442 continue;
444 if (vc->fd_readv)
445 len = vc->fd_readv(vc->opaque, iov, iovcnt);
446 else if (vc->fd_read)
447 len = vc_sendv_compat(vc, iov, iovcnt);
449 max_len = MAX(max_len, len);
452 return max_len;
455 #if defined(CONFIG_SLIRP)
457 /* slirp network adapter */
459 static int slirp_inited;
460 static int slirp_restrict;
461 static char *slirp_ip;
462 static VLANClientState *slirp_vc;
464 int slirp_can_output(void)
466 return !slirp_vc || qemu_can_send_packet(slirp_vc);
469 void slirp_output(const uint8_t *pkt, int pkt_len)
471 #ifdef DEBUG_SLIRP
472 printf("slirp output:\n");
473 hex_dump(stdout, pkt, pkt_len);
474 #endif
475 if (!slirp_vc)
476 return;
477 qemu_send_packet(slirp_vc, pkt, pkt_len);
480 int slirp_is_inited(void)
482 return slirp_inited;
485 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
487 #ifdef DEBUG_SLIRP
488 printf("slirp input:\n");
489 hex_dump(stdout, buf, size);
490 #endif
491 slirp_input(buf, size);
494 static int net_slirp_init(VLANState *vlan, const char *model, const char *name)
496 if (!slirp_inited) {
497 slirp_inited = 1;
498 slirp_init(slirp_restrict, slirp_ip);
500 slirp_vc = qemu_new_vlan_client(vlan, model, name,
501 slirp_receive, NULL, NULL);
502 slirp_vc->info_str[0] = '\0';
503 return 0;
506 void net_slirp_redir(const char *redir_str)
508 int is_udp;
509 char buf[256], *r;
510 const char *p;
511 struct in_addr guest_addr;
512 int host_port, guest_port;
514 if (!slirp_inited) {
515 slirp_inited = 1;
516 slirp_init(slirp_restrict, slirp_ip);
519 p = redir_str;
520 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
521 goto fail;
522 if (!strcmp(buf, "tcp")) {
523 is_udp = 0;
524 } else if (!strcmp(buf, "udp")) {
525 is_udp = 1;
526 } else {
527 goto fail;
530 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
531 goto fail;
532 host_port = strtol(buf, &r, 0);
533 if (r == buf)
534 goto fail;
536 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
537 goto fail;
538 if (buf[0] == '\0') {
539 pstrcpy(buf, sizeof(buf), "10.0.2.15");
541 if (!inet_aton(buf, &guest_addr))
542 goto fail;
544 guest_port = strtol(p, &r, 0);
545 if (r == p)
546 goto fail;
548 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
549 fprintf(stderr, "qemu: could not set up redirection\n");
550 exit(1);
552 return;
553 fail:
554 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
555 exit(1);
558 #ifndef _WIN32
560 static char smb_dir[1024];
562 static void erase_dir(char *dir_name)
564 DIR *d;
565 struct dirent *de;
566 char filename[1024];
568 /* erase all the files in the directory */
569 if ((d = opendir(dir_name)) != 0) {
570 for(;;) {
571 de = readdir(d);
572 if (!de)
573 break;
574 if (strcmp(de->d_name, ".") != 0 &&
575 strcmp(de->d_name, "..") != 0) {
576 snprintf(filename, sizeof(filename), "%s/%s",
577 smb_dir, de->d_name);
578 if (unlink(filename) != 0) /* is it a directory? */
579 erase_dir(filename);
582 closedir(d);
583 rmdir(dir_name);
587 /* automatic user mode samba server configuration */
588 static void smb_exit(void)
590 erase_dir(smb_dir);
593 /* automatic user mode samba server configuration */
594 void net_slirp_smb(const char *exported_dir)
596 char smb_conf[1024];
597 char smb_cmdline[1024];
598 FILE *f;
600 if (!slirp_inited) {
601 slirp_inited = 1;
602 slirp_init(slirp_restrict, slirp_ip);
605 /* XXX: better tmp dir construction */
606 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
607 if (mkdir(smb_dir, 0700) < 0) {
608 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
609 exit(1);
611 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
613 f = fopen(smb_conf, "w");
614 if (!f) {
615 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
616 exit(1);
618 fprintf(f,
619 "[global]\n"
620 "private dir=%s\n"
621 "smb ports=0\n"
622 "socket address=127.0.0.1\n"
623 "pid directory=%s\n"
624 "lock directory=%s\n"
625 "log file=%s/log.smbd\n"
626 "smb passwd file=%s/smbpasswd\n"
627 "security = share\n"
628 "[qemu]\n"
629 "path=%s\n"
630 "read only=no\n"
631 "guest ok=yes\n",
632 smb_dir,
633 smb_dir,
634 smb_dir,
635 smb_dir,
636 smb_dir,
637 exported_dir
639 fclose(f);
640 atexit(smb_exit);
642 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
643 SMBD_COMMAND, smb_conf);
645 slirp_add_exec(0, smb_cmdline, 4, 139);
648 #endif /* !defined(_WIN32) */
649 void do_info_slirp(void)
651 slirp_stats();
654 #endif /* CONFIG_SLIRP */
656 #ifdef _WIN32
658 int tap_has_vnet_hdr(void *opaque)
660 return 0;
663 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
667 #else /* !defined(_WIN32) */
669 /* Maximum GSO packet size (64k) plus plenty of room for
670 * the ethernet and virtio_net headers
672 #define TAP_BUFSIZE (4096 + 65536)
674 #ifdef IFF_VNET_HDR
675 #include <linux/virtio_net.h>
676 #endif
678 typedef struct TAPState {
679 VLANClientState *vc;
680 int fd;
681 char down_script[1024];
682 char down_script_arg[128];
683 char buf[TAP_BUFSIZE];
684 int size;
685 unsigned int has_vnet_hdr : 1;
686 unsigned int using_vnet_hdr : 1;
687 } TAPState;
689 #ifdef HAVE_IOVEC
690 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
691 int iovcnt)
693 TAPState *s = opaque;
694 ssize_t len;
696 do {
697 len = writev(s->fd, iov, iovcnt);
698 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
700 return len;
702 #endif
704 static void tap_receive(void *opaque, const uint8_t *buf, int size)
706 struct iovec iov[2];
707 int i = 0;
709 #ifdef IFF_VNET_HDR
710 TAPState *s = opaque;
711 struct virtio_net_hdr hdr = { 0, };
713 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
714 iov[i].iov_base = &hdr;
715 iov[i].iov_len = sizeof(hdr);
716 i++;
718 #endif
720 iov[i].iov_base = (char *) buf;
721 iov[i].iov_len = size;
722 i++;
724 tap_receive_iov(opaque, iov, i);
727 static int tap_can_send(void *opaque)
729 TAPState *s = opaque;
730 VLANClientState *vc;
731 int can_receive = 0;
733 /* Check to see if any of our clients can receive a packet */
734 for (vc = s->vc->vlan->first_client; vc; vc = vc->next) {
735 /* Skip ourselves */
736 if (vc == s->vc)
737 continue;
739 if (!vc->fd_can_read) {
740 /* no fd_can_read handler, they always can receive */
741 can_receive = 1;
742 } else
743 can_receive = vc->fd_can_read(vc->opaque);
745 /* Once someone can receive, we try to send a packet */
746 if (can_receive)
747 break;
750 return can_receive;
753 static int tap_send_packet(TAPState *s)
755 uint8_t *buf = s->buf;
756 int size = s->size;
758 #ifdef IFF_VNET_HDR
759 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
760 buf += sizeof(struct virtio_net_hdr);
761 size -= sizeof(struct virtio_net_hdr);
763 #endif
765 return qemu_send_packet(s->vc, buf, size);
768 static void tap_send(void *opaque)
770 TAPState *s = opaque;
772 /* First try to send any buffered packet */
773 if (s->size > 0) {
774 int err;
776 /* If noone can receive the packet, buffer it */
777 err = tap_send_packet(s);
778 if (err == -EAGAIN)
779 return;
782 /* Read packets until we hit EAGAIN */
783 do {
784 #ifdef __sun__
785 struct strbuf sbuf;
786 int f = 0;
787 sbuf.maxlen = sizeof(s->buf);
788 sbuf.buf = s->buf;
789 s->size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
790 #else
791 // FIXME: kvm_sleep_begin();
792 s->size = read(s->fd, s->buf, sizeof(s->buf));
793 // FIXME: kvm_sleep_end();
794 #endif
796 if (s->size == -1 && errno == EINTR)
797 continue;
799 if (s->size > 0) {
800 int err;
802 /* If noone can receive the packet, buffer it */
803 err = tap_send_packet(s);
804 if (err == -EAGAIN)
805 break;
807 } while (s->size > 0);
810 int tap_has_vnet_hdr(void *opaque)
812 VLANClientState *vc = opaque;
813 TAPState *s = vc->opaque;
815 return s ? s->has_vnet_hdr : 0;
818 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
820 VLANClientState *vc = opaque;
821 TAPState *s = vc->opaque;
823 if (!s || !s->has_vnet_hdr)
824 return;
826 s->using_vnet_hdr = using_vnet_hdr != 0;
829 static int tap_probe_vnet_hdr(int fd)
831 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
832 struct ifreq ifr;
834 if (ioctl(fd, TUNGETIFF, &ifr) != 0) {
835 fprintf(stderr, "TUNGETIFF ioctl() failed: %s\n", strerror(errno));
836 return 0;
839 return ifr.ifr_flags & IFF_VNET_HDR;
840 #else
841 return 0;
842 #endif
845 #ifdef TUNSETOFFLOAD
846 static void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6,
847 int ecn)
849 TAPState *s = vc->opaque;
850 unsigned int offload = 0;
852 if (csum) {
853 offload |= TUN_F_CSUM;
854 if (tso4)
855 offload |= TUN_F_TSO4;
856 if (tso6)
857 offload |= TUN_F_TSO6;
858 if ((tso4 || tso6) && ecn)
859 offload |= TUN_F_TSO_ECN;
862 if (ioctl(s->fd, TUNSETOFFLOAD, offload) != 0)
863 fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n",
864 strerror(errno));
866 #endif /* TUNSETOFFLOAD */
868 /* fd support */
870 static TAPState *net_tap_fd_init(VLANState *vlan,
871 const char *model,
872 const char *name,
873 int fd,
874 int vnet_hdr)
876 TAPState *s;
878 s = qemu_mallocz(sizeof(TAPState));
879 if (!s)
880 return NULL;
881 s->fd = fd;
882 s->has_vnet_hdr = vnet_hdr != 0;
883 s->vc = qemu_new_vlan_client(vlan, model, name, tap_receive, NULL, s);
884 #ifdef HAVE_IOVEC
885 s->vc->fd_readv = tap_receive_iov;
886 #endif
887 #ifdef TUNSETOFFLOAD
888 s->vc->set_offload = tap_set_offload;
889 #endif
890 qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
891 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
892 return s;
895 #if defined (_BSD) || defined (__FreeBSD_kernel__)
896 static int tap_open(char *ifname, int ifname_size)
898 int fd;
899 char *dev;
900 struct stat s;
902 TFR(fd = open("/dev/tap", O_RDWR));
903 if (fd < 0) {
904 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
905 return -1;
908 fstat(fd, &s);
909 dev = devname(s.st_rdev, S_IFCHR);
910 pstrcpy(ifname, ifname_size, dev);
912 fcntl(fd, F_SETFL, O_NONBLOCK);
913 return fd;
915 #elif defined(__sun__)
916 #define TUNNEWPPA (('T'<<16) | 0x0001)
918 * Allocate TAP device, returns opened fd.
919 * Stores dev name in the first arg(must be large enough).
921 int tap_alloc(char *dev, size_t dev_size)
923 int tap_fd, if_fd, ppa = -1;
924 static int ip_fd = 0;
925 char *ptr;
927 static int arp_fd = 0;
928 int ip_muxid, arp_muxid;
929 struct strioctl strioc_if, strioc_ppa;
930 int link_type = I_PLINK;;
931 struct lifreq ifr;
932 char actual_name[32] = "";
934 memset(&ifr, 0x0, sizeof(ifr));
936 if( *dev ){
937 ptr = dev;
938 while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
939 ppa = atoi(ptr);
942 /* Check if IP device was opened */
943 if( ip_fd )
944 close(ip_fd);
946 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
947 if (ip_fd < 0) {
948 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
949 return -1;
952 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
953 if (tap_fd < 0) {
954 syslog(LOG_ERR, "Can't open /dev/tap");
955 return -1;
958 /* Assign a new PPA and get its unit number. */
959 strioc_ppa.ic_cmd = TUNNEWPPA;
960 strioc_ppa.ic_timout = 0;
961 strioc_ppa.ic_len = sizeof(ppa);
962 strioc_ppa.ic_dp = (char *)&ppa;
963 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
964 syslog (LOG_ERR, "Can't assign new interface");
966 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
967 if (if_fd < 0) {
968 syslog(LOG_ERR, "Can't open /dev/tap (2)");
969 return -1;
971 if(ioctl(if_fd, I_PUSH, "ip") < 0){
972 syslog(LOG_ERR, "Can't push IP module");
973 return -1;
976 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
977 syslog(LOG_ERR, "Can't get flags\n");
979 snprintf (actual_name, 32, "tap%d", ppa);
980 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
982 ifr.lifr_ppa = ppa;
983 /* Assign ppa according to the unit number returned by tun device */
985 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
986 syslog (LOG_ERR, "Can't set PPA %d", ppa);
987 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
988 syslog (LOG_ERR, "Can't get flags\n");
989 /* Push arp module to if_fd */
990 if (ioctl (if_fd, I_PUSH, "arp") < 0)
991 syslog (LOG_ERR, "Can't push ARP module (2)");
993 /* Push arp module to ip_fd */
994 if (ioctl (ip_fd, I_POP, NULL) < 0)
995 syslog (LOG_ERR, "I_POP failed\n");
996 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
997 syslog (LOG_ERR, "Can't push ARP module (3)\n");
998 /* Open arp_fd */
999 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
1000 if (arp_fd < 0)
1001 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
1003 /* Set ifname to arp */
1004 strioc_if.ic_cmd = SIOCSLIFNAME;
1005 strioc_if.ic_timout = 0;
1006 strioc_if.ic_len = sizeof(ifr);
1007 strioc_if.ic_dp = (char *)&ifr;
1008 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
1009 syslog (LOG_ERR, "Can't set ifname to arp\n");
1012 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
1013 syslog(LOG_ERR, "Can't link TAP device to IP");
1014 return -1;
1017 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
1018 syslog (LOG_ERR, "Can't link TAP device to ARP");
1020 close (if_fd);
1022 memset(&ifr, 0x0, sizeof(ifr));
1023 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1024 ifr.lifr_ip_muxid = ip_muxid;
1025 ifr.lifr_arp_muxid = arp_muxid;
1027 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
1029 ioctl (ip_fd, I_PUNLINK , arp_muxid);
1030 ioctl (ip_fd, I_PUNLINK, ip_muxid);
1031 syslog (LOG_ERR, "Can't set multiplexor id");
1034 snprintf(dev, dev_size, "tap%d", ppa);
1035 return tap_fd;
1038 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1040 char dev[10]="";
1041 int fd;
1042 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
1043 fprintf(stderr, "Cannot allocate TAP device\n");
1044 return -1;
1046 pstrcpy(ifname, ifname_size, dev);
1047 fcntl(fd, F_SETFL, O_NONBLOCK);
1048 return fd;
1050 #elif defined (_AIX)
1051 static int tap_open(char *ifname, int ifname_size)
1053 fprintf (stderr, "no tap on AIX\n");
1054 return -1;
1056 #else
1057 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1059 struct ifreq ifr;
1060 int fd, ret;
1062 TFR(fd = open("/dev/net/tun", O_RDWR));
1063 if (fd < 0) {
1064 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1065 return -1;
1067 memset(&ifr, 0, sizeof(ifr));
1068 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1070 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
1072 unsigned int features;
1074 if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&
1075 features & IFF_VNET_HDR) {
1076 *vnet_hdr = 1;
1077 ifr.ifr_flags |= IFF_VNET_HDR;
1080 #endif
1082 if (ifname[0] != '\0')
1083 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
1084 else
1085 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
1086 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1087 if (ret != 0) {
1088 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1089 close(fd);
1090 return -1;
1092 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1093 fcntl(fd, F_SETFL, O_NONBLOCK);
1094 return fd;
1096 #endif
1098 static int launch_script(const char *setup_script, const char *ifname, int fd)
1100 int pid, status;
1101 char *args[3];
1102 char **parg;
1104 /* try to launch network script */
1105 pid = fork();
1106 if (pid >= 0) {
1107 if (pid == 0) {
1108 int open_max = sysconf (_SC_OPEN_MAX), i;
1109 for (i = 0; i < open_max; i++)
1110 if (i != STDIN_FILENO &&
1111 i != STDOUT_FILENO &&
1112 i != STDERR_FILENO &&
1113 i != fd)
1114 close(i);
1116 parg = args;
1117 *parg++ = (char *)setup_script;
1118 *parg++ = (char *)ifname;
1119 *parg++ = NULL;
1120 execv(setup_script, args);
1121 _exit(1);
1123 while (waitpid(pid, &status, 0) != pid);
1124 if (!WIFEXITED(status) ||
1125 WEXITSTATUS(status) != 0) {
1126 fprintf(stderr, "%s: could not launch network script\n",
1127 setup_script);
1128 return -1;
1131 return 0;
1134 static int net_tap_init(VLANState *vlan, const char *model,
1135 const char *name, const char *ifname1,
1136 const char *setup_script, const char *down_script)
1138 TAPState *s;
1139 int fd;
1140 int vnet_hdr;
1141 char ifname[128];
1143 if (ifname1 != NULL)
1144 pstrcpy(ifname, sizeof(ifname), ifname1);
1145 else
1146 ifname[0] = '\0';
1147 vnet_hdr = 0;
1148 TFR(fd = tap_open(ifname, sizeof(ifname), &vnet_hdr));
1149 if (fd < 0)
1150 return -1;
1152 if (!setup_script || !strcmp(setup_script, "no"))
1153 setup_script = "";
1154 if (setup_script[0] != '\0') {
1155 if (launch_script(setup_script, ifname, fd))
1156 return -1;
1158 s = net_tap_fd_init(vlan, model, name, fd, vnet_hdr);
1159 if (!s)
1160 return -1;
1162 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1163 "ifname=%s,script=%s,downscript=%s",
1164 ifname, setup_script, down_script);
1165 if (down_script && strcmp(down_script, "no")) {
1166 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1167 snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1169 return 0;
1172 #endif /* !_WIN32 */
1174 #if defined(CONFIG_VDE)
1175 typedef struct VDEState {
1176 VLANClientState *vc;
1177 VDECONN *vde;
1178 } VDEState;
1180 static void vde_to_qemu(void *opaque)
1182 VDEState *s = opaque;
1183 uint8_t buf[4096];
1184 int size;
1186 size = vde_recv(s->vde, buf, sizeof(buf), 0);
1187 if (size > 0) {
1188 qemu_send_packet(s->vc, buf, size);
1192 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
1194 VDEState *s = opaque;
1195 int ret;
1196 for(;;) {
1197 ret = vde_send(s->vde, buf, size, 0);
1198 if (ret < 0 && errno == EINTR) {
1199 } else {
1200 break;
1205 static int net_vde_init(VLANState *vlan, const char *model,
1206 const char *name, const char *sock,
1207 int port, const char *group, int mode)
1209 VDEState *s;
1210 char *init_group = strlen(group) ? (char *)group : NULL;
1211 char *init_sock = strlen(sock) ? (char *)sock : NULL;
1213 struct vde_open_args args = {
1214 .port = port,
1215 .group = init_group,
1216 .mode = mode,
1219 s = qemu_mallocz(sizeof(VDEState));
1220 if (!s)
1221 return -1;
1222 s->vde = vde_open(init_sock, "QEMU", &args);
1223 if (!s->vde){
1224 free(s);
1225 return -1;
1227 s->vc = qemu_new_vlan_client(vlan, model, name, vde_from_qemu, NULL, s);
1228 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1229 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1230 sock, vde_datafd(s->vde));
1231 return 0;
1233 #endif
1235 /* network connection */
1236 typedef struct NetSocketState {
1237 VLANClientState *vc;
1238 int fd;
1239 int state; /* 0 = getting length, 1 = getting data */
1240 int index;
1241 int packet_len;
1242 uint8_t buf[4096];
1243 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1244 } NetSocketState;
1246 typedef struct NetSocketListenState {
1247 VLANState *vlan;
1248 char *model;
1249 char *name;
1250 int fd;
1251 } NetSocketListenState;
1253 /* XXX: we consider we can send the whole packet without blocking */
1254 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1256 NetSocketState *s = opaque;
1257 uint32_t len;
1258 len = htonl(size);
1260 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1261 send_all(s->fd, buf, size);
1264 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1266 NetSocketState *s = opaque;
1267 sendto(s->fd, buf, size, 0,
1268 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1271 static void net_socket_send(void *opaque)
1273 NetSocketState *s = opaque;
1274 int l, size, err;
1275 uint8_t buf1[4096];
1276 const uint8_t *buf;
1278 size = recv(s->fd, buf1, sizeof(buf1), 0);
1279 if (size < 0) {
1280 err = socket_error();
1281 if (err != EWOULDBLOCK)
1282 goto eoc;
1283 } else if (size == 0) {
1284 /* end of connection */
1285 eoc:
1286 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1287 closesocket(s->fd);
1288 return;
1290 buf = buf1;
1291 while (size > 0) {
1292 /* reassemble a packet from the network */
1293 switch(s->state) {
1294 case 0:
1295 l = 4 - s->index;
1296 if (l > size)
1297 l = size;
1298 memcpy(s->buf + s->index, buf, l);
1299 buf += l;
1300 size -= l;
1301 s->index += l;
1302 if (s->index == 4) {
1303 /* got length */
1304 s->packet_len = ntohl(*(uint32_t *)s->buf);
1305 s->index = 0;
1306 s->state = 1;
1308 break;
1309 case 1:
1310 l = s->packet_len - s->index;
1311 if (l > size)
1312 l = size;
1313 memcpy(s->buf + s->index, buf, l);
1314 s->index += l;
1315 buf += l;
1316 size -= l;
1317 if (s->index >= s->packet_len) {
1318 qemu_send_packet(s->vc, s->buf, s->packet_len);
1319 s->index = 0;
1320 s->state = 0;
1322 break;
1327 static void net_socket_send_dgram(void *opaque)
1329 NetSocketState *s = opaque;
1330 int size;
1332 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1333 if (size < 0)
1334 return;
1335 if (size == 0) {
1336 /* end of connection */
1337 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1338 return;
1340 qemu_send_packet(s->vc, s->buf, size);
1343 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1345 struct ip_mreq imr;
1346 int fd;
1347 int val, ret;
1348 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1349 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1350 inet_ntoa(mcastaddr->sin_addr),
1351 (int)ntohl(mcastaddr->sin_addr.s_addr));
1352 return -1;
1355 fd = socket(PF_INET, SOCK_DGRAM, 0);
1356 if (fd < 0) {
1357 perror("socket(PF_INET, SOCK_DGRAM)");
1358 return -1;
1361 val = 1;
1362 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1363 (const char *)&val, sizeof(val));
1364 if (ret < 0) {
1365 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1366 goto fail;
1369 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1370 if (ret < 0) {
1371 perror("bind");
1372 goto fail;
1375 /* Add host to multicast group */
1376 imr.imr_multiaddr = mcastaddr->sin_addr;
1377 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1379 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1380 (const char *)&imr, sizeof(struct ip_mreq));
1381 if (ret < 0) {
1382 perror("setsockopt(IP_ADD_MEMBERSHIP)");
1383 goto fail;
1386 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1387 val = 1;
1388 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1389 (const char *)&val, sizeof(val));
1390 if (ret < 0) {
1391 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1392 goto fail;
1395 socket_set_nonblock(fd);
1396 return fd;
1397 fail:
1398 if (fd >= 0)
1399 closesocket(fd);
1400 return -1;
1403 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1404 const char *model,
1405 const char *name,
1406 int fd, int is_connected)
1408 struct sockaddr_in saddr;
1409 int newfd;
1410 socklen_t saddr_len;
1411 NetSocketState *s;
1413 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1414 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1415 * by ONLY ONE process: we must "clone" this dgram socket --jjo
1418 if (is_connected) {
1419 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1420 /* must be bound */
1421 if (saddr.sin_addr.s_addr==0) {
1422 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1423 fd);
1424 return NULL;
1426 /* clone dgram socket */
1427 newfd = net_socket_mcast_create(&saddr);
1428 if (newfd < 0) {
1429 /* error already reported by net_socket_mcast_create() */
1430 close(fd);
1431 return NULL;
1433 /* clone newfd to fd, close newfd */
1434 dup2(newfd, fd);
1435 close(newfd);
1437 } else {
1438 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1439 fd, strerror(errno));
1440 return NULL;
1444 s = qemu_mallocz(sizeof(NetSocketState));
1445 if (!s)
1446 return NULL;
1447 s->fd = fd;
1449 s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive_dgram, NULL, s);
1450 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1452 /* mcast: save bound address as dst */
1453 if (is_connected) s->dgram_dst=saddr;
1455 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1456 "socket: fd=%d (%s mcast=%s:%d)",
1457 fd, is_connected? "cloned" : "",
1458 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1459 return s;
1462 static void net_socket_connect(void *opaque)
1464 NetSocketState *s = opaque;
1465 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1468 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1469 const char *model,
1470 const char *name,
1471 int fd, int is_connected)
1473 NetSocketState *s;
1474 s = qemu_mallocz(sizeof(NetSocketState));
1475 if (!s)
1476 return NULL;
1477 s->fd = fd;
1478 s->vc = qemu_new_vlan_client(vlan, model, name,
1479 net_socket_receive, NULL, s);
1480 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1481 "socket: fd=%d", fd);
1482 if (is_connected) {
1483 net_socket_connect(s);
1484 } else {
1485 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1487 return s;
1490 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1491 const char *model, const char *name,
1492 int fd, int is_connected)
1494 int so_type=-1, optlen=sizeof(so_type);
1496 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1497 (socklen_t *)&optlen)< 0) {
1498 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1499 return NULL;
1501 switch(so_type) {
1502 case SOCK_DGRAM:
1503 return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1504 case SOCK_STREAM:
1505 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1506 default:
1507 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1508 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1509 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1511 return NULL;
1514 static void net_socket_accept(void *opaque)
1516 NetSocketListenState *s = opaque;
1517 NetSocketState *s1;
1518 struct sockaddr_in saddr;
1519 socklen_t len;
1520 int fd;
1522 for(;;) {
1523 len = sizeof(saddr);
1524 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1525 if (fd < 0 && errno != EINTR) {
1526 return;
1527 } else if (fd >= 0) {
1528 break;
1531 s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1532 if (!s1) {
1533 closesocket(fd);
1534 } else {
1535 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1536 "socket: connection from %s:%d",
1537 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1541 static int net_socket_listen_init(VLANState *vlan,
1542 const char *model,
1543 const char *name,
1544 const char *host_str)
1546 NetSocketListenState *s;
1547 int fd, val, ret;
1548 struct sockaddr_in saddr;
1550 if (parse_host_port(&saddr, host_str) < 0)
1551 return -1;
1553 s = qemu_mallocz(sizeof(NetSocketListenState));
1554 if (!s)
1555 return -1;
1557 fd = socket(PF_INET, SOCK_STREAM, 0);
1558 if (fd < 0) {
1559 perror("socket");
1560 return -1;
1562 socket_set_nonblock(fd);
1564 /* allow fast reuse */
1565 val = 1;
1566 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1568 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1569 if (ret < 0) {
1570 perror("bind");
1571 return -1;
1573 ret = listen(fd, 0);
1574 if (ret < 0) {
1575 perror("listen");
1576 return -1;
1578 s->vlan = vlan;
1579 s->model = strdup(model);
1580 s->name = strdup(name);
1581 s->fd = fd;
1582 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1583 return 0;
1586 static int net_socket_connect_init(VLANState *vlan,
1587 const char *model,
1588 const char *name,
1589 const char *host_str)
1591 NetSocketState *s;
1592 int fd, connected, ret, err;
1593 struct sockaddr_in saddr;
1595 if (parse_host_port(&saddr, host_str) < 0)
1596 return -1;
1598 fd = socket(PF_INET, SOCK_STREAM, 0);
1599 if (fd < 0) {
1600 perror("socket");
1601 return -1;
1603 socket_set_nonblock(fd);
1605 connected = 0;
1606 for(;;) {
1607 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1608 if (ret < 0) {
1609 err = socket_error();
1610 if (err == EINTR || err == EWOULDBLOCK) {
1611 } else if (err == EINPROGRESS) {
1612 break;
1613 #ifdef _WIN32
1614 } else if (err == WSAEALREADY) {
1615 break;
1616 #endif
1617 } else {
1618 perror("connect");
1619 closesocket(fd);
1620 return -1;
1622 } else {
1623 connected = 1;
1624 break;
1627 s = net_socket_fd_init(vlan, model, name, fd, connected);
1628 if (!s)
1629 return -1;
1630 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1631 "socket: connect to %s:%d",
1632 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1633 return 0;
1636 static int net_socket_mcast_init(VLANState *vlan,
1637 const char *model,
1638 const char *name,
1639 const char *host_str)
1641 NetSocketState *s;
1642 int fd;
1643 struct sockaddr_in saddr;
1645 if (parse_host_port(&saddr, host_str) < 0)
1646 return -1;
1649 fd = net_socket_mcast_create(&saddr);
1650 if (fd < 0)
1651 return -1;
1653 s = net_socket_fd_init(vlan, model, name, fd, 0);
1654 if (!s)
1655 return -1;
1657 s->dgram_dst = saddr;
1659 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1660 "socket: mcast=%s:%d",
1661 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1662 return 0;
1666 /* find or alloc a new VLAN */
1667 VLANState *qemu_find_vlan(int id)
1669 VLANState **pvlan, *vlan;
1670 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1671 if (vlan->id == id)
1672 return vlan;
1674 vlan = qemu_mallocz(sizeof(VLANState));
1675 if (!vlan)
1676 return NULL;
1677 vlan->id = id;
1678 vlan->next = NULL;
1679 pvlan = &first_vlan;
1680 while (*pvlan != NULL)
1681 pvlan = &(*pvlan)->next;
1682 *pvlan = vlan;
1683 return vlan;
1686 void qemu_check_nic_model(NICInfo *nd, const char *model)
1688 const char *models[2];
1690 models[0] = model;
1691 models[1] = NULL;
1693 qemu_check_nic_model_list(nd, models, model);
1696 void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
1697 const char *default_model)
1699 int i, exit_status = 0;
1701 if (!nd->model)
1702 nd->model = strdup(default_model);
1704 if (strcmp(nd->model, "?") != 0) {
1705 for (i = 0 ; models[i]; i++)
1706 if (strcmp(nd->model, models[i]) == 0)
1707 return;
1709 fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
1710 exit_status = 1;
1713 fprintf(stderr, "qemu: Supported NIC models: ");
1714 for (i = 0 ; models[i]; i++)
1715 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1717 exit(exit_status);
1720 int net_client_init(const char *device, const char *p)
1722 char buf[1024];
1723 int vlan_id, ret;
1724 VLANState *vlan;
1725 char *name = NULL;
1727 vlan_id = 0;
1728 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1729 vlan_id = strtol(buf, NULL, 0);
1731 vlan = qemu_find_vlan(vlan_id);
1732 if (!vlan) {
1733 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
1734 return -1;
1736 if (get_param_value(buf, sizeof(buf), "name", p)) {
1737 name = strdup(buf);
1739 if (!strcmp(device, "nic")) {
1740 NICInfo *nd;
1741 uint8_t *macaddr;
1743 if (nb_nics >= MAX_NICS) {
1744 fprintf(stderr, "Too Many NICs\n");
1745 return -1;
1747 nd = &nd_table[nb_nics];
1748 macaddr = nd->macaddr;
1749 macaddr[0] = 0x52;
1750 macaddr[1] = 0x54;
1751 macaddr[2] = 0x00;
1752 macaddr[3] = 0x12;
1753 macaddr[4] = 0x34;
1754 macaddr[5] = 0x56 + nb_nics;
1756 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1757 if (parse_macaddr(macaddr, buf) < 0) {
1758 fprintf(stderr, "invalid syntax for ethernet address\n");
1759 return -1;
1762 if (get_param_value(buf, sizeof(buf), "model", p)) {
1763 nd->model = strdup(buf);
1765 nd->vlan = vlan;
1766 nd->name = name;
1767 name = NULL;
1768 nb_nics++;
1769 vlan->nb_guest_devs++;
1770 ret = 0;
1771 } else
1772 if (!strcmp(device, "none")) {
1773 /* does nothing. It is needed to signal that no network cards
1774 are wanted */
1775 ret = 0;
1776 } else
1777 #ifdef CONFIG_SLIRP
1778 if (!strcmp(device, "user")) {
1779 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1780 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1782 if (get_param_value(buf, sizeof(buf), "restrict", p)) {
1783 slirp_restrict = (buf[0] == 'y') ? 1 : 0;
1785 if (get_param_value(buf, sizeof(buf), "ip", p)) {
1786 slirp_ip = strdup(buf);
1788 vlan->nb_host_devs++;
1789 ret = net_slirp_init(vlan, device, name);
1790 } else
1791 #endif
1792 #ifdef _WIN32
1793 if (!strcmp(device, "tap")) {
1794 char ifname[64];
1795 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1796 fprintf(stderr, "tap: no interface name\n");
1797 return -1;
1799 vlan->nb_host_devs++;
1800 ret = tap_win32_init(vlan, device, name, ifname);
1801 } else
1802 #elif defined (_AIX)
1803 #else
1804 if (!strcmp(device, "tap")) {
1805 char ifname[64];
1806 char setup_script[1024], down_script[1024];
1807 int fd;
1808 vlan->nb_host_devs++;
1809 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1810 fd = strtol(buf, NULL, 0);
1811 fcntl(fd, F_SETFL, O_NONBLOCK);
1812 ret = -1;
1813 if (net_tap_fd_init(vlan, device, name, fd,
1814 tap_probe_vnet_hdr(fd)))
1815 ret = 0;
1816 } else {
1817 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1818 ifname[0] = '\0';
1820 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1821 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1823 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1824 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1826 ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
1828 } else
1829 #endif
1830 if (!strcmp(device, "socket")) {
1831 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1832 int fd;
1833 fd = strtol(buf, NULL, 0);
1834 ret = -1;
1835 if (net_socket_fd_init(vlan, device, name, fd, 1))
1836 ret = 0;
1837 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1838 ret = net_socket_listen_init(vlan, device, name, buf);
1839 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1840 ret = net_socket_connect_init(vlan, device, name, buf);
1841 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1842 ret = net_socket_mcast_init(vlan, device, name, buf);
1843 } else {
1844 fprintf(stderr, "Unknown socket options: %s\n", p);
1845 return -1;
1847 vlan->nb_host_devs++;
1848 } else
1849 #ifdef CONFIG_VDE
1850 if (!strcmp(device, "vde")) {
1851 char vde_sock[1024], vde_group[512];
1852 int vde_port, vde_mode;
1853 vlan->nb_host_devs++;
1854 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1855 vde_sock[0] = '\0';
1857 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1858 vde_port = strtol(buf, NULL, 10);
1859 } else {
1860 vde_port = 0;
1862 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1863 vde_group[0] = '\0';
1865 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1866 vde_mode = strtol(buf, NULL, 8);
1867 } else {
1868 vde_mode = 0700;
1870 ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
1871 } else
1872 #endif
1874 fprintf(stderr, "Unknown network device: %s\n", device);
1875 if (name)
1876 free(name);
1877 return -1;
1879 if (ret < 0) {
1880 fprintf(stderr, "Could not initialize device '%s'\n", device);
1882 if (name)
1883 free(name);
1884 return ret;
1887 void net_client_uninit(NICInfo *nd)
1889 nd->vlan->nb_guest_devs--; /* XXX: free vlan on last reference */
1890 nb_nics--;
1891 nd->used = 0;
1892 free((void *)nd->model);
1895 int net_client_parse(const char *str)
1897 const char *p;
1898 char *q;
1899 char device[64];
1901 p = str;
1902 q = device;
1903 while (*p != '\0' && *p != ',') {
1904 if ((q - device) < sizeof(device) - 1)
1905 *q++ = *p;
1906 p++;
1908 *q = '\0';
1909 if (*p == ',')
1910 p++;
1912 return net_client_init(device, p);
1915 void do_info_network(void)
1917 VLANState *vlan;
1918 VLANClientState *vc;
1920 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1921 term_printf("VLAN %d devices:\n", vlan->id);
1922 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
1923 term_printf(" %s: %s\n", vc->name, vc->info_str);
1927 int do_set_link(const char *name, const char *up_or_down)
1929 VLANState *vlan;
1930 VLANClientState *vc = NULL;
1932 for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
1933 for (vc = vlan->first_client; vc != NULL; vc = vc->next)
1934 if (strcmp(vc->name, name) == 0)
1935 goto done;
1936 done:
1938 if (!vc) {
1939 term_printf("could not find network device '%s'", name);
1940 return 0;
1943 if (strcmp(up_or_down, "up") == 0)
1944 vc->link_down = 0;
1945 else if (strcmp(up_or_down, "down") == 0)
1946 vc->link_down = 1;
1947 else
1948 term_printf("invalid link status '%s'; only 'up' or 'down' valid\n",
1949 up_or_down);
1951 if (vc->link_status_changed)
1952 vc->link_status_changed(vc);
1954 return 1;
1957 void net_cleanup(void)
1959 VLANState *vlan;
1961 #if !defined(_WIN32)
1962 /* close network clients */
1963 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1964 VLANClientState *vc;
1966 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1967 if (vc->fd_read == tap_receive) {
1968 TAPState *s = vc->opaque;
1970 if (s->down_script[0])
1971 launch_script(s->down_script, s->down_script_arg, s->fd);
1973 #if defined(CONFIG_VDE)
1974 if (vc->fd_read == vde_from_qemu) {
1975 VDEState *s = vc->opaque;
1976 vde_close(s->vde);
1978 #endif
1981 #endif
1984 void net_client_check(void)
1986 VLANState *vlan;
1988 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1989 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
1990 continue;
1991 if (vlan->nb_guest_devs == 0)
1992 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
1993 if (vlan->nb_host_devs == 0)
1994 fprintf(stderr,
1995 "Warning: vlan %d is not connected to host network\n",
1996 vlan->id);