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