Remove remaining libc5 support code
[oweals/busybox.git] / libbb / interface.c
1 /*
2  * stolen from net-tools-1.59 and stripped down for busybox by 
3  *                      Erik Andersen <andersen@codepoet.org>
4  *
5  * Heavily modified by Manuel Novoa III       Mar 12, 2001
6  *
7  * Pruned unused code using KEEP_UNUSED define.
8  * Added print_bytes_scaled function to reduce code size.
9  * Added some (potentially) missing defines.
10  * Improved display support for -a and for a named interface.
11  *
12  * -----------------------------------------------------------
13  *
14  * ifconfig   This file contains an implementation of the command
15  *              that either displays or sets the characteristics of
16  *              one or more of the system's networking interfaces.
17  *
18  * Version:     $Id: interface.c,v 1.17 2003/07/22 08:56:46 andersen Exp $
19  *
20  * Author:      Fred N. van Kempen, <waltje@uwalt.nl.mugnet.org>
21  *              and others.  Copyright 1993 MicroWalt Corporation
22  *
23  *              This program is free software; you can redistribute it
24  *              and/or  modify it under  the terms of  the GNU General
25  *              Public  License as  published  by  the  Free  Software
26  *              Foundation;  either  version 2 of the License, or  (at
27  *              your option) any later version.
28  *
29  * Patched to support 'add' and 'del' keywords for INET(4) addresses
30  * by Mrs. Brisby <mrs.brisby@nimh.org>
31  *
32  * {1.34} - 19980630 - Arnaldo Carvalho de Melo <acme@conectiva.com.br>
33  *                     - gettext instead of catgets for i18n
34  *          10/1998  - Andi Kleen. Use interface list primitives.       
35  *          20001008 - Bernd Eckenfels, Patch from RH for setting mtu 
36  *                      (default AF was wrong)
37  */
38
39 /* #define KEEP_UNUSED */
40
41 /* 
42  * 
43  * Protocol Families.
44  * 
45  */
46 #define HAVE_AFINET 1
47 #undef HAVE_AFIPX
48 #undef HAVE_AFATALK
49 #undef HAVE_AFNETROM
50 #undef HAVE_AFX25
51 #undef HAVE_AFECONET
52 #undef HAVE_AFASH
53
54 #ifdef CONFIG_FEATURE_IPV6
55 # define HAVE_AFINET6 1
56 #else
57 # undef HAVE_AFINET6
58 #endif
59
60 /* 
61  * 
62  * Device Hardware types.
63  * 
64  */
65 #define HAVE_HWETHER    1
66 #define HAVE_HWPPP      1
67 #undef HAVE_HWSLIP
68
69
70 #include "inet_common.h"
71 #include <stdio.h>
72 #include <errno.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <unistd.h>
76 #include <fcntl.h>
77 #include <ctype.h>
78 #include <sys/ioctl.h>
79 #include <sys/types.h>
80 #include <net/if.h>
81 #include <net/if_arp.h>
82 #include "libbb.h"
83
84 #define _(x) x
85 #define _PATH_PROCNET_DEV               "/proc/net/dev"
86 #define _PATH_PROCNET_IFINET6           "/proc/net/if_inet6"
87 #define new(p) ((p) = xcalloc(1,sizeof(*(p))))
88 #define KRELEASE(maj,min,patch) ((maj) * 65536 + (min)*256 + (patch))
89
90 static int procnetdev_vsn = 1;
91
92 #ifdef HAVE_HWSLIP
93 #include <net/if_slip.h>
94 #endif
95
96 #if HAVE_AFINET6
97
98 #ifndef _LINUX_IN6_H
99 /*
100  *    This is in linux/include/net/ipv6.h.
101  */
102
103 struct in6_ifreq {
104         struct in6_addr ifr6_addr;
105         __u32 ifr6_prefixlen;
106         unsigned int ifr6_ifindex;
107 };
108
109 #endif
110
111 #endif                                                  /* HAVE_AFINET6 */
112
113 #if HAVE_AFIPX
114 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
115 #include <netipx/ipx.h>
116 #else
117 #include "ipx.h"
118 #endif
119 #endif
120
121 /* Defines for glibc2.0 users. */
122 #ifndef SIOCSIFTXQLEN
123 #define SIOCSIFTXQLEN      0x8943
124 #define SIOCGIFTXQLEN      0x8942
125 #endif
126
127 /* ifr_qlen is ifru_ivalue, but it isn't present in 2.0 kernel headers */
128 #ifndef ifr_qlen
129 #define ifr_qlen        ifr_ifru.ifru_mtu
130 #endif
131
132 #ifndef HAVE_TXQUEUELEN
133 #define HAVE_TXQUEUELEN 1
134 #endif
135
136 #ifndef IFF_DYNAMIC
137 #define IFF_DYNAMIC     0x8000  /* dialup device with changing addresses */
138 #endif
139
140 /* This structure defines protocol families and their handlers. */
141 struct aftype {
142         const char *name;
143         const char *title;
144         int af;
145         int alen;
146         char *(*print) (unsigned char *);
147         char *(*sprint) (struct sockaddr *, int numeric);
148         int (*input) (int type, char *bufp, struct sockaddr *);
149         void (*herror) (char *text);
150         int (*rprint) (int options);
151         int (*rinput) (int typ, int ext, char **argv);
152
153         /* may modify src */
154         int (*getmask) (char *src, struct sockaddr * mask, char *name);
155
156         int fd;
157         char *flag_file;
158 };
159
160 #ifdef KEEP_UNUSED
161
162 static int flag_unx;
163
164 #ifdef HAVE_AFIPX
165 static int flag_ipx;
166 #endif
167 #ifdef HAVE_AFX25
168 static int flag_ax25;
169 #endif
170 #ifdef HAVE_AFATALK
171 static int flag_ddp;
172 #endif
173 #ifdef HAVE_AFNETROM
174 static int flag_netrom;
175 #endif
176 static int flag_inet;
177
178 #ifdef HAVE_AFINET6
179 static int flag_inet6;
180 #endif
181 #ifdef HAVE_AFECONET
182 static int flag_econet;
183 #endif
184 #ifdef HAVE_AFX25
185 static int flag_x25 = 0;
186 #endif
187 #ifdef HAVE_AFASH
188 static int flag_ash;
189 #endif
190
191
192 static struct aftrans_t {
193         char *alias;
194         char *name;
195         int *flag;
196 } aftrans[] = {
197
198 #ifdef HAVE_AFX25
199         {
200         "ax25", "ax25", &flag_ax25},
201 #endif
202         {
203         "ip", "inet", &flag_inet},
204 #ifdef HAVE_AFINET6
205         {
206         "ip6", "inet6", &flag_inet6},
207 #endif
208 #ifdef HAVE_AFIPX
209         {
210         "ipx", "ipx", &flag_ipx},
211 #endif
212 #ifdef HAVE_AFATALK
213         {
214         "appletalk", "ddp", &flag_ddp},
215 #endif
216 #ifdef HAVE_AFNETROM
217         {
218         "netrom", "netrom", &flag_netrom},
219 #endif
220         {
221         "inet", "inet", &flag_inet},
222 #ifdef HAVE_AFINET6
223         {
224         "inet6", "inet6", &flag_inet6},
225 #endif
226 #ifdef HAVE_AFATALK
227         {
228         "ddp", "ddp", &flag_ddp},
229 #endif
230         {
231         "unix", "unix", &flag_unx}, {
232         "tcpip", "inet", &flag_inet},
233 #ifdef HAVE_AFECONET
234         {
235         "econet", "ec", &flag_econet},
236 #endif
237 #ifdef HAVE_AFX25
238         {
239         "x25", "x25", &flag_x25},
240 #endif
241 #ifdef HAVE_AFASH
242         {
243         "ash", "ash", &flag_ash},
244 #endif
245         {
246         0, 0, 0}
247 };
248
249 static char afname[256] = "";
250 #endif                                                  /* KEEP_UNUSED */
251
252 #if HAVE_AFUNIX
253
254 /* Display a UNIX domain address. */
255 static char *UNIX_print(unsigned char *ptr)
256 {
257         return (ptr);
258 }
259
260
261 /* Display a UNIX domain address. */
262 static char *UNIX_sprint(struct sockaddr *sap, int numeric)
263 {
264         static char buf[64];
265
266         if (sap->sa_family == 0xFFFF || sap->sa_family == 0)
267                 return safe_strncpy(buf, _("[NONE SET]"), sizeof(buf));
268         return (UNIX_print(sap->sa_data));
269 }
270
271
272 static struct aftype unix_aftype = {
273         "unix", "UNIX Domain", AF_UNIX, 0,
274         UNIX_print, UNIX_sprint, NULL, NULL,
275         NULL, NULL, NULL,
276         -1,
277         "/proc/net/unix"
278 };
279 #endif                                                  /* HAVE_AFUNIX */
280
281 #if HAVE_AFINET
282
283 #ifdef KEEP_UNUSED
284 static void INET_reserror(char *text)
285 {
286         herror(text);
287 }
288
289 /* Display an Internet socket address. */
290 static char *INET_print(unsigned char *ptr)
291 {
292         return (inet_ntoa((*(struct in_addr *) ptr)));
293 }
294 #endif                                                  /* KEEP_UNUSED */
295
296 /* Display an Internet socket address. */
297 static char *INET_sprint(struct sockaddr *sap, int numeric)
298 {
299         static char buff[128];
300
301         if (sap->sa_family == 0xFFFF || sap->sa_family == 0)
302                 return safe_strncpy(buff, _("[NONE SET]"), sizeof(buff));
303
304         if (INET_rresolve(buff, sizeof(buff), (struct sockaddr_in *) sap,
305                                           numeric, 0xffffff00) != 0)
306                 return (NULL);
307
308         return (buff);
309 }
310
311 #ifdef KEEP_UNUSED
312 static char *INET_sprintmask(struct sockaddr *sap, int numeric,
313                                                          unsigned int netmask)
314 {
315         static char buff[128];
316
317         if (sap->sa_family == 0xFFFF || sap->sa_family == 0)
318                 return safe_strncpy(buff, _("[NONE SET]"), sizeof(buff));
319         if (INET_rresolve(buff, sizeof(buff), (struct sockaddr_in *) sap,
320                                           numeric, netmask) != 0)
321                 return (NULL);
322         return (buff);
323 }
324
325 static int INET_getsock(char *bufp, struct sockaddr *sap)
326 {
327         char *sp = bufp, *bp;
328         unsigned int i;
329         unsigned val;
330         struct sockaddr_in *sin;
331
332         sin = (struct sockaddr_in *) sap;
333         sin->sin_family = AF_INET;
334         sin->sin_port = 0;
335
336         val = 0;
337         bp = (char *) &val;
338         for (i = 0; i < sizeof(sin->sin_addr.s_addr); i++) {
339                 *sp = toupper(*sp);
340
341                 if ((*sp >= 'A') && (*sp <= 'F'))
342                         bp[i] |= (int) (*sp - 'A') + 10;
343                 else if ((*sp >= '0') && (*sp <= '9'))
344                         bp[i] |= (int) (*sp - '0');
345                 else
346                         return (-1);
347
348                 bp[i] <<= 4;
349                 sp++;
350                 *sp = toupper(*sp);
351
352                 if ((*sp >= 'A') && (*sp <= 'F'))
353                         bp[i] |= (int) (*sp - 'A') + 10;
354                 else if ((*sp >= '0') && (*sp <= '9'))
355                         bp[i] |= (int) (*sp - '0');
356                 else
357                         return (-1);
358
359                 sp++;
360         }
361         sin->sin_addr.s_addr = htonl(val);
362
363         return (sp - bufp);
364 }
365
366 static int INET_input(int type, char *bufp, struct sockaddr *sap)
367 {
368         switch (type) {
369         case 1:
370                 return (INET_getsock(bufp, sap));
371         case 256:
372                 return (INET_resolve(bufp, (struct sockaddr_in *) sap, 1));
373         default:
374                 return (INET_resolve(bufp, (struct sockaddr_in *) sap, 0));
375         }
376 }
377
378 static int INET_getnetmask(char *adr, struct sockaddr *m, char *name)
379 {
380         struct sockaddr_in *mask = (struct sockaddr_in *) m;
381         char *slash, *end;
382         int prefix;
383
384         if ((slash = strchr(adr, '/')) == NULL)
385                 return 0;
386
387         *slash++ = '\0';
388         prefix = strtoul(slash, &end, 0);
389         if (*end != '\0')
390                 return -1;
391
392         if (name) {
393                 sprintf(name, "/%d", prefix);
394         }
395         mask->sin_family = AF_INET;
396         mask->sin_addr.s_addr = htonl(~(0xffffffffU >> prefix));
397         return 1;
398 }
399 #endif                                                  /* KEEP_UNUSED */
400
401 static struct aftype inet_aftype = {
402         "inet", "DARPA Internet", AF_INET, sizeof(unsigned long),
403         NULL /* UNUSED INET_print */ , INET_sprint,
404         NULL /* UNUSED INET_input */ , NULL /* UNUSED INET_reserror */ ,
405         NULL /*INET_rprint */ , NULL /*INET_rinput */ ,
406         NULL /* UNUSED INET_getnetmask */ ,
407         -1,
408         NULL
409 };
410
411 #endif                                                  /* HAVE_AFINET */
412
413 #if HAVE_AFINET6
414
415 #ifdef KEEP_UNUSED
416 static void INET6_reserror(char *text)
417 {
418         herror(text);
419 }
420
421 /* Display an Internet socket address. */
422 static char *INET6_print(unsigned char *ptr)
423 {
424         static char name[80];
425
426         inet_ntop(AF_INET6, (struct in6_addr *) ptr, name, 80);
427         return name;
428 }
429 #endif                                                  /* KEEP_UNUSED */
430
431 /* Display an Internet socket address. */
432 /* dirty! struct sockaddr usually doesn't suffer for inet6 addresses, fst. */
433 static char *INET6_sprint(struct sockaddr *sap, int numeric)
434 {
435         static char buff[128];
436
437         if (sap->sa_family == 0xFFFF || sap->sa_family == 0)
438                 return safe_strncpy(buff, _("[NONE SET]"), sizeof(buff));
439         if (INET6_rresolve
440                 (buff, sizeof(buff), (struct sockaddr_in6 *) sap, numeric) != 0)
441                 return safe_strncpy(buff, _("[UNKNOWN]"), sizeof(buff));
442         return (buff);
443 }
444
445 #ifdef KEEP_UNUSED
446 static int INET6_getsock(char *bufp, struct sockaddr *sap)
447 {
448         struct sockaddr_in6 *sin6;
449
450         sin6 = (struct sockaddr_in6 *) sap;
451         sin6->sin6_family = AF_INET6;
452         sin6->sin6_port = 0;
453
454         if (inet_pton(AF_INET6, bufp, sin6->sin6_addr.s6_addr) <= 0)
455                 return (-1);
456
457         return 16;                      /* ?;) */
458 }
459
460 static int INET6_input(int type, char *bufp, struct sockaddr *sap)
461 {
462         switch (type) {
463         case 1:
464                 return (INET6_getsock(bufp, sap));
465         default:
466                 return (INET6_resolve(bufp, (struct sockaddr_in6 *) sap));
467         }
468 }
469 #endif                                                  /* KEEP_UNUSED */
470
471 static struct aftype inet6_aftype = {
472         "inet6", "IPv6", AF_INET6, sizeof(struct in6_addr),
473         NULL /* UNUSED INET6_print */ , INET6_sprint,
474         NULL /* UNUSED INET6_input */ , NULL /* UNUSED INET6_reserror */ ,
475         NULL /*INET6_rprint */ , NULL /*INET6_rinput */ ,
476         NULL /* UNUSED INET6_getnetmask */ ,
477         -1,
478         NULL
479 };
480
481 #endif                                                  /* HAVE_AFINET6 */
482
483 /* Display an UNSPEC address. */
484 static char *UNSPEC_print(unsigned char *ptr)
485 {
486         static char buff[sizeof(struct sockaddr) * 3 + 1];
487         char *pos;
488         unsigned int i;
489
490         pos = buff;
491         for (i = 0; i < sizeof(struct sockaddr); i++) {
492                 /* careful -- not every libc's sprintf returns # bytes written */
493                 sprintf(pos, "%02X-", (*ptr++ & 0377));
494                 pos += 3;
495         }
496         /* Erase trailing "-".  Works as long as sizeof(struct sockaddr) != 0 */
497         *--pos = '\0';
498         return (buff);
499 }
500
501 /* Display an UNSPEC socket address. */
502 static char *UNSPEC_sprint(struct sockaddr *sap, int numeric)
503 {
504         static char buf[64];
505
506         if (sap->sa_family == 0xFFFF || sap->sa_family == 0)
507                 return safe_strncpy(buf, _("[NONE SET]"), sizeof(buf));
508         return (UNSPEC_print(sap->sa_data));
509 }
510
511 static struct aftype unspec_aftype = {
512         "unspec", "UNSPEC", AF_UNSPEC, 0,
513         UNSPEC_print, UNSPEC_sprint, NULL, NULL,
514         NULL,
515 };
516
517 static struct aftype *aftypes[] = {
518 #if HAVE_AFUNIX
519         &unix_aftype,
520 #endif
521 #if HAVE_AFINET
522         &inet_aftype,
523 #endif
524 #if HAVE_AFINET6
525         &inet6_aftype,
526 #endif
527 #if HAVE_AFAX25
528         &ax25_aftype,
529 #endif
530 #if HAVE_AFNETROM
531         &netrom_aftype,
532 #endif
533 #if HAVE_AFROSE
534         &rose_aftype,
535 #endif
536 #if HAVE_AFIPX
537         &ipx_aftype,
538 #endif
539 #if HAVE_AFATALK
540         &ddp_aftype,
541 #endif
542 #if HAVE_AFECONET
543         &ec_aftype,
544 #endif
545 #if HAVE_AFASH
546         &ash_aftype,
547 #endif
548 #if HAVE_AFX25
549         &x25_aftype,
550 #endif
551         &unspec_aftype,
552         NULL
553 };
554
555 #ifdef KEEP_UNUSED
556 static short sVafinit = 0;
557
558 static void afinit()
559 {
560         unspec_aftype.title = _("UNSPEC");
561 #if HAVE_AFUNIX
562         unix_aftype.title = _("UNIX Domain");
563 #endif
564 #if HAVE_AFINET
565         inet_aftype.title = _("DARPA Internet");
566 #endif
567 #if HAVE_AFINET6
568         inet6_aftype.title = _("IPv6");
569 #endif
570 #if HAVE_AFAX25
571         ax25_aftype.title = _("AMPR AX.25");
572 #endif
573 #if HAVE_AFNETROM
574         netrom_aftype.title = _("AMPR NET/ROM");
575 #endif
576 #if HAVE_AFIPX
577         ipx_aftype.title = _("Novell IPX");
578 #endif
579 #if HAVE_AFATALK
580         ddp_aftype.title = _("Appletalk DDP");
581 #endif
582 #if HAVE_AFECONET
583         ec_aftype.title = _("Econet");
584 #endif
585 #if HAVE_AFX25
586         x25_aftype.title = _("CCITT X.25");
587 #endif
588 #if HAVE_AFROSE
589         rose_aftype.title = _("AMPR ROSE");
590 #endif
591 #if HAVE_AFASH
592         ash_aftype.title = _("Ash");
593 #endif
594         sVafinit = 1;
595 }
596
597 static int aftrans_opt(const char *arg)
598 {
599         struct aftrans_t *paft;
600         char *tmp1, *tmp2;
601         char buf[256];
602
603         safe_strncpy(buf, arg, sizeof(buf));
604
605         tmp1 = buf;
606
607         while (tmp1) {
608
609                 tmp2 = strchr(tmp1, ',');
610
611                 if (tmp2)
612                         *(tmp2++) = '\0';
613
614                 paft = aftrans;
615                 for (paft = aftrans; paft->alias; paft++) {
616                         if (strcmp(tmp1, paft->alias))
617                                 continue;
618                         if (strlen(paft->name) + strlen(afname) + 1 >= sizeof(afname)) {
619                                 bb_error_msg(_("Too many address family arguments."));
620                                 return (0);
621                         }
622                         if (paft->flag)
623                                 (*paft->flag)++;
624                         if (afname[0])
625                                 strcat(afname, ",");
626                         strcat(afname, paft->name);
627                         break;
628                 }
629                 if (!paft->alias) {
630                         bb_error_msg(_("Unknown address family `%s'."), tmp1);
631                         return (1);
632                 }
633                 tmp1 = tmp2;
634         }
635
636         return (0);
637 }
638
639 /* set the default AF list from the program name or a constant value    */
640 static void aftrans_def(char *tool, char *argv0, char *dflt)
641 {
642         char *tmp;
643         char *buf;
644
645         strcpy(afname, dflt);
646
647         if (!(tmp = strrchr(argv0, '/')))
648                 tmp = argv0;    /* no slash?! */
649         else
650                 tmp++;
651
652         if (!(buf = strdup(tmp)))
653                 return;
654
655         if (strlen(tool) >= strlen(tmp)) {
656                 free(buf);
657                 return;
658         }
659         tmp = buf + (strlen(tmp) - strlen(tool));
660
661         if (strcmp(tmp, tool) != 0) {
662                 free(buf);
663                 return;
664         }
665         *tmp = '\0';
666         if ((tmp = strchr(buf, '_')))
667                 *tmp = '\0';
668
669         afname[0] = '\0';
670         if (aftrans_opt(buf))
671                 strcpy(afname, buf);
672
673         free(buf);
674 }
675
676 /* Check our protocol family table for this family. */
677 static struct aftype *get_aftype(const char *name)
678 {
679         struct aftype **afp;
680
681 #ifdef KEEP_UNUSED
682         if (!sVafinit)
683                 afinit();
684 #endif                                                  /* KEEP_UNUSED */
685
686         afp = aftypes;
687         while (*afp != NULL) {
688                 if (!strcmp((*afp)->name, name))
689                         return (*afp);
690                 afp++;
691         }
692         if (strchr(name, ','))
693                 bb_error_msg(_("Please don't supply more than one address family."));
694         return (NULL);
695 }
696 #endif                                                  /* KEEP_UNUSED */
697
698 /* Check our protocol family table for this family. */
699 static struct aftype *get_afntype(int af)
700 {
701         struct aftype **afp;
702
703 #ifdef KEEP_UNUSED
704         if (!sVafinit)
705                 afinit();
706 #endif                                                  /* KEEP_UNUSED */
707
708         afp = aftypes;
709         while (*afp != NULL) {
710                 if ((*afp)->af == af)
711                         return (*afp);
712                 afp++;
713         }
714         return (NULL);
715 }
716
717 /* Check our protocol family table for this family and return its socket */
718 static int get_socket_for_af(int af)
719 {
720         struct aftype **afp;
721
722 #ifdef KEEP_UNUSED
723         if (!sVafinit)
724                 afinit();
725 #endif                                                  /* KEEP_UNUSED */
726
727         afp = aftypes;
728         while (*afp != NULL) {
729                 if ((*afp)->af == af)
730                         return (*afp)->fd;
731                 afp++;
732         }
733         return -1;
734 }
735
736 #ifdef KEEP_UNUSED
737 /* type: 0=all, 1=getroute */
738 static void print_aflist(int type)
739 {
740         int count = 0;
741         char *txt;
742         struct aftype **afp;
743
744 #ifdef KEEP_UNUSED
745         if (!sVafinit)
746                 afinit();
747 #endif                                                  /* KEEP_UNUSED */
748
749         afp = aftypes;
750         while (*afp != NULL) {
751                 if ((type == 1 && ((*afp)->rprint == NULL)) || ((*afp)->af == 0)) {
752                         afp++;
753                         continue;
754                 }
755                 if ((count % 3) == 0)
756                         fprintf(stderr, count ? "\n    " : "    ");
757                 txt = (*afp)->name;
758                 if (!txt)
759                         txt = "..";
760                 fprintf(stderr, "%s (%s) ", txt, _((*afp)->title));
761                 count++;
762                 afp++;
763         }
764         fprintf(stderr, "\n");
765 }
766 #endif                                                  /* KEEP_UNUSED */
767
768 struct user_net_device_stats {
769         unsigned long long rx_packets;  /* total packets received       */
770         unsigned long long tx_packets;  /* total packets transmitted    */
771         unsigned long long rx_bytes;    /* total bytes received         */
772         unsigned long long tx_bytes;    /* total bytes transmitted      */
773         unsigned long rx_errors;        /* bad packets received         */
774         unsigned long tx_errors;        /* packet transmit problems     */
775         unsigned long rx_dropped;       /* no space in linux buffers    */
776         unsigned long tx_dropped;       /* no space available in linux  */
777         unsigned long rx_multicast;     /* multicast packets received   */
778         unsigned long rx_compressed;
779         unsigned long tx_compressed;
780         unsigned long collisions;
781
782         /* detailed rx_errors: */
783         unsigned long rx_length_errors;
784         unsigned long rx_over_errors;   /* receiver ring buff overflow  */
785         unsigned long rx_crc_errors;    /* recved pkt with crc error    */
786         unsigned long rx_frame_errors;  /* recv'd frame alignment error */
787         unsigned long rx_fifo_errors;   /* recv'r fifo overrun          */
788         unsigned long rx_missed_errors; /* receiver missed packet     */
789         /* detailed tx_errors */
790         unsigned long tx_aborted_errors;
791         unsigned long tx_carrier_errors;
792         unsigned long tx_fifo_errors;
793         unsigned long tx_heartbeat_errors;
794         unsigned long tx_window_errors;
795 };
796
797 struct interface {
798         struct interface *next, *prev;
799         char name[IFNAMSIZ];    /* interface name        */
800         short type;                     /* if type               */
801         short flags;            /* various flags         */
802         int metric;                     /* routing metric        */
803         int mtu;                        /* MTU value             */
804         int tx_queue_len;       /* transmit queue length */
805         struct ifmap map;       /* hardware setup        */
806         struct sockaddr addr;   /* IP address            */
807         struct sockaddr dstaddr;        /* P-P IP address        */
808         struct sockaddr broadaddr;      /* IP broadcast address  */
809         struct sockaddr netmask;        /* IP network mask       */
810         struct sockaddr ipxaddr_bb;     /* IPX network address   */
811         struct sockaddr ipxaddr_sn;     /* IPX network address   */
812         struct sockaddr ipxaddr_e3;     /* IPX network address   */
813         struct sockaddr ipxaddr_e2;     /* IPX network address   */
814         struct sockaddr ddpaddr;        /* Appletalk DDP address */
815         struct sockaddr ecaddr; /* Econet address        */
816         int has_ip;
817         int has_ipx_bb;
818         int has_ipx_sn;
819         int has_ipx_e3;
820         int has_ipx_e2;
821         int has_ax25;
822         int has_ddp;
823         int has_econet;
824         char hwaddr[32];        /* HW address            */
825         int statistics_valid;
826         struct user_net_device_stats stats;     /* statistics            */
827         int keepalive;          /* keepalive value for SLIP */
828         int outfill;            /* outfill value for SLIP */
829 };
830
831
832 int interface_opt_a = 0;        /* show all interfaces          */
833
834 #ifdef KEEP_UNUSED
835 static int opt_i = 0;   /* show the statistics          */
836 static int opt_v = 0;   /* debugging output flag        */
837
838 static int addr_family = 0;     /* currently selected AF        */
839 #endif                                                  /* KEEP_UNUSED */
840
841 static struct interface *int_list, *int_last;
842 static int skfd = -1;   /* generic raw socket desc.     */
843
844
845 static int sockets_open(int family)
846 {
847         struct aftype **aft;
848         int sfd = -1;
849         static int force = -1;
850
851         if (force < 0) {
852                 force = 0;
853                 if (get_kernel_revision() < KRELEASE(2, 1, 0))
854                         force = 1;
855                 if (access("/proc/net", R_OK))
856                         force = 1;
857         }
858         for (aft = aftypes; *aft; aft++) {
859                 struct aftype *af = *aft;
860                 int type = SOCK_DGRAM;
861
862                 if (af->af == AF_UNSPEC)
863                         continue;
864                 if (family && family != af->af)
865                         continue;
866                 if (af->fd != -1) {
867                         sfd = af->fd;
868                         continue;
869                 }
870                 /* Check some /proc file first to not stress kmod */
871                 if (!family && !force && af->flag_file) {
872                         if (access(af->flag_file, R_OK))
873                                 continue;
874                 }
875 #if HAVE_AFNETROM
876                 if (af->af == AF_NETROM)
877                         type = SOCK_SEQPACKET;
878 #endif
879 #if HAVE_AFX25
880                 if (af->af == AF_X25)
881                         type = SOCK_SEQPACKET;
882 #endif
883                 af->fd = socket(af->af, type, 0);
884                 if (af->fd >= 0)
885                         sfd = af->fd;
886         }
887         if (sfd < 0) {
888                 bb_error_msg(_("No usable address families found."));
889         }
890         return sfd;
891 }
892
893 /* like strcmp(), but knows about numbers */
894 static int nstrcmp(const char *astr, const char *b)
895 {
896         const char *a = astr;
897
898         while (*a == *b) {
899                 if (*a == '\0')
900                         return 0;
901                 a++;
902                 b++;
903         }
904         if (isdigit(*a)) {
905                 if (!isdigit(*b))
906                         return -1;
907                 while (a > astr) {
908                         a--;
909                         if (!isdigit(*a)) {
910                                 a++;
911                                 break;
912                         }
913                         if (!isdigit(*b))
914                                 return -1;
915                         b--;
916                 }
917                 return atoi(a) > atoi(b) ? 1 : -1;
918         }
919         return *a - *b;
920 }
921
922 static struct interface *add_interface(char *name)
923 {
924         struct interface *ife, **nextp, *new;
925
926         for (ife = int_last; ife; ife = ife->prev) {
927                 int n = nstrcmp(ife->name, name);
928
929                 if (n == 0)
930                         return ife;
931                 if (n < 0)
932                         break;
933         }
934         new(new);
935         safe_strncpy(new->name, name, IFNAMSIZ);
936         nextp = ife ? &ife->next : &int_list;
937         new->prev = ife;
938         new->next = *nextp;
939         if (new->next)
940                 new->next->prev = new;
941         else
942                 int_last = new;
943         *nextp = new;
944         return new;
945 }
946
947
948 static int if_readconf(void)
949 {
950         int numreqs = 30;
951         struct ifconf ifc;
952         struct ifreq *ifr;
953         int n, err = -1;
954         int skfd2;
955
956         /* SIOCGIFCONF currently seems to only work properly on AF_INET sockets
957            (as of 2.1.128) */
958         skfd2 = get_socket_for_af(AF_INET);
959         if (skfd2 < 0) {
960                 bb_perror_msg(("warning: no inet socket available"));
961                 /* Try to soldier on with whatever socket we can get hold of.  */
962                 skfd2 = sockets_open(0);
963                 if (skfd2 < 0)
964                         return -1;
965         }
966
967         ifc.ifc_buf = NULL;
968         for (;;) {
969                 ifc.ifc_len = sizeof(struct ifreq) * numreqs;
970                 ifc.ifc_buf = xrealloc(ifc.ifc_buf, ifc.ifc_len);
971
972                 if (ioctl(skfd2, SIOCGIFCONF, &ifc) < 0) {
973                         perror("SIOCGIFCONF");
974                         goto out;
975                 }
976                 if (ifc.ifc_len == sizeof(struct ifreq) * numreqs) {
977                         /* assume it overflowed and try again */
978                         numreqs += 10;
979                         continue;
980                 }
981                 break;
982         }
983
984         ifr = ifc.ifc_req;
985         for (n = 0; n < ifc.ifc_len; n += sizeof(struct ifreq)) {
986                 add_interface(ifr->ifr_name);
987                 ifr++;
988         }
989         err = 0;
990
991   out:
992         free(ifc.ifc_buf);
993         return err;
994 }
995
996 static char *get_name(char *name, char *p)
997 {
998         while (isspace(*p))
999                 p++;
1000         while (*p) {
1001                 if (isspace(*p))
1002                         break;
1003                 if (*p == ':') {        /* could be an alias */
1004                         char *dot = p, *dotname = name;
1005
1006                         *name++ = *p++;
1007                         while (isdigit(*p))
1008                                 *name++ = *p++;
1009                         if (*p != ':') {        /* it wasn't, backup */
1010                                 p = dot;
1011                                 name = dotname;
1012                         }
1013                         if (*p == '\0')
1014                                 return NULL;
1015                         p++;
1016                         break;
1017                 }
1018                 *name++ = *p++;
1019         }
1020         *name++ = '\0';
1021         return p;
1022 }
1023
1024 static int get_dev_fields(char *bp, struct interface *ife)
1025 {
1026         switch (procnetdev_vsn) {
1027         case 3:
1028                 sscanf(bp,
1029                            "%Lu %Lu %lu %lu %lu %lu %lu %lu %Lu %Lu %lu %lu %lu %lu %lu %lu",
1030                            &ife->stats.rx_bytes,
1031                            &ife->stats.rx_packets,
1032                            &ife->stats.rx_errors,
1033                            &ife->stats.rx_dropped,
1034                            &ife->stats.rx_fifo_errors,
1035                            &ife->stats.rx_frame_errors,
1036                            &ife->stats.rx_compressed,
1037                            &ife->stats.rx_multicast,
1038                            &ife->stats.tx_bytes,
1039                            &ife->stats.tx_packets,
1040                            &ife->stats.tx_errors,
1041                            &ife->stats.tx_dropped,
1042                            &ife->stats.tx_fifo_errors,
1043                            &ife->stats.collisions,
1044                            &ife->stats.tx_carrier_errors, &ife->stats.tx_compressed);
1045                 break;
1046         case 2:
1047                 sscanf(bp, "%Lu %Lu %lu %lu %lu %lu %Lu %Lu %lu %lu %lu %lu %lu",
1048                            &ife->stats.rx_bytes,
1049                            &ife->stats.rx_packets,
1050                            &ife->stats.rx_errors,
1051                            &ife->stats.rx_dropped,
1052                            &ife->stats.rx_fifo_errors,
1053                            &ife->stats.rx_frame_errors,
1054                            &ife->stats.tx_bytes,
1055                            &ife->stats.tx_packets,
1056                            &ife->stats.tx_errors,
1057                            &ife->stats.tx_dropped,
1058                            &ife->stats.tx_fifo_errors,
1059                            &ife->stats.collisions, &ife->stats.tx_carrier_errors);
1060                 ife->stats.rx_multicast = 0;
1061                 break;
1062         case 1:
1063                 sscanf(bp, "%Lu %lu %lu %lu %lu %Lu %lu %lu %lu %lu %lu",
1064                            &ife->stats.rx_packets,
1065                            &ife->stats.rx_errors,
1066                            &ife->stats.rx_dropped,
1067                            &ife->stats.rx_fifo_errors,
1068                            &ife->stats.rx_frame_errors,
1069                            &ife->stats.tx_packets,
1070                            &ife->stats.tx_errors,
1071                            &ife->stats.tx_dropped,
1072                            &ife->stats.tx_fifo_errors,
1073                            &ife->stats.collisions, &ife->stats.tx_carrier_errors);
1074                 ife->stats.rx_bytes = 0;
1075                 ife->stats.tx_bytes = 0;
1076                 ife->stats.rx_multicast = 0;
1077                 break;
1078         }
1079         return 0;
1080 }
1081
1082 static inline int procnetdev_version(char *buf)
1083 {
1084         if (strstr(buf, "compressed"))
1085                 return 3;
1086         if (strstr(buf, "bytes"))
1087                 return 2;
1088         return 1;
1089 }
1090
1091 static int if_readlist_proc(char *target)
1092 {
1093         static int proc_read;
1094         FILE *fh;
1095         char buf[512];
1096         struct interface *ife;
1097         int err;
1098
1099         if (proc_read)
1100                 return 0;
1101         if (!target)
1102                 proc_read = 1;
1103
1104         fh = fopen(_PATH_PROCNET_DEV, "r");
1105         if (!fh) {
1106                 bb_perror_msg(_("Warning: cannot open %s. Limited output."), _PATH_PROCNET_DEV);
1107                 return if_readconf();
1108         }
1109         fgets(buf, sizeof buf, fh);     /* eat line */
1110         fgets(buf, sizeof buf, fh);
1111
1112 #if 0                                   /* pretty, but can't cope with missing fields */
1113         fmt = proc_gen_fmt(_PATH_PROCNET_DEV, 1, fh, "face", "",        /* parsed separately */
1114                                            "bytes", "%lu",
1115                                            "packets", "%lu",
1116                                            "errs", "%lu",
1117                                            "drop", "%lu",
1118                                            "fifo", "%lu",
1119                                            "frame", "%lu",
1120                                            "compressed", "%lu",
1121                                            "multicast", "%lu",
1122                                            "bytes", "%lu",
1123                                            "packets", "%lu",
1124                                            "errs", "%lu",
1125                                            "drop", "%lu",
1126                                            "fifo", "%lu",
1127                                            "colls", "%lu",
1128                                            "carrier", "%lu", "compressed", "%lu", NULL);
1129         if (!fmt)
1130                 return -1;
1131 #else
1132         procnetdev_vsn = procnetdev_version(buf);
1133 #endif
1134
1135         err = 0;
1136         while (fgets(buf, sizeof buf, fh)) {
1137                 char *s, name[IFNAMSIZ];
1138
1139                 s = get_name(name, buf);
1140                 ife = add_interface(name);
1141                 get_dev_fields(s, ife);
1142                 ife->statistics_valid = 1;
1143                 if (target && !strcmp(target, name))
1144                         break;
1145         }
1146         if (ferror(fh)) {
1147                 perror(_PATH_PROCNET_DEV);
1148                 err = -1;
1149                 proc_read = 0;
1150         }
1151 #if 0
1152         free(fmt);
1153 #endif
1154         fclose(fh);
1155         return err;
1156 }
1157
1158 static int if_readlist(void)
1159 {
1160         int err = if_readlist_proc(NULL);
1161
1162         if (!err)
1163                 err = if_readconf();
1164         return err;
1165 }
1166
1167 static int for_all_interfaces(int (*doit) (struct interface *, void *),
1168                                                           void *cookie)
1169 {
1170         struct interface *ife;
1171
1172         if (!int_list && (if_readlist() < 0))
1173                 return -1;
1174         for (ife = int_list; ife; ife = ife->next) {
1175                 int err = doit(ife, cookie);
1176
1177                 if (err)
1178                         return err;
1179         }
1180         return 0;
1181 }
1182
1183 /* Support for fetching an IPX address */
1184
1185 #if HAVE_AFIPX
1186 static int ipx_getaddr(int sock, int ft, struct ifreq *ifr)
1187 {
1188         ((struct sockaddr_ipx *) &ifr->ifr_addr)->sipx_type = ft;
1189         return ioctl(sock, SIOCGIFADDR, ifr);
1190 }
1191 #endif
1192
1193
1194 /* Fetch the interface configuration from the kernel. */
1195 static int if_fetch(struct interface *ife)
1196 {
1197         struct ifreq ifr;
1198         int fd;
1199         char *ifname = ife->name;
1200
1201         strcpy(ifr.ifr_name, ifname);
1202         if (ioctl(skfd, SIOCGIFFLAGS, &ifr) < 0)
1203                 return (-1);
1204         ife->flags = ifr.ifr_flags;
1205
1206         strcpy(ifr.ifr_name, ifname);
1207         if (ioctl(skfd, SIOCGIFHWADDR, &ifr) < 0)
1208                 memset(ife->hwaddr, 0, 32);
1209         else
1210                 memcpy(ife->hwaddr, ifr.ifr_hwaddr.sa_data, 8);
1211
1212         ife->type = ifr.ifr_hwaddr.sa_family;
1213
1214         strcpy(ifr.ifr_name, ifname);
1215         if (ioctl(skfd, SIOCGIFMETRIC, &ifr) < 0)
1216                 ife->metric = 0;
1217         else
1218                 ife->metric = ifr.ifr_metric;
1219
1220         strcpy(ifr.ifr_name, ifname);
1221         if (ioctl(skfd, SIOCGIFMTU, &ifr) < 0)
1222                 ife->mtu = 0;
1223         else
1224                 ife->mtu = ifr.ifr_mtu;
1225
1226 #ifdef HAVE_HWSLIP
1227         if (ife->type == ARPHRD_SLIP || ife->type == ARPHRD_CSLIP ||
1228                 ife->type == ARPHRD_SLIP6 || ife->type == ARPHRD_CSLIP6 ||
1229                 ife->type == ARPHRD_ADAPT) {
1230 #ifdef SIOCGOUTFILL
1231                 strcpy(ifr.ifr_name, ifname);
1232                 if (ioctl(skfd, SIOCGOUTFILL, &ifr) < 0)
1233                         ife->outfill = 0;
1234                 else
1235                         ife->outfill = (unsigned int) ifr.ifr_data;
1236 #endif
1237 #ifdef SIOCGKEEPALIVE
1238                 strcpy(ifr.ifr_name, ifname);
1239                 if (ioctl(skfd, SIOCGKEEPALIVE, &ifr) < 0)
1240                         ife->keepalive = 0;
1241                 else
1242                         ife->keepalive = (unsigned int) ifr.ifr_data;
1243 #endif
1244         }
1245 #endif
1246
1247         strcpy(ifr.ifr_name, ifname);
1248         if (ioctl(skfd, SIOCGIFMAP, &ifr) < 0)
1249                 memset(&ife->map, 0, sizeof(struct ifmap));
1250         else
1251                 memcpy(&ife->map, &ifr.ifr_map, sizeof(struct ifmap));
1252
1253         strcpy(ifr.ifr_name, ifname);
1254         if (ioctl(skfd, SIOCGIFMAP, &ifr) < 0)
1255                 memset(&ife->map, 0, sizeof(struct ifmap));
1256         else
1257                 ife->map = ifr.ifr_map;
1258
1259 #ifdef HAVE_TXQUEUELEN
1260         strcpy(ifr.ifr_name, ifname);
1261         if (ioctl(skfd, SIOCGIFTXQLEN, &ifr) < 0)
1262                 ife->tx_queue_len = -1; /* unknown value */
1263         else
1264                 ife->tx_queue_len = ifr.ifr_qlen;
1265 #else
1266         ife->tx_queue_len = -1; /* unknown value */
1267 #endif
1268
1269 #if HAVE_AFINET
1270         /* IPv4 address? */
1271         fd = get_socket_for_af(AF_INET);
1272         if (fd >= 0) {
1273                 strcpy(ifr.ifr_name, ifname);
1274                 ifr.ifr_addr.sa_family = AF_INET;
1275                 if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) {
1276                         ife->has_ip = 1;
1277                         ife->addr = ifr.ifr_addr;
1278                         strcpy(ifr.ifr_name, ifname);
1279                         if (ioctl(fd, SIOCGIFDSTADDR, &ifr) < 0)
1280                                 memset(&ife->dstaddr, 0, sizeof(struct sockaddr));
1281                         else
1282                                 ife->dstaddr = ifr.ifr_dstaddr;
1283
1284                         strcpy(ifr.ifr_name, ifname);
1285                         if (ioctl(fd, SIOCGIFBRDADDR, &ifr) < 0)
1286                                 memset(&ife->broadaddr, 0, sizeof(struct sockaddr));
1287                         else
1288                                 ife->broadaddr = ifr.ifr_broadaddr;
1289
1290                         strcpy(ifr.ifr_name, ifname);
1291                         if (ioctl(fd, SIOCGIFNETMASK, &ifr) < 0)
1292                                 memset(&ife->netmask, 0, sizeof(struct sockaddr));
1293                         else
1294                                 ife->netmask = ifr.ifr_netmask;
1295                 } else
1296                         memset(&ife->addr, 0, sizeof(struct sockaddr));
1297         }
1298 #endif
1299
1300 #if HAVE_AFATALK
1301         /* DDP address maybe ? */
1302         fd = get_socket_for_af(AF_APPLETALK);
1303         if (fd >= 0) {
1304                 strcpy(ifr.ifr_name, ifname);
1305                 if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) {
1306                         ife->ddpaddr = ifr.ifr_addr;
1307                         ife->has_ddp = 1;
1308                 }
1309         }
1310 #endif
1311
1312 #if HAVE_AFIPX
1313         /* Look for IPX addresses with all framing types */
1314         fd = get_socket_for_af(AF_IPX);
1315         if (fd >= 0) {
1316                 strcpy(ifr.ifr_name, ifname);
1317                 if (!ipx_getaddr(fd, IPX_FRAME_ETHERII, &ifr)) {
1318                         ife->has_ipx_bb = 1;
1319                         ife->ipxaddr_bb = ifr.ifr_addr;
1320                 }
1321                 strcpy(ifr.ifr_name, ifname);
1322                 if (!ipx_getaddr(fd, IPX_FRAME_SNAP, &ifr)) {
1323                         ife->has_ipx_sn = 1;
1324                         ife->ipxaddr_sn = ifr.ifr_addr;
1325                 }
1326                 strcpy(ifr.ifr_name, ifname);
1327                 if (!ipx_getaddr(fd, IPX_FRAME_8023, &ifr)) {
1328                         ife->has_ipx_e3 = 1;
1329                         ife->ipxaddr_e3 = ifr.ifr_addr;
1330                 }
1331                 strcpy(ifr.ifr_name, ifname);
1332                 if (!ipx_getaddr(fd, IPX_FRAME_8022, &ifr)) {
1333                         ife->has_ipx_e2 = 1;
1334                         ife->ipxaddr_e2 = ifr.ifr_addr;
1335                 }
1336         }
1337 #endif
1338
1339 #if HAVE_AFECONET
1340         /* Econet address maybe? */
1341         fd = get_socket_for_af(AF_ECONET);
1342         if (fd >= 0) {
1343                 strcpy(ifr.ifr_name, ifname);
1344                 if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) {
1345                         ife->ecaddr = ifr.ifr_addr;
1346                         ife->has_econet = 1;
1347                 }
1348         }
1349 #endif
1350
1351         return 0;
1352 }
1353
1354
1355 static int do_if_fetch(struct interface *ife)
1356 {
1357         if (if_fetch(ife) < 0) {
1358                 char *errmsg;
1359
1360                 if (errno == ENODEV) {
1361                         /* Give better error message for this case. */
1362                         errmsg = _("Device not found");
1363                 } else {
1364                         errmsg = strerror(errno);
1365                 }
1366                 bb_error_msg(_("%s: error fetching interface information: %s\n"),
1367                                 ife->name, errmsg);
1368                 return -1;
1369         }
1370         return 0;
1371 }
1372
1373 /* This structure defines hardware protocols and their handlers. */
1374 struct hwtype {
1375         const char *name;
1376         const char *title;
1377         int type;
1378         int alen;
1379         char *(*print) (unsigned char *);
1380         int (*input) (char *, struct sockaddr *);
1381         int (*activate) (int fd);
1382         int suppress_null_addr;
1383 };
1384
1385 static struct hwtype unspec_hwtype = {
1386         "unspec", "UNSPEC", -1, 0,
1387         UNSPEC_print, NULL, NULL
1388 };
1389
1390 static struct hwtype loop_hwtype = {
1391         "loop", "Local Loopback", ARPHRD_LOOPBACK, 0,
1392         NULL, NULL, NULL
1393 };
1394
1395 #if HAVE_HWETHER
1396 #include <net/if_arp.h>
1397
1398 #if __GLIBC__ >=2 && __GLIBC_MINOR >= 1
1399 #include <net/ethernet.h>
1400 #else
1401 #include <linux/if_ether.h>
1402 #endif
1403
1404 /* Display an Ethernet address in readable format. */
1405 static char *pr_ether(unsigned char *ptr)
1406 {
1407         static char buff[64];
1408
1409         snprintf(buff, sizeof(buff), "%02X:%02X:%02X:%02X:%02X:%02X",
1410                          (ptr[0] & 0377), (ptr[1] & 0377), (ptr[2] & 0377),
1411                          (ptr[3] & 0377), (ptr[4] & 0377), (ptr[5] & 0377)
1412                 );
1413         return (buff);
1414 }
1415
1416 #ifdef KEEP_UNUSED
1417 /* Input an Ethernet address and convert to binary. */
1418 static int in_ether(char *bufp, struct sockaddr *sap)
1419 {
1420         unsigned char *ptr;
1421         char c, *orig;
1422         int i;
1423         unsigned val;
1424
1425         sap->sa_family = ether_hwtype.type;
1426         ptr = sap->sa_data;
1427
1428         i = 0;
1429         orig = bufp;
1430         while ((*bufp != '\0') && (i < ETH_ALEN)) {
1431                 val = 0;
1432                 c = *bufp++;
1433                 if (isdigit(c))
1434                         val = c - '0';
1435                 else if (c >= 'a' && c <= 'f')
1436                         val = c - 'a' + 10;
1437                 else if (c >= 'A' && c <= 'F')
1438                         val = c - 'A' + 10;
1439                 else {
1440 #ifdef DEBUG
1441                         bb_error_msg(_("in_ether(%s): invalid ether address!\n"), orig);
1442 #endif
1443                         errno = EINVAL;
1444                         return (-1);
1445                 }
1446                 val <<= 4;
1447                 c = *bufp;
1448                 if (isdigit(c))
1449                         val |= c - '0';
1450                 else if (c >= 'a' && c <= 'f')
1451                         val |= c - 'a' + 10;
1452                 else if (c >= 'A' && c <= 'F')
1453                         val |= c - 'A' + 10;
1454                 else if (c == ':' || c == 0)
1455                         val >>= 4;
1456                 else {
1457 #ifdef DEBUG
1458                         bb_error_msg(_("in_ether(%s): invalid ether address!"), orig);
1459 #endif
1460                         errno = EINVAL;
1461                         return (-1);
1462                 }
1463                 if (c != 0)
1464                         bufp++;
1465                 *ptr++ = (unsigned char) (val & 0377);
1466                 i++;
1467
1468                 /* We might get a semicolon here - not required. */
1469                 if (*bufp == ':') {
1470 #ifdef DEBUG
1471                         if (i == ETH_ALEN) {
1472                                 bb_error_msg(_("in_ether(%s): trailing : ignored!"), orig);
1473                         }
1474 #endif
1475                         bufp++;
1476                 }
1477         }
1478
1479 #ifdef DEBUG
1480         /* That's it.  Any trailing junk? */
1481         if ((i == ETH_ALEN) && (*bufp != '\0')) {
1482                 bb_error_msg(_("in_ether(%s): trailing junk!"), orig);
1483                 errno = EINVAL;
1484                 return (-1);
1485         }
1486         bb_error_msg("in_ether(%s): %s", orig, pr_ether(sap->sa_data));
1487 #endif
1488
1489         return (0);
1490 }
1491 #endif                                                  /* KEEP_UNUSED */
1492
1493
1494 static struct hwtype ether_hwtype = {
1495         "ether", "Ethernet", ARPHRD_ETHER, ETH_ALEN,
1496         pr_ether, NULL /* UNUSED in_ether */ , NULL
1497 };
1498
1499
1500 #endif                                                  /* HAVE_HWETHER */
1501
1502
1503 #if HAVE_HWPPP
1504
1505 #include <net/if_arp.h>
1506
1507 #ifdef KEEP_UNUSED
1508 /* Start the PPP encapsulation on the file descriptor. */
1509 static int do_ppp(int fd)
1510 {
1511         bb_error_msg(_("You cannot start PPP with this program."));
1512         return -1;
1513 }
1514 #endif                                                  /* KEEP_UNUSED */
1515
1516 static struct hwtype ppp_hwtype = {
1517         "ppp", "Point-Point Protocol", ARPHRD_PPP, 0,
1518         NULL, NULL, NULL /* UNUSED do_ppp */ , 0
1519 };
1520
1521
1522 #endif                                                  /* HAVE_PPP */
1523
1524 static struct hwtype *hwtypes[] = {
1525
1526         &loop_hwtype,
1527
1528 #if HAVE_HWSLIP
1529         &slip_hwtype,
1530         &cslip_hwtype,
1531         &slip6_hwtype,
1532         &cslip6_hwtype,
1533         &adaptive_hwtype,
1534 #endif
1535 #if HAVE_HWSTRIP
1536         &strip_hwtype,
1537 #endif
1538 #if HAVE_HWASH
1539         &ash_hwtype,
1540 #endif
1541 #if HAVE_HWETHER
1542         &ether_hwtype,
1543 #endif
1544 #if HAVE_HWTR
1545         &tr_hwtype,
1546 #ifdef ARPHRD_IEEE802_TR
1547         &tr_hwtype1,
1548 #endif
1549 #endif
1550 #if HAVE_HWAX25
1551         &ax25_hwtype,
1552 #endif
1553 #if HAVE_HWNETROM
1554         &netrom_hwtype,
1555 #endif
1556 #if HAVE_HWROSE
1557         &rose_hwtype,
1558 #endif
1559 #if HAVE_HWTUNNEL
1560         &tunnel_hwtype,
1561 #endif
1562 #if HAVE_HWPPP
1563         &ppp_hwtype,
1564 #endif
1565 #if HAVE_HWHDLCLAPB
1566         &hdlc_hwtype,
1567         &lapb_hwtype,
1568 #endif
1569 #if HAVE_HWARC
1570         &arcnet_hwtype,
1571 #endif
1572 #if HAVE_HWFR
1573         &dlci_hwtype,
1574         &frad_hwtype,
1575 #endif
1576 #if HAVE_HWSIT
1577         &sit_hwtype,
1578 #endif
1579 #if HAVE_HWFDDI
1580         &fddi_hwtype,
1581 #endif
1582 #if HAVE_HWHIPPI
1583         &hippi_hwtype,
1584 #endif
1585 #if HAVE_HWIRDA
1586         &irda_hwtype,
1587 #endif
1588 #if HAVE_HWEC
1589         &ec_hwtype,
1590 #endif
1591 #if HAVE_HWX25
1592         &x25_hwtype,
1593 #endif
1594         &unspec_hwtype,
1595         NULL
1596 };
1597
1598 #ifdef KEEP_UNUSED
1599 static short sVhwinit = 0;
1600
1601 static void hwinit()
1602 {
1603         loop_hwtype.title = _("Local Loopback");
1604         unspec_hwtype.title = _("UNSPEC");
1605 #if HAVE_HWSLIP
1606         slip_hwtype.title = _("Serial Line IP");
1607         cslip_hwtype.title = _("VJ Serial Line IP");
1608         slip6_hwtype.title = _("6-bit Serial Line IP");
1609         cslip6_hwtype.title = _("VJ 6-bit Serial Line IP");
1610         adaptive_hwtype.title = _("Adaptive Serial Line IP");
1611 #endif
1612 #if HAVE_HWETHER
1613         ether_hwtype.title = _("Ethernet");
1614 #endif
1615 #if HAVE_HWASH
1616         ash_hwtype.title = _("Ash");
1617 #endif
1618 #if HAVE_HWFDDI
1619         fddi_hwtype.title = _("Fiber Distributed Data Interface");
1620 #endif
1621 #if HAVE_HWHIPPI
1622         hippi_hwtype.title = _("HIPPI");
1623 #endif
1624 #if HAVE_HWAX25
1625         ax25_hwtype.title = _("AMPR AX.25");
1626 #endif
1627 #if HAVE_HWROSE
1628         rose_hwtype.title = _("AMPR ROSE");
1629 #endif
1630 #if HAVE_HWNETROM
1631         netrom_hwtype.title = _("AMPR NET/ROM");
1632 #endif
1633 #if HAVE_HWX25
1634         x25_hwtype.title = _("generic X.25");
1635 #endif
1636 #if HAVE_HWTUNNEL
1637         tunnel_hwtype.title = _("IPIP Tunnel");
1638 #endif
1639 #if HAVE_HWPPP
1640         ppp_hwtype.title = _("Point-to-Point Protocol");
1641 #endif
1642 #if HAVE_HWHDLCLAPB
1643         hdlc_hwtype.title = _("(Cisco)-HDLC");
1644         lapb_hwtype.title = _("LAPB");
1645 #endif
1646 #if HAVE_HWARC
1647         arcnet_hwtype.title = _("ARCnet");
1648 #endif
1649 #if HAVE_HWFR
1650         dlci_hwtype.title = _("Frame Relay DLCI");
1651         frad_hwtype.title = _("Frame Relay Access Device");
1652 #endif
1653 #if HAVE_HWSIT
1654         sit_hwtype.title = _("IPv6-in-IPv4");
1655 #endif
1656 #if HAVE_HWIRDA
1657         irda_hwtype.title = _("IrLAP");
1658 #endif
1659 #if HAVE_HWTR
1660         tr_hwtype.title = _("16/4 Mbps Token Ring");
1661 #ifdef ARPHRD_IEEE802_TR
1662         tr_hwtype1.title = _("16/4 Mbps Token Ring (New)");
1663 #endif
1664 #endif
1665 #if HAVE_HWEC
1666         ec_hwtype.title = _("Econet");
1667 #endif
1668         sVhwinit = 1;
1669 }
1670 #endif                                                  /* KEEP_UNUSED */
1671
1672 #ifdef IFF_PORTSEL
1673 static const char *if_port_text[][4] = {
1674         /* Keep in step with <linux/netdevice.h> */
1675         {"unknown", NULL, NULL, NULL},
1676         {"10base2", "bnc", "coax", NULL},
1677         {"10baseT", "utp", "tpe", NULL},
1678         {"AUI", "thick", "db15", NULL},
1679         {"100baseT", NULL, NULL, NULL},
1680         {"100baseTX", NULL, NULL, NULL},
1681         {"100baseFX", NULL, NULL, NULL},
1682         {NULL, NULL, NULL, NULL},
1683 };
1684 #endif
1685
1686 /* Check our hardware type table for this type. */
1687 static struct hwtype *get_hwntype(int type)
1688 {
1689         struct hwtype **hwp;
1690
1691 #ifdef KEEP_UNUSED
1692         if (!sVhwinit)
1693                 hwinit();
1694 #endif                                                  /* KEEP_UNUSED */
1695
1696         hwp = hwtypes;
1697         while (*hwp != NULL) {
1698                 if ((*hwp)->type == type)
1699                         return (*hwp);
1700                 hwp++;
1701         }
1702         return (NULL);
1703 }
1704
1705 /* return 1 if address is all zeros */
1706 static int hw_null_address(struct hwtype *hw, void *ap)
1707 {
1708         unsigned int i;
1709         unsigned char *address = (unsigned char *) ap;
1710
1711         for (i = 0; i < hw->alen; i++)
1712                 if (address[i])
1713                         return 0;
1714         return 1;
1715 }
1716
1717 static const char TRext[] = "\0\0k\0M";
1718
1719 static void print_bytes_scaled(unsigned long long ull, const char *end)
1720 {
1721         unsigned long long int_part;
1722         unsigned long frac_part;
1723         const char *ext;
1724         int i;
1725
1726         frac_part = 0;
1727         ext = TRext;
1728         int_part = ull;
1729         for (i = 0; i < 2; i++) {
1730                 if (int_part >= 1024) {
1731                         frac_part = ((int_part % 1024) * 10) / 1024;
1732                         int_part /= 1024;
1733                         ext += 2;       /* Kb, Mb */
1734                 }
1735         }
1736
1737         printf("X bytes:%Lu (%Lu.%lu %siB)%s", ull, int_part, frac_part, ext, end);
1738 }
1739
1740 static void ife_print(struct interface *ptr)
1741 {
1742         struct aftype *ap;
1743         struct hwtype *hw;
1744         int hf;
1745         int can_compress = 0;
1746
1747 #if HAVE_AFIPX
1748         static struct aftype *ipxtype = NULL;
1749 #endif
1750 #if HAVE_AFECONET
1751         static struct aftype *ectype = NULL;
1752 #endif
1753 #if HAVE_AFATALK
1754         static struct aftype *ddptype = NULL;
1755 #endif
1756 #if HAVE_AFINET6
1757         FILE *f;
1758         char addr6[40], devname[20];
1759         struct sockaddr_in6 sap;
1760         int plen, scope, dad_status, if_idx;
1761         char addr6p[8][5];
1762 #endif
1763
1764         ap = get_afntype(ptr->addr.sa_family);
1765         if (ap == NULL)
1766                 ap = get_afntype(0);
1767
1768         hf = ptr->type;
1769
1770         if (hf == ARPHRD_CSLIP || hf == ARPHRD_CSLIP6)
1771                 can_compress = 1;
1772
1773         hw = get_hwntype(hf);
1774         if (hw == NULL)
1775                 hw = get_hwntype(-1);
1776
1777         printf(_("%-9.9s Link encap:%s  "), ptr->name, _(hw->title));
1778         /* For some hardware types (eg Ash, ATM) we don't print the 
1779            hardware address if it's null.  */
1780         if (hw->print != NULL && (!(hw_null_address(hw, ptr->hwaddr) &&
1781                                                                 hw->suppress_null_addr)))
1782                 printf(_("HWaddr %s  "), hw->print(ptr->hwaddr));
1783 #ifdef IFF_PORTSEL
1784         if (ptr->flags & IFF_PORTSEL) {
1785                 printf(_("Media:%s"), if_port_text[ptr->map.port][0]);
1786                 if (ptr->flags & IFF_AUTOMEDIA)
1787                         printf(_("(auto)"));
1788         }
1789 #endif
1790         printf("\n");
1791
1792 #if HAVE_AFINET
1793         if (ptr->has_ip) {
1794                 printf(_("          %s addr:%s "), ap->name,
1795                            ap->sprint(&ptr->addr, 1));
1796                 if (ptr->flags & IFF_POINTOPOINT) {
1797                         printf(_(" P-t-P:%s "), ap->sprint(&ptr->dstaddr, 1));
1798                 }
1799                 if (ptr->flags & IFF_BROADCAST) {
1800                         printf(_(" Bcast:%s "), ap->sprint(&ptr->broadaddr, 1));
1801                 }
1802                 printf(_(" Mask:%s\n"), ap->sprint(&ptr->netmask, 1));
1803         }
1804 #endif
1805
1806 #if HAVE_AFINET6
1807
1808 #define IPV6_ADDR_ANY           0x0000U
1809
1810 #define IPV6_ADDR_UNICAST       0x0001U
1811 #define IPV6_ADDR_MULTICAST     0x0002U
1812 #define IPV6_ADDR_ANYCAST       0x0004U
1813
1814 #define IPV6_ADDR_LOOPBACK      0x0010U
1815 #define IPV6_ADDR_LINKLOCAL     0x0020U
1816 #define IPV6_ADDR_SITELOCAL     0x0040U
1817
1818 #define IPV6_ADDR_COMPATv4      0x0080U
1819
1820 #define IPV6_ADDR_SCOPE_MASK    0x00f0U
1821
1822 #define IPV6_ADDR_MAPPED        0x1000U
1823 #define IPV6_ADDR_RESERVED      0x2000U /* reserved address space */
1824
1825         if ((f = fopen(_PATH_PROCNET_IFINET6, "r")) != NULL) {
1826                 while (fscanf
1827                            (f, "%4s%4s%4s%4s%4s%4s%4s%4s %02x %02x %02x %02x %20s\n",
1828                                 addr6p[0], addr6p[1], addr6p[2], addr6p[3], addr6p[4],
1829                                 addr6p[5], addr6p[6], addr6p[7], &if_idx, &plen, &scope,
1830                                 &dad_status, devname) != EOF) {
1831                         if (!strcmp(devname, ptr->name)) {
1832                                 sprintf(addr6, "%s:%s:%s:%s:%s:%s:%s:%s",
1833                                                 addr6p[0], addr6p[1], addr6p[2], addr6p[3],
1834                                                 addr6p[4], addr6p[5], addr6p[6], addr6p[7]);
1835                                 inet_pton(AF_INET6, addr6,
1836                                                   (struct sockaddr *) &sap.sin6_addr);
1837                                 sap.sin6_family = AF_INET6;
1838                                 printf(_("          inet6 addr: %s/%d"),
1839                                            inet6_aftype.sprint((struct sockaddr *) &sap, 1),
1840                                            plen);
1841                                 printf(_(" Scope:"));
1842                                 switch (scope & IPV6_ADDR_SCOPE_MASK) {
1843                                 case 0:
1844                                         printf(_("Global"));
1845                                         break;
1846                                 case IPV6_ADDR_LINKLOCAL:
1847                                         printf(_("Link"));
1848                                         break;
1849                                 case IPV6_ADDR_SITELOCAL:
1850                                         printf(_("Site"));
1851                                         break;
1852                                 case IPV6_ADDR_COMPATv4:
1853                                         printf(_("Compat"));
1854                                         break;
1855                                 case IPV6_ADDR_LOOPBACK:
1856                                         printf(_("Host"));
1857                                         break;
1858                                 default:
1859                                         printf(_("Unknown"));
1860                                 }
1861                                 printf("\n");
1862                         }
1863                 }
1864                 fclose(f);
1865         }
1866 #endif
1867
1868 #if HAVE_AFIPX
1869         if (ipxtype == NULL)
1870                 ipxtype = get_afntype(AF_IPX);
1871
1872         if (ipxtype != NULL) {
1873                 if (ptr->has_ipx_bb)
1874                         printf(_("          IPX/Ethernet II addr:%s\n"),
1875                                    ipxtype->sprint(&ptr->ipxaddr_bb, 1));
1876                 if (ptr->has_ipx_sn)
1877                         printf(_("          IPX/Ethernet SNAP addr:%s\n"),
1878                                    ipxtype->sprint(&ptr->ipxaddr_sn, 1));
1879                 if (ptr->has_ipx_e2)
1880                         printf(_("          IPX/Ethernet 802.2 addr:%s\n"),
1881                                    ipxtype->sprint(&ptr->ipxaddr_e2, 1));
1882                 if (ptr->has_ipx_e3)
1883                         printf(_("          IPX/Ethernet 802.3 addr:%s\n"),
1884                                    ipxtype->sprint(&ptr->ipxaddr_e3, 1));
1885         }
1886 #endif
1887
1888 #if HAVE_AFATALK
1889         if (ddptype == NULL)
1890                 ddptype = get_afntype(AF_APPLETALK);
1891         if (ddptype != NULL) {
1892                 if (ptr->has_ddp)
1893                         printf(_("          EtherTalk Phase 2 addr:%s\n"),
1894                                    ddptype->sprint(&ptr->ddpaddr, 1));
1895         }
1896 #endif
1897
1898 #if HAVE_AFECONET
1899         if (ectype == NULL)
1900                 ectype = get_afntype(AF_ECONET);
1901         if (ectype != NULL) {
1902                 if (ptr->has_econet)
1903                         printf(_("          econet addr:%s\n"),
1904                                    ectype->sprint(&ptr->ecaddr, 1));
1905         }
1906 #endif
1907
1908         printf("          ");
1909         /* DONT FORGET TO ADD THE FLAGS IN ife_print_short, too */
1910         if (ptr->flags == 0)
1911                 printf(_("[NO FLAGS] "));
1912         if (ptr->flags & IFF_UP)
1913                 printf(_("UP "));
1914         if (ptr->flags & IFF_BROADCAST)
1915                 printf(_("BROADCAST "));
1916         if (ptr->flags & IFF_DEBUG)
1917                 printf(_("DEBUG "));
1918         if (ptr->flags & IFF_LOOPBACK)
1919                 printf(_("LOOPBACK "));
1920         if (ptr->flags & IFF_POINTOPOINT)
1921                 printf(_("POINTOPOINT "));
1922         if (ptr->flags & IFF_NOTRAILERS)
1923                 printf(_("NOTRAILERS "));
1924         if (ptr->flags & IFF_RUNNING)
1925                 printf(_("RUNNING "));
1926         if (ptr->flags & IFF_NOARP)
1927                 printf(_("NOARP "));
1928         if (ptr->flags & IFF_PROMISC)
1929                 printf(_("PROMISC "));
1930         if (ptr->flags & IFF_ALLMULTI)
1931                 printf(_("ALLMULTI "));
1932         if (ptr->flags & IFF_SLAVE)
1933                 printf(_("SLAVE "));
1934         if (ptr->flags & IFF_MASTER)
1935                 printf(_("MASTER "));
1936         if (ptr->flags & IFF_MULTICAST)
1937                 printf(_("MULTICAST "));
1938 #ifdef HAVE_DYNAMIC
1939         if (ptr->flags & IFF_DYNAMIC)
1940                 printf(_("DYNAMIC "));
1941 #endif
1942         /* DONT FORGET TO ADD THE FLAGS IN ife_print_short */
1943         printf(_(" MTU:%d  Metric:%d"), ptr->mtu, ptr->metric ? ptr->metric : 1);
1944 #ifdef SIOCSKEEPALIVE
1945         if (ptr->outfill || ptr->keepalive)
1946                 printf(_("  Outfill:%d  Keepalive:%d"), ptr->outfill, ptr->keepalive);
1947 #endif
1948         printf("\n");
1949
1950         /* If needed, display the interface statistics. */
1951
1952         if (ptr->statistics_valid) {
1953                 /* XXX: statistics are currently only printed for the primary address,
1954                  *      not for the aliases, although strictly speaking they're shared
1955                  *      by all addresses.
1956                  */
1957                 printf("          ");
1958
1959                 printf(_
1960                            ("RX packets:%Lu errors:%lu dropped:%lu overruns:%lu frame:%lu\n"),
1961                            ptr->stats.rx_packets, ptr->stats.rx_errors,
1962                            ptr->stats.rx_dropped, ptr->stats.rx_fifo_errors,
1963                            ptr->stats.rx_frame_errors);
1964                 if (can_compress)
1965                         printf(_("             compressed:%lu\n"),
1966                                    ptr->stats.rx_compressed);
1967                 printf("          ");
1968                 printf(_
1969                            ("TX packets:%Lu errors:%lu dropped:%lu overruns:%lu carrier:%lu\n"),
1970                            ptr->stats.tx_packets, ptr->stats.tx_errors,
1971                            ptr->stats.tx_dropped, ptr->stats.tx_fifo_errors,
1972                            ptr->stats.tx_carrier_errors);
1973                 printf(_("          collisions:%lu "), ptr->stats.collisions);
1974                 if (can_compress)
1975                         printf(_("compressed:%lu "), ptr->stats.tx_compressed);
1976                 if (ptr->tx_queue_len != -1)
1977                         printf(_("txqueuelen:%d "), ptr->tx_queue_len);
1978                 printf("\n          R");
1979                 print_bytes_scaled(ptr->stats.rx_bytes, "  T");
1980                 print_bytes_scaled(ptr->stats.tx_bytes, "\n");
1981
1982         }
1983
1984         if ((ptr->map.irq || ptr->map.mem_start || ptr->map.dma ||
1985                  ptr->map.base_addr)) {
1986                 printf("          ");
1987                 if (ptr->map.irq)
1988                         printf(_("Interrupt:%d "), ptr->map.irq);
1989                 if (ptr->map.base_addr >= 0x100)        /* Only print devices using it for 
1990                                                                                            I/O maps */
1991                         printf(_("Base address:0x%lx "),
1992                                    (unsigned long) ptr->map.base_addr);
1993                 if (ptr->map.mem_start) {
1994                         printf(_("Memory:%lx-%lx "), ptr->map.mem_start,
1995                                    ptr->map.mem_end);
1996                 }
1997                 if (ptr->map.dma)
1998                         printf(_("DMA chan:%x "), ptr->map.dma);
1999                 printf("\n");
2000         }
2001         printf("\n");
2002 }
2003
2004
2005 static int do_if_print(struct interface *ife, void *cookie)
2006 {
2007         int *opt_a = (int *) cookie;
2008         int res;
2009
2010         res = do_if_fetch(ife);
2011         if (res >= 0) {
2012                 if ((ife->flags & IFF_UP) || *opt_a)
2013                         ife_print(ife);
2014         }
2015         return res;
2016 }
2017
2018 static struct interface *lookup_interface(char *name)
2019 {
2020         struct interface *ife = NULL;
2021
2022         if (if_readlist_proc(name) < 0)
2023                 return NULL;
2024         ife = add_interface(name);
2025         return ife;
2026 }
2027
2028 /* for ipv4 add/del modes */
2029 static int if_print(char *ifname)
2030 {
2031         int res;
2032
2033         if (!ifname) {
2034                 res = for_all_interfaces(do_if_print, &interface_opt_a);
2035         } else {
2036                 struct interface *ife;
2037
2038                 ife = lookup_interface(ifname);
2039                 res = do_if_fetch(ife);
2040                 if (res >= 0)
2041                         ife_print(ife);
2042         }
2043         return res;
2044 }
2045
2046 int display_interfaces(char *ifname)
2047 {
2048         int status;
2049
2050         /* Create a channel to the NET kernel. */
2051         if ((skfd = sockets_open(0)) < 0) {
2052                 bb_perror_msg_and_die("socket");
2053         }
2054
2055         /* Do we have to show the current setup? */
2056         status = if_print(ifname);
2057         close(skfd);
2058         exit(status < 0);
2059 }