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