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