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