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