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