d0b5ae11e19efec861aa7b3e50dfe78adcad63a9
[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.17 2005/03/04 01:47:54 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 *if_nm);
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 addr_req;
785         int ecode;
786 #ifdef INET6
787         struct in6_aliasreq in6_addr_req; 
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(&addr_req, 0, sizeof(addr_req));
808                 strncpy(addr_req.ifra_name, name, IFNAMSIZ);
809                 memcpy(&addr_req.ifra_addr, srcres->ai_addr,
810                     srcres->ai_addr->sa_len);
811                 memcpy(&addr_req.ifra_dstaddr, dstres->ai_addr,
812                     dstres->ai_addr->sa_len);
813
814                 if (ioctl(s, SIOCSIFPHYADDR, &addr_req) < 0)
815                         warn("SIOCSIFPHYADDR");
816                 break;
817
818 #ifdef INET6
819         case AF_INET6:
820                 memset(&in6_addr_req, 0, sizeof(in6_addr_req));
821                 strncpy(in6_addr_req.ifra_name, name, IFNAMSIZ);
822                 memcpy(&in6_addr_req.ifra_addr, srcres->ai_addr,
823                     srcres->ai_addr->sa_len);
824                 memcpy(&in6_addr_req.ifra_dstaddr, dstres->ai_addr,
825                     dstres->ai_addr->sa_len);
826
827                 if (ioctl(s, SIOCSIFPHYADDR_IN6, &in6_addr_req) < 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 #if defined(INET6) && defined(__KAME__) && defined(KAME_SCOPEID)
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 #if defined(INET6) && defined(__KAME__) && defined(KAME_SCOPEID)
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 *addr_in, null_in;
1271
1272         memset(&null_in, 0, sizeof(null_in));
1273
1274         addr_in = (struct sockaddr_in *)info->rti_info[RTAX_IFA];
1275         printf("\tinet %s ", inet_ntoa(addr_in->sin_addr));
1276
1277         if (flags & IFF_POINTOPOINT) {
1278                 /* note RTAX_BRD overlap with IFF_BROADCAST */
1279                 addr_in = (struct sockaddr_in *)info->rti_info[RTAX_BRD];
1280                 if (!addr_in)
1281                         addr_in = &null_in;
1282                 printf("--> %s ", inet_ntoa(addr_in->sin_addr));
1283         }
1284
1285         addr_in = (struct sockaddr_in *)info->rti_info[RTAX_NETMASK];
1286         if (!addr_in)
1287                 addr_in = &null_in;
1288         printf("netmask 0x%lx ",
1289                (unsigned long)ntohl(addr_in->sin_addr.s_addr));
1290
1291         if (flags & IFF_BROADCAST) {
1292                 /* note RTAX_BRD overlap with IFF_POINTOPOINT */
1293                 addr_in = (struct sockaddr_in *)info->rti_info[RTAX_BRD];
1294                 if (addr_in && addr_in->sin_addr.s_addr != 0)
1295                         printf("broadcast %s", inet_ntoa(addr_in->sin_addr));
1296         }
1297         putchar('\n');
1298 }
1299
1300 #ifdef INET6
1301 #if defined(__KAME__) && defined(KAME_SCOPEID)
1302 void
1303 in6_fillscopeid(struct sockaddr_in6 *sin6)
1304 {
1305         if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
1306                 sin6->sin6_scope_id =
1307                         ntohs(*(u_int16_t *)&sin6->sin6_addr.s6_addr[2]);
1308                 sin6->sin6_addr.s6_addr[2] = sin6->sin6_addr.s6_addr[3] = 0;
1309         }
1310 }
1311 #endif /* defined(__KAME__) && defined(KAME_SCOPEID) */
1312
1313 void
1314 in6_status(int s __unused, struct rt_addrinfo *info)
1315 {
1316         struct sockaddr_in6 *addr_in, null_in;
1317         struct in6_ifreq ifr6;
1318         int s6;
1319         u_int32_t flags6;
1320         struct in6_addrlifetime lifetime;
1321         time_t t = time(NULL);
1322         int error;
1323         u_int32_t scopeid;
1324
1325         memset(&null_in, 0, sizeof(null_in));
1326
1327         addr_in = (struct sockaddr_in6 *)info->rti_info[RTAX_IFA];
1328         strncpy(ifr6.ifr_name, ifr.ifr_name, sizeof(ifr.ifr_name));
1329         if ((s6 = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1330                 perror("ifconfig: socket");
1331                 return;
1332         }
1333         ifr6.ifr_addr = *addr_in;
1334         if (ioctl(s6, SIOCGIFAFLAG_IN6, &ifr6) < 0) {
1335                 perror("ifconfig: ioctl(SIOCGIFAFLAG_IN6)");
1336                 close(s6);
1337                 return;
1338         }
1339         flags6 = ifr6.ifr_ifru.ifru_flags6;
1340         memset(&lifetime, 0, sizeof(lifetime));
1341         ifr6.ifr_addr = *addr_in;
1342         if (ioctl(s6, SIOCGIFALIFETIME_IN6, &ifr6) < 0) {
1343                 perror("ifconfig: ioctl(SIOCGIFALIFETIME_IN6)");
1344                 close(s6);
1345                 return;
1346         }
1347         lifetime = ifr6.ifr_ifru.ifru_lifetime;
1348         close(s6);
1349
1350         /* XXX: embedded link local addr check */
1351         if (IN6_IS_ADDR_LINKLOCAL(&addr_in->sin6_addr) &&
1352             *(u_short *)&addr_in->sin6_addr.s6_addr[2] != 0) {
1353                 u_short idx;
1354
1355                 idx = *(u_short *)&addr_in->sin6_addr.s6_addr[2];
1356                 *(u_short *)&addr_in->sin6_addr.s6_addr[2] = 0;
1357                 if (addr_in->sin6_scope_id == 0)
1358                         addr_in->sin6_scope_id = ntohs(idx);
1359         }
1360         scopeid = addr_in->sin6_scope_id;
1361
1362         error = getnameinfo((struct sockaddr *)addr_in, addr_in->sin6_len, addr_buf,
1363                             sizeof(addr_buf), NULL, 0,
1364                             NI_NUMERICHOST|NI_WITHSCOPEID);
1365         if (error != 0)
1366                 inet_ntop(AF_INET6, &addr_in->sin6_addr, addr_buf,
1367                           sizeof(addr_buf));
1368         printf("\tinet6 %s ", addr_buf);
1369
1370         if (flags & IFF_POINTOPOINT) {
1371                 /* note RTAX_BRD overlap with IFF_BROADCAST */
1372                 addr_in = (struct sockaddr_in6 *)info->rti_info[RTAX_BRD];
1373                 /*
1374                  * some of the interfaces do not have valid destination
1375                  * address.
1376                  */
1377                 if (addr_in && addr_in->sin6_family == AF_INET6) {
1378                         /* XXX: embedded link local addr check */
1379                         if (IN6_IS_ADDR_LINKLOCAL(&addr_in->sin6_addr) &&
1380                             *(u_short *)&addr_in->sin6_addr.s6_addr[2] != 0) {
1381                                 u_short idx;
1382
1383                                 idx = *(u_short *)&addr_in->sin6_addr.s6_addr[2];
1384                                 *(u_short *)&addr_in->sin6_addr.s6_addr[2] = 0;
1385                                 if (addr_in->sin6_scope_id == 0)
1386                                         addr_in->sin6_scope_id = ntohs(idx);
1387                         }
1388
1389                         error = getnameinfo((struct sockaddr *)addr_in,
1390                                             addr_in->sin6_len, addr_buf,
1391                                             sizeof(addr_buf), NULL, 0,
1392                                             NI_NUMERICHOST|NI_WITHSCOPEID);
1393                         if (error != 0)
1394                                 inet_ntop(AF_INET6, &addr_in->sin6_addr, addr_buf,
1395                                           sizeof(addr_buf));
1396                         printf("--> %s ", addr_buf);
1397                 }
1398         }
1399
1400         addr_in = (struct sockaddr_in6 *)info->rti_info[RTAX_NETMASK];
1401         if (!addr_in)
1402                 addr_in = &null_in;
1403         printf("prefixlen %d ", prefix(&addr_in->sin6_addr,
1404                 sizeof(struct in6_addr)));
1405
1406         if ((flags6 & IN6_IFF_ANYCAST) != 0)
1407                 printf("anycast ");
1408         if ((flags6 & IN6_IFF_TENTATIVE) != 0)
1409                 printf("tentative ");
1410         if ((flags6 & IN6_IFF_DUPLICATED) != 0)
1411                 printf("duplicated ");
1412         if ((flags6 & IN6_IFF_DETACHED) != 0)
1413                 printf("detached ");
1414         if ((flags6 & IN6_IFF_DEPRECATED) != 0)
1415                 printf("deprecated ");
1416         if ((flags6 & IN6_IFF_AUTOCONF) != 0)
1417                 printf("autoconf ");
1418         if ((flags6 & IN6_IFF_TEMPORARY) != 0)
1419                 printf("temporary ");
1420
1421         if (scopeid)
1422                 printf("scopeid 0x%x ", scopeid);
1423
1424         if (ip6lifetime && (lifetime.ia6t_preferred || lifetime.ia6t_expire)) {
1425                 printf("pltime ");
1426                 if (lifetime.ia6t_preferred) {
1427                         printf("%s ", lifetime.ia6t_preferred < t
1428                                 ? "0" : sec2str(lifetime.ia6t_preferred - t));
1429                 } else
1430                         printf("infty ");
1431
1432                 printf("vltime ");
1433                 if (lifetime.ia6t_expire) {
1434                         printf("%s ", lifetime.ia6t_expire < t
1435                                 ? "0" : sec2str(lifetime.ia6t_expire - t));
1436                 } else
1437                         printf("infty ");
1438         }
1439
1440         putchar('\n');
1441 }
1442 #endif /*INET6*/
1443
1444 #ifndef NO_IPX
1445 void
1446 ipx_status(int s __unused, struct rt_addrinfo *info)
1447 {
1448         struct sockaddr_ipx *sipx, null_sipx;
1449
1450         memset(&null_sipx, 0, sizeof(null_sipx));
1451
1452         sipx = (struct sockaddr_ipx *)info->rti_info[RTAX_IFA];
1453         printf("\tipx %s ", ipx_ntoa(sipx->sipx_addr));
1454
1455         if (flags & IFF_POINTOPOINT) {
1456                 sipx = (struct sockaddr_ipx *)info->rti_info[RTAX_BRD];
1457                 if (!sipx)
1458                         sipx = &null_sipx;
1459                 printf("--> %s ", ipx_ntoa(sipx->sipx_addr));
1460         }
1461         putchar('\n');
1462 }
1463 #endif
1464
1465 void
1466 at_status(int s __unused, struct rt_addrinfo *info)
1467 {
1468         struct sockaddr_at *sat, null_sat;
1469         struct netrange *nr;
1470
1471         memset(&null_sat, 0, sizeof(null_sat));
1472
1473         sat = (struct sockaddr_at *)info->rti_info[RTAX_IFA];
1474         nr = &sat->sat_range.r_netrange;
1475         printf("\tatalk %d.%d range %d-%d phase %d",
1476                 ntohs(sat->sat_addr.s_net), sat->sat_addr.s_node,
1477                 ntohs(nr->nr_firstnet), ntohs(nr->nr_lastnet), nr->nr_phase);
1478         if (flags & IFF_POINTOPOINT) {
1479                 /* note RTAX_BRD overlap with IFF_BROADCAST */
1480                 sat = (struct sockaddr_at *)info->rti_info[RTAX_BRD];
1481                 if (!sat)
1482                         sat = &null_sat;
1483                 printf("--> %d.%d",
1484                         ntohs(sat->sat_addr.s_net), sat->sat_addr.s_node);
1485         }
1486         if (flags & IFF_BROADCAST) {
1487                 /* note RTAX_BRD overlap with IFF_POINTOPOINT */
1488                 sat = (struct sockaddr_at *)info->rti_info[RTAX_BRD];
1489                 if (sat)
1490                         printf(" broadcast %d.%d",
1491                                 ntohs(sat->sat_addr.s_net),
1492                                 sat->sat_addr.s_node);
1493         }
1494
1495         putchar('\n');
1496 }
1497
1498 #ifdef NS
1499 void
1500 xns_status(int s __unused, struct rt_addrinfo *info)
1501 {
1502         struct sockaddr_ns *sns, null_sns;
1503
1504         memset(&null_sns, 0, sizeof(null_sns));
1505
1506         sns = (struct sockaddr_ns *)info->rti_info[RTAX_IFA];
1507         printf("\tns %s ", ns_ntoa(sns->sns_addr));
1508
1509         if (flags & IFF_POINTOPOINT) {
1510                 sns = (struct sockaddr_ns *)info->rti_info[RTAX_BRD];
1511                 if (!sns)
1512                         sns = &null_sns;
1513                 printf("--> %s ", ns_ntoa(sns->sns_addr));
1514         }
1515
1516         putchar('\n');
1517         close(s);
1518 }
1519 #endif
1520
1521
1522 void
1523 link_status(int s __unused, struct rt_addrinfo *info)
1524 {
1525         struct sockaddr_dl *sdl = (struct sockaddr_dl *)info;
1526
1527         if (sdl->sdl_alen > 0) {
1528                 if (sdl->sdl_type == IFT_ETHER &&
1529                     sdl->sdl_alen == ETHER_ADDR_LEN)
1530                         printf("\tether %s\n",
1531                             ether_ntoa((struct ether_addr *)LLADDR(sdl)));
1532                 else {
1533                         int n = sdl->sdl_nlen > 0 ? sdl->sdl_nlen + 1 : 0;
1534
1535                         printf("\tlladdr %s\n", link_ntoa(sdl) + n);
1536                 }
1537         }
1538 }
1539
1540 void
1541 Perror(const char *cmd)
1542 {
1543         switch (errno) {
1544
1545         case ENXIO:
1546                 errx(1, "%s: no such interface", cmd);
1547                 break;
1548
1549         case EPERM:
1550                 errx(1, "%s: permission denied", cmd);
1551                 break;
1552
1553         default:
1554                 err(1, "%s", cmd);
1555         }
1556 }
1557
1558 #define SIN(x) ((struct sockaddr_in *) &(x))
1559 struct sockaddr_in *sintab[] = {
1560 SIN(ridreq.ifr_addr), SIN(addreq.ifra_addr),
1561 SIN(addreq.ifra_mask), SIN(addreq.ifra_broadaddr)};
1562
1563 void
1564 in_getaddr(const char *s, int which)
1565 {
1566         register struct sockaddr_in *addr_in = sintab[which];
1567         struct hostent *hp;
1568         struct netent *np;
1569
1570         addr_in->sin_len = sizeof(*addr_in);
1571         if (which != MASK)
1572                 addr_in->sin_family = AF_INET;
1573
1574         if (which == ADDR) {
1575                 char *p = NULL;
1576
1577                 if((p = strrchr(s, '/')) != NULL) {
1578                         /* address is `name/masklen' */
1579                         int masklen;
1580                         int ret;
1581                         struct sockaddr_in *min = sintab[MASK];
1582                         *p = '\0';
1583                         ret = sscanf(p+1, "%u", &masklen);
1584                         if(ret != 1 || (masklen < 0 || masklen > 32)) {
1585                                 *p = '/';
1586                                 errx(1, "%s: bad value", s);
1587                         }
1588                         min->sin_len = sizeof(*min);
1589                         min->sin_addr.s_addr = htonl(~((1LL << (32 - masklen)) - 1) & 
1590                                               0xffffffff);
1591                 }
1592         }
1593
1594         if (inet_aton(s, &addr_in->sin_addr))
1595                 return;
1596         if ((hp = gethostbyname(s)) != 0)
1597                 bcopy(hp->h_addr, (char *)&addr_in->sin_addr, 
1598                     MIN(hp->h_length, sizeof(addr_in->sin_addr)));
1599         else if ((np = getnetbyname(s)) != 0)
1600                 addr_in->sin_addr = inet_makeaddr(np->n_net, INADDR_ANY);
1601         else
1602                 errx(1, "%s: bad value", s);
1603 }
1604
1605 #ifdef INET6
1606 #define SIN6(x) ((struct sockaddr_in6 *) &(x))
1607 struct  sockaddr_in6 *sin6tab[] = {
1608 SIN6(in6_ridreq.ifr_addr), SIN6(in6_addreq.ifra_addr),
1609 SIN6(in6_addreq.ifra_prefixmask), SIN6(in6_addreq.ifra_dstaddr)};
1610
1611 void
1612 in6_getaddr(const char *s, int which)
1613 {
1614         register struct sockaddr_in6 *addr_in = sin6tab[which];
1615         struct addrinfo hints, *res;
1616         int error = -1;
1617
1618         newaddr &= 1;
1619
1620         addr_in->sin6_len = sizeof(*addr_in);
1621         if (which != MASK)
1622                 addr_in->sin6_family = AF_INET6;
1623
1624         if (which == ADDR) {
1625                 char *p = NULL;
1626                 if((p = strrchr(s, '/')) != NULL) {
1627                         *p = '\0';
1628                         in6_getprefix(p + 1, MASK);
1629                         explicit_prefix = 1;
1630                 }
1631         }
1632
1633         if (addr_in->sin6_family == AF_INET6) {
1634                 bzero(&hints, sizeof(struct addrinfo));
1635                 hints.ai_family = AF_INET6;
1636                 error = getaddrinfo(s, NULL, &hints, &res);
1637         }
1638         if (error != 0) {
1639                 if (inet_pton(AF_INET6, s, &addr_in->sin6_addr) != 1)
1640                         errx(1, "%s: bad value", s);
1641         } else
1642                 bcopy(res->ai_addr, addr_in, res->ai_addrlen);
1643 }
1644
1645 void
1646 in6_getprefix(const char *plen, int which)
1647 {
1648         register struct sockaddr_in6 *addr_in = sin6tab[which];
1649         register u_char *cp;
1650         int len = atoi(plen);
1651
1652         if ((len < 0) || (len > 128))
1653                 errx(1, "%s: bad value", plen);
1654         addr_in->sin6_len = sizeof(*addr_in);
1655         if (which != MASK)
1656                 addr_in->sin6_family = AF_INET6;
1657         if ((len == 0) || (len == 128)) {
1658                 memset(&addr_in->sin6_addr, 0xff, sizeof(struct in6_addr));
1659                 return;
1660         }
1661         memset((void *)&addr_in->sin6_addr, 0x00, sizeof(addr_in->sin6_addr));
1662         for (cp = (u_char *)&addr_in->sin6_addr; len > 7; len -= 8)
1663                 *cp++ = 0xff;
1664         *cp = 0xff << (8 - len);
1665 }
1666 #endif
1667
1668 /*
1669  * Print a value a la the %b format of the kernel's printf
1670  */
1671 void
1672 printb(const char *s, register unsigned v, register const char *bits)
1673 {
1674         register int i, any = 0;
1675         register char c;
1676
1677         if (bits && *bits == 8)
1678                 printf("%s=%o", s, v);
1679         else
1680                 printf("%s=%x", s, v);
1681         bits++;
1682         if (bits) {
1683                 putchar('<');
1684                 while ((i = *bits++) != '\0') {
1685                         if (v & (1 << (i-1))) {
1686                                 if (any)
1687                                         putchar(',');
1688                                 any = 1;
1689                                 for (; (c = *bits) > 32; bits++)
1690                                         putchar(c);
1691                         } else
1692                                 for (; *bits > 32; bits++)
1693                                         ;
1694                 }
1695                 putchar('>');
1696         }
1697 }
1698
1699 #ifndef NO_IPX
1700 #define SIPX(x) ((struct sockaddr_ipx *) &(x))
1701 struct sockaddr_ipx *sipxtab[] = {
1702 SIPX(ridreq.ifr_addr), SIPX(addreq.ifra_addr),
1703 SIPX(addreq.ifra_mask), SIPX(addreq.ifra_broadaddr)};
1704
1705 void
1706 ipx_getaddr(const char *addr, int which)
1707 {
1708         struct sockaddr_ipx *sipx = sipxtab[which];
1709
1710         sipx->sipx_family = AF_IPX;
1711         sipx->sipx_len = sizeof(*sipx);
1712         sipx->sipx_addr = ipx_addr(addr);
1713         if (which == MASK)
1714                 printf("Attempt to set IPX netmask will be ineffectual\n");
1715 }
1716 #endif
1717
1718 void
1719 at_getaddr(const char *addr, int which)
1720 {
1721         struct sockaddr_at *sat = (struct sockaddr_at *) &addreq.ifra_addr;
1722         u_int net, node;
1723
1724         sat->sat_family = AF_APPLETALK;
1725         sat->sat_len = sizeof(*sat);
1726         if (which == MASK)
1727                 errx(1, "AppleTalk does not use netmasks");
1728         if (sscanf(addr, "%u.%u", &net, &node) != 2
1729             || net > 0xffff || node > 0xfe)
1730                 errx(1, "%s: illegal address", addr);
1731         sat->sat_addr.s_net = htons(net);
1732         sat->sat_addr.s_node = node;
1733 }
1734
1735 void
1736 link_getaddr(const char *addr, int which)
1737 {
1738         char *temp;
1739         struct sockaddr_dl sdl;
1740         struct sockaddr *sa = &ridreq.ifr_addr;
1741
1742         if (which != ADDR)
1743                 errx(1, "can't set link-level netmask or broadcast");
1744         if ((temp = malloc(strlen(addr) + 1)) == NULL)
1745                 errx(1, "malloc failed");
1746         temp[0] = ':';
1747         strcpy(temp + 1, addr);
1748         sdl.sdl_len = sizeof(sdl);
1749         link_addr(temp, &sdl);
1750         free(temp);
1751         if (sdl.sdl_alen > sizeof(sa->sa_data))
1752                 errx(1, "malformed link-level address");
1753         sa->sa_family = AF_LINK;
1754         sa->sa_len = sdl.sdl_alen;
1755         bcopy(LLADDR(&sdl), sa->sa_data, sdl.sdl_alen);
1756 }
1757
1758 /* XXX  FIXME -- should use strtoul for better parsing. */
1759 void
1760 setatrange(const char *range, int dummy __unused, int s __unused,
1761            const struct afswtch *afp __unused)
1762 {
1763         u_short first = 123, last = 123;
1764
1765         if (sscanf(range, "%hu-%hu", &first, &last) != 2
1766             || first == 0 || first > 0xffff
1767             || last == 0 || last > 0xffff || first > last)
1768                 errx(1, "%s: illegal net range: %u-%u", range, first, last);
1769         at_nr.nr_firstnet = htons(first);
1770         at_nr.nr_lastnet = htons(last);
1771 }
1772
1773 void
1774 setatphase(const char *phase, int dummy __unused, int s __unused,
1775            const struct afswtch *afp __unused)
1776 {
1777         if (!strcmp(phase, "1"))
1778                 at_nr.nr_phase = 1;
1779         else if (!strcmp(phase, "2"))
1780                 at_nr.nr_phase = 2;
1781         else
1782                 errx(1, "%s: illegal phase", phase);
1783 }
1784
1785 void
1786 checkatrange(struct sockaddr_at *sat)
1787 {
1788         if (at_nr.nr_phase == 0)
1789                 at_nr.nr_phase = 2;     /* Default phase 2 */
1790         if (at_nr.nr_firstnet == 0)
1791                 at_nr.nr_firstnet =     /* Default range of one */
1792                 at_nr.nr_lastnet = sat->sat_addr.s_net;
1793 printf("\tatalk %d.%d range %d-%d phase %d\n",
1794         ntohs(sat->sat_addr.s_net), sat->sat_addr.s_node,
1795         ntohs(at_nr.nr_firstnet), ntohs(at_nr.nr_lastnet), at_nr.nr_phase);
1796         if ((u_short) ntohs(at_nr.nr_firstnet) >
1797                         (u_short) ntohs(sat->sat_addr.s_net)
1798                     || (u_short) ntohs(at_nr.nr_lastnet) <
1799                         (u_short) ntohs(sat->sat_addr.s_net))
1800                 errx(1, "AppleTalk address is not in range");
1801         sat->sat_range.r_netrange = at_nr;
1802 }
1803
1804 #ifdef NS
1805 #define SNS(x) ((struct sockaddr_ns *) &(x))
1806 struct sockaddr_ns *snstab[] = {
1807 SNS(ridreq.ifr_addr), SNS(addreq.ifra_addr),
1808 SNS(addreq.ifra_mask), SNS(addreq.ifra_broadaddr)};
1809
1810 void
1811 xns_getaddr(const char *addr, int which)
1812 {
1813         struct sockaddr_ns *sns = snstab[which];
1814
1815         sns->sns_family = AF_NS;
1816         sns->sns_len = sizeof(*sns);
1817         sns->sns_addr = ns_addr(addr);
1818         if (which == MASK)
1819                 printf("Attempt to set XNS netmask will be ineffectual\n");
1820 }
1821 #endif
1822
1823 #ifdef INET6
1824 int
1825 prefix(void *val, int size)
1826 {
1827         register u_char *addr = (u_char *)val;
1828         register int byte, bit, plen = 0;
1829
1830         for (byte = 0; byte < size; byte++, plen += 8)
1831                 if (addr[byte] != 0xff)
1832                         break;
1833         if (byte == size)
1834                 return (plen);
1835         for (bit = 7; bit != 0; bit--, plen++)
1836                 if (!(addr[byte] & (1 << bit)))
1837                         break;
1838         for (; bit != 0; bit--)
1839                 if (addr[byte] & (1 << bit))
1840                         return(0);
1841         byte++;
1842         for (; byte < size; byte++)
1843                 if (addr[byte])
1844                         return(0);
1845         return (plen);
1846 }
1847
1848 static char *
1849 sec2str(time_t total)
1850 {
1851         static char result[256];
1852         int days, hours, mins, secs;
1853         int first = 1;
1854         char *p = result;
1855
1856         if (0) {
1857                 days = total / 3600 / 24;
1858                 hours = (total / 3600) % 24;
1859                 mins = (total / 60) % 60;
1860                 secs = total % 60;
1861
1862                 if (days) {
1863                         first = 0;
1864                         p += sprintf(p, "%dd", days);
1865                 }
1866                 if (!first || hours) {
1867                         first = 0;
1868                         p += sprintf(p, "%dh", hours);
1869                 }
1870                 if (!first || mins) {
1871                         first = 0;
1872                         p += sprintf(p, "%dm", mins);
1873                 }
1874                 sprintf(p, "%ds", secs);
1875         } else
1876                 sprintf(result, "%lu", (unsigned long)total);
1877
1878         return(result);
1879 }
1880 #endif /*INET6*/
1881
1882 void
1883 ifmaybeload(char *if_nm)
1884 {
1885         struct module_stat mstat;
1886         int fileid, modid;
1887         char ifkind[35], *cp, *dp;
1888
1889
1890         /* turn interface and unit into module name */
1891         strcpy(ifkind, "if_");
1892         for (cp = if_nm, dp = ifkind + 3;
1893             (*cp != 0) && !isdigit(*cp); cp++, dp++)
1894                 *dp = *cp;
1895         *dp = 0;
1896
1897         /* scan files in kernel */
1898         mstat.version = sizeof(struct module_stat);
1899         for (fileid = kldnext(0); fileid > 0; fileid = kldnext(fileid)) {
1900                 /* scan modules in file */
1901                 for (modid = kldfirstmod(fileid); modid > 0;
1902                      modid = modfnext(modid)) {
1903                         if (modstat(modid, &mstat) < 0)
1904                                 continue;
1905                         /* strip bus name if present */
1906                         if ((cp = strchr(mstat.name, '/')) != NULL) {
1907                                 cp++;
1908                         } else {
1909                                 cp = mstat.name;
1910                         }
1911                         /* already loaded? */
1912                         if (strncmp(if_nm, cp, strlen(cp)) == 0 ||
1913                                 strncmp(ifkind, cp, strlen(cp)) == 0)
1914                                 return;
1915                 }
1916         }
1917
1918         /* not present, we should try to load it */
1919         kldload(ifkind);
1920 }
1921
1922 void
1923 list_cloners(void)
1924 {
1925         struct if_clonereq ifcr;
1926         char *cp, *buf;
1927         int idx;
1928         int s;
1929
1930         s = socket(AF_INET, SOCK_DGRAM, 0);
1931         if (s == -1)
1932                 err(1, "socket");
1933
1934         memset(&ifcr, 0, sizeof(ifcr));
1935
1936         if (ioctl(s, SIOCIFGCLONERS, &ifcr) < 0)
1937                 err(1, "SIOCIFGCLONERS for count");
1938
1939         buf = malloc(ifcr.ifcr_total * IFNAMSIZ);
1940         if (buf == NULL)
1941                 err(1, "unable to allocate cloner name buffer");
1942
1943         ifcr.ifcr_count = ifcr.ifcr_total;
1944         ifcr.ifcr_buffer = buf;
1945
1946         if (ioctl(s, SIOCIFGCLONERS, &ifcr) < 0)
1947                 err(1, "SIOCIFGCLONERS for names");
1948
1949         /*
1950          * In case some disappeared in the mean time, clamp it down.
1951          */
1952         if (ifcr.ifcr_count > ifcr.ifcr_total)
1953                 ifcr.ifcr_count = ifcr.ifcr_total;
1954
1955         for (cp = buf, idx = 0; idx < ifcr.ifcr_count; idx++, cp += IFNAMSIZ) {
1956                 if (idx > 0)
1957                         putchar(' ');
1958                 printf("%s", cp);
1959         }
1960
1961         putchar('\n');
1962         free(buf);
1963 }
1964
1965 void
1966 clone_create(void)
1967 {
1968         int s;
1969
1970         s = socket(AF_INET, SOCK_DGRAM, 0);
1971         if (s == -1)
1972                 err(1, "socket");
1973
1974         memset(&ifr, 0, sizeof(ifr));
1975         strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
1976         if (ioctl(s, SIOCIFCREATE, &ifr) < 0)
1977                 err(1, "SIOCIFCREATE");
1978
1979         /*
1980          * If we get a different name back then we put in, we probably
1981          * want to print it out, but we might change our mind later so
1982          * we just signal our intrest and leave the printout for later.
1983          */
1984         if (strcmp(name, ifr.ifr_name) != 0) {
1985                 printname = 1;
1986                 strlcpy(name, ifr.ifr_name, sizeof(name));
1987         }
1988
1989         close(s);
1990 }
1991
1992 void
1993 clone_destroy(const char *val __unused, int d __unused, int s,
1994               const struct afswtch *rafp __unused)
1995 {
1996
1997         strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
1998         if (ioctl(s, SIOCIFDESTROY, &ifr) < 0)
1999                 err(1, "SIOCIFDESTROY");
2000         /*
2001          * If we create and destroy an interface in the same command,
2002          * there isn't any reason to print it's name.
2003          */
2004         printname = 0;
2005 }