From 746e565c097ed311ebb65842ac8a6527535993a7 Mon Sep 17 00:00:00 2001 From: Rob Landley Date: Sun, 3 Jul 2016 16:05:12 -0500 Subject: Promote netsat, and move ifconfig, netcat, and rfkill to new toys/net directory. --- toys/net/README | 1 + toys/net/ifconfig.c | 517 +++++++++++++++++++++++++++++++++++++++++++++++++ toys/net/netcat.c | 230 ++++++++++++++++++++++ toys/net/netstat.c | 383 ++++++++++++++++++++++++++++++++++++ toys/net/rfkill.c | 102 ++++++++++ toys/other/ifconfig.c | 517 ------------------------------------------------- toys/other/netcat.c | 230 ---------------------- toys/other/rfkill.c | 102 ---------- toys/pending/netstat.c | 383 ------------------------------------ 9 files changed, 1233 insertions(+), 1232 deletions(-) create mode 100644 toys/net/README create mode 100644 toys/net/ifconfig.c create mode 100644 toys/net/netcat.c create mode 100644 toys/net/netstat.c create mode 100644 toys/net/rfkill.c delete mode 100644 toys/other/ifconfig.c delete mode 100644 toys/other/netcat.c delete mode 100644 toys/other/rfkill.c delete mode 100644 toys/pending/netstat.c (limited to 'toys') diff --git a/toys/net/README b/toys/net/README new file mode 100644 index 00000000..8708e4b5 --- /dev/null +++ b/toys/net/README @@ -0,0 +1 @@ +Networking diff --git a/toys/net/ifconfig.c b/toys/net/ifconfig.c new file mode 100644 index 00000000..1d2a41dc --- /dev/null +++ b/toys/net/ifconfig.c @@ -0,0 +1,517 @@ +/* ifconfig.c - Configure network interface. + * + * Copyright 2012 Ranjan Kumar + * Copyright 2012 Kyungwan Han + * Reviewed by Kyungsu Kim + * + * Not in SUSv4. + +USE_IFCONFIG(NEWTOY(ifconfig, "^?a", TOYFLAG_SBIN)) + +config IFCONFIG + bool "ifconfig" + default y + help + usage: ifconfig [-a] [INTERFACE [ACTION...]] + + Display or configure network interface. + + With no arguments, display active interfaces. First argument is interface + to operate on, one argument by itself displays that interface. + + -a Show all interfaces, not just active ones + + Additional arguments are actions to perform on the interface: + + ADDRESS[/NETMASK] - set IPv4 address (1.2.3.4/5) + default - unset ipv4 address + add|del ADDRESS[/PREFIXLEN] - add/remove IPv6 address (1111::8888/128) + up - enable interface + down - disable interface + + netmask|broadcast|pointopoint ADDRESS - set more IPv4 characteristics + hw ether|infiniband ADDRESS - set LAN hardware address (AA:BB:CC...) + txqueuelen LEN - number of buffered packets before output blocks + mtu LEN - size of outgoing packets (Maximum Transmission Unit) + + Flags you can set on an interface (or -remove by prefixing with -): + arp - don't use Address Resolution Protocol to map LAN routes + promisc - don't discard packets that aren't to this LAN hardware address + multicast - force interface into multicast mode if the driver doesn't + allmulti - promisc for multicast packets + + Obsolete fields included for historical purposes: + irq|io_addr|mem_start ADDR - micromanage obsolete hardware + outfill|keepalive INTEGER - SLIP analog dialup line quality monitoring + metric INTEGER - added to Linux 0.9.10 with comment "never used", still true +*/ + +#define FOR_ifconfig +#include "toys.h" + +#include +#include + +GLOBALS( + int sockfd; +) + +// Convert hostname to binary address for AF_INET or AF_INET6 +// return /prefix (or range max if none) +int get_addrinfo(char *host, sa_family_t af, void *addr) +{ + struct addrinfo hints, *result, *rp = 0; + int status, len; + char *from, *slash; + + memset(&hints, 0 , sizeof(struct addrinfo)); + hints.ai_family = af; + hints.ai_socktype = SOCK_STREAM; + + slash = strchr(host, '/'); + if (slash) *slash = 0; + + status = getaddrinfo(host, NULL, &hints, &result); + if (!status) + for (rp = result; rp; rp = rp->ai_next) + if (rp->ai_family == af) break; + if (!rp) error_exit("bad address '%s' : %s", host, gai_strerror(status)); + + // ai_addr isn't struct in_addr or in6_addr, it's struct sockaddr. Of course. + // You'd think ipv4 and ipv6 would have some basic compatibility, but no. + from = ((char *)rp->ai_addr) + 4; + if (af == AF_INET6) { + len = 16; + from += 4; // skip "flowinfo" field ipv6 puts before address + } else len = 4; + memcpy(addr, from, len); + freeaddrinfo(result); + + len = -1; + if (slash) len = atolx_range(slash+1, 0, (af == AF_INET) ? 32 : 128); + + return len; +} + +static void display_ifconfig(char *name, int always, unsigned long long val[]) +{ + struct ifreq ifre; + struct { + int type; + char *title; + } types[] = { + {ARPHRD_LOOPBACK, "Local Loopback"}, {ARPHRD_ETHER, "Ethernet"}, + {ARPHRD_PPP, "Point-to-Point Protocol"}, {ARPHRD_INFINIBAND, "InfiniBand"}, + {ARPHRD_SIT, "IPv6-in-IPv4"}, {-1, "UNSPEC"} + }; + int i; + char *pp; + FILE *fp; + short flags; + + xstrncpy(ifre.ifr_name, name, IFNAMSIZ); + if (ioctl(TT.sockfd, SIOCGIFFLAGS, &ifre)<0) perror_exit_raw(name); + flags = ifre.ifr_flags; + if (!always && !(flags & IFF_UP)) return; + + // query hardware type and hardware address + i = ioctl(TT.sockfd, SIOCGIFHWADDR, &ifre); + + for (i=0; i < (sizeof(types)/sizeof(*types))-1; i++) + if (ifre.ifr_hwaddr.sa_family == types[i].type) break; + + xprintf("%-9s Link encap:%s ", name, types[i].title); + if(i >= 0 && ifre.ifr_hwaddr.sa_family == ARPHRD_ETHER) { + xprintf("HWaddr "); + for (i=0; i<6; i++) xprintf(":%02x"+!i, ifre.ifr_hwaddr.sa_data[i]); + } + xputc('\n'); + + // If an address is assigned record that. + + ifre.ifr_addr.sa_family = AF_INET; + memset(&ifre.ifr_addr, 0, sizeof(ifre.ifr_addr)); + ioctl(TT.sockfd, SIOCGIFADDR, &ifre); + pp = (char *)&ifre.ifr_addr; + for (i = 0; isin_family == AF_INET) ? "inet" : + (si->sin_family == AF_INET6) ? "inet6" : "unspec"); + + for (i=0; i < sizeof(addr)/sizeof(*addr); i++) { + if (!addr[i].flag || (flags & addr[i].flag)) { + if (addr[i].ioctl && ioctl(TT.sockfd, addr[i].ioctl, &ifre)) + si->sin_family = 0; + xprintf(" %s:%s ", addr[i].name, + (si->sin_family == 0xFFFF || !si->sin_family) + ? "[NOT SET]" : inet_ntoa(si->sin_addr)); + } + } + + xputc('\n'); + } + + fp = fopen(pp = "/proc/net/if_inet6", "r"); + if (fp) { + char iface_name[IFNAMSIZ]; + int plen, iscope; + + while (fgets(toybuf, sizeof(toybuf), fp)) { + int nitems; + char ipv6_addr[40]; + + nitems = sscanf(toybuf, "%32s %*08x %02x %02x %*02x %15s\n", + ipv6_addr, &plen, &iscope, iface_name); + if (nitems<0 && feof(fp)) break; + if (nitems != 4) perror_exit("bad %s", pp); + + if (!strcmp(name, iface_name)) { + struct sockaddr_in6 s6; + char *ptr = ipv6_addr+sizeof(ipv6_addr)-1; + + // convert giant hex string into colon-spearated ipv6 address by + // inserting ':' every 4 characters. + for (i = 32; i; i--) + if ((*(ptr--) = ipv6_addr[i])) if (!(i&3)) *(ptr--) = ':'; + + // Convert to binary and back to get abbreviated :: version + if (inet_pton(AF_INET6, ipv6_addr, (void *)&s6.sin6_addr) > 0) { + if (inet_ntop(AF_INET6, &s6.sin6_addr, toybuf, sizeof(toybuf))) { + char *scopes[] = {"Global","Host","Link","Site","Compat"}, + *scope = "Unknown"; + + for (i=0; i < sizeof(scopes)/sizeof(*scopes); i++) + if (iscope == (!!i)<<(i+3)) scope = scopes[i]; + xprintf("%10cinet6 addr: %s/%d Scope: %s\n", + ' ', toybuf, plen, scope); + } + } + } + } + fclose(fp); + } + + xprintf("%10c", ' '); + + if (flags) { + unsigned short mask = 1; + char **s, *str[] = { + "UP", "BROADCAST", "DEBUG", "LOOPBACK", "POINTOPOINT", "NOTRAILERS", + "RUNNING", "NOARP", "PROMISC", "ALLMULTI", "MASTER", "SLAVE", "MULTICAST", + "PORTSEL", "AUTOMEDIA", "DYNAMIC", NULL + }; + + for (s = str; *s; s++) { + if (flags & mask) xprintf("%s ", *s); + mask = mask << 1; + } + } else xprintf("[NO FLAGS] "); + + if (ioctl(TT.sockfd, SIOCGIFMTU, &ifre) < 0) ifre.ifr_mtu = 0; + xprintf(" MTU:%d", ifre.ifr_mtu); + if (ioctl(TT.sockfd, SIOCGIFMETRIC, &ifre) < 0) ifre.ifr_metric = 0; + if (!ifre.ifr_metric) ifre.ifr_metric = 1; + xprintf(" Metric:%d", ifre.ifr_metric); + + // non-virtual interface + + if (val) { + char *label[] = {"RX bytes", "RX packets", "errors", "dropped", "overruns", + "frame", 0, 0, "TX bytes", "TX packets", "errors", "dropped", "overruns", + "collisions", "carrier", 0, "txqueuelen"}; + signed char order[] = {-1, 1, 2, 3, 4, 5, -1, 9, 10, 11, 12, 14, -1, + 13, 16, -1, 0, 8}; + int i; + + // Query txqueuelen + if (ioctl(TT.sockfd, SIOCGIFTXQLEN, &ifre) >= 0) val[16] = ifre.ifr_qlen; + else val[16] = -1; + + for (i = 0; i < sizeof(order); i++) { + int j = order[i]; + + if (j < 0) xprintf("\n%10c", ' '); + else xprintf("%s:%llu ", label[j], val[j]); + } + } + xputc('\n'); + + if(!ioctl(TT.sockfd, SIOCGIFMAP, &ifre) && (ifre.ifr_map.irq || + ifre.ifr_map.mem_start || ifre.ifr_map.dma || ifre.ifr_map.base_addr)) + { + xprintf("%10c", ' '); + if(ifre.ifr_map.irq) xprintf("Interrupt:%d ", ifre.ifr_map.irq); + if(ifre.ifr_map.base_addr >= 0x100) // IO_MAP_INDEX + xprintf("Base address:0x%x ", ifre.ifr_map.base_addr); + if(ifre.ifr_map.mem_start) + xprintf("Memory:%lx-%lx ", ifre.ifr_map.mem_start, ifre.ifr_map.mem_end); + if(ifre.ifr_map.dma) xprintf("DMA chan:%x ", ifre.ifr_map.dma); + xputc('\n'); + } + xputc('\n'); +} + +static void show_iface(char *iface_name) +{ + char *name; + struct string_list *ifaces = 0, *sl; + int i, j; + FILE *fp; + + fp = xfopen("/proc/net/dev", "r"); + + for (i=0; fgets(toybuf, sizeof(toybuf), fp); i++) { + char *buf = toybuf; + unsigned long long val[17]; + + if (i<2) continue; + + while (isspace(*buf)) buf++; + name = strsep(&buf, ":"); + if(!buf) error_exit("bad name %s", name); + + errno = 0; + for (j=0; j<16 && !errno; j++) val[j] = strtoll(buf, &buf, 0); + if (errno) perror_exit("bad %s at %s", name, buf); + + if (iface_name) { + if (!strcmp(iface_name, name)) { + display_ifconfig(iface_name, 1, val); + + return; + } + } else { + sl = xmalloc(sizeof(*sl)+strlen(name)+1); + strcpy(sl->str, name); + sl->next = ifaces; + ifaces = sl; + + display_ifconfig(sl->str, toys.optflags & FLAG_a, val); + } + } + fclose(fp); + + if (iface_name) display_ifconfig(iface_name, 1, 0); + else { + struct ifconf ifcon; + struct ifreq *ifre; + int num; + + // Loop until buffer's big enough + ifcon.ifc_buf = NULL; + for (num = 30;;num += 10) { + ifcon.ifc_len = sizeof(struct ifreq)*num; + ifcon.ifc_buf = xrealloc(ifcon.ifc_buf, ifcon.ifc_len); + xioctl(TT.sockfd, SIOCGIFCONF, &ifcon); + if (ifcon.ifc_len != sizeof(struct ifreq)*num) break; + } + + ifre = ifcon.ifc_req; + for(num = 0; num < ifcon.ifc_len && ifre; num += sizeof(struct ifreq), ifre++) + { + // Skip duplicates + for(sl = ifaces; sl; sl = sl->next) + if(!strcmp(sl->str, ifre->ifr_name)) break; + + if(!sl) display_ifconfig(ifre->ifr_name, toys.optflags & FLAG_a, 0); + } + + free(ifcon.ifc_buf); + } + + llist_traverse(ifaces, free); +} + +// Encode offset and size of field into an int, and make result negative +#define IFREQ_OFFSZ(x) -(int)((offsetof(struct ifreq, x)<<16) + sizeof(ifre.x)) + +void ifconfig_main(void) +{ + char **argv = toys.optargs; + struct ifreq ifre; + int i; + + TT.sockfd = xsocket(AF_INET, SOCK_DGRAM, 0); + if(toys.optc < 2) { + show_iface(*argv); + return; + } + + // Open interface + memset(&ifre, 0, sizeof(struct ifreq)); + xstrncpy(ifre.ifr_name, *argv, IFNAMSIZ); + + // Perform operations on interface + while(*++argv) { + // Table of known operations + struct argh { + char *name; + int on, off; // set, clear + } try[] = { + {0, IFF_UP|IFF_RUNNING, SIOCSIFADDR}, + {"up", IFF_UP|IFF_RUNNING, 0}, + {"down", 0, IFF_UP}, + {"arp", 0, IFF_NOARP}, + {"promisc", IFF_PROMISC, 0}, + {"allmulti", IFF_ALLMULTI, 0}, + {"multicast", IFF_MULTICAST, 0}, + {"pointopoint", IFF_POINTOPOINT, SIOCSIFDSTADDR}, + {"broadcast", IFF_BROADCAST, SIOCSIFBRDADDR}, + {"netmask", 0, SIOCSIFNETMASK}, + {"dstaddr", 0, SIOCSIFDSTADDR}, + {"mtu", IFREQ_OFFSZ(ifr_mtu), SIOCSIFMTU}, + {"keepalive", IFREQ_OFFSZ(ifr_data), SIOCDEVPRIVATE}, // SIOCSKEEPALIVE + {"outfill", IFREQ_OFFSZ(ifr_data), SIOCDEVPRIVATE+2}, // SIOCSOUTFILL + {"metric", IFREQ_OFFSZ(ifr_metric), SIOCSIFMETRIC}, + {"txqueuelen", IFREQ_OFFSZ(ifr_qlen), SIOCSIFTXQLEN}, + {"mem_start", IFREQ_OFFSZ(ifr_map.mem_start), SIOCSIFMAP}, + {"io_addr", IFREQ_OFFSZ(ifr_map.base_addr), SIOCSIFMAP}, + {"irq", IFREQ_OFFSZ(ifr_map.irq), SIOCSIFMAP}, + {"inet", 0, 0}, + {"inet6", 0, 0} + }; + char *s = *argv; + int rev = (*s == '-'); + + s += rev; + + // "set hardware address" is oddball enough to special case + if (!strcmp(*argv, "hw")) { + char *hw_addr, *ptr, *p; + struct sockaddr *sock = &ifre.ifr_hwaddr; + int count = 6; + + ptr = p = (char *)sock->sa_data; + memset(sock, 0, sizeof(struct sockaddr)); + if (argv[1]) { + if (!strcmp("ether", *++argv)) sock->sa_family = ARPHRD_ETHER; + else if (!strcmp("infiniband", *argv)) { + sock->sa_family = ARPHRD_INFINIBAND; + count = 20; + p = ptr = toybuf; + } + } + if (!sock->sa_family || !argv[1]) help_exit("bad hw '%s'", *argv); + hw_addr = *++argv; + + // Parse and verify address. + while (*hw_addr && (p-ptr) < count) { + int val, len = 0; + + if (*hw_addr == ':') hw_addr++; + sscanf(hw_addr, "%2x%n", &val, &len); + if (!len || len > 2) break; // 1 nibble can be set e.g. C2:79:38:95:D:A + hw_addr += len; + *p++ = val; + } + + if ((p-ptr) != count || *hw_addr) + error_exit("bad hw-addr '%s'", *argv); + + // the linux kernel's "struct sockaddr" (include/linux/socket.h in the + // kernel source) only has 14 bytes of sa_data, and an infiniband address + // is 20. So if we go through the ioctl, the kernel will truncate + // infiniband addresses, meaning we have to go through sysfs instead. + if (sock->sa_family == ARPHRD_INFINIBAND && !strchr(ifre.ifr_name, '/')) { + int fd; + + sprintf(toybuf, "/sys/class/net/%s/address", ifre.ifr_name); + fd = xopen(toybuf, O_RDWR); + xwrite(fd, *argv, strlen(*argv)); + close(fd); + } else xioctl(TT.sockfd, SIOCSIFHWADDR, &ifre); + continue; + + // Add/remove ipv6 address to interface + + } else if (!strcmp(*argv, "add") || !strcmp(*argv, "del")) { + struct ifreq_inet6 { + struct in6_addr addr; + unsigned prefix; + int index; + } ifre6; + int plen, fd6 = xsocket(AF_INET6, SOCK_DGRAM, 0); + + if (!argv[1]) help_exit("%s", *argv); + + plen = get_addrinfo(argv[1], AF_INET6, &ifre6.addr); + if (plen < 0) plen = 128; + xioctl(fd6, SIOCGIFINDEX, &ifre); + ifre6.index = ifre.ifr_ifindex; + ifre6.prefix = plen; + xioctl(fd6, **(argv++)=='a' ? SIOCSIFADDR : SIOCDIFADDR, &ifre6); + + close(fd6); + continue; + // Iterate through table to find/perform operation + } else for (i = 0; i < ARRAY_LEN(try); i++) { + struct argh *t = try+i; + int on = t->on, off = t->off; + + if (!t->name) { + if (isdigit(**argv) || !strcmp(*argv, "default")) argv--; + else continue; + } else if (strcmp(t->name, s)) continue; + + // Is this an SIOCSI entry? + if ((off|0xff) == 0x89ff) { + if (!rev) { + if (!*++argv) error_exit("%s needs argument", t->name); + + // Assign value to ifre field and call ioctl? (via IFREQ_OFFSZ.) + if (on < 0) { + long l = strtoul(*argv, 0, 0); + + if (off == SIOCSIFMAP) xioctl(TT.sockfd, SIOCGIFMAP, &ifre); + on = -on; + poke((on>>16) + (char *)&ifre, l, on&15); + xioctl(TT.sockfd, off, &ifre); + break; + } else { + struct sockaddr_in *si = (struct sockaddr_in *)&ifre.ifr_addr; + int mask = -1; + + si->sin_family = AF_INET; + + if (!strcmp(*argv, "default")) si->sin_addr.s_addr = INADDR_ANY; + else mask = get_addrinfo(*argv, AF_INET, &si->sin_addr); + xioctl(TT.sockfd, off, &ifre); + + // Handle /netmask + if (mask >= 0) { + // sin_addr probably isn't unaligned, but just in case... + mask = htonl((~0)<<(32-mask)); + memcpy(&si->sin_addr, &mask, 4); + xioctl(TT.sockfd, SIOCSIFNETMASK, &ifre); + } + } + } + off = 0; + } + + // Set flags + if (on || off) { + xioctl(TT.sockfd, SIOCGIFFLAGS, &ifre); + ifre.ifr_flags &= ~(rev ? on : off); + ifre.ifr_flags |= (rev ? off : on); + xioctl(TT.sockfd, SIOCSIFFLAGS, &ifre); + } + + break; + } + if (i == sizeof(try)/sizeof(*try)) help_exit("bad argument '%s'", *argv); + } + close(TT.sockfd); +} diff --git a/toys/net/netcat.c b/toys/net/netcat.c new file mode 100644 index 00000000..1c75eb26 --- /dev/null +++ b/toys/net/netcat.c @@ -0,0 +1,230 @@ +/* netcat.c - Forward stdin/stdout to a file or network connection. + * + * Copyright 2007 Rob Landley + * + * TODO: udp, ipv6, genericize for telnet/microcom/tail-f + +USE_NETCAT(OLDTOY(nc, netcat, TOYFLAG_USR|TOYFLAG_BIN)) +USE_NETCAT(NEWTOY(netcat, USE_NETCAT_LISTEN("^tlL")"w#p#s:q#f:", TOYFLAG_BIN)) + +config NETCAT + bool "netcat" + default y + help + usage: netcat [-u] [-wpq #] [-s addr] {IPADDR PORTNUM|-f FILENAME} + + -f use FILENAME (ala /dev/ttyS0) instead of network + -p local port number + -q SECONDS quit this many seconds after EOF on stdin. + -s local ipv4 address + -w SECONDS timeout for connection + + Use "stty 115200 -F /dev/ttyS0 && stty raw -echo -ctlecho" with + netcat -f to connect to a serial port. + +config NETCAT_LISTEN + bool "netcat server options (-let)" + default y + depends on NETCAT + depends on TOYBOX_FORK + help + usage: netcat [-lL COMMAND...] + + -l listen for one incoming connection. + -L listen for multiple incoming connections (server mode). + + The command line after -l or -L is executed to handle each incoming + connection. If none, the connection is forwarded to stdin/stdout. + + For a quick-and-dirty server, try something like: + netcat -s 127.0.0.1 -p 1234 -tL /bin/bash -l + +config NETCAT_LISTEN_TTY + bool + default y + depends on NETCAT_LISTEN + depends on TOYBOX_FORK + help + usage: netcat [-t] + + -t allocate tty (must come before -l or -L) +*/ + +#define FOR_netcat +#include "toys.h" + +GLOBALS( + char *filename; // -f read from filename instead of network + long quit_delay; // -q Exit after EOF from stdin after # seconds. + char *source_address; // -s Bind to a specific source address. + long port; // -p Bind to a specific source port. + long wait; // -w Wait # seconds for a connection. +) + +static void timeout(int signum) +{ + if (TT.wait) error_exit("Timeout"); + // This should be xexit() but would need siglongjmp()... + exit(0); +} + +static void set_alarm(int seconds) +{ + xsignal(SIGALRM, seconds ? timeout : SIG_DFL); + alarm(seconds); +} + +// Translate x.x.x.x numeric IPv4 address, or else DNS lookup an IPv4 name. +static void lookup_name(char *name, uint32_t *result) +{ + struct hostent *hostbyname; + + hostbyname = gethostbyname(name); // getaddrinfo + if (!hostbyname) error_exit("no host '%s'", name); + *result = *(uint32_t *)*hostbyname->h_addr_list; +} + +// Worry about a fancy lookup later. +static void lookup_port(char *str, uint16_t *port) +{ + *port = SWAP_BE16(atoi(str)); +} + +void netcat_main(void) +{ + int sockfd=-1, pollcount=2; + struct pollfd pollfds[2]; + + memset(pollfds, 0, 2*sizeof(struct pollfd)); + pollfds[0].events = pollfds[1].events = POLLIN; + set_alarm(TT.wait); + + // The argument parsing logic can't make "<2" conditional on other + // arguments like -f and -l, so we do it by hand here. + if ((toys.optflags&FLAG_f) ? toys.optc : + (!(toys.optflags&(FLAG_l|FLAG_L)) && toys.optc!=2)) + help_exit("Argument count wrong"); + + if (TT.filename) pollfds[0].fd = xopen(TT.filename, O_RDWR); + else { + int temp; + struct sockaddr_in address; + + // Setup socket + sockfd = xsocket(AF_INET, SOCK_STREAM, 0); + fcntl(sockfd, F_SETFD, FD_CLOEXEC); + temp = 1; + setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &temp, sizeof(temp)); + memset(&address, 0, sizeof(address)); + address.sin_family = AF_INET; + if (TT.source_address || TT.port) { + address.sin_port = SWAP_BE16(TT.port); + if (TT.source_address) + lookup_name(TT.source_address, (uint32_t *)&address.sin_addr); + if (bind(sockfd, (struct sockaddr *)&address, sizeof(address))) + perror_exit("bind"); + } + + // Dial out + + if (!CFG_NETCAT_LISTEN || !(toys.optflags&(FLAG_L|FLAG_l))) { + // Figure out where to dial out to. + lookup_name(*toys.optargs, (uint32_t *)&address.sin_addr); + lookup_port(toys.optargs[1], &address.sin_port); + temp = connect(sockfd, (struct sockaddr *)&address, sizeof(address)); + if (temp<0) perror_exit("connect"); + pollfds[0].fd = sockfd; + + // Listen for incoming connections + + } else { + socklen_t len = sizeof(address); + + if (listen(sockfd, 5)) error_exit("listen"); + if (!TT.port) { + getsockname(sockfd, (struct sockaddr *)&address, &len); + printf("%d\n", SWAP_BE16(address.sin_port)); + fflush(stdout); + } + // Do we need to return immediately because -l has arguments? + + if ((toys.optflags & FLAG_l) && toys.optc) { + if (CFG_TOYBOX_FORK && xfork()) goto cleanup; + close(0); + close(1); + close(2); + } + + for (;;) { + pid_t child = 0; + + // For -l, call accept from the _new_ process. + + pollfds[0].fd = accept(sockfd, (struct sockaddr *)&address, &len); + if (pollfds[0].fd<0) perror_exit("accept"); + + // Do we need a tty? + + if (toys.optflags&FLAG_t) + child = forkpty(&(pollfds[1].fd), NULL, NULL, NULL); + + // Do we need to fork and/or redirect for exec? + + else { + if (toys.optflags&FLAG_L) { + toys.stacktop = 0; + child = vfork(); + } + if (!child && toys.optc) { + int fd = pollfds[0].fd; + + dup2(fd, 0); + dup2(fd, 1); + if (toys.optflags&FLAG_L) dup2(fd, 2); + if (fd>2) close(fd); + } + } + + if (child<0) error_msg("Fork failed\n"); + if (child<1) break; + close(pollfds[0].fd); + } + } + } + + // We have a connection. Disarm timeout. + // (Does not play well with -L, but what _should_ that do?) + set_alarm(0); + + if (CFG_NETCAT_LISTEN && ((toys.optflags&(FLAG_L|FLAG_l)) && toys.optc)) + xexec(toys.optargs); + + // Poll loop copying stdin->socket and socket->stdout. + for (;;) { + int i; + + if (0>poll(pollfds, pollcount, -1)) perror_exit("poll"); + + for (i=0; i + * Copyright 2013 Kyungwan Han + * + * Not in SUSv4. + * +USE_NETSTAT(NEWTOY(netstat, "pWrxwutneal", TOYFLAG_BIN)) +config NETSTAT + bool "netstat" + default y + help + usage: netstat [-pWrxwutneal] + + Display networking information. Default is netsat -tuwx + + -r routing table + -a all sockets (not just connected) + -l listening server sockets + -t TCP sockets + -u UDP sockets + -w raw sockets + -x unix sockets + -e extended info + -n don't resolve names + -W wide display + -p PID/Program name of sockets +*/ + +#define FOR_netstat +#include "toys.h" +#include + +GLOBALS( + struct num_cache *inodes; + int wpad; +); + +// convert address into text format. +static void addr2str(int af, void *addr, unsigned port, char *buf, int len, + char *proto) +{ + int pos, count; + struct servent *ser = 0; + + // Convert to numeric address + if (!inet_ntop(af, addr, buf, 256)) { + *buf = 0; + + return; + } + buf[len] = 0; + pos = strlen(buf); + + // If there's no port number, it's a local :* binding, nothing to look up. + if (!port) { + if (len-pos<2) pos = len-2; + strcpy(buf+pos, ":*"); + + return; + } + + if (!(toys.optflags & FLAG_n)) { + struct addrinfo hints, *result, *rp; + char cut[4]; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = af; + + if (!getaddrinfo(buf, NULL, &hints, &result)) { + socklen_t sock_len = (af == AF_INET) ? sizeof(struct sockaddr_in) + : sizeof(struct sockaddr_in6); + + // We assume that a failing getnameinfo dosn't stomp "buf" here. + for (rp = result; rp; rp = rp->ai_next) + if (!getnameinfo(rp->ai_addr, sock_len, buf, 256, 0, 0, 0)) break; + freeaddrinfo(result); + buf[len] = 0; + pos = strlen(buf); + } + + // Doesn't understand proto "tcp6", so truncate + memcpy(cut, proto, 3); + cut[3] = 0; + ser = getservbyport(htons(port), cut); + } + + // Append :service + count = snprintf(0, 0, ":%u", port); + if (ser) { + count = snprintf(0, 0, ":%s", ser->s_name); + // sheer paranoia + if (count>=len) { + count = len-1; + ser->s_name[count] = 0; + } + } + if (len-poss_name); + else sprintf(buf+pos, ":%u", port); +} + +// Display info for tcp/udp/raw +static void show_ip(char *fname) +{ + char *ss_state = "UNKNOWN", buf[12], *s, *label = strrchr(fname, '/')+1; + char *state_label[] = {"", "ESTABLISHED", "SYN_SENT", "SYN_RECV", "FIN_WAIT1", + "FIN_WAIT2", "TIME_WAIT", "CLOSE", "CLOSE_WAIT", + "LAST_ACK", "LISTEN", "CLOSING", "UNKNOWN"}; + struct passwd *pw; + FILE *fp = fopen(fname, "r"); + + if (!fp) { + perror_msg("'%s'", fname); + return; + } + + if(!fgets(toybuf, sizeof(toybuf), fp)) return; //skip header. + + while (fgets(toybuf, sizeof(toybuf), fp)) { + char lip[256], rip[256]; + union { + struct {unsigned u; unsigned char b[4];} i4; + struct {struct {unsigned a, b, c, d;} u; unsigned char b[16];} i6; + } laddr, raddr; + unsigned lport, rport, state, txq, rxq, num, uid, nitems; + unsigned long inode; + + // Try ipv6, then try ipv4 + nitems = sscanf(toybuf, + " %d: %8x%8x%8x%8x:%x %8x%8x%8x%8x:%x %x %x:%x %*X:%*X %*X %d %*d %ld", + &num, &laddr.i6.u.a, &laddr.i6.u.b, &laddr.i6.u.c, + &laddr.i6.u.d, &lport, &raddr.i6.u.a, &raddr.i6.u.b, + &raddr.i6.u.c, &raddr.i6.u.d, &rport, &state, &txq, &rxq, + &uid, &inode); + + if (nitems!=16) { + nitems = sscanf(toybuf, + " %d: %x:%x %x:%x %x %x:%x %*X:%*X %*X %d %*d %ld", + &num, &laddr.i4.u, &lport, &raddr.i4.u, &rport, &state, &txq, + &rxq, &uid, &inode); + + if (nitems!=10) continue; + nitems = AF_INET; + } else nitems = AF_INET6; + + // Should we display this? (listening or all or TCP/UDP/RAW) + if (!((toys.optflags & FLAG_l) && (!rport && (state & 0xA))) + && !(toys.optflags & FLAG_a) && !(rport & (0x10 | 0x20 | 0x40))) + continue; + + addr2str(nitems, &laddr, lport, lip, TT.wpad, label); + addr2str(nitems, &raddr, rport, rip, TT.wpad, label); + + // Display data + s = label; + if (strstart(&s, "tcp")) { + int sz = ARRAY_LEN(state_label); + if (!state || state >= sz) state = sz-1; + ss_state = state_label[state]; + } else if (strstart(&s, "udp")) { + if (state == 1) ss_state = state_label[state]; + else if (state == 7) ss_state = ""; + } else if (strstart(&s, "raw")) sprintf(ss_state = buf, "%u", state); + + if (!(toys.optflags & FLAG_n) && (pw = bufgetpwuid(uid))) + snprintf(toybuf, sizeof(toybuf), "%s", pw->pw_name); + else snprintf(toybuf, sizeof(toybuf), "%d", uid); + + printf("%-6s%6d%7d ", label, rxq, txq); + printf("%*.*s %*.*s ", -TT.wpad, TT.wpad, lip, -TT.wpad, TT.wpad, rip); + printf("%-11s", ss_state); + if ((toys.optflags & FLAG_e)) printf(" %-10s %-11ld", toybuf, inode); + if ((toys.optflags & FLAG_p)) { + struct num_cache *nc = get_num_cache(TT.inodes, inode); + + printf(" %s", nc ? nc->data : "-"); + } + xputc('\n'); + } + fclose(fp); +} + +static void show_unix_sockets(void) +{ + char *types[] = {"","STREAM","DGRAM","RAW","RDM","SEQPACKET","DCCP","PACKET"}, + *states[] = {"","LISTENING","CONNECTING","CONNECTED","DISCONNECTING"}, + *s, *ss; + unsigned long refcount, flags, type, state, inode; + FILE *fp = xfopen("/proc/net/unix", "r"); + + if(!fgets(toybuf, sizeof(toybuf), fp)) return; //skip header. + + while (fgets(toybuf, sizeof(toybuf), fp)) { + unsigned offset = 0; + + // count = 6 or 7 (first field ignored, sockets don't always have filenames) + if (6ARRAY_LEN(types)) type = 0; + if (state>ARRAY_LEN(states) || (state==1 && !flags)) state = 0; + sprintf(toybuf, "[ %s]", flags ? "ACC " : ""); + + printf("unix %-6ld %-11s %-10s %-13s %8lu ", + refcount, toybuf, types[type], states[state], inode); + if (toys.optflags & FLAG_p) { + struct num_cache *nc = get_num_cache(TT.inodes, inode); + + printf("%-19.19s", nc ? nc->data : "-"); + } + + if (offset) { + if ((ss = strrchr(s = toybuf+offset, '\n'))) *ss = 0; + printf("%s", s); + } + xputc('\n'); + } + + fclose(fp); +} + +static int scan_pids(struct dirtree *node) +{ + char *s = toybuf+256; + struct dirent *entry; + DIR *dp; + int pid, dirfd; + + if (!node->parent) return DIRTREE_RECURSE; + if (!(pid = atol(node->name))) return 0; + + sprintf(toybuf, "/proc/%d/cmdline", pid); + if (!(readfile(toybuf, toybuf, 256))) return 0; + + sprintf(s, "%d/fd", pid); + if (-1==(dirfd = openat(dirtree_parentfd(node), s, O_RDONLY))) return 0; + if (!(dp = fdopendir(dirfd))) { + close(dirfd); + + return 0; + } + + while ((entry = readdir(dp))) { + s = toybuf+256; + if (!readlinkat0(dirfd, entry->d_name, s, sizeof(toybuf)-256)) continue; + // Can the "[0000]:" happen in a modern kernel? + if (strstart(&s, "socket:[") || strstart(&s, "[0000]:")) { + long long ll = atoll(s); + + sprintf(s, "%d/%s", pid, getbasename(toybuf)); + add_num_cache(&TT.inodes, ll, s, strlen(s)+1); + } + } + closedir(dp); + + return 0; +} + +/* + * extract inet4 route info from /proc/net/route file and display it. + */ +static void display_routes(void) +{ + static const char flagchars[] = "GHRDMDAC"; + static const unsigned flagarray[] = { + RTF_GATEWAY, RTF_HOST, RTF_REINSTATE, RTF_DYNAMIC, RTF_MODIFIED + }; + unsigned long dest, gate, mask; + int flags, ref, use, metric, mss, win, irtt; + char *out = toybuf, *flag_val; + char iface[64]={0}; + FILE *fp = xfopen("/proc/net/route", "r"); + + if(!fgets(toybuf, sizeof(toybuf), fp)) return; //skip header. + + printf("Kernel IP routing table\n" + "Destination\tGateway \tGenmask \tFlags %s Iface\n", + !(toys.optflags&FLAG_e) ? " MSS Window irtt" : "Metric Ref Use"); + + while (fgets(toybuf, sizeof(toybuf), fp)) { + char *destip = 0, *gateip = 0, *maskip = 0; + + if (11 != sscanf(toybuf, "%63s%lx%lx%X%d%d%d%lx%d%d%d", iface, &dest, + &gate, &flags, &ref, &use, &metric, &mask, &mss, &win, &irtt)) + break; + + // skip down interfaces. + if (!(flags & RTF_UP)) continue; + +// TODO /proc/net/ipv6_route + + if (dest) { + if (inet_ntop(AF_INET, &dest, out, 16)) destip = out; + } else destip = (toys.optflags&FLAG_n) ? "0.0.0.0" : "default"; + out += 16; + + if (gate) { + if (inet_ntop(AF_INET, &gate, out, 16)) gateip = out; + } else gateip = (toys.optflags&FLAG_n) ? "0.0.0.0" : "*"; + out += 16; + +// TODO /24 + //For Mask + if (inet_ntop(AF_INET, &mask, out, 16)) maskip = out; + else maskip = "?"; + out += 16; + + //Get flag Values + flag_val = out; + *out++ = 'U'; + for (dest = 0; dest < ARRAY_LEN(flagarray); dest++) + if (flags&flagarray[dest]) *out++ = flagchars[dest]; + *out = 0; + if (flags & RTF_REJECT) *flag_val = '!'; + + printf("%-15.15s %-15.15s %-16s%-6s", destip, gateip, maskip, flag_val); + if (!(toys.optflags & FLAG_e)) + printf("%5d %-5d %6d %s\n", mss, win, irtt, iface); + else printf("%-6d %-2d %7d %s\n", metric, ref, use, iface); + } + + fclose(fp); +} + +void netstat_main(void) +{ + int tuwx = FLAG_t|FLAG_u|FLAG_w|FLAG_x; + char *type = "w/o"; + + TT.wpad = (toys.optflags&FLAG_W) ? 51 : 23; + if (!(toys.optflags&(FLAG_r|tuwx))) toys.optflags |= tuwx; + if (toys.optflags & FLAG_r) display_routes(); + if (!(toys.optflags&tuwx)) return; + + if (toys.optflags & FLAG_a) type = "established and"; + else if (toys.optflags & FLAG_l) type = "only"; + + if (toys.optflags & FLAG_p) dirtree_read("/proc", scan_pids); + + if (toys.optflags&(FLAG_t|FLAG_u|FLAG_w)) { + printf("Active %s (%s servers)\n", "Internet connections", type); + printf("Proto Recv-Q Send-Q %*s %*s State ", -TT.wpad, "Local Address", + -TT.wpad, "Foreign Address"); + if (toys.optflags & FLAG_e) printf(" User Inode "); + if (toys.optflags & FLAG_p) printf(" PID/Program Name"); + xputc('\n'); + + if (toys.optflags & FLAG_t) { + show_ip("/proc/net/tcp"); + show_ip("/proc/net/tcp6"); + } + if (toys.optflags & FLAG_u) { + show_ip("/proc/net/udp"); + show_ip("/proc/net/udp6"); + } + if (toys.optflags & FLAG_w) { + show_ip("/proc/net/raw"); + show_ip("/proc/net/raw6"); + } + } + + if (toys.optflags & FLAG_x) { + printf("Active %s (%s servers)\n", "UNIX domain sockets", type); + + printf("Proto RefCnt Flags\t Type\t State\t %s Path\n", + (toys.optflags&FLAG_p) ? "PID/Program Name" : "I-Node"); + show_unix_sockets(); + } + + if ((toys.optflags & FLAG_p) && CFG_TOYBOX_FREE) + llist_traverse(TT.inodes, free); + toys.exitval = 0; +} diff --git a/toys/net/rfkill.c b/toys/net/rfkill.c new file mode 100644 index 00000000..36fe320d --- /dev/null +++ b/toys/net/rfkill.c @@ -0,0 +1,102 @@ +/* rfkill.c - Enable/disable wireless devices. + * + * Copyright 2014 Ranjan Kumar + * Copyright 2014 Kyungwan Han + * + * No Standard + +USE_RFKILL(NEWTOY(rfkill, "<1>2", TOYFLAG_USR|TOYFLAG_SBIN)) + +config RFKILL + bool "rfkill" + default y + help + Usage: rfkill COMMAND [DEVICE] + + Enable/disable wireless devices. + + Commands: + list [DEVICE] List current state + block DEVICE Disable device + unblock DEVICE Enable device + + DEVICE is an index number, or one of: + all, wlan(wifi), bluetooth, uwb(ultrawideband), wimax, wwan, gps, fm. +*/ + +#define FOR_rfkill +#include "toys.h" +#include + +void rfkill_main(void) +{ + struct rfkill_event rfevent; + int fd, tvar, idx = -1, tid = RFKILL_TYPE_ALL; + char **optargs = toys.optargs; + + // Parse command line options + for (tvar = 0; tvar < 3; tvar++) + if (!strcmp((char *[]){"list", "block", "unblock"}[tvar], *optargs)) break; + if (tvar == 3) error_exit("unknown cmd '%s'", *optargs); + if (tvar) { + int i; + struct arglist { + char *name; + int idx; + } rftypes[] = {{"all", RFKILL_TYPE_ALL}, {"wifi", RFKILL_TYPE_WLAN}, + {"wlan", RFKILL_TYPE_WLAN}, {"bluetooth", RFKILL_TYPE_BLUETOOTH}, + {"uwb", RFKILL_TYPE_UWB}, {"ultrawideband", RFKILL_TYPE_UWB}, + {"wimax", RFKILL_TYPE_WIMAX}, {"wwan", RFKILL_TYPE_WWAN}, + {"gps", RFKILL_TYPE_GPS}, {"fm", 7}}; // RFKILL_TYPE_FM = 7 + + if (!*++optargs) error_exit("'%s' needs IDENTIFIER", optargs[-1]); + for (i = 0; i < ARRAY_LEN(rftypes); i++) + if (!strcmp(rftypes[i].name, *optargs)) break; + if (i == ARRAY_LEN(rftypes)) idx = atolx_range(*optargs, 0, INT_MAX); + else tid = rftypes[i].idx; + } + + // Perform requested action + fd = xopen("/dev/rfkill", (tvar ? O_RDWR : O_RDONLY)|O_NONBLOCK); + if (tvar) { + // block/unblock + memset(&rfevent, 0, sizeof(rfevent)); + rfevent.soft = tvar == 1; + if (idx >= 0) { + rfevent.idx = idx; + rfevent.op = RFKILL_OP_CHANGE; + } else { + rfevent.type = tid; + rfevent.op = RFKILL_OP_CHANGE_ALL; + } + xwrite(fd, &rfevent, sizeof(rfevent)); + } else { + // show list. + while (sizeof(rfevent) == readall(fd, &rfevent, sizeof(rfevent))) { + char *line, *name = 0, *type = 0; + + // filter list items + if ((tid > 0 && tid != rfevent.type) || (idx != -1 && idx != rfevent.idx)) + continue; + + sprintf(toybuf, "/sys/class/rfkill/rfkill%u/uevent", rfevent.idx); + tvar = xopen(toybuf, O_RDONLY); + while ((line = get_line(tvar))) { + char *s = line; + + if (strstart(&s, "RFKILL_NAME=")) name = xstrdup(s); + else if (strstart(&s, "RFKILL_TYPE=")) type = xstrdup(s); + + free(line); + } + xclose(tvar); + + xprintf("%u: %s: %s\n", rfevent.idx, name, type); + xprintf("\tSoft blocked: %s\n", rfevent.soft ? "yes" : "no"); + xprintf("\tHard blocked: %s\n", rfevent.hard ? "yes" : "no"); + free(name); + free(type); + } + } + xclose(fd); +} diff --git a/toys/other/ifconfig.c b/toys/other/ifconfig.c deleted file mode 100644 index 1d2a41dc..00000000 --- a/toys/other/ifconfig.c +++ /dev/null @@ -1,517 +0,0 @@ -/* ifconfig.c - Configure network interface. - * - * Copyright 2012 Ranjan Kumar - * Copyright 2012 Kyungwan Han - * Reviewed by Kyungsu Kim - * - * Not in SUSv4. - -USE_IFCONFIG(NEWTOY(ifconfig, "^?a", TOYFLAG_SBIN)) - -config IFCONFIG - bool "ifconfig" - default y - help - usage: ifconfig [-a] [INTERFACE [ACTION...]] - - Display or configure network interface. - - With no arguments, display active interfaces. First argument is interface - to operate on, one argument by itself displays that interface. - - -a Show all interfaces, not just active ones - - Additional arguments are actions to perform on the interface: - - ADDRESS[/NETMASK] - set IPv4 address (1.2.3.4/5) - default - unset ipv4 address - add|del ADDRESS[/PREFIXLEN] - add/remove IPv6 address (1111::8888/128) - up - enable interface - down - disable interface - - netmask|broadcast|pointopoint ADDRESS - set more IPv4 characteristics - hw ether|infiniband ADDRESS - set LAN hardware address (AA:BB:CC...) - txqueuelen LEN - number of buffered packets before output blocks - mtu LEN - size of outgoing packets (Maximum Transmission Unit) - - Flags you can set on an interface (or -remove by prefixing with -): - arp - don't use Address Resolution Protocol to map LAN routes - promisc - don't discard packets that aren't to this LAN hardware address - multicast - force interface into multicast mode if the driver doesn't - allmulti - promisc for multicast packets - - Obsolete fields included for historical purposes: - irq|io_addr|mem_start ADDR - micromanage obsolete hardware - outfill|keepalive INTEGER - SLIP analog dialup line quality monitoring - metric INTEGER - added to Linux 0.9.10 with comment "never used", still true -*/ - -#define FOR_ifconfig -#include "toys.h" - -#include -#include - -GLOBALS( - int sockfd; -) - -// Convert hostname to binary address for AF_INET or AF_INET6 -// return /prefix (or range max if none) -int get_addrinfo(char *host, sa_family_t af, void *addr) -{ - struct addrinfo hints, *result, *rp = 0; - int status, len; - char *from, *slash; - - memset(&hints, 0 , sizeof(struct addrinfo)); - hints.ai_family = af; - hints.ai_socktype = SOCK_STREAM; - - slash = strchr(host, '/'); - if (slash) *slash = 0; - - status = getaddrinfo(host, NULL, &hints, &result); - if (!status) - for (rp = result; rp; rp = rp->ai_next) - if (rp->ai_family == af) break; - if (!rp) error_exit("bad address '%s' : %s", host, gai_strerror(status)); - - // ai_addr isn't struct in_addr or in6_addr, it's struct sockaddr. Of course. - // You'd think ipv4 and ipv6 would have some basic compatibility, but no. - from = ((char *)rp->ai_addr) + 4; - if (af == AF_INET6) { - len = 16; - from += 4; // skip "flowinfo" field ipv6 puts before address - } else len = 4; - memcpy(addr, from, len); - freeaddrinfo(result); - - len = -1; - if (slash) len = atolx_range(slash+1, 0, (af == AF_INET) ? 32 : 128); - - return len; -} - -static void display_ifconfig(char *name, int always, unsigned long long val[]) -{ - struct ifreq ifre; - struct { - int type; - char *title; - } types[] = { - {ARPHRD_LOOPBACK, "Local Loopback"}, {ARPHRD_ETHER, "Ethernet"}, - {ARPHRD_PPP, "Point-to-Point Protocol"}, {ARPHRD_INFINIBAND, "InfiniBand"}, - {ARPHRD_SIT, "IPv6-in-IPv4"}, {-1, "UNSPEC"} - }; - int i; - char *pp; - FILE *fp; - short flags; - - xstrncpy(ifre.ifr_name, name, IFNAMSIZ); - if (ioctl(TT.sockfd, SIOCGIFFLAGS, &ifre)<0) perror_exit_raw(name); - flags = ifre.ifr_flags; - if (!always && !(flags & IFF_UP)) return; - - // query hardware type and hardware address - i = ioctl(TT.sockfd, SIOCGIFHWADDR, &ifre); - - for (i=0; i < (sizeof(types)/sizeof(*types))-1; i++) - if (ifre.ifr_hwaddr.sa_family == types[i].type) break; - - xprintf("%-9s Link encap:%s ", name, types[i].title); - if(i >= 0 && ifre.ifr_hwaddr.sa_family == ARPHRD_ETHER) { - xprintf("HWaddr "); - for (i=0; i<6; i++) xprintf(":%02x"+!i, ifre.ifr_hwaddr.sa_data[i]); - } - xputc('\n'); - - // If an address is assigned record that. - - ifre.ifr_addr.sa_family = AF_INET; - memset(&ifre.ifr_addr, 0, sizeof(ifre.ifr_addr)); - ioctl(TT.sockfd, SIOCGIFADDR, &ifre); - pp = (char *)&ifre.ifr_addr; - for (i = 0; isin_family == AF_INET) ? "inet" : - (si->sin_family == AF_INET6) ? "inet6" : "unspec"); - - for (i=0; i < sizeof(addr)/sizeof(*addr); i++) { - if (!addr[i].flag || (flags & addr[i].flag)) { - if (addr[i].ioctl && ioctl(TT.sockfd, addr[i].ioctl, &ifre)) - si->sin_family = 0; - xprintf(" %s:%s ", addr[i].name, - (si->sin_family == 0xFFFF || !si->sin_family) - ? "[NOT SET]" : inet_ntoa(si->sin_addr)); - } - } - - xputc('\n'); - } - - fp = fopen(pp = "/proc/net/if_inet6", "r"); - if (fp) { - char iface_name[IFNAMSIZ]; - int plen, iscope; - - while (fgets(toybuf, sizeof(toybuf), fp)) { - int nitems; - char ipv6_addr[40]; - - nitems = sscanf(toybuf, "%32s %*08x %02x %02x %*02x %15s\n", - ipv6_addr, &plen, &iscope, iface_name); - if (nitems<0 && feof(fp)) break; - if (nitems != 4) perror_exit("bad %s", pp); - - if (!strcmp(name, iface_name)) { - struct sockaddr_in6 s6; - char *ptr = ipv6_addr+sizeof(ipv6_addr)-1; - - // convert giant hex string into colon-spearated ipv6 address by - // inserting ':' every 4 characters. - for (i = 32; i; i--) - if ((*(ptr--) = ipv6_addr[i])) if (!(i&3)) *(ptr--) = ':'; - - // Convert to binary and back to get abbreviated :: version - if (inet_pton(AF_INET6, ipv6_addr, (void *)&s6.sin6_addr) > 0) { - if (inet_ntop(AF_INET6, &s6.sin6_addr, toybuf, sizeof(toybuf))) { - char *scopes[] = {"Global","Host","Link","Site","Compat"}, - *scope = "Unknown"; - - for (i=0; i < sizeof(scopes)/sizeof(*scopes); i++) - if (iscope == (!!i)<<(i+3)) scope = scopes[i]; - xprintf("%10cinet6 addr: %s/%d Scope: %s\n", - ' ', toybuf, plen, scope); - } - } - } - } - fclose(fp); - } - - xprintf("%10c", ' '); - - if (flags) { - unsigned short mask = 1; - char **s, *str[] = { - "UP", "BROADCAST", "DEBUG", "LOOPBACK", "POINTOPOINT", "NOTRAILERS", - "RUNNING", "NOARP", "PROMISC", "ALLMULTI", "MASTER", "SLAVE", "MULTICAST", - "PORTSEL", "AUTOMEDIA", "DYNAMIC", NULL - }; - - for (s = str; *s; s++) { - if (flags & mask) xprintf("%s ", *s); - mask = mask << 1; - } - } else xprintf("[NO FLAGS] "); - - if (ioctl(TT.sockfd, SIOCGIFMTU, &ifre) < 0) ifre.ifr_mtu = 0; - xprintf(" MTU:%d", ifre.ifr_mtu); - if (ioctl(TT.sockfd, SIOCGIFMETRIC, &ifre) < 0) ifre.ifr_metric = 0; - if (!ifre.ifr_metric) ifre.ifr_metric = 1; - xprintf(" Metric:%d", ifre.ifr_metric); - - // non-virtual interface - - if (val) { - char *label[] = {"RX bytes", "RX packets", "errors", "dropped", "overruns", - "frame", 0, 0, "TX bytes", "TX packets", "errors", "dropped", "overruns", - "collisions", "carrier", 0, "txqueuelen"}; - signed char order[] = {-1, 1, 2, 3, 4, 5, -1, 9, 10, 11, 12, 14, -1, - 13, 16, -1, 0, 8}; - int i; - - // Query txqueuelen - if (ioctl(TT.sockfd, SIOCGIFTXQLEN, &ifre) >= 0) val[16] = ifre.ifr_qlen; - else val[16] = -1; - - for (i = 0; i < sizeof(order); i++) { - int j = order[i]; - - if (j < 0) xprintf("\n%10c", ' '); - else xprintf("%s:%llu ", label[j], val[j]); - } - } - xputc('\n'); - - if(!ioctl(TT.sockfd, SIOCGIFMAP, &ifre) && (ifre.ifr_map.irq || - ifre.ifr_map.mem_start || ifre.ifr_map.dma || ifre.ifr_map.base_addr)) - { - xprintf("%10c", ' '); - if(ifre.ifr_map.irq) xprintf("Interrupt:%d ", ifre.ifr_map.irq); - if(ifre.ifr_map.base_addr >= 0x100) // IO_MAP_INDEX - xprintf("Base address:0x%x ", ifre.ifr_map.base_addr); - if(ifre.ifr_map.mem_start) - xprintf("Memory:%lx-%lx ", ifre.ifr_map.mem_start, ifre.ifr_map.mem_end); - if(ifre.ifr_map.dma) xprintf("DMA chan:%x ", ifre.ifr_map.dma); - xputc('\n'); - } - xputc('\n'); -} - -static void show_iface(char *iface_name) -{ - char *name; - struct string_list *ifaces = 0, *sl; - int i, j; - FILE *fp; - - fp = xfopen("/proc/net/dev", "r"); - - for (i=0; fgets(toybuf, sizeof(toybuf), fp); i++) { - char *buf = toybuf; - unsigned long long val[17]; - - if (i<2) continue; - - while (isspace(*buf)) buf++; - name = strsep(&buf, ":"); - if(!buf) error_exit("bad name %s", name); - - errno = 0; - for (j=0; j<16 && !errno; j++) val[j] = strtoll(buf, &buf, 0); - if (errno) perror_exit("bad %s at %s", name, buf); - - if (iface_name) { - if (!strcmp(iface_name, name)) { - display_ifconfig(iface_name, 1, val); - - return; - } - } else { - sl = xmalloc(sizeof(*sl)+strlen(name)+1); - strcpy(sl->str, name); - sl->next = ifaces; - ifaces = sl; - - display_ifconfig(sl->str, toys.optflags & FLAG_a, val); - } - } - fclose(fp); - - if (iface_name) display_ifconfig(iface_name, 1, 0); - else { - struct ifconf ifcon; - struct ifreq *ifre; - int num; - - // Loop until buffer's big enough - ifcon.ifc_buf = NULL; - for (num = 30;;num += 10) { - ifcon.ifc_len = sizeof(struct ifreq)*num; - ifcon.ifc_buf = xrealloc(ifcon.ifc_buf, ifcon.ifc_len); - xioctl(TT.sockfd, SIOCGIFCONF, &ifcon); - if (ifcon.ifc_len != sizeof(struct ifreq)*num) break; - } - - ifre = ifcon.ifc_req; - for(num = 0; num < ifcon.ifc_len && ifre; num += sizeof(struct ifreq), ifre++) - { - // Skip duplicates - for(sl = ifaces; sl; sl = sl->next) - if(!strcmp(sl->str, ifre->ifr_name)) break; - - if(!sl) display_ifconfig(ifre->ifr_name, toys.optflags & FLAG_a, 0); - } - - free(ifcon.ifc_buf); - } - - llist_traverse(ifaces, free); -} - -// Encode offset and size of field into an int, and make result negative -#define IFREQ_OFFSZ(x) -(int)((offsetof(struct ifreq, x)<<16) + sizeof(ifre.x)) - -void ifconfig_main(void) -{ - char **argv = toys.optargs; - struct ifreq ifre; - int i; - - TT.sockfd = xsocket(AF_INET, SOCK_DGRAM, 0); - if(toys.optc < 2) { - show_iface(*argv); - return; - } - - // Open interface - memset(&ifre, 0, sizeof(struct ifreq)); - xstrncpy(ifre.ifr_name, *argv, IFNAMSIZ); - - // Perform operations on interface - while(*++argv) { - // Table of known operations - struct argh { - char *name; - int on, off; // set, clear - } try[] = { - {0, IFF_UP|IFF_RUNNING, SIOCSIFADDR}, - {"up", IFF_UP|IFF_RUNNING, 0}, - {"down", 0, IFF_UP}, - {"arp", 0, IFF_NOARP}, - {"promisc", IFF_PROMISC, 0}, - {"allmulti", IFF_ALLMULTI, 0}, - {"multicast", IFF_MULTICAST, 0}, - {"pointopoint", IFF_POINTOPOINT, SIOCSIFDSTADDR}, - {"broadcast", IFF_BROADCAST, SIOCSIFBRDADDR}, - {"netmask", 0, SIOCSIFNETMASK}, - {"dstaddr", 0, SIOCSIFDSTADDR}, - {"mtu", IFREQ_OFFSZ(ifr_mtu), SIOCSIFMTU}, - {"keepalive", IFREQ_OFFSZ(ifr_data), SIOCDEVPRIVATE}, // SIOCSKEEPALIVE - {"outfill", IFREQ_OFFSZ(ifr_data), SIOCDEVPRIVATE+2}, // SIOCSOUTFILL - {"metric", IFREQ_OFFSZ(ifr_metric), SIOCSIFMETRIC}, - {"txqueuelen", IFREQ_OFFSZ(ifr_qlen), SIOCSIFTXQLEN}, - {"mem_start", IFREQ_OFFSZ(ifr_map.mem_start), SIOCSIFMAP}, - {"io_addr", IFREQ_OFFSZ(ifr_map.base_addr), SIOCSIFMAP}, - {"irq", IFREQ_OFFSZ(ifr_map.irq), SIOCSIFMAP}, - {"inet", 0, 0}, - {"inet6", 0, 0} - }; - char *s = *argv; - int rev = (*s == '-'); - - s += rev; - - // "set hardware address" is oddball enough to special case - if (!strcmp(*argv, "hw")) { - char *hw_addr, *ptr, *p; - struct sockaddr *sock = &ifre.ifr_hwaddr; - int count = 6; - - ptr = p = (char *)sock->sa_data; - memset(sock, 0, sizeof(struct sockaddr)); - if (argv[1]) { - if (!strcmp("ether", *++argv)) sock->sa_family = ARPHRD_ETHER; - else if (!strcmp("infiniband", *argv)) { - sock->sa_family = ARPHRD_INFINIBAND; - count = 20; - p = ptr = toybuf; - } - } - if (!sock->sa_family || !argv[1]) help_exit("bad hw '%s'", *argv); - hw_addr = *++argv; - - // Parse and verify address. - while (*hw_addr && (p-ptr) < count) { - int val, len = 0; - - if (*hw_addr == ':') hw_addr++; - sscanf(hw_addr, "%2x%n", &val, &len); - if (!len || len > 2) break; // 1 nibble can be set e.g. C2:79:38:95:D:A - hw_addr += len; - *p++ = val; - } - - if ((p-ptr) != count || *hw_addr) - error_exit("bad hw-addr '%s'", *argv); - - // the linux kernel's "struct sockaddr" (include/linux/socket.h in the - // kernel source) only has 14 bytes of sa_data, and an infiniband address - // is 20. So if we go through the ioctl, the kernel will truncate - // infiniband addresses, meaning we have to go through sysfs instead. - if (sock->sa_family == ARPHRD_INFINIBAND && !strchr(ifre.ifr_name, '/')) { - int fd; - - sprintf(toybuf, "/sys/class/net/%s/address", ifre.ifr_name); - fd = xopen(toybuf, O_RDWR); - xwrite(fd, *argv, strlen(*argv)); - close(fd); - } else xioctl(TT.sockfd, SIOCSIFHWADDR, &ifre); - continue; - - // Add/remove ipv6 address to interface - - } else if (!strcmp(*argv, "add") || !strcmp(*argv, "del")) { - struct ifreq_inet6 { - struct in6_addr addr; - unsigned prefix; - int index; - } ifre6; - int plen, fd6 = xsocket(AF_INET6, SOCK_DGRAM, 0); - - if (!argv[1]) help_exit("%s", *argv); - - plen = get_addrinfo(argv[1], AF_INET6, &ifre6.addr); - if (plen < 0) plen = 128; - xioctl(fd6, SIOCGIFINDEX, &ifre); - ifre6.index = ifre.ifr_ifindex; - ifre6.prefix = plen; - xioctl(fd6, **(argv++)=='a' ? SIOCSIFADDR : SIOCDIFADDR, &ifre6); - - close(fd6); - continue; - // Iterate through table to find/perform operation - } else for (i = 0; i < ARRAY_LEN(try); i++) { - struct argh *t = try+i; - int on = t->on, off = t->off; - - if (!t->name) { - if (isdigit(**argv) || !strcmp(*argv, "default")) argv--; - else continue; - } else if (strcmp(t->name, s)) continue; - - // Is this an SIOCSI entry? - if ((off|0xff) == 0x89ff) { - if (!rev) { - if (!*++argv) error_exit("%s needs argument", t->name); - - // Assign value to ifre field and call ioctl? (via IFREQ_OFFSZ.) - if (on < 0) { - long l = strtoul(*argv, 0, 0); - - if (off == SIOCSIFMAP) xioctl(TT.sockfd, SIOCGIFMAP, &ifre); - on = -on; - poke((on>>16) + (char *)&ifre, l, on&15); - xioctl(TT.sockfd, off, &ifre); - break; - } else { - struct sockaddr_in *si = (struct sockaddr_in *)&ifre.ifr_addr; - int mask = -1; - - si->sin_family = AF_INET; - - if (!strcmp(*argv, "default")) si->sin_addr.s_addr = INADDR_ANY; - else mask = get_addrinfo(*argv, AF_INET, &si->sin_addr); - xioctl(TT.sockfd, off, &ifre); - - // Handle /netmask - if (mask >= 0) { - // sin_addr probably isn't unaligned, but just in case... - mask = htonl((~0)<<(32-mask)); - memcpy(&si->sin_addr, &mask, 4); - xioctl(TT.sockfd, SIOCSIFNETMASK, &ifre); - } - } - } - off = 0; - } - - // Set flags - if (on || off) { - xioctl(TT.sockfd, SIOCGIFFLAGS, &ifre); - ifre.ifr_flags &= ~(rev ? on : off); - ifre.ifr_flags |= (rev ? off : on); - xioctl(TT.sockfd, SIOCSIFFLAGS, &ifre); - } - - break; - } - if (i == sizeof(try)/sizeof(*try)) help_exit("bad argument '%s'", *argv); - } - close(TT.sockfd); -} diff --git a/toys/other/netcat.c b/toys/other/netcat.c deleted file mode 100644 index 1c75eb26..00000000 --- a/toys/other/netcat.c +++ /dev/null @@ -1,230 +0,0 @@ -/* netcat.c - Forward stdin/stdout to a file or network connection. - * - * Copyright 2007 Rob Landley - * - * TODO: udp, ipv6, genericize for telnet/microcom/tail-f - -USE_NETCAT(OLDTOY(nc, netcat, TOYFLAG_USR|TOYFLAG_BIN)) -USE_NETCAT(NEWTOY(netcat, USE_NETCAT_LISTEN("^tlL")"w#p#s:q#f:", TOYFLAG_BIN)) - -config NETCAT - bool "netcat" - default y - help - usage: netcat [-u] [-wpq #] [-s addr] {IPADDR PORTNUM|-f FILENAME} - - -f use FILENAME (ala /dev/ttyS0) instead of network - -p local port number - -q SECONDS quit this many seconds after EOF on stdin. - -s local ipv4 address - -w SECONDS timeout for connection - - Use "stty 115200 -F /dev/ttyS0 && stty raw -echo -ctlecho" with - netcat -f to connect to a serial port. - -config NETCAT_LISTEN - bool "netcat server options (-let)" - default y - depends on NETCAT - depends on TOYBOX_FORK - help - usage: netcat [-lL COMMAND...] - - -l listen for one incoming connection. - -L listen for multiple incoming connections (server mode). - - The command line after -l or -L is executed to handle each incoming - connection. If none, the connection is forwarded to stdin/stdout. - - For a quick-and-dirty server, try something like: - netcat -s 127.0.0.1 -p 1234 -tL /bin/bash -l - -config NETCAT_LISTEN_TTY - bool - default y - depends on NETCAT_LISTEN - depends on TOYBOX_FORK - help - usage: netcat [-t] - - -t allocate tty (must come before -l or -L) -*/ - -#define FOR_netcat -#include "toys.h" - -GLOBALS( - char *filename; // -f read from filename instead of network - long quit_delay; // -q Exit after EOF from stdin after # seconds. - char *source_address; // -s Bind to a specific source address. - long port; // -p Bind to a specific source port. - long wait; // -w Wait # seconds for a connection. -) - -static void timeout(int signum) -{ - if (TT.wait) error_exit("Timeout"); - // This should be xexit() but would need siglongjmp()... - exit(0); -} - -static void set_alarm(int seconds) -{ - xsignal(SIGALRM, seconds ? timeout : SIG_DFL); - alarm(seconds); -} - -// Translate x.x.x.x numeric IPv4 address, or else DNS lookup an IPv4 name. -static void lookup_name(char *name, uint32_t *result) -{ - struct hostent *hostbyname; - - hostbyname = gethostbyname(name); // getaddrinfo - if (!hostbyname) error_exit("no host '%s'", name); - *result = *(uint32_t *)*hostbyname->h_addr_list; -} - -// Worry about a fancy lookup later. -static void lookup_port(char *str, uint16_t *port) -{ - *port = SWAP_BE16(atoi(str)); -} - -void netcat_main(void) -{ - int sockfd=-1, pollcount=2; - struct pollfd pollfds[2]; - - memset(pollfds, 0, 2*sizeof(struct pollfd)); - pollfds[0].events = pollfds[1].events = POLLIN; - set_alarm(TT.wait); - - // The argument parsing logic can't make "<2" conditional on other - // arguments like -f and -l, so we do it by hand here. - if ((toys.optflags&FLAG_f) ? toys.optc : - (!(toys.optflags&(FLAG_l|FLAG_L)) && toys.optc!=2)) - help_exit("Argument count wrong"); - - if (TT.filename) pollfds[0].fd = xopen(TT.filename, O_RDWR); - else { - int temp; - struct sockaddr_in address; - - // Setup socket - sockfd = xsocket(AF_INET, SOCK_STREAM, 0); - fcntl(sockfd, F_SETFD, FD_CLOEXEC); - temp = 1; - setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &temp, sizeof(temp)); - memset(&address, 0, sizeof(address)); - address.sin_family = AF_INET; - if (TT.source_address || TT.port) { - address.sin_port = SWAP_BE16(TT.port); - if (TT.source_address) - lookup_name(TT.source_address, (uint32_t *)&address.sin_addr); - if (bind(sockfd, (struct sockaddr *)&address, sizeof(address))) - perror_exit("bind"); - } - - // Dial out - - if (!CFG_NETCAT_LISTEN || !(toys.optflags&(FLAG_L|FLAG_l))) { - // Figure out where to dial out to. - lookup_name(*toys.optargs, (uint32_t *)&address.sin_addr); - lookup_port(toys.optargs[1], &address.sin_port); - temp = connect(sockfd, (struct sockaddr *)&address, sizeof(address)); - if (temp<0) perror_exit("connect"); - pollfds[0].fd = sockfd; - - // Listen for incoming connections - - } else { - socklen_t len = sizeof(address); - - if (listen(sockfd, 5)) error_exit("listen"); - if (!TT.port) { - getsockname(sockfd, (struct sockaddr *)&address, &len); - printf("%d\n", SWAP_BE16(address.sin_port)); - fflush(stdout); - } - // Do we need to return immediately because -l has arguments? - - if ((toys.optflags & FLAG_l) && toys.optc) { - if (CFG_TOYBOX_FORK && xfork()) goto cleanup; - close(0); - close(1); - close(2); - } - - for (;;) { - pid_t child = 0; - - // For -l, call accept from the _new_ process. - - pollfds[0].fd = accept(sockfd, (struct sockaddr *)&address, &len); - if (pollfds[0].fd<0) perror_exit("accept"); - - // Do we need a tty? - - if (toys.optflags&FLAG_t) - child = forkpty(&(pollfds[1].fd), NULL, NULL, NULL); - - // Do we need to fork and/or redirect for exec? - - else { - if (toys.optflags&FLAG_L) { - toys.stacktop = 0; - child = vfork(); - } - if (!child && toys.optc) { - int fd = pollfds[0].fd; - - dup2(fd, 0); - dup2(fd, 1); - if (toys.optflags&FLAG_L) dup2(fd, 2); - if (fd>2) close(fd); - } - } - - if (child<0) error_msg("Fork failed\n"); - if (child<1) break; - close(pollfds[0].fd); - } - } - } - - // We have a connection. Disarm timeout. - // (Does not play well with -L, but what _should_ that do?) - set_alarm(0); - - if (CFG_NETCAT_LISTEN && ((toys.optflags&(FLAG_L|FLAG_l)) && toys.optc)) - xexec(toys.optargs); - - // Poll loop copying stdin->socket and socket->stdout. - for (;;) { - int i; - - if (0>poll(pollfds, pollcount, -1)) perror_exit("poll"); - - for (i=0; i - * Copyright 2014 Kyungwan Han - * - * No Standard - -USE_RFKILL(NEWTOY(rfkill, "<1>2", TOYFLAG_USR|TOYFLAG_SBIN)) - -config RFKILL - bool "rfkill" - default y - help - Usage: rfkill COMMAND [DEVICE] - - Enable/disable wireless devices. - - Commands: - list [DEVICE] List current state - block DEVICE Disable device - unblock DEVICE Enable device - - DEVICE is an index number, or one of: - all, wlan(wifi), bluetooth, uwb(ultrawideband), wimax, wwan, gps, fm. -*/ - -#define FOR_rfkill -#include "toys.h" -#include - -void rfkill_main(void) -{ - struct rfkill_event rfevent; - int fd, tvar, idx = -1, tid = RFKILL_TYPE_ALL; - char **optargs = toys.optargs; - - // Parse command line options - for (tvar = 0; tvar < 3; tvar++) - if (!strcmp((char *[]){"list", "block", "unblock"}[tvar], *optargs)) break; - if (tvar == 3) error_exit("unknown cmd '%s'", *optargs); - if (tvar) { - int i; - struct arglist { - char *name; - int idx; - } rftypes[] = {{"all", RFKILL_TYPE_ALL}, {"wifi", RFKILL_TYPE_WLAN}, - {"wlan", RFKILL_TYPE_WLAN}, {"bluetooth", RFKILL_TYPE_BLUETOOTH}, - {"uwb", RFKILL_TYPE_UWB}, {"ultrawideband", RFKILL_TYPE_UWB}, - {"wimax", RFKILL_TYPE_WIMAX}, {"wwan", RFKILL_TYPE_WWAN}, - {"gps", RFKILL_TYPE_GPS}, {"fm", 7}}; // RFKILL_TYPE_FM = 7 - - if (!*++optargs) error_exit("'%s' needs IDENTIFIER", optargs[-1]); - for (i = 0; i < ARRAY_LEN(rftypes); i++) - if (!strcmp(rftypes[i].name, *optargs)) break; - if (i == ARRAY_LEN(rftypes)) idx = atolx_range(*optargs, 0, INT_MAX); - else tid = rftypes[i].idx; - } - - // Perform requested action - fd = xopen("/dev/rfkill", (tvar ? O_RDWR : O_RDONLY)|O_NONBLOCK); - if (tvar) { - // block/unblock - memset(&rfevent, 0, sizeof(rfevent)); - rfevent.soft = tvar == 1; - if (idx >= 0) { - rfevent.idx = idx; - rfevent.op = RFKILL_OP_CHANGE; - } else { - rfevent.type = tid; - rfevent.op = RFKILL_OP_CHANGE_ALL; - } - xwrite(fd, &rfevent, sizeof(rfevent)); - } else { - // show list. - while (sizeof(rfevent) == readall(fd, &rfevent, sizeof(rfevent))) { - char *line, *name = 0, *type = 0; - - // filter list items - if ((tid > 0 && tid != rfevent.type) || (idx != -1 && idx != rfevent.idx)) - continue; - - sprintf(toybuf, "/sys/class/rfkill/rfkill%u/uevent", rfevent.idx); - tvar = xopen(toybuf, O_RDONLY); - while ((line = get_line(tvar))) { - char *s = line; - - if (strstart(&s, "RFKILL_NAME=")) name = xstrdup(s); - else if (strstart(&s, "RFKILL_TYPE=")) type = xstrdup(s); - - free(line); - } - xclose(tvar); - - xprintf("%u: %s: %s\n", rfevent.idx, name, type); - xprintf("\tSoft blocked: %s\n", rfevent.soft ? "yes" : "no"); - xprintf("\tHard blocked: %s\n", rfevent.hard ? "yes" : "no"); - free(name); - free(type); - } - } - xclose(fd); -} diff --git a/toys/pending/netstat.c b/toys/pending/netstat.c deleted file mode 100644 index c7ab62d0..00000000 --- a/toys/pending/netstat.c +++ /dev/null @@ -1,383 +0,0 @@ -/* netstat.c - Display Linux networking subsystem. - * - * Copyright 2012 Ranjan Kumar - * Copyright 2013 Kyungwan Han - * - * Not in SUSv4. - * -USE_NETSTAT(NEWTOY(netstat, "pWrxwutneal", TOYFLAG_BIN)) -config NETSTAT - bool "netstat" - default n - help - usage: netstat [-pWrxwutneal] - - Display networking information. Default is netsat -tuwx - - -r routing table - -a all sockets (not just connected) - -l listening server sockets - -t TCP sockets - -u UDP sockets - -w raw sockets - -x unix sockets - -e extended info - -n don't resolve names - -W wide display - -p PID/Program name of sockets -*/ - -#define FOR_netstat -#include "toys.h" -#include - -GLOBALS( - struct num_cache *inodes; - int wpad; -); - -// convert address into text format. -static void addr2str(int af, void *addr, unsigned port, char *buf, int len, - char *proto) -{ - int pos, count; - struct servent *ser = 0; - - // Convert to numeric address - if (!inet_ntop(af, addr, buf, 256)) { - *buf = 0; - - return; - } - buf[len] = 0; - pos = strlen(buf); - - // If there's no port number, it's a local :* binding, nothing to look up. - if (!port) { - if (len-pos<2) pos = len-2; - strcpy(buf+pos, ":*"); - - return; - } - - if (!(toys.optflags & FLAG_n)) { - struct addrinfo hints, *result, *rp; - char cut[4]; - - memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = af; - - if (!getaddrinfo(buf, NULL, &hints, &result)) { - socklen_t sock_len = (af == AF_INET) ? sizeof(struct sockaddr_in) - : sizeof(struct sockaddr_in6); - - // We assume that a failing getnameinfo dosn't stomp "buf" here. - for (rp = result; rp; rp = rp->ai_next) - if (!getnameinfo(rp->ai_addr, sock_len, buf, 256, 0, 0, 0)) break; - freeaddrinfo(result); - buf[len] = 0; - pos = strlen(buf); - } - - // Doesn't understand proto "tcp6", so truncate - memcpy(cut, proto, 3); - cut[3] = 0; - ser = getservbyport(htons(port), cut); - } - - // Append :service - count = snprintf(0, 0, ":%u", port); - if (ser) { - count = snprintf(0, 0, ":%s", ser->s_name); - // sheer paranoia - if (count>=len) { - count = len-1; - ser->s_name[count] = 0; - } - } - if (len-poss_name); - else sprintf(buf+pos, ":%u", port); -} - -// Display info for tcp/udp/raw -static void show_ip(char *fname) -{ - char *ss_state = "UNKNOWN", buf[12], *s, *label = strrchr(fname, '/')+1; - char *state_label[] = {"", "ESTABLISHED", "SYN_SENT", "SYN_RECV", "FIN_WAIT1", - "FIN_WAIT2", "TIME_WAIT", "CLOSE", "CLOSE_WAIT", - "LAST_ACK", "LISTEN", "CLOSING", "UNKNOWN"}; - struct passwd *pw; - FILE *fp = fopen(fname, "r"); - - if (!fp) { - perror_msg("'%s'", fname); - return; - } - - if(!fgets(toybuf, sizeof(toybuf), fp)) return; //skip header. - - while (fgets(toybuf, sizeof(toybuf), fp)) { - char lip[256], rip[256]; - union { - struct {unsigned u; unsigned char b[4];} i4; - struct {struct {unsigned a, b, c, d;} u; unsigned char b[16];} i6; - } laddr, raddr; - unsigned lport, rport, state, txq, rxq, num, uid, nitems; - unsigned long inode; - - // Try ipv6, then try ipv4 - nitems = sscanf(toybuf, - " %d: %8x%8x%8x%8x:%x %8x%8x%8x%8x:%x %x %x:%x %*X:%*X %*X %d %*d %ld", - &num, &laddr.i6.u.a, &laddr.i6.u.b, &laddr.i6.u.c, - &laddr.i6.u.d, &lport, &raddr.i6.u.a, &raddr.i6.u.b, - &raddr.i6.u.c, &raddr.i6.u.d, &rport, &state, &txq, &rxq, - &uid, &inode); - - if (nitems!=16) { - nitems = sscanf(toybuf, - " %d: %x:%x %x:%x %x %x:%x %*X:%*X %*X %d %*d %ld", - &num, &laddr.i4.u, &lport, &raddr.i4.u, &rport, &state, &txq, - &rxq, &uid, &inode); - - if (nitems!=10) continue; - nitems = AF_INET; - } else nitems = AF_INET6; - - // Should we display this? (listening or all or TCP/UDP/RAW) - if (!((toys.optflags & FLAG_l) && (!rport && (state & 0xA))) - && !(toys.optflags & FLAG_a) && !(rport & (0x10 | 0x20 | 0x40))) - continue; - - addr2str(nitems, &laddr, lport, lip, TT.wpad, label); - addr2str(nitems, &raddr, rport, rip, TT.wpad, label); - - // Display data - s = label; - if (strstart(&s, "tcp")) { - int sz = ARRAY_LEN(state_label); - if (!state || state >= sz) state = sz-1; - ss_state = state_label[state]; - } else if (strstart(&s, "udp")) { - if (state == 1) ss_state = state_label[state]; - else if (state == 7) ss_state = ""; - } else if (strstart(&s, "raw")) sprintf(ss_state = buf, "%u", state); - - if (!(toys.optflags & FLAG_n) && (pw = bufgetpwuid(uid))) - snprintf(toybuf, sizeof(toybuf), "%s", pw->pw_name); - else snprintf(toybuf, sizeof(toybuf), "%d", uid); - - printf("%-6s%6d%7d ", label, rxq, txq); - printf("%*.*s %*.*s ", -TT.wpad, TT.wpad, lip, -TT.wpad, TT.wpad, rip); - printf("%-11s", ss_state); - if ((toys.optflags & FLAG_e)) printf(" %-10s %-11ld", toybuf, inode); - if ((toys.optflags & FLAG_p)) { - struct num_cache *nc = get_num_cache(TT.inodes, inode); - - printf(" %s", nc ? nc->data : "-"); - } - xputc('\n'); - } - fclose(fp); -} - -static void show_unix_sockets(void) -{ - char *types[] = {"","STREAM","DGRAM","RAW","RDM","SEQPACKET","DCCP","PACKET"}, - *states[] = {"","LISTENING","CONNECTING","CONNECTED","DISCONNECTING"}, - *s, *ss; - unsigned long refcount, flags, type, state, inode; - FILE *fp = xfopen("/proc/net/unix", "r"); - - if(!fgets(toybuf, sizeof(toybuf), fp)) return; //skip header. - - while (fgets(toybuf, sizeof(toybuf), fp)) { - unsigned offset = 0; - - // count = 6 or 7 (first field ignored, sockets don't always have filenames) - if (6ARRAY_LEN(types)) type = 0; - if (state>ARRAY_LEN(states) || (state==1 && !flags)) state = 0; - sprintf(toybuf, "[ %s]", flags ? "ACC " : ""); - - printf("unix %-6ld %-11s %-10s %-13s %8lu ", - refcount, toybuf, types[type], states[state], inode); - if (toys.optflags & FLAG_p) { - struct num_cache *nc = get_num_cache(TT.inodes, inode); - - printf("%-19.19s", nc ? nc->data : "-"); - } - - if (offset) { - if ((ss = strrchr(s = toybuf+offset, '\n'))) *ss = 0; - printf("%s", s); - } - xputc('\n'); - } - - fclose(fp); -} - -static int scan_pids(struct dirtree *node) -{ - char *s = toybuf+256; - struct dirent *entry; - DIR *dp; - int pid, dirfd; - - if (!node->parent) return DIRTREE_RECURSE; - if (!(pid = atol(node->name))) return 0; - - sprintf(toybuf, "/proc/%d/cmdline", pid); - if (!(readfile(toybuf, toybuf, 256))) return 0; - - sprintf(s, "%d/fd", pid); - if (-1==(dirfd = openat(dirtree_parentfd(node), s, O_RDONLY))) return 0; - if (!(dp = fdopendir(dirfd))) { - close(dirfd); - - return 0; - } - - while ((entry = readdir(dp))) { - s = toybuf+256; - if (!readlinkat0(dirfd, entry->d_name, s, sizeof(toybuf)-256)) continue; - // Can the "[0000]:" happen in a modern kernel? - if (strstart(&s, "socket:[") || strstart(&s, "[0000]:")) { - long long ll = atoll(s); - - sprintf(s, "%d/%s", pid, getbasename(toybuf)); - add_num_cache(&TT.inodes, ll, s, strlen(s)+1); - } - } - closedir(dp); - - return 0; -} - -/* - * extract inet4 route info from /proc/net/route file and display it. - */ -static void display_routes(void) -{ - static const char flagchars[] = "GHRDMDAC"; - static const unsigned flagarray[] = { - RTF_GATEWAY, RTF_HOST, RTF_REINSTATE, RTF_DYNAMIC, RTF_MODIFIED - }; - unsigned long dest, gate, mask; - int flags, ref, use, metric, mss, win, irtt; - char *out = toybuf, *flag_val; - char iface[64]={0}; - FILE *fp = xfopen("/proc/net/route", "r"); - - if(!fgets(toybuf, sizeof(toybuf), fp)) return; //skip header. - - printf("Kernel IP routing table\n" - "Destination\tGateway \tGenmask \tFlags %s Iface\n", - !(toys.optflags&FLAG_e) ? " MSS Window irtt" : "Metric Ref Use"); - - while (fgets(toybuf, sizeof(toybuf), fp)) { - char *destip = 0, *gateip = 0, *maskip = 0; - - if (11 != sscanf(toybuf, "%63s%lx%lx%X%d%d%d%lx%d%d%d", iface, &dest, - &gate, &flags, &ref, &use, &metric, &mask, &mss, &win, &irtt)) - break; - - // skip down interfaces. - if (!(flags & RTF_UP)) continue; - -// TODO /proc/net/ipv6_route - - if (dest) { - if (inet_ntop(AF_INET, &dest, out, 16)) destip = out; - } else destip = (toys.optflags&FLAG_n) ? "0.0.0.0" : "default"; - out += 16; - - if (gate) { - if (inet_ntop(AF_INET, &gate, out, 16)) gateip = out; - } else gateip = (toys.optflags&FLAG_n) ? "0.0.0.0" : "*"; - out += 16; - -// TODO /24 - //For Mask - if (inet_ntop(AF_INET, &mask, out, 16)) maskip = out; - else maskip = "?"; - out += 16; - - //Get flag Values - flag_val = out; - *out++ = 'U'; - for (dest = 0; dest < ARRAY_LEN(flagarray); dest++) - if (flags&flagarray[dest]) *out++ = flagchars[dest]; - *out = 0; - if (flags & RTF_REJECT) *flag_val = '!'; - - printf("%-15.15s %-15.15s %-16s%-6s", destip, gateip, maskip, flag_val); - if (!(toys.optflags & FLAG_e)) - printf("%5d %-5d %6d %s\n", mss, win, irtt, iface); - else printf("%-6d %-2d %7d %s\n", metric, ref, use, iface); - } - - fclose(fp); -} - -void netstat_main(void) -{ - int tuwx = FLAG_t|FLAG_u|FLAG_w|FLAG_x; - char *type = "w/o"; - - TT.wpad = (toys.optflags&FLAG_W) ? 51 : 23; - if (!(toys.optflags&(FLAG_r|tuwx))) toys.optflags |= tuwx; - if (toys.optflags & FLAG_r) display_routes(); - if (!(toys.optflags&tuwx)) return; - - if (toys.optflags & FLAG_a) type = "established and"; - else if (toys.optflags & FLAG_l) type = "only"; - - if (toys.optflags & FLAG_p) dirtree_read("/proc", scan_pids); - - if (toys.optflags&(FLAG_t|FLAG_u|FLAG_w)) { - printf("Active %s (%s servers)\n", "Internet connections", type); - printf("Proto Recv-Q Send-Q %*s %*s State ", -TT.wpad, "Local Address", - -TT.wpad, "Foreign Address"); - if (toys.optflags & FLAG_e) printf(" User Inode "); - if (toys.optflags & FLAG_p) printf(" PID/Program Name"); - xputc('\n'); - - if (toys.optflags & FLAG_t) { - show_ip("/proc/net/tcp"); - show_ip("/proc/net/tcp6"); - } - if (toys.optflags & FLAG_u) { - show_ip("/proc/net/udp"); - show_ip("/proc/net/udp6"); - } - if (toys.optflags & FLAG_w) { - show_ip("/proc/net/raw"); - show_ip("/proc/net/raw6"); - } - } - - if (toys.optflags & FLAG_x) { - printf("Active %s (%s servers)\n", "UNIX domain sockets", type); - - printf("Proto RefCnt Flags\t Type\t State\t %s Path\n", - (toys.optflags&FLAG_p) ? "PID/Program Name" : "I-Node"); - show_unix_sockets(); - } - - if ((toys.optflags & FLAG_p) && CFG_TOYBOX_FREE) - llist_traverse(TT.inodes, free); - toys.exitval = 0; -} -- cgit v1.2.3