xref: /freebsd/sbin/ifconfig/ifconfig.c (revision f0a75d274af375d15b97b830966b99a02b7db911)
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/sysctl.h>
48 #include <sys/time.h>
49 #include <sys/module.h>
50 #include <sys/linker.h>
51 
52 #include <net/ethernet.h>
53 #include <net/if.h>
54 #include <net/if_var.h>
55 #include <net/if_dl.h>
56 #include <net/if_types.h>
57 #include <net/route.h>
58 
59 /* IP */
60 #include <netinet/in.h>
61 #include <netinet/in_var.h>
62 #include <arpa/inet.h>
63 #include <netdb.h>
64 
65 #include <ifaddrs.h>
66 #include <ctype.h>
67 #include <err.h>
68 #include <errno.h>
69 #include <fcntl.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 int	setaddr;
86 int	setipdst;
87 int	setmask;
88 int	doalias;
89 int	clearaddr;
90 int	newaddr = 1;
91 int	verbose;
92 
93 int	supmedia = 0;
94 int	printkeys = 0;		/* Print keying material for interfaces. */
95 
96 static	int ifconfig(int argc, char *const *argv, const struct afswtch *afp);
97 static	void status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
98 		struct ifaddrs *ifa);
99 static	void tunnel_status(int s);
100 static	void usage(void);
101 
102 static struct afswtch *af_getbyname(const char *name);
103 static struct afswtch *af_getbyfamily(int af);
104 static void af_other_status(int);
105 
106 static struct option *opts = NULL;
107 
108 void
109 opt_register(struct option *p)
110 {
111 	p->next = opts;
112 	opts = p;
113 }
114 
115 static void
116 usage(void)
117 {
118 	char options[1024];
119 	struct option *p;
120 
121 	/* XXX not right but close enough for now */
122 	options[0] = '\0';
123 	for (p = opts; p != NULL; p = p->next) {
124 		strlcat(options, p->opt_usage, sizeof(options));
125 		strlcat(options, " ", sizeof(options));
126 	}
127 
128 	fprintf(stderr,
129 	"usage: ifconfig %sinterface address_family [address [dest_address]]\n"
130 	"                [parameters]\n"
131 	"       ifconfig interface create\n"
132 	"       ifconfig -a %s[-d] [-m] [-u] [-v] [address_family]\n"
133 	"       ifconfig -l [-d] [-u] [address_family]\n"
134 	"       ifconfig %s[-d] [-m] [-u] [-v]\n",
135 		options, options, options);
136 	exit(1);
137 }
138 
139 int
140 main(int argc, char *argv[])
141 {
142 	int c, all, namesonly, downonly, uponly;
143 	const struct afswtch *afp = NULL;
144 	int ifindex;
145 	struct ifaddrs *ifap, *ifa;
146 	struct ifreq paifr;
147 	const struct sockaddr_dl *sdl;
148 	char options[1024], *cp;
149 	const char *ifname;
150 	struct option *p;
151 	size_t iflen;
152 
153 	all = downonly = uponly = namesonly = verbose = 0;
154 
155 	/* Parse leading line options */
156 	strlcpy(options, "adklmuv", sizeof(options));
157 	for (p = opts; p != NULL; p = p->next)
158 		strlcat(options, p->opt, sizeof(options));
159 	while ((c = getopt(argc, argv, options)) != -1) {
160 		switch (c) {
161 		case 'a':	/* scan all interfaces */
162 			all++;
163 			break;
164 		case 'd':	/* restrict scan to "down" interfaces */
165 			downonly++;
166 			break;
167 		case 'k':
168 			printkeys++;
169 			break;
170 		case 'l':	/* scan interface names only */
171 			namesonly++;
172 			break;
173 		case 'm':	/* show media choices in status */
174 			supmedia = 1;
175 			break;
176 		case 'u':	/* restrict scan to "up" interfaces */
177 			uponly++;
178 			break;
179 		case 'v':
180 			verbose++;
181 			break;
182 		default:
183 			for (p = opts; p != NULL; p = p->next)
184 				if (p->opt[0] == c) {
185 					p->cb(optarg);
186 					break;
187 				}
188 			if (p == NULL)
189 				usage();
190 			break;
191 		}
192 	}
193 	argc -= optind;
194 	argv += optind;
195 
196 	/* -l cannot be used with -a or -m */
197 	if (namesonly && (all || supmedia))
198 		usage();
199 
200 	/* nonsense.. */
201 	if (uponly && downonly)
202 		usage();
203 
204 	/* no arguments is equivalent to '-a' */
205 	if (!namesonly && argc < 1)
206 		all = 1;
207 
208 	/* -a and -l allow an address family arg to limit the output */
209 	if (all || namesonly) {
210 		if (argc > 1)
211 			usage();
212 
213 		ifname = NULL;
214 		ifindex = 0;
215 		if (argc == 1) {
216 			afp = af_getbyname(*argv);
217 			if (afp == NULL)
218 				usage();
219 			if (afp->af_name != NULL)
220 				argc--, argv++;
221 			/* leave with afp non-zero */
222 		}
223 	} else {
224 		/* not listing, need an argument */
225 		if (argc < 1)
226 			usage();
227 
228 		ifname = *argv;
229 		argc--, argv++;
230 
231 		/* check and maybe load support for this interface */
232 		ifmaybeload(ifname);
233 
234 		ifindex = if_nametoindex(ifname);
235 		if (ifindex == 0) {
236 			/*
237 			 * NOTE:  We must special-case the `create' command
238 			 * right here as we would otherwise fail when trying
239 			 * to find the interface.
240 			 */
241 			if (argc > 0 && (strcmp(argv[0], "create") == 0 ||
242 			    strcmp(argv[0], "plumb") == 0)) {
243 				iflen = strlcpy(name, ifname, sizeof(name));
244 				if (iflen >= sizeof(name))
245 					errx(1, "%s: cloning name too long",
246 					    ifname);
247 				ifconfig(argc, argv, NULL);
248 				exit(0);
249 			}
250 			errx(1, "interface %s does not exist", ifname);
251 		}
252 	}
253 
254 	/* Check for address family */
255 	if (argc > 0) {
256 		afp = af_getbyname(*argv);
257 		if (afp != NULL)
258 			argc--, argv++;
259 	}
260 
261 	if (getifaddrs(&ifap) != 0)
262 		err(EXIT_FAILURE, "getifaddrs");
263 	cp = NULL;
264 	ifindex = 0;
265 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
266 		memset(&paifr, 0, sizeof(paifr));
267 		strncpy(paifr.ifr_name, ifa->ifa_name, sizeof(paifr.ifr_name));
268 		if (sizeof(paifr.ifr_addr) >= ifa->ifa_addr->sa_len) {
269 			memcpy(&paifr.ifr_addr, ifa->ifa_addr,
270 			    ifa->ifa_addr->sa_len);
271 		}
272 
273 		if (ifname != NULL && strcmp(ifname, ifa->ifa_name) != 0)
274 			continue;
275 		if (ifa->ifa_addr->sa_family == AF_LINK)
276 			sdl = (const struct sockaddr_dl *) ifa->ifa_addr;
277 		else
278 			sdl = NULL;
279 		if (cp != NULL && strcmp(cp, ifa->ifa_name) == 0)
280 			continue;
281 		iflen = strlcpy(name, ifa->ifa_name, sizeof(name));
282 		if (iflen >= sizeof(name)) {
283 			warnx("%s: interface name too long, skipping",
284 			    ifa->ifa_name);
285 			continue;
286 		}
287 		cp = ifa->ifa_name;
288 
289 		if (downonly && (ifa->ifa_flags & IFF_UP) != 0)
290 			continue;
291 		if (uponly && (ifa->ifa_flags & IFF_UP) == 0)
292 			continue;
293 		ifindex++;
294 		/*
295 		 * Are we just listing the interfaces?
296 		 */
297 		if (namesonly) {
298 			if (ifindex > 1)
299 				printf(" ");
300 			fputs(name, stdout);
301 			continue;
302 		}
303 
304 		if (argc > 0)
305 			ifconfig(argc, argv, afp);
306 		else
307 			status(afp, sdl, ifa);
308 	}
309 	if (namesonly)
310 		printf("\n");
311 	freeifaddrs(ifap);
312 
313 	exit(0);
314 }
315 
316 static struct afswtch *afs = NULL;
317 
318 void
319 af_register(struct afswtch *p)
320 {
321 	p->af_next = afs;
322 	afs = p;
323 }
324 
325 static struct afswtch *
326 af_getbyname(const char *name)
327 {
328 	struct afswtch *afp;
329 
330 	for (afp = afs; afp !=  NULL; afp = afp->af_next)
331 		if (strcmp(afp->af_name, name) == 0)
332 			return afp;
333 	return NULL;
334 }
335 
336 static struct afswtch *
337 af_getbyfamily(int af)
338 {
339 	struct afswtch *afp;
340 
341 	for (afp = afs; afp != NULL; afp = afp->af_next)
342 		if (afp->af_af == af)
343 			return afp;
344 	return NULL;
345 }
346 
347 static void
348 af_other_status(int s)
349 {
350 	struct afswtch *afp;
351 	uint8_t afmask[howmany(AF_MAX, NBBY)];
352 
353 	memset(afmask, 0, sizeof(afmask));
354 	for (afp = afs; afp != NULL; afp = afp->af_next) {
355 		if (afp->af_other_status == NULL)
356 			continue;
357 		if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
358 			continue;
359 		afp->af_other_status(s);
360 		setbit(afmask, afp->af_af);
361 	}
362 }
363 
364 static void
365 af_all_tunnel_status(int s)
366 {
367 	struct afswtch *afp;
368 	uint8_t afmask[howmany(AF_MAX, NBBY)];
369 
370 	memset(afmask, 0, sizeof(afmask));
371 	for (afp = afs; afp != NULL; afp = afp->af_next) {
372 		if (afp->af_status_tunnel == NULL)
373 			continue;
374 		if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
375 			continue;
376 		afp->af_status_tunnel(s);
377 		setbit(afmask, afp->af_af);
378 	}
379 }
380 
381 static struct cmd *cmds = NULL;
382 
383 void
384 cmd_register(struct cmd *p)
385 {
386 	p->c_next = cmds;
387 	cmds = p;
388 }
389 
390 static const struct cmd *
391 cmd_lookup(const char *name)
392 {
393 #define	N(a)	(sizeof(a)/sizeof(a[0]))
394 	const struct cmd *p;
395 
396 	for (p = cmds; p != NULL; p = p->c_next)
397 		if (strcmp(name, p->c_name) == 0)
398 			return p;
399 	return NULL;
400 #undef N
401 }
402 
403 struct callback {
404 	callback_func *cb_func;
405 	void	*cb_arg;
406 	struct callback *cb_next;
407 };
408 static struct callback *callbacks = NULL;
409 
410 void
411 callback_register(callback_func *func, void *arg)
412 {
413 	struct callback *cb;
414 
415 	cb = malloc(sizeof(struct callback));
416 	if (cb == NULL)
417 		errx(1, "unable to allocate memory for callback");
418 	cb->cb_func = func;
419 	cb->cb_arg = arg;
420 	cb->cb_next = callbacks;
421 	callbacks = cb;
422 }
423 
424 /* specially-handled commands */
425 static void setifaddr(const char *, int, int, const struct afswtch *);
426 static const struct cmd setifaddr_cmd = DEF_CMD("ifaddr", 0, setifaddr);
427 
428 static void setifdstaddr(const char *, int, int, const struct afswtch *);
429 static const struct cmd setifdstaddr_cmd =
430 	DEF_CMD("ifdstaddr", 0, setifdstaddr);
431 
432 static int
433 ifconfig(int argc, char *const *argv, const struct afswtch *afp)
434 {
435 	struct callback *cb;
436 	int s;
437 
438 	if (afp == NULL)
439 		afp = af_getbyname("inet");
440 	ifr.ifr_addr.sa_family =
441 		afp->af_af == AF_LINK || afp->af_af == AF_UNSPEC ?
442 		AF_INET : afp->af_af;
443 	strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
444 
445 	if ((s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0)) < 0)
446 		err(1, "socket(family %u,SOCK_DGRAM", ifr.ifr_addr.sa_family);
447 
448 	while (argc > 0) {
449 		const struct cmd *p;
450 
451 		p = cmd_lookup(*argv);
452 		if (p == NULL) {
453 			/*
454 			 * Not a recognized command, choose between setting
455 			 * the interface address and the dst address.
456 			 */
457 			p = (setaddr ? &setifdstaddr_cmd : &setifaddr_cmd);
458 		}
459 		if (p->c_u.c_func || p->c_u.c_func2) {
460 			if (p->c_parameter == NEXTARG) {
461 				if (argv[1] == NULL)
462 					errx(1, "'%s' requires argument",
463 					    p->c_name);
464 				p->c_u.c_func(argv[1], 0, s, afp);
465 				argc--, argv++;
466 			} else if (p->c_parameter == OPTARG) {
467 				p->c_u.c_func(argv[1], 0, s, afp);
468 				if (argv[1] != NULL)
469 					argc--, argv++;
470 			} else if (p->c_parameter == NEXTARG2) {
471 				if (argc < 3)
472 					errx(1, "'%s' requires 2 arguments",
473 					    p->c_name);
474 				p->c_u.c_func2(argv[1], argv[2], s, afp);
475 				argc -= 2, argv += 2;
476 			} else
477 				p->c_u.c_func(*argv, p->c_parameter, s, afp);
478 		}
479 		argc--, argv++;
480 	}
481 
482 	/*
483 	 * Do any post argument processing required by the address family.
484 	 */
485 	if (afp->af_postproc != NULL)
486 		afp->af_postproc(s, afp);
487 	/*
488 	 * Do deferred callbacks registered while processing
489 	 * command-line arguments.
490 	 */
491 	for (cb = callbacks; cb != NULL; cb = cb->cb_next)
492 		cb->cb_func(s, cb->cb_arg);
493 	/*
494 	 * Do deferred operations.
495 	 */
496 	if (clearaddr) {
497 		if (afp->af_ridreq == NULL || afp->af_difaddr == 0) {
498 			warnx("interface %s cannot change %s addresses!",
499 			      name, afp->af_name);
500 			clearaddr = 0;
501 		}
502 	}
503 	if (clearaddr) {
504 		int ret;
505 		strncpy(afp->af_ridreq, name, sizeof ifr.ifr_name);
506 		ret = ioctl(s, afp->af_difaddr, afp->af_ridreq);
507 		if (ret < 0) {
508 			if (errno == EADDRNOTAVAIL && (doalias >= 0)) {
509 				/* means no previous address for interface */
510 			} else
511 				Perror("ioctl (SIOCDIFADDR)");
512 		}
513 	}
514 	if (newaddr) {
515 		if (afp->af_addreq == NULL || afp->af_aifaddr == 0) {
516 			warnx("interface %s cannot change %s addresses!",
517 			      name, afp->af_name);
518 			newaddr = 0;
519 		}
520 	}
521 	if (newaddr && (setaddr || setmask)) {
522 		strncpy(afp->af_addreq, name, sizeof ifr.ifr_name);
523 		if (ioctl(s, afp->af_aifaddr, afp->af_addreq) < 0)
524 			Perror("ioctl (SIOCAIFADDR)");
525 	}
526 
527 	close(s);
528 	return(0);
529 }
530 
531 /*ARGSUSED*/
532 static void
533 setifaddr(const char *addr, int param, int s, const struct afswtch *afp)
534 {
535 	if (afp->af_getaddr == NULL)
536 		return;
537 	/*
538 	 * Delay the ioctl to set the interface addr until flags are all set.
539 	 * The address interpretation may depend on the flags,
540 	 * and the flags may change when the address is set.
541 	 */
542 	setaddr++;
543 	if (doalias == 0 && afp->af_af != AF_LINK)
544 		clearaddr = 1;
545 	afp->af_getaddr(addr, (doalias >= 0 ? ADDR : RIDADDR));
546 }
547 
548 static void
549 settunnel(const char *src, const char *dst, int s, const struct afswtch *afp)
550 {
551 	struct addrinfo *srcres, *dstres;
552 	int ecode;
553 
554 	if (afp->af_settunnel == NULL) {
555 		warn("address family %s does not support tunnel setup",
556 			afp->af_name);
557 		return;
558 	}
559 
560 	if ((ecode = getaddrinfo(src, NULL, NULL, &srcres)) != 0)
561 		errx(1, "error in parsing address string: %s",
562 		    gai_strerror(ecode));
563 
564 	if ((ecode = getaddrinfo(dst, NULL, NULL, &dstres)) != 0)
565 		errx(1, "error in parsing address string: %s",
566 		    gai_strerror(ecode));
567 
568 	if (srcres->ai_addr->sa_family != dstres->ai_addr->sa_family)
569 		errx(1,
570 		    "source and destination address families do not match");
571 
572 	afp->af_settunnel(s, srcres, dstres);
573 
574 	freeaddrinfo(srcres);
575 	freeaddrinfo(dstres);
576 }
577 
578 /* ARGSUSED */
579 static void
580 deletetunnel(const char *vname, int param, int s, const struct afswtch *afp)
581 {
582 
583 	if (ioctl(s, SIOCDIFPHYADDR, &ifr) < 0)
584 		err(1, "SIOCDIFPHYADDR");
585 }
586 
587 static void
588 setifnetmask(const char *addr, int dummy __unused, int s,
589     const struct afswtch *afp)
590 {
591 	if (afp->af_getaddr != NULL) {
592 		setmask++;
593 		afp->af_getaddr(addr, MASK);
594 	}
595 }
596 
597 static void
598 setifbroadaddr(const char *addr, int dummy __unused, int s,
599     const struct afswtch *afp)
600 {
601 	if (afp->af_getaddr != NULL)
602 		afp->af_getaddr(addr, DSTADDR);
603 }
604 
605 static void
606 setifipdst(const char *addr, int dummy __unused, int s,
607     const struct afswtch *afp)
608 {
609 	const struct afswtch *inet;
610 
611 	inet = af_getbyname("inet");
612 	if (inet == NULL)
613 		return;
614 	inet->af_getaddr(addr, DSTADDR);
615 	setipdst++;
616 	clearaddr = 0;
617 	newaddr = 0;
618 }
619 
620 static void
621 notealias(const char *addr, int param, int s, const struct afswtch *afp)
622 {
623 #define rqtosa(x) (&(((struct ifreq *)(afp->x))->ifr_addr))
624 	if (setaddr && doalias == 0 && param < 0)
625 		if (afp->af_addreq != NULL && afp->af_ridreq != NULL)
626 			bcopy((caddr_t)rqtosa(af_addreq),
627 			      (caddr_t)rqtosa(af_ridreq),
628 			      rqtosa(af_addreq)->sa_len);
629 	doalias = param;
630 	if (param < 0) {
631 		clearaddr = 1;
632 		newaddr = 0;
633 	} else
634 		clearaddr = 0;
635 #undef rqtosa
636 }
637 
638 /*ARGSUSED*/
639 static void
640 setifdstaddr(const char *addr, int param __unused, int s,
641     const struct afswtch *afp)
642 {
643 	if (afp->af_getaddr != NULL)
644 		afp->af_getaddr(addr, DSTADDR);
645 }
646 
647 /*
648  * Note: doing an SIOCIGIFFLAGS scribbles on the union portion
649  * of the ifreq structure, which may confuse other parts of ifconfig.
650  * Make a private copy so we can avoid that.
651  */
652 static void
653 setifflags(const char *vname, int value, int s, const struct afswtch *afp)
654 {
655 	struct ifreq		my_ifr;
656 	int flags;
657 
658 	bcopy((char *)&ifr, (char *)&my_ifr, sizeof(struct ifreq));
659 
660  	if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&my_ifr) < 0) {
661  		Perror("ioctl (SIOCGIFFLAGS)");
662  		exit(1);
663  	}
664 	strncpy(my_ifr.ifr_name, name, sizeof (my_ifr.ifr_name));
665 	flags = (my_ifr.ifr_flags & 0xffff) | (my_ifr.ifr_flagshigh << 16);
666 
667 	if (value < 0) {
668 		value = -value;
669 		flags &= ~value;
670 	} else
671 		flags |= value;
672 	my_ifr.ifr_flags = flags & 0xffff;
673 	my_ifr.ifr_flagshigh = flags >> 16;
674 	if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&my_ifr) < 0)
675 		Perror(vname);
676 }
677 
678 void
679 setifcap(const char *vname, int value, int s, const struct afswtch *afp)
680 {
681 	int flags;
682 
683  	if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) < 0) {
684  		Perror("ioctl (SIOCGIFCAP)");
685  		exit(1);
686  	}
687 	flags = ifr.ifr_curcap;
688 	if (value < 0) {
689 		value = -value;
690 		flags &= ~value;
691 	} else
692 		flags |= value;
693 	flags &= ifr.ifr_reqcap;
694 	ifr.ifr_reqcap = flags;
695 	if (ioctl(s, SIOCSIFCAP, (caddr_t)&ifr) < 0)
696 		Perror(vname);
697 }
698 
699 static void
700 setifmetric(const char *val, int dummy __unused, int s,
701     const struct afswtch *afp)
702 {
703 	strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
704 	ifr.ifr_metric = atoi(val);
705 	if (ioctl(s, SIOCSIFMETRIC, (caddr_t)&ifr) < 0)
706 		warn("ioctl (set metric)");
707 }
708 
709 static void
710 setifmtu(const char *val, int dummy __unused, int s,
711     const struct afswtch *afp)
712 {
713 	strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
714 	ifr.ifr_mtu = atoi(val);
715 	if (ioctl(s, SIOCSIFMTU, (caddr_t)&ifr) < 0)
716 		warn("ioctl (set mtu)");
717 }
718 
719 static void
720 setifname(const char *val, int dummy __unused, int s,
721     const struct afswtch *afp)
722 {
723 	char *newname;
724 
725 	newname = strdup(val);
726 	if (newname == NULL) {
727 		warn("no memory to set ifname");
728 		return;
729 	}
730 	ifr.ifr_data = newname;
731 	if (ioctl(s, SIOCSIFNAME, (caddr_t)&ifr) < 0) {
732 		warn("ioctl (set name)");
733 		free(newname);
734 		return;
735 	}
736 	strlcpy(name, newname, sizeof(name));
737 	free(newname);
738 }
739 
740 #define	IFFBITS \
741 "\020\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5POINTOPOINT\6SMART\7RUNNING" \
742 "\10NOARP\11PROMISC\12ALLMULTI\13OACTIVE\14SIMPLEX\15LINK0\16LINK1\17LINK2" \
743 "\20MULTICAST\22PPROMISC\23MONITOR\24STATICARP\25NEEDSGIANT"
744 
745 #define	IFCAPBITS \
746 "\020\1RXCSUM\2TXCSUM\3NETCONS\4VLAN_MTU\5VLAN_HWTAGGING\6JUMBO_MTU\7POLLING" \
747 "\10VLAN_HWCSUM\11TSO4\12TSO6"
748 
749 /*
750  * Print the status of the interface.  If an address family was
751  * specified, show only it; otherwise, show them all.
752  */
753 static void
754 status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
755 	struct ifaddrs *ifa)
756 {
757 	struct ifaddrs *ift;
758 	int allfamilies, s;
759 	struct ifstat ifs;
760 
761 	if (afp == NULL) {
762 		allfamilies = 1;
763 		afp = af_getbyname("inet");
764 	} else
765 		allfamilies = 0;
766 
767 	ifr.ifr_addr.sa_family = afp->af_af == AF_LINK ? AF_INET : afp->af_af;
768 	strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
769 
770 	s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0);
771 	if (s < 0)
772 		err(1, "socket(family %u,SOCK_DGRAM)", ifr.ifr_addr.sa_family);
773 
774 	printf("%s: ", name);
775 	printb("flags", ifa->ifa_flags, IFFBITS);
776 	if (ioctl(s, SIOCGIFMETRIC, &ifr) != -1)
777 		printf(" metric %d", ifr.ifr_metric);
778 	if (ioctl(s, SIOCGIFMTU, &ifr) != -1)
779 		printf(" mtu %d", ifr.ifr_mtu);
780 	putchar('\n');
781 
782 	if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) == 0) {
783 		if (ifr.ifr_curcap != 0) {
784 			printb("\toptions", ifr.ifr_curcap, IFCAPBITS);
785 			putchar('\n');
786 		}
787 		if (supmedia && ifr.ifr_reqcap != 0) {
788 			printb("\tcapabilities", ifr.ifr_reqcap, IFCAPBITS);
789 			putchar('\n');
790 		}
791 	}
792 
793 	tunnel_status(s);
794 
795 	for (ift = ifa; ift != NULL; ift = ift->ifa_next) {
796 		if (ift->ifa_addr == NULL)
797 			continue;
798 		if (strcmp(ifa->ifa_name, ift->ifa_name) != 0)
799 			continue;
800 		if (allfamilies) {
801 			const struct afswtch *p;
802 			p = af_getbyfamily(ift->ifa_addr->sa_family);
803 			if (p != NULL && p->af_status != NULL)
804 				p->af_status(s, ift);
805 		} else if (afp->af_af == ift->ifa_addr->sa_family)
806 			afp->af_status(s, ift);
807 	}
808 #if 0
809 	if (allfamilies || afp->af_af == AF_LINK) {
810 		const struct afswtch *lafp;
811 
812 		/*
813 		 * Hack; the link level address is received separately
814 		 * from the routing information so any address is not
815 		 * handled above.  Cobble together an entry and invoke
816 		 * the status method specially.
817 		 */
818 		lafp = af_getbyname("lladdr");
819 		if (lafp != NULL) {
820 			info.rti_info[RTAX_IFA] = (struct sockaddr *)sdl;
821 			lafp->af_status(s, &info);
822 		}
823 	}
824 #endif
825 	if (allfamilies)
826 		af_other_status(s);
827 	else if (afp->af_other_status != NULL)
828 		afp->af_other_status(s);
829 
830 	strncpy(ifs.ifs_name, name, sizeof ifs.ifs_name);
831 	if (ioctl(s, SIOCGIFSTATUS, &ifs) == 0)
832 		printf("%s", ifs.ascii);
833 
834 	close(s);
835 	return;
836 }
837 
838 static void
839 tunnel_status(int s)
840 {
841 	af_all_tunnel_status(s);
842 }
843 
844 void
845 Perror(const char *cmd)
846 {
847 	switch (errno) {
848 
849 	case ENXIO:
850 		errx(1, "%s: no such interface", cmd);
851 		break;
852 
853 	case EPERM:
854 		errx(1, "%s: permission denied", cmd);
855 		break;
856 
857 	default:
858 		err(1, "%s", cmd);
859 	}
860 }
861 
862 /*
863  * Print a value a la the %b format of the kernel's printf
864  */
865 void
866 printb(const char *s, unsigned v, const char *bits)
867 {
868 	int i, any = 0;
869 	char c;
870 
871 	if (bits && *bits == 8)
872 		printf("%s=%o", s, v);
873 	else
874 		printf("%s=%x", s, v);
875 	bits++;
876 	if (bits) {
877 		putchar('<');
878 		while ((i = *bits++) != '\0') {
879 			if (v & (1 << (i-1))) {
880 				if (any)
881 					putchar(',');
882 				any = 1;
883 				for (; (c = *bits) > 32; bits++)
884 					putchar(c);
885 			} else
886 				for (; *bits > 32; bits++)
887 					;
888 		}
889 		putchar('>');
890 	}
891 }
892 
893 void
894 ifmaybeload(const char *name)
895 {
896 	struct module_stat mstat;
897 	int fileid, modid;
898 	char ifkind[35], *dp;
899 	const char *cp;
900 
901 	/* turn interface and unit into module name */
902 	strcpy(ifkind, "if_");
903 	for (cp = name, dp = ifkind + 3;
904 	    (*cp != 0) && !isdigit(*cp); cp++, dp++)
905 		*dp = *cp;
906 	*dp = 0;
907 
908 	/* scan files in kernel */
909 	mstat.version = sizeof(struct module_stat);
910 	for (fileid = kldnext(0); fileid > 0; fileid = kldnext(fileid)) {
911 		/* scan modules in file */
912 		for (modid = kldfirstmod(fileid); modid > 0;
913 		     modid = modfnext(modid)) {
914 			if (modstat(modid, &mstat) < 0)
915 				continue;
916 			/* strip bus name if present */
917 			if ((cp = strchr(mstat.name, '/')) != NULL) {
918 				cp++;
919 			} else {
920 				cp = mstat.name;
921 			}
922 			/* already loaded? */
923 			if (strncmp(name, cp, strlen(cp)) == 0 ||
924 			    strncmp(ifkind, cp, strlen(cp)) == 0)
925 				return;
926 		}
927 	}
928 
929 	/* not present, we should try to load it */
930 	kldload(ifkind);
931 }
932 
933 static struct cmd basic_cmds[] = {
934 	DEF_CMD("up",		IFF_UP,		setifflags),
935 	DEF_CMD("down",		-IFF_UP,	setifflags),
936 	DEF_CMD("arp",		-IFF_NOARP,	setifflags),
937 	DEF_CMD("-arp",		IFF_NOARP,	setifflags),
938 	DEF_CMD("debug",	IFF_DEBUG,	setifflags),
939 	DEF_CMD("-debug",	-IFF_DEBUG,	setifflags),
940 	DEF_CMD("promisc",	IFF_PPROMISC,	setifflags),
941 	DEF_CMD("-promisc",	-IFF_PPROMISC,	setifflags),
942 	DEF_CMD("add",		IFF_UP,		notealias),
943 	DEF_CMD("alias",	IFF_UP,		notealias),
944 	DEF_CMD("-alias",	-IFF_UP,	notealias),
945 	DEF_CMD("delete",	-IFF_UP,	notealias),
946 	DEF_CMD("remove",	-IFF_UP,	notealias),
947 #ifdef notdef
948 #define	EN_SWABIPS	0x1000
949 	DEF_CMD("swabips",	EN_SWABIPS,	setifflags),
950 	DEF_CMD("-swabips",	-EN_SWABIPS,	setifflags),
951 #endif
952 	DEF_CMD_ARG("netmask",			setifnetmask),
953 	DEF_CMD_ARG("metric",			setifmetric),
954 	DEF_CMD_ARG("broadcast",		setifbroadaddr),
955 	DEF_CMD_ARG("ipdst",			setifipdst),
956 	DEF_CMD_ARG2("tunnel",			settunnel),
957 	DEF_CMD("-tunnel", 0,			deletetunnel),
958 	DEF_CMD("deletetunnel", 0,		deletetunnel),
959 	DEF_CMD("link0",	IFF_LINK0,	setifflags),
960 	DEF_CMD("-link0",	-IFF_LINK0,	setifflags),
961 	DEF_CMD("link1",	IFF_LINK1,	setifflags),
962 	DEF_CMD("-link1",	-IFF_LINK1,	setifflags),
963 	DEF_CMD("link2",	IFF_LINK2,	setifflags),
964 	DEF_CMD("-link2",	-IFF_LINK2,	setifflags),
965 	DEF_CMD("monitor",	IFF_MONITOR,	setifflags),
966 	DEF_CMD("-monitor",	-IFF_MONITOR,	setifflags),
967 	DEF_CMD("staticarp",	IFF_STATICARP,	setifflags),
968 	DEF_CMD("-staticarp",	-IFF_STATICARP,	setifflags),
969 	DEF_CMD("rxcsum",	IFCAP_RXCSUM,	setifcap),
970 	DEF_CMD("-rxcsum",	-IFCAP_RXCSUM,	setifcap),
971 	DEF_CMD("txcsum",	IFCAP_TXCSUM,	setifcap),
972 	DEF_CMD("-txcsum",	-IFCAP_TXCSUM,	setifcap),
973 	DEF_CMD("netcons",	IFCAP_NETCONS,	setifcap),
974 	DEF_CMD("-netcons",	-IFCAP_NETCONS,	setifcap),
975 	DEF_CMD("polling",	IFCAP_POLLING,	setifcap),
976 	DEF_CMD("-polling",	-IFCAP_POLLING,	setifcap),
977 	DEF_CMD("tso",		IFCAP_TSO,	setifcap),
978 	DEF_CMD("-tso",		-IFCAP_TSO,	setifcap),
979 	DEF_CMD("normal",	-IFF_LINK0,	setifflags),
980 	DEF_CMD("compress",	IFF_LINK0,	setifflags),
981 	DEF_CMD("noicmp",	IFF_LINK1,	setifflags),
982 	DEF_CMD_ARG("mtu",			setifmtu),
983 	DEF_CMD_ARG("name",			setifname),
984 };
985 
986 static __constructor void
987 ifconfig_ctor(void)
988 {
989 #define	N(a)	(sizeof(a) / sizeof(a[0]))
990 	int i;
991 
992 	for (i = 0; i < N(basic_cmds);  i++)
993 		cmd_register(&basic_cmds[i]);
994 #undef N
995 }
996