xref: /third_party/toybox/toys/net/ifconfig.c (revision 0f66f451)
1/* ifconfig.c - Configure network interface.
2 *
3 * Copyright 2012 Ranjan Kumar <ranjankumar.bth@gmail.com>
4 * Copyright 2012 Kyungwan Han <asura321@gamil.com>
5 * Reviewed by Kyungsu Kim <kaspyx@gmail.com>
6 *
7 * Not in SUSv4.
8 *
9 * Obsolete fields included for historical purposes:
10 * irq|io_addr|mem_start ADDR - micromanage obsolete hardware
11 * outfill|keepalive INTEGER - SLIP analog dialup line quality monitoring
12 * metric INTEGER - added to Linux 0.9.10 with comment "never used", still true
13
14USE_IFCONFIG(NEWTOY(ifconfig, "^?aS", TOYFLAG_SBIN))
15
16config IFCONFIG
17  bool "ifconfig"
18  default y
19  help
20    usage: ifconfig [-aS] [INTERFACE [ACTION...]]
21
22    Display or configure network interface.
23
24    With no arguments, display active interfaces. First argument is interface
25    to operate on, one argument by itself displays that interface.
26
27    -a	All interfaces displayed, not just active ones
28    -S	Short view, one line per interface
29
30    Standard ACTIONs to perform on an INTERFACE:
31
32    ADDR[/MASK]        - set IPv4 address (1.2.3.4/5) and activate interface
33    add|del ADDR[/LEN] - add/remove IPv6 address (1111::8888/128)
34    up|down            - activate or deactivate interface
35
36    Advanced ACTIONs (default values usually suffice):
37
38    default          - remove IPv4 address
39    netmask ADDR     - set IPv4 netmask via 255.255.255.0 instead of /24
40    txqueuelen LEN   - number of buffered packets before output blocks
41    mtu LEN          - size of outgoing packets (Maximum Transmission Unit)
42    broadcast ADDR   - Set broadcast address
43    pointopoint ADDR - PPP and PPPOE use this instead of "route add default gw"
44    hw TYPE ADDR     - set hardware (mac) address (type = ether|infiniband)
45
46    Flags you can set on an interface (or -remove by prefixing with -):
47
48    arp       - don't use Address Resolution Protocol to map LAN routes
49    promisc   - don't discard packets that aren't to this LAN hardware address
50    multicast - force interface into multicast mode if the driver doesn't
51    allmulti  - promisc for multicast packets
52*/
53
54#define FOR_ifconfig
55#include "toys.h"
56
57#include <net/if_arp.h>
58#include <net/ethernet.h>
59
60GLOBALS(
61  int sockfd;
62)
63
64// Convert hostname to binary address for AF_INET or AF_INET6
65// return /prefix (or range max if none)
66static int get_addrinfo(char *host, sa_family_t af, void *addr)
67{
68  struct addrinfo hints, *result, *rp = 0;
69  int status, len;
70  char *from, *slash;
71
72  memset(&hints, 0 , sizeof(struct addrinfo));
73  hints.ai_family = af;
74  hints.ai_socktype = SOCK_STREAM;
75
76  slash = strchr(host, '/');
77  if (slash) *slash = 0;
78
79  status = getaddrinfo(host, NULL, &hints, &result);
80  if (!status)
81    for (rp = result; rp; rp = rp->ai_next)
82      if (rp->ai_family == af) break;
83  if (!rp) error_exit("bad address '%s' : %s", host, gai_strerror(status));
84
85  // ai_addr isn't struct in_addr or in6_addr, it's struct sockaddr. Of course.
86  // You'd think ipv4 and ipv6 would have some basic compatibility, but no.
87  from = ((char *)rp->ai_addr) + 4;
88  if (af == AF_INET6) {
89    len = 16;
90    from += 4;  // skip "flowinfo" field ipv6 puts before address
91  } else len = 4;
92  memcpy(addr, from, len);
93  freeaddrinfo(result);
94
95  len = -1;
96  if (slash) len = atolx_range(slash+1, 0, (af == AF_INET) ? 32 : 128);
97
98  return len;
99}
100
101static void display_ifconfig(char *name, int always, unsigned long long val[])
102{
103  struct ifreq ifre;
104  struct sockaddr_in *si = (void *)&ifre.ifr_addr;
105  struct {
106    int type;
107    char *title;
108  } types[] = {
109    {ARPHRD_LOOPBACK, "Local Loopback"}, {ARPHRD_ETHER, "Ethernet"},
110    {ARPHRD_PPP, "Point-to-Point Protocol"}, {ARPHRD_INFINIBAND, "InfiniBand"},
111    {ARPHRD_SIT, "IPv6-in-IPv4"}, {-1, "UNSPEC"}
112  };
113  int i;
114  char *pp;
115  FILE *fp;
116  short flags;
117
118  xstrncpy(ifre.ifr_name, name, IFNAMSIZ);
119  if (ioctl(TT.sockfd, SIOCGIFFLAGS, &ifre)<0) perror_exit_raw(name);
120  flags = ifre.ifr_flags;
121  if (!always && !(flags & IFF_UP)) return;
122
123  if (toys.optflags&FLAG_S) {
124    unsigned uu = 0;
125    int len;
126
127    ioctl(TT.sockfd, SIOCGIFADDR, &ifre);
128    len = printf("%*s %s", -9, name, inet_ntoa(si->sin_addr));
129    if (!ioctl(TT.sockfd, SIOCGIFNETMASK, &ifre))
130      uu = htonl(*(unsigned *)&(si->sin_addr));
131    for (i = 0; uu; i++) uu <<= 1;
132    len += printf("/%d", i);
133    printf("%*c", 29-len, ' ');
134  }
135
136  // Query hardware type and hardware address.
137  // Not xioctl because you don't have permission for this on Android.
138  ioctl(TT.sockfd, SIOCGIFHWADDR, &ifre);
139
140  if (toys.optflags&FLAG_S)
141    for (i=0; i<6; i++) printf(":%02x"+!i, ifre.ifr_hwaddr.sa_data[i]);
142  else {
143    for (i=0; i < ARRAY_LEN(types)-1; i++)
144      if (ifre.ifr_hwaddr.sa_family == types[i].type) break;
145    xprintf("%-9s Link encap:%s  ", name, types[i].title);
146    if(ifre.ifr_hwaddr.sa_family == ARPHRD_ETHER) {
147      xprintf("HWaddr ");
148      for (i=0; i<6; i++) xprintf(":%02x"+!i, ifre.ifr_hwaddr.sa_data[i]);
149    }
150    sprintf(toybuf, "/sys/class/net/%.15s/device/driver", name);
151    if (readlink0(toybuf, toybuf, sizeof(toybuf))>0)
152      if ((pp = strrchr(toybuf, '/'))) xprintf("  Driver %s", pp+1);
153    xputc('\n');
154  }
155
156  // If an address is assigned record that.
157
158  ifre.ifr_addr.sa_family = AF_INET;
159  memset(&ifre.ifr_addr, 0, sizeof(ifre.ifr_addr));
160  ioctl(TT.sockfd, SIOCGIFADDR, &ifre);
161  pp = (char *)&ifre.ifr_addr;
162  for (i = 0; i<sizeof(ifre.ifr_addr); i++) if (pp[i]) break;
163
164  if (!(toys.optflags&FLAG_S) && i != sizeof(ifre.ifr_addr)) {
165    struct sockaddr_in *si = (struct sockaddr_in *)&ifre.ifr_addr;
166    struct {
167      char *name;
168      int flag, ioctl;
169    } addr[] = {
170      {"addr", 0, 0},
171      {"P-t-P", IFF_POINTOPOINT, SIOCGIFDSTADDR},
172      {"Bcast", IFF_BROADCAST, SIOCGIFBRDADDR},
173      {"Mask", 0, SIOCGIFNETMASK}
174    };
175
176    // TODO: can this be ipv6? Why are we checking here when ipv6 source later?
177    xprintf("%10c%s", ' ', (si->sin_family == AF_INET) ? "inet" :
178        (si->sin_family == AF_INET6) ? "inet6" : "unspec");
179
180    for (i=0; i<ARRAY_LEN(addr); i++) {
181      if (!addr[i].flag || (flags & addr[i].flag)) {
182        if (addr[i].ioctl && ioctl(TT.sockfd, addr[i].ioctl, &ifre))
183          si->sin_family = 0;
184        xprintf(" %s:%s ", addr[i].name,
185          (si->sin_family == 0xFFFF || !si->sin_family)
186            ? "[NOT SET]" : inet_ntoa(si->sin_addr));
187      }
188    }
189
190    xputc('\n');
191  }
192
193  fp = fopen(pp = "/proc/net/if_inet6", "r");
194  if (fp) {
195    char iface_name[IFNAMSIZ];
196    int plen, iscope;
197
198    while (fgets(toybuf, sizeof(toybuf), fp)) {
199      int nitems;
200      char ipv6_addr[40];
201
202      nitems = sscanf(toybuf, "%32s %*08x %02x %02x %*02x %15s\n",
203                      ipv6_addr, &plen, &iscope, iface_name);
204      if (nitems<0 && feof(fp)) break;
205      if (nitems != 4) perror_exit("bad %s", pp);
206
207      if (!strcmp(name, iface_name)) {
208        struct sockaddr_in6 s6;
209        char *ptr = ipv6_addr+sizeof(ipv6_addr)-1;
210
211        // convert giant hex string into colon-spearated ipv6 address by
212        // inserting ':' every 4 characters.
213        for (i = 32; i; i--)
214          if ((*(ptr--) = ipv6_addr[i])) if (!(i&3)) *(ptr--) = ':';
215
216        // Convert to binary and back to get abbreviated :: version
217        if (inet_pton(AF_INET6, ipv6_addr, (void *)&s6.sin6_addr) > 0) {
218          if (inet_ntop(AF_INET6, &s6.sin6_addr, toybuf, sizeof(toybuf))) {
219            char *scopes[] = {"Global","Host","Link","Site","Compat"},
220                 *scope = "Unknown";
221
222            for (i=0; i<ARRAY_LEN(scopes); i++)
223              if (iscope == (!!i)<<(i+3)) scope = scopes[i];
224            if (toys.optflags&FLAG_S) xprintf(" %s/%d@%c", toybuf, plen,*scope);
225            else xprintf("%10cinet6 addr: %s/%d Scope: %s\n",
226                         ' ', toybuf, plen, scope);
227          }
228        }
229      }
230    }
231    fclose(fp);
232  }
233
234  if (toys.optflags&FLAG_S) {
235    xputc('\n');
236    return;
237  }
238
239  xprintf("%10c", ' ');
240
241  if (flags) {
242    unsigned short mask = 1;
243    char **s, *str[] = {
244      "UP", "BROADCAST", "DEBUG", "LOOPBACK", "POINTOPOINT", "NOTRAILERS",
245      "RUNNING", "NOARP", "PROMISC", "ALLMULTI", "MASTER", "SLAVE", "MULTICAST",
246      "PORTSEL", "AUTOMEDIA", "DYNAMIC", NULL
247    };
248
249    for (s = str; *s; s++) {
250      if (flags & mask) xprintf("%s ", *s);
251      mask <<= 1;
252    }
253  } else xprintf("[NO FLAGS] ");
254
255  if (ioctl(TT.sockfd, SIOCGIFMTU, &ifre) < 0) ifre.ifr_mtu = 0;
256  xprintf(" MTU:%d", ifre.ifr_mtu);
257  if (ioctl(TT.sockfd, SIOCGIFMETRIC, &ifre) < 0) ifre.ifr_metric = 0;
258  if (!ifre.ifr_metric) ifre.ifr_metric = 1;
259  xprintf("  Metric:%d", ifre.ifr_metric);
260
261  // non-virtual interface
262
263  if (val) {
264    char *label[] = {"RX bytes", "RX packets", "errors", "dropped", "overruns",
265      "frame", 0, 0, "TX bytes", "TX packets", "errors", "dropped", "overruns",
266      "collisions", "carrier", 0, "txqueuelen"};
267    signed char order[] = {-1, 1, 2, 3, 4, 5, -1, 9, 10, 11, 12, 14, -1,
268      13, 16, -1, 0, 8};
269    int i;
270
271    // Query txqueuelen
272    if (ioctl(TT.sockfd, SIOCGIFTXQLEN, &ifre) >= 0) val[16] = ifre.ifr_qlen;
273    else val[16] = -1;
274
275    for (i = 0; i<sizeof(order); i++) {
276      int j = order[i];
277
278      if (j < 0) xprintf("\n%10c", ' ');
279      else xprintf("%s:%llu ", label[j], val[j]);
280    }
281  }
282  xputc('\n');
283
284  if(!ioctl(TT.sockfd, SIOCGIFMAP, &ifre) && (ifre.ifr_map.irq ||
285      ifre.ifr_map.mem_start || ifre.ifr_map.dma || ifre.ifr_map.base_addr))
286  {
287    xprintf("%10c", ' ');
288    if(ifre.ifr_map.irq) xprintf("Interrupt:%d ", ifre.ifr_map.irq);
289    if(ifre.ifr_map.base_addr >= 0x100) // IO_MAP_INDEX
290      xprintf("Base address:0x%x ", ifre.ifr_map.base_addr);
291    if(ifre.ifr_map.mem_start)
292      xprintf("Memory:%lx-%lx ", ifre.ifr_map.mem_start, ifre.ifr_map.mem_end);
293    if(ifre.ifr_map.dma) xprintf("DMA chan:%x ", ifre.ifr_map.dma);
294    xputc('\n');
295  }
296  xputc('\n');
297}
298
299static void show_iface(char *iface_name)
300{
301  char *name;
302  struct string_list *ifaces = 0, *sl;
303  int i, j;
304  FILE *fp;
305
306  fp = xfopen("/proc/net/dev", "r");
307
308  for (i=0; fgets(toybuf, sizeof(toybuf), fp); i++) {
309    char *buf = toybuf;
310    unsigned long long val[17];
311
312    if (i<2) continue;
313
314    while (isspace(*buf)) buf++;
315    name = strsep(&buf, ":");
316    if(!buf) error_exit("bad name %s", name);
317
318    errno = 0;
319    for (j=0; j<16 && !errno; j++) val[j] = strtoll(buf, &buf, 0);
320    if (errno) perror_exit("bad %s at %s", name, buf);
321
322    if (iface_name) {
323      if (!strcmp(iface_name, name)) {
324        display_ifconfig(iface_name, 1, val);
325
326        return;
327      }
328    } else {
329      sl = xmalloc(sizeof(*sl)+strlen(name)+1);
330      strcpy(sl->str, name);
331      sl->next = ifaces;
332      ifaces = sl;
333
334      display_ifconfig(sl->str, toys.optflags & FLAG_a, val);
335    }
336  }
337  fclose(fp);
338
339  if (iface_name) display_ifconfig(iface_name, 1, 0);
340  else {
341    struct ifconf ifcon;
342    struct ifreq *ifre;
343    int num;
344
345    // Loop until buffer's big enough
346    ifcon.ifc_buf = NULL;
347    for (num = 30;;num += 10) {
348      ifcon.ifc_len = sizeof(struct ifreq)*num;
349      ifcon.ifc_buf = xrealloc(ifcon.ifc_buf, ifcon.ifc_len);
350      xioctl(TT.sockfd, SIOCGIFCONF, &ifcon);
351      if (ifcon.ifc_len != sizeof(struct ifreq)*num) break;
352    }
353
354    ifre = ifcon.ifc_req;
355    for(num = 0; num < ifcon.ifc_len && ifre; num += sizeof(struct ifreq), ifre++)
356    {
357      // Skip duplicates
358      for(sl = ifaces; sl; sl = sl->next)
359        if(!strcmp(sl->str, ifre->ifr_name)) break;
360
361      if(!sl) display_ifconfig(ifre->ifr_name, toys.optflags & FLAG_a, 0);
362    }
363
364    free(ifcon.ifc_buf);
365  }
366
367  llist_traverse(ifaces, free);
368}
369
370// Encode offset and size of field into an int, and make result negative
371#define IFREQ_OFFSZ(x) -(int)((offsetof(struct ifreq, x)<<16) + sizeof(ifre.x))
372
373void ifconfig_main(void)
374{
375  char **argv = toys.optargs;
376  struct ifreq ifre;
377  int i;
378
379  TT.sockfd = xsocket(AF_INET, SOCK_DGRAM, 0);
380  if(toys.optc < 2) {
381    show_iface(*argv);
382    return;
383  }
384
385  // Open interface
386  memset(&ifre, 0, sizeof(struct ifreq));
387  xstrncpy(ifre.ifr_name, *argv, IFNAMSIZ);
388
389  // Perform operations on interface
390  while(*++argv) {
391    // Table of known operations
392    struct argh {
393      char *name;
394      int on, off; // set, clear
395    } try[] = {
396      {0, IFF_UP|IFF_RUNNING, SIOCSIFADDR},
397      {"up", IFF_UP|IFF_RUNNING, 0},
398      {"down", 0, IFF_UP},
399      {"arp", 0, IFF_NOARP},
400      {"promisc", IFF_PROMISC, 0},
401      {"allmulti", IFF_ALLMULTI, 0},
402      {"multicast", IFF_MULTICAST, 0},
403      {"pointopoint", IFF_POINTOPOINT, SIOCSIFDSTADDR},
404      {"broadcast", IFF_BROADCAST, SIOCSIFBRDADDR},
405      {"netmask", 0, SIOCSIFNETMASK},
406      {"dstaddr", 0, SIOCSIFDSTADDR},
407      {"mtu", IFREQ_OFFSZ(ifr_mtu), SIOCSIFMTU},
408      {"keepalive", IFREQ_OFFSZ(ifr_data), SIOCDEVPRIVATE}, // SIOCSKEEPALIVE
409      {"outfill", IFREQ_OFFSZ(ifr_data), SIOCDEVPRIVATE+2}, // SIOCSOUTFILL
410      {"metric", IFREQ_OFFSZ(ifr_metric), SIOCSIFMETRIC},
411      {"txqueuelen", IFREQ_OFFSZ(ifr_qlen), SIOCSIFTXQLEN},
412      {"mem_start", IFREQ_OFFSZ(ifr_map.mem_start), SIOCSIFMAP},
413      {"io_addr", IFREQ_OFFSZ(ifr_map.base_addr), SIOCSIFMAP},
414      {"irq", IFREQ_OFFSZ(ifr_map.irq), SIOCSIFMAP},
415      {"inet", 0, 0},
416      {"inet6", 0, 0}
417    };
418    char *s = *argv;
419    int rev = (*s == '-');
420
421    s += rev;
422
423    // "set hardware address" is oddball enough to special case
424    if (!strcmp(*argv, "hw")) {
425      char *hw_addr, *ptr, *p;
426      struct sockaddr *sock = &ifre.ifr_hwaddr;
427      int count = 6;
428
429      ptr = p = (char *)sock->sa_data;
430      memset(sock, 0, sizeof(struct sockaddr));
431      if (argv[1]) {
432        if (!strcmp("ether", *++argv)) sock->sa_family = ARPHRD_ETHER;
433        else if (!strcmp("infiniband", *argv)) {
434          sock->sa_family = ARPHRD_INFINIBAND;
435          count = 20;
436          p = ptr = toybuf;
437        }
438      }
439      if (!sock->sa_family || !argv[1]) help_exit("bad hw '%s'", *argv);
440      hw_addr = *++argv;
441
442      // Parse and verify address.
443      while (*hw_addr && (p-ptr) < count) {
444        int val, len = 0;
445
446        if (*hw_addr == ':') hw_addr++;
447        sscanf(hw_addr, "%2x%n", &val, &len);
448        if (!len || len > 2) break; // 1 nibble can be set e.g. C2:79:38:95:D:A
449        hw_addr += len;
450        *p++ = val;
451      }
452
453      if ((p-ptr) != count || *hw_addr)
454        error_exit("bad hw-addr '%s'", *argv);
455
456      // the linux kernel's "struct sockaddr" (include/linux/socket.h in the
457      // kernel source) only has 14 bytes of sa_data, and an infiniband address
458      // is 20. So if we go through the ioctl, the kernel will truncate
459      // infiniband addresses, meaning we have to go through sysfs instead.
460      if (sock->sa_family == ARPHRD_INFINIBAND && !strchr(ifre.ifr_name, '/')) {
461        int fd;
462
463        sprintf(toybuf, "/sys/class/net/%s/address", ifre.ifr_name);
464        fd = xopen(toybuf, O_RDWR);
465        xwrite(fd, *argv, strlen(*argv));
466        close(fd);
467      } else xioctl(TT.sockfd, SIOCSIFHWADDR, &ifre);
468      continue;
469
470    // Add/remove ipv6 address to interface
471
472    } else if (!strcmp(*argv, "add") || !strcmp(*argv, "del")) {
473      struct ifreq_inet6 {
474        struct in6_addr addr;
475        unsigned prefix;
476        int index;
477      } ifre6;
478      int plen, fd6 = xsocket(AF_INET6, SOCK_DGRAM, 0);
479
480      if (!argv[1]) help_exit("%s", *argv);
481
482      plen = get_addrinfo(argv[1], AF_INET6, &ifre6.addr);
483      if (plen < 0) plen = 128;
484      xioctl(fd6, SIOCGIFINDEX, &ifre);
485      ifre6.index = ifre.ifr_ifindex;
486      ifre6.prefix = plen;
487      xioctl(fd6, **(argv++)=='a' ? SIOCSIFADDR : SIOCDIFADDR, &ifre6);
488
489      close(fd6);
490      continue;
491    // Iterate through table to find/perform operation
492    } else for (i = 0; i<ARRAY_LEN(try); i++) {
493      struct argh *t = try+i;
494      int on = t->on, off = t->off;
495
496      if (!t->name) {
497        if (isdigit(**argv) || !strcmp(*argv, "default")) argv--;
498        else continue;
499      } else if (strcmp(t->name, s)) continue;
500
501      // Is this an SIOCSI entry?
502      if ((off|0xff) == 0x89ff) {
503        if (!rev) {
504          if (!*++argv) error_exit("%s needs argument", t->name);
505
506          // Assign value to ifre field and call ioctl? (via IFREQ_OFFSZ.)
507          if (on < 0) {
508            long l = strtoul(*argv, 0, 0);
509
510            if (off == SIOCSIFMAP) xioctl(TT.sockfd, SIOCGIFMAP, &ifre);
511            on = -on;
512            poke((on>>16) + (char *)&ifre, l, on&15);
513            xioctl(TT.sockfd, off, &ifre);
514            break;
515          } else {
516            struct sockaddr_in *si = (struct sockaddr_in *)&ifre.ifr_addr;
517            int mask = -1;
518
519            si->sin_family = AF_INET;
520
521            if (!strcmp(*argv, "default")) si->sin_addr.s_addr = INADDR_ANY;
522            else mask = get_addrinfo(*argv, AF_INET, &si->sin_addr);
523            xioctl(TT.sockfd, off, &ifre);
524
525            // Handle /netmask
526            if (mask >= 0) {
527              // sin_addr probably isn't unaligned, but just in case...
528              mask = htonl((~0)<<(32-mask));
529              memcpy(&si->sin_addr, &mask, 4);
530              xioctl(TT.sockfd, SIOCSIFNETMASK, &ifre);
531            }
532          }
533        }
534        off = 0;
535      }
536
537      // Set flags
538      if (on || off) {
539        xioctl(TT.sockfd, SIOCGIFFLAGS, &ifre);
540        ifre.ifr_flags &= ~(rev ? on : off);
541        ifre.ifr_flags |= (rev ? off : on);
542        xioctl(TT.sockfd, SIOCSIFFLAGS, &ifre);
543      }
544
545      break;
546    }
547    if (i == ARRAY_LEN(try)) help_exit("bad argument '%s'", *argv);
548  }
549  close(TT.sockfd);
550}
551