xref: /dragonfly/sbin/ifconfig/ifconfig.c (revision 3d33658b)
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 		}
265 	}
266 
267 	/* Check for address family */
268 	if (argc > 0) {
269 		afp = af_getbyname(*argv);
270 		if (afp != NULL)
271 			argc--, argv++;
272 	}
273 
274 retry:
275 	mib[0] = CTL_NET;
276 	mib[1] = PF_ROUTE;
277 	mib[2] = 0;
278 	mib[3] = 0;			/* address family */
279 	mib[4] = NET_RT_IFLIST;
280 	mib[5] = ifindex;		/* interface index */
281 
282 	/* if particular family specified, only ask about it */
283 	if (afp != NULL)
284 		mib[3] = afp->af_af;
285 
286 	if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
287 		errx(1, "iflist-sysctl-estimate");
288 	if ((buf = malloc(needed)) == NULL)
289 		errx(1, "malloc");
290 	if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
291 		if (errno == ENOMEM && count++ < 10) {
292 			warnx("Routing table grew, retrying");
293 			free(buf);
294 			sleep(1);
295 			goto retry;
296 		}
297 		errx(1, "actual retrieval of interface table");
298 	}
299 	lim = buf + needed;
300 
301 	next = buf;
302 	while (next < lim) {
303 		int name_len;
304 
305 		ifm = (struct if_msghdr *)next;
306 
307 		if (ifm->ifm_type == RTM_IFINFO) {
308 #ifdef notyet
309 			if (ifm->ifm_data.ifi_datalen == 0)
310 				ifm->ifm_data.ifi_datalen = sizeof(struct if_data);
311 			sdl = (struct sockaddr_dl *)((char *)ifm + sizeof(struct if_msghdr) -
312 			    sizeof(struct if_data) + ifm->ifm_data.ifi_datalen);
313 #else
314 			sdl = (struct sockaddr_dl *)(ifm + 1);
315 #endif
316 			flags = ifm->ifm_flags;
317 		} else {
318 			fprintf(stderr, "out of sync parsing NET_RT_IFLIST\n");
319 			fprintf(stderr, "expected %d, got %d\n", RTM_IFINFO,
320 				ifm->ifm_type);
321 			fprintf(stderr, "msglen = %d\n", ifm->ifm_msglen);
322 			fprintf(stderr, "buf:%p, next:%p, lim:%p\n", buf, next,
323 				lim);
324 			exit(1);
325 		}
326 
327 		next += ifm->ifm_msglen;
328 		ifam = NULL;
329 		addrcount = 0;
330 		while (next < lim) {
331 			nextifm = (struct if_msghdr *)next;
332 
333 			if (nextifm->ifm_type != RTM_NEWADDR)
334 				break;
335 
336 			if (ifam == NULL)
337 				ifam = (struct ifa_msghdr *)nextifm;
338 
339 			addrcount++;
340 			next += nextifm->ifm_msglen;
341 		}
342 
343 		if (sizeof(name) <= sdl->sdl_nlen)
344 			name_len = sizeof(name) - 1;
345 		else
346 			name_len = sdl->sdl_nlen;
347 
348 		memcpy(name, sdl->sdl_data, name_len);
349 		name[name_len] = '\0';
350 
351 		if (all || namesonly) {
352 			if (uponly)
353 				if ((flags & IFF_UP) == 0)
354 					continue; /* not up */
355 			if (downonly)
356 				if (flags & IFF_UP)
357 					continue; /* not down */
358 			if (namesonly) {
359 				if (afp == NULL || afp->af_af != AF_LINK ||
360 				    sdl->sdl_type == IFT_ETHER) {
361 					if (need_nl)
362 						putchar(' ');
363 					fputs(name, stdout);
364 					need_nl++;
365 				}
366 				continue;
367 			}
368 		}
369 
370 		if (argc > 0)
371 			ifconfig(argc, argv, 0, afp);
372 		else
373 			status(afp, addrcount, sdl, ifm, ifam);
374 	}
375 	free(buf);
376 
377 	if (namesonly && need_nl > 0)
378 		putchar('\n');
379 
380 	return (0);
381 }
382 
383 static struct afswtch *afs = NULL;
384 
385 void
386 af_register(struct afswtch *p)
387 {
388 	p->af_next = afs;
389 	afs = p;
390 }
391 
392 static struct afswtch *
393 af_getbyname(const char *name)
394 {
395 	struct afswtch *afp;
396 
397 	for (afp = afs; afp !=  NULL; afp = afp->af_next)
398 		if (strcmp(afp->af_name, name) == 0)
399 			return afp;
400 	return NULL;
401 }
402 
403 static struct afswtch *
404 af_getbyfamily(int af)
405 {
406 	struct afswtch *afp;
407 
408 	for (afp = afs; afp != NULL; afp = afp->af_next)
409 		if (afp->af_af == af)
410 			return afp;
411 	return NULL;
412 }
413 
414 static void
415 af_other_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_other_status == NULL)
423 			continue;
424 		if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
425 			continue;
426 		afp->af_other_status(s);
427 		setbit(afmask, afp->af_af);
428 	}
429 }
430 
431 static void
432 af_all_tunnel_status(int s)
433 {
434 	struct afswtch *afp;
435 	uint8_t afmask[howmany(AF_MAX, NBBY)];
436 
437 	memset(afmask, 0, sizeof(afmask));
438 	for (afp = afs; afp != NULL; afp = afp->af_next) {
439 		if (afp->af_status_tunnel == NULL)
440 			continue;
441 		if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
442 			continue;
443 		afp->af_status_tunnel(s);
444 		setbit(afmask, afp->af_af);
445 	}
446 }
447 
448 static struct cmd *cmds = NULL;
449 
450 void
451 cmd_register(struct cmd *p)
452 {
453 	p->c_next = cmds;
454 	cmds = p;
455 }
456 
457 static const struct cmd *
458 cmd_lookup(const char *name, int iscreate)
459 {
460 	const struct cmd *p;
461 
462 	for (p = cmds; p != NULL; p = p->c_next)
463 		if (strcmp(name, p->c_name) == 0) {
464 			if (iscreate) {
465 				if (p->c_iscloneop)
466 					return p;
467 			} else {
468 				if (!p->c_iscloneop)
469 					return p;
470 			}
471 		}
472 	return NULL;
473 }
474 
475 struct callback {
476 	callback_func *cb_func;
477 	void	*cb_arg;
478 	struct callback *cb_next;
479 };
480 static struct callback *callbacks = NULL;
481 
482 void
483 callback_register(callback_func *func, void *arg)
484 {
485 	struct callback *cb;
486 
487 	cb = malloc(sizeof(struct callback));
488 	if (cb == NULL)
489 		errx(1, "unable to allocate memory for callback");
490 	cb->cb_func = func;
491 	cb->cb_arg = arg;
492 	cb->cb_next = callbacks;
493 	callbacks = cb;
494 }
495 
496 /* specially-handled commands */
497 static void setifaddr(const char *, int, int, const struct afswtch *);
498 static const struct cmd setifaddr_cmd = DEF_CMD("ifaddr", 0, setifaddr);
499 
500 static void setifdstaddr(const char *, int, int, const struct afswtch *);
501 static const struct cmd setifdstaddr_cmd =
502 	DEF_CMD("ifdstaddr", 0, setifdstaddr);
503 
504 static int
505 ifconfig(int argc, char *const *argv, int iscreate,
506 	 const struct afswtch *uafp)
507 {
508 	const struct afswtch *afp, *nafp;
509 	struct callback *cb;
510 	int s;
511 
512 	strlcpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
513 	afp = uafp != NULL ? uafp : af_getbyname("inet");
514 top:
515 	ifr.ifr_addr.sa_family =
516 		afp->af_af == AF_LINK || afp->af_af == AF_UNSPEC ?
517 		AF_LOCAL : afp->af_af;
518 
519 	if ((s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0)) < 0 &&
520 	    (uafp != NULL || errno != EAFNOSUPPORT ||
521 	     (s = socket(AF_LOCAL, SOCK_DGRAM, 0)) < 0))
522 		err(1, "socket(family %u,SOCK_DGRAM)", ifr.ifr_addr.sa_family);
523 
524 	while (argc > 0) {
525 		const struct cmd *p;
526 
527 		p = cmd_lookup(*argv, iscreate);
528 
529 		if (iscreate && p == NULL) {
530 			/*
531 			 * Push the clone create callback so the new
532 			 * device is created and can be used for any
533 			 * remaining arguments.
534 			 */
535 			cb = callbacks;
536 			if (cb == NULL)
537 				errx(1, "internal error, no callback");
538 			callbacks = cb->cb_next;
539 			cb->cb_func(s, cb->cb_arg);
540 			iscreate = 0;
541 
542 			/*
543 			 * After cloning, make sure we have an up-to-date name
544 			 * in ifr_name.
545 			 */
546 			strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
547 
548 			/*
549 			 * Handle any address family spec that
550 			 * immediately follows and potentially
551 			 * recreate the socket.
552 			 */
553 			nafp = af_getbyname(*argv);
554 			if (nafp != NULL) {
555 				argc--, argv++;
556 				if (nafp != afp) {
557 					close(s);
558 					afp = nafp;
559 					goto top;
560 				}
561 			}
562 			/*
563 			 * Look for a normal parameter.
564 			 */
565 			continue;
566 		}
567 		if (p == NULL) {
568 			/*
569 			 * Not a recognized command, choose between setting
570 			 * the interface address and the dst address.
571 			 */
572 			p = (setaddr ? &setifdstaddr_cmd : &setifaddr_cmd);
573 		}
574 		if (p->c_u.c_func || p->c_u.c_func2) {
575 			if (p->c_parameter == NEXTARG) {
576 				if (argv[1] == NULL)
577 					errx(1, "'%s' requires argument",
578 					    p->c_name);
579 				p->c_u.c_func(argv[1], 0, s, afp);
580 				argc--, argv++;
581 			} else if (p->c_parameter == OPTARG) {
582 				p->c_u.c_func(argv[1], 0, s, afp);
583 				if (argv[1] != NULL)
584 					argc--, argv++;
585 			} else if (p->c_parameter == NEXTARG2) {
586 				if (argc < 3)
587 					errx(1, "'%s' requires 2 arguments",
588 					    p->c_name);
589 				p->c_u.c_func2(argv[1], argv[2], s, afp);
590 				argc -= 2, argv += 2;
591 			} else
592 				p->c_u.c_func(*argv, p->c_parameter, s, afp);
593 		}
594 		argc--, argv++;
595 	}
596 
597 	/*
598 	 * Do any post argument processing required by the address family.
599 	 */
600 	if (afp->af_postproc != NULL)
601 		afp->af_postproc(s, afp);
602 	/*
603 	 * Do deferred callbacks registered while processing
604 	 * command-line arguments.
605 	 */
606 	for (cb = callbacks; cb != NULL; cb = cb->cb_next)
607 		cb->cb_func(s, cb->cb_arg);
608 	/*
609 	 * Do deferred operations.
610 	 */
611 	if (clearaddr) {
612 		if (afp->af_ridreq == NULL || afp->af_difaddr == 0) {
613 			warnx("interface %s cannot change %s addresses!",
614 			      name, afp->af_name);
615 			clearaddr = 0;
616 		}
617 	}
618 	if (clearaddr) {
619 		int ret;
620 		strlcpy(afp->af_ridreq, name, sizeof ifr.ifr_name);
621 		ret = ioctl(s, afp->af_difaddr, afp->af_ridreq);
622 		if (ret < 0) {
623 			if (errno == EADDRNOTAVAIL && (doalias >= 0)) {
624 				/* means no previous address for interface */
625 			} else
626 				Perror("ioctl (SIOCDIFADDR)");
627 		}
628 	}
629 	if (newaddr) {
630 		if (afp->af_addreq == NULL || afp->af_aifaddr == 0) {
631 			warnx("interface %s cannot change %s addresses!",
632 			      name, afp->af_name);
633 			newaddr = 0;
634 		}
635 	}
636 	if (newaddr && (setaddr || setmask)) {
637 		strlcpy(afp->af_addreq, name, sizeof ifr.ifr_name);
638 		if (ioctl(s, afp->af_aifaddr, afp->af_addreq) < 0)
639 			Perror("ioctl (SIOCAIFADDR)");
640 	}
641 
642 	close(s);
643 	return (0);
644 }
645 
646 /*ARGSUSED*/
647 static void
648 setifaddr(const char *addr, int param, int s, const struct afswtch *afp)
649 {
650 	if (afp->af_getaddr == NULL)
651 		return;
652 	/*
653 	 * Delay the ioctl to set the interface addr until flags are all set.
654 	 * The address interpretation may depend on the flags,
655 	 * and the flags may change when the address is set.
656 	 */
657 	setaddr++;
658 	if (doalias == 0 && afp->af_af != AF_LINK)
659 		clearaddr = 1;
660 	afp->af_getaddr(addr, (doalias >= 0 ? ADDR : RIDADDR));
661 }
662 
663 static void
664 settunnel(const char *src, const char *dst, int s, const struct afswtch *afp)
665 {
666 	struct addrinfo *srcres, *dstres;
667 	int ecode;
668 
669 	if (afp->af_settunnel == NULL) {
670 		warn("address family %s does not support tunnel setup",
671 			afp->af_name);
672 		return;
673 	}
674 
675 	if ((ecode = getaddrinfo(src, NULL, NULL, &srcres)) != 0)
676 		errx(1, "error in parsing address string: %s",
677 		    gai_strerror(ecode));
678 
679 	if ((ecode = getaddrinfo(dst, NULL, NULL, &dstres)) != 0)
680 		errx(1, "error in parsing address string: %s",
681 		    gai_strerror(ecode));
682 
683 	if (srcres->ai_addr->sa_family != dstres->ai_addr->sa_family)
684 		errx(1,
685 		    "source and destination address families do not match");
686 
687 	afp->af_settunnel(s, srcres, dstres);
688 
689 	freeaddrinfo(srcres);
690 	freeaddrinfo(dstres);
691 }
692 
693 /* ARGSUSED */
694 static void
695 deletetunnel(const char *vname, int param, int s, const struct afswtch *afp)
696 {
697 
698 	if (ioctl(s, SIOCDIFPHYADDR, &ifr) < 0)
699 		err(1, "SIOCDIFPHYADDR");
700 }
701 
702 static void
703 setifnetmask(const char *addr, int dummy __unused, int s,
704     const struct afswtch *afp)
705 {
706 	if (afp->af_getaddr != NULL) {
707 		setmask++;
708 		afp->af_getaddr(addr, MASK);
709 	}
710 }
711 
712 static void
713 setifbroadaddr(const char *addr, int dummy __unused, int s,
714     const struct afswtch *afp)
715 {
716 	if (afp->af_getaddr != NULL)
717 		afp->af_getaddr(addr, DSTADDR);
718 }
719 
720 static void
721 notealias(const char *addr, int param, int s, const struct afswtch *afp)
722 {
723 #define rqtosa(x) (&(((struct ifreq *)(afp->x))->ifr_addr))
724 	if (setaddr && doalias == 0 && param < 0)
725 		if (afp->af_addreq != NULL && afp->af_ridreq != NULL)
726 			bcopy((caddr_t)rqtosa(af_addreq),
727 			      (caddr_t)rqtosa(af_ridreq),
728 			      rqtosa(af_addreq)->sa_len);
729 	doalias = param;
730 	if (param < 0) {
731 		clearaddr = 1;
732 		newaddr = 0;
733 	} else
734 		clearaddr = 0;
735 #undef rqtosa
736 }
737 
738 /*ARGSUSED*/
739 static void
740 setifdstaddr(const char *addr, int param __unused, int s,
741     const struct afswtch *afp)
742 {
743 	if (afp->af_getaddr != NULL)
744 		afp->af_getaddr(addr, DSTADDR);
745 }
746 
747 /*
748  * Note: doing an SIOCIGIFFLAGS scribbles on the union portion
749  * of the ifreq structure, which may confuse other parts of ifconfig.
750  * Make a private copy so we can avoid that.
751  */
752 static void
753 setifflags(const char *vname, int value, int s, const struct afswtch *afp)
754 {
755 	struct ifreq		my_ifr;
756 
757 	bcopy((char *)&ifr, (char *)&my_ifr, sizeof(struct ifreq));
758 
759 	if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&my_ifr) < 0) {
760 		Perror("ioctl (SIOCGIFFLAGS)");
761 	}
762 	strlcpy(my_ifr.ifr_name, name, sizeof (my_ifr.ifr_name));
763 	flags = (my_ifr.ifr_flags & 0xffff) | (my_ifr.ifr_flagshigh << 16);
764 
765 	if (value < 0) {
766 		value = -value;
767 		flags &= ~value;
768 	} else
769 		flags |= value;
770 	my_ifr.ifr_flags = flags & 0xffff;
771 	my_ifr.ifr_flagshigh = flags >> 16;
772 	if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&my_ifr) < 0)
773 		Perror(vname);
774 }
775 
776 void
777 setifcap(const char *vname, int value, int s, const struct afswtch *afp)
778 {
779 
780 	if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) < 0) {
781 		Perror("ioctl (SIOCGIFCAP)");
782 	}
783 	flags = ifr.ifr_curcap;
784 	if (value < 0) {
785 		value = -value;
786 		flags &= ~value;
787 	} else
788 		flags |= value;
789 	ifr.ifr_reqcap = flags;
790 	if (ioctl(s, SIOCSIFCAP, (caddr_t)&ifr) < 0)
791 		Perror(vname);
792 }
793 
794 static void
795 setifmetric(const char *val, int dummy __unused, int s,
796     const struct afswtch *afp)
797 {
798 	strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
799 	ifr.ifr_metric = atoi(val);
800 	if (ioctl(s, SIOCSIFMETRIC, (caddr_t)&ifr) < 0)
801 		err(1, "ioctl SIOCSIFMETRIC (set metric)");
802 }
803 
804 static void
805 setifmtu(const char *val, int dummy __unused, int s,
806     const struct afswtch *afp)
807 {
808 	strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
809 	ifr.ifr_mtu = atoi(val);
810 	if (ioctl(s, SIOCSIFMTU, (caddr_t)&ifr) < 0)
811 		err(1, "ioctl SIOCSIFMTU (set mtu)");
812 }
813 
814 static void
815 setiftsolen(const char *val, int dummy __unused, int s,
816     const struct afswtch *afp)
817 {
818 	strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
819 	ifr.ifr_tsolen = atoi(val);
820 	if (ioctl(s, SIOCSIFTSOLEN, (caddr_t)&ifr) < 0)
821 		err(1, "ioctl SIOCSIFTSOLEN (set tsolen)");
822 }
823 
824 static void
825 setifname(const char *val, int dummy __unused, int s,
826     const struct afswtch *afp)
827 {
828 	char *newname;
829 
830 	strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
831 
832 	newname = strdup(val);
833 	if (newname == NULL)
834 		err(1, "no memory to set ifname");
835 	ifr.ifr_data = newname;
836 	if (ioctl(s, SIOCSIFNAME, (caddr_t)&ifr) < 0) {
837 		free(newname);
838 		err(1, "ioctl SIOCSIFNAME (set name)");
839 	}
840 	printifname = 1;
841 	strlcpy(name, newname, sizeof(name));
842 	free(newname);
843 }
844 
845 static void
846 setifpollcpu(const char *val, int dummy __unused, int s,
847     const struct afswtch *afp)
848 {
849 	warnx("pollcpu is deprecated, use polling or npolling instead");
850 	setifflags("npolling", IFF_NPOLLING, s, afp);
851 }
852 
853 /*
854  * Expand the compacted form of addresses as returned via the
855  * configuration read via sysctl().
856  */
857 static void
858 rt_xaddrs(caddr_t cp, caddr_t cplim, struct rt_addrinfo *rtinfo)
859 {
860 	struct sockaddr *sa;
861 	int i;
862 
863 	memset(rtinfo->rti_info, 0, sizeof(rtinfo->rti_info));
864 	for (i = 0; (i < RTAX_MAX) && (cp < cplim); i++) {
865 		if ((rtinfo->rti_addrs & (1 << i)) == 0)
866 			continue;
867 		rtinfo->rti_info[i] = sa = (struct sockaddr *)cp;
868 		RT_ADVANCE(cp, sa);
869 	}
870 }
871 
872 #define	IFFBITS \
873 "\020\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5POINTOPOINT\6SMART\7RUNNING" \
874 "\10NOARP\11PROMISC\12ALLMULTI\14SIMPLEX\15LINK0\16LINK1\17LINK2" \
875 "\20MULTICAST\22PPROMISC\23MONITOR\24STATICARP\25NPOLLING\26IDIRECT"
876 
877 #define	IFCAPBITS \
878 "\020\1RXCSUM\2TXCSUM\3NETCONS\4VLAN_MTU\5VLAN_HWTAGGING\6JUMBO_MTU\7RSS" \
879 "\10VLAN_HWCSUM\11TSO"
880 
881 /*
882  * Print the status of the interface.  If an address family was
883  * specified, show only it; otherwise, show them all.
884  */
885 static void
886 status(const struct afswtch *afp, int addrcount, struct	sockaddr_dl *sdl,
887     struct if_msghdr *ifm, struct ifa_msghdr *ifam)
888 {
889 	struct	rt_addrinfo info;
890 	int allfamilies, s;
891 	struct ifstat ifs;
892 
893 	if (afp == NULL) {
894 		allfamilies = 1;
895 		ifr.ifr_addr.sa_family = AF_LOCAL;
896 	} else {
897 		allfamilies = 0;
898 		ifr.ifr_addr.sa_family =
899 		    afp->af_af == AF_LINK ? AF_LOCAL : afp->af_af;
900 	}
901 	strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
902 
903 	s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0);
904 	if (s < 0)
905 		err(1, "socket(family %u,SOCK_DGRAM)", ifr.ifr_addr.sa_family);
906 
907 	printf("%s: ", name);
908 	printb("flags", flags, IFFBITS);
909 	if (ifm->ifm_data.ifi_metric)
910 		printf(" metric %ld", ifm->ifm_data.ifi_metric);
911 	if (ifm->ifm_data.ifi_mtu)
912 		printf(" mtu %ld", ifm->ifm_data.ifi_mtu);
913 	putchar('\n');
914 
915 	if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) == 0) {
916 		if (ifr.ifr_curcap != 0) {
917 			printb("\toptions", ifr.ifr_curcap, IFCAPBITS);
918 			putchar('\n');
919 		}
920 		if (supmedia && ifr.ifr_reqcap != 0) {
921 			printb("\tcapabilities", ifr.ifr_reqcap, IFCAPBITS);
922 			putchar('\n');
923 			if (ifr.ifr_reqcap & IFCAP_TSO) {
924 				if (ioctl(s, SIOCGIFTSOLEN,
925 				    (caddr_t)&ifr) == 0) {
926 					printf("\ttsolen %d", ifr.ifr_tsolen);
927 					putchar('\n');
928 				}
929 			}
930 		}
931 	}
932 
933 	tunnel_status(s);
934 
935 	while (addrcount > 0) {
936 		info.rti_addrs = ifam->ifam_addrs;
937 		/* Expand the compacted addresses */
938 		rt_xaddrs((char *)(ifam + 1), ifam->ifam_msglen + (char *)ifam,
939 			  &info);
940 
941 		if (allfamilies) {
942 			const struct afswtch *p;
943 			p = af_getbyfamily(info.rti_info[RTAX_IFA]->sa_family);
944 			if (p != NULL && p->af_status != NULL)
945 				p->af_status(s, &info);
946 		} else if (afp->af_af == info.rti_info[RTAX_IFA]->sa_family)
947 			afp->af_status(s, &info);
948 		addrcount--;
949 		ifam = (struct ifa_msghdr *)((char *)ifam + ifam->ifam_msglen);
950 	}
951 	if (allfamilies || afp->af_af == AF_LINK) {
952 		const struct afswtch *lafp;
953 
954 		/*
955 		 * Hack; the link level address is received separately
956 		 * from the routing information so any address is not
957 		 * handled above.  Cobble together an entry and invoke
958 		 * the status method specially.
959 		 */
960 		lafp = af_getbyname("lladdr");
961 		if (lafp != NULL) {
962 			info.rti_info[RTAX_IFA] = (struct sockaddr *)sdl;
963 			lafp->af_status(s, &info);
964 		}
965 	}
966 	if (allfamilies)
967 		af_other_status(s);
968 	else if (afp->af_other_status != NULL)
969 		afp->af_other_status(s);
970 
971 	strlcpy(ifs.ifs_name, name, sizeof ifs.ifs_name);
972 	if (ioctl(s, SIOCGIFSTATUS, &ifs) == 0)
973 		printf("%s", ifs.ascii);
974 
975 	close(s);
976 	return;
977 }
978 
979 static void
980 tunnel_status(int s)
981 {
982 	af_all_tunnel_status(s);
983 }
984 
985 void
986 Perror(const char *cmd)
987 {
988 	switch (errno) {
989 
990 	case ENXIO:
991 		errx(1, "%s: no such interface", cmd);
992 		break;
993 
994 	case EPERM:
995 		errx(1, "%s: permission denied", cmd);
996 		break;
997 
998 	default:
999 		err(1, "%s", cmd);
1000 	}
1001 }
1002 
1003 /*
1004  * Print a value a la the %pb%i format of the kernel's kprintf()
1005  */
1006 void
1007 printb(const char *s, unsigned v, const char *bits)
1008 {
1009 	int i, any = 0;
1010 	char c;
1011 
1012 	if (bits && *bits == 8)
1013 		printf("%s=%o", s, v);
1014 	else
1015 		printf("%s=%x", s, v);
1016 	bits++;
1017 	if (bits) {
1018 		putchar('<');
1019 		while ((i = *bits++) != '\0') {
1020 			if (v & (1 << (i-1))) {
1021 				if (any)
1022 					putchar(',');
1023 				any = 1;
1024 				for (; (c = *bits) > 32; bits++)
1025 					putchar(c);
1026 			} else
1027 				for (; *bits > 32; bits++)
1028 					;
1029 		}
1030 		putchar('>');
1031 	}
1032 }
1033 
1034 void
1035 ifmaybeload(const char *name)
1036 {
1037 #define MOD_PREFIX_LEN		3	/* "if_" */
1038 	struct module_stat mstat;
1039 	int fileid, modid;
1040 	char ifkind[IFNAMSIZ + MOD_PREFIX_LEN], ifname[IFNAMSIZ], *dp;
1041 	const char *cp;
1042 
1043 	/* loading suppressed by the user */
1044 	if (noload)
1045 		return;
1046 
1047 	/* trim the interface number off the end */
1048 	strlcpy(ifname, name, sizeof(ifname));
1049 	for (dp = ifname; *dp != 0; dp++)
1050 		if (isdigit(*dp)) {
1051 			*dp = 0;
1052 			break;
1053 		}
1054 
1055 	/* turn interface and unit into module name */
1056 	strlcpy(ifkind, "if_", sizeof(ifkind));
1057 	strlcat(ifkind, ifname, sizeof(ifkind));
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 (strcmp(ifname, cp) == 0 ||
1075 			    strcmp(ifkind, 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 	DEF_CMD_ARG2("tunnel",			settunnel),
1107 	DEF_CMD("-tunnel", 0,			deletetunnel),
1108 	DEF_CMD("deletetunnel", 0,		deletetunnel),
1109 	DEF_CMD("link0",	IFF_LINK0,	setifflags),
1110 	DEF_CMD("-link0",	-IFF_LINK0,	setifflags),
1111 	DEF_CMD("link1",	IFF_LINK1,	setifflags),
1112 	DEF_CMD("-link1",	-IFF_LINK1,	setifflags),
1113 	DEF_CMD("link2",	IFF_LINK2,	setifflags),
1114 	DEF_CMD("-link2",	-IFF_LINK2,	setifflags),
1115 	DEF_CMD("monitor",	IFF_MONITOR,	setifflags),
1116 	DEF_CMD("-monitor",	-IFF_MONITOR,	setifflags),
1117 	DEF_CMD("staticarp",	IFF_STATICARP,	setifflags),
1118 	DEF_CMD("-staticarp",	-IFF_STATICARP,	setifflags),
1119 	DEF_CMD("polling",	IFF_NPOLLING,	setifflags),
1120 	DEF_CMD("-polling",	-IFF_NPOLLING,	setifflags),
1121 	DEF_CMD("npolling",	IFF_NPOLLING,	setifflags),
1122 	DEF_CMD("-npolling",	-IFF_NPOLLING,	setifflags),
1123 	DEF_CMD("rxcsum",	IFCAP_RXCSUM,	setifcap),
1124 	DEF_CMD("-rxcsum",	-IFCAP_RXCSUM,	setifcap),
1125 	DEF_CMD("txcsum",	IFCAP_TXCSUM,	setifcap),
1126 	DEF_CMD("-txcsum",	-IFCAP_TXCSUM,	setifcap),
1127 	DEF_CMD("netcons",	IFCAP_NETCONS,	setifcap),
1128 	DEF_CMD("-netcons",	-IFCAP_NETCONS,	setifcap),
1129 	DEF_CMD("rss",		IFCAP_RSS,	setifcap),
1130 	DEF_CMD("-rss",		-IFCAP_RSS,	setifcap),
1131 	DEF_CMD("tso",		IFCAP_TSO,	setifcap),
1132 	DEF_CMD("-tso",		-IFCAP_TSO,	setifcap),
1133 	DEF_CMD("normal",	-IFF_LINK0,	setifflags),
1134 	DEF_CMD("compress",	IFF_LINK0,	setifflags),
1135 	DEF_CMD("noicmp",	IFF_LINK1,	setifflags),
1136 	DEF_CMD_ARG("mtu",			setifmtu),
1137 	DEF_CMD_ARG("name",			setifname),
1138 	DEF_CMD_ARG("pollcpu",			setifpollcpu),
1139 	DEF_CMD_ARG("tsolen",			setiftsolen)
1140 };
1141 
1142 static __constructor(101) void
1143 ifconfig_ctor(void)
1144 {
1145 	size_t i;
1146 
1147 	for (i = 0; i < nitems(basic_cmds);  i++)
1148 		cmd_register(&basic_cmds[i]);
1149 }
1150