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