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