/* Exits on error */ static void do_changename(char *dev, char *newdev) { struct ifreq ifr; int fd; strncpy_IFNAMSIZ(ifr.ifr_name, dev); strncpy_IFNAMSIZ(ifr.ifr_newname, newdev); fd = get_ctl_fd(); xioctl(fd, SIOCSIFNAME, &ifr); close(fd); }
static smallint detect_link_wlan(void) { int i; struct iwreq iwrequest; uint8_t mac[ETH_ALEN]; memset(&iwrequest, 0, sizeof(iwrequest)); strncpy_IFNAMSIZ(iwrequest.ifr_ifrn.ifrn_name, G.iface); if (network_ioctl(SIOCGIWAP, &iwrequest, "SIOCGIWAP") < 0) { return IFSTATUS_ERR; } memcpy(mac, &iwrequest.u.ap_addr.sa_data, ETH_ALEN); if (mac[0] == 0xFF || mac[0] == 0x44 || mac[0] == 0x00) { for (i = 1; i < ETH_ALEN; ++i) { if (mac[i] != mac[0]) return IFSTATUS_UP; } return IFSTATUS_DOWN; } return IFSTATUS_UP; }
/* Exits on error */ static int get_address(char *dev, int *htype) { struct ifreq ifr; struct sockaddr_ll me; socklen_t alen; int s; s = xsocket(PF_PACKET, SOCK_DGRAM, 0); memset(&ifr, 0, sizeof(ifr)); strncpy_IFNAMSIZ(ifr.ifr_name, dev); xioctl(s, SIOCGIFINDEX, &ifr); memset(&me, 0, sizeof(me)); me.sll_family = AF_PACKET; me.sll_ifindex = ifr.ifr_ifindex; me.sll_protocol = htons(ETH_P_LOOP); xbind(s, (struct sockaddr*)&me, sizeof(me)); alen = sizeof(me); getsockname(s, (struct sockaddr*)&me, &alen); //never happens: //if (getsockname(s, (struct sockaddr*)&me, &alen) == -1) // bb_perror_msg_and_die("getsockname"); close(s); *htype = me.sll_hatype; return me.sll_halen; }
/* Dies on error, otherwise returns 0 */ static int do_del_ioctl(const char *basedev, struct ip_tunnel_parm *p) { struct ifreq ifr; int fd; if (p->name[0]) { strncpy_IFNAMSIZ(ifr.ifr_name, p->name); } else { strncpy_IFNAMSIZ(ifr.ifr_name, basedev); } ifr.ifr_ifru.ifru_data = (void*)p; fd = xsocket(AF_INET, SOCK_DGRAM, 0); xioctl(fd, SIOCDELTUNNEL, &ifr); close(fd); return 0; }
int tunctl_main(int argc UNUSED_PARAM, char **argv) { struct ifreq ifr; int fd; const char *opt_name = "tap%d"; const char *opt_device = "/dev/net/tun"; unsigned opts; enum { OPT_f = 1 << 0, // control device name (/dev/net/tun) OPT_t = 1 << 1, // create named interface OPT_d = 1 << 2, // delete named interface }; opt_complementary = "=0:t--d:d--t"; // no arguments; t ^ d opts = getopt32(argv, "f:t:d:u:g:b", // u, g, b accepted and ignored &opt_device, &opt_name, &opt_name, NULL, NULL); // set interface name memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TAP | IFF_NO_PI; strncpy_IFNAMSIZ(ifr.ifr_name, opt_name); // open device fd = xopen(opt_device, O_RDWR); IOCTL(fd, TUNSETIFF, (void *)&ifr); // create or delete interface IOCTL(fd, TUNSETPERSIST, (void *)(uintptr_t)(0 == (opts & OPT_d))); return EXIT_SUCCESS; }
int FAST_FUNC udhcp_read_interface(const char *interface, int *ifindex, uint32_t *nip, uint8_t *mac, uint16_t *mtu) { /* char buffer instead of bona-fide struct avoids aliasing warning */ char ifr_buf[sizeof(struct ifreq)]; struct ifreq *const ifr = (void *)ifr_buf; int fd; struct sockaddr_in *our_ip; memset(ifr, 0, sizeof(*ifr)); fd = xsocket(AF_INET, SOCK_RAW, IPPROTO_RAW); ifr->ifr_addr.sa_family = AF_INET; strncpy_IFNAMSIZ(ifr->ifr_name, interface); if (nip) { if (ioctl_or_perror(fd, SIOCGIFADDR, ifr, "is interface %s up and configured?", interface) ) { close(fd); return -1; } our_ip = (struct sockaddr_in *) &ifr->ifr_addr; *nip = our_ip->sin_addr.s_addr; log1("IP %s", inet_ntoa(our_ip->sin_addr)); } if (ifindex) { if (ioctl_or_warn(fd, SIOCGIFINDEX, ifr) != 0) { close(fd); return -1; } log1("Adapter index %d", ifr->ifr_ifindex); *ifindex = ifr->ifr_ifindex; } if (mac) { if (ioctl_or_warn(fd, SIOCGIFHWADDR, ifr) != 0) { close(fd); return -1; } memcpy(mac, ifr->ifr_hwaddr.sa_data, 6); log1("MAC %02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); } if (mtu) { if (ioctl_or_warn(fd, SIOCGIFMTU, ifr) != 0) { close(fd); return -1; } log1("Adapter mtu %d", ifr->ifr_mtu); *mtu = ifr->ifr_mtu; } close(fd); return 0; }
/* Dies on error */ static int do_ioctl_get_ifindex(char *dev) { struct ifreq ifr; int fd; strncpy_IFNAMSIZ(ifr.ifr_name, dev); fd = xsocket(AF_INET, SOCK_DGRAM, 0); xioctl(fd, SIOCGIFINDEX, &ifr); close(fd); return ifr.ifr_ifindex; }
/* Exits on error */ static void set_mtu(char *dev, int mtu) { struct ifreq ifr; int s; s = get_ctl_fd(); memset(&ifr, 0, sizeof(ifr)); strncpy_IFNAMSIZ(ifr.ifr_name, dev); ifr.ifr_mtu = mtu; xioctl(s, SIOCSIFMTU, &ifr); close(s); }
/* Exits on error */ static void set_qlen(char *dev, int qlen) { struct ifreq ifr; int s; s = get_ctl_fd(); memset(&ifr, 0, sizeof(ifr)); strncpy_IFNAMSIZ(ifr.ifr_name, dev); ifr.ifr_qlen = qlen; xioctl(s, SIOCSIFTXQLEN, &ifr); close(s); }
static int do_ioctl_get_iftype(char *dev) { struct ifreq ifr; int fd; int err; strncpy_IFNAMSIZ(ifr.ifr_name, dev); fd = xsocket(AF_INET, SOCK_DGRAM, 0); err = ioctl_or_warn(fd, SIOCGIFHWADDR, &ifr); close(fd); return err ? -1 : ifr.ifr_addr.sa_family; }
int vconfig_main(int argc, char **argv) { struct vlan_ioctl_args ifr; const char *p; int fd; if (argc < 3) { bb_show_usage(); } /* Don't bother closing the filedes. It will be closed on cleanup. */ /* Will die if 802.1q is not present */ xopen(conf_file_name, O_RDONLY); memset(&ifr, 0, sizeof(ifr)); ++argv; p = xfind_str(cmds+2, *argv); ifr.cmd = *p; if (argc != p[-1]) { bb_show_usage(); } if (ifr.cmd == SET_VLAN_NAME_TYPE_CMD) { /* set_name_type */ ifr.u.name_type = *xfind_str(name_types+1, argv[1]); } else { strncpy_IFNAMSIZ(ifr.device1, argv[1]); p = argv[2]; /* I suppose one could try to combine some of the function calls below, * since ifr.u.flag, ifr.u.VID, and ifr.u.skb_priority are all same-sized * (unsigned) int members of a unions. But because of the range checking, * doing so wouldn't save that much space and would also make maintainence * more of a pain. */ if (ifr.cmd == SET_VLAN_FLAG_CMD) { /* set_flag */ ifr.u.flag = xatoul_range(p, 0, 1); /* DM: in order to set reorder header, qos must be set */ ifr.vlan_qos = xatoul_range(argv[3], 0, 7); } else if (ifr.cmd == ADD_VLAN_CMD) { /* add */ ifr.u.VID = xatoul_range(p, 0, VLAN_GROUP_ARRAY_LEN-1); } else if (ifr.cmd != DEL_VLAN_CMD) { /* set_{egress|ingress}_map */ ifr.u.skb_priority = xatou(p); ifr.vlan_qos = xatoul_range(argv[3], 0, 7); } } fd = xsocket(AF_INET, SOCK_STREAM, 0); ioctl_or_perror_and_die(fd, SIOCSIFVLAN, &ifr, "ioctl error for %s", *argv); return 0; }
static int do_get_ioctl(const char *basedev, struct ip_tunnel_parm *p) { struct ifreq ifr; int fd; int err; strncpy_IFNAMSIZ(ifr.ifr_name, basedev); ifr.ifr_ifru.ifru_data = (void*)p; fd = xsocket(AF_INET, SOCK_DGRAM, 0); err = ioctl_or_warn(fd, SIOCGETTUNNEL, &ifr); close(fd); return err; }
int FAST_FUNC setsockopt_bindtodevice(int fd, const char *iface) { int r; struct ifreq ifr; strncpy_IFNAMSIZ(ifr.ifr_name, iface); /* NB: passing (iface, strlen(iface) + 1) does not work! * (maybe it works on _some_ kernels, but not on 2.6.26) * Actually, ifr_name is at offset 0, and in practice * just giving char[IFNAMSIZ] instead of struct ifreq works too. * But just in case it's not true on some obscure arch... */ r = setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr)); if (r) bb_perror_msg("can't bind to interface %s", iface); return r; }
/* Exits on error */ static void do_chflags(char *dev, uint32_t flags, uint32_t mask) { struct ifreq ifr; int fd; strncpy_IFNAMSIZ(ifr.ifr_name, dev); fd = get_ctl_fd(); xioctl(fd, SIOCGIFFLAGS, &ifr); if ((ifr.ifr_flags ^ flags) & mask) { ifr.ifr_flags &= ~mask; ifr.ifr_flags |= mask & flags; xioctl(fd, SIOCSIFFLAGS, &ifr); } close(fd); }
/* Dies on error, otherwise returns 0 */ static int do_add_ioctl(int cmd, const char *basedev, struct ip_tunnel_parm *p) { struct ifreq ifr; int fd; if (cmd == SIOCCHGTUNNEL && p->name[0]) { strncpy_IFNAMSIZ(ifr.ifr_name, p->name); } else { strncpy_IFNAMSIZ(ifr.ifr_name, basedev); } ifr.ifr_ifru.ifru_data = (void*)p; fd = xsocket(AF_INET, SOCK_DGRAM, 0); #if ENABLE_IOCTL_HEX2STR_ERROR /* #define magic will turn ioctl# into string */ if (cmd == SIOCCHGTUNNEL) xioctl(fd, SIOCCHGTUNNEL, &ifr); else xioctl(fd, SIOCADDTUNNEL, &ifr); #else xioctl(fd, cmd, &ifr); #endif close(fd); return 0; }
/* Exits on error */ static void parse_address(char *dev, int hatype, int halen, char *lla, struct ifreq *ifr) { int alen; memset(ifr, 0, sizeof(*ifr)); strncpy_IFNAMSIZ(ifr->ifr_name, dev); ifr->ifr_hwaddr.sa_family = hatype; alen = hatype == 1/*ARPHRD_ETHER*/ ? 14/*ETH_HLEN*/ : 19/*INFINIBAND_HLEN*/; alen = ll_addr_a2n((unsigned char *)(ifr->ifr_hwaddr.sa_data), alen, lla); if (alen < 0) exit(EXIT_FAILURE); if (alen != halen) { bb_error_msg_and_die("wrong address (%s) length: expected %d bytes", lla, halen); } }
int zcip_main(int argc UNUSED_PARAM, char **argv) { char *r_opt; const char *l_opt = "169.254.0.0"; int state; int nsent; unsigned opts; // Ugly trick, but I want these zeroed in one go struct { const struct ether_addr null_ethaddr; struct ifreq ifr; uint32_t chosen_nip; int conflicts; int timeout_ms; // must be signed int verbose; } L; #define null_ethaddr (L.null_ethaddr) #define ifr (L.ifr ) #define chosen_nip (L.chosen_nip ) #define conflicts (L.conflicts ) #define timeout_ms (L.timeout_ms ) #define verbose (L.verbose ) memset(&L, 0, sizeof(L)); INIT_G(); #define FOREGROUND (opts & 1) #define QUIT (opts & 2) // Parse commandline: prog [options] ifname script // exactly 2 args; -v accumulates and implies -f opt_complementary = "=2:vv:vf"; opts = getopt32(argv, "fqr:l:v", &r_opt, &l_opt, &verbose); #if !BB_MMU // on NOMMU reexec early (or else we will rerun things twice) if (!FOREGROUND) bb_daemonize_or_rexec(0 /*was: DAEMON_CHDIR_ROOT*/, argv); #endif // Open an ARP socket // (need to do it before openlog to prevent openlog from taking // fd 3 (sock_fd==3)) xmove_fd(xsocket(AF_PACKET, SOCK_PACKET, htons(ETH_P_ARP)), sock_fd); if (!FOREGROUND) { // do it before all bb_xx_msg calls openlog(applet_name, 0, LOG_DAEMON); logmode |= LOGMODE_SYSLOG; } bb_logenv_override(); { // -l n.n.n.n struct in_addr net; if (inet_aton(l_opt, &net) == 0 || (net.s_addr & htonl(IN_CLASSB_NET)) != net.s_addr ) { bb_error_msg_and_die("invalid network address"); } G.localnet_ip = ntohl(net.s_addr); } if (opts & 4) { // -r n.n.n.n struct in_addr ip; if (inet_aton(r_opt, &ip) == 0 || (ntohl(ip.s_addr) & IN_CLASSB_NET) != G.localnet_ip ) { bb_error_msg_and_die("invalid link address"); } chosen_nip = ip.s_addr; } argv += optind - 1; /* Now: argv[0]:junk argv[1]:intf argv[2]:script argv[3]:NULL */ /* We need to make space for script argument: */ argv[0] = argv[1]; argv[1] = argv[2]; /* Now: argv[0]:intf argv[1]:script argv[2]:junk argv[3]:NULL */ #define argv_intf (argv[0]) xsetenv("interface", argv_intf); // Initialize the interface (modprobe, ifup, etc) if (run(argv, "init", 0)) return EXIT_FAILURE; // Initialize G.iface_sockaddr // G.iface_sockaddr is: { u16 sa_family; u8 sa_data[14]; } //memset(&G.iface_sockaddr, 0, sizeof(G.iface_sockaddr)); //TODO: are we leaving sa_family == 0 (AF_UNSPEC)?! safe_strncpy(G.iface_sockaddr.sa_data, argv_intf, sizeof(G.iface_sockaddr.sa_data)); // Bind to the interface's ARP socket xbind(sock_fd, &G.iface_sockaddr, sizeof(G.iface_sockaddr)); // Get the interface's ethernet address //memset(&ifr, 0, sizeof(ifr)); strncpy_IFNAMSIZ(ifr.ifr_name, argv_intf); xioctl(sock_fd, SIOCGIFHWADDR, &ifr); memcpy(&G.our_ethaddr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN); // Start with some stable ip address, either a function of // the hardware address or else the last address we used. // we are taking low-order four bytes, as top-order ones // aren't random enough. // NOTE: the sequence of addresses we try changes only // depending on when we detect conflicts. { uint32_t t; move_from_unaligned32(t, ((char *)&G.our_ethaddr + 2)); t += getpid(); srand(t); } // FIXME cases to handle: // - zcip already running! // - link already has local address... just defend/update // Daemonize now; don't delay system startup if (!FOREGROUND) { #if BB_MMU bb_daemonize(0 /*was: DAEMON_CHDIR_ROOT*/); #endif bb_info_msg("start, interface %s", argv_intf); } // Run the dynamic address negotiation protocol, // restarting after address conflicts: // - start with some address we want to try // - short random delay // - arp probes to see if another host uses it // 00:04:e2:64:23:c2 > ff:ff:ff:ff:ff:ff arp who-has 169.254.194.171 tell 0.0.0.0 // - arp announcements that we're claiming it // 00:04:e2:64:23:c2 > ff:ff:ff:ff:ff:ff arp who-has 169.254.194.171 (00:04:e2:64:23:c2) tell 169.254.194.171 // - use it // - defend it, within limits // exit if: // - address is successfully obtained and -q was given: // run "<script> config", then exit with exitcode 0 // - poll error (when does this happen?) // - read error (when does this happen?) // - sendto error (in send_arp_request()) (when does this happen?) // - revents & POLLERR (link down). run "<script> deconfig" first if (chosen_nip == 0) { new_nip_and_PROBE: chosen_nip = pick_nip(); } nsent = 0; state = PROBE; while (1) { struct pollfd fds[1]; unsigned deadline_us; struct arp_packet p; int ip_conflict; int n; fds[0].fd = sock_fd; fds[0].events = POLLIN; fds[0].revents = 0; // Poll, being ready to adjust current timeout if (!timeout_ms) { timeout_ms = random_delay_ms(PROBE_WAIT); // FIXME setsockopt(sock_fd, SO_ATTACH_FILTER, ...) to // make the kernel filter out all packets except // ones we'd care about. } // Set deadline_us to the point in time when we timeout deadline_us = MONOTONIC_US() + timeout_ms * 1000; VDBG("...wait %d %s nsent=%u\n", timeout_ms, argv_intf, nsent); n = safe_poll(fds, 1, timeout_ms); if (n < 0) { //bb_perror_msg("poll"); - done in safe_poll return EXIT_FAILURE; } if (n == 0) { // timed out? VDBG("state:%d\n", state); switch (state) { case PROBE: // No conflicting ARP packets were seen: // we can progress through the states if (nsent < PROBE_NUM) { nsent++; VDBG("probe/%u %s@%s\n", nsent, argv_intf, nip_to_a(chosen_nip)); timeout_ms = PROBE_MIN * 1000; timeout_ms += random_delay_ms(PROBE_MAX - PROBE_MIN); send_arp_request(0, &null_ethaddr, chosen_nip); continue; } // Switch to announce state nsent = 0; state = ANNOUNCE; goto send_announce; case ANNOUNCE: // No conflicting ARP packets were seen: // we can progress through the states if (nsent < ANNOUNCE_NUM) { send_announce: nsent++; VDBG("announce/%u %s@%s\n", nsent, argv_intf, nip_to_a(chosen_nip)); timeout_ms = ANNOUNCE_INTERVAL * 1000; send_arp_request(chosen_nip, &G.our_ethaddr, chosen_nip); continue; } // Switch to monitor state // FIXME update filters run(argv, "config", chosen_nip); // NOTE: all other exit paths should deconfig... if (QUIT) return EXIT_SUCCESS; // fall through: switch to MONITOR default: // case DEFEND: // case MONITOR: (shouldn't happen, MONITOR timeout is infinite) // Defend period ended with no ARP replies - we won timeout_ms = -1; // never timeout in monitor state state = MONITOR; continue; } } // Packet arrived, or link went down. // We need to adjust the timeout in case we didn't receive // a conflicting packet. if (timeout_ms > 0) { unsigned diff = deadline_us - MONOTONIC_US(); if ((int)(diff) < 0) { // Current time is greater than the expected timeout time. diff = 0; } VDBG("adjusting timeout\n"); timeout_ms = (diff / 1000) | 1; // never 0 } if ((fds[0].revents & POLLIN) == 0) { if (fds[0].revents & POLLERR) { // FIXME: links routinely go down; // this shouldn't necessarily exit. bb_error_msg("iface %s is down", argv_intf); if (state >= MONITOR) { // Only if we are in MONITOR or DEFEND run(argv, "deconfig", chosen_nip); } return EXIT_FAILURE; } continue; } // Read ARP packet if (safe_read(sock_fd, &p, sizeof(p)) < 0) { bb_perror_msg_and_die(bb_msg_read_error); } if (p.eth.ether_type != htons(ETHERTYPE_ARP)) continue; if (p.arp.arp_op != htons(ARPOP_REQUEST) && p.arp.arp_op != htons(ARPOP_REPLY) ) { continue; } #ifdef DEBUG { struct ether_addr *sha = (struct ether_addr *) p.arp.arp_sha; struct ether_addr *tha = (struct ether_addr *) p.arp.arp_tha; struct in_addr *spa = (struct in_addr *) p.arp.arp_spa; struct in_addr *tpa = (struct in_addr *) p.arp.arp_tpa; VDBG("source=%s %s\n", ether_ntoa(sha), inet_ntoa(*spa)); VDBG("target=%s %s\n", ether_ntoa(tha), inet_ntoa(*tpa)); } #endif ip_conflict = 0; if (memcmp(&p.arp.arp_sha, &G.our_ethaddr, ETH_ALEN) != 0) { if (memcmp(p.arp.arp_spa, &chosen_nip, 4) == 0) { // A probe or reply with source_ip == chosen ip ip_conflict = 1; } if (p.arp.arp_op == htons(ARPOP_REQUEST) && memcmp(p.arp.arp_spa, &const_int_0, 4) == 0 && memcmp(p.arp.arp_tpa, &chosen_nip, 4) == 0 ) { // A probe with source_ip == 0.0.0.0, target_ip == chosen ip: // another host trying to claim this ip! ip_conflict |= 2; } } VDBG("state:%d ip_conflict:%d\n", state, ip_conflict); if (!ip_conflict) continue; // Either src or target IP conflict exists if (state <= ANNOUNCE) { // PROBE or ANNOUNCE conflicts++; timeout_ms = PROBE_MIN * 1000 + CONFLICT_MULTIPLIER * random_delay_ms(conflicts); goto new_nip_and_PROBE; } // MONITOR or DEFEND: only src IP conflict is a problem if (ip_conflict & 1) { if (state == MONITOR) { // Src IP conflict, defend with a single ARP probe VDBG("monitor conflict - defending\n"); timeout_ms = DEFEND_INTERVAL * 1000; state = DEFEND; send_arp_request(chosen_nip, &G.our_ethaddr, chosen_nip); continue; } // state == DEFEND // Another src IP conflict, start over VDBG("defend conflict - starting over\n"); run(argv, "deconfig", chosen_nip); conflicts = 0; timeout_ms = 0; goto new_nip_and_PROBE; } // Note: if we only have a target IP conflict here (ip_conflict & 2), // IOW: if we just saw this sort of ARP packet: // aa:bb:cc:dd:ee:ff > xx:xx:xx:xx:xx:xx arp who-has <chosen_nip> tell 0.0.0.0 // we expect _kernel_ to respond to that, because <chosen_nip> // is (expected to be) configured on this iface. } // while (1) #undef argv_intf }
int nameif_main(int argc UNUSED_PARAM, char **argv) { ethtable_t *clist = NULL; const char *fname = "/etc/mactab"; int ctl_sk; ethtable_t *ch; parser_t *parser; char *token[2]; if (1 & getopt32(argv, "sc:", &fname)) { openlog(applet_name, 0, LOG_LOCAL0); /* Why not just "="? I assume logging to stderr * can't hurt. 2>/dev/null if you don't like it: */ logmode |= LOGMODE_SYSLOG; } argv += optind; if (argv[0]) { do { if (!argv[1]) bb_show_usage(); prepend_new_eth_table(&clist, argv[0], argv[1]); argv += 2; } while (*argv); } else { parser = config_open(fname); while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL)) prepend_new_eth_table(&clist, token[0], token[1]); config_close(parser); } ctl_sk = xsocket(PF_INET, SOCK_DGRAM, 0); parser = config_open2("/proc/net/dev", xfopen_for_read); while (clist && config_read(parser, token, 2, 2, "\0: \t", PARSE_NORMAL)) { struct ifreq ifr; #if ENABLE_FEATURE_NAMEIF_EXTENDED struct ethtool_drvinfo drvinfo; struct ethtool_cmd eth_settings; #endif if (parser->lineno <= 2) continue; /* Skip the first two lines */ /* Find the current interface name and copy it to ifr.ifr_name */ memset(&ifr, 0, sizeof(struct ifreq)); strncpy_IFNAMSIZ(ifr.ifr_name, token[0]); #if ENABLE_FEATURE_NAMEIF_EXTENDED /* Check for phy address */ memset(ð_settings, 0, sizeof(eth_settings)); eth_settings.cmd = ETHTOOL_GSET; ifr.ifr_data = (caddr_t) ð_settings; ioctl(ctl_sk, SIOCETHTOOL, &ifr); /* Check for driver etc. */ memset(&drvinfo, 0, sizeof(drvinfo)); drvinfo.cmd = ETHTOOL_GDRVINFO; ifr.ifr_data = (caddr_t) &drvinfo; /* Get driver and businfo first, so we have it in drvinfo */ ioctl(ctl_sk, SIOCETHTOOL, &ifr); #endif ioctl(ctl_sk, SIOCGIFHWADDR, &ifr); /* Search the list for a matching device */ for (ch = clist; ch; ch = ch->next) { #if ENABLE_FEATURE_NAMEIF_EXTENDED if (ch->bus_info && strcmp(ch->bus_info, drvinfo.bus_info) != 0) continue; if (ch->driver && strcmp(ch->driver, drvinfo.driver) != 0) continue; if (ch->phy_address != -1 && ch->phy_address != eth_settings.phy_address) continue; #endif if (ch->mac && memcmp(ch->mac, ifr.ifr_hwaddr.sa_data, ETH_ALEN) != 0) continue; /* if we came here, all selectors have matched */ break; } /* Nothing found for current interface */ if (!ch) continue; if (strcmp(ifr.ifr_name, ch->ifname) != 0) { strcpy(ifr.ifr_newname, ch->ifname); ioctl_or_perror_and_die(ctl_sk, SIOCSIFNAME, &ifr, "can't change ifname %s to %s", ifr.ifr_name, ch->ifname); } /* Remove list entry of renamed interface */ if (ch->prev != NULL) ch->prev->next = ch->next; else clist = ch->next; if (ch->next != NULL) ch->next->prev = ch->prev; if (ENABLE_FEATURE_CLEAN_UP) delete_eth_table(ch); } if (ENABLE_FEATURE_CLEAN_UP) { for (ch = clist; ch; ch = ch->next) delete_eth_table(ch); config_close(parser); }; return 0; }
int zcip_main(int argc UNUSED_PARAM, char **argv) { int state; char *r_opt; unsigned opts; // ugly trick, but I want these zeroed in one go struct { const struct in_addr null_ip; const struct ether_addr null_addr; struct in_addr ip; struct ifreq ifr; int timeout_ms; /* must be signed */ unsigned conflicts; unsigned nprobes; unsigned nclaims; int ready; } L; #define null_ip (L.null_ip ) #define null_addr (L.null_addr ) #define ip (L.ip ) #define ifr (L.ifr ) #define timeout_ms (L.timeout_ms) #define conflicts (L.conflicts ) #define nprobes (L.nprobes ) #define nclaims (L.nclaims ) #define ready (L.ready ) memset(&L, 0, sizeof(L)); INIT_G(); #define FOREGROUND (opts & 1) #define QUIT (opts & 2) // parse commandline: prog [options] ifname script // exactly 2 args; -v accumulates and implies -f opt_complementary = "=2:vv:vf"; opts = getopt32(argv, "fqr:p:v", &r_opt, &pidfile, &verbose); #if !BB_MMU // on NOMMU reexec early (or else we will rerun things twice) if (!FOREGROUND) bb_daemonize_or_rexec(0 /*was: DAEMON_CHDIR_ROOT*/, argv); #endif // open an ARP socket // (need to do it before openlog to prevent openlog from taking // fd 3 (sock_fd==3)) xmove_fd(xsocket(AF_PACKET, SOCK_PACKET, htons(ETH_P_ARP)), sock_fd); if (!FOREGROUND) { // do it before all bb_xx_msg calls openlog(applet_name, 0, LOG_DAEMON); logmode |= LOGMODE_SYSLOG; } if (opts & 4) { // -r n.n.n.n if (inet_aton(r_opt, &ip) == 0 || (ntohl(ip.s_addr) & IN_CLASSB_NET) != LINKLOCAL_ADDR ) { bb_error_msg_and_die("invalid link address"); } } argv += optind - 1; /* Now: argv[0]:junk argv[1]:intf argv[2]:script argv[3]:NULL */ /* We need to make space for script argument: */ argv[0] = argv[1]; argv[1] = argv[2]; /* Now: argv[0]:intf argv[1]:script argv[2]:junk argv[3]:NULL */ #define argv_intf (argv[0]) xsetenv("interface", argv_intf); // initialize the interface (modprobe, ifup, etc) if (run(argv, "init", NULL)) return EXIT_FAILURE; // initialize saddr // saddr is: { u16 sa_family; u8 sa_data[14]; } //memset(&saddr, 0, sizeof(saddr)); //TODO: are we leaving sa_family == 0 (AF_UNSPEC)?! safe_strncpy(saddr.sa_data, argv_intf, sizeof(saddr.sa_data)); // bind to the interface's ARP socket xbind(sock_fd, &saddr, sizeof(saddr)); // get the interface's ethernet address //memset(&ifr, 0, sizeof(ifr)); strncpy_IFNAMSIZ(ifr.ifr_name, argv_intf); xioctl(sock_fd, SIOCGIFHWADDR, &ifr); memcpy(ð_addr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN); // start with some stable ip address, either a function of // the hardware address or else the last address we used. // we are taking low-order four bytes, as top-order ones // aren't random enough. // NOTE: the sequence of addresses we try changes only // depending on when we detect conflicts. { uint32_t t; move_from_unaligned32(t, ((char *)ð_addr + 2)); srand(t); } if (ip.s_addr == 0) ip.s_addr = pick(); // FIXME cases to handle: // - zcip already running! // - link already has local address... just defend/update // daemonize now; don't delay system startup if (!FOREGROUND) { #if BB_MMU bb_daemonize(0 /*was: DAEMON_CHDIR_ROOT*/); #endif if (verbose) bb_info_msg("start, interface %s", argv_intf); } write_pidfile(pidfile); bb_signals(BB_FATAL_SIGS, cleanup); // run the dynamic address negotiation protocol, // restarting after address conflicts: // - start with some address we want to try // - short random delay // - arp probes to see if another host uses it // - arp announcements that we're claiming it // - use it // - defend it, within limits // exit if: // - address is successfully obtained and -q was given: // run "<script> config", then exit with exitcode 0 // - poll error (when does this happen?) // - read error (when does this happen?) // - sendto error (in arp()) (when does this happen?) // - revents & POLLERR (link down). run "<script> deconfig" first state = PROBE; while (1) { struct pollfd fds[1]; unsigned deadline_us; struct arp_packet p; int source_ip_conflict; int target_ip_conflict; fds[0].fd = sock_fd; fds[0].events = POLLIN; fds[0].revents = 0; // poll, being ready to adjust current timeout if (!timeout_ms) { timeout_ms = random_delay_ms(PROBE_WAIT); // FIXME setsockopt(sock_fd, SO_ATTACH_FILTER, ...) to // make the kernel filter out all packets except // ones we'd care about. } // set deadline_us to the point in time when we timeout deadline_us = MONOTONIC_US() + timeout_ms * 1000; VDBG("...wait %d %s nprobes=%u, nclaims=%u\n", timeout_ms, argv_intf, nprobes, nclaims); switch (safe_poll(fds, 1, timeout_ms)) { default: //bb_perror_msg("poll"); - done in safe_poll cleanup(EXIT_FAILURE); // timeout case 0: VDBG("state = %d\n", state); switch (state) { case PROBE: // timeouts in the PROBE state mean no conflicting ARP packets // have been received, so we can progress through the states if (nprobes < PROBE_NUM) { nprobes++; VDBG("probe/%u %s@%s\n", nprobes, argv_intf, inet_ntoa(ip)); arp(/* ARPOP_REQUEST, */ /* ð_addr, */ null_ip, &null_addr, ip); timeout_ms = PROBE_MIN * 1000; timeout_ms += random_delay_ms(PROBE_MAX - PROBE_MIN); } else { // Switch to announce state. state = ANNOUNCE; nclaims = 0; VDBG("announce/%u %s@%s\n", nclaims, argv_intf, inet_ntoa(ip)); arp(/* ARPOP_REQUEST, */ /* ð_addr, */ ip, ð_addr, ip); timeout_ms = ANNOUNCE_INTERVAL * 1000; } break; case RATE_LIMIT_PROBE: // timeouts in the RATE_LIMIT_PROBE state mean no conflicting ARP packets // have been received, so we can move immediately to the announce state state = ANNOUNCE; nclaims = 0; VDBG("announce/%u %s@%s\n", nclaims, argv_intf, inet_ntoa(ip)); arp(/* ARPOP_REQUEST, */ /* ð_addr, */ ip, ð_addr, ip); timeout_ms = ANNOUNCE_INTERVAL * 1000; break; case ANNOUNCE: // timeouts in the ANNOUNCE state mean no conflicting ARP packets // have been received, so we can progress through the states if (nclaims < ANNOUNCE_NUM) { nclaims++; VDBG("announce/%u %s@%s\n", nclaims, argv_intf, inet_ntoa(ip)); arp(/* ARPOP_REQUEST, */ /* ð_addr, */ ip, ð_addr, ip); timeout_ms = ANNOUNCE_INTERVAL * 1000; } else { // Switch to monitor state. state = MONITOR; // link is ok to use earlier // FIXME update filters run(argv, "config", &ip); ready = 1; conflicts = 0; timeout_ms = -1; // Never timeout in the monitor state. // NOTE: all other exit paths // should deconfig ... if (QUIT) cleanup(EXIT_SUCCESS); } break; case DEFEND: // We won! No ARP replies, so just go back to monitor. state = MONITOR; timeout_ms = -1; conflicts = 0; break; default: // Invalid, should never happen. Restart the whole protocol. state = PROBE; ip.s_addr = pick(); timeout_ms = 0; nprobes = 0; nclaims = 0; break; } // switch (state) break; // case 0 (timeout) // packets arriving, or link went down case 1: // We need to adjust the timeout in case we didn't receive // a conflicting packet. if (timeout_ms > 0) { unsigned diff = deadline_us - MONOTONIC_US(); if ((int)(diff) < 0) { // Current time is greater than the expected timeout time. // Should never happen. VDBG("missed an expected timeout\n"); timeout_ms = 0; } else { VDBG("adjusting timeout\n"); timeout_ms = (diff / 1000) | 1; /* never 0 */ } } if ((fds[0].revents & POLLIN) == 0) { if (fds[0].revents & POLLERR) { // FIXME: links routinely go down; // this shouldn't necessarily exit. bb_error_msg("iface %s is down", argv_intf); if (ready) { run(argv, "deconfig", &ip); } cleanup(EXIT_FAILURE); } continue; } // read ARP packet if (safe_read(sock_fd, &p, sizeof(p)) < 0) { bb_perror_msg(bb_msg_read_error); cleanup(EXIT_FAILURE); } if (p.eth.ether_type != htons(ETHERTYPE_ARP)) continue; #ifdef DEBUG { struct ether_addr *sha = (struct ether_addr *) p.arp.arp_sha; struct ether_addr *tha = (struct ether_addr *) p.arp.arp_tha; struct in_addr *spa = (struct in_addr *) p.arp.arp_spa; struct in_addr *tpa = (struct in_addr *) p.arp.arp_tpa; VDBG("%s recv arp type=%d, op=%d,\n", argv_intf, ntohs(p.eth.ether_type), ntohs(p.arp.arp_op)); VDBG("\tsource=%s %s\n", ether_ntoa(sha), inet_ntoa(*spa)); VDBG("\ttarget=%s %s\n", ether_ntoa(tha), inet_ntoa(*tpa)); } #endif if (p.arp.arp_op != htons(ARPOP_REQUEST) && p.arp.arp_op != htons(ARPOP_REPLY)) continue; source_ip_conflict = 0; target_ip_conflict = 0; if (memcmp(p.arp.arp_spa, &ip.s_addr, sizeof(struct in_addr)) == 0 && memcmp(&p.arp.arp_sha, ð_addr, ETH_ALEN) != 0 ) { source_ip_conflict = 1; } if (p.arp.arp_op == htons(ARPOP_REQUEST) && memcmp(p.arp.arp_tpa, &ip.s_addr, sizeof(struct in_addr)) == 0 && memcmp(&p.arp.arp_tha, ð_addr, ETH_ALEN) != 0 ) { target_ip_conflict = 1; } VDBG("state = %d, source ip conflict = %d, target ip conflict = %d\n", state, source_ip_conflict, target_ip_conflict); switch (state) { case PROBE: case ANNOUNCE: // When probing or announcing, check for source IP conflicts // and other hosts doing ARP probes (target IP conflicts). if (source_ip_conflict || target_ip_conflict) { conflicts++; if (conflicts >= MAX_CONFLICTS) { VDBG("%s ratelimit\n", argv_intf); timeout_ms = RATE_LIMIT_INTERVAL * 1000; state = RATE_LIMIT_PROBE; } // restart the whole protocol ip.s_addr = pick(); timeout_ms = 0; nprobes = 0; nclaims = 0; } break; case MONITOR: // If a conflict, we try to defend with a single ARP probe. if (source_ip_conflict) { VDBG("monitor conflict -- defending\n"); state = DEFEND; timeout_ms = DEFEND_INTERVAL * 1000; arp(/* ARPOP_REQUEST, */ /* ð_addr, */ ip, ð_addr, ip); } break; case DEFEND: // Well, we tried. Start over (on conflict). if (source_ip_conflict) { state = PROBE; VDBG("defend conflict -- starting over\n"); ready = 0; run(argv, "deconfig", &ip); // restart the whole protocol ip.s_addr = pick(); timeout_ms = 0; nprobes = 0; nclaims = 0; } break; default: // Invalid, should never happen. Restart the whole protocol. VDBG("invalid state -- starting over\n"); state = PROBE; ip.s_addr = pick(); timeout_ms = 0; nprobes = 0; nclaims = 0; break; } // switch state break; // case 1 (packets arriving) } // switch poll } // while (1) #undef argv_intf }
int ether_wake_main(int argc UNUSED_PARAM, char **argv) { const char *ifname = "eth0"; char *pass; unsigned flags; unsigned char wol_passwd[6]; int wol_passwd_sz = 0; int s; /* Raw socket */ int pktsize; unsigned char outpack[1000]; struct ether_addr eaddr; struct whereto_t whereto; /* who to wake up */ /* handle misc user options */ opt_complementary = "=1"; flags = getopt32(argv, "bi:p:", &ifname, &pass); if (flags & 4) /* -p */ wol_passwd_sz = get_wol_pw(pass, wol_passwd); flags &= 1; /* we further interested only in -b [bcast] flag */ /* create the raw socket */ s = make_socket(); /* now that we have a raw socket we can drop root */ /* xsetuid(getuid()); - but save on code size... */ /* look up the dest mac address */ get_dest_addr(argv[optind], &eaddr); /* fill out the header of the packet */ pktsize = get_fill(outpack, &eaddr, flags /* & 1 OPT_BROADCAST */); bb_debug_dump_packet(outpack, pktsize); /* Fill in the source address, if possible. */ #ifdef __linux__ { struct ifreq if_hwaddr; strncpy_IFNAMSIZ(if_hwaddr.ifr_name, ifname); ioctl_or_perror_and_die(s, SIOCGIFHWADDR, &if_hwaddr, "SIOCGIFHWADDR on %s failed", ifname); memcpy(outpack+6, if_hwaddr.ifr_hwaddr.sa_data, 6); # ifdef DEBUG { unsigned char *hwaddr = if_hwaddr.ifr_hwaddr.sa_data; printf("The hardware address (SIOCGIFHWADDR) of %s is type %d " "%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x\n\n", ifname, if_hwaddr.ifr_hwaddr.sa_family, hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5]); } # endif } #endif /* __linux__ */ bb_debug_dump_packet(outpack, pktsize); /* append the password if specified */ if (wol_passwd_sz > 0) { memcpy(outpack+pktsize, wol_passwd, wol_passwd_sz); pktsize += wol_passwd_sz; } bb_debug_dump_packet(outpack, pktsize); /* This is necessary for broadcasts to work */ if (flags /* & 1 OPT_BROADCAST */) { if (setsockopt_broadcast(s) != 0) bb_perror_msg("SO_BROADCAST"); } #if defined(PF_PACKET) { struct ifreq ifr; strncpy_IFNAMSIZ(ifr.ifr_name, ifname); xioctl(s, SIOCGIFINDEX, &ifr); memset(&whereto, 0, sizeof(whereto)); whereto.sll_family = AF_PACKET; whereto.sll_ifindex = ifr.ifr_ifindex; /* The manual page incorrectly claims the address must be filled. We do so because the code may change to match the docs. */ whereto.sll_halen = ETH_ALEN; memcpy(whereto.sll_addr, outpack, ETH_ALEN); } #else whereto.sa_family = 0; strcpy(whereto.sa_data, ifname); #endif xsendto(s, outpack, pktsize, (struct sockaddr *)&whereto, sizeof(whereto)); if (ENABLE_FEATURE_CLEAN_UP) close(s); return EXIT_SUCCESS; }
static void set_ifreq_to_ifname(struct ifreq *ifreq) { memset(ifreq, 0, sizeof(struct ifreq)); strncpy_IFNAMSIZ(ifreq->ifr_name, G.iface); }
int arping_main(int argc UNUSED_PARAM, char **argv) { const char *device = "eth0"; char *source = NULL; char *target; unsigned char *packet; char *err_str; INIT_G(); sock_fd = xsocket(AF_PACKET, SOCK_DGRAM, 0); // Drop suid root privileges // Need to remove SUID_NEVER from applets.h for this to work //xsetuid(getuid()); err_str = xasprintf("interface %s %%s", device); { unsigned opt; char *str_timeout; /* Dad also sets quit_on_reply. * Advert also sets unsolicited. */ opt_complementary = "=1:Df:AU:c+"; opt = getopt32(argv, "DUAqfbc:w:I:s:", &count, &str_timeout, &device, &source); if (opt & 0x80) /* -w: timeout */ timeout_us = xatou_range(str_timeout, 0, INT_MAX/2000000) * 1000000 + 500000; //if (opt & 0x200) /* -s: source */ option_mask32 &= 0x3f; /* set respective flags */ } target = argv[optind]; xfunc_error_retval = 2; { struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy_IFNAMSIZ(ifr.ifr_name, device); /* We use ifr.ifr_name in error msg so that problem * with truncated name will be visible */ ioctl_or_perror_and_die(sock_fd, SIOCGIFINDEX, &ifr, err_str, "not found"); me.sll_ifindex = ifr.ifr_ifindex; xioctl(sock_fd, SIOCGIFFLAGS, (char *) &ifr); if (!(ifr.ifr_flags & IFF_UP)) { bb_error_msg_and_die(err_str, "is down"); } if (ifr.ifr_flags & (IFF_NOARP | IFF_LOOPBACK)) { bb_error_msg(err_str, "is not ARPable"); return (option_mask32 & DAD ? 0 : 2); } } /* if (!inet_aton(target, &dst)) - not needed */ { len_and_sockaddr *lsa; lsa = xhost_and_af2sockaddr(target, 0, AF_INET); dst = lsa->u.sin.sin_addr; if (ENABLE_FEATURE_CLEAN_UP) free(lsa); } if (source && !inet_aton(source, &src)) { bb_error_msg_and_die("invalid source address %s", source); } if ((option_mask32 & (DAD|UNSOLICITED)) == UNSOLICITED && src.s_addr == 0) src = dst; if (!(option_mask32 & DAD) || src.s_addr) { struct sockaddr_in saddr; int probe_fd = xsocket(AF_INET, SOCK_DGRAM, 0); setsockopt_bindtodevice(probe_fd, device); memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; if (src.s_addr) { /* Check that this is indeed our IP */ saddr.sin_addr = src; xbind(probe_fd, (struct sockaddr *) &saddr, sizeof(saddr)); } else { /* !(option_mask32 & DAD) case */ /* Find IP address on this iface */ socklen_t alen = sizeof(saddr); saddr.sin_port = htons(1025); saddr.sin_addr = dst; if (setsockopt(probe_fd, SOL_SOCKET, SO_DONTROUTE, &const_int_1, sizeof(const_int_1)) == -1) bb_perror_msg("setsockopt(SO_DONTROUTE)"); xconnect(probe_fd, (struct sockaddr *) &saddr, sizeof(saddr)); if (getsockname(probe_fd, (struct sockaddr *) &saddr, &alen) == -1) { bb_perror_msg_and_die("getsockname"); } if (saddr.sin_family != AF_INET) bb_error_msg_and_die("no IP address configured"); src = saddr.sin_addr; } close(probe_fd); } me.sll_family = AF_PACKET; //me.sll_ifindex = ifindex; - done before me.sll_protocol = htons(ETH_P_ARP); xbind(sock_fd, (struct sockaddr *) &me, sizeof(me)); { socklen_t alen = sizeof(me); if (getsockname(sock_fd, (struct sockaddr *) &me, &alen) == -1) { bb_perror_msg_and_die("getsockname"); } } if (me.sll_halen == 0) { bb_error_msg(err_str, "is not ARPable (no ll address)"); return (option_mask32 & DAD ? 0 : 2); } he = me; memset(he.sll_addr, -1, he.sll_halen); if (!(option_mask32 & QUIET)) { /* inet_ntoa uses static storage, can't use in same printf */ printf("ARPING to %s", inet_ntoa(dst)); printf(" from %s via %s\n", inet_ntoa(src), device); } signal_SA_RESTART_empty_mask(SIGINT, (void (*)(int))finish); signal_SA_RESTART_empty_mask(SIGALRM, (void (*)(int))catcher); catcher(); packet = xmalloc(4096); while (1) { sigset_t sset, osset; struct sockaddr_ll from; socklen_t alen = sizeof(from); int cc; cc = recvfrom(sock_fd, packet, 4096, 0, (struct sockaddr *) &from, &alen); if (cc < 0) { bb_perror_msg("recvfrom"); continue; } sigemptyset(&sset); sigaddset(&sset, SIGALRM); sigaddset(&sset, SIGINT); sigprocmask(SIG_BLOCK, &sset, &osset); recv_pack(packet, cc, &from); sigprocmask(SIG_SETMASK, &osset, NULL); } }
/* Dies on error */ static void parse_args(char **argv, int cmd, struct ip_tunnel_parm *p) { static const char keywords[] ALIGN1 = "mode\0""ipip\0""ip/ip\0""gre\0""gre/ip\0""sit\0""ipv6/ip\0" "key\0""ikey\0""okey\0""seq\0""iseq\0""oseq\0" "csum\0""icsum\0""ocsum\0""nopmtudisc\0""pmtudisc\0" "remote\0""any\0""local\0""dev\0" "ttl\0""inherit\0""tos\0""dsfield\0" "name\0"; enum { ARG_mode, ARG_ipip, ARG_ip_ip, ARG_gre, ARG_gre_ip, ARG_sit, ARG_ip6_ip, ARG_key, ARG_ikey, ARG_okey, ARG_seq, ARG_iseq, ARG_oseq, ARG_csum, ARG_icsum, ARG_ocsum, ARG_nopmtudisc, ARG_pmtudisc, ARG_remote, ARG_any, ARG_local, ARG_dev, ARG_ttl, ARG_inherit, ARG_tos, ARG_dsfield, ARG_name }; int count = 0; char medium[IFNAMSIZ]; int key; memset(p, 0, sizeof(*p)); medium[0] = '\0'; p->iph.version = 4; p->iph.ihl = 5; #ifndef IP_DF #define IP_DF 0x4000 /* Flag: "Don't Fragment" */ #endif p->iph.frag_off = htons(IP_DF); while (*argv) { key = index_in_strings(keywords, *argv); if (key == ARG_mode) { NEXT_ARG(); key = index_in_strings(keywords, *argv); if (key == ARG_ipip || key == ARG_ip_ip ) { if (p->iph.protocol && p->iph.protocol != IPPROTO_IPIP) { bb_error_msg_and_die("%s tunnel mode", "you managed to ask for more than one"); } p->iph.protocol = IPPROTO_IPIP; } else if (key == ARG_gre || key == ARG_gre_ip ) { if (p->iph.protocol && p->iph.protocol != IPPROTO_GRE) { bb_error_msg_and_die("%s tunnel mode", "you managed to ask for more than one"); } p->iph.protocol = IPPROTO_GRE; } else if (key == ARG_sit || key == ARG_ip6_ip ) { if (p->iph.protocol && p->iph.protocol != IPPROTO_IPV6) { bb_error_msg_and_die("%s tunnel mode", "you managed to ask for more than one"); } p->iph.protocol = IPPROTO_IPV6; } else { bb_error_msg_and_die("%s tunnel mode", "can't guess"); } } else if (key == ARG_key) { unsigned uval; NEXT_ARG(); p->i_flags |= GRE_KEY; p->o_flags |= GRE_KEY; if (strchr(*argv, '.')) p->i_key = p->o_key = get_addr32(*argv); else { uval = get_unsigned(*argv, "key"); p->i_key = p->o_key = htonl(uval); } } else if (key == ARG_ikey) { unsigned uval; NEXT_ARG(); p->i_flags |= GRE_KEY; if (strchr(*argv, '.')) p->o_key = get_addr32(*argv); else { uval = get_unsigned(*argv, "ikey"); p->i_key = htonl(uval); } } else if (key == ARG_okey) { unsigned uval; NEXT_ARG(); p->o_flags |= GRE_KEY; if (strchr(*argv, '.')) p->o_key = get_addr32(*argv); else { uval = get_unsigned(*argv, "okey"); p->o_key = htonl(uval); } } else if (key == ARG_seq) { p->i_flags |= GRE_SEQ; p->o_flags |= GRE_SEQ; } else if (key == ARG_iseq) { p->i_flags |= GRE_SEQ; } else if (key == ARG_oseq) { p->o_flags |= GRE_SEQ; } else if (key == ARG_csum) { p->i_flags |= GRE_CSUM; p->o_flags |= GRE_CSUM; } else if (key == ARG_icsum) { p->i_flags |= GRE_CSUM; } else if (key == ARG_ocsum) { p->o_flags |= GRE_CSUM; } else if (key == ARG_nopmtudisc) { p->iph.frag_off = 0; } else if (key == ARG_pmtudisc) { p->iph.frag_off = htons(IP_DF); } else if (key == ARG_remote) { NEXT_ARG(); key = index_in_strings(keywords, *argv); if (key != ARG_any) p->iph.daddr = get_addr32(*argv); } else if (key == ARG_local) { NEXT_ARG(); key = index_in_strings(keywords, *argv); if (key != ARG_any) p->iph.saddr = get_addr32(*argv); } else if (key == ARG_dev) { NEXT_ARG(); strncpy_IFNAMSIZ(medium, *argv); } else if (key == ARG_ttl) { unsigned uval; NEXT_ARG(); key = index_in_strings(keywords, *argv); if (key != ARG_inherit) { uval = get_unsigned(*argv, "TTL"); if (uval > 255) invarg(*argv, "TTL must be <=255"); p->iph.ttl = uval; } } else if (key == ARG_tos || key == ARG_dsfield ) { uint32_t uval; NEXT_ARG(); key = index_in_strings(keywords, *argv); if (key != ARG_inherit) { if (rtnl_dsfield_a2n(&uval, *argv)) invarg(*argv, "TOS"); p->iph.tos = uval; } else p->iph.tos = 1; } else { if (key == ARG_name) { NEXT_ARG(); } if (p->name[0]) duparg2("name", *argv); strncpy_IFNAMSIZ(p->name, *argv); if (cmd == SIOCCHGTUNNEL && count == 0) { struct ip_tunnel_parm old_p; memset(&old_p, 0, sizeof(old_p)); if (do_get_ioctl(*argv, &old_p)) exit(EXIT_FAILURE); *p = old_p; } } count++; argv++; } if (p->iph.protocol == 0) { if (memcmp(p->name, "gre", 3) == 0) p->iph.protocol = IPPROTO_GRE; else if (memcmp(p->name, "ipip", 4) == 0) p->iph.protocol = IPPROTO_IPIP; else if (memcmp(p->name, "sit", 3) == 0) p->iph.protocol = IPPROTO_IPV6; } if (p->iph.protocol == IPPROTO_IPIP || p->iph.protocol == IPPROTO_IPV6) { if ((p->i_flags & GRE_KEY) || (p->o_flags & GRE_KEY)) { bb_error_msg_and_die("keys are not allowed with ipip and sit"); } } if (medium[0]) { p->link = do_ioctl_get_ifindex(medium); } if (p->i_key == 0 && IN_MULTICAST(ntohl(p->iph.daddr))) { p->i_key = p->iph.daddr; p->i_flags |= GRE_KEY; } if (p->o_key == 0 && IN_MULTICAST(ntohl(p->iph.daddr))) { p->o_key = p->iph.daddr; p->o_flags |= GRE_KEY; } if (IN_MULTICAST(ntohl(p->iph.daddr)) && !p->iph.saddr) { bb_error_msg_and_die("broadcast tunnel requires a source address"); } }
int brctl_main(int argc UNUSED_PARAM, char **argv) { static const char keywords[] ALIGN1 = "addbr\0" "delbr\0" "addif\0" "delif\0" IF_FEATURE_BRCTL_FANCY( "stp\0" "setageing\0" "setfd\0" "sethello\0" "setmaxage\0" "setpathcost\0" "setportprio\0" "setbridgeprio\0" ) IF_FEATURE_BRCTL_SHOW("show\0"); enum { ARG_addbr = 0, ARG_delbr, ARG_addif, ARG_delif IF_FEATURE_BRCTL_FANCY(, ARG_stp, ARG_setageing, ARG_setfd, ARG_sethello, ARG_setmaxage, ARG_setpathcost, ARG_setportprio, ARG_setbridgeprio ) IF_FEATURE_BRCTL_SHOW(, ARG_show) }; int fd; smallint key; struct ifreq ifr; char *br, *brif; argv++; while (*argv) { #if ENABLE_FEATURE_BRCTL_FANCY int ifidx[MAX_PORTS]; unsigned long args[4]; ifr.ifr_data = (char *) &args; #endif key = index_in_strings(keywords, *argv); if (key == -1) /* no match found in keywords array, bail out. */ bb_error_msg_and_die(bb_msg_invalid_arg_to, *argv, applet_name); argv++; fd = xsocket(AF_INET, SOCK_STREAM, 0); #if ENABLE_FEATURE_BRCTL_SHOW if (key == ARG_show) { /* show */ char brname[IFNAMSIZ]; int bridx[MAX_PORTS]; int i, num; arm_ioctl(args, BRCTL_GET_BRIDGES, (unsigned long) bridx, MAX_PORTS); num = xioctl(fd, SIOCGIFBR, args); puts("bridge name\tbridge id\t\tSTP enabled\tinterfaces"); for (i = 0; i < num; i++) { char ifname[IFNAMSIZ]; int j, tabs; struct __bridge_info bi; unsigned char *x; if (!if_indextoname(bridx[i], brname)) bb_perror_msg_and_die("can't get bridge name for index %d", i); strncpy_IFNAMSIZ(ifr.ifr_name, brname); arm_ioctl(args, BRCTL_GET_BRIDGE_INFO, (unsigned long) &bi, 0); xioctl(fd, SIOCDEVPRIVATE, &ifr); printf("%s\t\t", brname); /* print bridge id */ x = (unsigned char *) &bi.bridge_id; for (j = 0; j < 8; j++) { printf("%02x", x[j]); if (j == 1) bb_putchar('.'); } printf(bi.stp_enabled ? "\tyes" : "\tno"); /* print interface list */ arm_ioctl(args, BRCTL_GET_PORT_LIST, (unsigned long) ifidx, MAX_PORTS); xioctl(fd, SIOCDEVPRIVATE, &ifr); tabs = 0; for (j = 0; j < MAX_PORTS; j++) { if (!ifidx[j]) continue; if (!if_indextoname(ifidx[j], ifname)) bb_perror_msg_and_die("can't get interface name for index %d", j); if (tabs) printf("\t\t\t\t\t"); else tabs = 1; printf("\t\t%s\n", ifname); } if (!tabs) /* bridge has no interfaces */ bb_putchar('\n'); } goto done; } #endif if (!*argv) /* all but 'show' need at least one argument */ bb_show_usage(); br = *argv++; if (key == ARG_addbr || key == ARG_delbr) { /* addbr or delbr */ ioctl_or_perror_and_die(fd, key == ARG_addbr ? SIOCBRADDBR : SIOCBRDELBR, br, "bridge %s", br); goto done; } if (!*argv) /* all but 'addbr/delbr' need at least two arguments */ bb_show_usage(); strncpy_IFNAMSIZ(ifr.ifr_name, br); if (key == ARG_addif || key == ARG_delif) { /* addif or delif */ brif = *argv; ifr.ifr_ifindex = if_nametoindex(brif); if (!ifr.ifr_ifindex) { bb_perror_msg_and_die("iface %s", brif); } ioctl_or_perror_and_die(fd, key == ARG_addif ? SIOCBRADDIF : SIOCBRDELIF, &ifr, "bridge %s", br); goto done_next_argv; } #if ENABLE_FEATURE_BRCTL_FANCY if (key == ARG_stp) { /* stp */ static const char no_yes[] ALIGN1 = "0\0" "off\0" "n\0" "no\0" /* 0 .. 3 */ "1\0" "on\0" "y\0" "yes\0"; /* 4 .. 7 */ int onoff = index_in_strings(no_yes, *argv); if (onoff < 0) bb_error_msg_and_die(bb_msg_invalid_arg_to, *argv, applet_name); onoff = (unsigned)onoff / 4; arm_ioctl(args, BRCTL_SET_BRIDGE_STP_STATE, onoff, 0); goto fire; } if ((unsigned)(key - ARG_setageing) < 4) { /* time related ops */ static const uint8_t ops[] ALIGN1 = { BRCTL_SET_AGEING_TIME, /* ARG_setageing */ BRCTL_SET_BRIDGE_FORWARD_DELAY, /* ARG_setfd */ BRCTL_SET_BRIDGE_HELLO_TIME, /* ARG_sethello */ BRCTL_SET_BRIDGE_MAX_AGE /* ARG_setmaxage */ }; arm_ioctl(args, ops[key - ARG_setageing], str_to_jiffies(*argv), 0); goto fire; } if (key == ARG_setpathcost || key == ARG_setportprio || key == ARG_setbridgeprio ) { static const uint8_t ops[] ALIGN1 = { BRCTL_SET_PATH_COST, /* ARG_setpathcost */ BRCTL_SET_PORT_PRIORITY, /* ARG_setportprio */ BRCTL_SET_BRIDGE_PRIORITY /* ARG_setbridgeprio */ }; int port = -1; unsigned arg1, arg2; if (key != ARG_setbridgeprio) { /* get portnum */ unsigned i; port = if_nametoindex(*argv++); if (!port) bb_error_msg_and_die(bb_msg_invalid_arg_to, *argv, "port"); memset(ifidx, 0, sizeof ifidx); arm_ioctl(args, BRCTL_GET_PORT_LIST, (unsigned long)ifidx, MAX_PORTS); xioctl(fd, SIOCDEVPRIVATE, &ifr); for (i = 0; i < MAX_PORTS; i++) { if (ifidx[i] == port) { port = i; break; } } } arg1 = port; arg2 = xatoi_positive(*argv); if (key == ARG_setbridgeprio) { arg1 = arg2; arg2 = 0; } arm_ioctl(args, ops[key - ARG_setpathcost], arg1, arg2); } fire: /* Execute the previously set command */ xioctl(fd, SIOCDEVPRIVATE, &ifr); #endif done_next_argv: argv++; done: close(fd); } return EXIT_SUCCESS; }
int tunctl_main(int argc UNUSED_PARAM, char **argv) { struct ifreq ifr; int fd; const char *opt_name = "tap%d"; const char *opt_device = "/dev/net/tun"; #if ENABLE_FEATURE_TUNCTL_UG const char *opt_user, *opt_group; long user = -1, group = -1; #endif unsigned opts; enum { OPT_f = 1 << 0, // control device name (/dev/net/tun) OPT_t = 1 << 1, // create named interface OPT_d = 1 << 2, // delete named interface #if ENABLE_FEATURE_TUNCTL_UG OPT_u = 1 << 3, // set new interface owner OPT_g = 1 << 4, // set new interface group OPT_b = 1 << 5, // brief output #endif }; opt_complementary = "=0:t--d:d--t"; // no arguments; t ^ d opts = getopt32(argv, "f:t:d:" IF_FEATURE_TUNCTL_UG("u:g:b"), &opt_device, &opt_name, &opt_name IF_FEATURE_TUNCTL_UG(, &opt_user, &opt_group)); // select device memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TAP | IFF_NO_PI; strncpy_IFNAMSIZ(ifr.ifr_name, opt_name); // open device fd = xopen(opt_device, O_RDWR); IOCTL(fd, TUNSETIFF, (void *)&ifr); // delete? if (opts & OPT_d) { IOCTL(fd, TUNSETPERSIST, (void *)(uintptr_t)0); printf("Set '%s' nonpersistent\n", ifr.ifr_name); return EXIT_SUCCESS; } // create #if ENABLE_FEATURE_TUNCTL_UG if (opts & OPT_g) { group = xgroup2gid(opt_group); IOCTL(fd, TUNSETGROUP, (void *)(uintptr_t)group); } else user = geteuid(); if (opts & OPT_u) user = xuname2uid(opt_user); IOCTL(fd, TUNSETOWNER, (void *)(uintptr_t)user); #endif IOCTL(fd, TUNSETPERSIST, (void *)(uintptr_t)1); // show info #if ENABLE_FEATURE_TUNCTL_UG if (opts & OPT_b) { puts(ifr.ifr_name); } else { printf("Set '%s' %spersistent", ifr.ifr_name, ""); printf(" and owned by uid %ld", user); if (group != -1) printf(" gid %ld", group); bb_putchar('\n'); } #else puts(ifr.ifr_name); #endif return EXIT_SUCCESS; }