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