xref: /freebsd/sbin/ifconfig/ifconfig.c (revision aa0a1e58f0189b0fde359a8bda032887e72057fa)
1 /*
2  * Copyright (c) 1983, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #ifndef lint
31 static const char copyright[] =
32 "@(#) Copyright (c) 1983, 1993\n\
33 	The Regents of the University of California.  All rights reserved.\n";
34 #endif /* not lint */
35 
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)ifconfig.c	8.2 (Berkeley) 2/16/94";
39 #endif
40 static const char rcsid[] =
41   "$FreeBSD$";
42 #endif /* not lint */
43 
44 #include <sys/param.h>
45 #include <sys/ioctl.h>
46 #include <sys/socket.h>
47 #include <sys/time.h>
48 #include <sys/module.h>
49 #include <sys/linker.h>
50 
51 #include <net/ethernet.h>
52 #include <net/if.h>
53 #include <net/if_var.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 <ifaddrs.h>
65 #include <ctype.h>
66 #include <err.h>
67 #include <errno.h>
68 #include <fcntl.h>
69 #include <jail.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <unistd.h>
74 
75 #include "ifconfig.h"
76 
77 /*
78  * Since "struct ifreq" is composed of various union members, callers
79  * should pay special attention to interprete the value.
80  * (.e.g. little/big endian difference in the structure.)
81  */
82 struct	ifreq ifr;
83 
84 char	name[IFNAMSIZ];
85 char	*descr = NULL;
86 size_t	descrlen = 64;
87 int	setaddr;
88 int	setmask;
89 int	doalias;
90 int	clearaddr;
91 int	newaddr = 1;
92 int	verbose;
93 int	noload;
94 
95 int	supmedia = 0;
96 int	printkeys = 0;		/* Print keying material for interfaces. */
97 
98 static	int ifconfig(int argc, char *const *argv, int iscreate,
99 		const struct afswtch *afp);
100 static	void status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
101 		struct ifaddrs *ifa);
102 static	void tunnel_status(int s);
103 static	void usage(void);
104 
105 static struct afswtch *af_getbyname(const char *name);
106 static struct afswtch *af_getbyfamily(int af);
107 static void af_other_status(int);
108 
109 static struct option *opts = NULL;
110 
111 void
112 opt_register(struct option *p)
113 {
114 	p->next = opts;
115 	opts = p;
116 }
117 
118 static void
119 usage(void)
120 {
121 	char options[1024];
122 	struct option *p;
123 
124 	/* XXX not right but close enough for now */
125 	options[0] = '\0';
126 	for (p = opts; p != NULL; p = p->next) {
127 		strlcat(options, p->opt_usage, sizeof(options));
128 		strlcat(options, " ", sizeof(options));
129 	}
130 
131 	fprintf(stderr,
132 	"usage: ifconfig %sinterface address_family [address [dest_address]]\n"
133 	"                [parameters]\n"
134 	"       ifconfig interface create\n"
135 	"       ifconfig -a %s[-d] [-m] [-u] [-v] [address_family]\n"
136 	"       ifconfig -l [-d] [-u] [address_family]\n"
137 	"       ifconfig %s[-d] [-m] [-u] [-v]\n",
138 		options, options, options);
139 	exit(1);
140 }
141 
142 int
143 main(int argc, char *argv[])
144 {
145 	int c, all, namesonly, downonly, uponly;
146 	const struct afswtch *afp = NULL;
147 	int ifindex;
148 	struct ifaddrs *ifap, *ifa;
149 	struct ifreq paifr;
150 	const struct sockaddr_dl *sdl;
151 	char options[1024], *cp, *namecp = NULL;
152 	const char *ifname;
153 	struct option *p;
154 	size_t iflen;
155 
156 	all = downonly = uponly = namesonly = noload = verbose = 0;
157 
158 	/* Parse leading line options */
159 	strlcpy(options, "adklmnuv", sizeof(options));
160 	for (p = opts; p != NULL; p = p->next)
161 		strlcat(options, p->opt, sizeof(options));
162 	while ((c = getopt(argc, argv, options)) != -1) {
163 		switch (c) {
164 		case 'a':	/* scan all interfaces */
165 			all++;
166 			break;
167 		case 'd':	/* restrict scan to "down" interfaces */
168 			downonly++;
169 			break;
170 		case 'k':
171 			printkeys++;
172 			break;
173 		case 'l':	/* scan interface names only */
174 			namesonly++;
175 			break;
176 		case 'm':	/* show media choices in status */
177 			supmedia = 1;
178 			break;
179 		case 'n':	/* suppress module loading */
180 			noload++;
181 			break;
182 		case 'u':	/* restrict scan to "up" interfaces */
183 			uponly++;
184 			break;
185 		case 'v':
186 			verbose++;
187 			break;
188 		default:
189 			for (p = opts; p != NULL; p = p->next)
190 				if (p->opt[0] == c) {
191 					p->cb(optarg);
192 					break;
193 				}
194 			if (p == NULL)
195 				usage();
196 			break;
197 		}
198 	}
199 	argc -= optind;
200 	argv += optind;
201 
202 	/* -l cannot be used with -a or -m */
203 	if (namesonly && (all || supmedia))
204 		usage();
205 
206 	/* nonsense.. */
207 	if (uponly && downonly)
208 		usage();
209 
210 	/* no arguments is equivalent to '-a' */
211 	if (!namesonly && argc < 1)
212 		all = 1;
213 
214 	/* -a and -l allow an address family arg to limit the output */
215 	if (all || namesonly) {
216 		if (argc > 1)
217 			usage();
218 
219 		ifname = NULL;
220 		ifindex = 0;
221 		if (argc == 1) {
222 			afp = af_getbyname(*argv);
223 			if (afp == NULL)
224 				usage();
225 			if (afp->af_name != NULL)
226 				argc--, argv++;
227 			/* leave with afp non-zero */
228 		}
229 	} else {
230 		/* not listing, need an argument */
231 		if (argc < 1)
232 			usage();
233 
234 		ifname = *argv;
235 		argc--, argv++;
236 
237 		/* check and maybe load support for this interface */
238 		ifmaybeload(ifname);
239 
240 		ifindex = if_nametoindex(ifname);
241 		if (ifindex == 0) {
242 			/*
243 			 * NOTE:  We must special-case the `create' command
244 			 * right here as we would otherwise fail when trying
245 			 * to find the interface.
246 			 */
247 			if (argc > 0 && (strcmp(argv[0], "create") == 0 ||
248 			    strcmp(argv[0], "plumb") == 0)) {
249 				iflen = strlcpy(name, ifname, sizeof(name));
250 				if (iflen >= sizeof(name))
251 					errx(1, "%s: cloning name too long",
252 					    ifname);
253 				ifconfig(argc, argv, 1, NULL);
254 				exit(0);
255 			}
256 			/*
257 			 * NOTE:  We have to special-case the `-vnet' command
258 			 * right here as we would otherwise fail when trying
259 			 * to find the interface as it lives in another vnet.
260 			 */
261 			if (argc > 0 && (strcmp(argv[0], "-vnet") == 0)) {
262 				iflen = strlcpy(name, ifname, sizeof(name));
263 				if (iflen >= sizeof(name))
264 					errx(1, "%s: interface name too long",
265 					    ifname);
266 				ifconfig(argc, argv, 0, NULL);
267 				exit(0);
268 			}
269 			errx(1, "interface %s does not exist", ifname);
270 		}
271 	}
272 
273 	/* Check for address family */
274 	if (argc > 0) {
275 		afp = af_getbyname(*argv);
276 		if (afp != NULL)
277 			argc--, argv++;
278 	}
279 
280 	if (getifaddrs(&ifap) != 0)
281 		err(EXIT_FAILURE, "getifaddrs");
282 	cp = NULL;
283 	ifindex = 0;
284 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
285 		memset(&paifr, 0, sizeof(paifr));
286 		strncpy(paifr.ifr_name, ifa->ifa_name, sizeof(paifr.ifr_name));
287 		if (sizeof(paifr.ifr_addr) >= ifa->ifa_addr->sa_len) {
288 			memcpy(&paifr.ifr_addr, ifa->ifa_addr,
289 			    ifa->ifa_addr->sa_len);
290 		}
291 
292 		if (ifname != NULL && strcmp(ifname, ifa->ifa_name) != 0)
293 			continue;
294 		if (ifa->ifa_addr->sa_family == AF_LINK)
295 			sdl = (const struct sockaddr_dl *) ifa->ifa_addr;
296 		else
297 			sdl = NULL;
298 		if (cp != NULL && strcmp(cp, ifa->ifa_name) == 0 && !namesonly)
299 			continue;
300 		iflen = strlcpy(name, ifa->ifa_name, sizeof(name));
301 		if (iflen >= sizeof(name)) {
302 			warnx("%s: interface name too long, skipping",
303 			    ifa->ifa_name);
304 			continue;
305 		}
306 		cp = ifa->ifa_name;
307 
308 		if ((ifa->ifa_flags & IFF_CANTCONFIG) != 0)
309 			continue;
310 		if (downonly && (ifa->ifa_flags & IFF_UP) != 0)
311 			continue;
312 		if (uponly && (ifa->ifa_flags & IFF_UP) == 0)
313 			continue;
314 		/*
315 		 * Are we just listing the interfaces?
316 		 */
317 		if (namesonly) {
318 			if (namecp == cp)
319 				continue;
320 			if (afp != NULL) {
321 				/* special case for "ether" address family */
322 				if (!strcmp(afp->af_name, "ether")) {
323 					if (sdl == NULL ||
324 					    (sdl->sdl_type != IFT_ETHER &&
325 					    sdl->sdl_type != IFT_L2VLAN &&
326 					    sdl->sdl_type != IFT_BRIDGE) ||
327 					    sdl->sdl_alen != ETHER_ADDR_LEN)
328 						continue;
329 				} else {
330 					if (ifa->ifa_addr->sa_family != afp->af_af)
331 						continue;
332 				}
333 			}
334 			namecp = cp;
335 			ifindex++;
336 			if (ifindex > 1)
337 				printf(" ");
338 			fputs(name, stdout);
339 			continue;
340 		}
341 		ifindex++;
342 
343 		if (argc > 0)
344 			ifconfig(argc, argv, 0, afp);
345 		else
346 			status(afp, sdl, ifa);
347 	}
348 	if (namesonly)
349 		printf("\n");
350 	freeifaddrs(ifap);
351 
352 	exit(0);
353 }
354 
355 static struct afswtch *afs = NULL;
356 
357 void
358 af_register(struct afswtch *p)
359 {
360 	p->af_next = afs;
361 	afs = p;
362 }
363 
364 static struct afswtch *
365 af_getbyname(const char *name)
366 {
367 	struct afswtch *afp;
368 
369 	for (afp = afs; afp !=  NULL; afp = afp->af_next)
370 		if (strcmp(afp->af_name, name) == 0)
371 			return afp;
372 	return NULL;
373 }
374 
375 static struct afswtch *
376 af_getbyfamily(int af)
377 {
378 	struct afswtch *afp;
379 
380 	for (afp = afs; afp != NULL; afp = afp->af_next)
381 		if (afp->af_af == af)
382 			return afp;
383 	return NULL;
384 }
385 
386 static void
387 af_other_status(int s)
388 {
389 	struct afswtch *afp;
390 	uint8_t afmask[howmany(AF_MAX, NBBY)];
391 
392 	memset(afmask, 0, sizeof(afmask));
393 	for (afp = afs; afp != NULL; afp = afp->af_next) {
394 		if (afp->af_other_status == NULL)
395 			continue;
396 		if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
397 			continue;
398 		afp->af_other_status(s);
399 		setbit(afmask, afp->af_af);
400 	}
401 }
402 
403 static void
404 af_all_tunnel_status(int s)
405 {
406 	struct afswtch *afp;
407 	uint8_t afmask[howmany(AF_MAX, NBBY)];
408 
409 	memset(afmask, 0, sizeof(afmask));
410 	for (afp = afs; afp != NULL; afp = afp->af_next) {
411 		if (afp->af_status_tunnel == NULL)
412 			continue;
413 		if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
414 			continue;
415 		afp->af_status_tunnel(s);
416 		setbit(afmask, afp->af_af);
417 	}
418 }
419 
420 static struct cmd *cmds = NULL;
421 
422 void
423 cmd_register(struct cmd *p)
424 {
425 	p->c_next = cmds;
426 	cmds = p;
427 }
428 
429 static const struct cmd *
430 cmd_lookup(const char *name, int iscreate)
431 {
432 #define	N(a)	(sizeof(a)/sizeof(a[0]))
433 	const struct cmd *p;
434 
435 	for (p = cmds; p != NULL; p = p->c_next)
436 		if (strcmp(name, p->c_name) == 0) {
437 			if (iscreate) {
438 				if (p->c_iscloneop)
439 					return p;
440 			} else {
441 				if (!p->c_iscloneop)
442 					return p;
443 			}
444 		}
445 	return NULL;
446 #undef N
447 }
448 
449 struct callback {
450 	callback_func *cb_func;
451 	void	*cb_arg;
452 	struct callback *cb_next;
453 };
454 static struct callback *callbacks = NULL;
455 
456 void
457 callback_register(callback_func *func, void *arg)
458 {
459 	struct callback *cb;
460 
461 	cb = malloc(sizeof(struct callback));
462 	if (cb == NULL)
463 		errx(1, "unable to allocate memory for callback");
464 	cb->cb_func = func;
465 	cb->cb_arg = arg;
466 	cb->cb_next = callbacks;
467 	callbacks = cb;
468 }
469 
470 /* specially-handled commands */
471 static void setifaddr(const char *, int, int, const struct afswtch *);
472 static const struct cmd setifaddr_cmd = DEF_CMD("ifaddr", 0, setifaddr);
473 
474 static void setifdstaddr(const char *, int, int, const struct afswtch *);
475 static const struct cmd setifdstaddr_cmd =
476 	DEF_CMD("ifdstaddr", 0, setifdstaddr);
477 
478 static int
479 ifconfig(int argc, char *const *argv, int iscreate, const struct afswtch *uafp)
480 {
481 	const struct afswtch *afp, *nafp;
482 	const struct cmd *p;
483 	struct callback *cb;
484 	int s;
485 
486 	strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
487 	afp = uafp != NULL ? uafp : af_getbyname("inet");
488 top:
489 	ifr.ifr_addr.sa_family =
490 		afp->af_af == AF_LINK || afp->af_af == AF_UNSPEC ?
491 		AF_LOCAL : afp->af_af;
492 
493 	if ((s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0)) < 0 &&
494 	    (uafp != NULL || errno != EPROTONOSUPPORT ||
495 	     (s = socket(AF_LOCAL, SOCK_DGRAM, 0)) < 0))
496 		err(1, "socket(family %u,SOCK_DGRAM", ifr.ifr_addr.sa_family);
497 
498 	while (argc > 0) {
499 		p = cmd_lookup(*argv, iscreate);
500 		if (iscreate && p == NULL) {
501 			/*
502 			 * Push the clone create callback so the new
503 			 * device is created and can be used for any
504 			 * remaining arguments.
505 			 */
506 			cb = callbacks;
507 			if (cb == NULL)
508 				errx(1, "internal error, no callback");
509 			callbacks = cb->cb_next;
510 			cb->cb_func(s, cb->cb_arg);
511 			iscreate = 0;
512 			/*
513 			 * Handle any address family spec that
514 			 * immediately follows and potentially
515 			 * recreate the socket.
516 			 */
517 			nafp = af_getbyname(*argv);
518 			if (nafp != NULL) {
519 				argc--, argv++;
520 				if (nafp != afp) {
521 					close(s);
522 					afp = nafp;
523 					goto top;
524 				}
525 			}
526 			/*
527 			 * Look for a normal parameter.
528 			 */
529 			continue;
530 		}
531 		if (p == NULL) {
532 			/*
533 			 * Not a recognized command, choose between setting
534 			 * the interface address and the dst address.
535 			 */
536 			p = (setaddr ? &setifdstaddr_cmd : &setifaddr_cmd);
537 		}
538 		if (p->c_u.c_func || p->c_u.c_func2) {
539 			if (p->c_parameter == NEXTARG) {
540 				if (argv[1] == NULL)
541 					errx(1, "'%s' requires argument",
542 					    p->c_name);
543 				p->c_u.c_func(argv[1], 0, s, afp);
544 				argc--, argv++;
545 			} else if (p->c_parameter == OPTARG) {
546 				p->c_u.c_func(argv[1], 0, s, afp);
547 				if (argv[1] != NULL)
548 					argc--, argv++;
549 			} else if (p->c_parameter == NEXTARG2) {
550 				if (argc < 3)
551 					errx(1, "'%s' requires 2 arguments",
552 					    p->c_name);
553 				p->c_u.c_func2(argv[1], argv[2], s, afp);
554 				argc -= 2, argv += 2;
555 			} else
556 				p->c_u.c_func(*argv, p->c_parameter, s, afp);
557 		}
558 		argc--, argv++;
559 	}
560 
561 	/*
562 	 * Do any post argument processing required by the address family.
563 	 */
564 	if (afp->af_postproc != NULL)
565 		afp->af_postproc(s, afp);
566 	/*
567 	 * Do deferred callbacks registered while processing
568 	 * command-line arguments.
569 	 */
570 	for (cb = callbacks; cb != NULL; cb = cb->cb_next)
571 		cb->cb_func(s, cb->cb_arg);
572 	/*
573 	 * Do deferred operations.
574 	 */
575 	if (clearaddr) {
576 		if (afp->af_ridreq == NULL || afp->af_difaddr == 0) {
577 			warnx("interface %s cannot change %s addresses!",
578 			      name, afp->af_name);
579 			clearaddr = 0;
580 		}
581 	}
582 	if (clearaddr) {
583 		int ret;
584 		strncpy(afp->af_ridreq, name, sizeof ifr.ifr_name);
585 		ret = ioctl(s, afp->af_difaddr, afp->af_ridreq);
586 		if (ret < 0) {
587 			if (errno == EADDRNOTAVAIL && (doalias >= 0)) {
588 				/* means no previous address for interface */
589 			} else
590 				Perror("ioctl (SIOCDIFADDR)");
591 		}
592 	}
593 	if (newaddr) {
594 		if (afp->af_addreq == NULL || afp->af_aifaddr == 0) {
595 			warnx("interface %s cannot change %s addresses!",
596 			      name, afp->af_name);
597 			newaddr = 0;
598 		}
599 	}
600 	if (newaddr && (setaddr || setmask)) {
601 		strncpy(afp->af_addreq, name, sizeof ifr.ifr_name);
602 		if (ioctl(s, afp->af_aifaddr, afp->af_addreq) < 0)
603 			Perror("ioctl (SIOCAIFADDR)");
604 	}
605 
606 	close(s);
607 	return(0);
608 }
609 
610 /*ARGSUSED*/
611 static void
612 setifaddr(const char *addr, int param, int s, const struct afswtch *afp)
613 {
614 	if (afp->af_getaddr == NULL)
615 		return;
616 	/*
617 	 * Delay the ioctl to set the interface addr until flags are all set.
618 	 * The address interpretation may depend on the flags,
619 	 * and the flags may change when the address is set.
620 	 */
621 	setaddr++;
622 	if (doalias == 0 && afp->af_af != AF_LINK)
623 		clearaddr = 1;
624 	afp->af_getaddr(addr, (doalias >= 0 ? ADDR : RIDADDR));
625 }
626 
627 static void
628 settunnel(const char *src, const char *dst, int s, const struct afswtch *afp)
629 {
630 	struct addrinfo *srcres, *dstres;
631 	int ecode;
632 
633 	if (afp->af_settunnel == NULL) {
634 		warn("address family %s does not support tunnel setup",
635 			afp->af_name);
636 		return;
637 	}
638 
639 	if ((ecode = getaddrinfo(src, NULL, NULL, &srcres)) != 0)
640 		errx(1, "error in parsing address string: %s",
641 		    gai_strerror(ecode));
642 
643 	if ((ecode = getaddrinfo(dst, NULL, NULL, &dstres)) != 0)
644 		errx(1, "error in parsing address string: %s",
645 		    gai_strerror(ecode));
646 
647 	if (srcres->ai_addr->sa_family != dstres->ai_addr->sa_family)
648 		errx(1,
649 		    "source and destination address families do not match");
650 
651 	afp->af_settunnel(s, srcres, dstres);
652 
653 	freeaddrinfo(srcres);
654 	freeaddrinfo(dstres);
655 }
656 
657 /* ARGSUSED */
658 static void
659 deletetunnel(const char *vname, int param, int s, const struct afswtch *afp)
660 {
661 
662 	if (ioctl(s, SIOCDIFPHYADDR, &ifr) < 0)
663 		err(1, "SIOCDIFPHYADDR");
664 }
665 
666 static void
667 setifvnet(const char *jname, int dummy __unused, int s,
668     const struct afswtch *afp)
669 {
670 	struct ifreq my_ifr;
671 
672 	memcpy(&my_ifr, &ifr, sizeof(my_ifr));
673 	my_ifr.ifr_jid = jail_getid(jname);
674 	if (my_ifr.ifr_jid < 0)
675 		errx(1, "%s", jail_errmsg);
676 	if (ioctl(s, SIOCSIFVNET, &my_ifr) < 0)
677 		err(1, "SIOCSIFVNET");
678 }
679 
680 static void
681 setifrvnet(const char *jname, int dummy __unused, int s,
682     const struct afswtch *afp)
683 {
684 	struct ifreq my_ifr;
685 
686 	memcpy(&my_ifr, &ifr, sizeof(my_ifr));
687 	my_ifr.ifr_jid = jail_getid(jname);
688 	if (my_ifr.ifr_jid < 0)
689 		errx(1, "%s", jail_errmsg);
690 	if (ioctl(s, SIOCSIFRVNET, &my_ifr) < 0)
691 		err(1, "SIOCSIFRVNET(%d, %s)", my_ifr.ifr_jid, my_ifr.ifr_name);
692 }
693 
694 static void
695 setifnetmask(const char *addr, int dummy __unused, int s,
696     const struct afswtch *afp)
697 {
698 	if (afp->af_getaddr != NULL) {
699 		setmask++;
700 		afp->af_getaddr(addr, MASK);
701 	}
702 }
703 
704 static void
705 setifbroadaddr(const char *addr, int dummy __unused, int s,
706     const struct afswtch *afp)
707 {
708 	if (afp->af_getaddr != NULL)
709 		afp->af_getaddr(addr, DSTADDR);
710 }
711 
712 static void
713 setifipdst(const char *addr, int dummy __unused, int s,
714     const struct afswtch *afp)
715 {
716 	const struct afswtch *inet;
717 
718 	inet = af_getbyname("inet");
719 	if (inet == NULL)
720 		return;
721 	inet->af_getaddr(addr, DSTADDR);
722 	clearaddr = 0;
723 	newaddr = 0;
724 }
725 
726 static void
727 notealias(const char *addr, int param, int s, const struct afswtch *afp)
728 {
729 #define rqtosa(x) (&(((struct ifreq *)(afp->x))->ifr_addr))
730 	if (setaddr && doalias == 0 && param < 0)
731 		if (afp->af_addreq != NULL && afp->af_ridreq != NULL)
732 			bcopy((caddr_t)rqtosa(af_addreq),
733 			      (caddr_t)rqtosa(af_ridreq),
734 			      rqtosa(af_addreq)->sa_len);
735 	doalias = param;
736 	if (param < 0) {
737 		clearaddr = 1;
738 		newaddr = 0;
739 	} else
740 		clearaddr = 0;
741 #undef rqtosa
742 }
743 
744 /*ARGSUSED*/
745 static void
746 setifdstaddr(const char *addr, int param __unused, int s,
747     const struct afswtch *afp)
748 {
749 	if (afp->af_getaddr != NULL)
750 		afp->af_getaddr(addr, DSTADDR);
751 }
752 
753 /*
754  * Note: doing an SIOCIGIFFLAGS scribbles on the union portion
755  * of the ifreq structure, which may confuse other parts of ifconfig.
756  * Make a private copy so we can avoid that.
757  */
758 static void
759 setifflags(const char *vname, int value, int s, const struct afswtch *afp)
760 {
761 	struct ifreq		my_ifr;
762 	int flags;
763 
764 	memset(&my_ifr, 0, sizeof(my_ifr));
765 	(void) strlcpy(my_ifr.ifr_name, name, sizeof(my_ifr.ifr_name));
766 
767  	if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&my_ifr) < 0) {
768  		Perror("ioctl (SIOCGIFFLAGS)");
769  		exit(1);
770  	}
771 	flags = (my_ifr.ifr_flags & 0xffff) | (my_ifr.ifr_flagshigh << 16);
772 
773 	if (value < 0) {
774 		value = -value;
775 		flags &= ~value;
776 	} else
777 		flags |= value;
778 	my_ifr.ifr_flags = flags & 0xffff;
779 	my_ifr.ifr_flagshigh = flags >> 16;
780 	if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&my_ifr) < 0)
781 		Perror(vname);
782 }
783 
784 void
785 setifcap(const char *vname, int value, int s, const struct afswtch *afp)
786 {
787 	int flags;
788 
789  	if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) < 0) {
790  		Perror("ioctl (SIOCGIFCAP)");
791  		exit(1);
792  	}
793 	flags = ifr.ifr_curcap;
794 	if (value < 0) {
795 		value = -value;
796 		flags &= ~value;
797 	} else
798 		flags |= value;
799 	flags &= ifr.ifr_reqcap;
800 	ifr.ifr_reqcap = flags;
801 	if (ioctl(s, SIOCSIFCAP, (caddr_t)&ifr) < 0)
802 		Perror(vname);
803 }
804 
805 static void
806 setifmetric(const char *val, int dummy __unused, int s,
807     const struct afswtch *afp)
808 {
809 	strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
810 	ifr.ifr_metric = atoi(val);
811 	if (ioctl(s, SIOCSIFMETRIC, (caddr_t)&ifr) < 0)
812 		warn("ioctl (set metric)");
813 }
814 
815 static void
816 setifmtu(const char *val, int dummy __unused, int s,
817     const struct afswtch *afp)
818 {
819 	strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
820 	ifr.ifr_mtu = atoi(val);
821 	if (ioctl(s, SIOCSIFMTU, (caddr_t)&ifr) < 0)
822 		warn("ioctl (set mtu)");
823 }
824 
825 static void
826 setifname(const char *val, int dummy __unused, int s,
827     const struct afswtch *afp)
828 {
829 	char *newname;
830 
831 	newname = strdup(val);
832 	if (newname == NULL) {
833 		warn("no memory to set ifname");
834 		return;
835 	}
836 	ifr.ifr_data = newname;
837 	if (ioctl(s, SIOCSIFNAME, (caddr_t)&ifr) < 0) {
838 		warn("ioctl (set name)");
839 		free(newname);
840 		return;
841 	}
842 	strlcpy(name, newname, sizeof(name));
843 	free(newname);
844 }
845 
846 /* ARGSUSED */
847 static void
848 setifdescr(const char *val, int dummy __unused, int s,
849     const struct afswtch *afp)
850 {
851 	char *newdescr;
852 
853 	ifr.ifr_buffer.length = strlen(val) + 1;
854 	if (ifr.ifr_buffer.length == 1) {
855 		ifr.ifr_buffer.buffer = newdescr = NULL;
856 		ifr.ifr_buffer.length = 0;
857 	} else {
858 		newdescr = strdup(val);
859 		ifr.ifr_buffer.buffer = newdescr;
860 		if (newdescr == NULL) {
861 			warn("no memory to set ifdescr");
862 			return;
863 		}
864 	}
865 
866 	if (ioctl(s, SIOCSIFDESCR, (caddr_t)&ifr) < 0)
867 		warn("ioctl (set descr)");
868 
869 	free(newdescr);
870 }
871 
872 /* ARGSUSED */
873 static void
874 unsetifdescr(const char *val, int value, int s, const struct afswtch *afp)
875 {
876 
877 	setifdescr("", 0, s, 0);
878 }
879 
880 #define	IFFBITS \
881 "\020\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5POINTOPOINT\6SMART\7RUNNING" \
882 "\10NOARP\11PROMISC\12ALLMULTI\13OACTIVE\14SIMPLEX\15LINK0\16LINK1\17LINK2" \
883 "\20MULTICAST\22PPROMISC\23MONITOR\24STATICARP"
884 
885 #define	IFCAPBITS \
886 "\020\1RXCSUM\2TXCSUM\3NETCONS\4VLAN_MTU\5VLAN_HWTAGGING\6JUMBO_MTU\7POLLING" \
887 "\10VLAN_HWCSUM\11TSO4\12TSO6\13LRO\14WOL_UCAST\15WOL_MCAST\16WOL_MAGIC" \
888 "\21VLAN_HWFILTER\23VLAN_HWTSO\24LINKSTATE"
889 
890 /*
891  * Print the status of the interface.  If an address family was
892  * specified, show only it; otherwise, show them all.
893  */
894 static void
895 status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
896 	struct ifaddrs *ifa)
897 {
898 	struct ifaddrs *ift;
899 	int allfamilies, s;
900 	struct ifstat ifs;
901 
902 	if (afp == NULL) {
903 		allfamilies = 1;
904 		ifr.ifr_addr.sa_family = AF_LOCAL;
905 	} else {
906 		allfamilies = 0;
907 		ifr.ifr_addr.sa_family =
908 		    afp->af_af == AF_LINK ? AF_LOCAL : afp->af_af;
909 	}
910 	strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
911 
912 	s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0);
913 	if (s < 0)
914 		err(1, "socket(family %u,SOCK_DGRAM)", ifr.ifr_addr.sa_family);
915 
916 	printf("%s: ", name);
917 	printb("flags", ifa->ifa_flags, IFFBITS);
918 	if (ioctl(s, SIOCGIFMETRIC, &ifr) != -1)
919 		printf(" metric %d", ifr.ifr_metric);
920 	if (ioctl(s, SIOCGIFMTU, &ifr) != -1)
921 		printf(" mtu %d", ifr.ifr_mtu);
922 	putchar('\n');
923 
924 	for (;;) {
925 		if ((descr = reallocf(descr, descrlen)) != NULL) {
926 			ifr.ifr_buffer.buffer = descr;
927 			ifr.ifr_buffer.length = descrlen;
928 			if (ioctl(s, SIOCGIFDESCR, &ifr) == 0) {
929 				if (ifr.ifr_buffer.buffer == descr) {
930 					if (strlen(descr) > 0)
931 						printf("\tdescription: %s\n",
932 						    descr);
933 				} else if (ifr.ifr_buffer.length > descrlen) {
934 					descrlen = ifr.ifr_buffer.length;
935 					continue;
936 				}
937 			}
938 		} else
939 			warn("unable to allocate memory for interface"
940 			    "description");
941 		break;
942 	}
943 
944 	if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) == 0) {
945 		if (ifr.ifr_curcap != 0) {
946 			printb("\toptions", ifr.ifr_curcap, IFCAPBITS);
947 			putchar('\n');
948 		}
949 		if (supmedia && ifr.ifr_reqcap != 0) {
950 			printb("\tcapabilities", ifr.ifr_reqcap, IFCAPBITS);
951 			putchar('\n');
952 		}
953 	}
954 
955 	tunnel_status(s);
956 
957 	for (ift = ifa; ift != NULL; ift = ift->ifa_next) {
958 		if (ift->ifa_addr == NULL)
959 			continue;
960 		if (strcmp(ifa->ifa_name, ift->ifa_name) != 0)
961 			continue;
962 		if (allfamilies) {
963 			const struct afswtch *p;
964 			p = af_getbyfamily(ift->ifa_addr->sa_family);
965 			if (p != NULL && p->af_status != NULL)
966 				p->af_status(s, ift);
967 		} else if (afp->af_af == ift->ifa_addr->sa_family)
968 			afp->af_status(s, ift);
969 	}
970 #if 0
971 	if (allfamilies || afp->af_af == AF_LINK) {
972 		const struct afswtch *lafp;
973 
974 		/*
975 		 * Hack; the link level address is received separately
976 		 * from the routing information so any address is not
977 		 * handled above.  Cobble together an entry and invoke
978 		 * the status method specially.
979 		 */
980 		lafp = af_getbyname("lladdr");
981 		if (lafp != NULL) {
982 			info.rti_info[RTAX_IFA] = (struct sockaddr *)sdl;
983 			lafp->af_status(s, &info);
984 		}
985 	}
986 #endif
987 	if (allfamilies)
988 		af_other_status(s);
989 	else if (afp->af_other_status != NULL)
990 		afp->af_other_status(s);
991 
992 	strncpy(ifs.ifs_name, name, sizeof ifs.ifs_name);
993 	if (ioctl(s, SIOCGIFSTATUS, &ifs) == 0)
994 		printf("%s", ifs.ascii);
995 
996 	close(s);
997 	return;
998 }
999 
1000 static void
1001 tunnel_status(int s)
1002 {
1003 	af_all_tunnel_status(s);
1004 }
1005 
1006 void
1007 Perror(const char *cmd)
1008 {
1009 	switch (errno) {
1010 
1011 	case ENXIO:
1012 		errx(1, "%s: no such interface", cmd);
1013 		break;
1014 
1015 	case EPERM:
1016 		errx(1, "%s: permission denied", cmd);
1017 		break;
1018 
1019 	default:
1020 		err(1, "%s", cmd);
1021 	}
1022 }
1023 
1024 /*
1025  * Print a value a la the %b format of the kernel's printf
1026  */
1027 void
1028 printb(const char *s, unsigned v, const char *bits)
1029 {
1030 	int i, any = 0;
1031 	char c;
1032 
1033 	if (bits && *bits == 8)
1034 		printf("%s=%o", s, v);
1035 	else
1036 		printf("%s=%x", s, v);
1037 	bits++;
1038 	if (bits) {
1039 		putchar('<');
1040 		while ((i = *bits++) != '\0') {
1041 			if (v & (1 << (i-1))) {
1042 				if (any)
1043 					putchar(',');
1044 				any = 1;
1045 				for (; (c = *bits) > 32; bits++)
1046 					putchar(c);
1047 			} else
1048 				for (; *bits > 32; bits++)
1049 					;
1050 		}
1051 		putchar('>');
1052 	}
1053 }
1054 
1055 void
1056 ifmaybeload(const char *name)
1057 {
1058 #define MOD_PREFIX_LEN		3	/* "if_" */
1059 	struct module_stat mstat;
1060 	int fileid, modid;
1061 	char ifkind[IFNAMSIZ + MOD_PREFIX_LEN], ifname[IFNAMSIZ], *dp;
1062 	const char *cp;
1063 
1064 	/* loading suppressed by the user */
1065 	if (noload)
1066 		return;
1067 
1068 	/* trim the interface number off the end */
1069 	strlcpy(ifname, name, sizeof(ifname));
1070 	for (dp = ifname; *dp != 0; dp++)
1071 		if (isdigit(*dp)) {
1072 			*dp = 0;
1073 			break;
1074 		}
1075 
1076 	/* turn interface and unit into module name */
1077 	strcpy(ifkind, "if_");
1078 	strlcpy(ifkind + MOD_PREFIX_LEN, ifname,
1079 	    sizeof(ifkind) - MOD_PREFIX_LEN);
1080 
1081 	/* scan files in kernel */
1082 	mstat.version = sizeof(struct module_stat);
1083 	for (fileid = kldnext(0); fileid > 0; fileid = kldnext(fileid)) {
1084 		/* scan modules in file */
1085 		for (modid = kldfirstmod(fileid); modid > 0;
1086 		     modid = modfnext(modid)) {
1087 			if (modstat(modid, &mstat) < 0)
1088 				continue;
1089 			/* strip bus name if present */
1090 			if ((cp = strchr(mstat.name, '/')) != NULL) {
1091 				cp++;
1092 			} else {
1093 				cp = mstat.name;
1094 			}
1095 			/* already loaded? */
1096 			if (strncmp(ifname, cp, strlen(ifname) + 1) == 0 ||
1097 			    strncmp(ifkind, cp, strlen(ifkind) + 1) == 0)
1098 				return;
1099 		}
1100 	}
1101 
1102 	/* not present, we should try to load it */
1103 	kldload(ifkind);
1104 }
1105 
1106 static struct cmd basic_cmds[] = {
1107 	DEF_CMD("up",		IFF_UP,		setifflags),
1108 	DEF_CMD("down",		-IFF_UP,	setifflags),
1109 	DEF_CMD("arp",		-IFF_NOARP,	setifflags),
1110 	DEF_CMD("-arp",		IFF_NOARP,	setifflags),
1111 	DEF_CMD("debug",	IFF_DEBUG,	setifflags),
1112 	DEF_CMD("-debug",	-IFF_DEBUG,	setifflags),
1113 	DEF_CMD_ARG("description",		setifdescr),
1114 	DEF_CMD_ARG("descr",			setifdescr),
1115 	DEF_CMD("-description",	0,		unsetifdescr),
1116 	DEF_CMD("-descr",	0,		unsetifdescr),
1117 	DEF_CMD("promisc",	IFF_PPROMISC,	setifflags),
1118 	DEF_CMD("-promisc",	-IFF_PPROMISC,	setifflags),
1119 	DEF_CMD("add",		IFF_UP,		notealias),
1120 	DEF_CMD("alias",	IFF_UP,		notealias),
1121 	DEF_CMD("-alias",	-IFF_UP,	notealias),
1122 	DEF_CMD("delete",	-IFF_UP,	notealias),
1123 	DEF_CMD("remove",	-IFF_UP,	notealias),
1124 #ifdef notdef
1125 #define	EN_SWABIPS	0x1000
1126 	DEF_CMD("swabips",	EN_SWABIPS,	setifflags),
1127 	DEF_CMD("-swabips",	-EN_SWABIPS,	setifflags),
1128 #endif
1129 	DEF_CMD_ARG("netmask",			setifnetmask),
1130 	DEF_CMD_ARG("metric",			setifmetric),
1131 	DEF_CMD_ARG("broadcast",		setifbroadaddr),
1132 	DEF_CMD_ARG("ipdst",			setifipdst),
1133 	DEF_CMD_ARG2("tunnel",			settunnel),
1134 	DEF_CMD("-tunnel", 0,			deletetunnel),
1135 	DEF_CMD("deletetunnel", 0,		deletetunnel),
1136 	DEF_CMD_ARG("vnet",			setifvnet),
1137 	DEF_CMD_ARG("-vnet",			setifrvnet),
1138 	DEF_CMD("link0",	IFF_LINK0,	setifflags),
1139 	DEF_CMD("-link0",	-IFF_LINK0,	setifflags),
1140 	DEF_CMD("link1",	IFF_LINK1,	setifflags),
1141 	DEF_CMD("-link1",	-IFF_LINK1,	setifflags),
1142 	DEF_CMD("link2",	IFF_LINK2,	setifflags),
1143 	DEF_CMD("-link2",	-IFF_LINK2,	setifflags),
1144 	DEF_CMD("monitor",	IFF_MONITOR,	setifflags),
1145 	DEF_CMD("-monitor",	-IFF_MONITOR,	setifflags),
1146 	DEF_CMD("staticarp",	IFF_STATICARP,	setifflags),
1147 	DEF_CMD("-staticarp",	-IFF_STATICARP,	setifflags),
1148 	DEF_CMD("rxcsum",	IFCAP_RXCSUM,	setifcap),
1149 	DEF_CMD("-rxcsum",	-IFCAP_RXCSUM,	setifcap),
1150 	DEF_CMD("txcsum",	IFCAP_TXCSUM,	setifcap),
1151 	DEF_CMD("-txcsum",	-IFCAP_TXCSUM,	setifcap),
1152 	DEF_CMD("netcons",	IFCAP_NETCONS,	setifcap),
1153 	DEF_CMD("-netcons",	-IFCAP_NETCONS,	setifcap),
1154 	DEF_CMD("polling",	IFCAP_POLLING,	setifcap),
1155 	DEF_CMD("-polling",	-IFCAP_POLLING,	setifcap),
1156 	DEF_CMD("tso",		IFCAP_TSO,	setifcap),
1157 	DEF_CMD("-tso",		-IFCAP_TSO,	setifcap),
1158 	DEF_CMD("lro",		IFCAP_LRO,	setifcap),
1159 	DEF_CMD("-lro",		-IFCAP_LRO,	setifcap),
1160 	DEF_CMD("wol",		IFCAP_WOL,	setifcap),
1161 	DEF_CMD("-wol",		-IFCAP_WOL,	setifcap),
1162 	DEF_CMD("wol_ucast",	IFCAP_WOL_UCAST,	setifcap),
1163 	DEF_CMD("-wol_ucast",	-IFCAP_WOL_UCAST,	setifcap),
1164 	DEF_CMD("wol_mcast",	IFCAP_WOL_MCAST,	setifcap),
1165 	DEF_CMD("-wol_mcast",	-IFCAP_WOL_MCAST,	setifcap),
1166 	DEF_CMD("wol_magic",	IFCAP_WOL_MAGIC,	setifcap),
1167 	DEF_CMD("-wol_magic",	-IFCAP_WOL_MAGIC,	setifcap),
1168 	DEF_CMD("normal",	-IFF_LINK0,	setifflags),
1169 	DEF_CMD("compress",	IFF_LINK0,	setifflags),
1170 	DEF_CMD("noicmp",	IFF_LINK1,	setifflags),
1171 	DEF_CMD_ARG("mtu",			setifmtu),
1172 	DEF_CMD_ARG("name",			setifname),
1173 };
1174 
1175 static __constructor void
1176 ifconfig_ctor(void)
1177 {
1178 #define	N(a)	(sizeof(a) / sizeof(a[0]))
1179 	size_t i;
1180 
1181 	for (i = 0; i < N(basic_cmds);  i++)
1182 		cmd_register(&basic_cmds[i]);
1183 #undef N
1184 }
1185