kvm: extboot: Update number of HDs reported by BIOS
[qemu-kvm/fedora.git] / net.c
blob08cd8c176883ab3bfa31f62ae02a4db8a3a35164
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 && !vc->link_down) {
418 if (!vc->fd_can_read || vc->fd_can_read(vc->opaque)) {
419 vc->fd_read(vc->opaque, buf, size);
420 ret = 0;
424 return ret;
427 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
428 int iovcnt)
430 uint8_t buffer[4096];
431 size_t offset = 0;
432 int i;
434 for (i = 0; i < iovcnt; i++) {
435 size_t len;
437 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
438 memcpy(buffer + offset, iov[i].iov_base, len);
439 offset += len;
442 vc->fd_read(vc->opaque, buffer, offset);
444 return offset;
447 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
449 size_t offset = 0;
450 int i;
452 for (i = 0; i < iovcnt; i++)
453 offset += iov[i].iov_len;
454 return offset;
457 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
458 int iovcnt)
460 VLANState *vlan = vc1->vlan;
461 VLANClientState *vc;
462 ssize_t max_len = 0;
464 if (vc1->link_down)
465 return calc_iov_length(iov, iovcnt);
467 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
468 ssize_t len = 0;
470 if (vc == vc1)
471 continue;
473 if (vc->link_down)
474 len = calc_iov_length(iov, iovcnt);
475 if (vc->fd_readv)
476 len = vc->fd_readv(vc->opaque, iov, iovcnt);
477 else if (vc->fd_read)
478 len = vc_sendv_compat(vc, iov, iovcnt);
480 max_len = MAX(max_len, len);
483 return max_len;
486 #if defined(CONFIG_SLIRP)
488 /* slirp network adapter */
490 static int slirp_inited;
491 static int slirp_restrict;
492 static char *slirp_ip;
493 static VLANClientState *slirp_vc;
495 int slirp_can_output(void)
497 return !slirp_vc || qemu_can_send_packet(slirp_vc);
500 void slirp_output(const uint8_t *pkt, int pkt_len)
502 #ifdef DEBUG_SLIRP
503 printf("slirp output:\n");
504 hex_dump(stdout, pkt, pkt_len);
505 #endif
506 if (!slirp_vc)
507 return;
508 qemu_send_packet(slirp_vc, pkt, pkt_len);
511 int slirp_is_inited(void)
513 return slirp_inited;
516 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
518 #ifdef DEBUG_SLIRP
519 printf("slirp input:\n");
520 hex_dump(stdout, buf, size);
521 #endif
522 slirp_input(buf, size);
525 static int net_slirp_init(VLANState *vlan, const char *model, const char *name)
527 if (!slirp_inited) {
528 slirp_inited = 1;
529 slirp_init(slirp_restrict, slirp_ip);
531 slirp_vc = qemu_new_vlan_client(vlan, model, name,
532 slirp_receive, NULL, NULL, NULL);
533 slirp_vc->info_str[0] = '\0';
534 return 0;
537 void net_slirp_redir(const char *redir_str)
539 int is_udp;
540 char buf[256], *r;
541 const char *p;
542 struct in_addr guest_addr;
543 int host_port, guest_port;
545 if (!slirp_inited) {
546 slirp_inited = 1;
547 slirp_init(slirp_restrict, slirp_ip);
550 p = redir_str;
551 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
552 goto fail;
553 if (!strcmp(buf, "tcp")) {
554 is_udp = 0;
555 } else if (!strcmp(buf, "udp")) {
556 is_udp = 1;
557 } else {
558 goto fail;
561 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
562 goto fail;
563 host_port = strtol(buf, &r, 0);
564 if (r == buf)
565 goto fail;
567 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
568 goto fail;
569 if (buf[0] == '\0') {
570 pstrcpy(buf, sizeof(buf), "10.0.2.15");
572 if (!inet_aton(buf, &guest_addr))
573 goto fail;
575 guest_port = strtol(p, &r, 0);
576 if (r == p)
577 goto fail;
579 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
580 fprintf(stderr, "qemu: could not set up redirection\n");
581 exit(1);
583 return;
584 fail:
585 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
586 exit(1);
589 #ifndef _WIN32
591 static char smb_dir[1024];
593 static void erase_dir(char *dir_name)
595 DIR *d;
596 struct dirent *de;
597 char filename[1024];
599 /* erase all the files in the directory */
600 if ((d = opendir(dir_name)) != 0) {
601 for(;;) {
602 de = readdir(d);
603 if (!de)
604 break;
605 if (strcmp(de->d_name, ".") != 0 &&
606 strcmp(de->d_name, "..") != 0) {
607 snprintf(filename, sizeof(filename), "%s/%s",
608 smb_dir, de->d_name);
609 if (unlink(filename) != 0) /* is it a directory? */
610 erase_dir(filename);
613 closedir(d);
614 rmdir(dir_name);
618 /* automatic user mode samba server configuration */
619 static void smb_exit(void)
621 erase_dir(smb_dir);
624 /* automatic user mode samba server configuration */
625 void net_slirp_smb(const char *exported_dir)
627 char smb_conf[1024];
628 char smb_cmdline[1024];
629 FILE *f;
631 if (!slirp_inited) {
632 slirp_inited = 1;
633 slirp_init(slirp_restrict, slirp_ip);
636 /* XXX: better tmp dir construction */
637 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
638 if (mkdir(smb_dir, 0700) < 0) {
639 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
640 exit(1);
642 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
644 f = fopen(smb_conf, "w");
645 if (!f) {
646 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
647 exit(1);
649 fprintf(f,
650 "[global]\n"
651 "private dir=%s\n"
652 "smb ports=0\n"
653 "socket address=127.0.0.1\n"
654 "pid directory=%s\n"
655 "lock directory=%s\n"
656 "log file=%s/log.smbd\n"
657 "smb passwd file=%s/smbpasswd\n"
658 "security = share\n"
659 "[qemu]\n"
660 "path=%s\n"
661 "read only=no\n"
662 "guest ok=yes\n",
663 smb_dir,
664 smb_dir,
665 smb_dir,
666 smb_dir,
667 smb_dir,
668 exported_dir
670 fclose(f);
671 atexit(smb_exit);
673 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
674 SMBD_COMMAND, smb_conf);
676 slirp_add_exec(0, smb_cmdline, 4, 139);
679 #endif /* !defined(_WIN32) */
680 void do_info_slirp(void)
682 slirp_stats();
685 struct VMChannel {
686 CharDriverState *hd;
687 int port;
688 } *vmchannels;
690 static int vmchannel_can_read(void *opaque)
692 struct VMChannel *vmc = (struct VMChannel*)opaque;
693 return slirp_socket_can_recv(4, vmc->port);
696 static void vmchannel_read(void *opaque, const uint8_t *buf, int size)
698 struct VMChannel *vmc = (struct VMChannel*)opaque;
699 slirp_socket_recv(4, vmc->port, buf, size);
702 #endif /* CONFIG_SLIRP */
704 #ifdef _WIN32
706 int tap_has_vnet_hdr(void *opaque)
708 return 0;
711 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
715 #else /* !defined(_WIN32) */
717 /* Maximum GSO packet size (64k) plus plenty of room for
718 * the ethernet and virtio_net headers
720 #define TAP_BUFSIZE (4096 + 65536)
722 #ifdef IFF_VNET_HDR
723 #include <linux/virtio_net.h>
724 #endif
726 typedef struct TAPState {
727 VLANClientState *vc;
728 int fd;
729 char down_script[1024];
730 char down_script_arg[128];
731 char buf[TAP_BUFSIZE];
732 int size;
733 unsigned int has_vnet_hdr : 1;
734 unsigned int using_vnet_hdr : 1;
735 } TAPState;
737 static int launch_script(const char *setup_script, const char *ifname, int fd);
739 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
740 int iovcnt)
742 TAPState *s = opaque;
743 ssize_t len;
745 do {
746 len = writev(s->fd, iov, iovcnt);
747 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
749 return len;
752 static void tap_receive(void *opaque, const uint8_t *buf, int size)
754 struct iovec iov[2];
755 int i = 0;
757 #ifdef IFF_VNET_HDR
758 TAPState *s = opaque;
759 struct virtio_net_hdr hdr = { 0, };
761 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
762 iov[i].iov_base = &hdr;
763 iov[i].iov_len = sizeof(hdr);
764 i++;
766 #endif
768 iov[i].iov_base = (char *) buf;
769 iov[i].iov_len = size;
770 i++;
772 tap_receive_iov(opaque, iov, i);
775 static int tap_can_send(void *opaque)
777 TAPState *s = opaque;
778 VLANClientState *vc;
779 int can_receive = 0;
781 /* Check to see if any of our clients can receive a packet */
782 for (vc = s->vc->vlan->first_client; vc; vc = vc->next) {
783 /* Skip ourselves */
784 if (vc == s->vc)
785 continue;
787 if (!vc->fd_can_read) {
788 /* no fd_can_read handler, they always can receive */
789 can_receive = 1;
790 } else
791 can_receive = vc->fd_can_read(vc->opaque);
793 /* Once someone can receive, we try to send a packet */
794 if (can_receive)
795 break;
798 return can_receive;
801 static int tap_send_packet(TAPState *s)
803 uint8_t *buf = (uint8_t *)s->buf;
804 int size = s->size;
806 #ifdef IFF_VNET_HDR
807 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
808 buf += sizeof(struct virtio_net_hdr);
809 size -= sizeof(struct virtio_net_hdr);
811 #endif
813 return qemu_send_packet(s->vc, buf, size);
816 static void tap_send(void *opaque)
818 TAPState *s = opaque;
820 /* First try to send any buffered packet */
821 if (s->size > 0) {
822 int err;
824 /* If noone can receive the packet, buffer it */
825 err = tap_send_packet(s);
826 if (err == -EAGAIN)
827 return;
830 /* Read packets until we hit EAGAIN */
831 do {
832 #ifdef __sun__
833 struct strbuf sbuf;
834 int f = 0;
835 sbuf.maxlen = sizeof(s->buf);
836 sbuf.buf = s->buf;
837 s->size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
838 #else
839 // FIXME: kvm_sleep_begin();
840 s->size = read(s->fd, s->buf, sizeof(s->buf));
841 // FIXME: kvm_sleep_end();
842 #endif
844 if (s->size == -1 && errno == EINTR)
845 continue;
847 if (s->size > 0) {
848 int err;
850 /* If noone can receive the packet, buffer it */
851 err = tap_send_packet(s);
852 if (err == -EAGAIN)
853 break;
855 } while (s->size > 0);
858 int tap_has_vnet_hdr(void *opaque)
860 VLANClientState *vc = opaque;
861 TAPState *s = vc->opaque;
863 return s ? s->has_vnet_hdr : 0;
866 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
868 VLANClientState *vc = opaque;
869 TAPState *s = vc->opaque;
871 if (!s || !s->has_vnet_hdr)
872 return;
874 s->using_vnet_hdr = using_vnet_hdr != 0;
877 static int tap_probe_vnet_hdr(int fd)
879 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
880 struct ifreq ifr;
882 if (ioctl(fd, TUNGETIFF, &ifr) != 0) {
883 fprintf(stderr, "TUNGETIFF ioctl() failed: %s\n", strerror(errno));
884 return 0;
887 return ifr.ifr_flags & IFF_VNET_HDR;
888 #else
889 return 0;
890 #endif
893 #ifdef TUNSETOFFLOAD
894 static void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6,
895 int ecn)
897 TAPState *s = vc->opaque;
898 unsigned int offload = 0;
900 if (csum) {
901 offload |= TUN_F_CSUM;
902 if (tso4)
903 offload |= TUN_F_TSO4;
904 if (tso6)
905 offload |= TUN_F_TSO6;
906 if ((tso4 || tso6) && ecn)
907 offload |= TUN_F_TSO_ECN;
910 if (ioctl(s->fd, TUNSETOFFLOAD, offload) != 0)
911 fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n",
912 strerror(errno));
914 #endif /* TUNSETOFFLOAD */
916 static void tap_cleanup(VLANClientState *vc)
918 TAPState *s = vc->opaque;
920 if (s->down_script[0])
921 launch_script(s->down_script, s->down_script_arg, s->fd);
923 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
924 close(s->fd);
925 qemu_free(s);
928 /* fd support */
930 static TAPState *net_tap_fd_init(VLANState *vlan,
931 const char *model,
932 const char *name,
933 int fd,
934 int vnet_hdr)
936 TAPState *s;
938 s = qemu_mallocz(sizeof(TAPState));
939 s->fd = fd;
940 s->has_vnet_hdr = vnet_hdr != 0;
941 s->vc = qemu_new_vlan_client(vlan, model, name, tap_receive,
942 NULL, tap_cleanup, s);
943 #ifdef HAVE_IOVEC
944 s->vc->fd_readv = tap_receive_iov;
945 #endif
946 #ifdef TUNSETOFFLOAD
947 s->vc->set_offload = tap_set_offload;
948 #endif
949 qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
950 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
951 return s;
954 #if defined (_BSD) || defined (__FreeBSD_kernel__)
955 static int tap_open(char *ifname, int ifname_size)
957 int fd;
958 char *dev;
959 struct stat s;
961 TFR(fd = open("/dev/tap", O_RDWR));
962 if (fd < 0) {
963 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
964 return -1;
967 fstat(fd, &s);
968 dev = devname(s.st_rdev, S_IFCHR);
969 pstrcpy(ifname, ifname_size, dev);
971 fcntl(fd, F_SETFL, O_NONBLOCK);
972 return fd;
974 #elif defined(__sun__)
975 #define TUNNEWPPA (('T'<<16) | 0x0001)
977 * Allocate TAP device, returns opened fd.
978 * Stores dev name in the first arg(must be large enough).
980 int tap_alloc(char *dev, size_t dev_size)
982 int tap_fd, if_fd, ppa = -1;
983 static int ip_fd = 0;
984 char *ptr;
986 static int arp_fd = 0;
987 int ip_muxid, arp_muxid;
988 struct strioctl strioc_if, strioc_ppa;
989 int link_type = I_PLINK;;
990 struct lifreq ifr;
991 char actual_name[32] = "";
993 memset(&ifr, 0x0, sizeof(ifr));
995 if( *dev ){
996 ptr = dev;
997 while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
998 ppa = atoi(ptr);
1001 /* Check if IP device was opened */
1002 if( ip_fd )
1003 close(ip_fd);
1005 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
1006 if (ip_fd < 0) {
1007 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
1008 return -1;
1011 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
1012 if (tap_fd < 0) {
1013 syslog(LOG_ERR, "Can't open /dev/tap");
1014 return -1;
1017 /* Assign a new PPA and get its unit number. */
1018 strioc_ppa.ic_cmd = TUNNEWPPA;
1019 strioc_ppa.ic_timout = 0;
1020 strioc_ppa.ic_len = sizeof(ppa);
1021 strioc_ppa.ic_dp = (char *)&ppa;
1022 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
1023 syslog (LOG_ERR, "Can't assign new interface");
1025 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
1026 if (if_fd < 0) {
1027 syslog(LOG_ERR, "Can't open /dev/tap (2)");
1028 return -1;
1030 if(ioctl(if_fd, I_PUSH, "ip") < 0){
1031 syslog(LOG_ERR, "Can't push IP module");
1032 return -1;
1035 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
1036 syslog(LOG_ERR, "Can't get flags\n");
1038 snprintf (actual_name, 32, "tap%d", ppa);
1039 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1041 ifr.lifr_ppa = ppa;
1042 /* Assign ppa according to the unit number returned by tun device */
1044 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
1045 syslog (LOG_ERR, "Can't set PPA %d", ppa);
1046 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
1047 syslog (LOG_ERR, "Can't get flags\n");
1048 /* Push arp module to if_fd */
1049 if (ioctl (if_fd, I_PUSH, "arp") < 0)
1050 syslog (LOG_ERR, "Can't push ARP module (2)");
1052 /* Push arp module to ip_fd */
1053 if (ioctl (ip_fd, I_POP, NULL) < 0)
1054 syslog (LOG_ERR, "I_POP failed\n");
1055 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
1056 syslog (LOG_ERR, "Can't push ARP module (3)\n");
1057 /* Open arp_fd */
1058 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
1059 if (arp_fd < 0)
1060 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
1062 /* Set ifname to arp */
1063 strioc_if.ic_cmd = SIOCSLIFNAME;
1064 strioc_if.ic_timout = 0;
1065 strioc_if.ic_len = sizeof(ifr);
1066 strioc_if.ic_dp = (char *)&ifr;
1067 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
1068 syslog (LOG_ERR, "Can't set ifname to arp\n");
1071 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
1072 syslog(LOG_ERR, "Can't link TAP device to IP");
1073 return -1;
1076 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
1077 syslog (LOG_ERR, "Can't link TAP device to ARP");
1079 close (if_fd);
1081 memset(&ifr, 0x0, sizeof(ifr));
1082 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1083 ifr.lifr_ip_muxid = ip_muxid;
1084 ifr.lifr_arp_muxid = arp_muxid;
1086 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
1088 ioctl (ip_fd, I_PUNLINK , arp_muxid);
1089 ioctl (ip_fd, I_PUNLINK, ip_muxid);
1090 syslog (LOG_ERR, "Can't set multiplexor id");
1093 snprintf(dev, dev_size, "tap%d", ppa);
1094 return tap_fd;
1097 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1099 char dev[10]="";
1100 int fd;
1101 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
1102 fprintf(stderr, "Cannot allocate TAP device\n");
1103 return -1;
1105 pstrcpy(ifname, ifname_size, dev);
1106 fcntl(fd, F_SETFL, O_NONBLOCK);
1107 return fd;
1109 #elif defined (_AIX)
1110 static int tap_open(char *ifname, int ifname_size)
1112 fprintf (stderr, "no tap on AIX\n");
1113 return -1;
1115 #else
1116 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1118 struct ifreq ifr;
1119 int fd, ret;
1121 TFR(fd = open("/dev/net/tun", O_RDWR));
1122 if (fd < 0) {
1123 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1124 return -1;
1126 memset(&ifr, 0, sizeof(ifr));
1127 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1129 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
1131 unsigned int features;
1133 if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&
1134 features & IFF_VNET_HDR) {
1135 *vnet_hdr = 1;
1136 ifr.ifr_flags |= IFF_VNET_HDR;
1139 #endif
1141 if (ifname[0] != '\0')
1142 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
1143 else
1144 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
1145 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1146 if (ret != 0) {
1147 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1148 close(fd);
1149 return -1;
1151 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1152 fcntl(fd, F_SETFL, O_NONBLOCK);
1153 return fd;
1155 #endif
1157 static int launch_script(const char *setup_script, const char *ifname, int fd)
1159 int pid, status;
1160 char *args[3];
1161 char **parg;
1163 /* try to launch network script */
1164 pid = fork();
1165 if (pid >= 0) {
1166 if (pid == 0) {
1167 int open_max = sysconf (_SC_OPEN_MAX), i;
1168 for (i = 0; i < open_max; i++)
1169 if (i != STDIN_FILENO &&
1170 i != STDOUT_FILENO &&
1171 i != STDERR_FILENO &&
1172 i != fd)
1173 close(i);
1175 parg = args;
1176 *parg++ = (char *)setup_script;
1177 *parg++ = (char *)ifname;
1178 *parg++ = NULL;
1179 execv(setup_script, args);
1180 _exit(1);
1182 while (waitpid(pid, &status, 0) != pid);
1183 if (!WIFEXITED(status) ||
1184 WEXITSTATUS(status) != 0) {
1185 fprintf(stderr, "%s: could not launch network script\n",
1186 setup_script);
1187 return -1;
1190 return 0;
1193 static int net_tap_init(VLANState *vlan, const char *model,
1194 const char *name, const char *ifname1,
1195 const char *setup_script, const char *down_script)
1197 TAPState *s;
1198 int fd;
1199 int vnet_hdr;
1200 char ifname[128];
1202 if (ifname1 != NULL)
1203 pstrcpy(ifname, sizeof(ifname), ifname1);
1204 else
1205 ifname[0] = '\0';
1206 vnet_hdr = 0;
1207 TFR(fd = tap_open(ifname, sizeof(ifname), &vnet_hdr));
1208 if (fd < 0)
1209 return -1;
1211 if (!setup_script || !strcmp(setup_script, "no"))
1212 setup_script = "";
1213 if (setup_script[0] != '\0') {
1214 if (launch_script(setup_script, ifname, fd))
1215 return -1;
1217 s = net_tap_fd_init(vlan, model, name, fd, vnet_hdr);
1218 if (!s)
1219 return -1;
1221 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1222 "ifname=%s,script=%s,downscript=%s",
1223 ifname, setup_script, down_script);
1224 if (down_script && strcmp(down_script, "no")) {
1225 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1226 snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1228 return 0;
1231 #endif /* !_WIN32 */
1233 #if defined(CONFIG_VDE)
1234 typedef struct VDEState {
1235 VLANClientState *vc;
1236 VDECONN *vde;
1237 } VDEState;
1239 static void vde_to_qemu(void *opaque)
1241 VDEState *s = opaque;
1242 uint8_t buf[4096];
1243 int size;
1245 size = vde_recv(s->vde, buf, sizeof(buf), 0);
1246 if (size > 0) {
1247 qemu_send_packet(s->vc, buf, size);
1251 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
1253 VDEState *s = opaque;
1254 int ret;
1255 for(;;) {
1256 ret = vde_send(s->vde, buf, size, 0);
1257 if (ret < 0 && errno == EINTR) {
1258 } else {
1259 break;
1264 static void vde_cleanup(VLANClientState *vc)
1266 VDEState *s = vc->opaque;
1267 qemu_set_fd_handler(vde_datafd(s->vde), NULL, NULL, NULL);
1268 vde_close(s->vde);
1269 qemu_free(s);
1272 static int net_vde_init(VLANState *vlan, const char *model,
1273 const char *name, const char *sock,
1274 int port, const char *group, int mode)
1276 VDEState *s;
1277 char *init_group = strlen(group) ? (char *)group : NULL;
1278 char *init_sock = strlen(sock) ? (char *)sock : NULL;
1280 struct vde_open_args args = {
1281 .port = port,
1282 .group = init_group,
1283 .mode = mode,
1286 s = qemu_mallocz(sizeof(VDEState));
1287 s->vde = vde_open(init_sock, "QEMU", &args);
1288 if (!s->vde){
1289 free(s);
1290 return -1;
1292 s->vc = qemu_new_vlan_client(vlan, model, name, vde_from_qemu,
1293 NULL, vde_cleanup, s);
1294 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1295 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1296 sock, vde_datafd(s->vde));
1297 return 0;
1299 #endif
1301 /* network connection */
1302 typedef struct NetSocketState {
1303 VLANClientState *vc;
1304 int fd;
1305 int state; /* 0 = getting length, 1 = getting data */
1306 unsigned int index;
1307 unsigned int packet_len;
1308 uint8_t buf[4096];
1309 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1310 } NetSocketState;
1312 typedef struct NetSocketListenState {
1313 VLANState *vlan;
1314 char *model;
1315 char *name;
1316 int fd;
1317 } NetSocketListenState;
1319 /* XXX: we consider we can send the whole packet without blocking */
1320 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1322 NetSocketState *s = opaque;
1323 uint32_t len;
1324 len = htonl(size);
1326 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1327 send_all(s->fd, buf, size);
1330 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1332 NetSocketState *s = opaque;
1333 sendto(s->fd, buf, size, 0,
1334 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1337 static void net_socket_send(void *opaque)
1339 NetSocketState *s = opaque;
1340 int size, err;
1341 unsigned l;
1342 uint8_t buf1[4096];
1343 const uint8_t *buf;
1345 size = recv(s->fd, buf1, sizeof(buf1), 0);
1346 if (size < 0) {
1347 err = socket_error();
1348 if (err != EWOULDBLOCK)
1349 goto eoc;
1350 } else if (size == 0) {
1351 /* end of connection */
1352 eoc:
1353 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1354 closesocket(s->fd);
1355 return;
1357 buf = buf1;
1358 while (size > 0) {
1359 /* reassemble a packet from the network */
1360 switch(s->state) {
1361 case 0:
1362 l = 4 - s->index;
1363 if (l > size)
1364 l = size;
1365 memcpy(s->buf + s->index, buf, l);
1366 buf += l;
1367 size -= l;
1368 s->index += l;
1369 if (s->index == 4) {
1370 /* got length */
1371 s->packet_len = ntohl(*(uint32_t *)s->buf);
1372 s->index = 0;
1373 s->state = 1;
1375 break;
1376 case 1:
1377 l = s->packet_len - s->index;
1378 if (l > size)
1379 l = size;
1380 if (s->index + l <= sizeof(s->buf)) {
1381 memcpy(s->buf + s->index, buf, l);
1382 } else {
1383 fprintf(stderr, "serious error: oversized packet received,"
1384 "connection terminated.\n");
1385 s->state = 0;
1386 goto eoc;
1389 s->index += l;
1390 buf += l;
1391 size -= l;
1392 if (s->index >= s->packet_len) {
1393 qemu_send_packet(s->vc, s->buf, s->packet_len);
1394 s->index = 0;
1395 s->state = 0;
1397 break;
1402 static void net_socket_send_dgram(void *opaque)
1404 NetSocketState *s = opaque;
1405 int size;
1407 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1408 if (size < 0)
1409 return;
1410 if (size == 0) {
1411 /* end of connection */
1412 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1413 return;
1415 qemu_send_packet(s->vc, s->buf, size);
1418 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1420 struct ip_mreq imr;
1421 int fd;
1422 int val, ret;
1423 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1424 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1425 inet_ntoa(mcastaddr->sin_addr),
1426 (int)ntohl(mcastaddr->sin_addr.s_addr));
1427 return -1;
1430 fd = socket(PF_INET, SOCK_DGRAM, 0);
1431 if (fd < 0) {
1432 perror("socket(PF_INET, SOCK_DGRAM)");
1433 return -1;
1436 val = 1;
1437 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1438 (const char *)&val, sizeof(val));
1439 if (ret < 0) {
1440 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1441 goto fail;
1444 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1445 if (ret < 0) {
1446 perror("bind");
1447 goto fail;
1450 /* Add host to multicast group */
1451 imr.imr_multiaddr = mcastaddr->sin_addr;
1452 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1454 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1455 (const char *)&imr, sizeof(struct ip_mreq));
1456 if (ret < 0) {
1457 perror("setsockopt(IP_ADD_MEMBERSHIP)");
1458 goto fail;
1461 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1462 val = 1;
1463 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1464 (const char *)&val, sizeof(val));
1465 if (ret < 0) {
1466 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1467 goto fail;
1470 socket_set_nonblock(fd);
1471 return fd;
1472 fail:
1473 if (fd >= 0)
1474 closesocket(fd);
1475 return -1;
1478 static void net_socket_cleanup(VLANClientState *vc)
1480 NetSocketState *s = vc->opaque;
1481 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1482 close(s->fd);
1483 qemu_free(s);
1486 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1487 const char *model,
1488 const char *name,
1489 int fd, int is_connected)
1491 struct sockaddr_in saddr;
1492 int newfd;
1493 socklen_t saddr_len;
1494 NetSocketState *s;
1496 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1497 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1498 * by ONLY ONE process: we must "clone" this dgram socket --jjo
1501 if (is_connected) {
1502 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1503 /* must be bound */
1504 if (saddr.sin_addr.s_addr==0) {
1505 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1506 fd);
1507 return NULL;
1509 /* clone dgram socket */
1510 newfd = net_socket_mcast_create(&saddr);
1511 if (newfd < 0) {
1512 /* error already reported by net_socket_mcast_create() */
1513 close(fd);
1514 return NULL;
1516 /* clone newfd to fd, close newfd */
1517 dup2(newfd, fd);
1518 close(newfd);
1520 } else {
1521 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1522 fd, strerror(errno));
1523 return NULL;
1527 s = qemu_mallocz(sizeof(NetSocketState));
1528 s->fd = fd;
1530 s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive_dgram,
1531 NULL, net_socket_cleanup, s);
1532 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1534 /* mcast: save bound address as dst */
1535 if (is_connected) s->dgram_dst=saddr;
1537 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1538 "socket: fd=%d (%s mcast=%s:%d)",
1539 fd, is_connected? "cloned" : "",
1540 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1541 return s;
1544 static void net_socket_connect(void *opaque)
1546 NetSocketState *s = opaque;
1547 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1550 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1551 const char *model,
1552 const char *name,
1553 int fd, int is_connected)
1555 NetSocketState *s;
1556 s = qemu_mallocz(sizeof(NetSocketState));
1557 s->fd = fd;
1558 s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive,
1559 NULL, net_socket_cleanup, s);
1560 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1561 "socket: fd=%d", fd);
1562 if (is_connected) {
1563 net_socket_connect(s);
1564 } else {
1565 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1567 return s;
1570 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1571 const char *model, const char *name,
1572 int fd, int is_connected)
1574 int so_type=-1, optlen=sizeof(so_type);
1576 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1577 (socklen_t *)&optlen)< 0) {
1578 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1579 return NULL;
1581 switch(so_type) {
1582 case SOCK_DGRAM:
1583 return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1584 case SOCK_STREAM:
1585 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1586 default:
1587 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1588 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1589 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1591 return NULL;
1594 static void net_socket_accept(void *opaque)
1596 NetSocketListenState *s = opaque;
1597 NetSocketState *s1;
1598 struct sockaddr_in saddr;
1599 socklen_t len;
1600 int fd;
1602 for(;;) {
1603 len = sizeof(saddr);
1604 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1605 if (fd < 0 && errno != EINTR) {
1606 return;
1607 } else if (fd >= 0) {
1608 break;
1611 s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1612 if (!s1) {
1613 closesocket(fd);
1614 } else {
1615 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1616 "socket: connection from %s:%d",
1617 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1621 static int net_socket_listen_init(VLANState *vlan,
1622 const char *model,
1623 const char *name,
1624 const char *host_str)
1626 NetSocketListenState *s;
1627 int fd, val, ret;
1628 struct sockaddr_in saddr;
1630 if (parse_host_port(&saddr, host_str) < 0)
1631 return -1;
1633 s = qemu_mallocz(sizeof(NetSocketListenState));
1635 fd = socket(PF_INET, SOCK_STREAM, 0);
1636 if (fd < 0) {
1637 perror("socket");
1638 return -1;
1640 socket_set_nonblock(fd);
1642 /* allow fast reuse */
1643 val = 1;
1644 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1646 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1647 if (ret < 0) {
1648 perror("bind");
1649 return -1;
1651 ret = listen(fd, 0);
1652 if (ret < 0) {
1653 perror("listen");
1654 return -1;
1656 s->vlan = vlan;
1657 s->model = strdup(model);
1658 s->name = strdup(name);
1659 s->fd = fd;
1660 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1661 return 0;
1664 static int net_socket_connect_init(VLANState *vlan,
1665 const char *model,
1666 const char *name,
1667 const char *host_str)
1669 NetSocketState *s;
1670 int fd, connected, ret, err;
1671 struct sockaddr_in saddr;
1673 if (parse_host_port(&saddr, host_str) < 0)
1674 return -1;
1676 fd = socket(PF_INET, SOCK_STREAM, 0);
1677 if (fd < 0) {
1678 perror("socket");
1679 return -1;
1681 socket_set_nonblock(fd);
1683 connected = 0;
1684 for(;;) {
1685 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1686 if (ret < 0) {
1687 err = socket_error();
1688 if (err == EINTR || err == EWOULDBLOCK) {
1689 } else if (err == EINPROGRESS) {
1690 break;
1691 #ifdef _WIN32
1692 } else if (err == WSAEALREADY) {
1693 break;
1694 #endif
1695 } else {
1696 perror("connect");
1697 closesocket(fd);
1698 return -1;
1700 } else {
1701 connected = 1;
1702 break;
1705 s = net_socket_fd_init(vlan, model, name, fd, connected);
1706 if (!s)
1707 return -1;
1708 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1709 "socket: connect to %s:%d",
1710 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1711 return 0;
1714 static int net_socket_mcast_init(VLANState *vlan,
1715 const char *model,
1716 const char *name,
1717 const char *host_str)
1719 NetSocketState *s;
1720 int fd;
1721 struct sockaddr_in saddr;
1723 if (parse_host_port(&saddr, host_str) < 0)
1724 return -1;
1727 fd = net_socket_mcast_create(&saddr);
1728 if (fd < 0)
1729 return -1;
1731 s = net_socket_fd_init(vlan, model, name, fd, 0);
1732 if (!s)
1733 return -1;
1735 s->dgram_dst = saddr;
1737 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1738 "socket: mcast=%s:%d",
1739 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1740 return 0;
1744 /* find or alloc a new VLAN */
1745 VLANState *qemu_find_vlan(int id)
1747 VLANState **pvlan, *vlan;
1748 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1749 if (vlan->id == id)
1750 return vlan;
1752 vlan = qemu_mallocz(sizeof(VLANState));
1753 vlan->id = id;
1754 vlan->next = NULL;
1755 pvlan = &first_vlan;
1756 while (*pvlan != NULL)
1757 pvlan = &(*pvlan)->next;
1758 *pvlan = vlan;
1759 return vlan;
1762 static int nic_get_free_idx(void)
1764 int index;
1766 for (index = 0; index < MAX_NICS; index++)
1767 if (!nd_table[index].used)
1768 return index;
1769 return -1;
1772 void qemu_check_nic_model(NICInfo *nd, const char *model)
1774 const char *models[2];
1776 models[0] = model;
1777 models[1] = NULL;
1779 qemu_check_nic_model_list(nd, models, model);
1782 void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
1783 const char *default_model)
1785 int i, exit_status = 0;
1787 if (!nd->model)
1788 nd->model = strdup(default_model);
1790 if (strcmp(nd->model, "?") != 0) {
1791 for (i = 0 ; models[i]; i++)
1792 if (strcmp(nd->model, models[i]) == 0)
1793 return;
1795 fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
1796 exit_status = 1;
1799 fprintf(stderr, "qemu: Supported NIC models: ");
1800 for (i = 0 ; models[i]; i++)
1801 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1803 exit(exit_status);
1806 int net_client_init(const char *device, const char *p)
1808 char buf[1024];
1809 int vlan_id, ret;
1810 VLANState *vlan;
1811 char *name = NULL;
1813 vlan_id = 0;
1814 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1815 vlan_id = strtol(buf, NULL, 0);
1817 vlan = qemu_find_vlan(vlan_id);
1819 if (get_param_value(buf, sizeof(buf), "name", p)) {
1820 name = strdup(buf);
1822 if (!strcmp(device, "nic")) {
1823 NICInfo *nd;
1824 uint8_t *macaddr;
1825 int idx = nic_get_free_idx();
1827 if (idx == -1 || nb_nics >= MAX_NICS) {
1828 fprintf(stderr, "Too Many NICs\n");
1829 ret = -1;
1830 goto out;
1832 nd = &nd_table[idx];
1833 macaddr = nd->macaddr;
1834 macaddr[0] = 0x52;
1835 macaddr[1] = 0x54;
1836 macaddr[2] = 0x00;
1837 macaddr[3] = 0x12;
1838 macaddr[4] = 0x34;
1839 macaddr[5] = 0x56 + idx;
1841 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1842 if (parse_macaddr(macaddr, buf) < 0) {
1843 fprintf(stderr, "invalid syntax for ethernet address\n");
1844 ret = -1;
1845 goto out;
1848 if (get_param_value(buf, sizeof(buf), "model", p)) {
1849 nd->model = strdup(buf);
1851 nd->vlan = vlan;
1852 nd->name = name;
1853 nd->used = 1;
1854 name = NULL;
1855 nb_nics++;
1856 vlan->nb_guest_devs++;
1857 ret = idx;
1858 } else
1859 if (!strcmp(device, "none")) {
1860 /* does nothing. It is needed to signal that no network cards
1861 are wanted */
1862 ret = 0;
1863 } else
1864 #ifdef CONFIG_SLIRP
1865 if (!strcmp(device, "user")) {
1866 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1867 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1869 if (get_param_value(buf, sizeof(buf), "restrict", p)) {
1870 slirp_restrict = (buf[0] == 'y') ? 1 : 0;
1872 if (get_param_value(buf, sizeof(buf), "ip", p)) {
1873 slirp_ip = strdup(buf);
1875 vlan->nb_host_devs++;
1876 ret = net_slirp_init(vlan, device, name);
1877 } else if (!strcmp(device, "channel")) {
1878 long port;
1879 char name[20], *devname;
1880 struct VMChannel *vmc;
1882 port = strtol(p, &devname, 10);
1883 devname++;
1884 if (port < 1 || port > 65535) {
1885 fprintf(stderr, "vmchannel wrong port number\n");
1886 ret = -1;
1887 goto out;
1889 vmc = malloc(sizeof(struct VMChannel));
1890 snprintf(name, 20, "vmchannel%ld", port);
1891 vmc->hd = qemu_chr_open(name, devname, NULL);
1892 if (!vmc->hd) {
1893 fprintf(stderr, "qemu: could not open vmchannel device"
1894 "'%s'\n", devname);
1895 ret = -1;
1896 goto out;
1898 vmc->port = port;
1899 slirp_add_exec(3, vmc->hd, 4, port);
1900 qemu_chr_add_handlers(vmc->hd, vmchannel_can_read, vmchannel_read,
1901 NULL, vmc);
1902 ret = 0;
1903 } else
1904 #endif
1905 #ifdef _WIN32
1906 if (!strcmp(device, "tap")) {
1907 char ifname[64];
1908 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1909 fprintf(stderr, "tap: no interface name\n");
1910 ret = -1;
1911 goto out;
1913 vlan->nb_host_devs++;
1914 ret = tap_win32_init(vlan, device, name, ifname);
1915 } else
1916 #elif defined (_AIX)
1917 #else
1918 if (!strcmp(device, "tap")) {
1919 char ifname[64];
1920 char setup_script[1024], down_script[1024];
1921 int fd;
1922 vlan->nb_host_devs++;
1923 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1924 fd = strtol(buf, NULL, 0);
1925 fcntl(fd, F_SETFL, O_NONBLOCK);
1926 ret = -1;
1927 if (net_tap_fd_init(vlan, device, name, fd,
1928 tap_probe_vnet_hdr(fd)))
1929 ret = 0;
1930 } else {
1931 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1932 ifname[0] = '\0';
1934 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1935 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1937 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1938 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1940 ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
1942 } else
1943 #endif
1944 if (!strcmp(device, "socket")) {
1945 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1946 int fd;
1947 fd = strtol(buf, NULL, 0);
1948 ret = -1;
1949 if (net_socket_fd_init(vlan, device, name, fd, 1))
1950 ret = 0;
1951 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1952 ret = net_socket_listen_init(vlan, device, name, buf);
1953 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1954 ret = net_socket_connect_init(vlan, device, name, buf);
1955 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1956 ret = net_socket_mcast_init(vlan, device, name, buf);
1957 } else {
1958 fprintf(stderr, "Unknown socket options: %s\n", p);
1959 ret = -1;
1960 goto out;
1962 vlan->nb_host_devs++;
1963 } else
1964 #ifdef CONFIG_VDE
1965 if (!strcmp(device, "vde")) {
1966 char vde_sock[1024], vde_group[512];
1967 int vde_port, vde_mode;
1968 vlan->nb_host_devs++;
1969 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1970 vde_sock[0] = '\0';
1972 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1973 vde_port = strtol(buf, NULL, 10);
1974 } else {
1975 vde_port = 0;
1977 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1978 vde_group[0] = '\0';
1980 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1981 vde_mode = strtol(buf, NULL, 8);
1982 } else {
1983 vde_mode = 0700;
1985 ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
1986 } else
1987 #endif
1989 fprintf(stderr, "Unknown network device: %s\n", device);
1990 ret = -1;
1991 goto out;
1993 if (ret < 0) {
1994 fprintf(stderr, "Could not initialize device '%s'\n", device);
1996 out:
1997 if (name)
1998 free(name);
1999 return ret;
2002 void net_client_uninit(NICInfo *nd)
2004 nd->vlan->nb_guest_devs--;
2005 nb_nics--;
2006 nd->used = 0;
2007 free((void *)nd->model);
2010 static int net_host_check_device(const char *device)
2012 int i;
2013 const char *valid_param_list[] = { "tap", "socket"
2014 #ifdef CONFIG_SLIRP
2015 ,"user"
2016 #endif
2017 #ifdef CONFIG_VDE
2018 ,"vde"
2019 #endif
2021 for (i = 0; i < sizeof(valid_param_list) / sizeof(char *); i++) {
2022 if (!strncmp(valid_param_list[i], device,
2023 strlen(valid_param_list[i])))
2024 return 1;
2027 return 0;
2030 void net_host_device_add(const char *device, const char *opts)
2032 if (!net_host_check_device(device)) {
2033 term_printf("invalid host network device %s\n", device);
2034 return;
2036 net_client_init(device, opts);
2039 void net_host_device_remove(int vlan_id, const char *device)
2041 VLANState *vlan;
2042 VLANClientState *vc;
2044 vlan = qemu_find_vlan(vlan_id);
2046 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2047 if (!strcmp(vc->name, device))
2048 break;
2050 if (!vc) {
2051 term_printf("can't find device %s\n", device);
2052 return;
2054 qemu_del_vlan_client(vc);
2057 int net_client_parse(const char *str)
2059 const char *p;
2060 char *q;
2061 char device[64];
2063 p = str;
2064 q = device;
2065 while (*p != '\0' && *p != ',') {
2066 if ((q - device) < sizeof(device) - 1)
2067 *q++ = *p;
2068 p++;
2070 *q = '\0';
2071 if (*p == ',')
2072 p++;
2074 return net_client_init(device, p);
2077 void do_info_network(void)
2079 VLANState *vlan;
2080 VLANClientState *vc;
2082 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2083 term_printf("VLAN %d devices:\n", vlan->id);
2084 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2085 term_printf(" %s: %s\n", vc->name, vc->info_str);
2089 int do_set_link(const char *name, const char *up_or_down)
2091 VLANState *vlan;
2092 VLANClientState *vc = NULL;
2094 for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
2095 for (vc = vlan->first_client; vc != NULL; vc = vc->next)
2096 if (strcmp(vc->name, name) == 0)
2097 goto done;
2098 done:
2100 if (!vc) {
2101 term_printf("could not find network device '%s'", name);
2102 return 0;
2105 if (strcmp(up_or_down, "up") == 0)
2106 vc->link_down = 0;
2107 else if (strcmp(up_or_down, "down") == 0)
2108 vc->link_down = 1;
2109 else
2110 term_printf("invalid link status '%s'; only 'up' or 'down' valid\n",
2111 up_or_down);
2113 if (vc->link_status_changed)
2114 vc->link_status_changed(vc);
2116 return 1;
2119 void net_cleanup(void)
2121 VLANState *vlan;
2123 /* close network clients */
2124 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2125 VLANClientState *vc = vlan->first_client;
2127 while (vc) {
2128 VLANClientState *next = vc->next;
2130 qemu_del_vlan_client(vc);
2132 vc = next;
2137 void net_client_check(void)
2139 VLANState *vlan;
2141 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2142 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
2143 continue;
2144 if (vlan->nb_guest_devs == 0)
2145 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
2146 if (vlan->nb_host_devs == 0)
2147 fprintf(stderr,
2148 "Warning: vlan %d is not connected to host network\n",
2149 vlan->id);