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