ifconfig.c revision 337757
1/*
2 * Copyright (c) 1983, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#ifndef lint
31static const char copyright[] =
32"@(#) Copyright (c) 1983, 1993\n\
33	The Regents of the University of California.  All rights reserved.\n";
34#endif /* not lint */
35
36#ifndef lint
37#if 0
38static char sccsid[] = "@(#)ifconfig.c	8.2 (Berkeley) 2/16/94";
39#endif
40static const char rcsid[] =
41  "$FreeBSD: stable/10/sbin/ifconfig/ifconfig.c 337757 2018-08-14 14:19:57Z markj $";
42#endif /* not lint */
43
44#include <sys/param.h>
45#include <sys/ioctl.h>
46#include <sys/module.h>
47#include <sys/linker.h>
48#include <sys/socket.h>
49#include <sys/time.h>
50
51#include <net/ethernet.h>
52#include <net/if.h>
53#include <net/if_var.h>
54#include <net/if_dl.h>
55#include <net/if_types.h>
56#include <net/route.h>
57
58/* IP */
59#include <netinet/in.h>
60#include <netinet/in_var.h>
61#include <arpa/inet.h>
62#include <netdb.h>
63
64#include <ifaddrs.h>
65#include <ctype.h>
66#include <err.h>
67#include <errno.h>
68#include <fcntl.h>
69#ifdef JAIL
70#include <jail.h>
71#endif
72#include <stdio.h>
73#include <stdlib.h>
74#include <string.h>
75#include <unistd.h>
76
77#include "ifconfig.h"
78
79/*
80 * Since "struct ifreq" is composed of various union members, callers
81 * should pay special attention to interpret the value.
82 * (.e.g. little/big endian difference in the structure.)
83 */
84struct	ifreq ifr;
85
86char	name[IFNAMSIZ];
87char	*descr = NULL;
88size_t	descrlen = 64;
89int	setaddr;
90int	setmask;
91int	doalias;
92int	clearaddr;
93int	newaddr = 1;
94int	verbose;
95int	noload;
96int	printifname = 0;
97
98int	supmedia = 0;
99int	printkeys = 0;		/* Print keying material for interfaces. */
100
101static	int ifconfig(int argc, char *const *argv, int iscreate,
102		const struct afswtch *afp);
103static	void status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
104		struct ifaddrs *ifa);
105static	void tunnel_status(int s);
106static _Noreturn void usage(void);
107
108static struct afswtch *af_getbyname(const char *name);
109static struct afswtch *af_getbyfamily(int af);
110static void af_other_status(int);
111
112void printifnamemaybe(void);
113
114static struct option *opts = NULL;
115
116void
117opt_register(struct option *p)
118{
119	p->next = opts;
120	opts = p;
121}
122
123static void
124usage(void)
125{
126	char options[1024];
127	struct option *p;
128
129	/* XXX not right but close enough for now */
130	options[0] = '\0';
131	for (p = opts; p != NULL; p = p->next) {
132		strlcat(options, p->opt_usage, sizeof(options));
133		strlcat(options, " ", sizeof(options));
134	}
135
136	fprintf(stderr,
137	"usage: ifconfig %sinterface address_family [address [dest_address]]\n"
138	"                [parameters]\n"
139	"       ifconfig interface create\n"
140	"       ifconfig -a %s[-d] [-m] [-u] [-v] [address_family]\n"
141	"       ifconfig -l [-d] [-u] [address_family]\n"
142	"       ifconfig %s[-d] [-m] [-u] [-v]\n",
143		options, options, options);
144	exit(1);
145}
146
147void printifnamemaybe()
148{
149	if (printifname)
150		printf("%s\n", name);
151}
152
153int
154main(int argc, char *argv[])
155{
156	int c, all, namesonly, downonly, uponly;
157	const struct afswtch *afp = NULL;
158	int ifindex;
159	struct ifaddrs *ifap, *ifa;
160	struct ifreq paifr;
161	const struct sockaddr_dl *sdl;
162	char options[1024], *cp, *namecp = NULL;
163	const char *ifname;
164	struct option *p;
165	size_t iflen;
166
167	all = downonly = uponly = namesonly = noload = verbose = 0;
168
169	/*
170	 * Ensure we print interface name when expected to,
171	 * even if we terminate early due to error.
172	 */
173	atexit(printifnamemaybe);
174
175	/* Parse leading line options */
176	strlcpy(options, "adklmnuv", sizeof(options));
177	for (p = opts; p != NULL; p = p->next)
178		strlcat(options, p->opt, sizeof(options));
179	while ((c = getopt(argc, argv, options)) != -1) {
180		switch (c) {
181		case 'a':	/* scan all interfaces */
182			all++;
183			break;
184		case 'd':	/* restrict scan to "down" interfaces */
185			downonly++;
186			break;
187		case 'k':
188			printkeys++;
189			break;
190		case 'l':	/* scan interface names only */
191			namesonly++;
192			break;
193		case 'm':	/* show media choices in status */
194			supmedia = 1;
195			break;
196		case 'n':	/* suppress module loading */
197			noload++;
198			break;
199		case 'u':	/* restrict scan to "up" interfaces */
200			uponly++;
201			break;
202		case 'v':
203			verbose++;
204			break;
205		default:
206			for (p = opts; p != NULL; p = p->next)
207				if (p->opt[0] == c) {
208					p->cb(optarg);
209					break;
210				}
211			if (p == NULL)
212				usage();
213			break;
214		}
215	}
216	argc -= optind;
217	argv += optind;
218
219	/* -l cannot be used with -a or -m */
220	if (namesonly && (all || supmedia))
221		usage();
222
223	/* nonsense.. */
224	if (uponly && downonly)
225		usage();
226
227	/* no arguments is equivalent to '-a' */
228	if (!namesonly && argc < 1)
229		all = 1;
230
231	/* -a and -l allow an address family arg to limit the output */
232	if (all || namesonly) {
233		if (argc > 1)
234			usage();
235
236		ifname = NULL;
237		ifindex = 0;
238		if (argc == 1) {
239			afp = af_getbyname(*argv);
240			if (afp == NULL) {
241				warnx("Address family '%s' unknown.", *argv);
242				usage();
243			}
244			if (afp->af_name != NULL)
245				argc--, argv++;
246			/* leave with afp non-zero */
247		}
248	} else {
249		/* not listing, need an argument */
250		if (argc < 1)
251			usage();
252
253		ifname = *argv;
254		argc--, argv++;
255
256		/* check and maybe load support for this interface */
257		ifmaybeload(ifname);
258
259		ifindex = if_nametoindex(ifname);
260		if (ifindex == 0) {
261			/*
262			 * NOTE:  We must special-case the `create' command
263			 * right here as we would otherwise fail when trying
264			 * to find the interface.
265			 */
266			if (argc > 0 && (strcmp(argv[0], "create") == 0 ||
267			    strcmp(argv[0], "plumb") == 0)) {
268				iflen = strlcpy(name, ifname, sizeof(name));
269				if (iflen >= sizeof(name))
270					errx(1, "%s: cloning name too long",
271					    ifname);
272				ifconfig(argc, argv, 1, NULL);
273				exit(0);
274			}
275#ifdef JAIL
276			/*
277			 * NOTE:  We have to special-case the `-vnet' command
278			 * right here as we would otherwise fail when trying
279			 * to find the interface as it lives in another vnet.
280			 */
281			if (argc > 0 && (strcmp(argv[0], "-vnet") == 0)) {
282				iflen = strlcpy(name, ifname, sizeof(name));
283				if (iflen >= sizeof(name))
284					errx(1, "%s: interface name too long",
285					    ifname);
286				ifconfig(argc, argv, 0, NULL);
287				exit(0);
288			}
289#endif
290			errx(1, "interface %s does not exist", ifname);
291		}
292	}
293
294	/* Check for address family */
295	if (argc > 0) {
296		afp = af_getbyname(*argv);
297		if (afp != NULL)
298			argc--, argv++;
299	}
300
301	if (getifaddrs(&ifap) != 0)
302		err(EXIT_FAILURE, "getifaddrs");
303	cp = NULL;
304	ifindex = 0;
305	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
306		memset(&paifr, 0, sizeof(paifr));
307		strlcpy(paifr.ifr_name, ifa->ifa_name, sizeof(paifr.ifr_name));
308		if (sizeof(paifr.ifr_addr) >= ifa->ifa_addr->sa_len) {
309			memcpy(&paifr.ifr_addr, ifa->ifa_addr,
310			    ifa->ifa_addr->sa_len);
311		}
312
313		if (ifname != NULL && strcmp(ifname, ifa->ifa_name) != 0)
314			continue;
315		if (ifa->ifa_addr->sa_family == AF_LINK)
316			sdl = (const struct sockaddr_dl *) ifa->ifa_addr;
317		else
318			sdl = NULL;
319		if (cp != NULL && strcmp(cp, ifa->ifa_name) == 0 && !namesonly)
320			continue;
321		iflen = strlcpy(name, ifa->ifa_name, sizeof(name));
322		if (iflen >= sizeof(name)) {
323			warnx("%s: interface name too long, skipping",
324			    ifa->ifa_name);
325			continue;
326		}
327		cp = ifa->ifa_name;
328
329		if ((ifa->ifa_flags & IFF_CANTCONFIG) != 0)
330			continue;
331		if (downonly && (ifa->ifa_flags & IFF_UP) != 0)
332			continue;
333		if (uponly && (ifa->ifa_flags & IFF_UP) == 0)
334			continue;
335		/*
336		 * Are we just listing the interfaces?
337		 */
338		if (namesonly) {
339			if (namecp == cp)
340				continue;
341			if (afp != NULL) {
342				/* special case for "ether" address family */
343				if (!strcmp(afp->af_name, "ether")) {
344					if (sdl == NULL ||
345					    (sdl->sdl_type != IFT_ETHER &&
346					    sdl->sdl_type != IFT_L2VLAN &&
347					    sdl->sdl_type != IFT_BRIDGE) ||
348					    sdl->sdl_alen != ETHER_ADDR_LEN)
349						continue;
350				} else {
351					if (ifa->ifa_addr->sa_family != afp->af_af)
352						continue;
353				}
354			}
355			namecp = cp;
356			ifindex++;
357			if (ifindex > 1)
358				printf(" ");
359			fputs(name, stdout);
360			continue;
361		}
362		ifindex++;
363
364		if (argc > 0)
365			ifconfig(argc, argv, 0, afp);
366		else
367			status(afp, sdl, ifa);
368	}
369	if (namesonly)
370		printf("\n");
371	freeifaddrs(ifap);
372
373	exit(0);
374}
375
376static struct afswtch *afs = NULL;
377
378void
379af_register(struct afswtch *p)
380{
381	p->af_next = afs;
382	afs = p;
383}
384
385static struct afswtch *
386af_getbyname(const char *name)
387{
388	struct afswtch *afp;
389
390	for (afp = afs; afp !=  NULL; afp = afp->af_next)
391		if (strcmp(afp->af_name, name) == 0)
392			return afp;
393	return NULL;
394}
395
396static struct afswtch *
397af_getbyfamily(int af)
398{
399	struct afswtch *afp;
400
401	for (afp = afs; afp != NULL; afp = afp->af_next)
402		if (afp->af_af == af)
403			return afp;
404	return NULL;
405}
406
407static void
408af_other_status(int s)
409{
410	struct afswtch *afp;
411	uint8_t afmask[howmany(AF_MAX, NBBY)];
412
413	memset(afmask, 0, sizeof(afmask));
414	for (afp = afs; afp != NULL; afp = afp->af_next) {
415		if (afp->af_other_status == NULL)
416			continue;
417		if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
418			continue;
419		afp->af_other_status(s);
420		setbit(afmask, afp->af_af);
421	}
422}
423
424static void
425af_all_tunnel_status(int s)
426{
427	struct afswtch *afp;
428	uint8_t afmask[howmany(AF_MAX, NBBY)];
429
430	memset(afmask, 0, sizeof(afmask));
431	for (afp = afs; afp != NULL; afp = afp->af_next) {
432		if (afp->af_status_tunnel == NULL)
433			continue;
434		if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
435			continue;
436		afp->af_status_tunnel(s);
437		setbit(afmask, afp->af_af);
438	}
439}
440
441static struct cmd *cmds = NULL;
442
443void
444cmd_register(struct cmd *p)
445{
446	p->c_next = cmds;
447	cmds = p;
448}
449
450static const struct cmd *
451cmd_lookup(const char *name, int iscreate)
452{
453	const struct cmd *p;
454
455	for (p = cmds; p != NULL; p = p->c_next)
456		if (strcmp(name, p->c_name) == 0) {
457			if (iscreate) {
458				if (p->c_iscloneop)
459					return p;
460			} else {
461				if (!p->c_iscloneop)
462					return p;
463			}
464		}
465	return NULL;
466}
467
468struct callback {
469	callback_func *cb_func;
470	void	*cb_arg;
471	struct callback *cb_next;
472};
473static struct callback *callbacks = NULL;
474
475void
476callback_register(callback_func *func, void *arg)
477{
478	struct callback *cb;
479
480	cb = malloc(sizeof(struct callback));
481	if (cb == NULL)
482		errx(1, "unable to allocate memory for callback");
483	cb->cb_func = func;
484	cb->cb_arg = arg;
485	cb->cb_next = callbacks;
486	callbacks = cb;
487}
488
489/* specially-handled commands */
490static void setifaddr(const char *, int, int, const struct afswtch *);
491static const struct cmd setifaddr_cmd = DEF_CMD("ifaddr", 0, setifaddr);
492
493static void setifdstaddr(const char *, int, int, const struct afswtch *);
494static const struct cmd setifdstaddr_cmd =
495	DEF_CMD("ifdstaddr", 0, setifdstaddr);
496
497static int
498ifconfig(int argc, char *const *argv, int iscreate, const struct afswtch *uafp)
499{
500	const struct afswtch *afp, *nafp;
501	const struct cmd *p;
502	struct callback *cb;
503	int s;
504
505	strlcpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
506	afp = NULL;
507	if (uafp != NULL)
508		afp = uafp;
509	/*
510	 * This is the historical "accident" allowing users to configure IPv4
511	 * addresses without the "inet" keyword which while a nice feature has
512	 * proven to complicate other things.  We cannot remove this but only
513	 * make sure we will never have a similar implicit default for IPv6 or
514	 * any other address familiy.  We need a fallback though for
515	 * ifconfig IF up/down etc. to work without INET support as people
516	 * never used ifconfig IF link up/down, etc. either.
517	 */
518#ifndef RESCUE
519#ifdef INET
520	if (afp == NULL && feature_present("inet"))
521		afp = af_getbyname("inet");
522#endif
523#endif
524	if (afp == NULL)
525		afp = af_getbyname("link");
526	if (afp == NULL) {
527		warnx("Please specify an address_family.");
528		usage();
529	}
530top:
531	ifr.ifr_addr.sa_family =
532		afp->af_af == AF_LINK || afp->af_af == AF_UNSPEC ?
533		AF_LOCAL : afp->af_af;
534
535	if ((s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0)) < 0 &&
536	    (uafp != NULL || errno != EAFNOSUPPORT ||
537	     (s = socket(AF_LOCAL, SOCK_DGRAM, 0)) < 0))
538		err(1, "socket(family %u,SOCK_DGRAM", ifr.ifr_addr.sa_family);
539
540	while (argc > 0) {
541		p = cmd_lookup(*argv, iscreate);
542		if (iscreate && p == NULL) {
543			/*
544			 * Push the clone create callback so the new
545			 * device is created and can be used for any
546			 * remaining arguments.
547			 */
548			cb = callbacks;
549			if (cb == NULL)
550				errx(1, "internal error, no callback");
551			callbacks = cb->cb_next;
552			cb->cb_func(s, cb->cb_arg);
553			iscreate = 0;
554			/*
555			 * Handle any address family spec that
556			 * immediately follows and potentially
557			 * recreate the socket.
558			 */
559			nafp = af_getbyname(*argv);
560			if (nafp != NULL) {
561				argc--, argv++;
562				if (nafp != afp) {
563					close(s);
564					afp = nafp;
565					goto top;
566				}
567			}
568			/*
569			 * Look for a normal parameter.
570			 */
571			continue;
572		}
573		if (p == NULL) {
574			/*
575			 * Not a recognized command, choose between setting
576			 * the interface address and the dst address.
577			 */
578			p = (setaddr ? &setifdstaddr_cmd : &setifaddr_cmd);
579		}
580		if (p->c_parameter == NEXTARG && p->c_u.c_func) {
581			if (argv[1] == NULL)
582				errx(1, "'%s' requires argument",
583				    p->c_name);
584			p->c_u.c_func(argv[1], 0, s, afp);
585			argc--, argv++;
586		} else if (p->c_parameter == OPTARG && p->c_u.c_func) {
587			p->c_u.c_func(argv[1], 0, s, afp);
588			if (argv[1] != NULL)
589				argc--, argv++;
590		} else if (p->c_parameter == NEXTARG2 && p->c_u.c_func2) {
591			if (argc < 3)
592				errx(1, "'%s' requires 2 arguments",
593				    p->c_name);
594			p->c_u.c_func2(argv[1], argv[2], s, afp);
595			argc -= 2, argv += 2;
596		} else if (p->c_u.c_func)
597			p->c_u.c_func(*argv, p->c_parameter, s, afp);
598		argc--, argv++;
599	}
600
601	/*
602	 * Do any post argument processing required by the address family.
603	 */
604	if (afp->af_postproc != NULL)
605		afp->af_postproc(s, afp);
606	/*
607	 * Do deferred callbacks registered while processing
608	 * command-line arguments.
609	 */
610	for (cb = callbacks; cb != NULL; cb = cb->cb_next)
611		cb->cb_func(s, cb->cb_arg);
612	/*
613	 * Do deferred operations.
614	 */
615	if (clearaddr) {
616		if (afp->af_ridreq == NULL || afp->af_difaddr == 0) {
617			warnx("interface %s cannot change %s addresses!",
618			      name, afp->af_name);
619			clearaddr = 0;
620		}
621	}
622	if (clearaddr) {
623		int ret;
624		strlcpy(((struct ifreq *)afp->af_ridreq)->ifr_name, name,
625			sizeof ifr.ifr_name);
626		ret = ioctl(s, afp->af_difaddr, afp->af_ridreq);
627		if (ret < 0) {
628			if (errno == EADDRNOTAVAIL && (doalias >= 0)) {
629				/* means no previous address for interface */
630			} else
631				Perror("ioctl (SIOCDIFADDR)");
632		}
633	}
634	if (newaddr) {
635		if (afp->af_addreq == NULL || afp->af_aifaddr == 0) {
636			warnx("interface %s cannot change %s addresses!",
637			      name, afp->af_name);
638			newaddr = 0;
639		}
640	}
641	if (newaddr && (setaddr || setmask)) {
642		strlcpy(((struct ifreq *)afp->af_addreq)->ifr_name, name,
643			sizeof ifr.ifr_name);
644		if (ioctl(s, afp->af_aifaddr, afp->af_addreq) < 0)
645			Perror("ioctl (SIOCAIFADDR)");
646	}
647
648	close(s);
649	return(0);
650}
651
652/*ARGSUSED*/
653static void
654setifaddr(const char *addr, int param, int s, const struct afswtch *afp)
655{
656	if (afp->af_getaddr == NULL)
657		return;
658	/*
659	 * Delay the ioctl to set the interface addr until flags are all set.
660	 * The address interpretation may depend on the flags,
661	 * and the flags may change when the address is set.
662	 */
663	setaddr++;
664	if (doalias == 0 && afp->af_af != AF_LINK)
665		clearaddr = 1;
666	afp->af_getaddr(addr, (doalias >= 0 ? ADDR : RIDADDR));
667}
668
669static void
670settunnel(const char *src, const char *dst, int s, const struct afswtch *afp)
671{
672	struct addrinfo *srcres, *dstres;
673	int ecode;
674
675	if (afp->af_settunnel == NULL) {
676		warn("address family %s does not support tunnel setup",
677			afp->af_name);
678		return;
679	}
680
681	if ((ecode = getaddrinfo(src, NULL, NULL, &srcres)) != 0)
682		errx(1, "error in parsing address string: %s",
683		    gai_strerror(ecode));
684
685	if ((ecode = getaddrinfo(dst, NULL, NULL, &dstres)) != 0)
686		errx(1, "error in parsing address string: %s",
687		    gai_strerror(ecode));
688
689	if (srcres->ai_addr->sa_family != dstres->ai_addr->sa_family)
690		errx(1,
691		    "source and destination address families do not match");
692
693	afp->af_settunnel(s, srcres, dstres);
694
695	freeaddrinfo(srcres);
696	freeaddrinfo(dstres);
697}
698
699/* ARGSUSED */
700static void
701deletetunnel(const char *vname, int param, int s, const struct afswtch *afp)
702{
703
704	if (ioctl(s, SIOCDIFPHYADDR, &ifr) < 0)
705		err(1, "SIOCDIFPHYADDR");
706}
707
708#ifdef JAIL
709static void
710setifvnet(const char *jname, int dummy __unused, int s,
711    const struct afswtch *afp)
712{
713	struct ifreq my_ifr;
714
715	memcpy(&my_ifr, &ifr, sizeof(my_ifr));
716	my_ifr.ifr_jid = jail_getid(jname);
717	if (my_ifr.ifr_jid < 0)
718		errx(1, "%s", jail_errmsg);
719	if (ioctl(s, SIOCSIFVNET, &my_ifr) < 0)
720		err(1, "SIOCSIFVNET");
721}
722
723static void
724setifrvnet(const char *jname, int dummy __unused, int s,
725    const struct afswtch *afp)
726{
727	struct ifreq my_ifr;
728
729	memcpy(&my_ifr, &ifr, sizeof(my_ifr));
730	my_ifr.ifr_jid = jail_getid(jname);
731	if (my_ifr.ifr_jid < 0)
732		errx(1, "%s", jail_errmsg);
733	if (ioctl(s, SIOCSIFRVNET, &my_ifr) < 0)
734		err(1, "SIOCSIFRVNET(%d, %s)", my_ifr.ifr_jid, my_ifr.ifr_name);
735}
736#endif
737
738static void
739setifnetmask(const char *addr, int dummy __unused, int s,
740    const struct afswtch *afp)
741{
742	if (afp->af_getaddr != NULL) {
743		setmask++;
744		afp->af_getaddr(addr, MASK);
745	}
746}
747
748static void
749setifbroadaddr(const char *addr, int dummy __unused, int s,
750    const struct afswtch *afp)
751{
752	if (afp->af_getaddr != NULL)
753		afp->af_getaddr(addr, DSTADDR);
754}
755
756static void
757setifipdst(const char *addr, int dummy __unused, int s,
758    const struct afswtch *afp)
759{
760	const struct afswtch *inet;
761
762	inet = af_getbyname("inet");
763	if (inet == NULL)
764		return;
765	inet->af_getaddr(addr, DSTADDR);
766	clearaddr = 0;
767	newaddr = 0;
768}
769
770static void
771notealias(const char *addr, int param, int s, const struct afswtch *afp)
772{
773#define rqtosa(x) (&(((struct ifreq *)(afp->x))->ifr_addr))
774	if (setaddr && doalias == 0 && param < 0)
775		if (afp->af_addreq != NULL && afp->af_ridreq != NULL)
776			bcopy((caddr_t)rqtosa(af_addreq),
777			      (caddr_t)rqtosa(af_ridreq),
778			      rqtosa(af_addreq)->sa_len);
779	doalias = param;
780	if (param < 0) {
781		clearaddr = 1;
782		newaddr = 0;
783	} else
784		clearaddr = 0;
785#undef rqtosa
786}
787
788/*ARGSUSED*/
789static void
790setifdstaddr(const char *addr, int param __unused, int s,
791    const struct afswtch *afp)
792{
793	if (afp->af_getaddr != NULL)
794		afp->af_getaddr(addr, DSTADDR);
795}
796
797/*
798 * Note: doing an SIOCIGIFFLAGS scribbles on the union portion
799 * of the ifreq structure, which may confuse other parts of ifconfig.
800 * Make a private copy so we can avoid that.
801 */
802static void
803setifflags(const char *vname, int value, int s, const struct afswtch *afp)
804{
805	struct ifreq		my_ifr;
806	int flags;
807
808	memset(&my_ifr, 0, sizeof(my_ifr));
809	(void) strlcpy(my_ifr.ifr_name, name, sizeof(my_ifr.ifr_name));
810
811 	if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&my_ifr) < 0) {
812 		Perror("ioctl (SIOCGIFFLAGS)");
813 		exit(1);
814 	}
815	flags = (my_ifr.ifr_flags & 0xffff) | (my_ifr.ifr_flagshigh << 16);
816
817	if (value < 0) {
818		value = -value;
819		flags &= ~value;
820	} else
821		flags |= value;
822	my_ifr.ifr_flags = flags & 0xffff;
823	my_ifr.ifr_flagshigh = flags >> 16;
824	if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&my_ifr) < 0)
825		Perror(vname);
826}
827
828void
829setifcap(const char *vname, int value, int s, const struct afswtch *afp)
830{
831	int flags;
832
833 	if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) < 0) {
834 		Perror("ioctl (SIOCGIFCAP)");
835 		exit(1);
836 	}
837	flags = ifr.ifr_curcap;
838	if (value < 0) {
839		value = -value;
840		flags &= ~value;
841	} else
842		flags |= value;
843	flags &= ifr.ifr_reqcap;
844	ifr.ifr_reqcap = flags;
845	if (ioctl(s, SIOCSIFCAP, (caddr_t)&ifr) < 0)
846		Perror(vname);
847}
848
849static void
850setifmetric(const char *val, int dummy __unused, int s,
851    const struct afswtch *afp)
852{
853	strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
854	ifr.ifr_metric = atoi(val);
855	if (ioctl(s, SIOCSIFMETRIC, (caddr_t)&ifr) < 0)
856		err(1, "ioctl SIOCSIFMETRIC (set metric)");
857}
858
859static void
860setifmtu(const char *val, int dummy __unused, int s,
861    const struct afswtch *afp)
862{
863	strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
864	ifr.ifr_mtu = atoi(val);
865	if (ioctl(s, SIOCSIFMTU, (caddr_t)&ifr) < 0)
866		err(1, "ioctl SIOCSIFMTU (set mtu)");
867}
868
869static void
870setifname(const char *val, int dummy __unused, int s,
871    const struct afswtch *afp)
872{
873	char *newname;
874
875	strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
876
877	newname = strdup(val);
878	if (newname == NULL)
879		err(1, "no memory to set ifname");
880	ifr.ifr_data = newname;
881	if (ioctl(s, SIOCSIFNAME, (caddr_t)&ifr) < 0) {
882		free(newname);
883		err(1, "ioctl SIOCSIFNAME (set name)");
884	}
885	printifname = 1;
886	strlcpy(name, newname, sizeof(name));
887	free(newname);
888}
889
890/* ARGSUSED */
891static void
892setifdescr(const char *val, int dummy __unused, int s,
893    const struct afswtch *afp)
894{
895	char *newdescr;
896
897	strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
898
899	ifr.ifr_buffer.length = strlen(val) + 1;
900	if (ifr.ifr_buffer.length == 1) {
901		ifr.ifr_buffer.buffer = newdescr = NULL;
902		ifr.ifr_buffer.length = 0;
903	} else {
904		newdescr = strdup(val);
905		ifr.ifr_buffer.buffer = newdescr;
906		if (newdescr == NULL) {
907			warn("no memory to set ifdescr");
908			return;
909		}
910	}
911
912	if (ioctl(s, SIOCSIFDESCR, (caddr_t)&ifr) < 0)
913		err(1, "ioctl SIOCSIFDESCR (set descr)");
914
915	free(newdescr);
916}
917
918/* ARGSUSED */
919static void
920unsetifdescr(const char *val, int value, int s, const struct afswtch *afp)
921{
922
923	setifdescr("", 0, s, 0);
924}
925
926#define	IFFBITS \
927"\020\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5POINTOPOINT\6SMART\7RUNNING" \
928"\10NOARP\11PROMISC\12ALLMULTI\13OACTIVE\14SIMPLEX\15LINK0\16LINK1\17LINK2" \
929"\20MULTICAST\22PPROMISC\23MONITOR\24STATICARP"
930
931#define	IFCAPBITS \
932"\020\1RXCSUM\2TXCSUM\3NETCONS\4VLAN_MTU\5VLAN_HWTAGGING\6JUMBO_MTU\7POLLING" \
933"\10VLAN_HWCSUM\11TSO4\12TSO6\13LRO\14WOL_UCAST\15WOL_MCAST\16WOL_MAGIC" \
934"\17TOE4\20TOE6\21VLAN_HWFILTER\23VLAN_HWTSO\24LINKSTATE\25NETMAP" \
935"\26RXCSUM_IPV6\27TXCSUM_IPV6"
936
937/*
938 * Print the status of the interface.  If an address family was
939 * specified, show only it; otherwise, show them all.
940 */
941static void
942status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
943	struct ifaddrs *ifa)
944{
945	struct ifaddrs *ift;
946	int allfamilies, s;
947	struct ifstat ifs;
948
949	if (afp == NULL) {
950		allfamilies = 1;
951		ifr.ifr_addr.sa_family = AF_LOCAL;
952	} else {
953		allfamilies = 0;
954		ifr.ifr_addr.sa_family =
955		    afp->af_af == AF_LINK ? AF_LOCAL : afp->af_af;
956	}
957	strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
958
959	s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0);
960	if (s < 0)
961		err(1, "socket(family %u,SOCK_DGRAM)", ifr.ifr_addr.sa_family);
962
963	printf("%s: ", name);
964	printb("flags", ifa->ifa_flags, IFFBITS);
965	if (ioctl(s, SIOCGIFMETRIC, &ifr) != -1)
966		printf(" metric %d", ifr.ifr_metric);
967	if (ioctl(s, SIOCGIFMTU, &ifr) != -1)
968		printf(" mtu %d", ifr.ifr_mtu);
969	putchar('\n');
970
971	for (;;) {
972		if ((descr = reallocf(descr, descrlen)) != NULL) {
973			ifr.ifr_buffer.buffer = descr;
974			ifr.ifr_buffer.length = descrlen;
975			if (ioctl(s, SIOCGIFDESCR, &ifr) == 0) {
976				if (ifr.ifr_buffer.buffer == descr) {
977					if (strlen(descr) > 0)
978						printf("\tdescription: %s\n",
979						    descr);
980				} else if (ifr.ifr_buffer.length > descrlen) {
981					descrlen = ifr.ifr_buffer.length;
982					continue;
983				}
984			}
985		} else
986			warn("unable to allocate memory for interface"
987			    "description");
988		break;
989	}
990
991	if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) == 0) {
992		if (ifr.ifr_curcap != 0) {
993			printb("\toptions", ifr.ifr_curcap, IFCAPBITS);
994			putchar('\n');
995		}
996		if (supmedia && ifr.ifr_reqcap != 0) {
997			printb("\tcapabilities", ifr.ifr_reqcap, IFCAPBITS);
998			putchar('\n');
999		}
1000	}
1001
1002	tunnel_status(s);
1003
1004	for (ift = ifa; ift != NULL; ift = ift->ifa_next) {
1005		if (ift->ifa_addr == NULL)
1006			continue;
1007		if (strcmp(ifa->ifa_name, ift->ifa_name) != 0)
1008			continue;
1009		if (allfamilies) {
1010			const struct afswtch *p;
1011			p = af_getbyfamily(ift->ifa_addr->sa_family);
1012			if (p != NULL && p->af_status != NULL)
1013				p->af_status(s, ift);
1014		} else if (afp->af_af == ift->ifa_addr->sa_family)
1015			afp->af_status(s, ift);
1016	}
1017#if 0
1018	if (allfamilies || afp->af_af == AF_LINK) {
1019		const struct afswtch *lafp;
1020
1021		/*
1022		 * Hack; the link level address is received separately
1023		 * from the routing information so any address is not
1024		 * handled above.  Cobble together an entry and invoke
1025		 * the status method specially.
1026		 */
1027		lafp = af_getbyname("lladdr");
1028		if (lafp != NULL) {
1029			info.rti_info[RTAX_IFA] = (struct sockaddr *)sdl;
1030			lafp->af_status(s, &info);
1031		}
1032	}
1033#endif
1034	if (allfamilies)
1035		af_other_status(s);
1036	else if (afp->af_other_status != NULL)
1037		afp->af_other_status(s);
1038
1039	strlcpy(ifs.ifs_name, name, sizeof ifs.ifs_name);
1040	if (ioctl(s, SIOCGIFSTATUS, &ifs) == 0)
1041		printf("%s", ifs.ascii);
1042
1043	if (verbose > 0)
1044		sfp_status(s, &ifr, verbose);
1045
1046	close(s);
1047	return;
1048}
1049
1050static void
1051tunnel_status(int s)
1052{
1053	af_all_tunnel_status(s);
1054}
1055
1056void
1057Perror(const char *cmd)
1058{
1059	switch (errno) {
1060
1061	case ENXIO:
1062		errx(1, "%s: no such interface", cmd);
1063		break;
1064
1065	case EPERM:
1066		errx(1, "%s: permission denied", cmd);
1067		break;
1068
1069	default:
1070		err(1, "%s", cmd);
1071	}
1072}
1073
1074/*
1075 * Print a value a la the %b format of the kernel's printf
1076 */
1077void
1078printb(const char *s, unsigned v, const char *bits)
1079{
1080	int i, any = 0;
1081	char c;
1082
1083	if (bits && *bits == 8)
1084		printf("%s=%o", s, v);
1085	else
1086		printf("%s=%x", s, v);
1087	if (bits) {
1088		bits++;
1089		putchar('<');
1090		while ((i = *bits++) != '\0') {
1091			if (v & (1 << (i-1))) {
1092				if (any)
1093					putchar(',');
1094				any = 1;
1095				for (; (c = *bits) > 32; bits++)
1096					putchar(c);
1097			} else
1098				for (; *bits > 32; bits++)
1099					;
1100		}
1101		putchar('>');
1102	}
1103}
1104
1105void
1106print_vhid(const struct ifaddrs *ifa, const char *s)
1107{
1108	struct if_data *ifd;
1109
1110	if (ifa->ifa_data == NULL)
1111		return;
1112
1113	ifd = ifa->ifa_data;
1114	if (ifd->ifi_vhid == 0)
1115		return;
1116
1117	printf("vhid %d ", ifd->ifi_vhid);
1118}
1119
1120void
1121ifmaybeload(const char *name)
1122{
1123#define MOD_PREFIX_LEN		3	/* "if_" */
1124	struct module_stat mstat;
1125	int fileid, modid;
1126	char ifkind[IFNAMSIZ + MOD_PREFIX_LEN], ifname[IFNAMSIZ], *dp;
1127	const char *cp;
1128
1129	/* loading suppressed by the user */
1130	if (noload)
1131		return;
1132
1133	/* trim the interface number off the end */
1134	strlcpy(ifname, name, sizeof(ifname));
1135	for (dp = ifname; *dp != 0; dp++)
1136		if (isdigit(*dp)) {
1137			*dp = 0;
1138			break;
1139		}
1140
1141	/* turn interface and unit into module name */
1142	strlcpy(ifkind, "if_", sizeof(ifkind));
1143	strlcat(ifkind, ifname, sizeof(ifkind));
1144
1145	/* scan files in kernel */
1146	mstat.version = sizeof(struct module_stat);
1147	for (fileid = kldnext(0); fileid > 0; fileid = kldnext(fileid)) {
1148		/* scan modules in file */
1149		for (modid = kldfirstmod(fileid); modid > 0;
1150		     modid = modfnext(modid)) {
1151			if (modstat(modid, &mstat) < 0)
1152				continue;
1153			/* strip bus name if present */
1154			if ((cp = strchr(mstat.name, '/')) != NULL) {
1155				cp++;
1156			} else {
1157				cp = mstat.name;
1158			}
1159			/* already loaded? */
1160			if (strcmp(ifname, cp) == 0 ||
1161			    strcmp(ifkind, cp) == 0)
1162				return;
1163		}
1164	}
1165
1166	/*
1167	 * Try to load the module.  But ignore failures, because ifconfig can't
1168	 * infer the names of all drivers (eg mlx4en(4)).
1169	 */
1170	(void) kldload(ifkind);
1171}
1172
1173static struct cmd basic_cmds[] = {
1174	DEF_CMD("up",		IFF_UP,		setifflags),
1175	DEF_CMD("down",		-IFF_UP,	setifflags),
1176	DEF_CMD("arp",		-IFF_NOARP,	setifflags),
1177	DEF_CMD("-arp",		IFF_NOARP,	setifflags),
1178	DEF_CMD("debug",	IFF_DEBUG,	setifflags),
1179	DEF_CMD("-debug",	-IFF_DEBUG,	setifflags),
1180	DEF_CMD_ARG("description",		setifdescr),
1181	DEF_CMD_ARG("descr",			setifdescr),
1182	DEF_CMD("-description",	0,		unsetifdescr),
1183	DEF_CMD("-descr",	0,		unsetifdescr),
1184	DEF_CMD("promisc",	IFF_PPROMISC,	setifflags),
1185	DEF_CMD("-promisc",	-IFF_PPROMISC,	setifflags),
1186	DEF_CMD("add",		IFF_UP,		notealias),
1187	DEF_CMD("alias",	IFF_UP,		notealias),
1188	DEF_CMD("-alias",	-IFF_UP,	notealias),
1189	DEF_CMD("delete",	-IFF_UP,	notealias),
1190	DEF_CMD("remove",	-IFF_UP,	notealias),
1191#ifdef notdef
1192#define	EN_SWABIPS	0x1000
1193	DEF_CMD("swabips",	EN_SWABIPS,	setifflags),
1194	DEF_CMD("-swabips",	-EN_SWABIPS,	setifflags),
1195#endif
1196	DEF_CMD_ARG("netmask",			setifnetmask),
1197	DEF_CMD_ARG("metric",			setifmetric),
1198	DEF_CMD_ARG("broadcast",		setifbroadaddr),
1199	DEF_CMD_ARG("ipdst",			setifipdst),
1200	DEF_CMD_ARG2("tunnel",			settunnel),
1201	DEF_CMD("-tunnel", 0,			deletetunnel),
1202	DEF_CMD("deletetunnel", 0,		deletetunnel),
1203#ifdef JAIL
1204	DEF_CMD_ARG("vnet",			setifvnet),
1205	DEF_CMD_ARG("-vnet",			setifrvnet),
1206#endif
1207	DEF_CMD("link0",	IFF_LINK0,	setifflags),
1208	DEF_CMD("-link0",	-IFF_LINK0,	setifflags),
1209	DEF_CMD("link1",	IFF_LINK1,	setifflags),
1210	DEF_CMD("-link1",	-IFF_LINK1,	setifflags),
1211	DEF_CMD("link2",	IFF_LINK2,	setifflags),
1212	DEF_CMD("-link2",	-IFF_LINK2,	setifflags),
1213	DEF_CMD("monitor",	IFF_MONITOR,	setifflags),
1214	DEF_CMD("-monitor",	-IFF_MONITOR,	setifflags),
1215	DEF_CMD("staticarp",	IFF_STATICARP,	setifflags),
1216	DEF_CMD("-staticarp",	-IFF_STATICARP,	setifflags),
1217	DEF_CMD("rxcsum6",	IFCAP_RXCSUM_IPV6,	setifcap),
1218	DEF_CMD("-rxcsum6",	-IFCAP_RXCSUM_IPV6,	setifcap),
1219	DEF_CMD("txcsum6",	IFCAP_TXCSUM_IPV6,	setifcap),
1220	DEF_CMD("-txcsum6",	-IFCAP_TXCSUM_IPV6,	setifcap),
1221	DEF_CMD("rxcsum",	IFCAP_RXCSUM,	setifcap),
1222	DEF_CMD("-rxcsum",	-IFCAP_RXCSUM,	setifcap),
1223	DEF_CMD("txcsum",	IFCAP_TXCSUM,	setifcap),
1224	DEF_CMD("-txcsum",	-IFCAP_TXCSUM,	setifcap),
1225	DEF_CMD("netcons",	IFCAP_NETCONS,	setifcap),
1226	DEF_CMD("-netcons",	-IFCAP_NETCONS,	setifcap),
1227	DEF_CMD("polling",	IFCAP_POLLING,	setifcap),
1228	DEF_CMD("-polling",	-IFCAP_POLLING,	setifcap),
1229	DEF_CMD("tso6",		IFCAP_TSO6,	setifcap),
1230	DEF_CMD("-tso6",	-IFCAP_TSO6,	setifcap),
1231	DEF_CMD("tso4",		IFCAP_TSO4,	setifcap),
1232	DEF_CMD("-tso4",	-IFCAP_TSO4,	setifcap),
1233	DEF_CMD("tso",		IFCAP_TSO,	setifcap),
1234	DEF_CMD("-tso",		-IFCAP_TSO,	setifcap),
1235	DEF_CMD("toe",		IFCAP_TOE,	setifcap),
1236	DEF_CMD("-toe",		-IFCAP_TOE,	setifcap),
1237	DEF_CMD("lro",		IFCAP_LRO,	setifcap),
1238	DEF_CMD("-lro",		-IFCAP_LRO,	setifcap),
1239	DEF_CMD("wol",		IFCAP_WOL,	setifcap),
1240	DEF_CMD("-wol",		-IFCAP_WOL,	setifcap),
1241	DEF_CMD("wol_ucast",	IFCAP_WOL_UCAST,	setifcap),
1242	DEF_CMD("-wol_ucast",	-IFCAP_WOL_UCAST,	setifcap),
1243	DEF_CMD("wol_mcast",	IFCAP_WOL_MCAST,	setifcap),
1244	DEF_CMD("-wol_mcast",	-IFCAP_WOL_MCAST,	setifcap),
1245	DEF_CMD("wol_magic",	IFCAP_WOL_MAGIC,	setifcap),
1246	DEF_CMD("-wol_magic",	-IFCAP_WOL_MAGIC,	setifcap),
1247	DEF_CMD("normal",	-IFF_LINK0,	setifflags),
1248	DEF_CMD("compress",	IFF_LINK0,	setifflags),
1249	DEF_CMD("noicmp",	IFF_LINK1,	setifflags),
1250	DEF_CMD_ARG("mtu",			setifmtu),
1251	DEF_CMD_ARG("name",			setifname),
1252};
1253
1254static __constructor void
1255ifconfig_ctor(void)
1256{
1257	size_t i;
1258
1259	for (i = 0; i < nitems(basic_cmds);  i++)
1260		cmd_register(&basic_cmds[i]);
1261}
1262