use KVM_UPSTREAM for ppc.
[qemu-kvm/fedora.git] / net.c
blobef3a96543f0cbc44e48d01db1aa170d652ac68bb
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 NetCleanup *cleanup,
335 void *opaque)
337 VLANClientState *vc, **pvc;
338 vc = qemu_mallocz(sizeof(VLANClientState));
339 vc->model = strdup(model);
340 if (name)
341 vc->name = strdup(name);
342 else
343 vc->name = assign_name(vc, model);
344 vc->fd_read = fd_read;
345 vc->fd_can_read = fd_can_read;
346 vc->cleanup = cleanup;
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 if (vc->cleanup) {
366 vc->cleanup(vc);
368 free(vc->name);
369 free(vc->model);
370 qemu_free(vc);
371 break;
372 } else
373 pvc = &(*pvc)->next;
376 VLANClientState *qemu_find_vlan_client(VLANState *vlan, void *opaque)
378 VLANClientState **pvc = &vlan->first_client;
380 while (*pvc != NULL)
381 if ((*pvc)->opaque == opaque)
382 return *pvc;
383 else
384 pvc = &(*pvc)->next;
386 return NULL;
389 int qemu_can_send_packet(VLANClientState *vc1)
391 VLANState *vlan = vc1->vlan;
392 VLANClientState *vc;
394 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
395 if (vc != vc1) {
396 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
397 return 1;
400 return 0;
403 int qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
405 VLANState *vlan = vc1->vlan;
406 VLANClientState *vc;
407 int ret = -EAGAIN;
409 if (vc1->link_down)
410 return 0;
412 #ifdef DEBUG_NET
413 printf("vlan %d send:\n", vlan->id);
414 hex_dump(stdout, buf, size);
415 #endif
416 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
417 if (vc != vc1) {
418 if (vc->link_down) {
419 ret = 0;
420 } else if (!vc->fd_can_read || vc->fd_can_read(vc->opaque)) {
421 vc->fd_read(vc->opaque, buf, size);
422 ret = 0;
426 return ret;
429 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
430 int iovcnt)
432 uint8_t buffer[4096];
433 size_t offset = 0;
434 int i;
436 for (i = 0; i < iovcnt; i++) {
437 size_t len;
439 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
440 memcpy(buffer + offset, iov[i].iov_base, len);
441 offset += len;
444 vc->fd_read(vc->opaque, buffer, offset);
446 return offset;
449 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
451 size_t offset = 0;
452 int i;
454 for (i = 0; i < iovcnt; i++)
455 offset += iov[i].iov_len;
456 return offset;
459 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
460 int iovcnt)
462 VLANState *vlan = vc1->vlan;
463 VLANClientState *vc;
464 ssize_t max_len = 0;
466 if (vc1->link_down)
467 return calc_iov_length(iov, iovcnt);
469 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
470 ssize_t len = 0;
472 if (vc == vc1)
473 continue;
475 if (vc->link_down)
476 len = calc_iov_length(iov, iovcnt);
477 if (vc->fd_readv)
478 len = vc->fd_readv(vc->opaque, iov, iovcnt);
479 else if (vc->fd_read)
480 len = vc_sendv_compat(vc, iov, iovcnt);
482 max_len = MAX(max_len, len);
485 return max_len;
488 #if defined(CONFIG_SLIRP)
490 /* slirp network adapter */
492 static int slirp_inited;
493 static int slirp_restrict;
494 static char *slirp_ip;
495 static VLANClientState *slirp_vc;
497 int slirp_can_output(void)
499 return !slirp_vc || qemu_can_send_packet(slirp_vc);
502 void slirp_output(const uint8_t *pkt, int pkt_len)
504 #ifdef DEBUG_SLIRP
505 printf("slirp output:\n");
506 hex_dump(stdout, pkt, pkt_len);
507 #endif
508 if (!slirp_vc)
509 return;
510 qemu_send_packet(slirp_vc, pkt, pkt_len);
513 int slirp_is_inited(void)
515 return slirp_inited;
518 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
520 #ifdef DEBUG_SLIRP
521 printf("slirp input:\n");
522 hex_dump(stdout, buf, size);
523 #endif
524 slirp_input(buf, size);
527 static int net_slirp_init(VLANState *vlan, const char *model, const char *name)
529 if (!slirp_inited) {
530 slirp_inited = 1;
531 slirp_init(slirp_restrict, slirp_ip);
533 slirp_vc = qemu_new_vlan_client(vlan, model, name,
534 slirp_receive, NULL, NULL, NULL);
535 slirp_vc->info_str[0] = '\0';
536 return 0;
539 void net_slirp_redir(const char *redir_str)
541 int is_udp;
542 char buf[256], *r;
543 const char *p;
544 struct in_addr guest_addr;
545 int host_port, guest_port;
547 if (!slirp_inited) {
548 slirp_inited = 1;
549 slirp_init(slirp_restrict, slirp_ip);
552 p = redir_str;
553 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
554 goto fail;
555 if (!strcmp(buf, "tcp")) {
556 is_udp = 0;
557 } else if (!strcmp(buf, "udp")) {
558 is_udp = 1;
559 } else {
560 goto fail;
563 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
564 goto fail;
565 host_port = strtol(buf, &r, 0);
566 if (r == buf)
567 goto fail;
569 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
570 goto fail;
571 if (buf[0] == '\0') {
572 pstrcpy(buf, sizeof(buf), "10.0.2.15");
574 if (!inet_aton(buf, &guest_addr))
575 goto fail;
577 guest_port = strtol(p, &r, 0);
578 if (r == p)
579 goto fail;
581 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
582 fprintf(stderr, "qemu: could not set up redirection\n");
583 exit(1);
585 return;
586 fail:
587 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
588 exit(1);
591 #ifndef _WIN32
593 static char smb_dir[1024];
595 static void erase_dir(char *dir_name)
597 DIR *d;
598 struct dirent *de;
599 char filename[1024];
601 /* erase all the files in the directory */
602 if ((d = opendir(dir_name)) != 0) {
603 for(;;) {
604 de = readdir(d);
605 if (!de)
606 break;
607 if (strcmp(de->d_name, ".") != 0 &&
608 strcmp(de->d_name, "..") != 0) {
609 snprintf(filename, sizeof(filename), "%s/%s",
610 smb_dir, de->d_name);
611 if (unlink(filename) != 0) /* is it a directory? */
612 erase_dir(filename);
615 closedir(d);
616 rmdir(dir_name);
620 /* automatic user mode samba server configuration */
621 static void smb_exit(void)
623 erase_dir(smb_dir);
626 /* automatic user mode samba server configuration */
627 void net_slirp_smb(const char *exported_dir)
629 char smb_conf[1024];
630 char smb_cmdline[1024];
631 FILE *f;
633 if (!slirp_inited) {
634 slirp_inited = 1;
635 slirp_init(slirp_restrict, slirp_ip);
638 /* XXX: better tmp dir construction */
639 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
640 if (mkdir(smb_dir, 0700) < 0) {
641 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
642 exit(1);
644 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
646 f = fopen(smb_conf, "w");
647 if (!f) {
648 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
649 exit(1);
651 fprintf(f,
652 "[global]\n"
653 "private dir=%s\n"
654 "smb ports=0\n"
655 "socket address=127.0.0.1\n"
656 "pid directory=%s\n"
657 "lock directory=%s\n"
658 "log file=%s/log.smbd\n"
659 "smb passwd file=%s/smbpasswd\n"
660 "security = share\n"
661 "[qemu]\n"
662 "path=%s\n"
663 "read only=no\n"
664 "guest ok=yes\n",
665 smb_dir,
666 smb_dir,
667 smb_dir,
668 smb_dir,
669 smb_dir,
670 exported_dir
672 fclose(f);
673 atexit(smb_exit);
675 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
676 SMBD_COMMAND, smb_conf);
678 slirp_add_exec(0, smb_cmdline, 4, 139);
681 #endif /* !defined(_WIN32) */
682 void do_info_slirp(void)
684 slirp_stats();
687 struct VMChannel {
688 CharDriverState *hd;
689 int port;
690 } *vmchannels;
692 static int vmchannel_can_read(void *opaque)
694 struct VMChannel *vmc = (struct VMChannel*)opaque;
695 return slirp_socket_can_recv(4, vmc->port);
698 static void vmchannel_read(void *opaque, const uint8_t *buf, int size)
700 struct VMChannel *vmc = (struct VMChannel*)opaque;
701 slirp_socket_recv(4, vmc->port, buf, size);
704 #endif /* CONFIG_SLIRP */
706 #ifdef _WIN32
708 int tap_has_vnet_hdr(void *opaque)
710 return 0;
713 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
717 #else /* !defined(_WIN32) */
719 /* Maximum GSO packet size (64k) plus plenty of room for
720 * the ethernet and virtio_net headers
722 #define TAP_BUFSIZE (4096 + 65536)
724 #ifdef IFF_VNET_HDR
725 #include <linux/virtio_net.h>
726 #endif
728 typedef struct TAPState {
729 VLANClientState *vc;
730 int fd;
731 char down_script[1024];
732 char down_script_arg[128];
733 char buf[TAP_BUFSIZE];
734 int size;
735 unsigned int has_vnet_hdr : 1;
736 unsigned int using_vnet_hdr : 1;
737 } TAPState;
739 static int launch_script(const char *setup_script, const char *ifname, int fd);
741 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
742 int iovcnt)
744 TAPState *s = opaque;
745 ssize_t len;
747 do {
748 len = writev(s->fd, iov, iovcnt);
749 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
751 return len;
754 static void tap_receive(void *opaque, const uint8_t *buf, int size)
756 struct iovec iov[2];
757 int i = 0;
759 #ifdef IFF_VNET_HDR
760 TAPState *s = opaque;
761 struct virtio_net_hdr hdr = { 0, };
763 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
764 iov[i].iov_base = &hdr;
765 iov[i].iov_len = sizeof(hdr);
766 i++;
768 #endif
770 iov[i].iov_base = (char *) buf;
771 iov[i].iov_len = size;
772 i++;
774 tap_receive_iov(opaque, iov, i);
777 static int tap_can_send(void *opaque)
779 TAPState *s = opaque;
780 VLANClientState *vc;
781 int can_receive = 0;
783 /* Check to see if any of our clients can receive a packet */
784 for (vc = s->vc->vlan->first_client; vc; vc = vc->next) {
785 /* Skip ourselves */
786 if (vc == s->vc)
787 continue;
789 if (!vc->fd_can_read) {
790 /* no fd_can_read handler, they always can receive */
791 can_receive = 1;
792 } else
793 can_receive = vc->fd_can_read(vc->opaque);
795 /* Once someone can receive, we try to send a packet */
796 if (can_receive)
797 break;
800 return can_receive;
803 static int tap_send_packet(TAPState *s)
805 uint8_t *buf = (uint8_t *)s->buf;
806 int size = s->size;
808 #ifdef IFF_VNET_HDR
809 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
810 buf += sizeof(struct virtio_net_hdr);
811 size -= sizeof(struct virtio_net_hdr);
813 #endif
815 return qemu_send_packet(s->vc, buf, size);
818 static void tap_send(void *opaque)
820 TAPState *s = opaque;
822 /* First try to send any buffered packet */
823 if (s->size > 0) {
824 int err;
826 /* If noone can receive the packet, buffer it */
827 err = tap_send_packet(s);
828 if (err == -EAGAIN)
829 return;
832 /* Read packets until we hit EAGAIN */
833 do {
834 #ifdef __sun__
835 struct strbuf sbuf;
836 int f = 0;
837 sbuf.maxlen = sizeof(s->buf);
838 sbuf.buf = s->buf;
839 s->size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
840 #else
841 // FIXME: kvm_sleep_begin();
842 s->size = read(s->fd, s->buf, sizeof(s->buf));
843 // FIXME: kvm_sleep_end();
844 #endif
846 if (s->size == -1 && errno == EINTR)
847 continue;
849 if (s->size > 0) {
850 int err;
852 /* If noone can receive the packet, buffer it */
853 err = tap_send_packet(s);
854 if (err == -EAGAIN)
855 break;
857 } while (s->size > 0);
860 int tap_has_vnet_hdr(void *opaque)
862 VLANClientState *vc = opaque;
863 TAPState *s = vc->opaque;
865 return s ? s->has_vnet_hdr : 0;
868 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
870 VLANClientState *vc = opaque;
871 TAPState *s = vc->opaque;
873 if (!s || !s->has_vnet_hdr)
874 return;
876 s->using_vnet_hdr = using_vnet_hdr != 0;
879 static int tap_probe_vnet_hdr(int fd)
881 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
882 struct ifreq ifr;
884 if (ioctl(fd, TUNGETIFF, &ifr) != 0) {
885 fprintf(stderr, "TUNGETIFF ioctl() failed: %s\n", strerror(errno));
886 return 0;
889 return ifr.ifr_flags & IFF_VNET_HDR;
890 #else
891 return 0;
892 #endif
895 #ifdef TUNSETOFFLOAD
896 static void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6,
897 int ecn)
899 TAPState *s = vc->opaque;
900 unsigned int offload = 0;
902 if (csum) {
903 offload |= TUN_F_CSUM;
904 if (tso4)
905 offload |= TUN_F_TSO4;
906 if (tso6)
907 offload |= TUN_F_TSO6;
908 if ((tso4 || tso6) && ecn)
909 offload |= TUN_F_TSO_ECN;
912 if (ioctl(s->fd, TUNSETOFFLOAD, offload) != 0)
913 fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n",
914 strerror(errno));
916 #endif /* TUNSETOFFLOAD */
918 static void tap_cleanup(VLANClientState *vc)
920 TAPState *s = vc->opaque;
922 if (s->down_script[0])
923 launch_script(s->down_script, s->down_script_arg, s->fd);
925 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
926 close(s->fd);
927 qemu_free(s);
930 /* fd support */
932 static TAPState *net_tap_fd_init(VLANState *vlan,
933 const char *model,
934 const char *name,
935 int fd,
936 int vnet_hdr)
938 TAPState *s;
940 s = qemu_mallocz(sizeof(TAPState));
941 s->fd = fd;
942 s->has_vnet_hdr = vnet_hdr != 0;
943 s->vc = qemu_new_vlan_client(vlan, model, name, tap_receive,
944 NULL, tap_cleanup, s);
945 #ifdef HAVE_IOVEC
946 s->vc->fd_readv = tap_receive_iov;
947 #endif
948 #ifdef TUNSETOFFLOAD
949 s->vc->set_offload = tap_set_offload;
950 tap_set_offload(s->vc, 0, 0, 0, 0);
951 #endif
952 qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
953 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
954 return s;
957 #if defined (_BSD) || defined (__FreeBSD_kernel__)
958 static int tap_open(char *ifname, int ifname_size)
960 int fd;
961 char *dev;
962 struct stat s;
964 TFR(fd = open("/dev/tap", O_RDWR));
965 if (fd < 0) {
966 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
967 return -1;
970 fstat(fd, &s);
971 dev = devname(s.st_rdev, S_IFCHR);
972 pstrcpy(ifname, ifname_size, dev);
974 fcntl(fd, F_SETFL, O_NONBLOCK);
975 return fd;
977 #elif defined(__sun__)
978 #define TUNNEWPPA (('T'<<16) | 0x0001)
980 * Allocate TAP device, returns opened fd.
981 * Stores dev name in the first arg(must be large enough).
983 int tap_alloc(char *dev, size_t dev_size)
985 int tap_fd, if_fd, ppa = -1;
986 static int ip_fd = 0;
987 char *ptr;
989 static int arp_fd = 0;
990 int ip_muxid, arp_muxid;
991 struct strioctl strioc_if, strioc_ppa;
992 int link_type = I_PLINK;;
993 struct lifreq ifr;
994 char actual_name[32] = "";
996 memset(&ifr, 0x0, sizeof(ifr));
998 if( *dev ){
999 ptr = dev;
1000 while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
1001 ppa = atoi(ptr);
1004 /* Check if IP device was opened */
1005 if( ip_fd )
1006 close(ip_fd);
1008 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
1009 if (ip_fd < 0) {
1010 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
1011 return -1;
1014 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
1015 if (tap_fd < 0) {
1016 syslog(LOG_ERR, "Can't open /dev/tap");
1017 return -1;
1020 /* Assign a new PPA and get its unit number. */
1021 strioc_ppa.ic_cmd = TUNNEWPPA;
1022 strioc_ppa.ic_timout = 0;
1023 strioc_ppa.ic_len = sizeof(ppa);
1024 strioc_ppa.ic_dp = (char *)&ppa;
1025 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
1026 syslog (LOG_ERR, "Can't assign new interface");
1028 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
1029 if (if_fd < 0) {
1030 syslog(LOG_ERR, "Can't open /dev/tap (2)");
1031 return -1;
1033 if(ioctl(if_fd, I_PUSH, "ip") < 0){
1034 syslog(LOG_ERR, "Can't push IP module");
1035 return -1;
1038 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
1039 syslog(LOG_ERR, "Can't get flags\n");
1041 snprintf (actual_name, 32, "tap%d", ppa);
1042 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1044 ifr.lifr_ppa = ppa;
1045 /* Assign ppa according to the unit number returned by tun device */
1047 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
1048 syslog (LOG_ERR, "Can't set PPA %d", ppa);
1049 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
1050 syslog (LOG_ERR, "Can't get flags\n");
1051 /* Push arp module to if_fd */
1052 if (ioctl (if_fd, I_PUSH, "arp") < 0)
1053 syslog (LOG_ERR, "Can't push ARP module (2)");
1055 /* Push arp module to ip_fd */
1056 if (ioctl (ip_fd, I_POP, NULL) < 0)
1057 syslog (LOG_ERR, "I_POP failed\n");
1058 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
1059 syslog (LOG_ERR, "Can't push ARP module (3)\n");
1060 /* Open arp_fd */
1061 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
1062 if (arp_fd < 0)
1063 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
1065 /* Set ifname to arp */
1066 strioc_if.ic_cmd = SIOCSLIFNAME;
1067 strioc_if.ic_timout = 0;
1068 strioc_if.ic_len = sizeof(ifr);
1069 strioc_if.ic_dp = (char *)&ifr;
1070 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
1071 syslog (LOG_ERR, "Can't set ifname to arp\n");
1074 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
1075 syslog(LOG_ERR, "Can't link TAP device to IP");
1076 return -1;
1079 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
1080 syslog (LOG_ERR, "Can't link TAP device to ARP");
1082 close (if_fd);
1084 memset(&ifr, 0x0, sizeof(ifr));
1085 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1086 ifr.lifr_ip_muxid = ip_muxid;
1087 ifr.lifr_arp_muxid = arp_muxid;
1089 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
1091 ioctl (ip_fd, I_PUNLINK , arp_muxid);
1092 ioctl (ip_fd, I_PUNLINK, ip_muxid);
1093 syslog (LOG_ERR, "Can't set multiplexor id");
1096 snprintf(dev, dev_size, "tap%d", ppa);
1097 return tap_fd;
1100 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1102 char dev[10]="";
1103 int fd;
1104 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
1105 fprintf(stderr, "Cannot allocate TAP device\n");
1106 return -1;
1108 pstrcpy(ifname, ifname_size, dev);
1109 fcntl(fd, F_SETFL, O_NONBLOCK);
1110 return fd;
1112 #elif defined (_AIX)
1113 static int tap_open(char *ifname, int ifname_size)
1115 fprintf (stderr, "no tap on AIX\n");
1116 return -1;
1118 #else
1119 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1121 struct ifreq ifr;
1122 int fd, ret;
1124 TFR(fd = open("/dev/net/tun", O_RDWR));
1125 if (fd < 0) {
1126 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1127 return -1;
1129 memset(&ifr, 0, sizeof(ifr));
1130 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1132 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
1134 unsigned int features;
1136 if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&
1137 features & IFF_VNET_HDR) {
1138 *vnet_hdr = 1;
1139 ifr.ifr_flags |= IFF_VNET_HDR;
1142 #endif
1144 if (ifname[0] != '\0')
1145 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
1146 else
1147 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
1148 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1149 if (ret != 0) {
1150 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1151 close(fd);
1152 return -1;
1154 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1155 fcntl(fd, F_SETFL, O_NONBLOCK);
1156 return fd;
1158 #endif
1160 static int launch_script(const char *setup_script, const char *ifname, int fd)
1162 int pid, status;
1163 char *args[3];
1164 char **parg;
1166 /* try to launch network script */
1167 pid = fork();
1168 if (pid >= 0) {
1169 if (pid == 0) {
1170 int open_max = sysconf (_SC_OPEN_MAX), i;
1171 for (i = 0; i < open_max; i++)
1172 if (i != STDIN_FILENO &&
1173 i != STDOUT_FILENO &&
1174 i != STDERR_FILENO &&
1175 i != fd)
1176 close(i);
1178 parg = args;
1179 *parg++ = (char *)setup_script;
1180 *parg++ = (char *)ifname;
1181 *parg++ = NULL;
1182 execv(setup_script, args);
1183 _exit(1);
1185 while (waitpid(pid, &status, 0) != pid);
1186 if (!WIFEXITED(status) ||
1187 WEXITSTATUS(status) != 0) {
1188 fprintf(stderr, "%s: could not launch network script\n",
1189 setup_script);
1190 return -1;
1193 return 0;
1196 static int net_tap_init(VLANState *vlan, const char *model,
1197 const char *name, const char *ifname1,
1198 const char *setup_script, const char *down_script)
1200 TAPState *s;
1201 int fd;
1202 int vnet_hdr;
1203 char ifname[128];
1205 if (ifname1 != NULL)
1206 pstrcpy(ifname, sizeof(ifname), ifname1);
1207 else
1208 ifname[0] = '\0';
1209 vnet_hdr = 0;
1210 TFR(fd = tap_open(ifname, sizeof(ifname), &vnet_hdr));
1211 if (fd < 0)
1212 return -1;
1214 if (!setup_script || !strcmp(setup_script, "no"))
1215 setup_script = "";
1216 if (setup_script[0] != '\0') {
1217 if (launch_script(setup_script, ifname, fd))
1218 return -1;
1220 s = net_tap_fd_init(vlan, model, name, fd, vnet_hdr);
1221 if (!s)
1222 return -1;
1224 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1225 "ifname=%s,script=%s,downscript=%s",
1226 ifname, setup_script, down_script);
1227 if (down_script && strcmp(down_script, "no")) {
1228 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1229 snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1231 return 0;
1234 #endif /* !_WIN32 */
1236 #if defined(CONFIG_VDE)
1237 typedef struct VDEState {
1238 VLANClientState *vc;
1239 VDECONN *vde;
1240 } VDEState;
1242 static void vde_to_qemu(void *opaque)
1244 VDEState *s = opaque;
1245 uint8_t buf[4096];
1246 int size;
1248 size = vde_recv(s->vde, buf, sizeof(buf), 0);
1249 if (size > 0) {
1250 qemu_send_packet(s->vc, buf, size);
1254 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
1256 VDEState *s = opaque;
1257 int ret;
1258 for(;;) {
1259 ret = vde_send(s->vde, buf, size, 0);
1260 if (ret < 0 && errno == EINTR) {
1261 } else {
1262 break;
1267 static void vde_cleanup(VLANClientState *vc)
1269 VDEState *s = vc->opaque;
1270 qemu_set_fd_handler(vde_datafd(s->vde), NULL, NULL, NULL);
1271 vde_close(s->vde);
1272 qemu_free(s);
1275 static int net_vde_init(VLANState *vlan, const char *model,
1276 const char *name, const char *sock,
1277 int port, const char *group, int mode)
1279 VDEState *s;
1280 char *init_group = strlen(group) ? (char *)group : NULL;
1281 char *init_sock = strlen(sock) ? (char *)sock : NULL;
1283 struct vde_open_args args = {
1284 .port = port,
1285 .group = init_group,
1286 .mode = mode,
1289 s = qemu_mallocz(sizeof(VDEState));
1290 s->vde = vde_open(init_sock, "QEMU", &args);
1291 if (!s->vde){
1292 free(s);
1293 return -1;
1295 s->vc = qemu_new_vlan_client(vlan, model, name, vde_from_qemu,
1296 NULL, vde_cleanup, s);
1297 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1298 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1299 sock, vde_datafd(s->vde));
1300 return 0;
1302 #endif
1304 /* network connection */
1305 typedef struct NetSocketState {
1306 VLANClientState *vc;
1307 int fd;
1308 int state; /* 0 = getting length, 1 = getting data */
1309 unsigned int index;
1310 unsigned int packet_len;
1311 uint8_t buf[4096];
1312 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1313 } NetSocketState;
1315 typedef struct NetSocketListenState {
1316 VLANState *vlan;
1317 char *model;
1318 char *name;
1319 int fd;
1320 } NetSocketListenState;
1322 /* XXX: we consider we can send the whole packet without blocking */
1323 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1325 NetSocketState *s = opaque;
1326 uint32_t len;
1327 len = htonl(size);
1329 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1330 send_all(s->fd, buf, size);
1333 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1335 NetSocketState *s = opaque;
1336 sendto(s->fd, buf, size, 0,
1337 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1340 static void net_socket_send(void *opaque)
1342 NetSocketState *s = opaque;
1343 int size, err;
1344 unsigned l;
1345 uint8_t buf1[4096];
1346 const uint8_t *buf;
1348 size = recv(s->fd, buf1, sizeof(buf1), 0);
1349 if (size < 0) {
1350 err = socket_error();
1351 if (err != EWOULDBLOCK)
1352 goto eoc;
1353 } else if (size == 0) {
1354 /* end of connection */
1355 eoc:
1356 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1357 closesocket(s->fd);
1358 return;
1360 buf = buf1;
1361 while (size > 0) {
1362 /* reassemble a packet from the network */
1363 switch(s->state) {
1364 case 0:
1365 l = 4 - s->index;
1366 if (l > size)
1367 l = size;
1368 memcpy(s->buf + s->index, buf, l);
1369 buf += l;
1370 size -= l;
1371 s->index += l;
1372 if (s->index == 4) {
1373 /* got length */
1374 s->packet_len = ntohl(*(uint32_t *)s->buf);
1375 s->index = 0;
1376 s->state = 1;
1378 break;
1379 case 1:
1380 l = s->packet_len - s->index;
1381 if (l > size)
1382 l = size;
1383 if (s->index + l <= sizeof(s->buf)) {
1384 memcpy(s->buf + s->index, buf, l);
1385 } else {
1386 fprintf(stderr, "serious error: oversized packet received,"
1387 "connection terminated.\n");
1388 s->state = 0;
1389 goto eoc;
1392 s->index += l;
1393 buf += l;
1394 size -= l;
1395 if (s->index >= s->packet_len) {
1396 qemu_send_packet(s->vc, s->buf, s->packet_len);
1397 s->index = 0;
1398 s->state = 0;
1400 break;
1405 static void net_socket_send_dgram(void *opaque)
1407 NetSocketState *s = opaque;
1408 int size;
1410 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1411 if (size < 0)
1412 return;
1413 if (size == 0) {
1414 /* end of connection */
1415 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1416 return;
1418 qemu_send_packet(s->vc, s->buf, size);
1421 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1423 struct ip_mreq imr;
1424 int fd;
1425 int val, ret;
1426 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1427 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1428 inet_ntoa(mcastaddr->sin_addr),
1429 (int)ntohl(mcastaddr->sin_addr.s_addr));
1430 return -1;
1433 fd = socket(PF_INET, SOCK_DGRAM, 0);
1434 if (fd < 0) {
1435 perror("socket(PF_INET, SOCK_DGRAM)");
1436 return -1;
1439 val = 1;
1440 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1441 (const char *)&val, sizeof(val));
1442 if (ret < 0) {
1443 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1444 goto fail;
1447 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1448 if (ret < 0) {
1449 perror("bind");
1450 goto fail;
1453 /* Add host to multicast group */
1454 imr.imr_multiaddr = mcastaddr->sin_addr;
1455 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1457 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1458 (const char *)&imr, sizeof(struct ip_mreq));
1459 if (ret < 0) {
1460 perror("setsockopt(IP_ADD_MEMBERSHIP)");
1461 goto fail;
1464 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1465 val = 1;
1466 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1467 (const char *)&val, sizeof(val));
1468 if (ret < 0) {
1469 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1470 goto fail;
1473 socket_set_nonblock(fd);
1474 return fd;
1475 fail:
1476 if (fd >= 0)
1477 closesocket(fd);
1478 return -1;
1481 static void net_socket_cleanup(VLANClientState *vc)
1483 NetSocketState *s = vc->opaque;
1484 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1485 close(s->fd);
1486 qemu_free(s);
1489 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1490 const char *model,
1491 const char *name,
1492 int fd, int is_connected)
1494 struct sockaddr_in saddr;
1495 int newfd;
1496 socklen_t saddr_len;
1497 NetSocketState *s;
1499 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1500 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1501 * by ONLY ONE process: we must "clone" this dgram socket --jjo
1504 if (is_connected) {
1505 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1506 /* must be bound */
1507 if (saddr.sin_addr.s_addr==0) {
1508 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1509 fd);
1510 return NULL;
1512 /* clone dgram socket */
1513 newfd = net_socket_mcast_create(&saddr);
1514 if (newfd < 0) {
1515 /* error already reported by net_socket_mcast_create() */
1516 close(fd);
1517 return NULL;
1519 /* clone newfd to fd, close newfd */
1520 dup2(newfd, fd);
1521 close(newfd);
1523 } else {
1524 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1525 fd, strerror(errno));
1526 return NULL;
1530 s = qemu_mallocz(sizeof(NetSocketState));
1531 s->fd = fd;
1533 s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive_dgram,
1534 NULL, net_socket_cleanup, s);
1535 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1537 /* mcast: save bound address as dst */
1538 if (is_connected) s->dgram_dst=saddr;
1540 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1541 "socket: fd=%d (%s mcast=%s:%d)",
1542 fd, is_connected? "cloned" : "",
1543 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1544 return s;
1547 static void net_socket_connect(void *opaque)
1549 NetSocketState *s = opaque;
1550 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1553 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1554 const char *model,
1555 const char *name,
1556 int fd, int is_connected)
1558 NetSocketState *s;
1559 s = qemu_mallocz(sizeof(NetSocketState));
1560 s->fd = fd;
1561 s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive,
1562 NULL, net_socket_cleanup, s);
1563 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1564 "socket: fd=%d", fd);
1565 if (is_connected) {
1566 net_socket_connect(s);
1567 } else {
1568 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1570 return s;
1573 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1574 const char *model, const char *name,
1575 int fd, int is_connected)
1577 int so_type=-1, optlen=sizeof(so_type);
1579 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1580 (socklen_t *)&optlen)< 0) {
1581 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1582 return NULL;
1584 switch(so_type) {
1585 case SOCK_DGRAM:
1586 return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1587 case SOCK_STREAM:
1588 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1589 default:
1590 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1591 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1592 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1594 return NULL;
1597 static void net_socket_accept(void *opaque)
1599 NetSocketListenState *s = opaque;
1600 NetSocketState *s1;
1601 struct sockaddr_in saddr;
1602 socklen_t len;
1603 int fd;
1605 for(;;) {
1606 len = sizeof(saddr);
1607 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1608 if (fd < 0 && errno != EINTR) {
1609 return;
1610 } else if (fd >= 0) {
1611 break;
1614 s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1615 if (!s1) {
1616 closesocket(fd);
1617 } else {
1618 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1619 "socket: connection from %s:%d",
1620 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1624 static int net_socket_listen_init(VLANState *vlan,
1625 const char *model,
1626 const char *name,
1627 const char *host_str)
1629 NetSocketListenState *s;
1630 int fd, val, ret;
1631 struct sockaddr_in saddr;
1633 if (parse_host_port(&saddr, host_str) < 0)
1634 return -1;
1636 s = qemu_mallocz(sizeof(NetSocketListenState));
1638 fd = socket(PF_INET, SOCK_STREAM, 0);
1639 if (fd < 0) {
1640 perror("socket");
1641 return -1;
1643 socket_set_nonblock(fd);
1645 /* allow fast reuse */
1646 val = 1;
1647 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1649 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1650 if (ret < 0) {
1651 perror("bind");
1652 return -1;
1654 ret = listen(fd, 0);
1655 if (ret < 0) {
1656 perror("listen");
1657 return -1;
1659 s->vlan = vlan;
1660 s->model = strdup(model);
1661 s->name = strdup(name);
1662 s->fd = fd;
1663 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1664 return 0;
1667 static int net_socket_connect_init(VLANState *vlan,
1668 const char *model,
1669 const char *name,
1670 const char *host_str)
1672 NetSocketState *s;
1673 int fd, connected, ret, err;
1674 struct sockaddr_in saddr;
1676 if (parse_host_port(&saddr, host_str) < 0)
1677 return -1;
1679 fd = socket(PF_INET, SOCK_STREAM, 0);
1680 if (fd < 0) {
1681 perror("socket");
1682 return -1;
1684 socket_set_nonblock(fd);
1686 connected = 0;
1687 for(;;) {
1688 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1689 if (ret < 0) {
1690 err = socket_error();
1691 if (err == EINTR || err == EWOULDBLOCK) {
1692 } else if (err == EINPROGRESS) {
1693 break;
1694 #ifdef _WIN32
1695 } else if (err == WSAEALREADY) {
1696 break;
1697 #endif
1698 } else {
1699 perror("connect");
1700 closesocket(fd);
1701 return -1;
1703 } else {
1704 connected = 1;
1705 break;
1708 s = net_socket_fd_init(vlan, model, name, fd, connected);
1709 if (!s)
1710 return -1;
1711 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1712 "socket: connect to %s:%d",
1713 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1714 return 0;
1717 static int net_socket_mcast_init(VLANState *vlan,
1718 const char *model,
1719 const char *name,
1720 const char *host_str)
1722 NetSocketState *s;
1723 int fd;
1724 struct sockaddr_in saddr;
1726 if (parse_host_port(&saddr, host_str) < 0)
1727 return -1;
1730 fd = net_socket_mcast_create(&saddr);
1731 if (fd < 0)
1732 return -1;
1734 s = net_socket_fd_init(vlan, model, name, fd, 0);
1735 if (!s)
1736 return -1;
1738 s->dgram_dst = saddr;
1740 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1741 "socket: mcast=%s:%d",
1742 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1743 return 0;
1747 /* find or alloc a new VLAN */
1748 VLANState *qemu_find_vlan(int id)
1750 VLANState **pvlan, *vlan;
1751 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1752 if (vlan->id == id)
1753 return vlan;
1755 vlan = qemu_mallocz(sizeof(VLANState));
1756 vlan->id = id;
1757 vlan->next = NULL;
1758 pvlan = &first_vlan;
1759 while (*pvlan != NULL)
1760 pvlan = &(*pvlan)->next;
1761 *pvlan = vlan;
1762 return vlan;
1765 static int nic_get_free_idx(void)
1767 int index;
1769 for (index = 0; index < MAX_NICS; index++)
1770 if (!nd_table[index].used)
1771 return index;
1772 return -1;
1775 void qemu_check_nic_model(NICInfo *nd, const char *model)
1777 const char *models[2];
1779 models[0] = model;
1780 models[1] = NULL;
1782 qemu_check_nic_model_list(nd, models, model);
1785 void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
1786 const char *default_model)
1788 int i, exit_status = 0;
1790 if (!nd->model)
1791 nd->model = strdup(default_model);
1793 if (strcmp(nd->model, "?") != 0) {
1794 for (i = 0 ; models[i]; i++)
1795 if (strcmp(nd->model, models[i]) == 0)
1796 return;
1798 fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
1799 exit_status = 1;
1802 fprintf(stderr, "qemu: Supported NIC models: ");
1803 for (i = 0 ; models[i]; i++)
1804 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1806 exit(exit_status);
1809 int net_client_init(const char *device, const char *p)
1811 char buf[1024];
1812 int vlan_id, ret;
1813 VLANState *vlan;
1814 char *name = NULL;
1816 vlan_id = 0;
1817 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1818 vlan_id = strtol(buf, NULL, 0);
1820 vlan = qemu_find_vlan(vlan_id);
1822 if (get_param_value(buf, sizeof(buf), "name", p)) {
1823 name = strdup(buf);
1825 if (!strcmp(device, "nic")) {
1826 NICInfo *nd;
1827 uint8_t *macaddr;
1828 int idx = nic_get_free_idx();
1830 if (idx == -1 || nb_nics >= MAX_NICS) {
1831 fprintf(stderr, "Too Many NICs\n");
1832 ret = -1;
1833 goto out;
1835 nd = &nd_table[idx];
1836 macaddr = nd->macaddr;
1837 macaddr[0] = 0x52;
1838 macaddr[1] = 0x54;
1839 macaddr[2] = 0x00;
1840 macaddr[3] = 0x12;
1841 macaddr[4] = 0x34;
1842 macaddr[5] = 0x56 + idx;
1844 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1845 if (parse_macaddr(macaddr, buf) < 0) {
1846 fprintf(stderr, "invalid syntax for ethernet address\n");
1847 ret = -1;
1848 goto out;
1851 if (get_param_value(buf, sizeof(buf), "model", p)) {
1852 nd->model = strdup(buf);
1854 nd->vlan = vlan;
1855 nd->name = name;
1856 nd->used = 1;
1857 name = NULL;
1858 nb_nics++;
1859 vlan->nb_guest_devs++;
1860 ret = idx;
1861 } else
1862 if (!strcmp(device, "none")) {
1863 /* does nothing. It is needed to signal that no network cards
1864 are wanted */
1865 ret = 0;
1866 } else
1867 #ifdef CONFIG_SLIRP
1868 if (!strcmp(device, "user")) {
1869 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1870 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1872 if (get_param_value(buf, sizeof(buf), "restrict", p)) {
1873 slirp_restrict = (buf[0] == 'y') ? 1 : 0;
1875 if (get_param_value(buf, sizeof(buf), "ip", p)) {
1876 slirp_ip = strdup(buf);
1878 vlan->nb_host_devs++;
1879 ret = net_slirp_init(vlan, device, name);
1880 } else if (!strcmp(device, "channel")) {
1881 long port;
1882 char name[20], *devname;
1883 struct VMChannel *vmc;
1885 port = strtol(p, &devname, 10);
1886 devname++;
1887 if (port < 1 || port > 65535) {
1888 fprintf(stderr, "vmchannel wrong port number\n");
1889 ret = -1;
1890 goto out;
1892 vmc = malloc(sizeof(struct VMChannel));
1893 snprintf(name, 20, "vmchannel%ld", port);
1894 vmc->hd = qemu_chr_open(name, devname, NULL);
1895 if (!vmc->hd) {
1896 fprintf(stderr, "qemu: could not open vmchannel device"
1897 "'%s'\n", devname);
1898 ret = -1;
1899 goto out;
1901 vmc->port = port;
1902 slirp_add_exec(3, vmc->hd, 4, port);
1903 qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,
1904 NULL, vmc);
1905 ret = 0;
1906 } else
1907 #endif
1908 #ifdef _WIN32
1909 if (!strcmp(device, "tap")) {
1910 char ifname[64];
1911 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1912 fprintf(stderr, "tap: no interface name\n");
1913 ret = -1;
1914 goto out;
1916 vlan->nb_host_devs++;
1917 ret = tap_win32_init(vlan, device, name, ifname);
1918 } else
1919 #elif defined (_AIX)
1920 #else
1921 if (!strcmp(device, "tap")) {
1922 char ifname[64];
1923 char setup_script[1024], down_script[1024];
1924 int fd;
1925 vlan->nb_host_devs++;
1926 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1927 fd = strtol(buf, NULL, 0);
1928 fcntl(fd, F_SETFL, O_NONBLOCK);
1929 ret = -1;
1930 if (net_tap_fd_init(vlan, device, name, fd,
1931 tap_probe_vnet_hdr(fd)))
1932 ret = 0;
1933 } else {
1934 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1935 ifname[0] = '\0';
1937 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1938 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1940 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1941 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1943 ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
1945 } else
1946 #endif
1947 if (!strcmp(device, "socket")) {
1948 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1949 int fd;
1950 fd = strtol(buf, NULL, 0);
1951 ret = -1;
1952 if (net_socket_fd_init(vlan, device, name, fd, 1))
1953 ret = 0;
1954 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1955 ret = net_socket_listen_init(vlan, device, name, buf);
1956 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1957 ret = net_socket_connect_init(vlan, device, name, buf);
1958 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1959 ret = net_socket_mcast_init(vlan, device, name, buf);
1960 } else {
1961 fprintf(stderr, "Unknown socket options: %s\n", p);
1962 ret = -1;
1963 goto out;
1965 vlan->nb_host_devs++;
1966 } else
1967 #ifdef CONFIG_VDE
1968 if (!strcmp(device, "vde")) {
1969 char vde_sock[1024], vde_group[512];
1970 int vde_port, vde_mode;
1971 vlan->nb_host_devs++;
1972 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1973 vde_sock[0] = '\0';
1975 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1976 vde_port = strtol(buf, NULL, 10);
1977 } else {
1978 vde_port = 0;
1980 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1981 vde_group[0] = '\0';
1983 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1984 vde_mode = strtol(buf, NULL, 8);
1985 } else {
1986 vde_mode = 0700;
1988 ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
1989 } else
1990 #endif
1992 fprintf(stderr, "Unknown network device: %s\n", device);
1993 ret = -1;
1994 goto out;
1996 if (ret < 0) {
1997 fprintf(stderr, "Could not initialize device '%s'\n", device);
1999 out:
2000 if (name)
2001 free(name);
2002 return ret;
2005 void net_client_uninit(NICInfo *nd)
2007 nd->vlan->nb_guest_devs--;
2008 nb_nics--;
2009 nd->used = 0;
2010 free((void *)nd->model);
2013 static int net_host_check_device(const char *device)
2015 int i;
2016 const char *valid_param_list[] = { "tap", "socket"
2017 #ifdef CONFIG_SLIRP
2018 ,"user"
2019 #endif
2020 #ifdef CONFIG_VDE
2021 ,"vde"
2022 #endif
2024 for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
2025 if (!strncmp(valid_param_list[i], device,
2026 strlen(valid_param_list[i])))
2027 return 1;
2030 return 0;
2033 void net_host_device_add(const char *device, const char *opts)
2035 if (!net_host_check_device(device)) {
2036 term_printf("invalid host network device %s\n", device);
2037 return;
2039 net_client_init(device, opts);
2042 void net_host_device_remove(int vlan_id, const char *device)
2044 VLANState *vlan;
2045 VLANClientState *vc;
2047 vlan = qemu_find_vlan(vlan_id);
2049 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2050 if (!strcmp(vc->name, device))
2051 break;
2053 if (!vc) {
2054 term_printf("can't find device %s\n", device);
2055 return;
2057 qemu_del_vlan_client(vc);
2060 int net_client_parse(const char *str)
2062 const char *p;
2063 char *q;
2064 char device[64];
2066 p = str;
2067 q = device;
2068 while (*p != '\0' && *p != ',') {
2069 if ((q - device) < sizeof(device) - 1)
2070 *q++ = *p;
2071 p++;
2073 *q = '\0';
2074 if (*p == ',')
2075 p++;
2077 return net_client_init(device, p);
2080 void do_info_network(void)
2082 VLANState *vlan;
2083 VLANClientState *vc;
2085 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2086 term_printf("VLAN %d devices:\n", vlan->id);
2087 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2088 term_printf(" %s: %s\n", vc->name, vc->info_str);
2092 int do_set_link(const char *name, const char *up_or_down)
2094 VLANState *vlan;
2095 VLANClientState *vc = NULL;
2097 for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
2098 for (vc = vlan->first_client; vc != NULL; vc = vc->next)
2099 if (strcmp(vc->name, name) == 0)
2100 goto done;
2101 done:
2103 if (!vc) {
2104 term_printf("could not find network device '%s'", name);
2105 return 0;
2108 if (strcmp(up_or_down, "up") == 0)
2109 vc->link_down = 0;
2110 else if (strcmp(up_or_down, "down") == 0)
2111 vc->link_down = 1;
2112 else
2113 term_printf("invalid link status '%s'; only 'up' or 'down' valid\n",
2114 up_or_down);
2116 if (vc->link_status_changed)
2117 vc->link_status_changed(vc);
2119 return 1;
2122 void net_cleanup(void)
2124 VLANState *vlan;
2126 /* close network clients */
2127 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2128 VLANClientState *vc = vlan->first_client;
2130 while (vc) {
2131 VLANClientState *next = vc->next;
2133 qemu_del_vlan_client(vc);
2135 vc = next;
2140 void net_client_check(void)
2142 VLANState *vlan;
2144 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2145 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
2146 continue;
2147 if (vlan->nb_guest_devs == 0)
2148 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
2149 if (vlan->nb_host_devs == 0)
2150 fprintf(stderr,
2151 "Warning: vlan %d is not connected to host network\n",
2152 vlan->id);