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