]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sbin/ifconfig/ifconfig.c
MFC r299873
[FreeBSD/stable/10.git] / sbin / ifconfig / ifconfig.c
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
31 static 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
38 static char sccsid[] = "@(#)ifconfig.c  8.2 (Berkeley) 2/16/94";
39 #endif
40 static const char rcsid[] =
41   "$FreeBSD$";
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  */
84 struct  ifreq ifr;
85
86 char    name[IFNAMSIZ];
87 char    *descr = NULL;
88 size_t  descrlen = 64;
89 int     setaddr;
90 int     setmask;
91 int     doalias;
92 int     clearaddr;
93 int     newaddr = 1;
94 int     verbose;
95 int     noload;
96 int     printifname = 0;
97
98 int     supmedia = 0;
99 int     printkeys = 0;          /* Print keying material for interfaces. */
100
101 static  int ifconfig(int argc, char *const *argv, int iscreate,
102                 const struct afswtch *afp);
103 static  void status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
104                 struct ifaddrs *ifa);
105 static  void tunnel_status(int s);
106 static  void usage(void);
107
108 static struct afswtch *af_getbyname(const char *name);
109 static struct afswtch *af_getbyfamily(int af);
110 static void af_other_status(int);
111
112 void printifnamemaybe(void);
113
114 static struct option *opts = NULL;
115
116 void
117 opt_register(struct option *p)
118 {
119         p->next = opts;
120         opts = p;
121 }
122
123 static void
124 usage(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
147 void printifnamemaybe()
148 {
149         if (printifname)
150                 printf("%s\n", name);
151 }
152
153 int
154 main(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
376 static struct afswtch *afs = NULL;
377
378 void
379 af_register(struct afswtch *p)
380 {
381         p->af_next = afs;
382         afs = p;
383 }
384
385 static struct afswtch *
386 af_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
396 static struct afswtch *
397 af_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
407 static void
408 af_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
424 static void
425 af_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
441 static struct cmd *cmds = NULL;
442
443 void
444 cmd_register(struct cmd *p)
445 {
446         p->c_next = cmds;
447         cmds = p;
448 }
449
450 static const struct cmd *
451 cmd_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
468 struct callback {
469         callback_func *cb_func;
470         void    *cb_arg;
471         struct callback *cb_next;
472 };
473 static struct callback *callbacks = NULL;
474
475 void
476 callback_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 */
490 static void setifaddr(const char *, int, int, const struct afswtch *);
491 static const struct cmd setifaddr_cmd = DEF_CMD("ifaddr", 0, setifaddr);
492
493 static void setifdstaddr(const char *, int, int, const struct afswtch *);
494 static const struct cmd setifdstaddr_cmd =
495         DEF_CMD("ifdstaddr", 0, setifdstaddr);
496
497 static int
498 ifconfig(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         }
530 top:
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_u.c_func || p->c_u.c_func2) {
581                         if (p->c_parameter == NEXTARG) {
582                                 if (argv[1] == NULL)
583                                         errx(1, "'%s' requires argument",
584                                             p->c_name);
585                                 p->c_u.c_func(argv[1], 0, s, afp);
586                                 argc--, argv++;
587                         } else if (p->c_parameter == OPTARG) {
588                                 p->c_u.c_func(argv[1], 0, s, afp);
589                                 if (argv[1] != NULL)
590                                         argc--, argv++;
591                         } else if (p->c_parameter == NEXTARG2) {
592                                 if (argc < 3)
593                                         errx(1, "'%s' requires 2 arguments",
594                                             p->c_name);
595                                 p->c_u.c_func2(argv[1], argv[2], s, afp);
596                                 argc -= 2, argv += 2;
597                         } else
598                                 p->c_u.c_func(*argv, p->c_parameter, s, afp);
599                 }
600                 argc--, argv++;
601         }
602
603         /*
604          * Do any post argument processing required by the address family.
605          */
606         if (afp->af_postproc != NULL)
607                 afp->af_postproc(s, afp);
608         /*
609          * Do deferred callbacks registered while processing
610          * command-line arguments.
611          */
612         for (cb = callbacks; cb != NULL; cb = cb->cb_next)
613                 cb->cb_func(s, cb->cb_arg);
614         /*
615          * Do deferred operations.
616          */
617         if (clearaddr) {
618                 if (afp->af_ridreq == NULL || afp->af_difaddr == 0) {
619                         warnx("interface %s cannot change %s addresses!",
620                               name, afp->af_name);
621                         clearaddr = 0;
622                 }
623         }
624         if (clearaddr) {
625                 int ret;
626                 strlcpy(((struct ifreq *)afp->af_ridreq)->ifr_name, name,
627                         sizeof ifr.ifr_name);
628                 ret = ioctl(s, afp->af_difaddr, afp->af_ridreq);
629                 if (ret < 0) {
630                         if (errno == EADDRNOTAVAIL && (doalias >= 0)) {
631                                 /* means no previous address for interface */
632                         } else
633                                 Perror("ioctl (SIOCDIFADDR)");
634                 }
635         }
636         if (newaddr) {
637                 if (afp->af_addreq == NULL || afp->af_aifaddr == 0) {
638                         warnx("interface %s cannot change %s addresses!",
639                               name, afp->af_name);
640                         newaddr = 0;
641                 }
642         }
643         if (newaddr && (setaddr || setmask)) {
644                 strlcpy(((struct ifreq *)afp->af_addreq)->ifr_name, name,
645                         sizeof ifr.ifr_name);
646                 if (ioctl(s, afp->af_aifaddr, afp->af_addreq) < 0)
647                         Perror("ioctl (SIOCAIFADDR)");
648         }
649
650         close(s);
651         return(0);
652 }
653
654 /*ARGSUSED*/
655 static void
656 setifaddr(const char *addr, int param, int s, const struct afswtch *afp)
657 {
658         if (afp->af_getaddr == NULL)
659                 return;
660         /*
661          * Delay the ioctl to set the interface addr until flags are all set.
662          * The address interpretation may depend on the flags,
663          * and the flags may change when the address is set.
664          */
665         setaddr++;
666         if (doalias == 0 && afp->af_af != AF_LINK)
667                 clearaddr = 1;
668         afp->af_getaddr(addr, (doalias >= 0 ? ADDR : RIDADDR));
669 }
670
671 static void
672 settunnel(const char *src, const char *dst, int s, const struct afswtch *afp)
673 {
674         struct addrinfo *srcres, *dstres;
675         int ecode;
676
677         if (afp->af_settunnel == NULL) {
678                 warn("address family %s does not support tunnel setup",
679                         afp->af_name);
680                 return;
681         }
682
683         if ((ecode = getaddrinfo(src, NULL, NULL, &srcres)) != 0)
684                 errx(1, "error in parsing address string: %s",
685                     gai_strerror(ecode));
686
687         if ((ecode = getaddrinfo(dst, NULL, NULL, &dstres)) != 0)  
688                 errx(1, "error in parsing address string: %s",
689                     gai_strerror(ecode));
690
691         if (srcres->ai_addr->sa_family != dstres->ai_addr->sa_family)
692                 errx(1,
693                     "source and destination address families do not match");
694
695         afp->af_settunnel(s, srcres, dstres);
696
697         freeaddrinfo(srcres);
698         freeaddrinfo(dstres);
699 }
700
701 /* ARGSUSED */
702 static void
703 deletetunnel(const char *vname, int param, int s, const struct afswtch *afp)
704 {
705
706         if (ioctl(s, SIOCDIFPHYADDR, &ifr) < 0)
707                 err(1, "SIOCDIFPHYADDR");
708 }
709
710 #ifdef JAIL
711 static void
712 setifvnet(const char *jname, int dummy __unused, int s,
713     const struct afswtch *afp)
714 {
715         struct ifreq my_ifr;
716
717         memcpy(&my_ifr, &ifr, sizeof(my_ifr));
718         my_ifr.ifr_jid = jail_getid(jname);
719         if (my_ifr.ifr_jid < 0)
720                 errx(1, "%s", jail_errmsg);
721         if (ioctl(s, SIOCSIFVNET, &my_ifr) < 0)
722                 err(1, "SIOCSIFVNET");
723 }
724
725 static void
726 setifrvnet(const char *jname, int dummy __unused, int s,
727     const struct afswtch *afp)
728 {
729         struct ifreq my_ifr;
730
731         memcpy(&my_ifr, &ifr, sizeof(my_ifr));
732         my_ifr.ifr_jid = jail_getid(jname);
733         if (my_ifr.ifr_jid < 0)
734                 errx(1, "%s", jail_errmsg);
735         if (ioctl(s, SIOCSIFRVNET, &my_ifr) < 0)
736                 err(1, "SIOCSIFRVNET(%d, %s)", my_ifr.ifr_jid, my_ifr.ifr_name);
737 }
738 #endif
739
740 static void
741 setifnetmask(const char *addr, int dummy __unused, int s,
742     const struct afswtch *afp)
743 {
744         if (afp->af_getaddr != NULL) {
745                 setmask++;
746                 afp->af_getaddr(addr, MASK);
747         }
748 }
749
750 static void
751 setifbroadaddr(const char *addr, int dummy __unused, int s,
752     const struct afswtch *afp)
753 {
754         if (afp->af_getaddr != NULL)
755                 afp->af_getaddr(addr, DSTADDR);
756 }
757
758 static void
759 setifipdst(const char *addr, int dummy __unused, int s,
760     const struct afswtch *afp)
761 {
762         const struct afswtch *inet;
763
764         inet = af_getbyname("inet");
765         if (inet == NULL)
766                 return;
767         inet->af_getaddr(addr, DSTADDR);
768         clearaddr = 0;
769         newaddr = 0;
770 }
771
772 static void
773 notealias(const char *addr, int param, int s, const struct afswtch *afp)
774 {
775 #define rqtosa(x) (&(((struct ifreq *)(afp->x))->ifr_addr))
776         if (setaddr && doalias == 0 && param < 0)
777                 if (afp->af_addreq != NULL && afp->af_ridreq != NULL)
778                         bcopy((caddr_t)rqtosa(af_addreq),
779                               (caddr_t)rqtosa(af_ridreq),
780                               rqtosa(af_addreq)->sa_len);
781         doalias = param;
782         if (param < 0) {
783                 clearaddr = 1;
784                 newaddr = 0;
785         } else
786                 clearaddr = 0;
787 #undef rqtosa
788 }
789
790 /*ARGSUSED*/
791 static void
792 setifdstaddr(const char *addr, int param __unused, int s, 
793     const struct afswtch *afp)
794 {
795         if (afp->af_getaddr != NULL)
796                 afp->af_getaddr(addr, DSTADDR);
797 }
798
799 /*
800  * Note: doing an SIOCIGIFFLAGS scribbles on the union portion
801  * of the ifreq structure, which may confuse other parts of ifconfig.
802  * Make a private copy so we can avoid that.
803  */
804 static void
805 setifflags(const char *vname, int value, int s, const struct afswtch *afp)
806 {
807         struct ifreq            my_ifr;
808         int flags;
809
810         memset(&my_ifr, 0, sizeof(my_ifr));
811         (void) strlcpy(my_ifr.ifr_name, name, sizeof(my_ifr.ifr_name));
812
813         if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&my_ifr) < 0) {
814                 Perror("ioctl (SIOCGIFFLAGS)");
815                 exit(1);
816         }
817         flags = (my_ifr.ifr_flags & 0xffff) | (my_ifr.ifr_flagshigh << 16);
818
819         if (value < 0) {
820                 value = -value;
821                 flags &= ~value;
822         } else
823                 flags |= value;
824         my_ifr.ifr_flags = flags & 0xffff;
825         my_ifr.ifr_flagshigh = flags >> 16;
826         if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&my_ifr) < 0)
827                 Perror(vname);
828 }
829
830 void
831 setifcap(const char *vname, int value, int s, const struct afswtch *afp)
832 {
833         int flags;
834
835         if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) < 0) {
836                 Perror("ioctl (SIOCGIFCAP)");
837                 exit(1);
838         }
839         flags = ifr.ifr_curcap;
840         if (value < 0) {
841                 value = -value;
842                 flags &= ~value;
843         } else
844                 flags |= value;
845         flags &= ifr.ifr_reqcap;
846         ifr.ifr_reqcap = flags;
847         if (ioctl(s, SIOCSIFCAP, (caddr_t)&ifr) < 0)
848                 Perror(vname);
849 }
850
851 static void
852 setifmetric(const char *val, int dummy __unused, int s, 
853     const struct afswtch *afp)
854 {
855         strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
856         ifr.ifr_metric = atoi(val);
857         if (ioctl(s, SIOCSIFMETRIC, (caddr_t)&ifr) < 0)
858                 err(1, "ioctl SIOCSIFMETRIC (set metric)");
859 }
860
861 static void
862 setifmtu(const char *val, int dummy __unused, int s, 
863     const struct afswtch *afp)
864 {
865         strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
866         ifr.ifr_mtu = atoi(val);
867         if (ioctl(s, SIOCSIFMTU, (caddr_t)&ifr) < 0)
868                 err(1, "ioctl SIOCSIFMTU (set mtu)");
869 }
870
871 static void
872 setifname(const char *val, int dummy __unused, int s, 
873     const struct afswtch *afp)
874 {
875         char *newname;
876         
877         strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
878
879         newname = strdup(val);
880         if (newname == NULL)
881                 err(1, "no memory to set ifname");
882         ifr.ifr_data = newname;
883         if (ioctl(s, SIOCSIFNAME, (caddr_t)&ifr) < 0) {
884                 free(newname);
885                 err(1, "ioctl SIOCSIFNAME (set name)");
886         }
887         printifname = 1;
888         strlcpy(name, newname, sizeof(name));
889         free(newname);
890 }
891
892 /* ARGSUSED */
893 static void
894 setifdescr(const char *val, int dummy __unused, int s, 
895     const struct afswtch *afp)
896 {
897         char *newdescr;
898
899         strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
900         
901         ifr.ifr_buffer.length = strlen(val) + 1;
902         if (ifr.ifr_buffer.length == 1) {
903                 ifr.ifr_buffer.buffer = newdescr = NULL;
904                 ifr.ifr_buffer.length = 0;
905         } else {
906                 newdescr = strdup(val);
907                 ifr.ifr_buffer.buffer = newdescr;
908                 if (newdescr == NULL) {
909                         warn("no memory to set ifdescr");
910                         return;
911                 }
912         }
913
914         if (ioctl(s, SIOCSIFDESCR, (caddr_t)&ifr) < 0)
915                 err(1, "ioctl SIOCSIFDESCR (set descr)");
916
917         free(newdescr);
918 }
919
920 /* ARGSUSED */
921 static void
922 unsetifdescr(const char *val, int value, int s, const struct afswtch *afp)
923 {
924
925         setifdescr("", 0, s, 0);
926 }
927
928 #define IFFBITS \
929 "\020\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5POINTOPOINT\6SMART\7RUNNING" \
930 "\10NOARP\11PROMISC\12ALLMULTI\13OACTIVE\14SIMPLEX\15LINK0\16LINK1\17LINK2" \
931 "\20MULTICAST\22PPROMISC\23MONITOR\24STATICARP"
932
933 #define IFCAPBITS \
934 "\020\1RXCSUM\2TXCSUM\3NETCONS\4VLAN_MTU\5VLAN_HWTAGGING\6JUMBO_MTU\7POLLING" \
935 "\10VLAN_HWCSUM\11TSO4\12TSO6\13LRO\14WOL_UCAST\15WOL_MCAST\16WOL_MAGIC" \
936 "\17TOE4\20TOE6\21VLAN_HWFILTER\23VLAN_HWTSO\24LINKSTATE\25NETMAP" \
937 "\26RXCSUM_IPV6\27TXCSUM_IPV6"
938
939 /*
940  * Print the status of the interface.  If an address family was
941  * specified, show only it; otherwise, show them all.
942  */
943 static void
944 status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
945         struct ifaddrs *ifa)
946 {
947         struct ifaddrs *ift;
948         int allfamilies, s;
949         struct ifstat ifs;
950
951         if (afp == NULL) {
952                 allfamilies = 1;
953                 ifr.ifr_addr.sa_family = AF_LOCAL;
954         } else {
955                 allfamilies = 0;
956                 ifr.ifr_addr.sa_family =
957                     afp->af_af == AF_LINK ? AF_LOCAL : afp->af_af;
958         }
959         strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
960
961         s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0);
962         if (s < 0)
963                 err(1, "socket(family %u,SOCK_DGRAM)", ifr.ifr_addr.sa_family);
964
965         printf("%s: ", name);
966         printb("flags", ifa->ifa_flags, IFFBITS);
967         if (ioctl(s, SIOCGIFMETRIC, &ifr) != -1)
968                 printf(" metric %d", ifr.ifr_metric);
969         if (ioctl(s, SIOCGIFMTU, &ifr) != -1)
970                 printf(" mtu %d", ifr.ifr_mtu);
971         putchar('\n');
972
973         for (;;) {
974                 if ((descr = reallocf(descr, descrlen)) != NULL) {
975                         ifr.ifr_buffer.buffer = descr;
976                         ifr.ifr_buffer.length = descrlen;
977                         if (ioctl(s, SIOCGIFDESCR, &ifr) == 0) {
978                                 if (ifr.ifr_buffer.buffer == descr) {
979                                         if (strlen(descr) > 0)
980                                                 printf("\tdescription: %s\n",
981                                                     descr);
982                                 } else if (ifr.ifr_buffer.length > descrlen) {
983                                         descrlen = ifr.ifr_buffer.length;
984                                         continue;
985                                 }
986                         }
987                 } else
988                         warn("unable to allocate memory for interface"
989                             "description");
990                 break;
991         }
992
993         if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) == 0) {
994                 if (ifr.ifr_curcap != 0) {
995                         printb("\toptions", ifr.ifr_curcap, IFCAPBITS);
996                         putchar('\n');
997                 }
998                 if (supmedia && ifr.ifr_reqcap != 0) {
999                         printb("\tcapabilities", ifr.ifr_reqcap, IFCAPBITS);
1000                         putchar('\n');
1001                 }
1002         }
1003
1004         tunnel_status(s);
1005
1006         for (ift = ifa; ift != NULL; ift = ift->ifa_next) {
1007                 if (ift->ifa_addr == NULL)
1008                         continue;
1009                 if (strcmp(ifa->ifa_name, ift->ifa_name) != 0)
1010                         continue;
1011                 if (allfamilies) {
1012                         const struct afswtch *p;
1013                         p = af_getbyfamily(ift->ifa_addr->sa_family);
1014                         if (p != NULL && p->af_status != NULL)
1015                                 p->af_status(s, ift);
1016                 } else if (afp->af_af == ift->ifa_addr->sa_family)
1017                         afp->af_status(s, ift);
1018         }
1019 #if 0
1020         if (allfamilies || afp->af_af == AF_LINK) {
1021                 const struct afswtch *lafp;
1022
1023                 /*
1024                  * Hack; the link level address is received separately
1025                  * from the routing information so any address is not
1026                  * handled above.  Cobble together an entry and invoke
1027                  * the status method specially.
1028                  */
1029                 lafp = af_getbyname("lladdr");
1030                 if (lafp != NULL) {
1031                         info.rti_info[RTAX_IFA] = (struct sockaddr *)sdl;
1032                         lafp->af_status(s, &info);
1033                 }
1034         }
1035 #endif
1036         if (allfamilies)
1037                 af_other_status(s);
1038         else if (afp->af_other_status != NULL)
1039                 afp->af_other_status(s);
1040
1041         strlcpy(ifs.ifs_name, name, sizeof ifs.ifs_name);
1042         if (ioctl(s, SIOCGIFSTATUS, &ifs) == 0) 
1043                 printf("%s", ifs.ascii);
1044
1045         if (verbose > 0)
1046                 sfp_status(s, &ifr, verbose);
1047
1048         close(s);
1049         return;
1050 }
1051
1052 static void
1053 tunnel_status(int s)
1054 {
1055         af_all_tunnel_status(s);
1056 }
1057
1058 void
1059 Perror(const char *cmd)
1060 {
1061         switch (errno) {
1062
1063         case ENXIO:
1064                 errx(1, "%s: no such interface", cmd);
1065                 break;
1066
1067         case EPERM:
1068                 errx(1, "%s: permission denied", cmd);
1069                 break;
1070
1071         default:
1072                 err(1, "%s", cmd);
1073         }
1074 }
1075
1076 /*
1077  * Print a value a la the %b format of the kernel's printf
1078  */
1079 void
1080 printb(const char *s, unsigned v, const char *bits)
1081 {
1082         int i, any = 0;
1083         char c;
1084
1085         if (bits && *bits == 8)
1086                 printf("%s=%o", s, v);
1087         else
1088                 printf("%s=%x", s, v);
1089         bits++;
1090         if (bits) {
1091                 putchar('<');
1092                 while ((i = *bits++) != '\0') {
1093                         if (v & (1 << (i-1))) {
1094                                 if (any)
1095                                         putchar(',');
1096                                 any = 1;
1097                                 for (; (c = *bits) > 32; bits++)
1098                                         putchar(c);
1099                         } else
1100                                 for (; *bits > 32; bits++)
1101                                         ;
1102                 }
1103                 putchar('>');
1104         }
1105 }
1106
1107 void
1108 print_vhid(const struct ifaddrs *ifa, const char *s)
1109 {
1110         struct if_data *ifd;
1111
1112         if (ifa->ifa_data == NULL)
1113                 return;
1114
1115         ifd = ifa->ifa_data;
1116         if (ifd->ifi_vhid == 0)
1117                 return;
1118         
1119         printf("vhid %d ", ifd->ifi_vhid);
1120 }
1121
1122 void
1123 ifmaybeload(const char *name)
1124 {
1125 #define MOD_PREFIX_LEN          3       /* "if_" */
1126         struct module_stat mstat;
1127         int fileid, modid;
1128         char ifkind[IFNAMSIZ + MOD_PREFIX_LEN], ifname[IFNAMSIZ], *dp;
1129         const char *cp;
1130
1131         /* loading suppressed by the user */
1132         if (noload)
1133                 return;
1134
1135         /* trim the interface number off the end */
1136         strlcpy(ifname, name, sizeof(ifname));
1137         for (dp = ifname; *dp != 0; dp++)
1138                 if (isdigit(*dp)) {
1139                         *dp = 0;
1140                         break;
1141                 }
1142
1143         /* turn interface and unit into module name */
1144         strlcpy(ifkind, "if_", sizeof(ifkind));
1145         strlcat(ifkind, ifname, sizeof(ifkind));
1146
1147         /* scan files in kernel */
1148         mstat.version = sizeof(struct module_stat);
1149         for (fileid = kldnext(0); fileid > 0; fileid = kldnext(fileid)) {
1150                 /* scan modules in file */
1151                 for (modid = kldfirstmod(fileid); modid > 0;
1152                      modid = modfnext(modid)) {
1153                         if (modstat(modid, &mstat) < 0)
1154                                 continue;
1155                         /* strip bus name if present */
1156                         if ((cp = strchr(mstat.name, '/')) != NULL) {
1157                                 cp++;
1158                         } else {
1159                                 cp = mstat.name;
1160                         }
1161                         /* already loaded? */
1162                         if (strcmp(ifname, cp) == 0 ||
1163                             strcmp(ifkind, cp) == 0)
1164                                 return;
1165                 }
1166         }
1167
1168         /* not present, we should try to load it */
1169         kldload(ifkind);
1170 }
1171
1172 static struct cmd basic_cmds[] = {
1173         DEF_CMD("up",           IFF_UP,         setifflags),
1174         DEF_CMD("down",         -IFF_UP,        setifflags),
1175         DEF_CMD("arp",          -IFF_NOARP,     setifflags),
1176         DEF_CMD("-arp",         IFF_NOARP,      setifflags),
1177         DEF_CMD("debug",        IFF_DEBUG,      setifflags),
1178         DEF_CMD("-debug",       -IFF_DEBUG,     setifflags),
1179         DEF_CMD_ARG("description",              setifdescr),
1180         DEF_CMD_ARG("descr",                    setifdescr),
1181         DEF_CMD("-description", 0,              unsetifdescr),
1182         DEF_CMD("-descr",       0,              unsetifdescr),
1183         DEF_CMD("promisc",      IFF_PPROMISC,   setifflags),
1184         DEF_CMD("-promisc",     -IFF_PPROMISC,  setifflags),
1185         DEF_CMD("add",          IFF_UP,         notealias),
1186         DEF_CMD("alias",        IFF_UP,         notealias),
1187         DEF_CMD("-alias",       -IFF_UP,        notealias),
1188         DEF_CMD("delete",       -IFF_UP,        notealias),
1189         DEF_CMD("remove",       -IFF_UP,        notealias),
1190 #ifdef notdef
1191 #define EN_SWABIPS      0x1000
1192         DEF_CMD("swabips",      EN_SWABIPS,     setifflags),
1193         DEF_CMD("-swabips",     -EN_SWABIPS,    setifflags),
1194 #endif
1195         DEF_CMD_ARG("netmask",                  setifnetmask),
1196         DEF_CMD_ARG("metric",                   setifmetric),
1197         DEF_CMD_ARG("broadcast",                setifbroadaddr),
1198         DEF_CMD_ARG("ipdst",                    setifipdst),
1199         DEF_CMD_ARG2("tunnel",                  settunnel),
1200         DEF_CMD("-tunnel", 0,                   deletetunnel),
1201         DEF_CMD("deletetunnel", 0,              deletetunnel),
1202 #ifdef JAIL
1203         DEF_CMD_ARG("vnet",                     setifvnet),
1204         DEF_CMD_ARG("-vnet",                    setifrvnet),
1205 #endif
1206         DEF_CMD("link0",        IFF_LINK0,      setifflags),
1207         DEF_CMD("-link0",       -IFF_LINK0,     setifflags),
1208         DEF_CMD("link1",        IFF_LINK1,      setifflags),
1209         DEF_CMD("-link1",       -IFF_LINK1,     setifflags),
1210         DEF_CMD("link2",        IFF_LINK2,      setifflags),
1211         DEF_CMD("-link2",       -IFF_LINK2,     setifflags),
1212         DEF_CMD("monitor",      IFF_MONITOR,    setifflags),
1213         DEF_CMD("-monitor",     -IFF_MONITOR,   setifflags),
1214         DEF_CMD("staticarp",    IFF_STATICARP,  setifflags),
1215         DEF_CMD("-staticarp",   -IFF_STATICARP, setifflags),
1216         DEF_CMD("rxcsum6",      IFCAP_RXCSUM_IPV6,      setifcap),
1217         DEF_CMD("-rxcsum6",     -IFCAP_RXCSUM_IPV6,     setifcap),
1218         DEF_CMD("txcsum6",      IFCAP_TXCSUM_IPV6,      setifcap),
1219         DEF_CMD("-txcsum6",     -IFCAP_TXCSUM_IPV6,     setifcap),
1220         DEF_CMD("rxcsum",       IFCAP_RXCSUM,   setifcap),
1221         DEF_CMD("-rxcsum",      -IFCAP_RXCSUM,  setifcap),
1222         DEF_CMD("txcsum",       IFCAP_TXCSUM,   setifcap),
1223         DEF_CMD("-txcsum",      -IFCAP_TXCSUM,  setifcap),
1224         DEF_CMD("netcons",      IFCAP_NETCONS,  setifcap),
1225         DEF_CMD("-netcons",     -IFCAP_NETCONS, setifcap),
1226         DEF_CMD("polling",      IFCAP_POLLING,  setifcap),
1227         DEF_CMD("-polling",     -IFCAP_POLLING, setifcap),
1228         DEF_CMD("tso6",         IFCAP_TSO6,     setifcap),
1229         DEF_CMD("-tso6",        -IFCAP_TSO6,    setifcap),
1230         DEF_CMD("tso4",         IFCAP_TSO4,     setifcap),
1231         DEF_CMD("-tso4",        -IFCAP_TSO4,    setifcap),
1232         DEF_CMD("tso",          IFCAP_TSO,      setifcap),
1233         DEF_CMD("-tso",         -IFCAP_TSO,     setifcap),
1234         DEF_CMD("toe",          IFCAP_TOE,      setifcap),
1235         DEF_CMD("-toe",         -IFCAP_TOE,     setifcap),
1236         DEF_CMD("lro",          IFCAP_LRO,      setifcap),
1237         DEF_CMD("-lro",         -IFCAP_LRO,     setifcap),
1238         DEF_CMD("wol",          IFCAP_WOL,      setifcap),
1239         DEF_CMD("-wol",         -IFCAP_WOL,     setifcap),
1240         DEF_CMD("wol_ucast",    IFCAP_WOL_UCAST,        setifcap),
1241         DEF_CMD("-wol_ucast",   -IFCAP_WOL_UCAST,       setifcap),
1242         DEF_CMD("wol_mcast",    IFCAP_WOL_MCAST,        setifcap),
1243         DEF_CMD("-wol_mcast",   -IFCAP_WOL_MCAST,       setifcap),
1244         DEF_CMD("wol_magic",    IFCAP_WOL_MAGIC,        setifcap),
1245         DEF_CMD("-wol_magic",   -IFCAP_WOL_MAGIC,       setifcap),
1246         DEF_CMD("normal",       -IFF_LINK0,     setifflags),
1247         DEF_CMD("compress",     IFF_LINK0,      setifflags),
1248         DEF_CMD("noicmp",       IFF_LINK1,      setifflags),
1249         DEF_CMD_ARG("mtu",                      setifmtu),
1250         DEF_CMD_ARG("name",                     setifname),
1251 };
1252
1253 static __constructor void
1254 ifconfig_ctor(void)
1255 {
1256         size_t i;
1257
1258         for (i = 0; i < nitems(basic_cmds);  i++)
1259                 cmd_register(&basic_cmds[i]);
1260 }