Rewrite the polling code. Instead of trying to do fancy polling enablement
[dragonfly.git] / sbin / ifconfig / ifconfig.c
1 /*
2  * Copyright (c) 1983, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#) Copyright (c) 1983, 1993 The Regents of the University of California.  All rights reserved.
30  * @(#)ifconfig.c       8.2 (Berkeley) 2/16/94
31  * $FreeBSD: src/sbin/ifconfig/ifconfig.c,v 1.96 2004/02/27 06:43:14 kan Exp $
32  * $DragonFly: src/sbin/ifconfig/ifconfig.c,v 1.22 2005/05/25 01:44:18 dillon Exp $
33  */
34
35 #include <sys/param.h>
36 #include <sys/ioctl.h>
37 #include <sys/socket.h>
38 #include <sys/sockio.h>
39 #include <sys/sysctl.h>
40 #include <sys/time.h>
41 #include <sys/module.h>
42 #include <sys/linker.h>
43
44 #include <net/ethernet.h>
45 #include <net/if.h>
46 #include <net/if_var.h>
47 #include <net/if_dl.h>
48 #include <net/if_types.h>
49 #include <net/route.h>
50
51 /* IP */
52 #include <netinet/in.h>
53 #include <netinet/in_var.h>
54 #include <arpa/inet.h>
55 #include <netdb.h>
56
57 #ifdef INET6
58 #include <netinet6/nd6.h>       /* Define ND6_INFINITE_LIFETIME */
59 #endif
60
61 #ifndef NO_IPX
62 /* IPX */
63 #define IPXIP
64 #define IPTUNNEL
65 #include <netipx/ipx.h>
66 #include <netipx/ipx_if.h>
67 #endif
68
69 /* Appletalk */
70 #include <netatalk/at.h>
71
72 /* XNS */
73 #ifdef NS
74 #define NSIP
75 #include <netns/ns.h>
76 #include <netns/ns_if.h>
77 #endif
78
79 /* OSI */
80
81 #include <ctype.h>
82 #include <err.h>
83 #include <errno.h>
84 #include <fcntl.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <unistd.h>
89 #include <ifaddrs.h>
90
91 #include "ifconfig.h"
92
93 /* wrapper for KAME-special getnameinfo() */
94 #ifndef NI_WITHSCOPEID
95 #define NI_WITHSCOPEID  0
96 #endif
97
98 /*
99  * Since "struct ifreq" is composed of various union members, callers
100  * should pay special attention to interprete the value.
101  * (.e.g. little/big endian difference in the structure.)
102  */
103 struct  ifreq           ifr, ridreq;
104 struct  ifaliasreq      addreq;
105 #ifdef INET6
106 struct  in6_ifreq       in6_ridreq;
107 struct  in6_aliasreq    in6_addreq = 
108   { { 0 }, 
109     { 0, 0, 0, 0, { { { 0 } } }, 0 }, 
110     { 0, 0, 0, 0, { { { 0 } } }, 0 }, 
111     { 0, 0, 0, 0, { { { 0 } } }, 0 }, 
112     0, 
113     { 0, 0, ND6_INFINITE_LIFETIME, ND6_INFINITE_LIFETIME } };
114 #endif
115 struct  sockaddr_in     netmask;
116 struct  netrange        at_nr;          /* AppleTalk net range */
117
118 char    name[IFNAMSIZ];
119 int     flags;
120 int     setaddr;
121 int     setipdst;
122 int     setmask;
123 int     doalias;
124 int     clearaddr;
125 int     newaddr = 1;
126 #ifdef INET6
127 static  int ip6lifetime;
128 #endif
129
130 struct  afswtch;
131
132 int supmedia = 0;
133 int listcloners = 0;
134 int printname = 0;              /* Print the name of the created interface. */
135
136 #ifdef INET6
137 char    addr_buf[MAXHOSTNAMELEN *2 + 1];        /*for getnameinfo()*/
138 #endif
139
140 void    Perror(const char *cmd);
141 void    checkatrange(struct sockaddr_at *);
142 int     ifconfig(int argc, char *const *argv, const struct afswtch *afp);
143 void    notealias(const char *, int, int, const struct afswtch *afp);
144 void    list_cloners(void);
145 void    printb(const char *s, unsigned value, const char *bits);
146 void    rt_xaddrs(caddr_t, caddr_t, struct rt_addrinfo *);
147 void    status(const struct afswtch *afp, int addrcount,
148                     struct sockaddr_dl *sdl, struct if_msghdr *ifm,
149                     struct ifa_msghdr *ifam);
150 void    tunnel_status(int s);
151 void    usage(void);
152 void    ifmaybeload(char *if_nm);
153
154 #ifdef INET6
155 void    in6_fillscopeid(struct sockaddr_in6 *sin6);
156 int     prefix(void *, int);
157 static  char *sec2str(time_t);
158 int     explicit_prefix = 0;
159 #endif
160
161 typedef void c_func(const char *cmd, int arg, int s, const struct afswtch *afp);
162 typedef void c_func2(const char *arg, const char *arg2, int s, const struct afswtch *afp);
163 c_func  setatphase, setatrange;
164 c_func  setifaddr, setifbroadaddr, setifdstaddr, setifnetmask;
165 c_func2 settunnel;
166 c_func  deletetunnel;
167 #ifdef INET6
168 c_func  setifprefixlen;
169 c_func  setip6flags;
170 c_func  setip6pltime;
171 c_func  setip6vltime;
172 c_func2 setip6lifetime;
173 c_func  setip6eui64;
174 #endif
175 c_func  setifipdst;
176 c_func  setifflags, setifmetric, setifmtu, setifcap;
177 c_func  clone_destroy;
178 c_func  setifname;
179
180
181 void clone_create(void);
182
183
184 #define NEXTARG         0xffffff
185 #define NEXTARG2        0xfffffe
186
187 const
188 struct  cmd {
189         const   char *c_name;
190         int     c_parameter;            /* NEXTARG means next argv */
191         void    (*c_func)(const char *, int, int, const struct afswtch *afp);
192         void    (*c_func2)(const char *, const char *, int, const struct afswtch *afp);
193 } cmds[] = {
194         { "up",         IFF_UP,         setifflags,     NULL },
195         { "down",       -IFF_UP,        setifflags,     NULL },
196         { "poll",       IFF_POLLING,    setifflags,     NULL },
197         { "-poll",      -IFF_POLLING,   setifflags,     NULL },
198         { "arp",        -IFF_NOARP,     setifflags,     NULL },
199         { "-arp",       IFF_NOARP,      setifflags,     NULL },
200         { "debug",      IFF_DEBUG,      setifflags,     NULL },
201         { "-debug",     -IFF_DEBUG,     setifflags,     NULL },
202         { "promisc",    IFF_PPROMISC,   setifflags,     NULL },
203         { "-promisc",   -IFF_PPROMISC,  setifflags,     NULL },
204         { "add",        IFF_UP,         notealias,      NULL },
205         { "alias",      IFF_UP,         notealias,      NULL },
206         { "-alias",     -IFF_UP,        notealias,      NULL },
207         { "delete",     -IFF_UP,        notealias,      NULL },
208         { "remove",     -IFF_UP,        notealias,      NULL },
209 #ifdef notdef
210 #define EN_SWABIPS      0x1000
211         { "swabips",    EN_SWABIPS,     setifflags,     NULL },
212         { "-swabips",   -EN_SWABIPS,    setifflags,     NULL },
213 #endif
214         { "netmask",    NEXTARG,        setifnetmask,   NULL },
215 #ifdef INET6
216         { "prefixlen",  NEXTARG,        setifprefixlen, NULL },
217         { "anycast",    IN6_IFF_ANYCAST, setip6flags,   NULL },
218         { "tentative",  IN6_IFF_TENTATIVE, setip6flags, NULL },
219         { "-tentative", -IN6_IFF_TENTATIVE, setip6flags, NULL },
220         { "deprecated", IN6_IFF_DEPRECATED, setip6flags, NULL },
221         { "-deprecated", -IN6_IFF_DEPRECATED, setip6flags, NULL },
222         { "autoconf",   IN6_IFF_AUTOCONF, setip6flags,  NULL },
223         { "-autoconf",  -IN6_IFF_AUTOCONF, setip6flags, NULL },
224         { "pltime",     NEXTARG,        setip6pltime,   NULL },
225         { "vltime",     NEXTARG,        setip6vltime,   NULL },
226         { "eui64",      0,              setip6eui64,    NULL },
227 #endif
228         { "range",      NEXTARG,        setatrange,     NULL },
229         { "phase",      NEXTARG,        setatphase,     NULL },
230         { "metric",     NEXTARG,        setifmetric,    NULL },
231         { "broadcast",  NEXTARG,        setifbroadaddr, NULL },
232         { "ipdst",      NEXTARG,        setifipdst,     NULL },
233         { "tunnel",     NEXTARG2,       NULL,           settunnel },
234         { "deletetunnel", 0,            deletetunnel,   NULL },
235         { "link0",      IFF_LINK0,      setifflags,     NULL },
236         { "-link0",     -IFF_LINK0,     setifflags,     NULL },
237         { "link1",      IFF_LINK1,      setifflags,     NULL },
238         { "-link1",     -IFF_LINK1,     setifflags,     NULL },
239         { "link2",      IFF_LINK2,      setifflags,     NULL },
240         { "-link2",     -IFF_LINK2,     setifflags,     NULL },
241 #if notyet
242         { "monitor",    IFF_MONITOR,    setifflags,     NULL },
243         { "-monitor",   -IFF_MONITOR,   setifflags,     NULL },
244         { "staticarp",  IFF_STATICARP,  setifflags,     NULL },
245         { "-staticarp", -IFF_STATICARP, setifflags,     NULL },
246 #endif
247
248 #ifdef USE_IF_MEDIA
249         { "media",      NEXTARG,        setmedia,       NULL },
250         { "mode",       NEXTARG,        setmediamode,   NULL },
251         { "mediaopt",   NEXTARG,        setmediaopt,    NULL },
252         { "-mediaopt",  NEXTARG,        unsetmediaopt,  NULL },
253 #endif
254 #ifdef USE_VLANS
255         { "vlan",       NEXTARG,        setvlantag,     NULL },
256         { "vlandev",    NEXTARG,        setvlandev,     NULL },
257         { "-vlandev",   NEXTARG,        unsetvlandev,   NULL },
258 #endif
259 #if 0
260         /* XXX `create' special-cased below */
261         {"create",      0,              clone_create,   NULL },
262         {"plumb",       0,              clone_create,   NULL },
263 #endif
264         {"destroy",     0,              clone_destroy,  NULL },
265         {"unplumb",     0,              clone_destroy,  NULL },
266 #ifdef USE_IEEE80211
267         { "ssid",       NEXTARG,        set80211ssid,   NULL },
268         { "nwid",       NEXTARG,        set80211ssid,   NULL },
269         { "stationname", NEXTARG,       set80211stationname,    NULL },
270         { "station",    NEXTARG,        set80211stationname,    NULL }, /* BSD/OS */
271         { "channel",    NEXTARG,        set80211channel,        NULL },
272         { "authmode",   NEXTARG,        set80211authmode,       NULL },
273         { "powersavemode", NEXTARG,     set80211powersavemode,  NULL },
274         { "powersave",  1,              set80211powersave,      NULL },
275         { "-powersave", 0,              set80211powersave,      NULL },
276         { "powersavesleep", NEXTARG,    set80211powersavesleep, NULL },
277         { "wepmode",    NEXTARG,        set80211wepmode,        NULL },
278         { "wep",        1,              set80211wep,    NULL },
279         { "-wep",       0,              set80211wep,    NULL },
280         { "weptxkey",   NEXTARG,        set80211weptxkey,       NULL },
281         { "wepkey",     NEXTARG,        set80211wepkey, NULL },
282         { "nwkey",      NEXTARG,        set80211nwkey,  NULL }, /* NetBSD */
283         { "-nwkey",     0,              set80211wep,    NULL },         /* NetBSD */
284         { "rtsthreshold",NEXTARG,       set80211rtsthreshold,   NULL },
285         { "protmode",   NEXTARG,        set80211protmode,       NULL },
286         { "txpower",    NEXTARG,        set80211txpower,        NULL },
287 #endif
288         { "rxcsum",     IFCAP_RXCSUM,   setifcap,       NULL },
289         { "-rxcsum",    -IFCAP_RXCSUM,  setifcap,       NULL },
290         { "txcsum",     IFCAP_TXCSUM,   setifcap,       NULL },
291         { "-txcsum",    -IFCAP_TXCSUM,  setifcap,       NULL },
292         { "netcons",    IFCAP_NETCONS,  setifcap,       NULL },
293         { "-netcons",   -IFCAP_NETCONS, setifcap,       NULL },
294         { "polling",    IFCAP_POLLING,  setifcap,       NULL },
295         { "-polling",   -IFCAP_POLLING, setifcap,       NULL },
296         { "vlanmtu",    IFCAP_VLAN_MTU,         setifcap,       NULL },
297         { "-vlanmtu",   -IFCAP_VLAN_MTU,        setifcap,       NULL },
298         { "vlanhwtag",  IFCAP_VLAN_HWTAGGING,   setifcap,       NULL },
299         { "-vlanhwtag", -IFCAP_VLAN_HWTAGGING,  setifcap,       NULL },
300         { "normal",     -IFF_LINK0,     setifflags,     NULL },
301         { "compress",   IFF_LINK0,      setifflags,     NULL },
302         { "noicmp",     IFF_LINK1,      setifflags,     NULL },
303         { "mtu",        NEXTARG,        setifmtu,       NULL },
304         { "name",       NEXTARG,        setifname,      NULL },
305         { NULL,         0,              setifaddr,      NULL },
306         { NULL,         0,              setifdstaddr,   NULL },
307 };
308
309 /*
310  * XNS support liberally adapted from code written at the University of
311  * Maryland principally by James O'Toole and Chris Torek.
312  */
313 typedef void af_status(int, struct rt_addrinfo *);
314 typedef void af_getaddr(const char *, int);
315 typedef void af_getprefix(const char *, int);
316
317 af_status       in_status, at_status, link_status;
318 af_getaddr      in_getaddr, at_getaddr, link_getaddr;
319
320 #ifndef NO_IPX
321 af_status       ipx_status;
322 af_getaddr      ipx_getaddr;
323 #endif
324
325 #ifdef INET6
326 af_status       in6_status;
327 af_getaddr      in6_getaddr;
328 af_getprefix    in6_getprefix;
329 #endif /*INET6*/
330 #ifdef NS
331 af_status       xns_status;
332 af_getaddr      xns_getaddr;
333 #endif
334
335 /* Known address families */
336 const
337 struct  afswtch {
338         const char *af_name;
339         short af_af;
340         af_status *af_status;
341         af_getaddr *af_getaddr;
342         af_getprefix *af_getprefix;
343         u_long af_difaddr;
344         u_long af_aifaddr;
345         caddr_t af_ridreq;
346         caddr_t af_addreq;
347 } afs[] = {
348 #define C(x) ((caddr_t) &x)
349         { "inet", AF_INET, in_status, in_getaddr, NULL,
350              SIOCDIFADDR, SIOCAIFADDR, C(ridreq), C(addreq) },
351 #ifdef INET6
352         { "inet6", AF_INET6, in6_status, in6_getaddr, in6_getprefix,
353              SIOCDIFADDR_IN6, SIOCAIFADDR_IN6,
354              C(in6_ridreq), C(in6_addreq) },
355 #endif /*INET6*/
356 #ifndef NO_IPX
357         { "ipx", AF_IPX, ipx_status, ipx_getaddr, NULL,
358              SIOCDIFADDR, SIOCAIFADDR, C(ridreq), C(addreq) },
359 #endif
360         { "atalk", AF_APPLETALK, at_status, at_getaddr, NULL,
361              SIOCDIFADDR, SIOCAIFADDR, C(addreq), C(addreq) },
362 #ifdef NS
363         { "ns", AF_NS, xns_status, xns_getaddr, NULL,
364              SIOCDIFADDR, SIOCAIFADDR, C(ridreq), C(addreq) },
365 #endif
366         { "link", AF_LINK, link_status, link_getaddr, NULL,
367              0, SIOCSIFLLADDR, NULL, C(ridreq) },
368         { "ether", AF_LINK, link_status, link_getaddr, NULL,
369              0, SIOCSIFLLADDR, NULL, C(ridreq) },
370         { "lladdr", AF_LINK, link_status, link_getaddr, NULL,
371              0, SIOCSIFLLADDR, NULL, C(ridreq) },
372         { NULL, 0,      NULL, NULL, NULL,       0, 0,   NULL, NULL }
373 };
374
375 /*
376  * Expand the compacted form of addresses as returned via the
377  * configuration read via sysctl().
378  */
379
380 #define ROUNDUP(a) \
381         ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
382 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
383
384 void
385 rt_xaddrs(caddr_t cp, caddr_t cplim, struct rt_addrinfo *rtinfo)
386 {
387         struct sockaddr *sa;
388         int i;
389
390         memset(rtinfo->rti_info, 0, sizeof(rtinfo->rti_info));
391         for (i = 0; (i < RTAX_MAX) && (cp < cplim); i++) {
392                 if ((rtinfo->rti_addrs & (1 << i)) == 0)
393                         continue;
394                 rtinfo->rti_info[i] = sa = (struct sockaddr *)cp;
395                 ADVANCE(cp, sa);
396         }
397 }
398
399
400 void
401 usage(void)
402 {
403 #ifndef INET6
404         fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
405         "usage: ifconfig interface address_family [address [dest_address]]",
406         "                [parameters]",
407         "       ifconfig -C",
408         "       ifconfig interface create",
409         "       ifconfig -a [-d] [-m] [-u] [address_family]",
410         "       ifconfig -l [-d] [-u] [address_family]",
411         "       ifconfig [-d] [-m] [-u]");
412 #else
413         fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
414         "usage: ifconfig [-L] interface address_family [address [dest_address]]",
415         "                [parameters]",
416         "       ifconfig -C",
417         "       ifconfig interface create",
418         "       ifconfig -a [-L] [-d] [-m] [-u] [address_family]",
419         "       ifconfig -l [-d] [-u] [address_family]",
420         "       ifconfig [-L] [-d] [-m] [-u]");
421 #endif
422         exit(1);
423 }
424
425 int
426 main(int argc, char * const *argv)
427 {
428         int c;
429         int all, namesonly, downonly, uponly;
430         int need_nl = 0, count = 0;
431         const struct afswtch *afp = 0;
432         int addrcount, ifindex;
433         struct  if_msghdr *ifm, *nextifm;
434         struct  ifa_msghdr *ifam;
435         struct  sockaddr_dl *sdl;
436         char    *buf, *lim, *next;
437
438         size_t needed;
439         int mib[6];
440
441         /* Parse leading line options */
442         all = downonly = uponly = namesonly = 0;
443         while ((c = getopt(argc, argv, "adlmuC"
444 #ifdef INET6
445                                         "L"
446 #endif
447                         )) != -1) {
448                 switch (c) {
449                 case 'a':       /* scan all interfaces */
450                         all++;
451                         break;
452                 case 'd':       /* restrict scan to "down" interfaces */
453                         downonly++;
454                         break;
455                 case 'l':       /* scan interface names only */
456                         namesonly++;
457                         break;
458                 case 'm':       /* show media choices in status */
459                         supmedia = 1;
460                         break;
461                 case 'u':       /* restrict scan to "up" interfaces */
462                         uponly++;
463                         break;
464                 case 'C':
465                         listcloners = 1;
466                         break;
467 #ifdef INET6
468                 case 'L':
469                         ip6lifetime++;  /* print IPv6 address lifetime */
470                         break;
471 #endif
472                 default:
473                         usage();
474                         break;
475                 }
476         }
477         argc -= optind;
478         argv += optind;
479
480         if (listcloners) {
481                 /* -C must be solitary */
482                 if (all || supmedia || uponly || downonly || namesonly ||
483                     argc > 0)
484                         usage();
485                 
486                 list_cloners();
487                 exit(0);
488         }
489
490         /* -l cannot be used with -a or -m */
491         if (namesonly && (all || supmedia))
492                 usage();
493
494         /* nonsense.. */
495         if (uponly && downonly)
496                 usage();
497
498         /* no arguments is equivalent to '-a' */
499         if (!namesonly && argc < 1)
500                 all = 1;
501
502         /* -a and -l allow an address family arg to limit the output */
503         if (all || namesonly) {
504                 if (argc > 1)
505                         usage();
506
507                 ifindex = 0;
508                 if (argc == 1) {
509                         for (afp = afs; afp->af_name; afp++)
510                                 if (strcmp(afp->af_name, *argv) == 0) {
511                                         argc--, argv++;
512                                         break;
513                                 }
514                         if (afp->af_name == NULL)
515                                 usage();
516                         /* leave with afp non-zero */
517                 }
518         } else {
519                 /* not listing, need an argument */
520                 if (argc < 1)
521                         usage();
522
523                 strncpy(name, *argv, sizeof(name));
524                 argc--, argv++;
525
526                 /* check and maybe load support for this interface */
527                 ifmaybeload(name);
528
529                 /*
530                  * NOTE:  We must special-case the `create' command right
531                  * here as we would otherwise fail when trying to find
532                  * the interface.
533                  */
534                 if (argc > 0 && (strcmp(argv[0], "create") == 0 ||
535                     strcmp(argv[0], "plumb") == 0)) {
536                         clone_create();
537                         argc--, argv++;
538                         if (argc == 0)
539                                 goto end;
540                 }
541                 ifindex = if_nametoindex(name);
542                 if (ifindex == 0)
543                         errx(1, "interface %s does not exist", name);
544         }
545
546         /* Check for address family */
547         if (argc > 0) {
548                 for (afp = afs; afp->af_name; afp++)
549                         if (strcmp(afp->af_name, *argv) == 0) {
550                                 argc--, argv++;
551                                 break;
552                         }
553                 if (afp->af_name == NULL)
554                         afp = NULL;     /* not a family, NULL */
555         }
556
557 retry:
558         mib[0] = CTL_NET;
559         mib[1] = PF_ROUTE;
560         mib[2] = 0;
561         mib[3] = 0;                     /* address family */
562         mib[4] = NET_RT_IFLIST;
563         mib[5] = ifindex;               /* interface index */
564
565         /* if particular family specified, only ask about it */
566         if (afp)
567                 mib[3] = afp->af_af;
568
569         if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
570                 errx(1, "iflist-sysctl-estimate");
571         if ((buf = malloc(needed)) == NULL)
572                 errx(1, "malloc");
573         if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
574                 if (errno == ENOMEM && count++ < 10) {
575                         warnx("Routing table grew, retrying");
576                         free(buf);
577                         sleep(1);
578                         goto retry;
579                 }
580                 errx(1, "actual retrieval of interface table");
581         }
582         lim = buf + needed;
583
584         next = buf;
585         while (next < lim) {
586
587                 ifm = (struct if_msghdr *)next;
588                 
589                 if (ifm->ifm_type == RTM_IFINFO) {
590 #if  notyet
591                         if (ifm->ifm_data.ifi_datalen == 0)
592                                 ifm->ifm_data.ifi_datalen = sizeof(struct if_data);
593                         sdl = (struct sockaddr_dl *)((char *)ifm + sizeof(struct if_msghdr) -
594                              sizeof(struct if_data) + ifm->ifm_data.ifi_datalen);
595 #else
596                        sdl = (struct sockaddr_dl *)(ifm + 1);
597 #endif
598                         flags = ifm->ifm_flags;
599                 } else {
600                         fprintf(stderr, "out of sync parsing NET_RT_IFLIST\n");
601                         fprintf(stderr, "expected %d, got %d\n", RTM_IFINFO,
602                                 ifm->ifm_type);
603                         fprintf(stderr, "msglen = %d\n", ifm->ifm_msglen);
604                         fprintf(stderr, "buf:%p, next:%p, lim:%p\n", buf, next,
605                                 lim);
606                         exit (1);
607                 }
608
609                 next += ifm->ifm_msglen;
610                 ifam = NULL;
611                 addrcount = 0;
612                 while (next < lim) {
613
614                         nextifm = (struct if_msghdr *)next;
615
616                         if (nextifm->ifm_type != RTM_NEWADDR)
617                                 break;
618
619                         if (ifam == NULL)
620                                 ifam = (struct ifa_msghdr *)nextifm;
621
622                         addrcount++;
623                         next += nextifm->ifm_msglen;
624                 }
625                 memcpy(name, sdl->sdl_data,
626                     sizeof(name) < sdl->sdl_nlen ?
627                     sizeof(name)-1 : sdl->sdl_nlen);
628                 name[sizeof(name) < sdl->sdl_nlen ?
629                     sizeof(name)-1 : sdl->sdl_nlen] = '\0';
630
631                 if (all || namesonly) {
632                         size_t len;
633
634                         /* sdl_data may not be terminated, don't use strlcpy */
635                         if ((len = sdl->sdl_nlen) > sizeof(name) - 1)
636                                 len = sizeof(name) - 1;
637                         bcopy(sdl->sdl_data, name, len);
638                         name[len] = 0;
639
640                         if (uponly)
641                                 if ((flags & IFF_UP) == 0)
642                                         continue; /* not up */
643                         if (downonly)
644                                 if (flags & IFF_UP)
645                                         continue; /* not down */
646                         if (namesonly) {
647                                 if (afp == NULL ||
648                                         afp->af_status != link_status ||
649                                         sdl->sdl_type == IFT_ETHER) {
650                                         if (need_nl)
651                                                 putchar(' ');
652                                         fputs(name, stdout);
653                                         need_nl++;
654                                 }
655                                 continue;
656                         }
657                 }
658
659                 if (argc > 0)
660                         ifconfig(argc, argv, afp);
661                 else
662                         status(afp, addrcount, sdl, ifm, ifam);
663         }
664         free(buf);
665
666         if (namesonly && need_nl > 0)
667                 putchar('\n');
668 end:
669         if (printname)
670                 printf("%s\n", name);
671
672         exit (0);
673 }
674
675
676 int
677 ifconfig(int argc, char *const *argv, const struct afswtch *afp)
678 {
679         int s;
680
681         if (afp == NULL)
682                 afp = &afs[0];
683         ifr.ifr_addr.sa_family = afp->af_af == AF_LINK ? AF_INET : afp->af_af;
684         strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
685
686         if ((s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0)) < 0)
687                 err(1, "socket");
688
689         while (argc > 0) {
690                 const struct cmd *p;
691
692                 for (p = cmds; p->c_name; p++)
693                         if (strcmp(*argv, p->c_name) == 0)
694                                 break;
695                 if (p->c_name == 0 && setaddr)
696                         p++;    /* got src, do dst */
697                 if (p->c_func || p->c_func2) {
698                         if (p->c_parameter == NEXTARG) {
699                                 if (argv[1] == NULL)
700                                         errx(1, "'%s' requires argument",
701                                             p->c_name);
702                                 (*p->c_func)(argv[1], 0, s, afp);
703                                 argc--, argv++;
704                         } else if (p->c_parameter == NEXTARG2) {
705                                 if (argc < 3)
706                                         errx(1, "'%s' requires 2 arguments",
707                                             p->c_name);
708                                 (*p->c_func2)(argv[1], argv[2], s, afp);
709                                 argc -= 2, argv += 2;
710                         } else
711                                 (*p->c_func)(*argv, p->c_parameter, s, afp);
712                 }
713                 argc--, argv++;
714         }
715 #ifdef INET6
716         if (ifr.ifr_addr.sa_family == AF_INET6 && explicit_prefix == 0) {
717                 /* Aggregatable address architecture defines all prefixes
718                    are 64. So, it is convenient to set prefixlen to 64 if
719                    it is not specified. */
720                 setifprefixlen("64", 0, s, afp);
721                 /* in6_getprefix("64", MASK) if MASK is available here... */
722         }
723 #endif
724 #ifndef NO_IPX
725         if (setipdst && ifr.ifr_addr.sa_family == AF_IPX) {
726                 struct ipxip_req rq;
727                 int size = sizeof(rq);
728
729                 rq.rq_ipx = addreq.ifra_addr;
730                 rq.rq_ip = addreq.ifra_dstaddr;
731
732                 if (setsockopt(s, 0, SO_IPXIP_ROUTE, &rq, size) < 0)
733                         Perror("Encapsulation Routing");
734         }
735 #endif
736         if (ifr.ifr_addr.sa_family == AF_APPLETALK)
737                 checkatrange((struct sockaddr_at *) &addreq.ifra_addr);
738 #ifdef NS
739         if (setipdst && ifr.ifr_addr.sa_family == AF_NS) {
740                 struct nsip_req rq;
741                 int size = sizeof(rq);
742
743                 rq.rq_ns = addreq.ifra_addr;
744                 rq.rq_ip = addreq.ifra_dstaddr;
745
746                 if (setsockopt(s, 0, SO_NSIP_ROUTE, &rq, size) < 0)
747                         Perror("Encapsulation Routing");
748         }
749 #endif
750         if (clearaddr) {
751                 if (afp->af_ridreq == NULL || afp->af_difaddr == 0) {
752                         warnx("interface %s cannot change %s addresses!",
753                               name, afp->af_name);
754                         clearaddr = NULL;
755                 }
756         }
757         if (clearaddr) {
758                 int ret;
759                 strncpy(afp->af_ridreq, name, sizeof ifr.ifr_name);
760                 if ((ret = ioctl(s, afp->af_difaddr, afp->af_ridreq)) < 0) {
761                         if (errno == EADDRNOTAVAIL && (doalias >= 0)) {
762                                 /* means no previous address for interface */
763                         } else
764                                 Perror("ioctl (SIOCDIFADDR)");
765                 }
766         }
767         if (newaddr) {
768                 if (afp->af_addreq == NULL || afp->af_aifaddr == 0) {
769                         warnx("interface %s cannot change %s addresses!",
770                               name, afp->af_name);
771                         newaddr = 0;
772                 }
773         }
774         if (newaddr && (setaddr || setmask)) {
775                 strncpy(afp->af_addreq, name, sizeof ifr.ifr_name);
776                 if (ioctl(s, afp->af_aifaddr, afp->af_addreq) < 0)
777                         Perror("ioctl (SIOCAIFADDR)");
778         }
779         close(s);
780         return(0);
781 }
782 #define RIDADDR 0
783 #define ADDR    1
784 #define MASK    2
785 #define DSTADDR 3
786
787 /*ARGSUSED*/
788 void
789 setifaddr(const char *addr, int param __unused, int s __unused,
790           const struct afswtch *afp)
791 {
792         if (*afp->af_getaddr == NULL)
793                 return;
794         /*
795          * Delay the ioctl to set the interface addr until flags are all set.
796          * The address interpretation may depend on the flags,
797          * and the flags may change when the address is set.
798          */
799         setaddr++;
800         if (doalias == 0 && afp->af_af != AF_LINK)
801                 clearaddr = 1;
802         (*afp->af_getaddr)(addr, (doalias >= 0 ? ADDR : RIDADDR));
803 }
804
805 void
806 settunnel(const char *src, const char *dst, int s, const struct afswtch *afp)
807 {
808         struct addrinfo hints, *srcres, *dstres;
809         struct ifaliasreq addr_req;
810         int ecode;
811 #ifdef INET6
812         struct in6_aliasreq in6_addr_req; 
813 #endif
814
815         memset(&hints, 0, sizeof(hints));
816         hints.ai_family = afp->af_af;
817
818         if ((ecode = getaddrinfo(src, NULL, NULL, &srcres)) != 0)
819                 errx(1, "error in parsing address string: %s",
820                     gai_strerror(ecode));
821
822         if ((ecode = getaddrinfo(dst, NULL, NULL, &dstres)) != 0)  
823                 errx(1, "error in parsing address string: %s",
824                     gai_strerror(ecode));
825
826         if (srcres->ai_addr->sa_family != dstres->ai_addr->sa_family)
827                 errx(1,
828                     "source and destination address families do not match");
829
830         switch (srcres->ai_addr->sa_family) {
831         case AF_INET:
832                 memset(&addr_req, 0, sizeof(addr_req));
833                 strncpy(addr_req.ifra_name, name, IFNAMSIZ);
834                 memcpy(&addr_req.ifra_addr, srcres->ai_addr,
835                     srcres->ai_addr->sa_len);
836                 memcpy(&addr_req.ifra_dstaddr, dstres->ai_addr,
837                     dstres->ai_addr->sa_len);
838
839                 if (ioctl(s, SIOCSIFPHYADDR, &addr_req) < 0)
840                         warn("SIOCSIFPHYADDR");
841                 break;
842
843 #ifdef INET6
844         case AF_INET6:
845                 memset(&in6_addr_req, 0, sizeof(in6_addr_req));
846                 strncpy(in6_addr_req.ifra_name, name, IFNAMSIZ);
847                 memcpy(&in6_addr_req.ifra_addr, srcres->ai_addr,
848                     srcres->ai_addr->sa_len);
849                 memcpy(&in6_addr_req.ifra_dstaddr, dstres->ai_addr,
850                     dstres->ai_addr->sa_len);
851
852                 if (ioctl(s, SIOCSIFPHYADDR_IN6, &in6_addr_req) < 0)
853                         warn("SIOCSIFPHYADDR_IN6");
854                 break;
855 #endif /* INET6 */
856
857         default:
858                 warn("address family not supported");
859         }
860
861         freeaddrinfo(srcres);
862         freeaddrinfo(dstres);
863 }
864
865 /* ARGSUSED */
866 void
867 deletetunnel(const char *vname __unused, int param __unused, int s,
868              const struct afswtch *afp __unused)
869 {
870         if (ioctl(s, SIOCDIFPHYADDR, &ifr) < 0)
871                 err(1, "SIOCDIFPHYADDR");
872 }
873
874 void
875 setifnetmask(const char *addr, int dummy __unused, int s __unused,
876              const struct afswtch *afp)
877 {
878         if (*afp->af_getaddr == NULL)
879                 return;
880         setmask++;
881         (*afp->af_getaddr)(addr, MASK);
882 }
883
884 #ifdef INET6
885 void
886 setifprefixlen(const char *addr, int dummy __unused, int s __unused,
887                const struct afswtch *afp)
888 {
889         if (*afp->af_getprefix)
890                 (*afp->af_getprefix)(addr, MASK);
891         explicit_prefix = 1;
892 }
893
894 void
895 setip6flags(const char *dummyaddr __unused, int flag, int dummysoc __unused,
896             const struct afswtch *afp)
897 {
898         if (afp->af_af != AF_INET6)
899                 err(1, "address flags can be set only for inet6 addresses");
900
901         if (flag < 0)
902                 in6_addreq.ifra_flags &= ~(-flag);
903         else
904                 in6_addreq.ifra_flags |= flag;
905 }
906
907 void
908 setip6pltime(const char *seconds, int dummy __unused, int s,
909              const struct afswtch *afp)
910 {
911         setip6lifetime("pltime", seconds, s, afp);
912 }
913
914 void
915 setip6vltime(const char *seconds, int dummy __unused, int s,
916              const struct afswtch *afp)
917 {
918         setip6lifetime("vltime", seconds, s, afp);
919 }
920
921 void
922 setip6lifetime(const char *cmd, const char *val, int s __unused,
923                const struct afswtch *afp)
924 {
925         time_t newval, t;
926         char *ep;
927
928         t = time(NULL);
929         newval = (time_t)strtoul(val, &ep, 0);
930         if (val == ep)
931                 errx(1, "invalid %s", cmd);
932         if (afp->af_af != AF_INET6)
933                 errx(1, "%s not allowed for the AF", cmd);
934         if (strcmp(cmd, "vltime") == 0) {
935                 in6_addreq.ifra_lifetime.ia6t_expire = t + newval;
936                 in6_addreq.ifra_lifetime.ia6t_vltime = newval;
937         } else if (strcmp(cmd, "pltime") == 0) {
938                 in6_addreq.ifra_lifetime.ia6t_preferred = t + newval;
939                 in6_addreq.ifra_lifetime.ia6t_pltime = newval;
940         }
941 }
942
943 void
944 setip6eui64(const char *cmd, int dummy __unused, int s __unused,
945             const struct afswtch *afp)
946 {
947         struct ifaddrs *ifap, *ifa;
948         const struct sockaddr_in6 *sin6 = NULL;
949         const struct in6_addr *lladdr = NULL;
950         struct in6_addr *in6;
951
952         if (afp->af_af != AF_INET6)
953                 errx(EXIT_FAILURE, "%s not allowed for the AF", cmd);
954         in6 = (struct in6_addr *)&in6_addreq.ifra_addr.sin6_addr;
955         if (memcmp(&in6addr_any.s6_addr[8], &in6->s6_addr[8], 8) != 0)
956                 errx(EXIT_FAILURE, "interface index is already filled");
957         if (getifaddrs(&ifap) != 0)
958                 err(EXIT_FAILURE, "getifaddrs");
959         for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
960                 if (ifa->ifa_addr->sa_family == AF_INET6 &&
961                     strcmp(ifa->ifa_name, name) == 0) {
962                         sin6 = (const struct sockaddr_in6 *)ifa->ifa_addr;
963                         if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
964                                 lladdr = &sin6->sin6_addr;
965                                 break;
966                         }
967                 }
968         }
969         if (!lladdr)
970                 errx(EXIT_FAILURE, "could not determine link local address"); 
971
972         memcpy(&in6->s6_addr[8], &lladdr->s6_addr[8], 8);
973
974         freeifaddrs(ifap);
975 }
976 #endif
977
978 void
979 setifbroadaddr(const char *addr, int dummy __unused, int s __unused,
980                const struct afswtch *afp)
981 {
982         if (*afp->af_getaddr == NULL)
983                 return;
984         (*afp->af_getaddr)(addr, DSTADDR);
985 }
986
987 void
988 setifipdst(const char *addr, int dummy __unused, int s __unused,
989            const struct afswtch *afp __unused)
990 {
991         in_getaddr(addr, DSTADDR);
992         setipdst++;
993         clearaddr = 0;
994         newaddr = 0;
995 }
996 #define rqtosa(x) (&(((struct ifreq *)(afp->x))->ifr_addr))
997
998 void
999 notealias(const char *addr __unused, int param, int s __unused,
1000           const struct afswtch *afp)
1001 {
1002         if (setaddr && doalias == 0 && param < 0)
1003                 if (afp->af_addreq != NULL && afp->af_ridreq != NULL)
1004                         bcopy((caddr_t)rqtosa(af_addreq),
1005                               (caddr_t)rqtosa(af_ridreq),
1006                               rqtosa(af_addreq)->sa_len);
1007         doalias = param;
1008         if (param < 0) {
1009                 clearaddr = 1;
1010                 newaddr = 0;
1011         } else
1012                 clearaddr = 0;
1013 }
1014
1015 /*ARGSUSED*/
1016 void
1017 setifdstaddr(const char *addr, int param __unused, int s __unused,
1018              const struct afswtch *afp)
1019 {
1020         if (*afp->af_getaddr == NULL)
1021                 return;
1022         (*afp->af_getaddr)(addr, DSTADDR);
1023 }
1024
1025 /*
1026  * Note: doing an SIOCIGIFFLAGS scribbles on the union portion
1027  * of the ifreq structure, which may confuse other parts of ifconfig.
1028  * Make a private copy so we can avoid that.
1029  */
1030 void
1031 setifflags(const char *vname, int value, int s,
1032            const struct afswtch *afp __unused)
1033 {
1034         struct ifreq            my_ifr;
1035
1036         bcopy((char *)&ifr, (char *)&my_ifr, sizeof(struct ifreq));
1037
1038         if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&my_ifr) < 0) {
1039                 Perror("ioctl (SIOCGIFFLAGS)");
1040                 exit(1);
1041         }
1042         strncpy(my_ifr.ifr_name, name, sizeof (my_ifr.ifr_name));
1043         flags = (my_ifr.ifr_flags & 0xffff) | (my_ifr.ifr_flagshigh << 16);
1044
1045         if (value < 0) {
1046                 value = -value;
1047                 flags &= ~value;
1048         } else
1049                 flags |= value;
1050         my_ifr.ifr_flags = flags & 0xffff;
1051         my_ifr.ifr_flagshigh = flags >> 16;
1052         if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&my_ifr) < 0)
1053                 Perror(vname);
1054 }
1055
1056 void
1057 setifcap(const char *vname, int value, int s,
1058          const struct afswtch *afp __unused)
1059 {
1060
1061         if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) < 0) {
1062                 Perror("ioctl (SIOCGIFCAP)");
1063                 exit(1);
1064         }
1065         flags = ifr.ifr_curcap;
1066         if (value < 0) {
1067                 value = -value;
1068                 flags &= ~value;
1069         } else
1070                 flags |= value;
1071         ifr.ifr_reqcap = flags;
1072         if (ioctl(s, SIOCSIFCAP, (caddr_t)&ifr) < 0)
1073                 Perror(vname);
1074 }
1075
1076 void
1077 setifmetric(const char *val, int dummy __unused, int s,
1078             const struct afswtch *afp __unused)
1079 {
1080         strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
1081         ifr.ifr_metric = atoi(val);
1082         if (ioctl(s, SIOCSIFMETRIC, (caddr_t)&ifr) < 0)
1083                 warn("ioctl (set metric)");
1084 }
1085
1086 void
1087 setifmtu(const char *val, int dummy __unused, int s,
1088          const struct afswtch *afp __unused)
1089 {
1090         strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
1091         ifr.ifr_mtu = atoi(val);
1092         if (ioctl(s, SIOCSIFMTU, (caddr_t)&ifr) < 0)
1093                 warn("ioctl (set mtu)");
1094 }
1095
1096 void
1097 setifname(const char *val, int dummy __unused, int s, 
1098           const struct afswtch *afp __unused)
1099 {
1100         char    *newname;
1101
1102         newname = strdup(val);
1103         
1104         ifr.ifr_data = newname;
1105         if (ioctl(s, SIOCSIFNAME, (caddr_t)&ifr) < 0) {
1106                 warn("ioctl (set name)");
1107                 free(newname);
1108                 return;
1109         }
1110         strlcpy(name, newname, sizeof(name));
1111
1112         free(newname);
1113
1114         /*
1115          * Even if we just created the interface, we don't need to print
1116          * its name because we just nailed it down separately.
1117          */
1118         printname = 0;
1119 }
1120
1121 #define IFFBITS \
1122 "\020\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5POINTOPOINT\6SMART\7RUNNING" \
1123 "\10NOARP\11PROMISC\12ALLMULTI\13OACTIVE\14SIMPLEX\15LINK0\16LINK1\17LINK2" \
1124 "\20MULTICAST\21POLLING\23MONITOR\24STATICARP"
1125
1126 #define IFCAPBITS \
1127 "\020\1RXCSUM\2TXCSUM\3NETCONS\4VLAN_MTU\5VLAN_HWTAGGING\6JUMBO_MTU\7POLLING"
1128
1129 /*
1130  * Print the status of the interface.  If an address family was
1131  * specified, show it and it only; otherwise, show them all.
1132  */
1133 void
1134 status(const struct afswtch *afp, int addrcount, struct sockaddr_dl *sdl,
1135        struct if_msghdr *ifm, struct ifa_msghdr *ifam)
1136 {
1137         const struct afswtch *p = NULL;
1138         struct  rt_addrinfo info;
1139         int allfamilies, s;
1140         struct ifstat ifs;
1141
1142         if (afp == NULL) {
1143                 allfamilies = 1;
1144                 afp = &afs[0];
1145         } else
1146                 allfamilies = 0;
1147
1148         ifr.ifr_addr.sa_family = afp->af_af == AF_LINK ? AF_INET : afp->af_af;
1149         strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
1150
1151         if ((s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0)) < 0)
1152                 err(1, "socket");
1153
1154         printf("flags %08x\n", flags);
1155         printf("%s: ", name);
1156         printb("flags", flags, IFFBITS);
1157         if (ifm->ifm_data.ifi_metric)
1158                 printf(" metric %ld", ifm->ifm_data.ifi_metric);
1159         if (ifm->ifm_data.ifi_mtu)
1160                 printf(" mtu %ld", ifm->ifm_data.ifi_mtu);
1161         putchar('\n');
1162
1163         if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) == 0) {
1164                 if (ifr.ifr_curcap != 0) {
1165                         printb("\toptions", ifr.ifr_curcap, IFCAPBITS);
1166                         putchar('\n');
1167                 }
1168                 if (supmedia && ifr.ifr_reqcap != 0) {
1169                         printf("\tcapability list:\n");
1170                         printb("\t\t", ifr.ifr_reqcap, IFCAPBITS);
1171                         putchar('\n');
1172                 }
1173         }
1174
1175         tunnel_status(s);
1176
1177         while (addrcount > 0) {
1178                 
1179                 info.rti_addrs = ifam->ifam_addrs;
1180
1181                 /* Expand the compacted addresses */
1182                 rt_xaddrs((char *)(ifam + 1), ifam->ifam_msglen + (char *)ifam,
1183                           &info);
1184
1185                 if (!allfamilies) {
1186                         if (afp->af_af == info.rti_info[RTAX_IFA]->sa_family) {
1187                                 p = afp;
1188                                 (*p->af_status)(s, &info);
1189                         }
1190                 } else for (p = afs; p->af_name; p++) {
1191                         if (p->af_af == info.rti_info[RTAX_IFA]->sa_family)
1192                                 (*p->af_status)(s, &info);
1193                 }
1194                 addrcount--;
1195                 ifam = (struct ifa_msghdr *)((char *)ifam + ifam->ifam_msglen);
1196         }
1197         if (allfamilies || afp->af_status == link_status)
1198                 link_status(s, (struct rt_addrinfo *)sdl);
1199 #ifdef USE_IF_MEDIA
1200         if (allfamilies || afp->af_status == media_status)
1201                 media_status(s, NULL);
1202 #endif
1203 #ifdef USE_VLANS
1204         if (allfamilies || afp->af_status == vlan_status)
1205                 vlan_status(s, NULL);
1206 #endif
1207 #ifdef USE_IEEE80211
1208         if (allfamilies || afp->af_status == ieee80211_status)
1209                 ieee80211_status(s, NULL);
1210 #endif
1211         strncpy(ifs.ifs_name, name, sizeof ifs.ifs_name);
1212         if (ioctl(s, SIOCGIFSTATUS, &ifs) == 0) 
1213                 printf("%s", ifs.ascii);
1214
1215         if (!allfamilies && !p &&
1216 #ifdef USE_IF_MEDIA
1217             afp->af_status != media_status &&
1218 #endif
1219             afp->af_status != link_status
1220 #ifdef USE_VLANS
1221             && afp->af_status != vlan_status
1222 #endif
1223                 )
1224                 warnx("%s has no %s interface address!", name, afp->af_name);
1225
1226         close(s);
1227         return;
1228 }
1229
1230 void
1231 tunnel_status(int s)
1232 {
1233         char psrcaddr[NI_MAXHOST];
1234         char pdstaddr[NI_MAXHOST];
1235         u_long srccmd, dstcmd;
1236         struct ifreq *ifrp;
1237         const char *ver = "";
1238 #ifdef NI_WITHSCOPEID
1239         const int niflag = NI_NUMERICHOST | NI_WITHSCOPEID;
1240 #else
1241         const int niflag = NI_NUMERICHOST;
1242 #endif
1243 #ifdef INET6
1244         struct in6_ifreq in6_ifr;
1245         int s6;
1246 #endif /* INET6 */
1247
1248         psrcaddr[0] = pdstaddr[0] = '\0';
1249
1250 #ifdef INET6
1251         memset(&in6_ifr, 0, sizeof(in6_ifr));
1252         strncpy(in6_ifr.ifr_name, name, IFNAMSIZ);
1253         s6 = socket(AF_INET6, SOCK_DGRAM, 0);
1254         if (s6 < 0) {
1255                 srccmd = SIOCGIFPSRCADDR;
1256                 dstcmd = SIOCGIFPDSTADDR;
1257                 ifrp = &ifr;
1258         } else {
1259                 close(s6);
1260                 srccmd = SIOCGIFPSRCADDR_IN6;
1261                 dstcmd = SIOCGIFPDSTADDR_IN6;
1262                 ifrp = (struct ifreq *)&in6_ifr;
1263         }
1264 #else /* INET6 */
1265         srccmd = SIOCGIFPSRCADDR;
1266         dstcmd = SIOCGIFPDSTADDR;
1267         ifrp = &ifr;
1268 #endif /* INET6 */
1269
1270         if (ioctl(s, srccmd, (caddr_t)ifrp) < 0)
1271                 return;
1272 #if defined(INET6) && defined(__KAME__) && defined(KAME_SCOPEID)
1273         if (ifrp->ifr_addr.sa_family == AF_INET6)
1274                 in6_fillscopeid((struct sockaddr_in6 *)&ifrp->ifr_addr);
1275 #endif
1276         getnameinfo(&ifrp->ifr_addr, ifrp->ifr_addr.sa_len,
1277             psrcaddr, sizeof(psrcaddr), 0, 0, niflag);
1278 #ifdef INET6
1279         if (ifrp->ifr_addr.sa_family == AF_INET6)
1280                 ver = "6";
1281 #endif
1282
1283         if (ioctl(s, dstcmd, (caddr_t)ifrp) < 0)
1284                 return;
1285 #if defined(INET6) && defined(__KAME__) && defined(KAME_SCOPEID)
1286         if (ifrp->ifr_addr.sa_family == AF_INET6)
1287                 in6_fillscopeid((struct sockaddr_in6 *)&ifrp->ifr_addr);
1288 #endif
1289         getnameinfo(&ifrp->ifr_addr, ifrp->ifr_addr.sa_len,
1290             pdstaddr, sizeof(pdstaddr), 0, 0, niflag);
1291
1292         printf("\ttunnel inet%s %s --> %s\n", ver,
1293             psrcaddr, pdstaddr);
1294 }
1295
1296 void
1297 in_status(int s __unused, struct rt_addrinfo *info)
1298 {
1299         struct sockaddr_in *addr_in, null_in;
1300
1301         memset(&null_in, 0, sizeof(null_in));
1302
1303         addr_in = (struct sockaddr_in *)info->rti_info[RTAX_IFA];
1304         printf("\tinet %s ", inet_ntoa(addr_in->sin_addr));
1305
1306         if (flags & IFF_POINTOPOINT) {
1307                 /* note RTAX_BRD overlap with IFF_BROADCAST */
1308                 addr_in = (struct sockaddr_in *)info->rti_info[RTAX_BRD];
1309                 if (!addr_in)
1310                         addr_in = &null_in;
1311                 printf("--> %s ", inet_ntoa(addr_in->sin_addr));
1312         }
1313
1314         addr_in = (struct sockaddr_in *)info->rti_info[RTAX_NETMASK];
1315         if (!addr_in)
1316                 addr_in = &null_in;
1317         printf("netmask 0x%lx ",
1318                (unsigned long)ntohl(addr_in->sin_addr.s_addr));
1319
1320         if (flags & IFF_BROADCAST) {
1321                 /* note RTAX_BRD overlap with IFF_POINTOPOINT */
1322                 addr_in = (struct sockaddr_in *)info->rti_info[RTAX_BRD];
1323                 if (addr_in && addr_in->sin_addr.s_addr != 0)
1324                         printf("broadcast %s", inet_ntoa(addr_in->sin_addr));
1325         }
1326         putchar('\n');
1327 }
1328
1329 #ifdef INET6
1330 #if defined(__KAME__) && defined(KAME_SCOPEID)
1331 void
1332 in6_fillscopeid(struct sockaddr_in6 *sin6 __unused)
1333 {
1334         if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
1335                 sin6->sin6_scope_id =
1336                         ntohs(*(u_int16_t *)&sin6->sin6_addr.s6_addr[2]);
1337                 sin6->sin6_addr.s6_addr[2] = sin6->sin6_addr.s6_addr[3] = 0;
1338         }
1339 }
1340 #endif /* defined(__KAME__) && defined(KAME_SCOPEID) */
1341
1342 void
1343 in6_status(int s __unused, struct rt_addrinfo *info)
1344 {
1345         struct sockaddr_in6 *addr_in, null_in;
1346         struct in6_ifreq ifr6;
1347         int s6;
1348         u_int32_t flags6;
1349         struct in6_addrlifetime lifetime;
1350         time_t t = time(NULL);
1351         int error;
1352         u_int32_t scopeid;
1353
1354         memset(&null_in, 0, sizeof(null_in));
1355
1356         addr_in = (struct sockaddr_in6 *)info->rti_info[RTAX_IFA];
1357         strncpy(ifr6.ifr_name, ifr.ifr_name, sizeof(ifr.ifr_name));
1358         if ((s6 = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1359                 perror("ifconfig: socket");
1360                 return;
1361         }
1362         ifr6.ifr_addr = *addr_in;
1363         if (ioctl(s6, SIOCGIFAFLAG_IN6, &ifr6) < 0) {
1364                 perror("ifconfig: ioctl(SIOCGIFAFLAG_IN6)");
1365                 close(s6);
1366                 return;
1367         }
1368         flags6 = ifr6.ifr_ifru.ifru_flags6;
1369         memset(&lifetime, 0, sizeof(lifetime));
1370         ifr6.ifr_addr = *addr_in;
1371         if (ioctl(s6, SIOCGIFALIFETIME_IN6, &ifr6) < 0) {
1372                 perror("ifconfig: ioctl(SIOCGIFALIFETIME_IN6)");
1373                 close(s6);
1374                 return;
1375         }
1376         lifetime = ifr6.ifr_ifru.ifru_lifetime;
1377         close(s6);
1378
1379         /* XXX: embedded link local addr check */
1380         if (IN6_IS_ADDR_LINKLOCAL(&addr_in->sin6_addr) &&
1381             *(u_short *)&addr_in->sin6_addr.s6_addr[2] != 0) {
1382                 u_short idx;
1383
1384                 idx = *(u_short *)&addr_in->sin6_addr.s6_addr[2];
1385                 *(u_short *)&addr_in->sin6_addr.s6_addr[2] = 0;
1386                 if (addr_in->sin6_scope_id == 0)
1387                         addr_in->sin6_scope_id = ntohs(idx);
1388         }
1389         scopeid = addr_in->sin6_scope_id;
1390
1391         error = getnameinfo((struct sockaddr *)addr_in, addr_in->sin6_len, addr_buf,
1392                             sizeof(addr_buf), NULL, 0,
1393                             NI_NUMERICHOST|NI_WITHSCOPEID);
1394         if (error != 0)
1395                 inet_ntop(AF_INET6, &addr_in->sin6_addr, addr_buf,
1396                           sizeof(addr_buf));
1397         printf("\tinet6 %s ", addr_buf);
1398
1399         if (flags & IFF_POINTOPOINT) {
1400                 /* note RTAX_BRD overlap with IFF_BROADCAST */
1401                 addr_in = (struct sockaddr_in6 *)info->rti_info[RTAX_BRD];
1402                 /*
1403                  * some of the interfaces do not have valid destination
1404                  * address.
1405                  */
1406                 if (addr_in && addr_in->sin6_family == AF_INET6) {
1407                         /* XXX: embedded link local addr check */
1408                         if (IN6_IS_ADDR_LINKLOCAL(&addr_in->sin6_addr) &&
1409                             *(u_short *)&addr_in->sin6_addr.s6_addr[2] != 0) {
1410                                 u_short idx;
1411
1412                                 idx = *(u_short *)&addr_in->sin6_addr.s6_addr[2];
1413                                 *(u_short *)&addr_in->sin6_addr.s6_addr[2] = 0;
1414                                 if (addr_in->sin6_scope_id == 0)
1415                                         addr_in->sin6_scope_id = ntohs(idx);
1416                         }
1417
1418                         error = getnameinfo((struct sockaddr *)addr_in,
1419                                             addr_in->sin6_len, addr_buf,
1420                                             sizeof(addr_buf), NULL, 0,
1421                                             NI_NUMERICHOST|NI_WITHSCOPEID);
1422                         if (error != 0)
1423                                 inet_ntop(AF_INET6, &addr_in->sin6_addr, addr_buf,
1424                                           sizeof(addr_buf));
1425                         printf("--> %s ", addr_buf);
1426                 }
1427         }
1428
1429         addr_in = (struct sockaddr_in6 *)info->rti_info[RTAX_NETMASK];
1430         if (!addr_in)
1431                 addr_in = &null_in;
1432         printf("prefixlen %d ", prefix(&addr_in->sin6_addr,
1433                 sizeof(struct in6_addr)));
1434
1435         if ((flags6 & IN6_IFF_ANYCAST) != 0)
1436                 printf("anycast ");
1437         if ((flags6 & IN6_IFF_TENTATIVE) != 0)
1438                 printf("tentative ");
1439         if ((flags6 & IN6_IFF_DUPLICATED) != 0)
1440                 printf("duplicated ");
1441         if ((flags6 & IN6_IFF_DETACHED) != 0)
1442                 printf("detached ");
1443         if ((flags6 & IN6_IFF_DEPRECATED) != 0)
1444                 printf("deprecated ");
1445         if ((flags6 & IN6_IFF_AUTOCONF) != 0)
1446                 printf("autoconf ");
1447         if ((flags6 & IN6_IFF_TEMPORARY) != 0)
1448                 printf("temporary ");
1449
1450         if (scopeid)
1451                 printf("scopeid 0x%x ", scopeid);
1452
1453         if (ip6lifetime && (lifetime.ia6t_preferred || lifetime.ia6t_expire)) {
1454                 printf("pltime ");
1455                 if (lifetime.ia6t_preferred) {
1456                         printf("%s ", lifetime.ia6t_preferred < t
1457                                 ? "0" : sec2str(lifetime.ia6t_preferred - t));
1458                 } else
1459                         printf("infty ");
1460
1461                 printf("vltime ");
1462                 if (lifetime.ia6t_expire) {
1463                         printf("%s ", lifetime.ia6t_expire < t
1464                                 ? "0" : sec2str(lifetime.ia6t_expire - t));
1465                 } else
1466                         printf("infty ");
1467         }
1468
1469         putchar('\n');
1470 }
1471 #endif /*INET6*/
1472
1473 #ifndef NO_IPX
1474 void
1475 ipx_status(int s __unused, struct rt_addrinfo *info)
1476 {
1477         struct sockaddr_ipx *sipx, null_sipx;
1478
1479         memset(&null_sipx, 0, sizeof(null_sipx));
1480
1481         sipx = (struct sockaddr_ipx *)info->rti_info[RTAX_IFA];
1482         printf("\tipx %s ", ipx_ntoa(sipx->sipx_addr));
1483
1484         if (flags & IFF_POINTOPOINT) {
1485                 sipx = (struct sockaddr_ipx *)info->rti_info[RTAX_BRD];
1486                 if (!sipx)
1487                         sipx = &null_sipx;
1488                 printf("--> %s ", ipx_ntoa(sipx->sipx_addr));
1489         }
1490         putchar('\n');
1491 }
1492 #endif
1493
1494 void
1495 at_status(int s __unused, struct rt_addrinfo *info)
1496 {
1497         struct sockaddr_at *sat, null_sat;
1498         struct netrange *nr;
1499
1500         memset(&null_sat, 0, sizeof(null_sat));
1501
1502         sat = (struct sockaddr_at *)info->rti_info[RTAX_IFA];
1503         nr = &sat->sat_range.r_netrange;
1504         printf("\tatalk %d.%d range %d-%d phase %d",
1505                 ntohs(sat->sat_addr.s_net), sat->sat_addr.s_node,
1506                 ntohs(nr->nr_firstnet), ntohs(nr->nr_lastnet), nr->nr_phase);
1507         if (flags & IFF_POINTOPOINT) {
1508                 /* note RTAX_BRD overlap with IFF_BROADCAST */
1509                 sat = (struct sockaddr_at *)info->rti_info[RTAX_BRD];
1510                 if (!sat)
1511                         sat = &null_sat;
1512                 printf("--> %d.%d",
1513                         ntohs(sat->sat_addr.s_net), sat->sat_addr.s_node);
1514         }
1515         if (flags & IFF_BROADCAST) {
1516                 /* note RTAX_BRD overlap with IFF_POINTOPOINT */
1517                 sat = (struct sockaddr_at *)info->rti_info[RTAX_BRD];
1518                 if (sat)
1519                         printf(" broadcast %d.%d",
1520                                 ntohs(sat->sat_addr.s_net),
1521                                 sat->sat_addr.s_node);
1522         }
1523
1524         putchar('\n');
1525 }
1526
1527 #ifdef NS
1528 void
1529 xns_status(int s __unused, struct rt_addrinfo *info)
1530 {
1531         struct sockaddr_ns *sns, null_sns;
1532
1533         memset(&null_sns, 0, sizeof(null_sns));
1534
1535         sns = (struct sockaddr_ns *)info->rti_info[RTAX_IFA];
1536         printf("\tns %s ", ns_ntoa(sns->sns_addr));
1537
1538         if (flags & IFF_POINTOPOINT) {
1539                 sns = (struct sockaddr_ns *)info->rti_info[RTAX_BRD];
1540                 if (!sns)
1541                         sns = &null_sns;
1542                 printf("--> %s ", ns_ntoa(sns->sns_addr));
1543         }
1544
1545         putchar('\n');
1546         close(s);
1547 }
1548 #endif
1549
1550
1551 void
1552 link_status(int s __unused, struct rt_addrinfo *info)
1553 {
1554         struct sockaddr_dl *sdl = (struct sockaddr_dl *)info;
1555
1556         if (sdl->sdl_alen > 0) {
1557                 if (sdl->sdl_type == IFT_ETHER &&
1558                     sdl->sdl_alen == ETHER_ADDR_LEN)
1559                         printf("\tether %s\n",
1560                             ether_ntoa((struct ether_addr *)LLADDR(sdl)));
1561                 else {
1562                         int n = sdl->sdl_nlen > 0 ? sdl->sdl_nlen + 1 : 0;
1563
1564                         printf("\tlladdr %s\n", link_ntoa(sdl) + n);
1565                 }
1566         }
1567 }
1568
1569 void
1570 Perror(const char *cmd)
1571 {
1572         switch (errno) {
1573
1574         case ENXIO:
1575                 errx(1, "%s: no such interface", cmd);
1576                 break;
1577
1578         case EPERM:
1579                 errx(1, "%s: permission denied", cmd);
1580                 break;
1581
1582         default:
1583                 err(1, "%s", cmd);
1584         }
1585 }
1586
1587 #define SIN(x) ((struct sockaddr_in *) &(x))
1588 struct sockaddr_in *sintab[] = {
1589 SIN(ridreq.ifr_addr), SIN(addreq.ifra_addr),
1590 SIN(addreq.ifra_mask), SIN(addreq.ifra_broadaddr)};
1591
1592 void
1593 in_getaddr(const char *s, int which)
1594 {
1595         struct sockaddr_in *addr_in = sintab[which];
1596         struct hostent *hp;
1597         struct netent *np;
1598
1599         addr_in->sin_len = sizeof(*addr_in);
1600         if (which != MASK)
1601                 addr_in->sin_family = AF_INET;
1602
1603         if (which == ADDR) {
1604                 char *p = NULL;
1605
1606                 if((p = strrchr(s, '/')) != NULL) {
1607                         /* address is `name/masklen' */
1608                         int masklen;
1609                         int ret;
1610                         struct sockaddr_in *min = sintab[MASK];
1611                         *p = '\0';
1612                         ret = sscanf(p+1, "%u", &masklen);
1613                         if(ret != 1 || (masklen < 0 || masklen > 32)) {
1614                                 *p = '/';
1615                                 errx(1, "%s: bad value", s);
1616                         }
1617                         min->sin_len = sizeof(*min);
1618                         min->sin_addr.s_addr = htonl(~((1LL << (32 - masklen)) - 1) & 
1619                                               0xffffffff);
1620                 }
1621         }
1622
1623         if (inet_aton(s, &addr_in->sin_addr))
1624                 return;
1625         if ((hp = gethostbyname(s)) != 0)
1626                 bcopy(hp->h_addr, (char *)&addr_in->sin_addr, 
1627                     MIN((size_t)hp->h_length, sizeof(addr_in->sin_addr)));
1628         else if ((np = getnetbyname(s)) != 0)
1629                 addr_in->sin_addr = inet_makeaddr(np->n_net, INADDR_ANY);
1630         else
1631                 errx(1, "%s: bad value", s);
1632 }
1633
1634 #ifdef INET6
1635 #define SIN6(x) ((struct sockaddr_in6 *) &(x))
1636 struct  sockaddr_in6 *sin6tab[] = {
1637 SIN6(in6_ridreq.ifr_addr), SIN6(in6_addreq.ifra_addr),
1638 SIN6(in6_addreq.ifra_prefixmask), SIN6(in6_addreq.ifra_dstaddr)};
1639
1640 void
1641 in6_getaddr(const char *s, int which)
1642 {
1643         struct sockaddr_in6 *addr_in = sin6tab[which];
1644         struct addrinfo hints, *res;
1645         int error = -1;
1646
1647         newaddr &= 1;
1648
1649         addr_in->sin6_len = sizeof(*addr_in);
1650         if (which != MASK)
1651                 addr_in->sin6_family = AF_INET6;
1652
1653         if (which == ADDR) {
1654                 char *p = NULL;
1655                 if((p = strrchr(s, '/')) != NULL) {
1656                         *p = '\0';
1657                         in6_getprefix(p + 1, MASK);
1658                         explicit_prefix = 1;
1659                 }
1660         }
1661
1662         if (addr_in->sin6_family == AF_INET6) {
1663                 bzero(&hints, sizeof(struct addrinfo));
1664                 hints.ai_family = AF_INET6;
1665                 error = getaddrinfo(s, NULL, &hints, &res);
1666         }
1667         if (error != 0) {
1668                 if (inet_pton(AF_INET6, s, &addr_in->sin6_addr) != 1)
1669                         errx(1, "%s: bad value", s);
1670         } else
1671                 bcopy(res->ai_addr, addr_in, res->ai_addrlen);
1672 }
1673
1674 void
1675 in6_getprefix(const char *plen, int which)
1676 {
1677         struct sockaddr_in6 *addr_in = sin6tab[which];
1678         u_char *cp;
1679         int len = atoi(plen);
1680
1681         if ((len < 0) || (len > 128))
1682                 errx(1, "%s: bad value", plen);
1683         addr_in->sin6_len = sizeof(*addr_in);
1684         if (which != MASK)
1685                 addr_in->sin6_family = AF_INET6;
1686         if ((len == 0) || (len == 128)) {
1687                 memset(&addr_in->sin6_addr, 0xff, sizeof(struct in6_addr));
1688                 return;
1689         }
1690         memset((void *)&addr_in->sin6_addr, 0x00, sizeof(addr_in->sin6_addr));
1691         for (cp = (u_char *)&addr_in->sin6_addr; len > 7; len -= 8)
1692                 *cp++ = 0xff;
1693         *cp = 0xff << (8 - len);
1694 }
1695 #endif
1696
1697 /*
1698  * Print a value a la the %b format of the kernel's printf
1699  */
1700 void
1701 printb(const char *s, unsigned v, const char *bits)
1702 {
1703         int i, any = 0;
1704         char c;
1705
1706         if (bits && *bits == 8)
1707                 printf("%s=%o", s, v);
1708         else
1709                 printf("%s=%x", s, v);
1710         bits++;
1711         if (bits) {
1712                 putchar('<');
1713                 while ((i = *bits++) != '\0') {
1714                         if (v & (1 << (i-1))) {
1715                                 if (any)
1716                                         putchar(',');
1717                                 any = 1;
1718                                 for (; (c = *bits) > 32; bits++)
1719                                         putchar(c);
1720                         } else
1721                                 for (; *bits > 32; bits++)
1722                                         ;
1723                 }
1724                 putchar('>');
1725         }
1726 }
1727
1728 #ifndef NO_IPX
1729 #define SIPX(x) ((struct sockaddr_ipx *) &(x))
1730 struct sockaddr_ipx *sipxtab[] = {
1731 SIPX(ridreq.ifr_addr), SIPX(addreq.ifra_addr),
1732 SIPX(addreq.ifra_mask), SIPX(addreq.ifra_broadaddr)};
1733
1734 void
1735 ipx_getaddr(const char *addr, int which)
1736 {
1737         struct sockaddr_ipx *sipx = sipxtab[which];
1738
1739         sipx->sipx_family = AF_IPX;
1740         sipx->sipx_len = sizeof(*sipx);
1741         sipx->sipx_addr = ipx_addr(addr);
1742         if (which == MASK)
1743                 printf("Attempt to set IPX netmask will be ineffectual\n");
1744 }
1745 #endif
1746
1747 void
1748 at_getaddr(const char *addr, int which)
1749 {
1750         struct sockaddr_at *sat = (struct sockaddr_at *) &addreq.ifra_addr;
1751         u_int net, node;
1752
1753         sat->sat_family = AF_APPLETALK;
1754         sat->sat_len = sizeof(*sat);
1755         if (which == MASK)
1756                 errx(1, "AppleTalk does not use netmasks");
1757         if (sscanf(addr, "%u.%u", &net, &node) != 2
1758             || net > 0xffff || node > 0xfe)
1759                 errx(1, "%s: illegal address", addr);
1760         sat->sat_addr.s_net = htons(net);
1761         sat->sat_addr.s_node = node;
1762 }
1763
1764 void
1765 link_getaddr(const char *addr, int which)
1766 {
1767         char *temp;
1768         struct sockaddr_dl sdl;
1769         struct sockaddr *sa = &ridreq.ifr_addr;
1770
1771         if (which != ADDR)
1772                 errx(1, "can't set link-level netmask or broadcast");
1773         if ((temp = malloc(strlen(addr) + 1)) == NULL)
1774                 errx(1, "malloc failed");
1775         temp[0] = ':';
1776         strcpy(temp + 1, addr);
1777         sdl.sdl_len = sizeof(sdl);
1778         link_addr(temp, &sdl);
1779         free(temp);
1780         if (sdl.sdl_alen > sizeof(sa->sa_data))
1781                 errx(1, "malformed link-level address");
1782         sa->sa_family = AF_LINK;
1783         sa->sa_len = sdl.sdl_alen;
1784         bcopy(LLADDR(&sdl), sa->sa_data, sdl.sdl_alen);
1785 }
1786
1787 /* XXX  FIXME -- should use strtoul for better parsing. */
1788 void
1789 setatrange(const char *range, int dummy __unused, int s __unused,
1790            const struct afswtch *afp __unused)
1791 {
1792         u_int   first = 123, last = 123;
1793
1794         if (sscanf(range, "%u-%u", &first, &last) != 2
1795             || first == 0 || first > 0xffff
1796             || last == 0 || last > 0xffff || first > last)
1797                 errx(1, "%s: illegal net range: %u-%u", range, first, last);
1798         at_nr.nr_firstnet = htons(first);
1799         at_nr.nr_lastnet = htons(last);
1800 }
1801
1802 void
1803 setatphase(const char *phase, int dummy __unused, int s __unused,
1804            const struct afswtch *afp __unused)
1805 {
1806         if (!strcmp(phase, "1"))
1807                 at_nr.nr_phase = 1;
1808         else if (!strcmp(phase, "2"))
1809                 at_nr.nr_phase = 2;
1810         else
1811                 errx(1, "%s: illegal phase", phase);
1812 }
1813
1814 void
1815 checkatrange(struct sockaddr_at *sat)
1816 {
1817         if (at_nr.nr_phase == 0)
1818                 at_nr.nr_phase = 2;     /* Default phase 2 */
1819         if (at_nr.nr_firstnet == 0)
1820                 at_nr.nr_firstnet =     /* Default range of one */
1821                 at_nr.nr_lastnet = sat->sat_addr.s_net;
1822 printf("\tatalk %d.%d range %d-%d phase %d\n",
1823         ntohs(sat->sat_addr.s_net), sat->sat_addr.s_node,
1824         ntohs(at_nr.nr_firstnet), ntohs(at_nr.nr_lastnet), at_nr.nr_phase);
1825         if ((u_short) ntohs(at_nr.nr_firstnet) >
1826                         (u_short) ntohs(sat->sat_addr.s_net)
1827                     || (u_short) ntohs(at_nr.nr_lastnet) <
1828                         (u_short) ntohs(sat->sat_addr.s_net))
1829                 errx(1, "AppleTalk address is not in range");
1830         sat->sat_range.r_netrange = at_nr;
1831 }
1832
1833 #ifdef NS
1834 #define SNS(x) ((struct sockaddr_ns *) &(x))
1835 struct sockaddr_ns *snstab[] = {
1836 SNS(ridreq.ifr_addr), SNS(addreq.ifra_addr),
1837 SNS(addreq.ifra_mask), SNS(addreq.ifra_broadaddr)};
1838
1839 void
1840 xns_getaddr(const char *addr, int which)
1841 {
1842         struct sockaddr_ns *sns = snstab[which];
1843
1844         sns->sns_family = AF_NS;
1845         sns->sns_len = sizeof(*sns);
1846         sns->sns_addr = ns_addr(addr);
1847         if (which == MASK)
1848                 printf("Attempt to set XNS netmask will be ineffectual\n");
1849 }
1850 #endif
1851
1852 #ifdef INET6
1853 int
1854 prefix(void *val, int size)
1855 {
1856         u_char *addr = (u_char *)val;
1857         int byte, bit, plen = 0;
1858
1859         for (byte = 0; byte < size; byte++, plen += 8)
1860                 if (addr[byte] != 0xff)
1861                         break;
1862         if (byte == size)
1863                 return (plen);
1864         for (bit = 7; bit != 0; bit--, plen++)
1865                 if (!(addr[byte] & (1 << bit)))
1866                         break;
1867         for (; bit != 0; bit--)
1868                 if (addr[byte] & (1 << bit))
1869                         return(0);
1870         byte++;
1871         for (; byte < size; byte++)
1872                 if (addr[byte])
1873                         return(0);
1874         return (plen);
1875 }
1876
1877 static char *
1878 sec2str(time_t total)
1879 {
1880         static char result[256];
1881         int days, hours, mins, secs;
1882         int first = 1;
1883         char *p = result;
1884
1885         if (0) {
1886                 days = total / 3600 / 24;
1887                 hours = (total / 3600) % 24;
1888                 mins = (total / 60) % 60;
1889                 secs = total % 60;
1890
1891                 if (days) {
1892                         first = 0;
1893                         p += sprintf(p, "%dd", days);
1894                 }
1895                 if (!first || hours) {
1896                         first = 0;
1897                         p += sprintf(p, "%dh", hours);
1898                 }
1899                 if (!first || mins) {
1900                         first = 0;
1901                         p += sprintf(p, "%dm", mins);
1902                 }
1903                 sprintf(p, "%ds", secs);
1904         } else
1905                 sprintf(result, "%lu", (unsigned long)total);
1906
1907         return(result);
1908 }
1909 #endif /*INET6*/
1910
1911 void
1912 ifmaybeload(char *if_nm)
1913 {
1914         struct module_stat mstat;
1915         int fileid, modid;
1916         char ifkind[35], *cp, *dp;
1917
1918
1919         /* turn interface and unit into module name */
1920         strcpy(ifkind, "if_");
1921         for (cp = if_nm, dp = ifkind + 3;
1922             (*cp != 0) && !isdigit(*cp); cp++, dp++)
1923                 *dp = *cp;
1924         *dp = 0;
1925
1926         /* scan files in kernel */
1927         mstat.version = sizeof(struct module_stat);
1928         for (fileid = kldnext(0); fileid > 0; fileid = kldnext(fileid)) {
1929                 /* scan modules in file */
1930                 for (modid = kldfirstmod(fileid); modid > 0;
1931                      modid = modfnext(modid)) {
1932                         if (modstat(modid, &mstat) < 0)
1933                                 continue;
1934                         /* strip bus name if present */
1935                         if ((cp = strchr(mstat.name, '/')) != NULL) {
1936                                 cp++;
1937                         } else {
1938                                 cp = mstat.name;
1939                         }
1940                         /* already loaded? */
1941                         if (strncmp(if_nm, cp, strlen(cp)) == 0 ||
1942                                 strncmp(ifkind, cp, strlen(cp)) == 0)
1943                                 return;
1944                 }
1945         }
1946
1947         /* not present, we should try to load it */
1948         kldload(ifkind);
1949 }
1950
1951 void
1952 list_cloners(void)
1953 {
1954         struct if_clonereq ifcr;
1955         char *cp, *buf;
1956         int idx;
1957         int s;
1958
1959         s = socket(AF_INET, SOCK_DGRAM, 0);
1960         if (s == -1)
1961                 err(1, "socket");
1962
1963         memset(&ifcr, 0, sizeof(ifcr));
1964
1965         if (ioctl(s, SIOCIFGCLONERS, &ifcr) < 0)
1966                 err(1, "SIOCIFGCLONERS for count");
1967
1968         buf = malloc(ifcr.ifcr_total * IFNAMSIZ);
1969         if (buf == NULL)
1970                 err(1, "unable to allocate cloner name buffer");
1971
1972         ifcr.ifcr_count = ifcr.ifcr_total;
1973         ifcr.ifcr_buffer = buf;
1974
1975         if (ioctl(s, SIOCIFGCLONERS, &ifcr) < 0)
1976                 err(1, "SIOCIFGCLONERS for names");
1977
1978         /*
1979          * In case some disappeared in the mean time, clamp it down.
1980          */
1981         if (ifcr.ifcr_count > ifcr.ifcr_total)
1982                 ifcr.ifcr_count = ifcr.ifcr_total;
1983
1984         for (cp = buf, idx = 0; idx < ifcr.ifcr_count; idx++, cp += IFNAMSIZ) {
1985                 if (idx > 0)
1986                         putchar(' ');
1987                 printf("%s", cp);
1988         }
1989
1990         putchar('\n');
1991         free(buf);
1992 }
1993
1994 void
1995 clone_create(void)
1996 {
1997         int s;
1998
1999         s = socket(AF_INET, SOCK_DGRAM, 0);
2000         if (s == -1)
2001                 err(1, "socket");
2002
2003         memset(&ifr, 0, sizeof(ifr));
2004         (void) strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
2005         if (ioctl(s, SIOCIFCREATE, &ifr) < 0)
2006                 err(1, "SIOCIFCREATE");
2007
2008         /*
2009          * If we get a different name back then we put in, we probably
2010          * want to print it out, but we might change our mind later so
2011          * we just signal our intrest and leave the printout for later.
2012          */
2013         if (strcmp(name, ifr.ifr_name) != 0) {
2014                 printname = 1;
2015                 strlcpy(name, ifr.ifr_name, sizeof(name));
2016         }
2017
2018         close(s);
2019 }
2020
2021 void
2022 clone_destroy(const char *val __unused, int d __unused, int s,
2023               const struct afswtch *rafp __unused)
2024 {
2025
2026         (void) strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
2027         if (ioctl(s, SIOCIFDESTROY, &ifr) < 0)
2028                 err(1, "SIOCIFDESTROY");
2029         /*
2030          * If we create and destroy an interface in the same command,
2031          * there isn't any reason to print it's name.
2032          */
2033         printname = 0;
2034 }