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