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