Fix ACPI GPE registers read/write handling.
[qemu-kvm/fedora.git] / net.c
blob534b8b0f983be4f80635f96f42da6cbf60c7e662
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu-common.h"
25 #include "net.h"
26 #include "console.h"
27 #include "sysemu.h"
28 #include "qemu-timer.h"
29 #include "qemu-char.h"
30 #include "audio/audio.h"
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <signal.h>
35 #include <time.h>
36 #include <errno.h>
37 #include <sys/time.h>
38 #include <zlib.h>
40 #ifndef _WIN32
41 #include <sys/times.h>
42 #include <sys/wait.h>
43 #include <termios.h>
44 #include <sys/mman.h>
45 #include <sys/ioctl.h>
46 #include <sys/resource.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #include <net/if.h>
50 #ifdef __NetBSD__
51 #include <net/if_tap.h>
52 #endif
53 #ifdef __linux__
54 #include <linux/if_tun.h>
55 #endif
56 #include <arpa/inet.h>
57 #include <dirent.h>
58 #include <netdb.h>
59 #include <sys/select.h>
60 #ifdef _BSD
61 #include <sys/stat.h>
62 #ifdef __FreeBSD__
63 #include <libutil.h>
64 #else
65 #include <util.h>
66 #endif
67 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
68 #include <freebsd/stdlib.h>
69 #else
70 #ifdef __linux__
71 #include <pty.h>
72 #include <malloc.h>
73 #include <linux/rtc.h>
75 /* For the benefit of older linux systems which don't supply it,
76 we use a local copy of hpet.h. */
77 /* #include <linux/hpet.h> */
78 #include "hpet.h"
80 #include <linux/ppdev.h>
81 #include <linux/parport.h>
82 #endif
83 #ifdef __sun__
84 #include <sys/stat.h>
85 #include <sys/ethernet.h>
86 #include <sys/sockio.h>
87 #include <netinet/arp.h>
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h> // must come after ip.h
92 #include <netinet/udp.h>
93 #include <netinet/tcp.h>
94 #include <net/if.h>
95 #include <syslog.h>
96 #include <stropts.h>
97 #endif
98 #endif
99 #endif
101 #include "qemu_socket.h"
103 #if defined(CONFIG_SLIRP)
104 #include "libslirp.h"
105 #endif
107 #if defined(__OpenBSD__)
108 #include <util.h>
109 #endif
111 #if defined(CONFIG_VDE)
112 #include <libvdeplug.h>
113 #endif
115 #ifdef _WIN32
116 #include <malloc.h>
117 #include <sys/timeb.h>
118 #include <mmsystem.h>
119 #define getopt_long_only getopt_long
120 #define memalign(align, size) malloc(size)
121 #endif
123 // FIXME: #include "qemu-kvm.h"
125 static VLANState *first_vlan;
127 /***********************************************************/
128 /* network device redirectors */
130 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
131 static void hex_dump(FILE *f, const uint8_t *buf, int size)
133 int len, i, j, c;
135 for(i=0;i<size;i+=16) {
136 len = size - i;
137 if (len > 16)
138 len = 16;
139 fprintf(f, "%08x ", i);
140 for(j=0;j<16;j++) {
141 if (j < len)
142 fprintf(f, " %02x", buf[i+j]);
143 else
144 fprintf(f, " ");
146 fprintf(f, " ");
147 for(j=0;j<len;j++) {
148 c = buf[i+j];
149 if (c < ' ' || c > '~')
150 c = '.';
151 fprintf(f, "%c", c);
153 fprintf(f, "\n");
156 #endif
158 static int parse_macaddr(uint8_t *macaddr, const char *p)
160 int i;
161 char *last_char;
162 long int offset;
164 errno = 0;
165 offset = strtol(p, &last_char, 0);
166 if (0 == errno && '\0' == *last_char &&
167 offset >= 0 && offset <= 0xFFFFFF) {
168 macaddr[3] = (offset & 0xFF0000) >> 16;
169 macaddr[4] = (offset & 0xFF00) >> 8;
170 macaddr[5] = offset & 0xFF;
171 return 0;
172 } else {
173 for(i = 0; i < 6; i++) {
174 macaddr[i] = strtol(p, (char **)&p, 16);
175 if (i == 5) {
176 if (*p != '\0')
177 return -1;
178 } else {
179 if (*p != ':' && *p != '-')
180 return -1;
181 p++;
184 return 0;
187 return -1;
190 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
192 const char *p, *p1;
193 int len;
194 p = *pp;
195 p1 = strchr(p, sep);
196 if (!p1)
197 return -1;
198 len = p1 - p;
199 p1++;
200 if (buf_size > 0) {
201 if (len > buf_size - 1)
202 len = buf_size - 1;
203 memcpy(buf, p, len);
204 buf[len] = '\0';
206 *pp = p1;
207 return 0;
210 int parse_host_src_port(struct sockaddr_in *haddr,
211 struct sockaddr_in *saddr,
212 const char *input_str)
214 char *str = strdup(input_str);
215 char *host_str = str;
216 char *src_str;
217 const char *src_str2;
218 char *ptr;
221 * Chop off any extra arguments at the end of the string which
222 * would start with a comma, then fill in the src port information
223 * if it was provided else use the "any address" and "any port".
225 if ((ptr = strchr(str,',')))
226 *ptr = '\0';
228 if ((src_str = strchr(input_str,'@'))) {
229 *src_str = '\0';
230 src_str++;
233 if (parse_host_port(haddr, host_str) < 0)
234 goto fail;
236 src_str2 = src_str;
237 if (!src_str || *src_str == '\0')
238 src_str2 = ":0";
240 if (parse_host_port(saddr, src_str2) < 0)
241 goto fail;
243 free(str);
244 return(0);
246 fail:
247 free(str);
248 return -1;
251 int parse_host_port(struct sockaddr_in *saddr, const char *str)
253 char buf[512];
254 struct hostent *he;
255 const char *p, *r;
256 int port;
258 p = str;
259 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
260 return -1;
261 saddr->sin_family = AF_INET;
262 if (buf[0] == '\0') {
263 saddr->sin_addr.s_addr = 0;
264 } else {
265 if (qemu_isdigit(buf[0])) {
266 if (!inet_aton(buf, &saddr->sin_addr))
267 return -1;
268 } else {
269 if ((he = gethostbyname(buf)) == NULL)
270 return - 1;
271 saddr->sin_addr = *(struct in_addr *)he->h_addr;
274 port = strtol(p, (char **)&r, 0);
275 if (r == p)
276 return -1;
277 saddr->sin_port = htons(port);
278 return 0;
281 #if !defined(_WIN32) && 0
282 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
284 const char *p;
285 int len;
287 len = MIN(108, strlen(str));
288 p = strchr(str, ',');
289 if (p)
290 len = MIN(len, p - str);
292 memset(uaddr, 0, sizeof(*uaddr));
294 uaddr->sun_family = AF_UNIX;
295 memcpy(uaddr->sun_path, str, len);
297 return 0;
299 #endif
301 void qemu_format_nic_info_str(VLANClientState *vc, uint8_t macaddr[6])
303 snprintf(vc->info_str, sizeof(vc->info_str),
304 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
305 vc->model,
306 macaddr[0], macaddr[1], macaddr[2],
307 macaddr[3], macaddr[4], macaddr[5]);
310 static char *assign_name(VLANClientState *vc1, const char *model)
312 VLANState *vlan;
313 char buf[256];
314 int id = 0;
316 for (vlan = first_vlan; vlan; vlan = vlan->next) {
317 VLANClientState *vc;
319 for (vc = vlan->first_client; vc; vc = vc->next)
320 if (vc != vc1 && strcmp(vc->model, model) == 0)
321 id++;
324 snprintf(buf, sizeof(buf), "%s.%d", model, id);
326 return strdup(buf);
329 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
330 const char *model,
331 const char *name,
332 IOReadHandler *fd_read,
333 IOCanRWHandler *fd_can_read,
334 void *opaque)
336 VLANClientState *vc, **pvc;
337 vc = qemu_mallocz(sizeof(VLANClientState));
338 vc->model = strdup(model);
339 if (name)
340 vc->name = strdup(name);
341 else
342 vc->name = assign_name(vc, model);
343 vc->fd_read = fd_read;
344 vc->fd_can_read = fd_can_read;
345 vc->opaque = opaque;
346 vc->vlan = vlan;
348 vc->next = NULL;
349 pvc = &vlan->first_client;
350 while (*pvc != NULL)
351 pvc = &(*pvc)->next;
352 *pvc = vc;
353 return vc;
356 void qemu_del_vlan_client(VLANClientState *vc)
358 VLANClientState **pvc = &vc->vlan->first_client;
360 while (*pvc != NULL)
361 if (*pvc == vc) {
362 *pvc = vc->next;
363 free(vc->name);
364 free(vc->model);
365 free(vc);
366 break;
367 } else
368 pvc = &(*pvc)->next;
371 int qemu_can_send_packet(VLANClientState *vc1)
373 VLANState *vlan = vc1->vlan;
374 VLANClientState *vc;
376 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
377 if (vc != vc1) {
378 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
379 return 1;
382 return 0;
385 int qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
387 VLANState *vlan = vc1->vlan;
388 VLANClientState *vc;
389 int ret = -EAGAIN;
391 if (vc1->link_down)
392 return 0;
394 #ifdef DEBUG_NET
395 printf("vlan %d send:\n", vlan->id);
396 hex_dump(stdout, buf, size);
397 #endif
398 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
399 if (vc != vc1 && !vc->link_down) {
400 if (!vc->fd_can_read || vc->fd_can_read(vc->opaque)) {
401 vc->fd_read(vc->opaque, buf, size);
402 ret = 0;
406 return ret;
409 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
410 int iovcnt)
412 uint8_t buffer[4096];
413 size_t offset = 0;
414 int i;
416 for (i = 0; i < iovcnt; i++) {
417 size_t len;
419 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
420 memcpy(buffer + offset, iov[i].iov_base, len);
421 offset += len;
424 vc->fd_read(vc->opaque, buffer, offset);
426 return offset;
429 static ssize_t calc_iov_length(const struct iovec *iov, int iovcnt)
431 size_t offset = 0;
432 int i;
434 for (i = 0; i < iovcnt; i++)
435 offset += iov[i].iov_len;
436 return offset;
439 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
440 int iovcnt)
442 VLANState *vlan = vc1->vlan;
443 VLANClientState *vc;
444 ssize_t max_len = 0;
446 if (vc1->link_down)
447 return calc_iov_length(iov, iovcnt);
449 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
450 ssize_t len = 0;
452 if (vc == vc1)
453 continue;
455 if (vc->link_down)
456 len = calc_iov_length(iov, iovcnt);
457 if (vc->fd_readv)
458 len = vc->fd_readv(vc->opaque, iov, iovcnt);
459 else if (vc->fd_read)
460 len = vc_sendv_compat(vc, iov, iovcnt);
462 max_len = MAX(max_len, len);
465 return max_len;
468 #if defined(CONFIG_SLIRP)
470 /* slirp network adapter */
472 static int slirp_inited;
473 static int slirp_restrict;
474 static char *slirp_ip;
475 static VLANClientState *slirp_vc;
477 int slirp_can_output(void)
479 return !slirp_vc || qemu_can_send_packet(slirp_vc);
482 void slirp_output(const uint8_t *pkt, int pkt_len)
484 #ifdef DEBUG_SLIRP
485 printf("slirp output:\n");
486 hex_dump(stdout, pkt, pkt_len);
487 #endif
488 if (!slirp_vc)
489 return;
490 qemu_send_packet(slirp_vc, pkt, pkt_len);
493 int slirp_is_inited(void)
495 return slirp_inited;
498 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
500 #ifdef DEBUG_SLIRP
501 printf("slirp input:\n");
502 hex_dump(stdout, buf, size);
503 #endif
504 slirp_input(buf, size);
507 static int net_slirp_init(VLANState *vlan, const char *model, const char *name)
509 if (!slirp_inited) {
510 slirp_inited = 1;
511 slirp_init(slirp_restrict, slirp_ip);
513 slirp_vc = qemu_new_vlan_client(vlan, model, name,
514 slirp_receive, NULL, NULL);
515 slirp_vc->info_str[0] = '\0';
516 return 0;
519 void net_slirp_redir(const char *redir_str)
521 int is_udp;
522 char buf[256], *r;
523 const char *p;
524 struct in_addr guest_addr;
525 int host_port, guest_port;
527 if (!slirp_inited) {
528 slirp_inited = 1;
529 slirp_init(slirp_restrict, slirp_ip);
532 p = redir_str;
533 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
534 goto fail;
535 if (!strcmp(buf, "tcp")) {
536 is_udp = 0;
537 } else if (!strcmp(buf, "udp")) {
538 is_udp = 1;
539 } else {
540 goto fail;
543 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
544 goto fail;
545 host_port = strtol(buf, &r, 0);
546 if (r == buf)
547 goto fail;
549 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
550 goto fail;
551 if (buf[0] == '\0') {
552 pstrcpy(buf, sizeof(buf), "10.0.2.15");
554 if (!inet_aton(buf, &guest_addr))
555 goto fail;
557 guest_port = strtol(p, &r, 0);
558 if (r == p)
559 goto fail;
561 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
562 fprintf(stderr, "qemu: could not set up redirection\n");
563 exit(1);
565 return;
566 fail:
567 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
568 exit(1);
571 #ifndef _WIN32
573 static char smb_dir[1024];
575 static void erase_dir(char *dir_name)
577 DIR *d;
578 struct dirent *de;
579 char filename[1024];
581 /* erase all the files in the directory */
582 if ((d = opendir(dir_name)) != 0) {
583 for(;;) {
584 de = readdir(d);
585 if (!de)
586 break;
587 if (strcmp(de->d_name, ".") != 0 &&
588 strcmp(de->d_name, "..") != 0) {
589 snprintf(filename, sizeof(filename), "%s/%s",
590 smb_dir, de->d_name);
591 if (unlink(filename) != 0) /* is it a directory? */
592 erase_dir(filename);
595 closedir(d);
596 rmdir(dir_name);
600 /* automatic user mode samba server configuration */
601 static void smb_exit(void)
603 erase_dir(smb_dir);
606 /* automatic user mode samba server configuration */
607 void net_slirp_smb(const char *exported_dir)
609 char smb_conf[1024];
610 char smb_cmdline[1024];
611 FILE *f;
613 if (!slirp_inited) {
614 slirp_inited = 1;
615 slirp_init(slirp_restrict, slirp_ip);
618 /* XXX: better tmp dir construction */
619 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
620 if (mkdir(smb_dir, 0700) < 0) {
621 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
622 exit(1);
624 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
626 f = fopen(smb_conf, "w");
627 if (!f) {
628 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
629 exit(1);
631 fprintf(f,
632 "[global]\n"
633 "private dir=%s\n"
634 "smb ports=0\n"
635 "socket address=127.0.0.1\n"
636 "pid directory=%s\n"
637 "lock directory=%s\n"
638 "log file=%s/log.smbd\n"
639 "smb passwd file=%s/smbpasswd\n"
640 "security = share\n"
641 "[qemu]\n"
642 "path=%s\n"
643 "read only=no\n"
644 "guest ok=yes\n",
645 smb_dir,
646 smb_dir,
647 smb_dir,
648 smb_dir,
649 smb_dir,
650 exported_dir
652 fclose(f);
653 atexit(smb_exit);
655 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
656 SMBD_COMMAND, smb_conf);
658 slirp_add_exec(0, smb_cmdline, 4, 139);
661 #endif /* !defined(_WIN32) */
662 void do_info_slirp(void)
664 slirp_stats();
667 #endif /* CONFIG_SLIRP */
669 #ifdef _WIN32
671 int tap_has_vnet_hdr(void *opaque)
673 return 0;
676 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
680 #else /* !defined(_WIN32) */
682 /* Maximum GSO packet size (64k) plus plenty of room for
683 * the ethernet and virtio_net headers
685 #define TAP_BUFSIZE (4096 + 65536)
687 #ifdef IFF_VNET_HDR
688 #include <linux/virtio_net.h>
689 #endif
691 typedef struct TAPState {
692 VLANClientState *vc;
693 int fd;
694 char down_script[1024];
695 char down_script_arg[128];
696 char buf[TAP_BUFSIZE];
697 int size;
698 unsigned int has_vnet_hdr : 1;
699 unsigned int using_vnet_hdr : 1;
700 } TAPState;
702 #ifdef HAVE_IOVEC
703 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
704 int iovcnt)
706 TAPState *s = opaque;
707 ssize_t len;
709 do {
710 len = writev(s->fd, iov, iovcnt);
711 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
713 return len;
715 #endif
717 static void tap_receive(void *opaque, const uint8_t *buf, int size)
719 struct iovec iov[2];
720 int i = 0;
722 #ifdef IFF_VNET_HDR
723 TAPState *s = opaque;
724 struct virtio_net_hdr hdr = { 0, };
726 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
727 iov[i].iov_base = &hdr;
728 iov[i].iov_len = sizeof(hdr);
729 i++;
731 #endif
733 iov[i].iov_base = (char *) buf;
734 iov[i].iov_len = size;
735 i++;
737 tap_receive_iov(opaque, iov, i);
740 static int tap_can_send(void *opaque)
742 TAPState *s = opaque;
743 VLANClientState *vc;
744 int can_receive = 0;
746 /* Check to see if any of our clients can receive a packet */
747 for (vc = s->vc->vlan->first_client; vc; vc = vc->next) {
748 /* Skip ourselves */
749 if (vc == s->vc)
750 continue;
752 if (!vc->fd_can_read) {
753 /* no fd_can_read handler, they always can receive */
754 can_receive = 1;
755 } else
756 can_receive = vc->fd_can_read(vc->opaque);
758 /* Once someone can receive, we try to send a packet */
759 if (can_receive)
760 break;
763 return can_receive;
766 static int tap_send_packet(TAPState *s)
768 uint8_t *buf = (uint8_t *)s->buf;
769 int size = s->size;
771 #ifdef IFF_VNET_HDR
772 if (s->has_vnet_hdr && !s->using_vnet_hdr) {
773 buf += sizeof(struct virtio_net_hdr);
774 size -= sizeof(struct virtio_net_hdr);
776 #endif
778 return qemu_send_packet(s->vc, buf, size);
781 static void tap_send(void *opaque)
783 TAPState *s = opaque;
785 /* First try to send any buffered packet */
786 if (s->size > 0) {
787 int err;
789 /* If noone can receive the packet, buffer it */
790 err = tap_send_packet(s);
791 if (err == -EAGAIN)
792 return;
795 /* Read packets until we hit EAGAIN */
796 do {
797 #ifdef __sun__
798 struct strbuf sbuf;
799 int f = 0;
800 sbuf.maxlen = sizeof(s->buf);
801 sbuf.buf = s->buf;
802 s->size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
803 #else
804 // FIXME: kvm_sleep_begin();
805 s->size = read(s->fd, s->buf, sizeof(s->buf));
806 // FIXME: kvm_sleep_end();
807 #endif
809 if (s->size == -1 && errno == EINTR)
810 continue;
812 if (s->size > 0) {
813 int err;
815 /* If noone can receive the packet, buffer it */
816 err = tap_send_packet(s);
817 if (err == -EAGAIN)
818 break;
820 } while (s->size > 0);
823 int tap_has_vnet_hdr(void *opaque)
825 VLANClientState *vc = opaque;
826 TAPState *s = vc->opaque;
828 return s ? s->has_vnet_hdr : 0;
831 void tap_using_vnet_hdr(void *opaque, int using_vnet_hdr)
833 VLANClientState *vc = opaque;
834 TAPState *s = vc->opaque;
836 if (!s || !s->has_vnet_hdr)
837 return;
839 s->using_vnet_hdr = using_vnet_hdr != 0;
842 static int tap_probe_vnet_hdr(int fd)
844 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
845 struct ifreq ifr;
847 if (ioctl(fd, TUNGETIFF, &ifr) != 0) {
848 fprintf(stderr, "TUNGETIFF ioctl() failed: %s\n", strerror(errno));
849 return 0;
852 return ifr.ifr_flags & IFF_VNET_HDR;
853 #else
854 return 0;
855 #endif
858 #ifdef TUNSETOFFLOAD
859 static void tap_set_offload(VLANClientState *vc, int csum, int tso4, int tso6,
860 int ecn)
862 TAPState *s = vc->opaque;
863 unsigned int offload = 0;
865 if (csum) {
866 offload |= TUN_F_CSUM;
867 if (tso4)
868 offload |= TUN_F_TSO4;
869 if (tso6)
870 offload |= TUN_F_TSO6;
871 if ((tso4 || tso6) && ecn)
872 offload |= TUN_F_TSO_ECN;
875 if (ioctl(s->fd, TUNSETOFFLOAD, offload) != 0)
876 fprintf(stderr, "TUNSETOFFLOAD ioctl() failed: %s\n",
877 strerror(errno));
879 #endif /* TUNSETOFFLOAD */
881 /* fd support */
883 static TAPState *net_tap_fd_init(VLANState *vlan,
884 const char *model,
885 const char *name,
886 int fd,
887 int vnet_hdr)
889 TAPState *s;
891 s = qemu_mallocz(sizeof(TAPState));
892 s->fd = fd;
893 s->has_vnet_hdr = vnet_hdr != 0;
894 s->vc = qemu_new_vlan_client(vlan, model, name, tap_receive, NULL, s);
895 #ifdef HAVE_IOVEC
896 s->vc->fd_readv = tap_receive_iov;
897 #endif
898 #ifdef TUNSETOFFLOAD
899 s->vc->set_offload = tap_set_offload;
900 #endif
901 qemu_set_fd_handler2(s->fd, tap_can_send, tap_send, NULL, s);
902 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "fd=%d", fd);
903 return s;
906 #if defined (_BSD) || defined (__FreeBSD_kernel__)
907 static int tap_open(char *ifname, int ifname_size)
909 int fd;
910 char *dev;
911 struct stat s;
913 TFR(fd = open("/dev/tap", O_RDWR));
914 if (fd < 0) {
915 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
916 return -1;
919 fstat(fd, &s);
920 dev = devname(s.st_rdev, S_IFCHR);
921 pstrcpy(ifname, ifname_size, dev);
923 fcntl(fd, F_SETFL, O_NONBLOCK);
924 return fd;
926 #elif defined(__sun__)
927 #define TUNNEWPPA (('T'<<16) | 0x0001)
929 * Allocate TAP device, returns opened fd.
930 * Stores dev name in the first arg(must be large enough).
932 int tap_alloc(char *dev, size_t dev_size)
934 int tap_fd, if_fd, ppa = -1;
935 static int ip_fd = 0;
936 char *ptr;
938 static int arp_fd = 0;
939 int ip_muxid, arp_muxid;
940 struct strioctl strioc_if, strioc_ppa;
941 int link_type = I_PLINK;;
942 struct lifreq ifr;
943 char actual_name[32] = "";
945 memset(&ifr, 0x0, sizeof(ifr));
947 if( *dev ){
948 ptr = dev;
949 while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
950 ppa = atoi(ptr);
953 /* Check if IP device was opened */
954 if( ip_fd )
955 close(ip_fd);
957 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
958 if (ip_fd < 0) {
959 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
960 return -1;
963 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
964 if (tap_fd < 0) {
965 syslog(LOG_ERR, "Can't open /dev/tap");
966 return -1;
969 /* Assign a new PPA and get its unit number. */
970 strioc_ppa.ic_cmd = TUNNEWPPA;
971 strioc_ppa.ic_timout = 0;
972 strioc_ppa.ic_len = sizeof(ppa);
973 strioc_ppa.ic_dp = (char *)&ppa;
974 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
975 syslog (LOG_ERR, "Can't assign new interface");
977 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
978 if (if_fd < 0) {
979 syslog(LOG_ERR, "Can't open /dev/tap (2)");
980 return -1;
982 if(ioctl(if_fd, I_PUSH, "ip") < 0){
983 syslog(LOG_ERR, "Can't push IP module");
984 return -1;
987 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
988 syslog(LOG_ERR, "Can't get flags\n");
990 snprintf (actual_name, 32, "tap%d", ppa);
991 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
993 ifr.lifr_ppa = ppa;
994 /* Assign ppa according to the unit number returned by tun device */
996 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
997 syslog (LOG_ERR, "Can't set PPA %d", ppa);
998 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
999 syslog (LOG_ERR, "Can't get flags\n");
1000 /* Push arp module to if_fd */
1001 if (ioctl (if_fd, I_PUSH, "arp") < 0)
1002 syslog (LOG_ERR, "Can't push ARP module (2)");
1004 /* Push arp module to ip_fd */
1005 if (ioctl (ip_fd, I_POP, NULL) < 0)
1006 syslog (LOG_ERR, "I_POP failed\n");
1007 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
1008 syslog (LOG_ERR, "Can't push ARP module (3)\n");
1009 /* Open arp_fd */
1010 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
1011 if (arp_fd < 0)
1012 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
1014 /* Set ifname to arp */
1015 strioc_if.ic_cmd = SIOCSLIFNAME;
1016 strioc_if.ic_timout = 0;
1017 strioc_if.ic_len = sizeof(ifr);
1018 strioc_if.ic_dp = (char *)&ifr;
1019 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
1020 syslog (LOG_ERR, "Can't set ifname to arp\n");
1023 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
1024 syslog(LOG_ERR, "Can't link TAP device to IP");
1025 return -1;
1028 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
1029 syslog (LOG_ERR, "Can't link TAP device to ARP");
1031 close (if_fd);
1033 memset(&ifr, 0x0, sizeof(ifr));
1034 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
1035 ifr.lifr_ip_muxid = ip_muxid;
1036 ifr.lifr_arp_muxid = arp_muxid;
1038 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
1040 ioctl (ip_fd, I_PUNLINK , arp_muxid);
1041 ioctl (ip_fd, I_PUNLINK, ip_muxid);
1042 syslog (LOG_ERR, "Can't set multiplexor id");
1045 snprintf(dev, dev_size, "tap%d", ppa);
1046 return tap_fd;
1049 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1051 char dev[10]="";
1052 int fd;
1053 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
1054 fprintf(stderr, "Cannot allocate TAP device\n");
1055 return -1;
1057 pstrcpy(ifname, ifname_size, dev);
1058 fcntl(fd, F_SETFL, O_NONBLOCK);
1059 return fd;
1061 #elif defined (_AIX)
1062 static int tap_open(char *ifname, int ifname_size)
1064 fprintf (stderr, "no tap on AIX\n");
1065 return -1;
1067 #else
1068 static int tap_open(char *ifname, int ifname_size, int *vnet_hdr)
1070 struct ifreq ifr;
1071 int fd, ret;
1073 TFR(fd = open("/dev/net/tun", O_RDWR));
1074 if (fd < 0) {
1075 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1076 return -1;
1078 memset(&ifr, 0, sizeof(ifr));
1079 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1081 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
1083 unsigned int features;
1085 if (ioctl(fd, TUNGETFEATURES, &features) == 0 &&
1086 features & IFF_VNET_HDR) {
1087 *vnet_hdr = 1;
1088 ifr.ifr_flags |= IFF_VNET_HDR;
1091 #endif
1093 if (ifname[0] != '\0')
1094 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
1095 else
1096 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
1097 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1098 if (ret != 0) {
1099 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1100 close(fd);
1101 return -1;
1103 pstrcpy(ifname, ifname_size, ifr.ifr_name);
1104 fcntl(fd, F_SETFL, O_NONBLOCK);
1105 return fd;
1107 #endif
1109 static int launch_script(const char *setup_script, const char *ifname, int fd)
1111 int pid, status;
1112 char *args[3];
1113 char **parg;
1115 /* try to launch network script */
1116 pid = fork();
1117 if (pid >= 0) {
1118 if (pid == 0) {
1119 int open_max = sysconf (_SC_OPEN_MAX), i;
1120 for (i = 0; i < open_max; i++)
1121 if (i != STDIN_FILENO &&
1122 i != STDOUT_FILENO &&
1123 i != STDERR_FILENO &&
1124 i != fd)
1125 close(i);
1127 parg = args;
1128 *parg++ = (char *)setup_script;
1129 *parg++ = (char *)ifname;
1130 *parg++ = NULL;
1131 execv(setup_script, args);
1132 _exit(1);
1134 while (waitpid(pid, &status, 0) != pid);
1135 if (!WIFEXITED(status) ||
1136 WEXITSTATUS(status) != 0) {
1137 fprintf(stderr, "%s: could not launch network script\n",
1138 setup_script);
1139 return -1;
1142 return 0;
1145 static int net_tap_init(VLANState *vlan, const char *model,
1146 const char *name, const char *ifname1,
1147 const char *setup_script, const char *down_script)
1149 TAPState *s;
1150 int fd;
1151 int vnet_hdr;
1152 char ifname[128];
1154 if (ifname1 != NULL)
1155 pstrcpy(ifname, sizeof(ifname), ifname1);
1156 else
1157 ifname[0] = '\0';
1158 vnet_hdr = 0;
1159 TFR(fd = tap_open(ifname, sizeof(ifname), &vnet_hdr));
1160 if (fd < 0)
1161 return -1;
1163 if (!setup_script || !strcmp(setup_script, "no"))
1164 setup_script = "";
1165 if (setup_script[0] != '\0') {
1166 if (launch_script(setup_script, ifname, fd))
1167 return -1;
1169 s = net_tap_fd_init(vlan, model, name, fd, vnet_hdr);
1170 if (!s)
1171 return -1;
1173 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1174 "ifname=%s,script=%s,downscript=%s",
1175 ifname, setup_script, down_script);
1176 if (down_script && strcmp(down_script, "no")) {
1177 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
1178 snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);
1180 return 0;
1183 #endif /* !_WIN32 */
1185 #if defined(CONFIG_VDE)
1186 typedef struct VDEState {
1187 VLANClientState *vc;
1188 VDECONN *vde;
1189 } VDEState;
1191 static void vde_to_qemu(void *opaque)
1193 VDEState *s = opaque;
1194 uint8_t buf[4096];
1195 int size;
1197 size = vde_recv(s->vde, buf, sizeof(buf), 0);
1198 if (size > 0) {
1199 qemu_send_packet(s->vc, buf, size);
1203 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
1205 VDEState *s = opaque;
1206 int ret;
1207 for(;;) {
1208 ret = vde_send(s->vde, buf, size, 0);
1209 if (ret < 0 && errno == EINTR) {
1210 } else {
1211 break;
1216 static int net_vde_init(VLANState *vlan, const char *model,
1217 const char *name, const char *sock,
1218 int port, const char *group, int mode)
1220 VDEState *s;
1221 char *init_group = strlen(group) ? (char *)group : NULL;
1222 char *init_sock = strlen(sock) ? (char *)sock : NULL;
1224 struct vde_open_args args = {
1225 .port = port,
1226 .group = init_group,
1227 .mode = mode,
1230 s = qemu_mallocz(sizeof(VDEState));
1231 s->vde = vde_open(init_sock, "QEMU", &args);
1232 if (!s->vde){
1233 free(s);
1234 return -1;
1236 s->vc = qemu_new_vlan_client(vlan, model, name, vde_from_qemu, NULL, s);
1237 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1238 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "sock=%s,fd=%d",
1239 sock, vde_datafd(s->vde));
1240 return 0;
1242 #endif
1244 /* network connection */
1245 typedef struct NetSocketState {
1246 VLANClientState *vc;
1247 int fd;
1248 int state; /* 0 = getting length, 1 = getting data */
1249 int index;
1250 int packet_len;
1251 uint8_t buf[4096];
1252 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1253 } NetSocketState;
1255 typedef struct NetSocketListenState {
1256 VLANState *vlan;
1257 char *model;
1258 char *name;
1259 int fd;
1260 } NetSocketListenState;
1262 /* XXX: we consider we can send the whole packet without blocking */
1263 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1265 NetSocketState *s = opaque;
1266 uint32_t len;
1267 len = htonl(size);
1269 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1270 send_all(s->fd, buf, size);
1273 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1275 NetSocketState *s = opaque;
1276 sendto(s->fd, buf, size, 0,
1277 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1280 static void net_socket_send(void *opaque)
1282 NetSocketState *s = opaque;
1283 int l, size, err;
1284 uint8_t buf1[4096];
1285 const uint8_t *buf;
1287 size = recv(s->fd, buf1, sizeof(buf1), 0);
1288 if (size < 0) {
1289 err = socket_error();
1290 if (err != EWOULDBLOCK)
1291 goto eoc;
1292 } else if (size == 0) {
1293 /* end of connection */
1294 eoc:
1295 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1296 closesocket(s->fd);
1297 return;
1299 buf = buf1;
1300 while (size > 0) {
1301 /* reassemble a packet from the network */
1302 switch(s->state) {
1303 case 0:
1304 l = 4 - s->index;
1305 if (l > size)
1306 l = size;
1307 memcpy(s->buf + s->index, buf, l);
1308 buf += l;
1309 size -= l;
1310 s->index += l;
1311 if (s->index == 4) {
1312 /* got length */
1313 s->packet_len = ntohl(*(uint32_t *)s->buf);
1314 s->index = 0;
1315 s->state = 1;
1317 break;
1318 case 1:
1319 l = s->packet_len - s->index;
1320 if (l > size)
1321 l = size;
1322 memcpy(s->buf + s->index, buf, l);
1323 s->index += l;
1324 buf += l;
1325 size -= l;
1326 if (s->index >= s->packet_len) {
1327 qemu_send_packet(s->vc, s->buf, s->packet_len);
1328 s->index = 0;
1329 s->state = 0;
1331 break;
1336 static void net_socket_send_dgram(void *opaque)
1338 NetSocketState *s = opaque;
1339 int size;
1341 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1342 if (size < 0)
1343 return;
1344 if (size == 0) {
1345 /* end of connection */
1346 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1347 return;
1349 qemu_send_packet(s->vc, s->buf, size);
1352 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1354 struct ip_mreq imr;
1355 int fd;
1356 int val, ret;
1357 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1358 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1359 inet_ntoa(mcastaddr->sin_addr),
1360 (int)ntohl(mcastaddr->sin_addr.s_addr));
1361 return -1;
1364 fd = socket(PF_INET, SOCK_DGRAM, 0);
1365 if (fd < 0) {
1366 perror("socket(PF_INET, SOCK_DGRAM)");
1367 return -1;
1370 val = 1;
1371 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1372 (const char *)&val, sizeof(val));
1373 if (ret < 0) {
1374 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1375 goto fail;
1378 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1379 if (ret < 0) {
1380 perror("bind");
1381 goto fail;
1384 /* Add host to multicast group */
1385 imr.imr_multiaddr = mcastaddr->sin_addr;
1386 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1388 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1389 (const char *)&imr, sizeof(struct ip_mreq));
1390 if (ret < 0) {
1391 perror("setsockopt(IP_ADD_MEMBERSHIP)");
1392 goto fail;
1395 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1396 val = 1;
1397 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1398 (const char *)&val, sizeof(val));
1399 if (ret < 0) {
1400 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1401 goto fail;
1404 socket_set_nonblock(fd);
1405 return fd;
1406 fail:
1407 if (fd >= 0)
1408 closesocket(fd);
1409 return -1;
1412 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan,
1413 const char *model,
1414 const char *name,
1415 int fd, int is_connected)
1417 struct sockaddr_in saddr;
1418 int newfd;
1419 socklen_t saddr_len;
1420 NetSocketState *s;
1422 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1423 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1424 * by ONLY ONE process: we must "clone" this dgram socket --jjo
1427 if (is_connected) {
1428 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1429 /* must be bound */
1430 if (saddr.sin_addr.s_addr==0) {
1431 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1432 fd);
1433 return NULL;
1435 /* clone dgram socket */
1436 newfd = net_socket_mcast_create(&saddr);
1437 if (newfd < 0) {
1438 /* error already reported by net_socket_mcast_create() */
1439 close(fd);
1440 return NULL;
1442 /* clone newfd to fd, close newfd */
1443 dup2(newfd, fd);
1444 close(newfd);
1446 } else {
1447 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1448 fd, strerror(errno));
1449 return NULL;
1453 s = qemu_mallocz(sizeof(NetSocketState));
1454 s->fd = fd;
1456 s->vc = qemu_new_vlan_client(vlan, model, name, net_socket_receive_dgram, NULL, s);
1457 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1459 /* mcast: save bound address as dst */
1460 if (is_connected) s->dgram_dst=saddr;
1462 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1463 "socket: fd=%d (%s mcast=%s:%d)",
1464 fd, is_connected? "cloned" : "",
1465 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1466 return s;
1469 static void net_socket_connect(void *opaque)
1471 NetSocketState *s = opaque;
1472 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1475 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,
1476 const char *model,
1477 const char *name,
1478 int fd, int is_connected)
1480 NetSocketState *s;
1481 s = qemu_mallocz(sizeof(NetSocketState));
1482 s->fd = fd;
1483 s->vc = qemu_new_vlan_client(vlan, model, name,
1484 net_socket_receive, NULL, s);
1485 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1486 "socket: fd=%d", fd);
1487 if (is_connected) {
1488 net_socket_connect(s);
1489 } else {
1490 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1492 return s;
1495 static NetSocketState *net_socket_fd_init(VLANState *vlan,
1496 const char *model, const char *name,
1497 int fd, int is_connected)
1499 int so_type=-1, optlen=sizeof(so_type);
1501 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1502 (socklen_t *)&optlen)< 0) {
1503 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1504 return NULL;
1506 switch(so_type) {
1507 case SOCK_DGRAM:
1508 return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);
1509 case SOCK_STREAM:
1510 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1511 default:
1512 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1513 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1514 return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);
1516 return NULL;
1519 static void net_socket_accept(void *opaque)
1521 NetSocketListenState *s = opaque;
1522 NetSocketState *s1;
1523 struct sockaddr_in saddr;
1524 socklen_t len;
1525 int fd;
1527 for(;;) {
1528 len = sizeof(saddr);
1529 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1530 if (fd < 0 && errno != EINTR) {
1531 return;
1532 } else if (fd >= 0) {
1533 break;
1536 s1 = net_socket_fd_init(s->vlan, s->model, s->name, fd, 1);
1537 if (!s1) {
1538 closesocket(fd);
1539 } else {
1540 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1541 "socket: connection from %s:%d",
1542 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1546 static int net_socket_listen_init(VLANState *vlan,
1547 const char *model,
1548 const char *name,
1549 const char *host_str)
1551 NetSocketListenState *s;
1552 int fd, val, ret;
1553 struct sockaddr_in saddr;
1555 if (parse_host_port(&saddr, host_str) < 0)
1556 return -1;
1558 s = qemu_mallocz(sizeof(NetSocketListenState));
1560 fd = socket(PF_INET, SOCK_STREAM, 0);
1561 if (fd < 0) {
1562 perror("socket");
1563 return -1;
1565 socket_set_nonblock(fd);
1567 /* allow fast reuse */
1568 val = 1;
1569 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1571 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1572 if (ret < 0) {
1573 perror("bind");
1574 return -1;
1576 ret = listen(fd, 0);
1577 if (ret < 0) {
1578 perror("listen");
1579 return -1;
1581 s->vlan = vlan;
1582 s->model = strdup(model);
1583 s->name = strdup(name);
1584 s->fd = fd;
1585 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1586 return 0;
1589 static int net_socket_connect_init(VLANState *vlan,
1590 const char *model,
1591 const char *name,
1592 const char *host_str)
1594 NetSocketState *s;
1595 int fd, connected, ret, err;
1596 struct sockaddr_in saddr;
1598 if (parse_host_port(&saddr, host_str) < 0)
1599 return -1;
1601 fd = socket(PF_INET, SOCK_STREAM, 0);
1602 if (fd < 0) {
1603 perror("socket");
1604 return -1;
1606 socket_set_nonblock(fd);
1608 connected = 0;
1609 for(;;) {
1610 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1611 if (ret < 0) {
1612 err = socket_error();
1613 if (err == EINTR || err == EWOULDBLOCK) {
1614 } else if (err == EINPROGRESS) {
1615 break;
1616 #ifdef _WIN32
1617 } else if (err == WSAEALREADY) {
1618 break;
1619 #endif
1620 } else {
1621 perror("connect");
1622 closesocket(fd);
1623 return -1;
1625 } else {
1626 connected = 1;
1627 break;
1630 s = net_socket_fd_init(vlan, model, name, fd, connected);
1631 if (!s)
1632 return -1;
1633 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1634 "socket: connect to %s:%d",
1635 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1636 return 0;
1639 static int net_socket_mcast_init(VLANState *vlan,
1640 const char *model,
1641 const char *name,
1642 const char *host_str)
1644 NetSocketState *s;
1645 int fd;
1646 struct sockaddr_in saddr;
1648 if (parse_host_port(&saddr, host_str) < 0)
1649 return -1;
1652 fd = net_socket_mcast_create(&saddr);
1653 if (fd < 0)
1654 return -1;
1656 s = net_socket_fd_init(vlan, model, name, fd, 0);
1657 if (!s)
1658 return -1;
1660 s->dgram_dst = saddr;
1662 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1663 "socket: mcast=%s:%d",
1664 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1665 return 0;
1669 /* find or alloc a new VLAN */
1670 VLANState *qemu_find_vlan(int id)
1672 VLANState **pvlan, *vlan;
1673 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1674 if (vlan->id == id)
1675 return vlan;
1677 vlan = qemu_mallocz(sizeof(VLANState));
1678 vlan->id = id;
1679 vlan->next = NULL;
1680 pvlan = &first_vlan;
1681 while (*pvlan != NULL)
1682 pvlan = &(*pvlan)->next;
1683 *pvlan = vlan;
1684 return vlan;
1687 void qemu_check_nic_model(NICInfo *nd, const char *model)
1689 const char *models[2];
1691 models[0] = model;
1692 models[1] = NULL;
1694 qemu_check_nic_model_list(nd, models, model);
1697 void qemu_check_nic_model_list(NICInfo *nd, const char * const *models,
1698 const char *default_model)
1700 int i, exit_status = 0;
1702 if (!nd->model)
1703 nd->model = strdup(default_model);
1705 if (strcmp(nd->model, "?") != 0) {
1706 for (i = 0 ; models[i]; i++)
1707 if (strcmp(nd->model, models[i]) == 0)
1708 return;
1710 fprintf(stderr, "qemu: Unsupported NIC model: %s\n", nd->model);
1711 exit_status = 1;
1714 fprintf(stderr, "qemu: Supported NIC models: ");
1715 for (i = 0 ; models[i]; i++)
1716 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
1718 exit(exit_status);
1721 int net_client_init(const char *device, const char *p)
1723 char buf[1024];
1724 int vlan_id, ret;
1725 VLANState *vlan;
1726 char *name = NULL;
1728 vlan_id = 0;
1729 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1730 vlan_id = strtol(buf, NULL, 0);
1732 vlan = qemu_find_vlan(vlan_id);
1733 if (!vlan) {
1734 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
1735 return -1;
1737 if (get_param_value(buf, sizeof(buf), "name", p)) {
1738 name = strdup(buf);
1740 if (!strcmp(device, "nic")) {
1741 NICInfo *nd;
1742 uint8_t *macaddr;
1744 if (nb_nics >= MAX_NICS) {
1745 fprintf(stderr, "Too Many NICs\n");
1746 return -1;
1748 nd = &nd_table[nb_nics];
1749 macaddr = nd->macaddr;
1750 macaddr[0] = 0x52;
1751 macaddr[1] = 0x54;
1752 macaddr[2] = 0x00;
1753 macaddr[3] = 0x12;
1754 macaddr[4] = 0x34;
1755 macaddr[5] = 0x56 + nb_nics;
1757 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1758 if (parse_macaddr(macaddr, buf) < 0) {
1759 fprintf(stderr, "invalid syntax for ethernet address\n");
1760 return -1;
1763 if (get_param_value(buf, sizeof(buf), "model", p)) {
1764 nd->model = strdup(buf);
1766 nd->vlan = vlan;
1767 nd->name = name;
1768 name = NULL;
1769 nb_nics++;
1770 vlan->nb_guest_devs++;
1771 ret = 0;
1772 } else
1773 if (!strcmp(device, "none")) {
1774 /* does nothing. It is needed to signal that no network cards
1775 are wanted */
1776 ret = 0;
1777 } else
1778 #ifdef CONFIG_SLIRP
1779 if (!strcmp(device, "user")) {
1780 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1781 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1783 if (get_param_value(buf, sizeof(buf), "restrict", p)) {
1784 slirp_restrict = (buf[0] == 'y') ? 1 : 0;
1786 if (get_param_value(buf, sizeof(buf), "ip", p)) {
1787 slirp_ip = strdup(buf);
1789 vlan->nb_host_devs++;
1790 ret = net_slirp_init(vlan, device, name);
1791 } else
1792 #endif
1793 #ifdef _WIN32
1794 if (!strcmp(device, "tap")) {
1795 char ifname[64];
1796 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1797 fprintf(stderr, "tap: no interface name\n");
1798 return -1;
1800 vlan->nb_host_devs++;
1801 ret = tap_win32_init(vlan, device, name, ifname);
1802 } else
1803 #elif defined (_AIX)
1804 #else
1805 if (!strcmp(device, "tap")) {
1806 char ifname[64];
1807 char setup_script[1024], down_script[1024];
1808 int fd;
1809 vlan->nb_host_devs++;
1810 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1811 fd = strtol(buf, NULL, 0);
1812 fcntl(fd, F_SETFL, O_NONBLOCK);
1813 ret = -1;
1814 if (net_tap_fd_init(vlan, device, name, fd,
1815 tap_probe_vnet_hdr(fd)))
1816 ret = 0;
1817 } else {
1818 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1819 ifname[0] = '\0';
1821 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1822 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1824 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1825 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1827 ret = net_tap_init(vlan, device, name, ifname, setup_script, down_script);
1829 } else
1830 #endif
1831 if (!strcmp(device, "socket")) {
1832 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1833 int fd;
1834 fd = strtol(buf, NULL, 0);
1835 ret = -1;
1836 if (net_socket_fd_init(vlan, device, name, fd, 1))
1837 ret = 0;
1838 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1839 ret = net_socket_listen_init(vlan, device, name, buf);
1840 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1841 ret = net_socket_connect_init(vlan, device, name, buf);
1842 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1843 ret = net_socket_mcast_init(vlan, device, name, buf);
1844 } else {
1845 fprintf(stderr, "Unknown socket options: %s\n", p);
1846 return -1;
1848 vlan->nb_host_devs++;
1849 } else
1850 #ifdef CONFIG_VDE
1851 if (!strcmp(device, "vde")) {
1852 char vde_sock[1024], vde_group[512];
1853 int vde_port, vde_mode;
1854 vlan->nb_host_devs++;
1855 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1856 vde_sock[0] = '\0';
1858 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1859 vde_port = strtol(buf, NULL, 10);
1860 } else {
1861 vde_port = 0;
1863 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1864 vde_group[0] = '\0';
1866 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1867 vde_mode = strtol(buf, NULL, 8);
1868 } else {
1869 vde_mode = 0700;
1871 ret = net_vde_init(vlan, device, name, vde_sock, vde_port, vde_group, vde_mode);
1872 } else
1873 #endif
1875 fprintf(stderr, "Unknown network device: %s\n", device);
1876 if (name)
1877 free(name);
1878 return -1;
1880 if (ret < 0) {
1881 fprintf(stderr, "Could not initialize device '%s'\n", device);
1883 if (name)
1884 free(name);
1885 return ret;
1888 void net_client_uninit(NICInfo *nd)
1890 nd->vlan->nb_guest_devs--; /* XXX: free vlan on last reference */
1891 nb_nics--;
1892 nd->used = 0;
1893 free((void *)nd->model);
1896 int net_client_parse(const char *str)
1898 const char *p;
1899 char *q;
1900 char device[64];
1902 p = str;
1903 q = device;
1904 while (*p != '\0' && *p != ',') {
1905 if ((q - device) < sizeof(device) - 1)
1906 *q++ = *p;
1907 p++;
1909 *q = '\0';
1910 if (*p == ',')
1911 p++;
1913 return net_client_init(device, p);
1916 void do_info_network(void)
1918 VLANState *vlan;
1919 VLANClientState *vc;
1921 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1922 term_printf("VLAN %d devices:\n", vlan->id);
1923 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
1924 term_printf(" %s: %s\n", vc->name, vc->info_str);
1928 int do_set_link(const char *name, const char *up_or_down)
1930 VLANState *vlan;
1931 VLANClientState *vc = NULL;
1933 for (vlan = first_vlan; vlan != NULL; vlan = vlan->next)
1934 for (vc = vlan->first_client; vc != NULL; vc = vc->next)
1935 if (strcmp(vc->name, name) == 0)
1936 goto done;
1937 done:
1939 if (!vc) {
1940 term_printf("could not find network device '%s'", name);
1941 return 0;
1944 if (strcmp(up_or_down, "up") == 0)
1945 vc->link_down = 0;
1946 else if (strcmp(up_or_down, "down") == 0)
1947 vc->link_down = 1;
1948 else
1949 term_printf("invalid link status '%s'; only 'up' or 'down' valid\n",
1950 up_or_down);
1952 if (vc->link_status_changed)
1953 vc->link_status_changed(vc);
1955 return 1;
1958 void net_cleanup(void)
1960 VLANState *vlan;
1962 #if !defined(_WIN32)
1963 /* close network clients */
1964 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1965 VLANClientState *vc;
1967 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1968 if (vc->fd_read == tap_receive) {
1969 TAPState *s = vc->opaque;
1971 if (s->down_script[0])
1972 launch_script(s->down_script, s->down_script_arg, s->fd);
1974 #if defined(CONFIG_VDE)
1975 if (vc->fd_read == vde_from_qemu) {
1976 VDEState *s = vc->opaque;
1977 vde_close(s->vde);
1979 #endif
1982 #endif
1985 void net_client_check(void)
1987 VLANState *vlan;
1989 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1990 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
1991 continue;
1992 if (vlan->nb_guest_devs == 0)
1993 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
1994 if (vlan->nb_host_devs == 0)
1995 fprintf(stderr,
1996 "Warning: vlan %d is not connected to host network\n",
1997 vlan->id);