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