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
24 #include "qemu-common.h"
28 #include "qemu-timer.h"
29 #include "qemu-char.h"
30 #include "audio/audio.h"
41 #include <sys/times.h>
45 #include <sys/ioctl.h>
46 #include <sys/resource.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
51 #include <net/if_tap.h>
54 #include <linux/if_tun.h>
56 #include <arpa/inet.h>
59 #include <sys/select.h>
67 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
68 #include <freebsd/stdlib.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> */
80 #include <linux/ppdev.h>
81 #include <linux/parport.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>
101 #include "qemu_socket.h"
103 #if defined(CONFIG_SLIRP)
104 #include "libslirp.h"
107 #if defined(__OpenBSD__)
111 #if defined(CONFIG_VDE)
112 #include <libvdeplug.h>
117 #include <sys/timeb.h>
118 #include <mmsystem.h>
119 #define getopt_long_only getopt_long
120 #define memalign(align, size) malloc(size)
123 static VLANState *first_vlan;
125 /***********************************************************/
126 /* network device redirectors */
128 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
129 static void hex_dump(FILE *f, const uint8_t *buf, int size)
133 for(i=0;i<size;i+=16) {
137 fprintf(f, "%08x ", i);
140 fprintf(f, " %02x", buf[i+j]);
147 if (c < ' ' || c > '~')
156 static int parse_macaddr(uint8_t *macaddr, const char *p)
163 offset = strtol(p, &last_char, 0);
164 if (0 == errno && '\0' == *last_char &&
165 offset >= 0 && offset <= 0xFFFFFF) {
166 macaddr[3] = (offset & 0xFF0000) >> 16;
167 macaddr[4] = (offset & 0xFF00) >> 8;
168 macaddr[5] = offset & 0xFF;
171 for(i = 0; i < 6; i++) {
172 macaddr[i] = strtol(p, (char **)&p, 16);
177 if (*p != ':' && *p != '-')
188 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
199 if (len > buf_size - 1)
208 int parse_host_src_port(struct sockaddr_in *haddr,
209 struct sockaddr_in *saddr,
210 const char *input_str)
212 char *str = strdup(input_str);
213 char *host_str = str;
215 const char *src_str2;
219 * Chop off any extra arguments at the end of the string which
220 * would start with a comma, then fill in the src port information
221 * if it was provided else use the "any address" and "any port".
223 if ((ptr = strchr(str,',')))
226 if ((src_str = strchr(input_str,'@'))) {
231 if (parse_host_port(haddr, host_str) < 0)
235 if (!src_str || *src_str == '\0')
238 if (parse_host_port(saddr, src_str2) < 0)
249 int parse_host_port(struct sockaddr_in *saddr, const char *str)
257 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
259 saddr->sin_family = AF_INET;
260 if (buf[0] == '\0') {
261 saddr->sin_addr.s_addr = 0;
263 if (qemu_isdigit(buf[0])) {
264 if (!inet_aton(buf, &saddr->sin_addr))
267 if ((he = gethostbyname(buf)) == NULL)
269 saddr->sin_addr = *(struct in_addr *)he->h_addr;
272 port = strtol(p, (char **)&r, 0);
275 saddr->sin_port = htons(port);
279 #if !defined(_WIN32) && 0
280 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
285 len = MIN(108, strlen(str));
286 p = strchr(str, ',');
288 len = MIN(len, p - str);
290 memset(uaddr, 0, sizeof(*uaddr));
292 uaddr->sun_family = AF_UNIX;
293 memcpy(uaddr->sun_path, str, len);
299 static char *assign_name(VLANClientState *vc1, const char *model)
305 for (vlan = first_vlan; vlan; vlan = vlan->next) {
308 for (vc = vlan->first_client; vc; vc = vc->next)
309 if (vc != vc1 && strcmp(vc->model, model) == 0)
313 snprintf(buf, sizeof(buf), "%s.%d", model, id);
318 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
320 IOReadHandler *fd_read,
321 IOCanRWHandler *fd_can_read,
324 VLANClientState *vc, **pvc;
325 vc = qemu_mallocz(sizeof(VLANClientState));
328 vc->model = strdup(model);
329 vc->name = assign_name(vc, model);
330 vc->fd_read = fd_read;
331 vc->fd_can_read = fd_can_read;
336 pvc = &vlan->first_client;
343 void qemu_del_vlan_client(VLANClientState *vc)
345 VLANClientState **pvc = &vc->vlan->first_client;
358 int qemu_can_send_packet(VLANClientState *vc1)
360 VLANState *vlan = vc1->vlan;
363 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
365 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
372 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
374 VLANState *vlan = vc1->vlan;
378 printf("vlan %d send:\n", vlan->id);
379 hex_dump(stdout, buf, size);
381 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
383 vc->fd_read(vc->opaque, buf, size);
388 static ssize_t vc_sendv_compat(VLANClientState *vc, const struct iovec *iov,
391 uint8_t buffer[4096];
395 for (i = 0; i < iovcnt; i++) {
398 len = MIN(sizeof(buffer) - offset, iov[i].iov_len);
399 memcpy(buffer + offset, iov[i].iov_base, len);
403 vc->fd_read(vc->opaque, buffer, offset);
408 ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,
411 VLANState *vlan = vc1->vlan;
415 for (vc = vlan->first_client; vc != NULL; vc = vc->next) {
422 len = vc->fd_readv(vc->opaque, iov, iovcnt);
423 else if (vc->fd_read)
424 len = vc_sendv_compat(vc, iov, iovcnt);
426 max_len = MAX(max_len, len);
432 #if defined(CONFIG_SLIRP)
434 /* slirp network adapter */
436 static int slirp_inited;
437 static VLANClientState *slirp_vc;
439 int slirp_can_output(void)
441 return !slirp_vc || qemu_can_send_packet(slirp_vc);
444 void slirp_output(const uint8_t *pkt, int pkt_len)
447 printf("slirp output:\n");
448 hex_dump(stdout, pkt, pkt_len);
452 qemu_send_packet(slirp_vc, pkt, pkt_len);
455 int slirp_is_inited(void)
460 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
463 printf("slirp input:\n");
464 hex_dump(stdout, buf, size);
466 slirp_input(buf, size);
469 static int net_slirp_init(VLANState *vlan, const char *model)
475 slirp_vc = qemu_new_vlan_client(vlan, model,
476 slirp_receive, NULL, NULL);
477 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
481 void net_slirp_redir(const char *redir_str)
486 struct in_addr guest_addr;
487 int host_port, guest_port;
495 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
497 if (!strcmp(buf, "tcp")) {
499 } else if (!strcmp(buf, "udp")) {
505 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
507 host_port = strtol(buf, &r, 0);
511 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
513 if (buf[0] == '\0') {
514 pstrcpy(buf, sizeof(buf), "10.0.2.15");
516 if (!inet_aton(buf, &guest_addr))
519 guest_port = strtol(p, &r, 0);
523 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
524 fprintf(stderr, "qemu: could not set up redirection\n");
529 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
535 static char smb_dir[1024];
537 static void erase_dir(char *dir_name)
543 /* erase all the files in the directory */
544 if ((d = opendir(dir_name)) != 0) {
549 if (strcmp(de->d_name, ".") != 0 &&
550 strcmp(de->d_name, "..") != 0) {
551 snprintf(filename, sizeof(filename), "%s/%s",
552 smb_dir, de->d_name);
553 if (unlink(filename) != 0) /* is it a directory? */
562 /* automatic user mode samba server configuration */
563 static void smb_exit(void)
568 /* automatic user mode samba server configuration */
569 void net_slirp_smb(const char *exported_dir)
572 char smb_cmdline[1024];
580 /* XXX: better tmp dir construction */
581 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
582 if (mkdir(smb_dir, 0700) < 0) {
583 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
586 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
588 f = fopen(smb_conf, "w");
590 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
597 "socket address=127.0.0.1\n"
599 "lock directory=%s\n"
600 "log file=%s/log.smbd\n"
601 "smb passwd file=%s/smbpasswd\n"
617 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
618 SMBD_COMMAND, smb_conf);
620 slirp_add_exec(0, smb_cmdline, 4, 139);
623 #endif /* !defined(_WIN32) */
624 void do_info_slirp(void)
629 #endif /* CONFIG_SLIRP */
633 typedef struct TAPState {
636 char down_script[1024];
640 static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,
643 TAPState *s = opaque;
647 len = writev(s->fd, iov, iovcnt);
648 } while (len == -1 && (errno == EINTR || errno == EAGAIN));
654 static void tap_receive(void *opaque, const uint8_t *buf, int size)
656 TAPState *s = opaque;
659 ret = write(s->fd, buf, size);
660 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
667 static void tap_send(void *opaque)
669 TAPState *s = opaque;
676 sbuf.maxlen = sizeof(buf);
678 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
680 size = read(s->fd, buf, sizeof(buf));
683 qemu_send_packet(s->vc, buf, size);
689 static TAPState *net_tap_fd_init(VLANState *vlan, const char *model, int fd)
693 s = qemu_mallocz(sizeof(TAPState));
697 s->vc = qemu_new_vlan_client(vlan, model, tap_receive, NULL, s);
699 s->vc->fd_readv = tap_receive_iov;
701 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
702 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
706 #if defined (_BSD) || defined (__FreeBSD_kernel__)
707 static int tap_open(char *ifname, int ifname_size)
713 TFR(fd = open("/dev/tap", O_RDWR));
715 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
720 dev = devname(s.st_rdev, S_IFCHR);
721 pstrcpy(ifname, ifname_size, dev);
723 fcntl(fd, F_SETFL, O_NONBLOCK);
726 #elif defined(__sun__)
727 #define TUNNEWPPA (('T'<<16) | 0x0001)
729 * Allocate TAP device, returns opened fd.
730 * Stores dev name in the first arg(must be large enough).
732 int tap_alloc(char *dev, size_t dev_size)
734 int tap_fd, if_fd, ppa = -1;
735 static int ip_fd = 0;
738 static int arp_fd = 0;
739 int ip_muxid, arp_muxid;
740 struct strioctl strioc_if, strioc_ppa;
741 int link_type = I_PLINK;;
743 char actual_name[32] = "";
745 memset(&ifr, 0x0, sizeof(ifr));
749 while( *ptr && !qemu_isdigit((int)*ptr) ) ptr++;
753 /* Check if IP device was opened */
757 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
759 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
763 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
765 syslog(LOG_ERR, "Can't open /dev/tap");
769 /* Assign a new PPA and get its unit number. */
770 strioc_ppa.ic_cmd = TUNNEWPPA;
771 strioc_ppa.ic_timout = 0;
772 strioc_ppa.ic_len = sizeof(ppa);
773 strioc_ppa.ic_dp = (char *)&ppa;
774 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
775 syslog (LOG_ERR, "Can't assign new interface");
777 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
779 syslog(LOG_ERR, "Can't open /dev/tap (2)");
782 if(ioctl(if_fd, I_PUSH, "ip") < 0){
783 syslog(LOG_ERR, "Can't push IP module");
787 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
788 syslog(LOG_ERR, "Can't get flags\n");
790 snprintf (actual_name, 32, "tap%d", ppa);
791 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
794 /* Assign ppa according to the unit number returned by tun device */
796 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
797 syslog (LOG_ERR, "Can't set PPA %d", ppa);
798 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
799 syslog (LOG_ERR, "Can't get flags\n");
800 /* Push arp module to if_fd */
801 if (ioctl (if_fd, I_PUSH, "arp") < 0)
802 syslog (LOG_ERR, "Can't push ARP module (2)");
804 /* Push arp module to ip_fd */
805 if (ioctl (ip_fd, I_POP, NULL) < 0)
806 syslog (LOG_ERR, "I_POP failed\n");
807 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
808 syslog (LOG_ERR, "Can't push ARP module (3)\n");
810 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
812 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
814 /* Set ifname to arp */
815 strioc_if.ic_cmd = SIOCSLIFNAME;
816 strioc_if.ic_timout = 0;
817 strioc_if.ic_len = sizeof(ifr);
818 strioc_if.ic_dp = (char *)𝔦
819 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
820 syslog (LOG_ERR, "Can't set ifname to arp\n");
823 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
824 syslog(LOG_ERR, "Can't link TAP device to IP");
828 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
829 syslog (LOG_ERR, "Can't link TAP device to ARP");
833 memset(&ifr, 0x0, sizeof(ifr));
834 pstrcpy(ifr.lifr_name, sizeof(ifr.lifr_name), actual_name);
835 ifr.lifr_ip_muxid = ip_muxid;
836 ifr.lifr_arp_muxid = arp_muxid;
838 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
840 ioctl (ip_fd, I_PUNLINK , arp_muxid);
841 ioctl (ip_fd, I_PUNLINK, ip_muxid);
842 syslog (LOG_ERR, "Can't set multiplexor id");
845 snprintf(dev, dev_size, "tap%d", ppa);
849 static int tap_open(char *ifname, int ifname_size)
853 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
854 fprintf(stderr, "Cannot allocate TAP device\n");
857 pstrcpy(ifname, ifname_size, dev);
858 fcntl(fd, F_SETFL, O_NONBLOCK);
862 static int tap_open(char *ifname, int ifname_size)
864 fprintf (stderr, "no tap on AIX\n");
868 static int tap_open(char *ifname, int ifname_size)
873 TFR(fd = open("/dev/net/tun", O_RDWR));
875 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
878 memset(&ifr, 0, sizeof(ifr));
879 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
880 if (ifname[0] != '\0')
881 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
883 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
884 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
886 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
890 pstrcpy(ifname, ifname_size, ifr.ifr_name);
891 fcntl(fd, F_SETFL, O_NONBLOCK);
896 static int launch_script(const char *setup_script, const char *ifname, int fd)
902 /* try to launch network script */
906 int open_max = sysconf (_SC_OPEN_MAX), i;
907 for (i = 0; i < open_max; i++)
908 if (i != STDIN_FILENO &&
909 i != STDOUT_FILENO &&
910 i != STDERR_FILENO &&
915 *parg++ = (char *)setup_script;
916 *parg++ = (char *)ifname;
918 execv(setup_script, args);
921 while (waitpid(pid, &status, 0) != pid);
922 if (!WIFEXITED(status) ||
923 WEXITSTATUS(status) != 0) {
924 fprintf(stderr, "%s: could not launch network script\n",
932 static int net_tap_init(VLANState *vlan, const char *model, const char *ifname1,
933 const char *setup_script, const char *down_script)
940 pstrcpy(ifname, sizeof(ifname), ifname1);
943 TFR(fd = tap_open(ifname, sizeof(ifname)));
947 if (!setup_script || !strcmp(setup_script, "no"))
949 if (setup_script[0] != '\0') {
950 if (launch_script(setup_script, ifname, fd))
953 s = net_tap_fd_init(vlan, model, fd);
956 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
957 "tap: ifname=%s setup_script=%s", ifname, setup_script);
958 if (down_script && strcmp(down_script, "no"))
959 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
965 #if defined(CONFIG_VDE)
966 typedef struct VDEState {
971 static void vde_to_qemu(void *opaque)
973 VDEState *s = opaque;
977 size = vde_recv(s->vde, buf, sizeof(buf), 0);
979 qemu_send_packet(s->vc, buf, size);
983 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
985 VDEState *s = opaque;
988 ret = vde_send(s->vde, buf, size, 0);
989 if (ret < 0 && errno == EINTR) {
996 static int net_vde_init(VLANState *vlan, const char *model, const char *sock,
997 int port, const char *group, int mode)
1000 char *init_group = strlen(group) ? (char *)group : NULL;
1001 char *init_sock = strlen(sock) ? (char *)sock : NULL;
1003 struct vde_open_args args = {
1005 .group = init_group,
1009 s = qemu_mallocz(sizeof(VDEState));
1012 s->vde = vde_open(init_sock, "QEMU", &args);
1017 s->vc = qemu_new_vlan_client(vlan, model, vde_from_qemu, NULL, s);
1018 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
1019 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
1020 sock, vde_datafd(s->vde));
1025 /* network connection */
1026 typedef struct NetSocketState {
1027 VLANClientState *vc;
1029 int state; /* 0 = getting length, 1 = getting data */
1033 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
1036 typedef struct NetSocketListenState {
1040 } NetSocketListenState;
1042 /* XXX: we consider we can send the whole packet without blocking */
1043 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
1045 NetSocketState *s = opaque;
1049 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
1050 send_all(s->fd, buf, size);
1053 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
1055 NetSocketState *s = opaque;
1056 sendto(s->fd, buf, size, 0,
1057 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
1060 static void net_socket_send(void *opaque)
1062 NetSocketState *s = opaque;
1067 size = recv(s->fd, buf1, sizeof(buf1), 0);
1069 err = socket_error();
1070 if (err != EWOULDBLOCK)
1072 } else if (size == 0) {
1073 /* end of connection */
1075 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1081 /* reassemble a packet from the network */
1087 memcpy(s->buf + s->index, buf, l);
1091 if (s->index == 4) {
1093 s->packet_len = ntohl(*(uint32_t *)s->buf);
1099 l = s->packet_len - s->index;
1102 memcpy(s->buf + s->index, buf, l);
1106 if (s->index >= s->packet_len) {
1107 qemu_send_packet(s->vc, s->buf, s->packet_len);
1116 static void net_socket_send_dgram(void *opaque)
1118 NetSocketState *s = opaque;
1121 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
1125 /* end of connection */
1126 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
1129 qemu_send_packet(s->vc, s->buf, size);
1132 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
1137 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
1138 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
1139 inet_ntoa(mcastaddr->sin_addr),
1140 (int)ntohl(mcastaddr->sin_addr.s_addr));
1144 fd = socket(PF_INET, SOCK_DGRAM, 0);
1146 perror("socket(PF_INET, SOCK_DGRAM)");
1151 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1152 (const char *)&val, sizeof(val));
1154 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
1158 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
1164 /* Add host to multicast group */
1165 imr.imr_multiaddr = mcastaddr->sin_addr;
1166 imr.imr_interface.s_addr = htonl(INADDR_ANY);
1168 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1169 (const char *)&imr, sizeof(struct ip_mreq));
1171 perror("setsockopt(IP_ADD_MEMBERSHIP)");
1175 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
1177 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1178 (const char *)&val, sizeof(val));
1180 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
1184 socket_set_nonblock(fd);
1192 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, const char *model,
1193 int fd, int is_connected)
1195 struct sockaddr_in saddr;
1197 socklen_t saddr_len;
1200 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
1201 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
1202 * by ONLY ONE process: we must "clone" this dgram socket --jjo
1206 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
1208 if (saddr.sin_addr.s_addr==0) {
1209 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
1213 /* clone dgram socket */
1214 newfd = net_socket_mcast_create(&saddr);
1216 /* error already reported by net_socket_mcast_create() */
1220 /* clone newfd to fd, close newfd */
1225 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
1226 fd, strerror(errno));
1231 s = qemu_mallocz(sizeof(NetSocketState));
1236 s->vc = qemu_new_vlan_client(vlan, model, net_socket_receive_dgram, NULL, s);
1237 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
1239 /* mcast: save bound address as dst */
1240 if (is_connected) s->dgram_dst=saddr;
1242 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1243 "socket: fd=%d (%s mcast=%s:%d)",
1244 fd, is_connected? "cloned" : "",
1245 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1249 static void net_socket_connect(void *opaque)
1251 NetSocketState *s = opaque;
1252 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
1255 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, const char *model,
1256 int fd, int is_connected)
1259 s = qemu_mallocz(sizeof(NetSocketState));
1263 s->vc = qemu_new_vlan_client(vlan, model,
1264 net_socket_receive, NULL, s);
1265 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1266 "socket: fd=%d", fd);
1268 net_socket_connect(s);
1270 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
1275 static NetSocketState *net_socket_fd_init(VLANState *vlan, const char *model,
1276 int fd, int is_connected)
1278 int so_type=-1, optlen=sizeof(so_type);
1280 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
1281 (socklen_t *)&optlen)< 0) {
1282 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
1287 return net_socket_fd_init_dgram(vlan, model, fd, is_connected);
1289 return net_socket_fd_init_stream(vlan, model, fd, is_connected);
1291 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
1292 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
1293 return net_socket_fd_init_stream(vlan, model, fd, is_connected);
1298 static void net_socket_accept(void *opaque)
1300 NetSocketListenState *s = opaque;
1302 struct sockaddr_in saddr;
1307 len = sizeof(saddr);
1308 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
1309 if (fd < 0 && errno != EINTR) {
1311 } else if (fd >= 0) {
1315 s1 = net_socket_fd_init(s->vlan, s->model, fd, 1);
1319 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
1320 "socket: connection from %s:%d",
1321 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1325 static int net_socket_listen_init(VLANState *vlan, const char *model,
1326 const char *host_str)
1328 NetSocketListenState *s;
1330 struct sockaddr_in saddr;
1332 if (parse_host_port(&saddr, host_str) < 0)
1335 s = qemu_mallocz(sizeof(NetSocketListenState));
1339 fd = socket(PF_INET, SOCK_STREAM, 0);
1344 socket_set_nonblock(fd);
1346 /* allow fast reuse */
1348 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
1350 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1355 ret = listen(fd, 0);
1361 s->model = strdup(model);
1363 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
1367 static int net_socket_connect_init(VLANState *vlan, const char *model,
1368 const char *host_str)
1371 int fd, connected, ret, err;
1372 struct sockaddr_in saddr;
1374 if (parse_host_port(&saddr, host_str) < 0)
1377 fd = socket(PF_INET, SOCK_STREAM, 0);
1382 socket_set_nonblock(fd);
1386 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
1388 err = socket_error();
1389 if (err == EINTR || err == EWOULDBLOCK) {
1390 } else if (err == EINPROGRESS) {
1393 } else if (err == WSAEALREADY) {
1406 s = net_socket_fd_init(vlan, model, fd, connected);
1409 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1410 "socket: connect to %s:%d",
1411 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1415 static int net_socket_mcast_init(VLANState *vlan, const char *model,
1416 const char *host_str)
1420 struct sockaddr_in saddr;
1422 if (parse_host_port(&saddr, host_str) < 0)
1426 fd = net_socket_mcast_create(&saddr);
1430 s = net_socket_fd_init(vlan, model, fd, 0);
1434 s->dgram_dst = saddr;
1436 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
1437 "socket: mcast=%s:%d",
1438 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
1443 /* find or alloc a new VLAN */
1444 VLANState *qemu_find_vlan(int id)
1446 VLANState **pvlan, *vlan;
1447 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1451 vlan = qemu_mallocz(sizeof(VLANState));
1456 pvlan = &first_vlan;
1457 while (*pvlan != NULL)
1458 pvlan = &(*pvlan)->next;
1463 int net_client_init(const char *device, const char *p)
1470 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
1471 vlan_id = strtol(buf, NULL, 0);
1473 vlan = qemu_find_vlan(vlan_id);
1475 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
1478 if (!strcmp(device, "nic")) {
1482 if (nb_nics >= MAX_NICS) {
1483 fprintf(stderr, "Too Many NICs\n");
1486 nd = &nd_table[nb_nics];
1487 macaddr = nd->macaddr;
1493 macaddr[5] = 0x56 + nb_nics;
1495 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
1496 if (parse_macaddr(macaddr, buf) < 0) {
1497 fprintf(stderr, "invalid syntax for ethernet address\n");
1501 if (get_param_value(buf, sizeof(buf), "model", p)) {
1502 nd->model = strdup(buf);
1506 vlan->nb_guest_devs++;
1509 if (!strcmp(device, "none")) {
1510 /* does nothing. It is needed to signal that no network cards
1515 if (!strcmp(device, "user")) {
1516 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
1517 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
1519 vlan->nb_host_devs++;
1520 ret = net_slirp_init(vlan, device);
1524 if (!strcmp(device, "tap")) {
1526 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1527 fprintf(stderr, "tap: no interface name\n");
1530 vlan->nb_host_devs++;
1531 ret = tap_win32_init(vlan, device, ifname);
1533 #elif defined (_AIX)
1535 if (!strcmp(device, "tap")) {
1537 char setup_script[1024], down_script[1024];
1539 vlan->nb_host_devs++;
1540 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1541 fd = strtol(buf, NULL, 0);
1542 fcntl(fd, F_SETFL, O_NONBLOCK);
1544 if (net_tap_fd_init(vlan, device, fd))
1547 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
1550 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
1551 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
1553 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
1554 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
1556 ret = net_tap_init(vlan, device, ifname, setup_script, down_script);
1560 if (!strcmp(device, "socket")) {
1561 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
1563 fd = strtol(buf, NULL, 0);
1565 if (net_socket_fd_init(vlan, device, fd, 1))
1567 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
1568 ret = net_socket_listen_init(vlan, device, buf);
1569 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
1570 ret = net_socket_connect_init(vlan, device, buf);
1571 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
1572 ret = net_socket_mcast_init(vlan, device, buf);
1574 fprintf(stderr, "Unknown socket options: %s\n", p);
1577 vlan->nb_host_devs++;
1580 if (!strcmp(device, "vde")) {
1581 char vde_sock[1024], vde_group[512];
1582 int vde_port, vde_mode;
1583 vlan->nb_host_devs++;
1584 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
1587 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
1588 vde_port = strtol(buf, NULL, 10);
1592 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
1593 vde_group[0] = '\0';
1595 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
1596 vde_mode = strtol(buf, NULL, 8);
1600 ret = net_vde_init(vlan, device, vde_sock, vde_port, vde_group, vde_mode);
1604 fprintf(stderr, "Unknown network device: %s\n", device);
1608 fprintf(stderr, "Could not initialize device '%s'\n", device);
1614 int net_client_parse(const char *str)
1622 while (*p != '\0' && *p != ',') {
1623 if ((q - device) < sizeof(device) - 1)
1631 return net_client_init(device, p);
1634 void do_info_network(void)
1637 VLANClientState *vc;
1639 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1640 term_printf("VLAN %d devices:\n", vlan->id);
1641 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
1642 term_printf(" %s\n", vc->info_str);
1646 void net_cleanup(void)
1650 #if !defined(_WIN32)
1651 /* close network clients */
1652 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1653 VLANClientState *vc;
1655 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1656 if (vc->fd_read == tap_receive) {
1658 TAPState *s = vc->opaque;
1660 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
1662 launch_script(s->down_script, ifname, s->fd);
1664 #if defined(CONFIG_VDE)
1665 if (vc->fd_read == vde_from_qemu) {
1666 VDEState *s = vc->opaque;
1675 void net_client_check(void)
1679 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1680 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
1682 if (vlan->nb_guest_devs == 0)
1683 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
1684 if (vlan->nb_host_devs == 0)
1686 "Warning: vlan %d is not connected to host network\n",