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
14 USE_IFCONFIG(NEWTOY(ifconfig, "^?aS", TOYFLAG_SBIN))
15
16 config 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
GLOBALS(int sockfd;)60 GLOBALS(
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)
66 static 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
display_ifconfig(char * name,int always,unsigned long long val[])101 static 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 xioctl(TT.sockfd, SIOCGIFHWADDR, &ifre);
138
139 if (toys.optflags&FLAG_S)
140 for (i=0; i<6; i++) printf(":%02x"+!i, ifre.ifr_hwaddr.sa_data[i]);
141 else {
142 for (i=0; i < ARRAY_LEN(types)-1; i++)
143 if (ifre.ifr_hwaddr.sa_family == types[i].type) break;
144 xprintf("%-9s Link encap:%s ", name, types[i].title);
145 if(ifre.ifr_hwaddr.sa_family == ARPHRD_ETHER) {
146 xprintf("HWaddr ");
147 for (i=0; i<6; i++) xprintf(":%02x"+!i, ifre.ifr_hwaddr.sa_data[i]);
148 }
149 sprintf(toybuf, "/sys/class/net/%.15s/device/driver", name);
150 if (readlink0(toybuf, toybuf, sizeof(toybuf))>0)
151 if ((pp = strrchr(toybuf, '/'))) xprintf(" Driver %s", pp+1);
152 xputc('\n');
153 }
154
155 // If an address is assigned record that.
156
157 ifre.ifr_addr.sa_family = AF_INET;
158 memset(&ifre.ifr_addr, 0, sizeof(ifre.ifr_addr));
159 ioctl(TT.sockfd, SIOCGIFADDR, &ifre);
160 pp = (char *)&ifre.ifr_addr;
161 for (i = 0; i<sizeof(ifre.ifr_addr); i++) if (pp[i]) break;
162
163 if (!(toys.optflags&FLAG_S) && i != sizeof(ifre.ifr_addr)) {
164 struct sockaddr_in *si = (struct sockaddr_in *)&ifre.ifr_addr;
165 struct {
166 char *name;
167 int flag, ioctl;
168 } addr[] = {
169 {"addr", 0, 0},
170 {"P-t-P", IFF_POINTOPOINT, SIOCGIFDSTADDR},
171 {"Bcast", IFF_BROADCAST, SIOCGIFBRDADDR},
172 {"Mask", 0, SIOCGIFNETMASK}
173 };
174
175 // TODO: can this be ipv6? Why are we checking here when ipv6 source later?
176 xprintf("%10c%s", ' ', (si->sin_family == AF_INET) ? "inet" :
177 (si->sin_family == AF_INET6) ? "inet6" : "unspec");
178
179 for (i=0; i<ARRAY_LEN(addr); i++) {
180 if (!addr[i].flag || (flags & addr[i].flag)) {
181 if (addr[i].ioctl && ioctl(TT.sockfd, addr[i].ioctl, &ifre))
182 si->sin_family = 0;
183 xprintf(" %s:%s ", addr[i].name,
184 (si->sin_family == 0xFFFF || !si->sin_family)
185 ? "[NOT SET]" : inet_ntoa(si->sin_addr));
186 }
187 }
188
189 xputc('\n');
190 }
191
192 fp = fopen(pp = "/proc/net/if_inet6", "r");
193 if (fp) {
194 char iface_name[IFNAMSIZ];
195 int plen, iscope;
196
197 while (fgets(toybuf, sizeof(toybuf), fp)) {
198 int nitems;
199 char ipv6_addr[40];
200
201 nitems = sscanf(toybuf, "%32s %*08x %02x %02x %*02x %15s\n",
202 ipv6_addr, &plen, &iscope, iface_name);
203 if (nitems<0 && feof(fp)) break;
204 if (nitems != 4) perror_exit("bad %s", pp);
205
206 if (!strcmp(name, iface_name)) {
207 struct sockaddr_in6 s6;
208 char *ptr = ipv6_addr+sizeof(ipv6_addr)-1;
209
210 // convert giant hex string into colon-spearated ipv6 address by
211 // inserting ':' every 4 characters.
212 for (i = 32; i; i--)
213 if ((*(ptr--) = ipv6_addr[i])) if (!(i&3)) *(ptr--) = ':';
214
215 // Convert to binary and back to get abbreviated :: version
216 if (inet_pton(AF_INET6, ipv6_addr, (void *)&s6.sin6_addr) > 0) {
217 if (inet_ntop(AF_INET6, &s6.sin6_addr, toybuf, sizeof(toybuf))) {
218 char *scopes[] = {"Global","Host","Link","Site","Compat"},
219 *scope = "Unknown";
220
221 for (i=0; i<ARRAY_LEN(scopes); i++)
222 if (iscope == (!!i)<<(i+3)) scope = scopes[i];
223 if (toys.optflags&FLAG_S) xprintf(" %s/%d@%c", toybuf, plen,*scope);
224 else xprintf("%10cinet6 addr: %s/%d Scope: %s\n",
225 ' ', toybuf, plen, scope);
226 }
227 }
228 }
229 }
230 fclose(fp);
231 }
232
233 if (toys.optflags&FLAG_S) {
234 xputc('\n');
235 return;
236 }
237
238 xprintf("%10c", ' ');
239
240 if (flags) {
241 unsigned short mask = 1;
242 char **s, *str[] = {
243 "UP", "BROADCAST", "DEBUG", "LOOPBACK", "POINTOPOINT", "NOTRAILERS",
244 "RUNNING", "NOARP", "PROMISC", "ALLMULTI", "MASTER", "SLAVE", "MULTICAST",
245 "PORTSEL", "AUTOMEDIA", "DYNAMIC", NULL
246 };
247
248 for (s = str; *s; s++) {
249 if (flags & mask) xprintf("%s ", *s);
250 mask = mask << 1;
251 }
252 } else xprintf("[NO FLAGS] ");
253
254 if (ioctl(TT.sockfd, SIOCGIFMTU, &ifre) < 0) ifre.ifr_mtu = 0;
255 xprintf(" MTU:%d", ifre.ifr_mtu);
256 if (ioctl(TT.sockfd, SIOCGIFMETRIC, &ifre) < 0) ifre.ifr_metric = 0;
257 if (!ifre.ifr_metric) ifre.ifr_metric = 1;
258 xprintf(" Metric:%d", ifre.ifr_metric);
259
260 // non-virtual interface
261
262 if (val) {
263 char *label[] = {"RX bytes", "RX packets", "errors", "dropped", "overruns",
264 "frame", 0, 0, "TX bytes", "TX packets", "errors", "dropped", "overruns",
265 "collisions", "carrier", 0, "txqueuelen"};
266 signed char order[] = {-1, 1, 2, 3, 4, 5, -1, 9, 10, 11, 12, 14, -1,
267 13, 16, -1, 0, 8};
268 int i;
269
270 // Query txqueuelen
271 if (ioctl(TT.sockfd, SIOCGIFTXQLEN, &ifre) >= 0) val[16] = ifre.ifr_qlen;
272 else val[16] = -1;
273
274 for (i = 0; i<sizeof(order); i++) {
275 int j = order[i];
276
277 if (j < 0) xprintf("\n%10c", ' ');
278 else xprintf("%s:%llu ", label[j], val[j]);
279 }
280 }
281 xputc('\n');
282
283 if(!ioctl(TT.sockfd, SIOCGIFMAP, &ifre) && (ifre.ifr_map.irq ||
284 ifre.ifr_map.mem_start || ifre.ifr_map.dma || ifre.ifr_map.base_addr))
285 {
286 xprintf("%10c", ' ');
287 if(ifre.ifr_map.irq) xprintf("Interrupt:%d ", ifre.ifr_map.irq);
288 if(ifre.ifr_map.base_addr >= 0x100) // IO_MAP_INDEX
289 xprintf("Base address:0x%x ", ifre.ifr_map.base_addr);
290 if(ifre.ifr_map.mem_start)
291 xprintf("Memory:%lx-%lx ", ifre.ifr_map.mem_start, ifre.ifr_map.mem_end);
292 if(ifre.ifr_map.dma) xprintf("DMA chan:%x ", ifre.ifr_map.dma);
293 xputc('\n');
294 }
295 xputc('\n');
296 }
297
show_iface(char * iface_name)298 static void show_iface(char *iface_name)
299 {
300 char *name;
301 struct string_list *ifaces = 0, *sl;
302 int i, j;
303 FILE *fp;
304
305 fp = xfopen("/proc/net/dev", "r");
306
307 for (i=0; fgets(toybuf, sizeof(toybuf), fp); i++) {
308 char *buf = toybuf;
309 unsigned long long val[17];
310
311 if (i<2) continue;
312
313 while (isspace(*buf)) buf++;
314 name = strsep(&buf, ":");
315 if(!buf) error_exit("bad name %s", name);
316
317 errno = 0;
318 for (j=0; j<16 && !errno; j++) val[j] = strtoll(buf, &buf, 0);
319 if (errno) perror_exit("bad %s at %s", name, buf);
320
321 if (iface_name) {
322 if (!strcmp(iface_name, name)) {
323 display_ifconfig(iface_name, 1, val);
324
325 return;
326 }
327 } else {
328 sl = xmalloc(sizeof(*sl)+strlen(name)+1);
329 strcpy(sl->str, name);
330 sl->next = ifaces;
331 ifaces = sl;
332
333 display_ifconfig(sl->str, toys.optflags & FLAG_a, val);
334 }
335 }
336 fclose(fp);
337
338 if (iface_name) display_ifconfig(iface_name, 1, 0);
339 else {
340 struct ifconf ifcon;
341 struct ifreq *ifre;
342 int num;
343
344 // Loop until buffer's big enough
345 ifcon.ifc_buf = NULL;
346 for (num = 30;;num += 10) {
347 ifcon.ifc_len = sizeof(struct ifreq)*num;
348 ifcon.ifc_buf = xrealloc(ifcon.ifc_buf, ifcon.ifc_len);
349 xioctl(TT.sockfd, SIOCGIFCONF, &ifcon);
350 if (ifcon.ifc_len != sizeof(struct ifreq)*num) break;
351 }
352
353 ifre = ifcon.ifc_req;
354 for(num = 0; num < ifcon.ifc_len && ifre; num += sizeof(struct ifreq), ifre++)
355 {
356 // Skip duplicates
357 for(sl = ifaces; sl; sl = sl->next)
358 if(!strcmp(sl->str, ifre->ifr_name)) break;
359
360 if(!sl) display_ifconfig(ifre->ifr_name, toys.optflags & FLAG_a, 0);
361 }
362
363 free(ifcon.ifc_buf);
364 }
365
366 llist_traverse(ifaces, free);
367 }
368
369 // Encode offset and size of field into an int, and make result negative
370 #define IFREQ_OFFSZ(x) -(int)((offsetof(struct ifreq, x)<<16) + sizeof(ifre.x))
371
ifconfig_main(void)372 void ifconfig_main(void)
373 {
374 char **argv = toys.optargs;
375 struct ifreq ifre;
376 int i;
377
378 TT.sockfd = xsocket(AF_INET, SOCK_DGRAM, 0);
379 if(toys.optc < 2) {
380 show_iface(*argv);
381 return;
382 }
383
384 // Open interface
385 memset(&ifre, 0, sizeof(struct ifreq));
386 xstrncpy(ifre.ifr_name, *argv, IFNAMSIZ);
387
388 // Perform operations on interface
389 while(*++argv) {
390 // Table of known operations
391 struct argh {
392 char *name;
393 int on, off; // set, clear
394 } try[] = {
395 {0, IFF_UP|IFF_RUNNING, SIOCSIFADDR},
396 {"up", IFF_UP|IFF_RUNNING, 0},
397 {"down", 0, IFF_UP},
398 {"arp", 0, IFF_NOARP},
399 {"promisc", IFF_PROMISC, 0},
400 {"allmulti", IFF_ALLMULTI, 0},
401 {"multicast", IFF_MULTICAST, 0},
402 {"pointopoint", IFF_POINTOPOINT, SIOCSIFDSTADDR},
403 {"broadcast", IFF_BROADCAST, SIOCSIFBRDADDR},
404 {"netmask", 0, SIOCSIFNETMASK},
405 {"dstaddr", 0, SIOCSIFDSTADDR},
406 {"mtu", IFREQ_OFFSZ(ifr_mtu), SIOCSIFMTU},
407 {"keepalive", IFREQ_OFFSZ(ifr_data), SIOCDEVPRIVATE}, // SIOCSKEEPALIVE
408 {"outfill", IFREQ_OFFSZ(ifr_data), SIOCDEVPRIVATE+2}, // SIOCSOUTFILL
409 {"metric", IFREQ_OFFSZ(ifr_metric), SIOCSIFMETRIC},
410 {"txqueuelen", IFREQ_OFFSZ(ifr_qlen), SIOCSIFTXQLEN},
411 {"mem_start", IFREQ_OFFSZ(ifr_map.mem_start), SIOCSIFMAP},
412 {"io_addr", IFREQ_OFFSZ(ifr_map.base_addr), SIOCSIFMAP},
413 {"irq", IFREQ_OFFSZ(ifr_map.irq), SIOCSIFMAP},
414 {"inet", 0, 0},
415 {"inet6", 0, 0}
416 };
417 char *s = *argv;
418 int rev = (*s == '-');
419
420 s += rev;
421
422 // "set hardware address" is oddball enough to special case
423 if (!strcmp(*argv, "hw")) {
424 char *hw_addr, *ptr, *p;
425 struct sockaddr *sock = &ifre.ifr_hwaddr;
426 int count = 6;
427
428 ptr = p = (char *)sock->sa_data;
429 memset(sock, 0, sizeof(struct sockaddr));
430 if (argv[1]) {
431 if (!strcmp("ether", *++argv)) sock->sa_family = ARPHRD_ETHER;
432 else if (!strcmp("infiniband", *argv)) {
433 sock->sa_family = ARPHRD_INFINIBAND;
434 count = 20;
435 p = ptr = toybuf;
436 }
437 }
438 if (!sock->sa_family || !argv[1]) help_exit("bad hw '%s'", *argv);
439 hw_addr = *++argv;
440
441 // Parse and verify address.
442 while (*hw_addr && (p-ptr) < count) {
443 int val, len = 0;
444
445 if (*hw_addr == ':') hw_addr++;
446 sscanf(hw_addr, "%2x%n", &val, &len);
447 if (!len || len > 2) break; // 1 nibble can be set e.g. C2:79:38:95:D:A
448 hw_addr += len;
449 *p++ = val;
450 }
451
452 if ((p-ptr) != count || *hw_addr)
453 error_exit("bad hw-addr '%s'", *argv);
454
455 // the linux kernel's "struct sockaddr" (include/linux/socket.h in the
456 // kernel source) only has 14 bytes of sa_data, and an infiniband address
457 // is 20. So if we go through the ioctl, the kernel will truncate
458 // infiniband addresses, meaning we have to go through sysfs instead.
459 if (sock->sa_family == ARPHRD_INFINIBAND && !strchr(ifre.ifr_name, '/')) {
460 int fd;
461
462 sprintf(toybuf, "/sys/class/net/%s/address", ifre.ifr_name);
463 fd = xopen(toybuf, O_RDWR);
464 xwrite(fd, *argv, strlen(*argv));
465 close(fd);
466 } else xioctl(TT.sockfd, SIOCSIFHWADDR, &ifre);
467 continue;
468
469 // Add/remove ipv6 address to interface
470
471 } else if (!strcmp(*argv, "add") || !strcmp(*argv, "del")) {
472 struct ifreq_inet6 {
473 struct in6_addr addr;
474 unsigned prefix;
475 int index;
476 } ifre6;
477 int plen, fd6 = xsocket(AF_INET6, SOCK_DGRAM, 0);
478
479 if (!argv[1]) help_exit("%s", *argv);
480
481 plen = get_addrinfo(argv[1], AF_INET6, &ifre6.addr);
482 if (plen < 0) plen = 128;
483 xioctl(fd6, SIOCGIFINDEX, &ifre);
484 ifre6.index = ifre.ifr_ifindex;
485 ifre6.prefix = plen;
486 xioctl(fd6, **(argv++)=='a' ? SIOCSIFADDR : SIOCDIFADDR, &ifre6);
487
488 close(fd6);
489 continue;
490 // Iterate through table to find/perform operation
491 } else for (i = 0; i<ARRAY_LEN(try); i++) {
492 struct argh *t = try+i;
493 int on = t->on, off = t->off;
494
495 if (!t->name) {
496 if (isdigit(**argv) || !strcmp(*argv, "default")) argv--;
497 else continue;
498 } else if (strcmp(t->name, s)) continue;
499
500 // Is this an SIOCSI entry?
501 if ((off|0xff) == 0x89ff) {
502 if (!rev) {
503 if (!*++argv) error_exit("%s needs argument", t->name);
504
505 // Assign value to ifre field and call ioctl? (via IFREQ_OFFSZ.)
506 if (on < 0) {
507 long l = strtoul(*argv, 0, 0);
508
509 if (off == SIOCSIFMAP) xioctl(TT.sockfd, SIOCGIFMAP, &ifre);
510 on = -on;
511 poke((on>>16) + (char *)&ifre, l, on&15);
512 xioctl(TT.sockfd, off, &ifre);
513 break;
514 } else {
515 struct sockaddr_in *si = (struct sockaddr_in *)&ifre.ifr_addr;
516 int mask = -1;
517
518 si->sin_family = AF_INET;
519
520 if (!strcmp(*argv, "default")) si->sin_addr.s_addr = INADDR_ANY;
521 else mask = get_addrinfo(*argv, AF_INET, &si->sin_addr);
522 xioctl(TT.sockfd, off, &ifre);
523
524 // Handle /netmask
525 if (mask >= 0) {
526 // sin_addr probably isn't unaligned, but just in case...
527 mask = htonl((~0)<<(32-mask));
528 memcpy(&si->sin_addr, &mask, 4);
529 xioctl(TT.sockfd, SIOCSIFNETMASK, &ifre);
530 }
531 }
532 }
533 off = 0;
534 }
535
536 // Set flags
537 if (on || off) {
538 xioctl(TT.sockfd, SIOCGIFFLAGS, &ifre);
539 ifre.ifr_flags &= ~(rev ? on : off);
540 ifre.ifr_flags |= (rev ? off : on);
541 xioctl(TT.sockfd, SIOCSIFFLAGS, &ifre);
542 }
543
544 break;
545 }
546 if (i == ARRAY_LEN(try)) help_exit("bad argument '%s'", *argv);
547 }
548 close(TT.sockfd);
549 }
550