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