Merge branch 'qemu-cvs'
[qemu-kvm/fedora.git] / net.c
blobee6619372627fc69e643f854c000ae31474a6be9
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 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
302 IOReadHandler *fd_read,
303 IOCanRWHandler *fd_can_read,
304 void *opaque)
306 VLANClientState *vc, **pvc;
307 vc = qemu_mallocz(sizeof(VLANClientState));
308 if (!vc)
309 return NULL;
310 vc->fd_read = fd_read;
311 vc->fd_can_read = fd_can_read;
312 vc->opaque = opaque;
313 vc->vlan = vlan;
315 vc->next = NULL;
316 pvc = &vlan->first_client;
317 while (*pvc != NULL)
318 pvc = &(*pvc)->next;
319 *pvc = vc;
320 return vc;
323 void qemu_del_vlan_client(VLANClientState *vc)
325 VLANClientState **pvc = &vc->vlan->first_client;
327 while (*pvc != NULL)
328 if (*pvc == vc) {
329 *pvc = vc->next;
330 free(vc);
331 break;
332 } else
333 pvc = &(*pvc)->next;
336 int qemu_can_send_packet(VLANClientState *vc1)
338 VLANState *vlan = vc1->vlan;
339 VLANClientState *vc;
341 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
342 if (vc != vc1) {
343 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
344 return 1;
347 return 0;
350 int qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
352 VLANState *vlan = vc1->vlan;
353 VLANClientState *vc;
354 int ret = -EAGAIN;
356 #ifdef DEBUG_NET
357 printf("vlan %d send:\n", vlan->id);
358 hex_dump(stdout, buf, size);
359 #endif
360 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
361 if (vc != vc1) {
362 if (!vc->fd_can_read || vc->fd_can_read(vc->opaque)) {
363 vc->fd_read(vc->opaque, buf, size);
364 ret = 0;
368 return ret;
371 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
372 int iovcnt)
374 uint8_t buffer[4096];
375 size_t offset = 0;
376 int i;
378 for (i = 0; i < iovcnt; i++) {
379 size_t len;
381 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
382 memcpy(buffer + offset, iov[i].iov_base, len);
383 offset += len;
386 vc->fd_read(vc->opaque, buffer, offset);
388 return offset;
391 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
392 int iovcnt)
394 VLANState *vlan = vc1->vlan;
395 VLANClientState *vc;
396 ssize_t max_len = 0;
398 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
399 ssize_t len = 0;
401 if (vc == vc1)
402 continue;
404 if (vc->fd_readv)
405 len = vc->fd_readv(vc->opaque, iov, iovcnt);
406 else if (vc->fd_read)
407 len = vc_sendv_compat(vc, iov, iovcnt);
409 max_len = MAX(max_len, len);
412 return max_len;
415 #if defined(CONFIG_SLIRP)
417 /* slirp network adapter */
419 static int slirp_inited;
420 static VLANClientState *slirp_vc;
422 int slirp_can_output(void)
424 return !slirp_vc || qemu_can_send_packet(slirp_vc);
427 void slirp_output(const uint8_t *pkt, int pkt_len)
429 #ifdef DEBUG_SLIRP
430 printf("slirp output:\n");
431 hex_dump(stdout, pkt, pkt_len);
432 #endif
433 if (!slirp_vc)
434 return;
435 qemu_send_packet(slirp_vc, pkt, pkt_len);
438 int slirp_is_inited(void)
440 return slirp_inited;
443 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
445 #ifdef DEBUG_SLIRP
446 printf("slirp input:\n");
447 hex_dump(stdout, buf, size);
448 #endif
449 slirp_input(buf, size);
452 static int net_slirp_init(VLANState *vlan)
454 if (!slirp_inited) {
455 slirp_inited = 1;
456 slirp_init();
458 slirp_vc = qemu_new_vlan_client(vlan,
459 slirp_receive, NULL, NULL);
460 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
461 return 0;
464 void net_slirp_redir(const char *redir_str)
466 int is_udp;
467 char buf[256], *r;
468 const char *p;
469 struct in_addr guest_addr;
470 int host_port, guest_port;
472 if (!slirp_inited) {
473 slirp_inited = 1;
474 slirp_init();
477 p = redir_str;
478 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
479 goto fail;
480 if (!strcmp(buf, "tcp")) {
481 is_udp = 0;
482 } else if (!strcmp(buf, "udp")) {
483 is_udp = 1;
484 } else {
485 goto fail;
488 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
489 goto fail;
490 host_port = strtol(buf, &r, 0);
491 if (r == buf)
492 goto fail;
494 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
495 goto fail;
496 if (buf[0] == '\0') {
497 pstrcpy(buf, sizeof(buf), "10.0.2.15");
499 if (!inet_aton(buf, &guest_addr))
500 goto fail;
502 guest_port = strtol(p, &r, 0);
503 if (r == p)
504 goto fail;
506 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
507 fprintf(stderr, "qemu: could not set up redirection\n");
508 exit(1);
510 return;
511 fail:
512 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
513 exit(1);
516 #ifndef _WIN32
518 static char smb_dir[1024];
520 static void erase_dir(char *dir_name)
522 DIR *d;
523 struct dirent *de;
524 char filename[1024];
526 /* erase all the files in the directory */
527 if ((d = opendir(dir_name)) != 0) {
528 for(;;) {
529 de = readdir(d);
530 if (!de)
531 break;
532 if (strcmp(de->d_name, ".") != 0 &&
533 strcmp(de->d_name, "..") != 0) {
534 snprintf(filename, sizeof(filename), "%s/%s",
535 smb_dir, de->d_name);
536 if (unlink(filename) != 0) /* is it a directory? */
537 erase_dir(filename);
540 closedir(d);
541 rmdir(dir_name);
545 /* automatic user mode samba server configuration */
546 static void smb_exit(void)
548 erase_dir(smb_dir);
551 /* automatic user mode samba server configuration */
552 void net_slirp_smb(const char *exported_dir)
554 char smb_conf[1024];
555 char smb_cmdline[1024];
556 FILE *f;
558 if (!slirp_inited) {
559 slirp_inited = 1;
560 slirp_init();
563 /* XXX: better tmp dir construction */
564 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
565 if (mkdir(smb_dir, 0700) < 0) {
566 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
567 exit(1);
569 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
571 f = fopen(smb_conf, "w");
572 if (!f) {
573 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
574 exit(1);
576 fprintf(f,
577 "[global]\n"
578 "private dir=%s\n"
579 "smb ports=0\n"
580 "socket address=127.0.0.1\n"
581 "pid directory=%s\n"
582 "lock directory=%s\n"
583 "log file=%s/log.smbd\n"
584 "smb passwd file=%s/smbpasswd\n"
585 "security = share\n"
586 "[qemu]\n"
587 "path=%s\n"
588 "read only=no\n"
589 "guest ok=yes\n",
590 smb_dir,
591 smb_dir,
592 smb_dir,
593 smb_dir,
594 smb_dir,
595 exported_dir
597 fclose(f);
598 atexit(smb_exit);
600 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
601 SMBD_COMMAND, smb_conf);
603 slirp_add_exec(0, smb_cmdline, 4, 139);
606 #endif /* !defined(_WIN32) */
607 void do_info_slirp(void)
609 slirp_stats();
612 #endif /* CONFIG_SLIRP */
614 #ifdef _WIN32
616 int tap_has_vnet_hdr(void *opaque)
618 return 0;
621 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
625 #else /* !defined(_WIN32) */
627 /* Maximum GSO packet size (64k) plus plenty of room for
628 * the ethernet and virtio_net headers
630 #define TAP_BUFSIZE (4096 + 65536)
632 #ifdef IFF_VNET_HDR
633 #include <linux/virtio_net.h>
634 #endif
636 typedef struct TAPState {
637 VLANClientState *vc;
638 int fd;
639 char down_script[1024];
640 char buf[TAP_BUFSIZE];
641 int size;
642 unsigned int has_vnet_hdr : 1;
643 unsigned int using_vnet_hdr : 1;
644 } TAPState;
646 #ifdef HAVE_IOVEC
647 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
648 int iovcnt)
650 TAPState *s = opaque;
651 ssize_t len;
653 do {
654 len = writev(s->fd, iov, iovcnt);
655 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
657 return len;
659 #endif
661 static void tap_receive(void *opaque, const uint8_t *buf, int size)
663 struct iovec iov[2];
664 int i = 0;
666 #ifdef IFF_VNET_HDR
667 TAPState *s = opaque;
668 struct virtio_net_hdr hdr = { 0, };
670 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
671 iov[i].iov_base = &hdr;
672 iov[i].iov_len = sizeof(hdr);
673 i++;
675 #endif
677 iov[i].iov_base = (char *) buf;
678 iov[i].iov_len = size;
679 i++;
681 tap_receive_iov(opaque, iov, i);
684 static int tap_can_send(void *opaque)
686 TAPState *s = opaque;
687 VLANClientState *vc;
688 int can_receive = 0;
690 /* Check to see if any of our clients can receive a packet */
691 for (vc = s->vc->vlan->first_client; vc; vc = vc->next) {
692 /* Skip ourselves */
693 if (vc == s->vc)
694 continue;
696 if (!vc->fd_can_read) {
697 /* no fd_can_read handler, they always can receive */
698 can_receive = 1;
699 } else
700 can_receive = vc->fd_can_read(vc->opaque);
702 /* Once someone can receive, we try to send a packet */
703 if (can_receive)
704 break;
707 return can_receive;
710 static int tap_send_packet(TAPState *s)
712 uint8_t *buf = s->buf;
713 int size = s->size;
715 #ifdef IFF_VNET_HDR
716 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
717 buf += sizeof(struct virtio_net_hdr);
718 size -= sizeof(struct virtio_net_hdr);
720 #endif
722 return qemu_send_packet(s->vc, buf, size);
725 static void tap_send(void *opaque)
727 TAPState *s = opaque;
729 /* First try to send any buffered packet */
730 if (s->size > 0) {
731 int err;
733 /* If noone can receive the packet, buffer it */
734 err = tap_send_packet(s);
735 if (err == -EAGAIN)
736 return;
739 /* Read packets until we hit EAGAIN */
740 do {
741 #ifdef __sun__
742 struct strbuf sbuf;
743 int f = 0;
744 sbuf.maxlen = sizeof(s->buf);
745 sbuf.buf = s->buf;
746 s->size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
747 #else
748 // FIXME: kvm_sleep_begin();
749 s->size = read(s->fd, s->buf, sizeof(s->buf));
750 // FIXME: kvm_sleep_end();
751 #endif
753 if (s->size == -1 && errno == EINTR)
754 continue;
756 if (s->size > 0) {
757 int err;
759 /* If noone can receive the packet, buffer it */
760 err = tap_send_packet(s);
761 if (err == -EAGAIN)
762 break;
764 } while (s->size > 0);
767 int tap_has_vnet_hdr(void *opaque)
769 VLANClientState *vc = opaque;
770 TAPState *s = vc->opaque;
772 return s ? s->has_vnet_hdr : 0;
775 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
777 VLANClientState *vc = opaque;
778 TAPState *s = vc->opaque;
780 if (!s || !s->has_vnet_hdr)
781 return;
783 s->using_vnet_hdr = using_vnet_hdr != 0;
786 static int tap_probe_vnet_hdr(int fd)
788 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
789 struct ifreq ifr;
791 if (ioctl(fd, TUNGETIFF, &ifr) != 0) {
792 fprintf(stderr, "TUNGETIFF ioctl() failed: %s\n", strerror(errno));
793 return 0;
796 return ifr.ifr_flags & IFF_VNET_HDR;
797 #else
798 return 0;
799 #endif
802 #ifdef TUNSETOFFLOAD
803 static void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6,
804 int ecn)
806 TAPState *s = vc->opaque;
807 unsigned int offload = 0;
809 if (csum) {
810 offload |= TUN_F_CSUM;
811 if (tso4)
812 offload |= TUN_F_TSO4;
813 if (tso6)
814 offload |= TUN_F_TSO6;
815 if ((tso4 || tso6) && ecn)
816 offload |= TUN_F_TSO_ECN;
819 if (ioctl(s->fd, TUNSETOFFLOAD, offload) != 0)
820 fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n",
821 strerror(errno));
823 #endif /* TUNSETOFFLOAD */
825 /* fd support */
827 static TAPState *net_tap_fd_init(VLANState *vlan, int fd, int vnet_hdr)
829 TAPState *s;
831 s = qemu_mallocz(sizeof(TAPState));
832 if (!s)
833 return NULL;
834 s->fd = fd;
835 s->has_vnet_hdr = vnet_hdr != 0;
836 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
837 #ifdef HAVE_IOVEC
838 s->vc->fd_readv = tap_receive_iov;
839 #endif
840 #ifdef TUNSETOFFLOAD
841 s->vc->set_offload = tap_set_offload;
842 #endif
843 qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
844 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
845 return s;
848 #if defined (_BSD) || defined (__FreeBSD_kernel__)
849 static int tap_open(char *ifname, int ifname_size)
851 int fd;
852 char *dev;
853 struct stat s;
855 TFR(fd = open("/dev/tap", O_RDWR));
856 if (fd < 0) {
857 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
858 return -1;
861 fstat(fd, &s);
862 dev = devname(s.st_rdev, S_IFCHR);
863 pstrcpy(ifname, ifname_size, dev);
865 fcntl(fd, F_SETFL, O_NONBLOCK);
866 return fd;
868 #elif defined(__sun__)
869 #define TUNNEWPPA (('T'<<16) | 0x0001)
871 * Allocate TAP device, returns opened fd.
872 * Stores dev name in the first arg(must be large enough).
874 int tap_alloc(char *dev, size_t dev_size)
876 int tap_fd, if_fd, ppa = -1;
877 static int ip_fd = 0;
878 char *ptr;
880 static int arp_fd = 0;
881 int ip_muxid, arp_muxid;
882 struct strioctl strioc_if, strioc_ppa;
883 int link_type = I_PLINK;;
884 struct lifreq ifr;
885 char actual_name[32] = "";
887 memset(&ifr, 0x0, sizeof(ifr));
889 if( *dev ){
890 ptr = dev;
891 while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
892 ppa = atoi(ptr);
895 /* Check if IP device was opened */
896 if( ip_fd )
897 close(ip_fd);
899 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
900 if (ip_fd < 0) {
901 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
902 return -1;
905 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
906 if (tap_fd < 0) {
907 syslog(LOG_ERR, "Can't open /dev/tap");
908 return -1;
911 /* Assign a new PPA and get its unit number. */
912 strioc_ppa.ic_cmd = TUNNEWPPA;
913 strioc_ppa.ic_timout = 0;
914 strioc_ppa.ic_len = sizeof(ppa);
915 strioc_ppa.ic_dp = (char *)&ppa;
916 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
917 syslog (LOG_ERR, "Can't assign new interface");
919 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
920 if (if_fd < 0) {
921 syslog(LOG_ERR, "Can't open /dev/tap (2)");
922 return -1;
924 if(ioctl(if_fd, I_PUSH, "ip") < 0){
925 syslog(LOG_ERR, "Can't push IP module");
926 return -1;
929 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
930 syslog(LOG_ERR, "Can't get flags\n");
932 snprintf (actual_name, 32, "tap%d", ppa);
933 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
935 ifr.lifr_ppa = ppa;
936 /* Assign ppa according to the unit number returned by tun device */
938 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
939 syslog (LOG_ERR, "Can't set PPA %d", ppa);
940 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
941 syslog (LOG_ERR, "Can't get flags\n");
942 /* Push arp module to if_fd */
943 if (ioctl (if_fd, I_PUSH, "arp") < 0)
944 syslog (LOG_ERR, "Can't push ARP module (2)");
946 /* Push arp module to ip_fd */
947 if (ioctl (ip_fd, I_POP, NULL) < 0)
948 syslog (LOG_ERR, "I_POP failed\n");
949 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
950 syslog (LOG_ERR, "Can't push ARP module (3)\n");
951 /* Open arp_fd */
952 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
953 if (arp_fd < 0)
954 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
956 /* Set ifname to arp */
957 strioc_if.ic_cmd = SIOCSLIFNAME;
958 strioc_if.ic_timout = 0;
959 strioc_if.ic_len = sizeof(ifr);
960 strioc_if.ic_dp = (char *)&ifr;
961 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
962 syslog (LOG_ERR, "Can't set ifname to arp\n");
965 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
966 syslog(LOG_ERR, "Can't link TAP device to IP");
967 return -1;
970 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
971 syslog (LOG_ERR, "Can't link TAP device to ARP");
973 close (if_fd);
975 memset(&ifr, 0x0, sizeof(ifr));
976 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
977 ifr.lifr_ip_muxid = ip_muxid;
978 ifr.lifr_arp_muxid = arp_muxid;
980 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
982 ioctl (ip_fd, I_PUNLINK , arp_muxid);
983 ioctl (ip_fd, I_PUNLINK, ip_muxid);
984 syslog (LOG_ERR, "Can't set multiplexor id");
987 snprintf(dev, dev_size, "tap%d", ppa);
988 return tap_fd;
991 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
993 char dev[10]="";
994 int fd;
995 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
996 fprintf(stderr, "Cannot allocate TAP device\n");
997 return -1;
999 pstrcpy(ifname, ifname_size, dev);
1000 fcntl(fd, F_SETFL, O_NONBLOCK);
1001 return fd;
1003 #elif defined (_AIX)
1004 static int tap_open(char *ifname, int ifname_size)
1006 fprintf (stderr, "no tap on AIX\n");
1007 return -1;
1009 #else
1010 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1012 struct ifreq ifr;
1013 int fd, ret;
1015 TFR(fd = open("/dev/net/tun", O_RDWR));
1016 if (fd < 0) {
1017 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1018 return -1;
1020 memset(&ifr, 0, sizeof(ifr));
1021 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1023 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
1025 unsigned int features;
1027 if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&
1028 features & IFF_VNET_HDR) {
1029 *vnet_hdr = 1;
1030 ifr.ifr_flags |= IFF_VNET_HDR;
1033 #endif
1035 if (ifname[0] != '\0')
1036 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
1037 else
1038 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
1039 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1040 if (ret != 0) {
1041 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1042 close(fd);
1043 return -1;
1045 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1046 fcntl(fd, F_SETFL, O_NONBLOCK);
1047 return fd;
1049 #endif
1051 static int launch_script(const char *setup_script, const char *ifname, int fd)
1053 int pid, status;
1054 char *args[3];
1055 char **parg;
1057 /* try to launch network script */
1058 pid = fork();
1059 if (pid >= 0) {
1060 if (pid == 0) {
1061 int open_max = sysconf (_SC_OPEN_MAX), i;
1062 for (i = 0; i < open_max; i++)
1063 if (i != STDIN_FILENO &&
1064 i != STDOUT_FILENO &&
1065 i != STDERR_FILENO &&
1066 i != fd)
1067 close(i);
1069 parg = args;
1070 *parg++ = (char *)setup_script;
1071 *parg++ = (char *)ifname;
1072 *parg++ = NULL;
1073 execv(setup_script, args);
1074 _exit(1);
1076 while (waitpid(pid, &status, 0) != pid);
1077 if (!WIFEXITED(status) ||
1078 WEXITSTATUS(status) != 0) {
1079 fprintf(stderr, "%s: could not launch network script\n",
1080 setup_script);
1081 return -1;
1084 return 0;
1087 static int net_tap_init(VLANState *vlan, const char *ifname1,
1088 const char *setup_script, const char *down_script)
1090 TAPState *s;
1091 int fd;
1092 int vnet_hdr;
1093 char ifname[128];
1095 if (ifname1 != NULL)
1096 pstrcpy(ifname, sizeof(ifname), ifname1);
1097 else
1098 ifname[0] = '\0';
1099 vnet_hdr = 0;
1100 TFR(fd = tap_open(ifname, sizeof(ifname), &vnet_hdr));
1101 if (fd < 0)
1102 return -1;
1104 if (!setup_script || !strcmp(setup_script, "no"))
1105 setup_script = "";
1106 if (setup_script[0] != '\0') {
1107 if (launch_script(setup_script, ifname, fd))
1108 return -1;
1110 s = net_tap_fd_init(vlan, fd, vnet_hdr);
1111 if (!s)
1112 return -1;
1114 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1115 "tap: ifname=%s setup_script=%s", ifname, setup_script);
1116 if (down_script && strcmp(down_script, "no"))
1117 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1118 return 0;
1121 #endif /* !_WIN32 */
1123 #if defined(CONFIG_VDE)
1124 typedef struct VDEState {
1125 VLANClientState *vc;
1126 VDECONN *vde;
1127 } VDEState;
1129 static void vde_to_qemu(void *opaque)
1131 VDEState *s = opaque;
1132 uint8_t buf[4096];
1133 int size;
1135 size = vde_recv(s->vde, buf, sizeof(buf), 0);
1136 if (size > 0) {
1137 qemu_send_packet(s->vc, buf, size);
1141 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
1143 VDEState *s = opaque;
1144 int ret;
1145 for(;;) {
1146 ret = vde_send(s->vde, buf, size, 0);
1147 if (ret < 0 && errno == EINTR) {
1148 } else {
1149 break;
1154 static int net_vde_init(VLANState *vlan, const char *sock, int port,
1155 const char *group, int mode)
1157 VDEState *s;
1158 char *init_group = strlen(group) ? (char *)group : NULL;
1159 char *init_sock = strlen(sock) ? (char *)sock : NULL;
1161 struct vde_open_args args = {
1162 .port = port,
1163 .group = init_group,
1164 .mode = mode,
1167 s = qemu_mallocz(sizeof(VDEState));
1168 if (!s)
1169 return -1;
1170 s->vde = vde_open(init_sock, "QEMU", &args);
1171 if (!s->vde){
1172 free(s);
1173 return -1;
1175 s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
1176 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1177 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
1178 sock, vde_datafd(s->vde));
1179 return 0;
1181 #endif
1183 /* network connection */
1184 typedef struct NetSocketState {
1185 VLANClientState *vc;
1186 int fd;
1187 int state; /* 0 = getting length, 1 = getting data */
1188 int index;
1189 int packet_len;
1190 uint8_t buf[4096];
1191 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1192 } NetSocketState;
1194 typedef struct NetSocketListenState {
1195 VLANState *vlan;
1196 int fd;
1197 } NetSocketListenState;
1199 /* XXX: we consider we can send the whole packet without blocking */
1200 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1202 NetSocketState *s = opaque;
1203 uint32_t len;
1204 len = htonl(size);
1206 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1207 send_all(s->fd, buf, size);
1210 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1212 NetSocketState *s = opaque;
1213 sendto(s->fd, buf, size, 0,
1214 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1217 static void net_socket_send(void *opaque)
1219 NetSocketState *s = opaque;
1220 int l, size, err;
1221 uint8_t buf1[4096];
1222 const uint8_t *buf;
1224 size = recv(s->fd, buf1, sizeof(buf1), 0);
1225 if (size < 0) {
1226 err = socket_error();
1227 if (err != EWOULDBLOCK)
1228 goto eoc;
1229 } else if (size == 0) {
1230 /* end of connection */
1231 eoc:
1232 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1233 closesocket(s->fd);
1234 return;
1236 buf = buf1;
1237 while (size > 0) {
1238 /* reassemble a packet from the network */
1239 switch(s->state) {
1240 case 0:
1241 l = 4 - s->index;
1242 if (l > size)
1243 l = size;
1244 memcpy(s->buf + s->index, buf, l);
1245 buf += l;
1246 size -= l;
1247 s->index += l;
1248 if (s->index == 4) {
1249 /* got length */
1250 s->packet_len = ntohl(*(uint32_t *)s->buf);
1251 s->index = 0;
1252 s->state = 1;
1254 break;
1255 case 1:
1256 l = s->packet_len - s->index;
1257 if (l > size)
1258 l = size;
1259 memcpy(s->buf + s->index, buf, l);
1260 s->index += l;
1261 buf += l;
1262 size -= l;
1263 if (s->index >= s->packet_len) {
1264 qemu_send_packet(s->vc, s->buf, s->packet_len);
1265 s->index = 0;
1266 s->state = 0;
1268 break;
1273 static void net_socket_send_dgram(void *opaque)
1275 NetSocketState *s = opaque;
1276 int size;
1278 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1279 if (size < 0)
1280 return;
1281 if (size == 0) {
1282 /* end of connection */
1283 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1284 return;
1286 qemu_send_packet(s->vc, s->buf, size);
1289 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1291 struct ip_mreq imr;
1292 int fd;
1293 int val, ret;
1294 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1295 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1296 inet_ntoa(mcastaddr->sin_addr),
1297 (int)ntohl(mcastaddr->sin_addr.s_addr));
1298 return -1;
1301 fd = socket(PF_INET, SOCK_DGRAM, 0);
1302 if (fd < 0) {
1303 perror("socket(PF_INET, SOCK_DGRAM)");
1304 return -1;
1307 val = 1;
1308 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1309 (const char *)&val, sizeof(val));
1310 if (ret < 0) {
1311 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1312 goto fail;
1315 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1316 if (ret < 0) {
1317 perror("bind");
1318 goto fail;
1321 /* Add host to multicast group */
1322 imr.imr_multiaddr = mcastaddr->sin_addr;
1323 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1325 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1326 (const char *)&imr, sizeof(struct ip_mreq));
1327 if (ret < 0) {
1328 perror("setsockopt(IP_ADD_MEMBERSHIP)");
1329 goto fail;
1332 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1333 val = 1;
1334 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1335 (const char *)&val, sizeof(val));
1336 if (ret < 0) {
1337 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1338 goto fail;
1341 socket_set_nonblock(fd);
1342 return fd;
1343 fail:
1344 if (fd >= 0)
1345 closesocket(fd);
1346 return -1;
1349 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
1350 int is_connected)
1352 struct sockaddr_in saddr;
1353 int newfd;
1354 socklen_t saddr_len;
1355 NetSocketState *s;
1357 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1358 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1359 * by ONLY ONE process: we must "clone" this dgram socket --jjo
1362 if (is_connected) {
1363 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1364 /* must be bound */
1365 if (saddr.sin_addr.s_addr==0) {
1366 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1367 fd);
1368 return NULL;
1370 /* clone dgram socket */
1371 newfd = net_socket_mcast_create(&saddr);
1372 if (newfd < 0) {
1373 /* error already reported by net_socket_mcast_create() */
1374 close(fd);
1375 return NULL;
1377 /* clone newfd to fd, close newfd */
1378 dup2(newfd, fd);
1379 close(newfd);
1381 } else {
1382 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1383 fd, strerror(errno));
1384 return NULL;
1388 s = qemu_mallocz(sizeof(NetSocketState));
1389 if (!s)
1390 return NULL;
1391 s->fd = fd;
1393 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
1394 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1396 /* mcast: save bound address as dst */
1397 if (is_connected) s->dgram_dst=saddr;
1399 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1400 "socket: fd=%d (%s mcast=%s:%d)",
1401 fd, is_connected? "cloned" : "",
1402 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1403 return s;
1406 static void net_socket_connect(void *opaque)
1408 NetSocketState *s = opaque;
1409 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1412 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
1413 int is_connected)
1415 NetSocketState *s;
1416 s = qemu_mallocz(sizeof(NetSocketState));
1417 if (!s)
1418 return NULL;
1419 s->fd = fd;
1420 s->vc = qemu_new_vlan_client(vlan,
1421 net_socket_receive, NULL, s);
1422 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1423 "socket: fd=%d", fd);
1424 if (is_connected) {
1425 net_socket_connect(s);
1426 } else {
1427 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1429 return s;
1432 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
1433 int is_connected)
1435 int so_type=-1, optlen=sizeof(so_type);
1437 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1438 (socklen_t *)&optlen)< 0) {
1439 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1440 return NULL;
1442 switch(so_type) {
1443 case SOCK_DGRAM:
1444 return net_socket_fd_init_dgram(vlan, fd, is_connected);
1445 case SOCK_STREAM:
1446 return net_socket_fd_init_stream(vlan, fd, is_connected);
1447 default:
1448 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1449 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1450 return net_socket_fd_init_stream(vlan, fd, is_connected);
1452 return NULL;
1455 static void net_socket_accept(void *opaque)
1457 NetSocketListenState *s = opaque;
1458 NetSocketState *s1;
1459 struct sockaddr_in saddr;
1460 socklen_t len;
1461 int fd;
1463 for(;;) {
1464 len = sizeof(saddr);
1465 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1466 if (fd < 0 && errno != EINTR) {
1467 return;
1468 } else if (fd >= 0) {
1469 break;
1472 s1 = net_socket_fd_init(s->vlan, fd, 1);
1473 if (!s1) {
1474 closesocket(fd);
1475 } else {
1476 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1477 "socket: connection from %s:%d",
1478 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1482 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
1484 NetSocketListenState *s;
1485 int fd, val, ret;
1486 struct sockaddr_in saddr;
1488 if (parse_host_port(&saddr, host_str) < 0)
1489 return -1;
1491 s = qemu_mallocz(sizeof(NetSocketListenState));
1492 if (!s)
1493 return -1;
1495 fd = socket(PF_INET, SOCK_STREAM, 0);
1496 if (fd < 0) {
1497 perror("socket");
1498 return -1;
1500 socket_set_nonblock(fd);
1502 /* allow fast reuse */
1503 val = 1;
1504 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1506 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1507 if (ret < 0) {
1508 perror("bind");
1509 return -1;
1511 ret = listen(fd, 0);
1512 if (ret < 0) {
1513 perror("listen");
1514 return -1;
1516 s->vlan = vlan;
1517 s->fd = fd;
1518 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1519 return 0;
1522 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
1524 NetSocketState *s;
1525 int fd, connected, ret, err;
1526 struct sockaddr_in saddr;
1528 if (parse_host_port(&saddr, host_str) < 0)
1529 return -1;
1531 fd = socket(PF_INET, SOCK_STREAM, 0);
1532 if (fd < 0) {
1533 perror("socket");
1534 return -1;
1536 socket_set_nonblock(fd);
1538 connected = 0;
1539 for(;;) {
1540 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1541 if (ret < 0) {
1542 err = socket_error();
1543 if (err == EINTR || err == EWOULDBLOCK) {
1544 } else if (err == EINPROGRESS) {
1545 break;
1546 #ifdef _WIN32
1547 } else if (err == WSAEALREADY) {
1548 break;
1549 #endif
1550 } else {
1551 perror("connect");
1552 closesocket(fd);
1553 return -1;
1555 } else {
1556 connected = 1;
1557 break;
1560 s = net_socket_fd_init(vlan, fd, connected);
1561 if (!s)
1562 return -1;
1563 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1564 "socket: connect to %s:%d",
1565 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1566 return 0;
1569 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
1571 NetSocketState *s;
1572 int fd;
1573 struct sockaddr_in saddr;
1575 if (parse_host_port(&saddr, host_str) < 0)
1576 return -1;
1579 fd = net_socket_mcast_create(&saddr);
1580 if (fd < 0)
1581 return -1;
1583 s = net_socket_fd_init(vlan, fd, 0);
1584 if (!s)
1585 return -1;
1587 s->dgram_dst = saddr;
1589 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1590 "socket: mcast=%s:%d",
1591 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1592 return 0;
1596 /* find or alloc a new VLAN */
1597 VLANState *qemu_find_vlan(int id)
1599 VLANState **pvlan, *vlan;
1600 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1601 if (vlan->id == id)
1602 return vlan;
1604 vlan = qemu_mallocz(sizeof(VLANState));
1605 if (!vlan)
1606 return NULL;
1607 vlan->id = id;
1608 vlan->next = NULL;
1609 pvlan = &first_vlan;
1610 while (*pvlan != NULL)
1611 pvlan = &(*pvlan)->next;
1612 *pvlan = vlan;
1613 return vlan;
1616 int net_client_init(const char *device, const char *p)
1618 char buf[1024];
1619 int vlan_id, ret;
1620 VLANState *vlan;
1622 vlan_id = 0;
1623 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1624 vlan_id = strtol(buf, NULL, 0);
1626 vlan = qemu_find_vlan(vlan_id);
1627 if (!vlan) {
1628 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
1629 return -1;
1631 if (!strcmp(device, "nic")) {
1632 NICInfo *nd;
1633 uint8_t *macaddr;
1635 if (nb_nics >= MAX_NICS) {
1636 fprintf(stderr, "Too Many NICs\n");
1637 return -1;
1639 nd = &nd_table[nb_nics];
1640 macaddr = nd->macaddr;
1641 macaddr[0] = 0x52;
1642 macaddr[1] = 0x54;
1643 macaddr[2] = 0x00;
1644 macaddr[3] = 0x12;
1645 macaddr[4] = 0x34;
1646 macaddr[5] = 0x56 + nb_nics;
1648 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1649 if (parse_macaddr(macaddr, buf) < 0) {
1650 fprintf(stderr, "invalid syntax for ethernet address\n");
1651 return -1;
1654 if (get_param_value(buf, sizeof(buf), "model", p)) {
1655 nd->model = strdup(buf);
1657 nd->vlan = vlan;
1658 nb_nics++;
1659 vlan->nb_guest_devs++;
1660 ret = 0;
1661 } else
1662 if (!strcmp(device, "none")) {
1663 /* does nothing. It is needed to signal that no network cards
1664 are wanted */
1665 ret = 0;
1666 } else
1667 #ifdef CONFIG_SLIRP
1668 if (!strcmp(device, "user")) {
1669 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1670 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1672 vlan->nb_host_devs++;
1673 ret = net_slirp_init(vlan);
1674 } else
1675 #endif
1676 #ifdef _WIN32
1677 if (!strcmp(device, "tap")) {
1678 char ifname[64];
1679 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1680 fprintf(stderr, "tap: no interface name\n");
1681 return -1;
1683 vlan->nb_host_devs++;
1684 ret = tap_win32_init(vlan, ifname);
1685 } else
1686 #elif defined (_AIX)
1687 #else
1688 if (!strcmp(device, "tap")) {
1689 char ifname[64];
1690 char setup_script[1024], down_script[1024];
1691 int fd;
1692 vlan->nb_host_devs++;
1693 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1694 fd = strtol(buf, NULL, 0);
1695 fcntl(fd, F_SETFL, O_NONBLOCK);
1696 ret = -1;
1697 if (net_tap_fd_init(vlan, fd, tap_probe_vnet_hdr(fd)))
1698 ret = 0;
1699 } else {
1700 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1701 ifname[0] = '\0';
1703 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1704 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1706 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1707 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1709 ret = net_tap_init(vlan, ifname, setup_script, down_script);
1711 } else
1712 #endif
1713 if (!strcmp(device, "socket")) {
1714 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1715 int fd;
1716 fd = strtol(buf, NULL, 0);
1717 ret = -1;
1718 if (net_socket_fd_init(vlan, fd, 1))
1719 ret = 0;
1720 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1721 ret = net_socket_listen_init(vlan, buf);
1722 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1723 ret = net_socket_connect_init(vlan, buf);
1724 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1725 ret = net_socket_mcast_init(vlan, buf);
1726 } else {
1727 fprintf(stderr, "Unknown socket options: %s\n", p);
1728 return -1;
1730 vlan->nb_host_devs++;
1731 } else
1732 #ifdef CONFIG_VDE
1733 if (!strcmp(device, "vde")) {
1734 char vde_sock[1024], vde_group[512];
1735 int vde_port, vde_mode;
1736 vlan->nb_host_devs++;
1737 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1738 vde_sock[0] = '\0';
1740 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1741 vde_port = strtol(buf, NULL, 10);
1742 } else {
1743 vde_port = 0;
1745 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1746 vde_group[0] = '\0';
1748 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1749 vde_mode = strtol(buf, NULL, 8);
1750 } else {
1751 vde_mode = 0700;
1753 ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
1754 } else
1755 #endif
1757 fprintf(stderr, "Unknown network device: %s\n", device);
1758 return -1;
1760 if (ret < 0) {
1761 fprintf(stderr, "Could not initialize device '%s'\n", device);
1764 return ret;
1767 void net_client_uninit(NICInfo *nd)
1769 nd->vlan->nb_guest_devs--; /* XXX: free vlan on last reference */
1770 nb_nics--;
1771 nd->used = 0;
1772 free((void *)nd->model);
1775 int net_client_parse(const char *str)
1777 const char *p;
1778 char *q;
1779 char device[64];
1781 p = str;
1782 q = device;
1783 while (*p != '\0' && *p != ',') {
1784 if ((q - device) < sizeof(device) - 1)
1785 *q++ = *p;
1786 p++;
1788 *q = '\0';
1789 if (*p == ',')
1790 p++;
1792 return net_client_init(device, p);
1795 void do_info_network(void)
1797 VLANState *vlan;
1798 VLANClientState *vc;
1800 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1801 term_printf("VLAN %d devices:\n", vlan->id);
1802 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
1803 term_printf(" %s\n", vc->info_str);
1807 void net_cleanup(void)
1809 VLANState *vlan;
1811 #if !defined(_WIN32)
1812 /* close network clients */
1813 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1814 VLANClientState *vc;
1816 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1817 if (vc->fd_read == tap_receive) {
1818 char ifname[64];
1819 TAPState *s = vc->opaque;
1821 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
1822 s->down_script[0])
1823 launch_script(s->down_script, ifname, s->fd);
1825 #if defined(CONFIG_VDE)
1826 if (vc->fd_read == vde_from_qemu) {
1827 VDEState *s = vc->opaque;
1828 vde_close(s->vde);
1830 #endif
1833 #endif
1836 void net_client_check(void)
1838 VLANState *vlan;
1840 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1841 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
1842 continue;
1843 if (vlan->nb_guest_devs == 0)
1844 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
1845 if (vlan->nb_host_devs == 0)
1846 fprintf(stderr,
1847 "Warning: vlan %d is not connected to host network\n",
1848 vlan->id);