xref: /freebsd/sbin/ifconfig/ifconfig.c (revision e17f5b1d)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1983, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)ifconfig.c	8.2 (Berkeley) 2/16/94";
41 #endif
42 static const char rcsid[] =
43   "$FreeBSD$";
44 #endif /* not lint */
45 
46 #include <sys/param.h>
47 #include <sys/ioctl.h>
48 #include <sys/module.h>
49 #include <sys/linker.h>
50 #include <sys/queue.h>
51 #include <sys/socket.h>
52 #include <sys/time.h>
53 
54 #include <net/ethernet.h>
55 #include <net/if.h>
56 #include <net/if_dl.h>
57 #include <net/if_types.h>
58 #include <net/route.h>
59 
60 /* IP */
61 #include <netinet/in.h>
62 #include <netinet/in_var.h>
63 #include <arpa/inet.h>
64 #include <netdb.h>
65 
66 #include <fnmatch.h>
67 #include <ifaddrs.h>
68 #include <ctype.h>
69 #include <err.h>
70 #include <errno.h>
71 #include <fcntl.h>
72 #ifdef JAIL
73 #include <jail.h>
74 #endif
75 #include <stdbool.h>
76 #include <stdio.h>
77 #include <stdlib.h>
78 #include <string.h>
79 #include <unistd.h>
80 
81 #include "ifconfig.h"
82 
83 /*
84  * Since "struct ifreq" is composed of various union members, callers
85  * should pay special attention to interpret the value.
86  * (.e.g. little/big endian difference in the structure.)
87  */
88 struct	ifreq ifr;
89 
90 char	name[IFNAMSIZ];
91 char	*descr = NULL;
92 size_t	descrlen = 64;
93 int	setaddr;
94 int	setmask;
95 int	doalias;
96 int	clearaddr;
97 int	newaddr = 1;
98 int	verbose;
99 int	noload;
100 int	printifname = 0;
101 
102 int	supmedia = 0;
103 int	printkeys = 0;		/* Print keying material for interfaces. */
104 int	exit_code = 0;
105 
106 /* Formatter Strings */
107 char	*f_inet, *f_inet6, *f_ether, *f_addr;
108 
109 static	bool group_member(const char *ifname, const char *match,
110 		const char *nomatch);
111 static	int ifconfig(int argc, char *const *argv, int iscreate,
112 		const struct afswtch *afp);
113 static	void status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
114 		struct ifaddrs *ifa);
115 static	void tunnel_status(int s);
116 static _Noreturn void usage(void);
117 
118 static int getifflags(const char *ifname, int us);
119 
120 static struct afswtch *af_getbyname(const char *name);
121 static struct afswtch *af_getbyfamily(int af);
122 static void af_other_status(int);
123 
124 void printifnamemaybe(void);
125 
126 static struct option *opts = NULL;
127 
128 struct ifa_order_elt {
129 	int if_order;
130 	int af_orders[255];
131 	struct ifaddrs *ifa;
132 	TAILQ_ENTRY(ifa_order_elt) link;
133 };
134 
135 TAILQ_HEAD(ifa_queue, ifa_order_elt);
136 
137 static struct module_map_entry {
138 	const char *ifname;
139 	const char *kldname;
140 } module_map[] = {
141 	{
142 		.ifname = "tun",
143 		.kldname = "if_tuntap",
144 	},
145 	{
146 		.ifname = "tap",
147 		.kldname = "if_tuntap",
148 	},
149 	{
150 		.ifname = "vmnet",
151 		.kldname = "if_tuntap",
152 	},
153 	{
154 		.ifname = "ipsec",
155 		.kldname = "ipsec",
156 	},
157 	{
158 		/*
159 		 * This mapping exists because there is a conflicting enc module
160 		 * in CAM.  ifconfig's guessing behavior will attempt to match
161 		 * the ifname to a module as well as if_${ifname} and clash with
162 		 * CAM enc.  This is an assertion of the correct module to load.
163 		 */
164 		.ifname = "enc",
165 		.kldname = "if_enc",
166 	},
167 };
168 
169 
170 void
171 opt_register(struct option *p)
172 {
173 	p->next = opts;
174 	opts = p;
175 }
176 
177 static void
178 usage(void)
179 {
180 	char options[1024];
181 	struct option *p;
182 
183 	/* XXX not right but close enough for now */
184 	options[0] = '\0';
185 	for (p = opts; p != NULL; p = p->next) {
186 		strlcat(options, p->opt_usage, sizeof(options));
187 		strlcat(options, " ", sizeof(options));
188 	}
189 
190 	fprintf(stderr,
191 	"usage: ifconfig [-f type:format] %sinterface address_family\n"
192 	"                [address [dest_address]] [parameters]\n"
193 	"       ifconfig interface create\n"
194 	"       ifconfig -a %s[-d] [-m] [-u] [-v] [address_family]\n"
195 	"       ifconfig -l [-d] [-u] [address_family]\n"
196 	"       ifconfig %s[-d] [-m] [-u] [-v]\n",
197 		options, options, options);
198 	exit(1);
199 }
200 
201 #define ORDERS_SIZE(x) sizeof(x) / sizeof(x[0])
202 
203 static int
204 calcorders(struct ifaddrs *ifa, struct ifa_queue *q)
205 {
206 	struct ifaddrs *prev;
207 	struct ifa_order_elt *cur;
208 	unsigned int ord, af, ifa_ord;
209 
210 	prev = NULL;
211 	cur = NULL;
212 	ord = 0;
213 	ifa_ord = 0;
214 
215 	while (ifa != NULL) {
216 		if (prev == NULL ||
217 		    strcmp(ifa->ifa_name, prev->ifa_name) != 0) {
218 			cur = calloc(1, sizeof(*cur));
219 
220 			if (cur == NULL)
221 				return (-1);
222 
223 			TAILQ_INSERT_TAIL(q, cur, link);
224 			cur->if_order = ifa_ord ++;
225 			cur->ifa = ifa;
226 			ord = 0;
227 		}
228 
229 		if (ifa->ifa_addr) {
230 			af = ifa->ifa_addr->sa_family;
231 
232 			if (af < ORDERS_SIZE(cur->af_orders) &&
233 			    cur->af_orders[af] == 0)
234 				cur->af_orders[af] = ++ord;
235 		}
236 		prev = ifa;
237 		ifa = ifa->ifa_next;
238 	}
239 
240 	return (0);
241 }
242 
243 static int
244 cmpifaddrs(struct ifaddrs *a, struct ifaddrs *b, struct ifa_queue *q)
245 {
246 	struct ifa_order_elt *cur, *e1, *e2;
247 	unsigned int af1, af2;
248 	int ret;
249 
250 	e1 = e2 = NULL;
251 
252 	ret = strcmp(a->ifa_name, b->ifa_name);
253 	if (ret != 0) {
254 		TAILQ_FOREACH(cur, q, link) {
255 			if (e1 && e2)
256 				break;
257 
258 			if (strcmp(cur->ifa->ifa_name, a->ifa_name) == 0)
259 				e1 = cur;
260 			else if (strcmp(cur->ifa->ifa_name, b->ifa_name) == 0)
261 				e2 = cur;
262 		}
263 
264 		if (!e1 || !e2)
265 			return (0);
266 		else
267 			return (e1->if_order - e2->if_order);
268 
269 	} else if (a->ifa_addr != NULL && b->ifa_addr != NULL) {
270 		TAILQ_FOREACH(cur, q, link) {
271 			if (strcmp(cur->ifa->ifa_name, a->ifa_name) == 0) {
272 				e1 = cur;
273 				break;
274 			}
275 		}
276 
277 		if (!e1)
278 			return (0);
279 
280 		af1 = a->ifa_addr->sa_family;
281 		af2 = b->ifa_addr->sa_family;
282 
283 		if (af1 < ORDERS_SIZE(e1->af_orders) &&
284 		    af2 < ORDERS_SIZE(e1->af_orders))
285 			return (e1->af_orders[af1] - e1->af_orders[af2]);
286 	}
287 
288 	return (0);
289 }
290 
291 static void freeformat(void)
292 {
293 
294 	if (f_inet != NULL)
295 		free(f_inet);
296 	if (f_inet6 != NULL)
297 		free(f_inet6);
298 	if (f_ether != NULL)
299 		free(f_ether);
300 	if (f_addr != NULL)
301 		free(f_addr);
302 }
303 
304 static void setformat(char *input)
305 {
306 	char	*formatstr, *category, *modifier;
307 
308 	formatstr = strdup(input);
309 	while ((category = strsep(&formatstr, ",")) != NULL) {
310 		modifier = strchr(category, ':');
311 		if (modifier == NULL || modifier[1] == '\0') {
312 			warnx("Skipping invalid format specification: %s\n",
313 			    category);
314 			continue;
315 		}
316 
317 		/* Split the string on the separator, then seek past it */
318 		modifier[0] = '\0';
319 		modifier++;
320 
321 		if (strcmp(category, "addr") == 0)
322 			f_addr = strdup(modifier);
323 		else if (strcmp(category, "ether") == 0)
324 			f_ether = strdup(modifier);
325 		else if (strcmp(category, "inet") == 0)
326 			f_inet = strdup(modifier);
327 		else if (strcmp(category, "inet6") == 0)
328 			f_inet6 = strdup(modifier);
329 	}
330 	free(formatstr);
331 }
332 
333 #undef ORDERS_SIZE
334 
335 static struct ifaddrs *
336 sortifaddrs(struct ifaddrs *list,
337     int (*compare)(struct ifaddrs *, struct ifaddrs *, struct ifa_queue *),
338     struct ifa_queue *q)
339 {
340 	struct ifaddrs *right, *temp, *last, *result, *next, *tail;
341 
342 	right = list;
343 	temp = list;
344 	last = list;
345 	result = NULL;
346 	next = NULL;
347 	tail = NULL;
348 
349 	if (!list || !list->ifa_next)
350 		return (list);
351 
352 	while (temp && temp->ifa_next) {
353 		last = right;
354 		right = right->ifa_next;
355 		temp = temp->ifa_next->ifa_next;
356 	}
357 
358 	last->ifa_next = NULL;
359 
360 	list = sortifaddrs(list, compare, q);
361 	right = sortifaddrs(right, compare, q);
362 
363 	while (list || right) {
364 
365 		if (!right) {
366 			next = list;
367 			list = list->ifa_next;
368 		} else if (!list) {
369 			next = right;
370 			right = right->ifa_next;
371 		} else if (compare(list, right, q) <= 0) {
372 			next = list;
373 			list = list->ifa_next;
374 		} else {
375 			next = right;
376 			right = right->ifa_next;
377 		}
378 
379 		if (!result)
380 			result = next;
381 		else
382 			tail->ifa_next = next;
383 
384 		tail = next;
385 	}
386 
387 	return (result);
388 }
389 
390 void printifnamemaybe()
391 {
392 	if (printifname)
393 		printf("%s\n", name);
394 }
395 
396 int
397 main(int argc, char *argv[])
398 {
399 	int c, all, namesonly, downonly, uponly;
400 	const struct afswtch *afp = NULL;
401 	int ifindex;
402 	struct ifaddrs *ifap, *sifap, *ifa;
403 	struct ifreq paifr;
404 	const struct sockaddr_dl *sdl;
405 	char options[1024], *cp, *envformat, *namecp = NULL;
406 	struct ifa_queue q = TAILQ_HEAD_INITIALIZER(q);
407 	struct ifa_order_elt *cur, *tmp;
408 	const char *ifname, *matchgroup, *nogroup;
409 	struct option *p;
410 	size_t iflen;
411 	int flags;
412 
413 	all = downonly = uponly = namesonly = noload = verbose = 0;
414 	f_inet = f_inet6 = f_ether = f_addr = NULL;
415 	matchgroup = nogroup = NULL;
416 
417 	envformat = getenv("IFCONFIG_FORMAT");
418 	if (envformat != NULL)
419 		setformat(envformat);
420 
421 	/*
422 	 * Ensure we print interface name when expected to,
423 	 * even if we terminate early due to error.
424 	 */
425 	atexit(printifnamemaybe);
426 
427 	/* Parse leading line options */
428 	strlcpy(options, "G:adf:klmnuv", sizeof(options));
429 	for (p = opts; p != NULL; p = p->next)
430 		strlcat(options, p->opt, sizeof(options));
431 	while ((c = getopt(argc, argv, options)) != -1) {
432 		switch (c) {
433 		case 'a':	/* scan all interfaces */
434 			all++;
435 			break;
436 		case 'd':	/* restrict scan to "down" interfaces */
437 			downonly++;
438 			break;
439 		case 'f':
440 			if (optarg == NULL)
441 				usage();
442 			setformat(optarg);
443 			break;
444 		case 'G':
445 			if (optarg == NULL || all == 0)
446 				usage();
447 			nogroup = optarg;
448 			break;
449 		case 'k':
450 			printkeys++;
451 			break;
452 		case 'l':	/* scan interface names only */
453 			namesonly++;
454 			break;
455 		case 'm':	/* show media choices in status */
456 			supmedia = 1;
457 			break;
458 		case 'n':	/* suppress module loading */
459 			noload++;
460 			break;
461 		case 'u':	/* restrict scan to "up" interfaces */
462 			uponly++;
463 			break;
464 		case 'v':
465 			verbose++;
466 			break;
467 		case 'g':
468 			if (all) {
469 				if (optarg == NULL)
470 					usage();
471 				matchgroup = optarg;
472 				break;
473 			}
474 			/* FALLTHROUGH */
475 		default:
476 			for (p = opts; p != NULL; p = p->next)
477 				if (p->opt[0] == c) {
478 					p->cb(optarg);
479 					break;
480 				}
481 			if (p == NULL)
482 				usage();
483 			break;
484 		}
485 	}
486 	argc -= optind;
487 	argv += optind;
488 
489 	/* -l cannot be used with -a or -m */
490 	if (namesonly && (all || supmedia))
491 		usage();
492 
493 	/* nonsense.. */
494 	if (uponly && downonly)
495 		usage();
496 
497 	/* no arguments is equivalent to '-a' */
498 	if (!namesonly && argc < 1)
499 		all = 1;
500 
501 	/* -a and -l allow an address family arg to limit the output */
502 	if (all || namesonly) {
503 		if (argc > 1)
504 			usage();
505 
506 		ifname = NULL;
507 		ifindex = 0;
508 		if (argc == 1) {
509 			afp = af_getbyname(*argv);
510 			if (afp == NULL) {
511 				warnx("Address family '%s' unknown.", *argv);
512 				usage();
513 			}
514 			if (afp->af_name != NULL)
515 				argc--, argv++;
516 			/* leave with afp non-zero */
517 		}
518 	} else {
519 		/* not listing, need an argument */
520 		if (argc < 1)
521 			usage();
522 
523 		ifname = *argv;
524 		argc--, argv++;
525 
526 		/* check and maybe load support for this interface */
527 		ifmaybeload(ifname);
528 
529 		ifindex = if_nametoindex(ifname);
530 		if (ifindex == 0) {
531 			/*
532 			 * NOTE:  We must special-case the `create' command
533 			 * right here as we would otherwise fail when trying
534 			 * to find the interface.
535 			 */
536 			if (argc > 0 && (strcmp(argv[0], "create") == 0 ||
537 			    strcmp(argv[0], "plumb") == 0)) {
538 				iflen = strlcpy(name, ifname, sizeof(name));
539 				if (iflen >= sizeof(name))
540 					errx(1, "%s: cloning name too long",
541 					    ifname);
542 				ifconfig(argc, argv, 1, NULL);
543 				exit(exit_code);
544 			}
545 #ifdef JAIL
546 			/*
547 			 * NOTE:  We have to special-case the `-vnet' command
548 			 * right here as we would otherwise fail when trying
549 			 * to find the interface as it lives in another vnet.
550 			 */
551 			if (argc > 0 && (strcmp(argv[0], "-vnet") == 0)) {
552 				iflen = strlcpy(name, ifname, sizeof(name));
553 				if (iflen >= sizeof(name))
554 					errx(1, "%s: interface name too long",
555 					    ifname);
556 				ifconfig(argc, argv, 0, NULL);
557 				exit(exit_code);
558 			}
559 #endif
560 			errx(1, "interface %s does not exist", ifname);
561 		} else {
562 			/*
563 			 * Do not allow use `create` command as hostname if
564 			 * address family is not specified.
565 			 */
566 			if (argc > 0 && (strcmp(argv[0], "create") == 0 ||
567 			    strcmp(argv[0], "plumb") == 0)) {
568 				if (argc == 1)
569 					errx(1, "interface %s already exists",
570 					    ifname);
571 				argc--, argv++;
572 			}
573 		}
574 	}
575 
576 	/* Check for address family */
577 	if (argc > 0) {
578 		afp = af_getbyname(*argv);
579 		if (afp != NULL)
580 			argc--, argv++;
581 	}
582 
583 	/*
584 	 * Check for a requested configuration action on a single interface,
585 	 * which doesn't require building, sorting, and searching the entire
586 	 * system address list
587 	 */
588 	if ((argc > 0) && (ifname != NULL)) {
589 		iflen = strlcpy(name, ifname, sizeof(name));
590 		if (iflen >= sizeof(name)) {
591 			warnx("%s: interface name too long, skipping", ifname);
592 		} else {
593 			flags = getifflags(name, -1);
594 			if (!(((flags & IFF_CANTCONFIG) != 0) ||
595 				(downonly && (flags & IFF_UP) != 0) ||
596 				(uponly && (flags & IFF_UP) == 0)))
597 				ifconfig(argc, argv, 0, afp);
598 		}
599 		goto done;
600 	}
601 
602 	if (getifaddrs(&ifap) != 0)
603 		err(EXIT_FAILURE, "getifaddrs");
604 
605 	cp = NULL;
606 
607 	if (calcorders(ifap, &q) != 0)
608 		err(EXIT_FAILURE, "calcorders");
609 
610 	sifap = sortifaddrs(ifap, cmpifaddrs, &q);
611 
612 	TAILQ_FOREACH_SAFE(cur, &q, link, tmp)
613 		free(cur);
614 
615 	ifindex = 0;
616 	for (ifa = sifap; ifa; ifa = ifa->ifa_next) {
617 		memset(&paifr, 0, sizeof(paifr));
618 		strlcpy(paifr.ifr_name, ifa->ifa_name, sizeof(paifr.ifr_name));
619 		if (sizeof(paifr.ifr_addr) >= ifa->ifa_addr->sa_len) {
620 			memcpy(&paifr.ifr_addr, ifa->ifa_addr,
621 			    ifa->ifa_addr->sa_len);
622 		}
623 
624 		if (ifname != NULL && strcmp(ifname, ifa->ifa_name) != 0)
625 			continue;
626 		if (ifa->ifa_addr->sa_family == AF_LINK)
627 			sdl = (const struct sockaddr_dl *) ifa->ifa_addr;
628 		else
629 			sdl = NULL;
630 		if (cp != NULL && strcmp(cp, ifa->ifa_name) == 0 && !namesonly)
631 			continue;
632 		iflen = strlcpy(name, ifa->ifa_name, sizeof(name));
633 		if (iflen >= sizeof(name)) {
634 			warnx("%s: interface name too long, skipping",
635 			    ifa->ifa_name);
636 			continue;
637 		}
638 		cp = ifa->ifa_name;
639 
640 		if ((ifa->ifa_flags & IFF_CANTCONFIG) != 0)
641 			continue;
642 		if (downonly && (ifa->ifa_flags & IFF_UP) != 0)
643 			continue;
644 		if (uponly && (ifa->ifa_flags & IFF_UP) == 0)
645 			continue;
646 		if (!group_member(ifa->ifa_name, matchgroup, nogroup))
647 			continue;
648 		/*
649 		 * Are we just listing the interfaces?
650 		 */
651 		if (namesonly) {
652 			if (namecp == cp)
653 				continue;
654 			if (afp != NULL) {
655 				/* special case for "ether" address family */
656 				if (!strcmp(afp->af_name, "ether")) {
657 					if (sdl == NULL ||
658 					    (sdl->sdl_type != IFT_ETHER &&
659 					    sdl->sdl_type != IFT_L2VLAN &&
660 					    sdl->sdl_type != IFT_BRIDGE) ||
661 					    sdl->sdl_alen != ETHER_ADDR_LEN)
662 						continue;
663 				} else {
664 					if (ifa->ifa_addr->sa_family
665 					    != afp->af_af)
666 						continue;
667 				}
668 			}
669 			namecp = cp;
670 			ifindex++;
671 			if (ifindex > 1)
672 				printf(" ");
673 			fputs(name, stdout);
674 			continue;
675 		}
676 		ifindex++;
677 
678 		if (argc > 0)
679 			ifconfig(argc, argv, 0, afp);
680 		else
681 			status(afp, sdl, ifa);
682 	}
683 	if (namesonly)
684 		printf("\n");
685 	freeifaddrs(ifap);
686 
687 done:
688 	freeformat();
689 	exit(exit_code);
690 }
691 
692 /*
693  * Returns true if an interface should be listed because any its groups
694  * matches shell pattern "match" and none of groups matches pattern "nomatch".
695  * If any pattern is NULL, corresponding condition is skipped.
696  */
697 static bool
698 group_member(const char *ifname, const char *match, const char *nomatch)
699 {
700 	static int		 sock = -1;
701 
702 	struct ifgroupreq	 ifgr;
703 	struct ifg_req		*ifg;
704 	int			 len;
705 	bool			 matched, nomatched;
706 
707 	/* Sanity checks. */
708 	if (match == NULL && nomatch == NULL)
709 		return (true);
710 	if (ifname == NULL)
711 		return (false);
712 
713 	memset(&ifgr, 0, sizeof(ifgr));
714 	strlcpy(ifgr.ifgr_name, ifname, IFNAMSIZ);
715 
716 	/* The socket is opened once. Let _exit() close it. */
717 	if (sock == -1) {
718 		sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
719     		if (sock == -1)
720             	    errx(1, "%s: socket(AF_LOCAL,SOCK_DGRAM)", __func__);
721 	}
722 
723 	/* Determine amount of memory for the list of groups. */
724 	if (ioctl(sock, SIOCGIFGROUP, (caddr_t)&ifgr) == -1) {
725 		if (errno == EINVAL || errno == ENOTTY)
726 			return (false);
727 		else
728 			errx(1, "%s: SIOCGIFGROUP", __func__);
729 	}
730 
731 	/* Obtain the list of groups. */
732 	len = ifgr.ifgr_len;
733 	ifgr.ifgr_groups =
734 	    (struct ifg_req *)calloc(len / sizeof(*ifg), sizeof(*ifg));
735 
736 	if (ifgr.ifgr_groups == NULL)
737 		errx(1, "%s: no memory", __func__);
738 	if (ioctl(sock, SIOCGIFGROUP, (caddr_t)&ifgr) == -1)
739 		errx(1, "%s: SIOCGIFGROUP", __func__);
740 
741 	/* Perform matching. */
742 	matched = false;
743 	nomatched = true;
744 	for (ifg = ifgr.ifgr_groups; ifg && len >= sizeof(*ifg); ifg++) {
745 		len -= sizeof(struct ifg_req);
746 		if (match)
747 			matched |= !fnmatch(match, ifg->ifgrq_group, 0);
748 		if (nomatch)
749 			nomatched &= fnmatch(nomatch, ifg->ifgrq_group, 0);
750 	}
751 
752 	if (match && !nomatch)
753 		return (matched);
754 	if (!match && nomatch)
755 		return (nomatched);
756 	return (matched && nomatched);
757 }
758 
759 static struct afswtch *afs = NULL;
760 
761 void
762 af_register(struct afswtch *p)
763 {
764 	p->af_next = afs;
765 	afs = p;
766 }
767 
768 static struct afswtch *
769 af_getbyname(const char *name)
770 {
771 	struct afswtch *afp;
772 
773 	for (afp = afs; afp !=  NULL; afp = afp->af_next)
774 		if (strcmp(afp->af_name, name) == 0)
775 			return afp;
776 	return NULL;
777 }
778 
779 static struct afswtch *
780 af_getbyfamily(int af)
781 {
782 	struct afswtch *afp;
783 
784 	for (afp = afs; afp != NULL; afp = afp->af_next)
785 		if (afp->af_af == af)
786 			return afp;
787 	return NULL;
788 }
789 
790 static void
791 af_other_status(int s)
792 {
793 	struct afswtch *afp;
794 	uint8_t afmask[howmany(AF_MAX, NBBY)];
795 
796 	memset(afmask, 0, sizeof(afmask));
797 	for (afp = afs; afp != NULL; afp = afp->af_next) {
798 		if (afp->af_other_status == NULL)
799 			continue;
800 		if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
801 			continue;
802 		afp->af_other_status(s);
803 		setbit(afmask, afp->af_af);
804 	}
805 }
806 
807 static void
808 af_all_tunnel_status(int s)
809 {
810 	struct afswtch *afp;
811 	uint8_t afmask[howmany(AF_MAX, NBBY)];
812 
813 	memset(afmask, 0, sizeof(afmask));
814 	for (afp = afs; afp != NULL; afp = afp->af_next) {
815 		if (afp->af_status_tunnel == NULL)
816 			continue;
817 		if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
818 			continue;
819 		afp->af_status_tunnel(s);
820 		setbit(afmask, afp->af_af);
821 	}
822 }
823 
824 static struct cmd *cmds = NULL;
825 
826 void
827 cmd_register(struct cmd *p)
828 {
829 	p->c_next = cmds;
830 	cmds = p;
831 }
832 
833 static const struct cmd *
834 cmd_lookup(const char *name, int iscreate)
835 {
836 	const struct cmd *p;
837 
838 	for (p = cmds; p != NULL; p = p->c_next)
839 		if (strcmp(name, p->c_name) == 0) {
840 			if (iscreate) {
841 				if (p->c_iscloneop)
842 					return p;
843 			} else {
844 				if (!p->c_iscloneop)
845 					return p;
846 			}
847 		}
848 	return NULL;
849 }
850 
851 struct callback {
852 	callback_func *cb_func;
853 	void	*cb_arg;
854 	struct callback *cb_next;
855 };
856 static struct callback *callbacks = NULL;
857 
858 void
859 callback_register(callback_func *func, void *arg)
860 {
861 	struct callback *cb;
862 
863 	cb = malloc(sizeof(struct callback));
864 	if (cb == NULL)
865 		errx(1, "unable to allocate memory for callback");
866 	cb->cb_func = func;
867 	cb->cb_arg = arg;
868 	cb->cb_next = callbacks;
869 	callbacks = cb;
870 }
871 
872 /* specially-handled commands */
873 static void setifaddr(const char *, int, int, const struct afswtch *);
874 static const struct cmd setifaddr_cmd = DEF_CMD("ifaddr", 0, setifaddr);
875 
876 static void setifdstaddr(const char *, int, int, const struct afswtch *);
877 static const struct cmd setifdstaddr_cmd =
878 	DEF_CMD("ifdstaddr", 0, setifdstaddr);
879 
880 static int
881 ifconfig(int argc, char *const *argv, int iscreate, const struct afswtch *uafp)
882 {
883 	const struct afswtch *afp, *nafp;
884 	const struct cmd *p;
885 	struct callback *cb;
886 	int s;
887 
888 	strlcpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
889 	afp = NULL;
890 	if (uafp != NULL)
891 		afp = uafp;
892 	/*
893 	 * This is the historical "accident" allowing users to configure IPv4
894 	 * addresses without the "inet" keyword which while a nice feature has
895 	 * proven to complicate other things.  We cannot remove this but only
896 	 * make sure we will never have a similar implicit default for IPv6 or
897 	 * any other address familiy.  We need a fallback though for
898 	 * ifconfig IF up/down etc. to work without INET support as people
899 	 * never used ifconfig IF link up/down, etc. either.
900 	 */
901 #ifndef RESCUE
902 #ifdef INET
903 	if (afp == NULL && feature_present("inet"))
904 		afp = af_getbyname("inet");
905 #endif
906 #endif
907 	if (afp == NULL)
908 		afp = af_getbyname("link");
909 	if (afp == NULL) {
910 		warnx("Please specify an address_family.");
911 		usage();
912 	}
913 top:
914 	ifr.ifr_addr.sa_family =
915 		afp->af_af == AF_LINK || afp->af_af == AF_UNSPEC ?
916 		AF_LOCAL : afp->af_af;
917 
918 	if ((s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0)) < 0 &&
919 	    (uafp != NULL || errno != EAFNOSUPPORT ||
920 	     (s = socket(AF_LOCAL, SOCK_DGRAM, 0)) < 0))
921 		err(1, "socket(family %u,SOCK_DGRAM)", ifr.ifr_addr.sa_family);
922 
923 	while (argc > 0) {
924 		p = cmd_lookup(*argv, iscreate);
925 		if (iscreate && p == NULL) {
926 			/*
927 			 * Push the clone create callback so the new
928 			 * device is created and can be used for any
929 			 * remaining arguments.
930 			 */
931 			cb = callbacks;
932 			if (cb == NULL)
933 				errx(1, "internal error, no callback");
934 			callbacks = cb->cb_next;
935 			cb->cb_func(s, cb->cb_arg);
936 			iscreate = 0;
937 			/*
938 			 * Handle any address family spec that
939 			 * immediately follows and potentially
940 			 * recreate the socket.
941 			 */
942 			nafp = af_getbyname(*argv);
943 			if (nafp != NULL) {
944 				argc--, argv++;
945 				if (nafp != afp) {
946 					close(s);
947 					afp = nafp;
948 					goto top;
949 				}
950 			}
951 			/*
952 			 * Look for a normal parameter.
953 			 */
954 			continue;
955 		}
956 		if (p == NULL) {
957 			/*
958 			 * Not a recognized command, choose between setting
959 			 * the interface address and the dst address.
960 			 */
961 			p = (setaddr ? &setifdstaddr_cmd : &setifaddr_cmd);
962 		}
963 		if (p->c_parameter == NEXTARG && p->c_u.c_func) {
964 			if (argv[1] == NULL)
965 				errx(1, "'%s' requires argument",
966 				    p->c_name);
967 			p->c_u.c_func(argv[1], 0, s, afp);
968 			argc--, argv++;
969 		} else if (p->c_parameter == OPTARG && p->c_u.c_func) {
970 			p->c_u.c_func(argv[1], 0, s, afp);
971 			if (argv[1] != NULL)
972 				argc--, argv++;
973 		} else if (p->c_parameter == NEXTARG2 && p->c_u.c_func2) {
974 			if (argc < 3)
975 				errx(1, "'%s' requires 2 arguments",
976 				    p->c_name);
977 			p->c_u.c_func2(argv[1], argv[2], s, afp);
978 			argc -= 2, argv += 2;
979 		} else if (p->c_u.c_func)
980 			p->c_u.c_func(*argv, p->c_parameter, s, afp);
981 		argc--, argv++;
982 	}
983 
984 	/*
985 	 * Do any post argument processing required by the address family.
986 	 */
987 	if (afp->af_postproc != NULL)
988 		afp->af_postproc(s, afp);
989 	/*
990 	 * Do deferred callbacks registered while processing
991 	 * command-line arguments.
992 	 */
993 	for (cb = callbacks; cb != NULL; cb = cb->cb_next)
994 		cb->cb_func(s, cb->cb_arg);
995 	/*
996 	 * Do deferred operations.
997 	 */
998 	if (clearaddr) {
999 		if (afp->af_ridreq == NULL || afp->af_difaddr == 0) {
1000 			warnx("interface %s cannot change %s addresses!",
1001 			      name, afp->af_name);
1002 			clearaddr = 0;
1003 		}
1004 	}
1005 	if (clearaddr) {
1006 		int ret;
1007 		strlcpy(((struct ifreq *)afp->af_ridreq)->ifr_name, name,
1008 			sizeof ifr.ifr_name);
1009 		ret = ioctl(s, afp->af_difaddr, afp->af_ridreq);
1010 		if (ret < 0) {
1011 			if (errno == EADDRNOTAVAIL && (doalias >= 0)) {
1012 				/* means no previous address for interface */
1013 			} else
1014 				Perror("ioctl (SIOCDIFADDR)");
1015 		}
1016 	}
1017 	if (newaddr) {
1018 		if (afp->af_addreq == NULL || afp->af_aifaddr == 0) {
1019 			warnx("interface %s cannot change %s addresses!",
1020 			      name, afp->af_name);
1021 			newaddr = 0;
1022 		}
1023 	}
1024 	if (newaddr && (setaddr || setmask)) {
1025 		strlcpy(((struct ifreq *)afp->af_addreq)->ifr_name, name,
1026 			sizeof ifr.ifr_name);
1027 		if (ioctl(s, afp->af_aifaddr, afp->af_addreq) < 0)
1028 			Perror("ioctl (SIOCAIFADDR)");
1029 	}
1030 
1031 	close(s);
1032 	return(0);
1033 }
1034 
1035 /*ARGSUSED*/
1036 static void
1037 setifaddr(const char *addr, int param, int s, const struct afswtch *afp)
1038 {
1039 	if (afp->af_getaddr == NULL)
1040 		return;
1041 	/*
1042 	 * Delay the ioctl to set the interface addr until flags are all set.
1043 	 * The address interpretation may depend on the flags,
1044 	 * and the flags may change when the address is set.
1045 	 */
1046 	setaddr++;
1047 	if (doalias == 0 && afp->af_af != AF_LINK)
1048 		clearaddr = 1;
1049 	afp->af_getaddr(addr, (doalias >= 0 ? ADDR : RIDADDR));
1050 }
1051 
1052 static void
1053 settunnel(const char *src, const char *dst, int s, const struct afswtch *afp)
1054 {
1055 	struct addrinfo *srcres, *dstres;
1056 	int ecode;
1057 
1058 	if (afp->af_settunnel == NULL) {
1059 		warn("address family %s does not support tunnel setup",
1060 			afp->af_name);
1061 		return;
1062 	}
1063 
1064 	if ((ecode = getaddrinfo(src, NULL, NULL, &srcres)) != 0)
1065 		errx(1, "error in parsing address string: %s",
1066 		    gai_strerror(ecode));
1067 
1068 	if ((ecode = getaddrinfo(dst, NULL, NULL, &dstres)) != 0)
1069 		errx(1, "error in parsing address string: %s",
1070 		    gai_strerror(ecode));
1071 
1072 	if (srcres->ai_addr->sa_family != dstres->ai_addr->sa_family)
1073 		errx(1,
1074 		    "source and destination address families do not match");
1075 
1076 	afp->af_settunnel(s, srcres, dstres);
1077 
1078 	freeaddrinfo(srcres);
1079 	freeaddrinfo(dstres);
1080 }
1081 
1082 /* ARGSUSED */
1083 static void
1084 deletetunnel(const char *vname, int param, int s, const struct afswtch *afp)
1085 {
1086 
1087 	if (ioctl(s, SIOCDIFPHYADDR, &ifr) < 0)
1088 		err(1, "SIOCDIFPHYADDR");
1089 }
1090 
1091 #ifdef JAIL
1092 static void
1093 setifvnet(const char *jname, int dummy __unused, int s,
1094     const struct afswtch *afp)
1095 {
1096 	struct ifreq my_ifr;
1097 
1098 	memcpy(&my_ifr, &ifr, sizeof(my_ifr));
1099 	my_ifr.ifr_jid = jail_getid(jname);
1100 	if (my_ifr.ifr_jid < 0)
1101 		errx(1, "%s", jail_errmsg);
1102 	if (ioctl(s, SIOCSIFVNET, &my_ifr) < 0)
1103 		err(1, "SIOCSIFVNET");
1104 }
1105 
1106 static void
1107 setifrvnet(const char *jname, int dummy __unused, int s,
1108     const struct afswtch *afp)
1109 {
1110 	struct ifreq my_ifr;
1111 
1112 	memcpy(&my_ifr, &ifr, sizeof(my_ifr));
1113 	my_ifr.ifr_jid = jail_getid(jname);
1114 	if (my_ifr.ifr_jid < 0)
1115 		errx(1, "%s", jail_errmsg);
1116 	if (ioctl(s, SIOCSIFRVNET, &my_ifr) < 0)
1117 		err(1, "SIOCSIFRVNET(%d, %s)", my_ifr.ifr_jid, my_ifr.ifr_name);
1118 }
1119 #endif
1120 
1121 static void
1122 setifnetmask(const char *addr, int dummy __unused, int s,
1123     const struct afswtch *afp)
1124 {
1125 	if (afp->af_getaddr != NULL) {
1126 		setmask++;
1127 		afp->af_getaddr(addr, MASK);
1128 	}
1129 }
1130 
1131 static void
1132 setifbroadaddr(const char *addr, int dummy __unused, int s,
1133     const struct afswtch *afp)
1134 {
1135 	if (afp->af_getaddr != NULL)
1136 		afp->af_getaddr(addr, DSTADDR);
1137 }
1138 
1139 static void
1140 notealias(const char *addr, int param, int s, const struct afswtch *afp)
1141 {
1142 #define rqtosa(x) (&(((struct ifreq *)(afp->x))->ifr_addr))
1143 	if (setaddr && doalias == 0 && param < 0)
1144 		if (afp->af_addreq != NULL && afp->af_ridreq != NULL)
1145 			bcopy((caddr_t)rqtosa(af_addreq),
1146 			      (caddr_t)rqtosa(af_ridreq),
1147 			      rqtosa(af_addreq)->sa_len);
1148 	doalias = param;
1149 	if (param < 0) {
1150 		clearaddr = 1;
1151 		newaddr = 0;
1152 	} else
1153 		clearaddr = 0;
1154 #undef rqtosa
1155 }
1156 
1157 /*ARGSUSED*/
1158 static void
1159 setifdstaddr(const char *addr, int param __unused, int s,
1160     const struct afswtch *afp)
1161 {
1162 	if (afp->af_getaddr != NULL)
1163 		afp->af_getaddr(addr, DSTADDR);
1164 }
1165 
1166 static int
1167 getifflags(const char *ifname, int us)
1168 {
1169 	struct ifreq my_ifr;
1170 	int s;
1171 
1172 	memset(&my_ifr, 0, sizeof(my_ifr));
1173 	(void) strlcpy(my_ifr.ifr_name, ifname, sizeof(my_ifr.ifr_name));
1174 	if (us < 0) {
1175 		if ((s = socket(AF_LOCAL, SOCK_DGRAM, 0)) < 0)
1176 			err(1, "socket(family AF_LOCAL,SOCK_DGRAM");
1177 	} else
1178 		s = us;
1179  	if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&my_ifr) < 0) {
1180  		Perror("ioctl (SIOCGIFFLAGS)");
1181  		exit(1);
1182  	}
1183 	if (us < 0)
1184 		close(s);
1185 	return ((my_ifr.ifr_flags & 0xffff) | (my_ifr.ifr_flagshigh << 16));
1186 }
1187 
1188 /*
1189  * Note: doing an SIOCIGIFFLAGS scribbles on the union portion
1190  * of the ifreq structure, which may confuse other parts of ifconfig.
1191  * Make a private copy so we can avoid that.
1192  */
1193 static void
1194 setifflags(const char *vname, int value, int s, const struct afswtch *afp)
1195 {
1196 	struct ifreq		my_ifr;
1197 	int flags;
1198 
1199 	flags = getifflags(name, s);
1200 	if (value < 0) {
1201 		value = -value;
1202 		flags &= ~value;
1203 	} else
1204 		flags |= value;
1205 	memset(&my_ifr, 0, sizeof(my_ifr));
1206 	(void) strlcpy(my_ifr.ifr_name, name, sizeof(my_ifr.ifr_name));
1207 	my_ifr.ifr_flags = flags & 0xffff;
1208 	my_ifr.ifr_flagshigh = flags >> 16;
1209 	if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&my_ifr) < 0)
1210 		Perror(vname);
1211 }
1212 
1213 void
1214 setifcap(const char *vname, int value, int s, const struct afswtch *afp)
1215 {
1216 	int flags;
1217 
1218  	if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) < 0) {
1219  		Perror("ioctl (SIOCGIFCAP)");
1220  		exit(1);
1221  	}
1222 	flags = ifr.ifr_curcap;
1223 	if (value < 0) {
1224 		value = -value;
1225 		flags &= ~value;
1226 	} else
1227 		flags |= value;
1228 	flags &= ifr.ifr_reqcap;
1229 	ifr.ifr_reqcap = flags;
1230 	if (ioctl(s, SIOCSIFCAP, (caddr_t)&ifr) < 0)
1231 		Perror(vname);
1232 }
1233 
1234 static void
1235 setifmetric(const char *val, int dummy __unused, int s,
1236     const struct afswtch *afp)
1237 {
1238 	strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
1239 	ifr.ifr_metric = atoi(val);
1240 	if (ioctl(s, SIOCSIFMETRIC, (caddr_t)&ifr) < 0)
1241 		err(1, "ioctl SIOCSIFMETRIC (set metric)");
1242 }
1243 
1244 static void
1245 setifmtu(const char *val, int dummy __unused, int s,
1246     const struct afswtch *afp)
1247 {
1248 	strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
1249 	ifr.ifr_mtu = atoi(val);
1250 	if (ioctl(s, SIOCSIFMTU, (caddr_t)&ifr) < 0)
1251 		err(1, "ioctl SIOCSIFMTU (set mtu)");
1252 }
1253 
1254 static void
1255 setifpcp(const char *val, int arg __unused, int s, const struct afswtch *afp)
1256 {
1257 	u_long ul;
1258 	char *endp;
1259 
1260 	ul = strtoul(val, &endp, 0);
1261 	if (*endp != '\0')
1262 		errx(1, "invalid value for pcp");
1263 	if (ul > 7)
1264 		errx(1, "value for pcp out of range");
1265 	ifr.ifr_lan_pcp = ul;
1266 	if (ioctl(s, SIOCSLANPCP, (caddr_t)&ifr) == -1)
1267 		err(1, "SIOCSLANPCP");
1268 }
1269 
1270 static void
1271 disableifpcp(const char *val, int arg __unused, int s,
1272     const struct afswtch *afp)
1273 {
1274 
1275 	ifr.ifr_lan_pcp = IFNET_PCP_NONE;
1276 	if (ioctl(s, SIOCSLANPCP, (caddr_t)&ifr) == -1)
1277 		err(1, "SIOCSLANPCP");
1278 }
1279 
1280 static void
1281 setifname(const char *val, int dummy __unused, int s,
1282     const struct afswtch *afp)
1283 {
1284 	char *newname;
1285 
1286 	strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
1287 
1288 	newname = strdup(val);
1289 	if (newname == NULL)
1290 		err(1, "no memory to set ifname");
1291 	ifr.ifr_data = newname;
1292 	if (ioctl(s, SIOCSIFNAME, (caddr_t)&ifr) < 0) {
1293 		free(newname);
1294 		err(1, "ioctl SIOCSIFNAME (set name)");
1295 	}
1296 	printifname = 1;
1297 	strlcpy(name, newname, sizeof(name));
1298 	free(newname);
1299 }
1300 
1301 /* ARGSUSED */
1302 static void
1303 setifdescr(const char *val, int dummy __unused, int s,
1304     const struct afswtch *afp)
1305 {
1306 	char *newdescr;
1307 
1308 	strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
1309 
1310 	ifr.ifr_buffer.length = strlen(val) + 1;
1311 	if (ifr.ifr_buffer.length == 1) {
1312 		ifr.ifr_buffer.buffer = newdescr = NULL;
1313 		ifr.ifr_buffer.length = 0;
1314 	} else {
1315 		newdescr = strdup(val);
1316 		ifr.ifr_buffer.buffer = newdescr;
1317 		if (newdescr == NULL) {
1318 			warn("no memory to set ifdescr");
1319 			return;
1320 		}
1321 	}
1322 
1323 	if (ioctl(s, SIOCSIFDESCR, (caddr_t)&ifr) < 0)
1324 		err(1, "ioctl SIOCSIFDESCR (set descr)");
1325 
1326 	free(newdescr);
1327 }
1328 
1329 /* ARGSUSED */
1330 static void
1331 unsetifdescr(const char *val, int value, int s, const struct afswtch *afp)
1332 {
1333 
1334 	setifdescr("", 0, s, 0);
1335 }
1336 
1337 #define	IFFBITS \
1338 "\020\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5POINTOPOINT\7RUNNING" \
1339 "\10NOARP\11PROMISC\12ALLMULTI\13OACTIVE\14SIMPLEX\15LINK0\16LINK1\17LINK2" \
1340 "\20MULTICAST\22PPROMISC\23MONITOR\24STATICARP"
1341 
1342 #define	IFCAPBITS \
1343 "\020\1RXCSUM\2TXCSUM\3NETCONS\4VLAN_MTU\5VLAN_HWTAGGING\6JUMBO_MTU\7POLLING" \
1344 "\10VLAN_HWCSUM\11TSO4\12TSO6\13LRO\14WOL_UCAST\15WOL_MCAST\16WOL_MAGIC" \
1345 "\17TOE4\20TOE6\21VLAN_HWFILTER\23VLAN_HWTSO\24LINKSTATE\25NETMAP" \
1346 "\26RXCSUM_IPV6\27TXCSUM_IPV6\31TXRTLMT\32HWRXTSTMP\33NOMAP\34TXTLS4\35TXTLS6"
1347 
1348 /*
1349  * Print the status of the interface.  If an address family was
1350  * specified, show only it; otherwise, show them all.
1351  */
1352 static void
1353 status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
1354 	struct ifaddrs *ifa)
1355 {
1356 	struct ifaddrs *ift;
1357 	int allfamilies, s;
1358 	struct ifstat ifs;
1359 
1360 	if (afp == NULL) {
1361 		allfamilies = 1;
1362 		ifr.ifr_addr.sa_family = AF_LOCAL;
1363 	} else {
1364 		allfamilies = 0;
1365 		ifr.ifr_addr.sa_family =
1366 		    afp->af_af == AF_LINK ? AF_LOCAL : afp->af_af;
1367 	}
1368 	strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
1369 
1370 	s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0);
1371 	if (s < 0)
1372 		err(1, "socket(family %u,SOCK_DGRAM)", ifr.ifr_addr.sa_family);
1373 
1374 	printf("%s: ", name);
1375 	printb("flags", ifa->ifa_flags, IFFBITS);
1376 	if (ioctl(s, SIOCGIFMETRIC, &ifr) != -1)
1377 		printf(" metric %d", ifr.ifr_metric);
1378 	if (ioctl(s, SIOCGIFMTU, &ifr) != -1)
1379 		printf(" mtu %d", ifr.ifr_mtu);
1380 	putchar('\n');
1381 
1382 	for (;;) {
1383 		if ((descr = reallocf(descr, descrlen)) != NULL) {
1384 			ifr.ifr_buffer.buffer = descr;
1385 			ifr.ifr_buffer.length = descrlen;
1386 			if (ioctl(s, SIOCGIFDESCR, &ifr) == 0) {
1387 				if (ifr.ifr_buffer.buffer == descr) {
1388 					if (strlen(descr) > 0)
1389 						printf("\tdescription: %s\n",
1390 						    descr);
1391 				} else if (ifr.ifr_buffer.length > descrlen) {
1392 					descrlen = ifr.ifr_buffer.length;
1393 					continue;
1394 				}
1395 			}
1396 		} else
1397 			warn("unable to allocate memory for interface"
1398 			    "description");
1399 		break;
1400 	}
1401 
1402 	if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) == 0) {
1403 		if (ifr.ifr_curcap != 0) {
1404 			printb("\toptions", ifr.ifr_curcap, IFCAPBITS);
1405 			putchar('\n');
1406 		}
1407 		if (supmedia && ifr.ifr_reqcap != 0) {
1408 			printb("\tcapabilities", ifr.ifr_reqcap, IFCAPBITS);
1409 			putchar('\n');
1410 		}
1411 	}
1412 
1413 	tunnel_status(s);
1414 
1415 	for (ift = ifa; ift != NULL; ift = ift->ifa_next) {
1416 		if (ift->ifa_addr == NULL)
1417 			continue;
1418 		if (strcmp(ifa->ifa_name, ift->ifa_name) != 0)
1419 			continue;
1420 		if (allfamilies) {
1421 			const struct afswtch *p;
1422 			p = af_getbyfamily(ift->ifa_addr->sa_family);
1423 			if (p != NULL && p->af_status != NULL)
1424 				p->af_status(s, ift);
1425 		} else if (afp->af_af == ift->ifa_addr->sa_family)
1426 			afp->af_status(s, ift);
1427 	}
1428 #if 0
1429 	if (allfamilies || afp->af_af == AF_LINK) {
1430 		const struct afswtch *lafp;
1431 
1432 		/*
1433 		 * Hack; the link level address is received separately
1434 		 * from the routing information so any address is not
1435 		 * handled above.  Cobble together an entry and invoke
1436 		 * the status method specially.
1437 		 */
1438 		lafp = af_getbyname("lladdr");
1439 		if (lafp != NULL) {
1440 			info.rti_info[RTAX_IFA] = (struct sockaddr *)sdl;
1441 			lafp->af_status(s, &info);
1442 		}
1443 	}
1444 #endif
1445 	if (allfamilies)
1446 		af_other_status(s);
1447 	else if (afp->af_other_status != NULL)
1448 		afp->af_other_status(s);
1449 
1450 	strlcpy(ifs.ifs_name, name, sizeof ifs.ifs_name);
1451 	if (ioctl(s, SIOCGIFSTATUS, &ifs) == 0)
1452 		printf("%s", ifs.ascii);
1453 
1454 	if (verbose > 0)
1455 		sfp_status(s, &ifr, verbose);
1456 
1457 	close(s);
1458 	return;
1459 }
1460 
1461 static void
1462 tunnel_status(int s)
1463 {
1464 	af_all_tunnel_status(s);
1465 }
1466 
1467 void
1468 Perror(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 /*
1486  * Print a value a la the %b format of the kernel's printf
1487  */
1488 void
1489 printb(const char *s, unsigned v, const char *bits)
1490 {
1491 	int i, any = 0;
1492 	char c;
1493 
1494 	if (bits && *bits == 8)
1495 		printf("%s=%o", s, v);
1496 	else
1497 		printf("%s=%x", s, v);
1498 	if (bits) {
1499 		bits++;
1500 		putchar('<');
1501 		while ((i = *bits++) != '\0') {
1502 			if (v & (1 << (i-1))) {
1503 				if (any)
1504 					putchar(',');
1505 				any = 1;
1506 				for (; (c = *bits) > 32; bits++)
1507 					putchar(c);
1508 			} else
1509 				for (; *bits > 32; bits++)
1510 					;
1511 		}
1512 		putchar('>');
1513 	}
1514 }
1515 
1516 void
1517 print_vhid(const struct ifaddrs *ifa, const char *s)
1518 {
1519 	struct if_data *ifd;
1520 
1521 	if (ifa->ifa_data == NULL)
1522 		return;
1523 
1524 	ifd = ifa->ifa_data;
1525 	if (ifd->ifi_vhid == 0)
1526 		return;
1527 
1528 	printf(" vhid %d", ifd->ifi_vhid);
1529 }
1530 
1531 void
1532 ifmaybeload(const char *name)
1533 {
1534 #define MOD_PREFIX_LEN		3	/* "if_" */
1535 	struct module_stat mstat;
1536 	int i, fileid, modid;
1537 	char ifkind[IFNAMSIZ + MOD_PREFIX_LEN], ifname[IFNAMSIZ], *dp;
1538 	const char *cp;
1539 	struct module_map_entry *mme;
1540 	bool found;
1541 
1542 	/* loading suppressed by the user */
1543 	if (noload)
1544 		return;
1545 
1546 	/* trim the interface number off the end */
1547 	strlcpy(ifname, name, sizeof(ifname));
1548 	for (dp = ifname; *dp != 0; dp++)
1549 		if (isdigit(*dp)) {
1550 			*dp = 0;
1551 			break;
1552 		}
1553 
1554 	/* Either derive it from the map or guess otherwise */
1555 	*ifkind = '\0';
1556 	found = false;
1557 	for (i = 0; i < nitems(module_map); ++i) {
1558 		mme = &module_map[i];
1559 		if (strcmp(mme->ifname, ifname) == 0) {
1560 			strlcpy(ifkind, mme->kldname, sizeof(ifkind));
1561 			found = true;
1562 			break;
1563 		}
1564 	}
1565 
1566 	/* We didn't have an alias for it... we'll guess. */
1567 	if (!found) {
1568 	    /* turn interface and unit into module name */
1569 	    strlcpy(ifkind, "if_", sizeof(ifkind));
1570 	    strlcat(ifkind, ifname, sizeof(ifkind));
1571 	}
1572 
1573 	/* scan files in kernel */
1574 	mstat.version = sizeof(struct module_stat);
1575 	for (fileid = kldnext(0); fileid > 0; fileid = kldnext(fileid)) {
1576 		/* scan modules in file */
1577 		for (modid = kldfirstmod(fileid); modid > 0;
1578 		     modid = modfnext(modid)) {
1579 			if (modstat(modid, &mstat) < 0)
1580 				continue;
1581 			/* strip bus name if present */
1582 			if ((cp = strchr(mstat.name, '/')) != NULL) {
1583 				cp++;
1584 			} else {
1585 				cp = mstat.name;
1586 			}
1587 			/*
1588 			 * Is it already loaded?  Don't compare with ifname if
1589 			 * we were specifically told which kld to use.  Doing
1590 			 * so could lead to conflicts not trivially solved.
1591 			 */
1592 			if ((!found && strcmp(ifname, cp) == 0) ||
1593 			    strcmp(ifkind, cp) == 0)
1594 				return;
1595 		}
1596 	}
1597 
1598 	/*
1599 	 * Try to load the module.  But ignore failures, because ifconfig can't
1600 	 * infer the names of all drivers (eg mlx4en(4)).
1601 	 */
1602 	(void) kldload(ifkind);
1603 }
1604 
1605 static struct cmd basic_cmds[] = {
1606 	DEF_CMD("up",		IFF_UP,		setifflags),
1607 	DEF_CMD("down",		-IFF_UP,	setifflags),
1608 	DEF_CMD("arp",		-IFF_NOARP,	setifflags),
1609 	DEF_CMD("-arp",		IFF_NOARP,	setifflags),
1610 	DEF_CMD("debug",	IFF_DEBUG,	setifflags),
1611 	DEF_CMD("-debug",	-IFF_DEBUG,	setifflags),
1612 	DEF_CMD_ARG("description",		setifdescr),
1613 	DEF_CMD_ARG("descr",			setifdescr),
1614 	DEF_CMD("-description",	0,		unsetifdescr),
1615 	DEF_CMD("-descr",	0,		unsetifdescr),
1616 	DEF_CMD("promisc",	IFF_PPROMISC,	setifflags),
1617 	DEF_CMD("-promisc",	-IFF_PPROMISC,	setifflags),
1618 	DEF_CMD("add",		IFF_UP,		notealias),
1619 	DEF_CMD("alias",	IFF_UP,		notealias),
1620 	DEF_CMD("-alias",	-IFF_UP,	notealias),
1621 	DEF_CMD("delete",	-IFF_UP,	notealias),
1622 	DEF_CMD("remove",	-IFF_UP,	notealias),
1623 #ifdef notdef
1624 #define	EN_SWABIPS	0x1000
1625 	DEF_CMD("swabips",	EN_SWABIPS,	setifflags),
1626 	DEF_CMD("-swabips",	-EN_SWABIPS,	setifflags),
1627 #endif
1628 	DEF_CMD_ARG("netmask",			setifnetmask),
1629 	DEF_CMD_ARG("metric",			setifmetric),
1630 	DEF_CMD_ARG("broadcast",		setifbroadaddr),
1631 	DEF_CMD_ARG2("tunnel",			settunnel),
1632 	DEF_CMD("-tunnel", 0,			deletetunnel),
1633 	DEF_CMD("deletetunnel", 0,		deletetunnel),
1634 #ifdef JAIL
1635 	DEF_CMD_ARG("vnet",			setifvnet),
1636 	DEF_CMD_ARG("-vnet",			setifrvnet),
1637 #endif
1638 	DEF_CMD("link0",	IFF_LINK0,	setifflags),
1639 	DEF_CMD("-link0",	-IFF_LINK0,	setifflags),
1640 	DEF_CMD("link1",	IFF_LINK1,	setifflags),
1641 	DEF_CMD("-link1",	-IFF_LINK1,	setifflags),
1642 	DEF_CMD("link2",	IFF_LINK2,	setifflags),
1643 	DEF_CMD("-link2",	-IFF_LINK2,	setifflags),
1644 	DEF_CMD("monitor",	IFF_MONITOR,	setifflags),
1645 	DEF_CMD("-monitor",	-IFF_MONITOR,	setifflags),
1646 	DEF_CMD("nomap",	IFCAP_NOMAP,	setifcap),
1647 	DEF_CMD("-nomap",	-IFCAP_NOMAP,	setifcap),
1648 	DEF_CMD("staticarp",	IFF_STATICARP,	setifflags),
1649 	DEF_CMD("-staticarp",	-IFF_STATICARP,	setifflags),
1650 	DEF_CMD("rxcsum6",	IFCAP_RXCSUM_IPV6,	setifcap),
1651 	DEF_CMD("-rxcsum6",	-IFCAP_RXCSUM_IPV6,	setifcap),
1652 	DEF_CMD("txcsum6",	IFCAP_TXCSUM_IPV6,	setifcap),
1653 	DEF_CMD("-txcsum6",	-IFCAP_TXCSUM_IPV6,	setifcap),
1654 	DEF_CMD("rxcsum",	IFCAP_RXCSUM,	setifcap),
1655 	DEF_CMD("-rxcsum",	-IFCAP_RXCSUM,	setifcap),
1656 	DEF_CMD("txcsum",	IFCAP_TXCSUM,	setifcap),
1657 	DEF_CMD("-txcsum",	-IFCAP_TXCSUM,	setifcap),
1658 	DEF_CMD("netcons",	IFCAP_NETCONS,	setifcap),
1659 	DEF_CMD("-netcons",	-IFCAP_NETCONS,	setifcap),
1660 	DEF_CMD_ARG("pcp",			setifpcp),
1661 	DEF_CMD("-pcp", 0,			disableifpcp),
1662 	DEF_CMD("polling",	IFCAP_POLLING,	setifcap),
1663 	DEF_CMD("-polling",	-IFCAP_POLLING,	setifcap),
1664 	DEF_CMD("tso6",		IFCAP_TSO6,	setifcap),
1665 	DEF_CMD("-tso6",	-IFCAP_TSO6,	setifcap),
1666 	DEF_CMD("tso4",		IFCAP_TSO4,	setifcap),
1667 	DEF_CMD("-tso4",	-IFCAP_TSO4,	setifcap),
1668 	DEF_CMD("tso",		IFCAP_TSO,	setifcap),
1669 	DEF_CMD("-tso",		-IFCAP_TSO,	setifcap),
1670 	DEF_CMD("toe",		IFCAP_TOE,	setifcap),
1671 	DEF_CMD("-toe",		-IFCAP_TOE,	setifcap),
1672 	DEF_CMD("lro",		IFCAP_LRO,	setifcap),
1673 	DEF_CMD("-lro",		-IFCAP_LRO,	setifcap),
1674 	DEF_CMD("txtls",	IFCAP_TXTLS,	setifcap),
1675 	DEF_CMD("-txtls",	-IFCAP_TXTLS,	setifcap),
1676 	DEF_CMD("wol",		IFCAP_WOL,	setifcap),
1677 	DEF_CMD("-wol",		-IFCAP_WOL,	setifcap),
1678 	DEF_CMD("wol_ucast",	IFCAP_WOL_UCAST,	setifcap),
1679 	DEF_CMD("-wol_ucast",	-IFCAP_WOL_UCAST,	setifcap),
1680 	DEF_CMD("wol_mcast",	IFCAP_WOL_MCAST,	setifcap),
1681 	DEF_CMD("-wol_mcast",	-IFCAP_WOL_MCAST,	setifcap),
1682 	DEF_CMD("wol_magic",	IFCAP_WOL_MAGIC,	setifcap),
1683 	DEF_CMD("-wol_magic",	-IFCAP_WOL_MAGIC,	setifcap),
1684 	DEF_CMD("txrtlmt",	IFCAP_TXRTLMT,	setifcap),
1685 	DEF_CMD("-txrtlmt",	-IFCAP_TXRTLMT,	setifcap),
1686 	DEF_CMD("hwrxtstmp",	IFCAP_HWRXTSTMP,	setifcap),
1687 	DEF_CMD("-hwrxtstmp",	-IFCAP_HWRXTSTMP,	setifcap),
1688 	DEF_CMD("normal",	-IFF_LINK0,	setifflags),
1689 	DEF_CMD("compress",	IFF_LINK0,	setifflags),
1690 	DEF_CMD("noicmp",	IFF_LINK1,	setifflags),
1691 	DEF_CMD_ARG("mtu",			setifmtu),
1692 	DEF_CMD_ARG("name",			setifname),
1693 };
1694 
1695 static __constructor void
1696 ifconfig_ctor(void)
1697 {
1698 	size_t i;
1699 
1700 	for (i = 0; i < nitems(basic_cmds);  i++)
1701 		cmd_register(&basic_cmds[i]);
1702 }
1703