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