]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/ifconfig/ifconfig.c
dma: update to 2022-01-27 snapshot
[FreeBSD/FreeBSD.git] / sbin / ifconfig / ifconfig.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1983, 1993\n\
35         The Regents of the University of California.  All rights reserved.\n";
36 #if 0
37 static char sccsid[] = "@(#)ifconfig.c  8.2 (Berkeley) 2/16/94";
38 #endif
39 static const char rcsid[] =
40   "$FreeBSD$";
41 #endif /* not lint */
42
43 #include <sys/param.h>
44 #include <sys/ioctl.h>
45 #include <sys/module.h>
46 #include <sys/linker.h>
47 #include <sys/queue.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_dl.h>
54 #include <net/if_types.h>
55 #include <net/route.h>
56
57 /* IP */
58 #include <netinet/in.h>
59 #include <netinet/in_var.h>
60 #include <arpa/inet.h>
61 #include <netdb.h>
62
63 #include <fnmatch.h>
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 <stdbool.h>
73 #include <stdio.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <unistd.h>
77
78 #include <libifconfig.h>
79
80 #include "ifconfig.h"
81
82 ifconfig_handle_t *lifh;
83
84 /*
85  * Since "struct ifreq" is composed of various union members, callers
86  * should pay special attention to interpret the value.
87  * (.e.g. little/big endian difference in the structure.)
88  */
89 struct  ifreq ifr;
90
91 char    name[IFNAMSIZ];
92 char    *descr = NULL;
93 size_t  descrlen = 64;
94 int     setaddr;
95 int     setmask;
96 int     doalias;
97 int     clearaddr;
98 int     newaddr = 1;
99 int     verbose;
100 int     noload;
101 int     printifname = 0;
102
103 int     supmedia = 0;
104 int     printkeys = 0;          /* Print keying material for interfaces. */
105 int     exit_code = 0;
106
107 /* Formatter Strings */
108 char    *f_inet, *f_inet6, *f_ether, *f_addr;
109
110 static  bool group_member(const char *ifname, const char *match,
111                 const char *nomatch);
112 static  int ifconfig(int argc, char *const *argv, int iscreate,
113                 const struct afswtch *afp);
114 static  void status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
115                 struct ifaddrs *ifa);
116 static  void tunnel_status(int s);
117 static _Noreturn void usage(void);
118
119 static int getifflags(const char *ifname, int us, bool err_ok);
120
121 static struct afswtch *af_getbyname(const char *name);
122 static struct afswtch *af_getbyfamily(int af);
123 static void af_other_status(int);
124
125 void printifnamemaybe(void);
126
127 static struct option *opts = NULL;
128
129 struct ifa_order_elt {
130         int if_order;
131         int af_orders[255];
132         struct ifaddrs *ifa;
133         TAILQ_ENTRY(ifa_order_elt) link;
134 };
135
136 TAILQ_HEAD(ifa_queue, ifa_order_elt);
137
138 static struct module_map_entry {
139         const char *ifname;
140         const char *kldname;
141 } module_map[] = {
142         {
143                 .ifname = "tun",
144                 .kldname = "if_tuntap",
145         },
146         {
147                 .ifname = "tap",
148                 .kldname = "if_tuntap",
149         },
150         {
151                 .ifname = "vmnet",
152                 .kldname = "if_tuntap",
153         },
154         {
155                 .ifname = "ipsec",
156                 .kldname = "ipsec",
157         },
158         {
159                 /*
160                  * This mapping exists because there is a conflicting enc module
161                  * in CAM.  ifconfig's guessing behavior will attempt to match
162                  * the ifname to a module as well as if_${ifname} and clash with
163                  * CAM enc.  This is an assertion of the correct module to load.
164                  */
165                 .ifname = "enc",
166                 .kldname = "if_enc",
167         },
168 };
169
170
171 void
172 opt_register(struct option *p)
173 {
174         p->next = opts;
175         opts = p;
176 }
177
178 static void
179 usage(void)
180 {
181         char options[1024];
182         struct option *p;
183
184         /* XXX not right but close enough for now */
185         options[0] = '\0';
186         for (p = opts; p != NULL; p = p->next) {
187                 strlcat(options, p->opt_usage, sizeof(options));
188                 strlcat(options, " ", sizeof(options));
189         }
190
191         fprintf(stderr,
192         "usage: ifconfig [-f type:format] %sinterface address_family\n"
193         "                [address [dest_address]] [parameters]\n"
194         "       ifconfig interface create\n"
195         "       ifconfig -a %s[-d] [-m] [-u] [-v] [address_family]\n"
196         "       ifconfig -l [-d] [-u] [address_family]\n"
197         "       ifconfig %s[-d] [-m] [-u] [-v]\n",
198                 options, options, options);
199         exit(1);
200 }
201
202 void
203 ioctl_ifcreate(int s, struct ifreq *ifr)
204 {
205         if (ioctl(s, SIOCIFCREATE2, ifr) < 0) {
206                 switch (errno) {
207                 case EEXIST:
208                         errx(1, "interface %s already exists", ifr->ifr_name);
209                 default:
210                         err(1, "SIOCIFCREATE2");
211                 }
212         }
213 }
214
215 static int
216 calcorders(struct ifaddrs *ifa, struct ifa_queue *q)
217 {
218         struct ifaddrs *prev;
219         struct ifa_order_elt *cur;
220         unsigned int ord, af, ifa_ord;
221
222         prev = NULL;
223         cur = NULL;
224         ord = 0;
225         ifa_ord = 0;
226
227         while (ifa != NULL) {
228                 if (prev == NULL ||
229                     strcmp(ifa->ifa_name, prev->ifa_name) != 0) {
230                         cur = calloc(1, sizeof(*cur));
231
232                         if (cur == NULL)
233                                 return (-1);
234
235                         TAILQ_INSERT_TAIL(q, cur, link);
236                         cur->if_order = ifa_ord ++;
237                         cur->ifa = ifa;
238                         ord = 0;
239                 }
240
241                 if (ifa->ifa_addr) {
242                         af = ifa->ifa_addr->sa_family;
243
244                         if (af < nitems(cur->af_orders) &&
245                             cur->af_orders[af] == 0)
246                                 cur->af_orders[af] = ++ord;
247                 }
248                 prev = ifa;
249                 ifa = ifa->ifa_next;
250         }
251
252         return (0);
253 }
254
255 static int
256 cmpifaddrs(struct ifaddrs *a, struct ifaddrs *b, struct ifa_queue *q)
257 {
258         struct ifa_order_elt *cur, *e1, *e2;
259         unsigned int af1, af2;
260         int ret;
261
262         e1 = e2 = NULL;
263
264         ret = strcmp(a->ifa_name, b->ifa_name);
265         if (ret != 0) {
266                 TAILQ_FOREACH(cur, q, link) {
267                         if (e1 && e2)
268                                 break;
269
270                         if (strcmp(cur->ifa->ifa_name, a->ifa_name) == 0)
271                                 e1 = cur;
272                         else if (strcmp(cur->ifa->ifa_name, b->ifa_name) == 0)
273                                 e2 = cur;
274                 }
275
276                 if (!e1 || !e2)
277                         return (0);
278                 else
279                         return (e1->if_order - e2->if_order);
280
281         } else if (a->ifa_addr != NULL && b->ifa_addr != NULL) {
282                 TAILQ_FOREACH(cur, q, link) {
283                         if (strcmp(cur->ifa->ifa_name, a->ifa_name) == 0) {
284                                 e1 = cur;
285                                 break;
286                         }
287                 }
288
289                 if (!e1)
290                         return (0);
291
292                 af1 = a->ifa_addr->sa_family;
293                 af2 = b->ifa_addr->sa_family;
294
295                 if (af1 < nitems(e1->af_orders) && af2 < nitems(e1->af_orders))
296                         return (e1->af_orders[af1] - e1->af_orders[af2]);
297         }
298
299         return (0);
300 }
301
302 static void freeformat(void)
303 {
304
305         if (f_inet != NULL)
306                 free(f_inet);
307         if (f_inet6 != NULL)
308                 free(f_inet6);
309         if (f_ether != NULL)
310                 free(f_ether);
311         if (f_addr != NULL)
312                 free(f_addr);
313 }
314
315 static void setformat(char *input)
316 {
317         char    *formatstr, *category, *modifier; 
318
319         formatstr = strdup(input);
320         while ((category = strsep(&formatstr, ",")) != NULL) {
321                 modifier = strchr(category, ':');
322                 if (modifier == NULL || modifier[1] == '\0') {
323                         warnx("Skipping invalid format specification: %s\n",
324                             category);
325                         continue;
326                 }
327
328                 /* Split the string on the separator, then seek past it */
329                 modifier[0] = '\0';
330                 modifier++;
331
332                 if (strcmp(category, "addr") == 0)
333                         f_addr = strdup(modifier);
334                 else if (strcmp(category, "ether") == 0)
335                         f_ether = strdup(modifier);
336                 else if (strcmp(category, "inet") == 0)
337                         f_inet = strdup(modifier);
338                 else if (strcmp(category, "inet6") == 0)
339                         f_inet6 = strdup(modifier);
340         }
341         free(formatstr);
342 }
343
344 static struct ifaddrs *
345 sortifaddrs(struct ifaddrs *list,
346     int (*compare)(struct ifaddrs *, struct ifaddrs *, struct ifa_queue *),
347     struct ifa_queue *q)
348 {
349         struct ifaddrs *right, *temp, *last, *result, *next, *tail;
350         
351         right = list;
352         temp = list;
353         last = list;
354         result = NULL;
355         next = NULL;
356         tail = NULL;
357
358         if (!list || !list->ifa_next)
359                 return (list);
360
361         while (temp && temp->ifa_next) {
362                 last = right;
363                 right = right->ifa_next;
364                 temp = temp->ifa_next->ifa_next;
365         }
366
367         last->ifa_next = NULL;
368
369         list = sortifaddrs(list, compare, q);
370         right = sortifaddrs(right, compare, q);
371
372         while (list || right) {
373
374                 if (!right) {
375                         next = list;
376                         list = list->ifa_next;
377                 } else if (!list) {
378                         next = right;
379                         right = right->ifa_next;
380                 } else if (compare(list, right, q) <= 0) {
381                         next = list;
382                         list = list->ifa_next;
383                 } else {
384                         next = right;
385                         right = right->ifa_next;
386                 }
387
388                 if (!result)
389                         result = next;
390                 else
391                         tail->ifa_next = next;
392
393                 tail = next;
394         }
395
396         return (result);
397 }
398
399 void printifnamemaybe()
400 {
401         if (printifname)
402                 printf("%s\n", name);
403 }
404
405 int
406 main(int argc, char *argv[])
407 {
408         int c, all, namesonly, downonly, uponly;
409         const struct afswtch *afp = NULL;
410         int ifindex;
411         struct ifaddrs *ifap, *sifap, *ifa;
412         struct ifreq paifr;
413         const struct sockaddr_dl *sdl;
414         char options[1024], *cp, *envformat, *namecp = NULL;
415         struct ifa_queue q = TAILQ_HEAD_INITIALIZER(q);
416         struct ifa_order_elt *cur, *tmp;
417         const char *ifname, *matchgroup, *nogroup;
418         struct option *p;
419         size_t iflen;
420         int flags;
421
422         all = downonly = uponly = namesonly = noload = verbose = 0;
423         f_inet = f_inet6 = f_ether = f_addr = NULL;
424         matchgroup = nogroup = NULL;
425
426         lifh = ifconfig_open();
427         if (lifh == NULL)
428                 err(EXIT_FAILURE, "ifconfig_open");
429
430         envformat = getenv("IFCONFIG_FORMAT");
431         if (envformat != NULL)
432                 setformat(envformat);
433
434         /*
435          * Ensure we print interface name when expected to,
436          * even if we terminate early due to error.
437          */
438         atexit(printifnamemaybe);
439
440         /* Parse leading line options */
441         strlcpy(options, "G:adf:klmnuv", sizeof(options));
442         for (p = opts; p != NULL; p = p->next)
443                 strlcat(options, p->opt, sizeof(options));
444         while ((c = getopt(argc, argv, options)) != -1) {
445                 switch (c) {
446                 case 'a':       /* scan all interfaces */
447                         all++;
448                         break;
449                 case 'd':       /* restrict scan to "down" interfaces */
450                         downonly++;
451                         break;
452                 case 'f':
453                         if (optarg == NULL)
454                                 usage();
455                         setformat(optarg);
456                         break;
457                 case 'G':
458                         if (optarg == NULL || all == 0)
459                                 usage();
460                         nogroup = optarg;
461                         break;
462                 case 'k':
463                         printkeys++;
464                         break;
465                 case 'l':       /* scan interface names only */
466                         namesonly++;
467                         break;
468                 case 'm':       /* show media choices in status */
469                         supmedia = 1;
470                         break;
471                 case 'n':       /* suppress module loading */
472                         noload++;
473                         break;
474                 case 'u':       /* restrict scan to "up" interfaces */
475                         uponly++;
476                         break;
477                 case 'v':
478                         verbose++;
479                         break;
480                 case 'g':
481                         if (all) {
482                                 if (optarg == NULL)
483                                         usage();
484                                 matchgroup = optarg;
485                                 break;
486                         }
487                         /* FALLTHROUGH */
488                 default:
489                         for (p = opts; p != NULL; p = p->next)
490                                 if (p->opt[0] == c) {
491                                         p->cb(optarg);
492                                         break;
493                                 }
494                         if (p == NULL)
495                                 usage();
496                         break;
497                 }
498         }
499         argc -= optind;
500         argv += optind;
501
502         /* -l cannot be used with -a or -m */
503         if (namesonly && (all || supmedia))
504                 usage();
505
506         /* nonsense.. */
507         if (uponly && downonly)
508                 usage();
509
510         /* no arguments is equivalent to '-a' */
511         if (!namesonly && argc < 1)
512                 all = 1;
513
514         /* -a and -l allow an address family arg to limit the output */
515         if (all || namesonly) {
516                 if (argc > 1)
517                         usage();
518
519                 ifname = NULL;
520                 ifindex = 0;
521                 if (argc == 1) {
522                         afp = af_getbyname(*argv);
523                         if (afp == NULL) {
524                                 warnx("Address family '%s' unknown.", *argv);
525                                 usage();
526                         }
527                         if (afp->af_name != NULL)
528                                 argc--, argv++;
529                         /* leave with afp non-zero */
530                 }
531         } else {
532                 /* not listing, need an argument */
533                 if (argc < 1)
534                         usage();
535
536                 ifname = *argv;
537                 argc--, argv++;
538
539                 /* check and maybe load support for this interface */
540                 ifmaybeload(ifname);
541
542                 ifindex = if_nametoindex(ifname);
543                 if (ifindex == 0) {
544                         /*
545                          * NOTE:  We must special-case the `create' command
546                          * right here as we would otherwise fail when trying
547                          * to find the interface.
548                          */
549                         if (argc > 0 && (strcmp(argv[0], "create") == 0 ||
550                             strcmp(argv[0], "plumb") == 0)) {
551                                 iflen = strlcpy(name, ifname, sizeof(name));
552                                 if (iflen >= sizeof(name))
553                                         errx(1, "%s: cloning name too long",
554                                             ifname);
555                                 ifconfig(argc, argv, 1, NULL);
556                                 exit(exit_code);
557                         }
558 #ifdef JAIL
559                         /*
560                          * NOTE:  We have to special-case the `-vnet' command
561                          * right here as we would otherwise fail when trying
562                          * to find the interface as it lives in another vnet.
563                          */
564                         if (argc > 0 && (strcmp(argv[0], "-vnet") == 0)) {
565                                 iflen = strlcpy(name, ifname, sizeof(name));
566                                 if (iflen >= sizeof(name))
567                                         errx(1, "%s: interface name too long",
568                                             ifname);
569                                 ifconfig(argc, argv, 0, NULL);
570                                 exit(exit_code);
571                         }
572 #endif
573                         errx(1, "interface %s does not exist", ifname);
574                 } else {
575                         /*
576                          * Do not allow use `create` command as hostname if
577                          * address family is not specified.
578                          */
579                         if (argc > 0 && (strcmp(argv[0], "create") == 0 ||
580                             strcmp(argv[0], "plumb") == 0)) {
581                                 if (argc == 1)
582                                         errx(1, "interface %s already exists",
583                                             ifname);
584                                 argc--, argv++;
585                         }
586                 }
587         }
588
589         /* Check for address family */
590         if (argc > 0) {
591                 afp = af_getbyname(*argv);
592                 if (afp != NULL)
593                         argc--, argv++;
594         }
595
596         /*
597          * Check for a requested configuration action on a single interface,
598          * which doesn't require building, sorting, and searching the entire
599          * system address list
600          */
601         if ((argc > 0) && (ifname != NULL)) {
602                 iflen = strlcpy(name, ifname, sizeof(name));
603                 if (iflen >= sizeof(name)) {
604                         warnx("%s: interface name too long, skipping", ifname);
605                 } else {
606                         flags = getifflags(name, -1, false);
607                         if (!(((flags & IFF_CANTCONFIG) != 0) ||
608                                 (downonly && (flags & IFF_UP) != 0) ||
609                                 (uponly && (flags & IFF_UP) == 0)))
610                                 ifconfig(argc, argv, 0, afp);
611                 }
612                 goto done;
613         }
614
615         if (getifaddrs(&ifap) != 0)
616                 err(EXIT_FAILURE, "getifaddrs");
617
618         cp = NULL;
619         
620         if (calcorders(ifap, &q) != 0)
621                 err(EXIT_FAILURE, "calcorders");
622                 
623         sifap = sortifaddrs(ifap, cmpifaddrs, &q);
624
625         TAILQ_FOREACH_SAFE(cur, &q, link, tmp)
626                 free(cur);
627
628         ifindex = 0;
629         for (ifa = sifap; ifa; ifa = ifa->ifa_next) {
630                 memset(&paifr, 0, sizeof(paifr));
631                 strlcpy(paifr.ifr_name, ifa->ifa_name, sizeof(paifr.ifr_name));
632                 if (sizeof(paifr.ifr_addr) >= ifa->ifa_addr->sa_len) {
633                         memcpy(&paifr.ifr_addr, ifa->ifa_addr,
634                             ifa->ifa_addr->sa_len);
635                 }
636
637                 if (ifname != NULL && strcmp(ifname, ifa->ifa_name) != 0)
638                         continue;
639                 if (ifa->ifa_addr->sa_family == AF_LINK)
640                         sdl = (const struct sockaddr_dl *) ifa->ifa_addr;
641                 else
642                         sdl = NULL;
643                 if (cp != NULL && strcmp(cp, ifa->ifa_name) == 0 && !namesonly)
644                         continue;
645                 iflen = strlcpy(name, ifa->ifa_name, sizeof(name));
646                 if (iflen >= sizeof(name)) {
647                         warnx("%s: interface name too long, skipping",
648                             ifa->ifa_name);
649                         continue;
650                 }
651                 cp = ifa->ifa_name;
652
653                 if ((ifa->ifa_flags & IFF_CANTCONFIG) != 0)
654                         continue;
655                 if (downonly && (ifa->ifa_flags & IFF_UP) != 0)
656                         continue;
657                 if (uponly && (ifa->ifa_flags & IFF_UP) == 0)
658                         continue;
659                 if (!group_member(ifa->ifa_name, matchgroup, nogroup))
660                         continue;
661                 /*
662                  * Are we just listing the interfaces?
663                  */
664                 if (namesonly) {
665                         if (namecp == cp)
666                                 continue;
667                         if (afp != NULL) {
668                                 /* special case for "ether" address family */
669                                 if (!strcmp(afp->af_name, "ether")) {
670                                         if (sdl == NULL ||
671                                             (sdl->sdl_type != IFT_ETHER &&
672                                             sdl->sdl_type != IFT_L2VLAN &&
673                                             sdl->sdl_type != IFT_BRIDGE) ||
674                                             sdl->sdl_alen != ETHER_ADDR_LEN)
675                                                 continue;
676                                 } else {
677                                         if (ifa->ifa_addr->sa_family 
678                                             != afp->af_af)
679                                                 continue;
680                                 }
681                         }
682                         namecp = cp;
683                         ifindex++;
684                         if (ifindex > 1)
685                                 printf(" ");
686                         fputs(name, stdout);
687                         continue;
688                 }
689                 ifindex++;
690
691                 if (argc > 0)
692                         ifconfig(argc, argv, 0, afp);
693                 else
694                         status(afp, sdl, ifa);
695         }
696         if (namesonly)
697                 printf("\n");
698         freeifaddrs(ifap);
699
700 done:
701         freeformat();
702         ifconfig_close(lifh);
703         exit(exit_code);
704 }
705
706 /*
707  * Returns true if an interface should be listed because any its groups
708  * matches shell pattern "match" and none of groups matches pattern "nomatch".
709  * If any pattern is NULL, corresponding condition is skipped.
710  */
711 static bool
712 group_member(const char *ifname, const char *match, const char *nomatch)
713 {
714         static int               sock = -1;
715
716         struct ifgroupreq        ifgr;
717         struct ifg_req          *ifg;
718         int                      len;
719         bool                     matched, nomatched;
720
721         /* Sanity checks. */
722         if (match == NULL && nomatch == NULL)
723                 return (true);
724         if (ifname == NULL)
725                 return (false);
726
727         memset(&ifgr, 0, sizeof(ifgr));
728         strlcpy(ifgr.ifgr_name, ifname, IFNAMSIZ);
729
730         /* The socket is opened once. Let _exit() close it. */
731         if (sock == -1) {
732                 sock = socket(AF_LOCAL, SOCK_DGRAM, 0);
733                 if (sock == -1)
734                     errx(1, "%s: socket(AF_LOCAL,SOCK_DGRAM)", __func__);
735         }
736
737         /* Determine amount of memory for the list of groups. */
738         if (ioctl(sock, SIOCGIFGROUP, (caddr_t)&ifgr) == -1) {
739                 if (errno == EINVAL || errno == ENOTTY)
740                         return (false);
741                 else
742                         errx(1, "%s: SIOCGIFGROUP", __func__);
743         }
744
745         /* Obtain the list of groups. */
746         len = ifgr.ifgr_len;
747         ifgr.ifgr_groups =
748             (struct ifg_req *)calloc(len / sizeof(*ifg), sizeof(*ifg));
749
750         if (ifgr.ifgr_groups == NULL)
751                 errx(1, "%s: no memory", __func__);
752         if (ioctl(sock, SIOCGIFGROUP, (caddr_t)&ifgr) == -1)
753                 errx(1, "%s: SIOCGIFGROUP", __func__);
754
755         /* Perform matching. */
756         matched = false;
757         nomatched = true;
758         for (ifg = ifgr.ifgr_groups; ifg && len >= sizeof(*ifg); ifg++) {
759                 len -= sizeof(struct ifg_req);
760                 if (match)
761                         matched |= !fnmatch(match, ifg->ifgrq_group, 0);
762                 if (nomatch)
763                         nomatched &= fnmatch(nomatch, ifg->ifgrq_group, 0);
764         }
765         free(ifgr.ifgr_groups);
766
767         if (match && !nomatch)
768                 return (matched);
769         if (!match && nomatch)
770                 return (nomatched);
771         return (matched && nomatched);
772 }
773
774 static struct afswtch *afs = NULL;
775
776 void
777 af_register(struct afswtch *p)
778 {
779         p->af_next = afs;
780         afs = p;
781 }
782
783 static struct afswtch *
784 af_getbyname(const char *name)
785 {
786         struct afswtch *afp;
787
788         for (afp = afs; afp !=  NULL; afp = afp->af_next)
789                 if (strcmp(afp->af_name, name) == 0)
790                         return afp;
791         return NULL;
792 }
793
794 static struct afswtch *
795 af_getbyfamily(int af)
796 {
797         struct afswtch *afp;
798
799         for (afp = afs; afp != NULL; afp = afp->af_next)
800                 if (afp->af_af == af)
801                         return afp;
802         return NULL;
803 }
804
805 static void
806 af_other_status(int s)
807 {
808         struct afswtch *afp;
809         uint8_t afmask[howmany(AF_MAX, NBBY)];
810
811         memset(afmask, 0, sizeof(afmask));
812         for (afp = afs; afp != NULL; afp = afp->af_next) {
813                 if (afp->af_other_status == NULL)
814                         continue;
815                 if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
816                         continue;
817                 afp->af_other_status(s);
818                 setbit(afmask, afp->af_af);
819         }
820 }
821
822 static void
823 af_all_tunnel_status(int s)
824 {
825         struct afswtch *afp;
826         uint8_t afmask[howmany(AF_MAX, NBBY)];
827
828         memset(afmask, 0, sizeof(afmask));
829         for (afp = afs; afp != NULL; afp = afp->af_next) {
830                 if (afp->af_status_tunnel == NULL)
831                         continue;
832                 if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
833                         continue;
834                 afp->af_status_tunnel(s);
835                 setbit(afmask, afp->af_af);
836         }
837 }
838
839 static struct cmd *cmds = NULL;
840
841 void
842 cmd_register(struct cmd *p)
843 {
844         p->c_next = cmds;
845         cmds = p;
846 }
847
848 static const struct cmd *
849 cmd_lookup(const char *name, int iscreate)
850 {
851         const struct cmd *p;
852
853         for (p = cmds; p != NULL; p = p->c_next)
854                 if (strcmp(name, p->c_name) == 0) {
855                         if (iscreate) {
856                                 if (p->c_iscloneop)
857                                         return p;
858                         } else {
859                                 if (!p->c_iscloneop)
860                                         return p;
861                         }
862                 }
863         return NULL;
864 }
865
866 struct callback {
867         callback_func *cb_func;
868         void    *cb_arg;
869         struct callback *cb_next;
870 };
871 static struct callback *callbacks = NULL;
872
873 void
874 callback_register(callback_func *func, void *arg)
875 {
876         struct callback *cb;
877
878         cb = malloc(sizeof(struct callback));
879         if (cb == NULL)
880                 errx(1, "unable to allocate memory for callback");
881         cb->cb_func = func;
882         cb->cb_arg = arg;
883         cb->cb_next = callbacks;
884         callbacks = cb;
885 }
886
887 /* specially-handled commands */
888 static void setifaddr(const char *, int, int, const struct afswtch *);
889 static const struct cmd setifaddr_cmd = DEF_CMD("ifaddr", 0, setifaddr);
890
891 static void setifdstaddr(const char *, int, int, const struct afswtch *);
892 static const struct cmd setifdstaddr_cmd =
893         DEF_CMD("ifdstaddr", 0, setifdstaddr);
894
895 static int
896 ifconfig(int argc, char *const *argv, int iscreate, const struct afswtch *uafp)
897 {
898         const struct afswtch *afp, *nafp;
899         const struct cmd *p;
900         struct callback *cb;
901         int s;
902
903         strlcpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
904         afp = NULL;
905         if (uafp != NULL)
906                 afp = uafp;
907         /*
908          * This is the historical "accident" allowing users to configure IPv4
909          * addresses without the "inet" keyword which while a nice feature has
910          * proven to complicate other things.  We cannot remove this but only
911          * make sure we will never have a similar implicit default for IPv6 or
912          * any other address familiy.  We need a fallback though for
913          * ifconfig IF up/down etc. to work without INET support as people
914          * never used ifconfig IF link up/down, etc. either.
915          */
916 #ifndef RESCUE
917 #ifdef INET
918         if (afp == NULL && feature_present("inet"))
919                 afp = af_getbyname("inet");
920 #endif
921 #endif
922         if (afp == NULL)
923                 afp = af_getbyname("link");
924         if (afp == NULL) {
925                 warnx("Please specify an address_family.");
926                 usage();
927         }
928 top:
929         ifr.ifr_addr.sa_family =
930                 afp->af_af == AF_LINK || afp->af_af == AF_UNSPEC ?
931                 AF_LOCAL : afp->af_af;
932
933         if ((s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0)) < 0 &&
934             (uafp != NULL || errno != EAFNOSUPPORT ||
935              (s = socket(AF_LOCAL, SOCK_DGRAM, 0)) < 0))
936                 err(1, "socket(family %u,SOCK_DGRAM)", ifr.ifr_addr.sa_family);
937
938         while (argc > 0) {
939                 p = cmd_lookup(*argv, iscreate);
940                 if (iscreate && p == NULL) {
941                         /*
942                          * Push the clone create callback so the new
943                          * device is created and can be used for any
944                          * remaining arguments.
945                          */
946                         cb = callbacks;
947                         if (cb == NULL)
948                                 errx(1, "internal error, no callback");
949                         callbacks = cb->cb_next;
950                         cb->cb_func(s, cb->cb_arg);
951                         iscreate = 0;
952                         /*
953                          * Handle any address family spec that
954                          * immediately follows and potentially
955                          * recreate the socket.
956                          */
957                         nafp = af_getbyname(*argv);
958                         if (nafp != NULL) {
959                                 argc--, argv++;
960                                 if (nafp != afp) {
961                                         close(s);
962                                         afp = nafp;
963                                         goto top;
964                                 }
965                         }
966                         /*
967                          * Look for a normal parameter.
968                          */
969                         continue;
970                 }
971                 if (p == NULL) {
972                         /*
973                          * Not a recognized command, choose between setting
974                          * the interface address and the dst address.
975                          */
976                         p = (setaddr ? &setifdstaddr_cmd : &setifaddr_cmd);
977                 }
978                 if (p->c_parameter == NEXTARG && p->c_u.c_func) {
979                         if (argv[1] == NULL)
980                                 errx(1, "'%s' requires argument",
981                                     p->c_name);
982                         p->c_u.c_func(argv[1], 0, s, afp);
983                         argc--, argv++;
984                 } else if (p->c_parameter == OPTARG && p->c_u.c_func) {
985                         p->c_u.c_func(argv[1], 0, s, afp);
986                         if (argv[1] != NULL)
987                                 argc--, argv++;
988                 } else if (p->c_parameter == NEXTARG2 && p->c_u.c_func2) {
989                         if (argc < 3)
990                                 errx(1, "'%s' requires 2 arguments",
991                                     p->c_name);
992                         p->c_u.c_func2(argv[1], argv[2], s, afp);
993                         argc -= 2, argv += 2;
994                 } else if (p->c_u.c_func)
995                         p->c_u.c_func(*argv, p->c_parameter, s, afp);
996                 argc--, argv++;
997         }
998
999         /*
1000          * Do any post argument processing required by the address family.
1001          */
1002         if (afp->af_postproc != NULL)
1003                 afp->af_postproc(s, afp, newaddr, getifflags(name, s, true));
1004         /*
1005          * Do deferred callbacks registered while processing
1006          * command-line arguments.
1007          */
1008         for (cb = callbacks; cb != NULL; cb = cb->cb_next)
1009                 cb->cb_func(s, cb->cb_arg);
1010         /*
1011          * Do deferred operations.
1012          */
1013         if (clearaddr) {
1014                 if (afp->af_ridreq == NULL || afp->af_difaddr == 0) {
1015                         warnx("interface %s cannot change %s addresses!",
1016                               name, afp->af_name);
1017                         clearaddr = 0;
1018                 }
1019         }
1020         if (clearaddr) {
1021                 int ret;
1022                 strlcpy(((struct ifreq *)afp->af_ridreq)->ifr_name, name,
1023                         sizeof ifr.ifr_name);
1024                 ret = ioctl(s, afp->af_difaddr, afp->af_ridreq);
1025                 if (ret < 0) {
1026                         if (errno == EADDRNOTAVAIL && (doalias >= 0)) {
1027                                 /* means no previous address for interface */
1028                         } else
1029                                 Perror("ioctl (SIOCDIFADDR)");
1030                 }
1031         }
1032         if (newaddr) {
1033                 if (afp->af_addreq == NULL || afp->af_aifaddr == 0) {
1034                         warnx("interface %s cannot change %s addresses!",
1035                               name, afp->af_name);
1036                         newaddr = 0;
1037                 }
1038         }
1039         if (newaddr && (setaddr || setmask)) {
1040                 strlcpy(((struct ifreq *)afp->af_addreq)->ifr_name, name,
1041                         sizeof ifr.ifr_name);
1042                 if (ioctl(s, afp->af_aifaddr, afp->af_addreq) < 0)
1043                         Perror("ioctl (SIOCAIFADDR)");
1044         }
1045
1046         close(s);
1047         return(0);
1048 }
1049
1050 /*ARGSUSED*/
1051 static void
1052 setifaddr(const char *addr, int param, int s, const struct afswtch *afp)
1053 {
1054         if (afp->af_getaddr == NULL)
1055                 return;
1056         /*
1057          * Delay the ioctl to set the interface addr until flags are all set.
1058          * The address interpretation may depend on the flags,
1059          * and the flags may change when the address is set.
1060          */
1061         setaddr++;
1062         if (doalias == 0 && afp->af_af != AF_LINK)
1063                 clearaddr = 1;
1064         afp->af_getaddr(addr, (doalias >= 0 ? ADDR : RIDADDR));
1065 }
1066
1067 static void
1068 settunnel(const char *src, const char *dst, int s, const struct afswtch *afp)
1069 {
1070         struct addrinfo *srcres, *dstres;
1071         int ecode;
1072
1073         if (afp->af_settunnel == NULL) {
1074                 warn("address family %s does not support tunnel setup",
1075                         afp->af_name);
1076                 return;
1077         }
1078
1079         if ((ecode = getaddrinfo(src, NULL, NULL, &srcres)) != 0)
1080                 errx(1, "error in parsing address string: %s",
1081                     gai_strerror(ecode));
1082
1083         if ((ecode = getaddrinfo(dst, NULL, NULL, &dstres)) != 0)
1084                 errx(1, "error in parsing address string: %s",
1085                     gai_strerror(ecode));
1086
1087         if (srcres->ai_addr->sa_family != dstres->ai_addr->sa_family)
1088                 errx(1,
1089                     "source and destination address families do not match");
1090
1091         afp->af_settunnel(s, srcres, dstres);
1092
1093         freeaddrinfo(srcres);
1094         freeaddrinfo(dstres);
1095 }
1096
1097 /* ARGSUSED */
1098 static void
1099 deletetunnel(const char *vname, int param, int s, const struct afswtch *afp)
1100 {
1101
1102         if (ioctl(s, SIOCDIFPHYADDR, &ifr) < 0)
1103                 err(1, "SIOCDIFPHYADDR");
1104 }
1105
1106 #ifdef JAIL
1107 static void
1108 setifvnet(const char *jname, int dummy __unused, int s,
1109     const struct afswtch *afp)
1110 {
1111         struct ifreq my_ifr;
1112
1113         memcpy(&my_ifr, &ifr, sizeof(my_ifr));
1114         my_ifr.ifr_jid = jail_getid(jname);
1115         if (my_ifr.ifr_jid < 0)
1116                 errx(1, "%s", jail_errmsg);
1117         if (ioctl(s, SIOCSIFVNET, &my_ifr) < 0)
1118                 err(1, "SIOCSIFVNET");
1119 }
1120
1121 static void
1122 setifrvnet(const char *jname, int dummy __unused, int s,
1123     const struct afswtch *afp)
1124 {
1125         struct ifreq my_ifr;
1126
1127         memcpy(&my_ifr, &ifr, sizeof(my_ifr));
1128         my_ifr.ifr_jid = jail_getid(jname);
1129         if (my_ifr.ifr_jid < 0)
1130                 errx(1, "%s", jail_errmsg);
1131         if (ioctl(s, SIOCSIFRVNET, &my_ifr) < 0)
1132                 err(1, "SIOCSIFRVNET(%d, %s)", my_ifr.ifr_jid, my_ifr.ifr_name);
1133 }
1134 #endif
1135
1136 static void
1137 setifnetmask(const char *addr, int dummy __unused, int s,
1138     const struct afswtch *afp)
1139 {
1140         if (afp->af_getaddr != NULL) {
1141                 setmask++;
1142                 afp->af_getaddr(addr, MASK);
1143         }
1144 }
1145
1146 static void
1147 setifbroadaddr(const char *addr, int dummy __unused, int s,
1148     const struct afswtch *afp)
1149 {
1150         if (afp->af_getaddr != NULL)
1151                 afp->af_getaddr(addr, DSTADDR);
1152 }
1153
1154 static void
1155 notealias(const char *addr, int param, int s, const struct afswtch *afp)
1156 {
1157 #define rqtosa(x) (&(((struct ifreq *)(afp->x))->ifr_addr))
1158         if (setaddr && doalias == 0 && param < 0)
1159                 if (afp->af_addreq != NULL && afp->af_ridreq != NULL)
1160                         bcopy((caddr_t)rqtosa(af_addreq),
1161                               (caddr_t)rqtosa(af_ridreq),
1162                               rqtosa(af_addreq)->sa_len);
1163         doalias = param;
1164         if (param < 0) {
1165                 clearaddr = 1;
1166                 newaddr = 0;
1167         } else
1168                 clearaddr = 0;
1169 #undef rqtosa
1170 }
1171
1172 /*ARGSUSED*/
1173 static void
1174 setifdstaddr(const char *addr, int param __unused, int s, 
1175     const struct afswtch *afp)
1176 {
1177         if (afp->af_getaddr != NULL)
1178                 afp->af_getaddr(addr, DSTADDR);
1179 }
1180
1181 static int
1182 getifflags(const char *ifname, int us, bool err_ok)
1183 {
1184         struct ifreq my_ifr;
1185         int s;
1186         
1187         memset(&my_ifr, 0, sizeof(my_ifr));
1188         (void) strlcpy(my_ifr.ifr_name, ifname, sizeof(my_ifr.ifr_name));
1189         if (us < 0) {
1190                 if ((s = socket(AF_LOCAL, SOCK_DGRAM, 0)) < 0)
1191                         err(1, "socket(family AF_LOCAL,SOCK_DGRAM");
1192         } else
1193                 s = us;
1194         if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&my_ifr) < 0) {
1195                 if (!err_ok) {
1196                         Perror("ioctl (SIOCGIFFLAGS)");
1197                         exit(1);
1198                 }
1199         }
1200         if (us < 0)
1201                 close(s);
1202         return ((my_ifr.ifr_flags & 0xffff) | (my_ifr.ifr_flagshigh << 16));
1203 }
1204
1205 /*
1206  * Note: doing an SIOCIGIFFLAGS scribbles on the union portion
1207  * of the ifreq structure, which may confuse other parts of ifconfig.
1208  * Make a private copy so we can avoid that.
1209  */
1210 static void
1211 setifflags(const char *vname, int value, int s, const struct afswtch *afp)
1212 {
1213         struct ifreq            my_ifr;
1214         int flags;
1215
1216         flags = getifflags(name, s, false);
1217         if (value < 0) {
1218                 value = -value;
1219                 flags &= ~value;
1220         } else
1221                 flags |= value;
1222         memset(&my_ifr, 0, sizeof(my_ifr));
1223         (void) strlcpy(my_ifr.ifr_name, name, sizeof(my_ifr.ifr_name));
1224         my_ifr.ifr_flags = flags & 0xffff;
1225         my_ifr.ifr_flagshigh = flags >> 16;
1226         if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&my_ifr) < 0)
1227                 Perror(vname);
1228 }
1229
1230 void
1231 setifcap(const char *vname, int value, int s, const struct afswtch *afp)
1232 {
1233         int flags;
1234
1235         if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) < 0) {
1236                 Perror("ioctl (SIOCGIFCAP)");
1237                 exit(1);
1238         }
1239         flags = ifr.ifr_curcap;
1240         if (value < 0) {
1241                 value = -value;
1242                 flags &= ~value;
1243         } else
1244                 flags |= value;
1245         flags &= ifr.ifr_reqcap;
1246         /* Check for no change in capabilities. */
1247         if (ifr.ifr_curcap == flags)
1248                 return;
1249         ifr.ifr_reqcap = flags;
1250         if (ioctl(s, SIOCSIFCAP, (caddr_t)&ifr) < 0)
1251                 Perror(vname);
1252 }
1253
1254 static void
1255 setifmetric(const char *val, int dummy __unused, int s, 
1256     const struct afswtch *afp)
1257 {
1258         strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
1259         ifr.ifr_metric = atoi(val);
1260         if (ioctl(s, SIOCSIFMETRIC, (caddr_t)&ifr) < 0)
1261                 err(1, "ioctl SIOCSIFMETRIC (set metric)");
1262 }
1263
1264 static void
1265 setifmtu(const char *val, int dummy __unused, int s, 
1266     const struct afswtch *afp)
1267 {
1268         strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
1269         ifr.ifr_mtu = atoi(val);
1270         if (ioctl(s, SIOCSIFMTU, (caddr_t)&ifr) < 0)
1271                 err(1, "ioctl SIOCSIFMTU (set mtu)");
1272 }
1273
1274 static void
1275 setifpcp(const char *val, int arg __unused, int s, const struct afswtch *afp)
1276 {
1277         u_long ul;
1278         char *endp;
1279
1280         ul = strtoul(val, &endp, 0);
1281         if (*endp != '\0')
1282                 errx(1, "invalid value for pcp");
1283         if (ul > 7)
1284                 errx(1, "value for pcp out of range");
1285         ifr.ifr_lan_pcp = ul;
1286         if (ioctl(s, SIOCSLANPCP, (caddr_t)&ifr) == -1)
1287                 err(1, "SIOCSLANPCP");
1288 }
1289
1290 static void
1291 disableifpcp(const char *val, int arg __unused, int s,
1292     const struct afswtch *afp)
1293 {
1294
1295         ifr.ifr_lan_pcp = IFNET_PCP_NONE;
1296         if (ioctl(s, SIOCSLANPCP, (caddr_t)&ifr) == -1)
1297                 err(1, "SIOCSLANPCP");
1298 }
1299
1300 static void
1301 setifname(const char *val, int dummy __unused, int s, 
1302     const struct afswtch *afp)
1303 {
1304         char *newname;
1305         
1306         strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
1307
1308         newname = strdup(val);
1309         if (newname == NULL)
1310                 err(1, "no memory to set ifname");
1311         ifr.ifr_data = newname;
1312         if (ioctl(s, SIOCSIFNAME, (caddr_t)&ifr) < 0) {
1313                 free(newname);
1314                 err(1, "ioctl SIOCSIFNAME (set name)");
1315         }
1316         printifname = 1;
1317         strlcpy(name, newname, sizeof(name));
1318         free(newname);
1319 }
1320
1321 /* ARGSUSED */
1322 static void
1323 setifdescr(const char *val, int dummy __unused, int s, 
1324     const struct afswtch *afp)
1325 {
1326         char *newdescr;
1327
1328         strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
1329         
1330         ifr.ifr_buffer.length = strlen(val) + 1;
1331         if (ifr.ifr_buffer.length == 1) {
1332                 ifr.ifr_buffer.buffer = newdescr = NULL;
1333                 ifr.ifr_buffer.length = 0;
1334         } else {
1335                 newdescr = strdup(val);
1336                 ifr.ifr_buffer.buffer = newdescr;
1337                 if (newdescr == NULL) {
1338                         warn("no memory to set ifdescr");
1339                         return;
1340                 }
1341         }
1342
1343         if (ioctl(s, SIOCSIFDESCR, (caddr_t)&ifr) < 0)
1344                 err(1, "ioctl SIOCSIFDESCR (set descr)");
1345
1346         free(newdescr);
1347 }
1348
1349 /* ARGSUSED */
1350 static void
1351 unsetifdescr(const char *val, int value, int s, const struct afswtch *afp)
1352 {
1353
1354         setifdescr("", 0, s, 0);
1355 }
1356
1357 #define IFFBITS \
1358 "\020\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5POINTOPOINT\7RUNNING" \
1359 "\10NOARP\11PROMISC\12ALLMULTI\13OACTIVE\14SIMPLEX\15LINK0\16LINK1\17LINK2" \
1360 "\20MULTICAST\22PPROMISC\23MONITOR\24STATICARP"
1361
1362 #define IFCAPBITS \
1363 "\020\1RXCSUM\2TXCSUM\3NETCONS\4VLAN_MTU\5VLAN_HWTAGGING\6JUMBO_MTU\7POLLING" \
1364 "\10VLAN_HWCSUM\11TSO4\12TSO6\13LRO\14WOL_UCAST\15WOL_MCAST\16WOL_MAGIC" \
1365 "\17TOE4\20TOE6\21VLAN_HWFILTER\23VLAN_HWTSO\24LINKSTATE\25NETMAP" \
1366 "\26RXCSUM_IPV6\27TXCSUM_IPV6\31TXRTLMT\32HWRXTSTMP\33NOMAP\34TXTLS4\35TXTLS6" \
1367 "\36VXLAN_HWCSUM\37VXLAN_HWTSO\40TXTLS_RTLMT"
1368
1369 /*
1370  * Print the status of the interface.  If an address family was
1371  * specified, show only it; otherwise, show them all.
1372  */
1373 static void
1374 status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
1375         struct ifaddrs *ifa)
1376 {
1377         struct ifaddrs *ift;
1378         int allfamilies, s;
1379         struct ifstat ifs;
1380
1381         if (afp == NULL) {
1382                 allfamilies = 1;
1383                 ifr.ifr_addr.sa_family = AF_LOCAL;
1384         } else {
1385                 allfamilies = 0;
1386                 ifr.ifr_addr.sa_family =
1387                     afp->af_af == AF_LINK ? AF_LOCAL : afp->af_af;
1388         }
1389         strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
1390
1391         s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0);
1392         if (s < 0)
1393                 err(1, "socket(family %u,SOCK_DGRAM)", ifr.ifr_addr.sa_family);
1394
1395         printf("%s: ", name);
1396         printb("flags", ifa->ifa_flags, IFFBITS);
1397         if (ioctl(s, SIOCGIFMETRIC, &ifr) != -1)
1398                 printf(" metric %d", ifr.ifr_metric);
1399         if (ioctl(s, SIOCGIFMTU, &ifr) != -1)
1400                 printf(" mtu %d", ifr.ifr_mtu);
1401         putchar('\n');
1402
1403         for (;;) {
1404                 if ((descr = reallocf(descr, descrlen)) != NULL) {
1405                         ifr.ifr_buffer.buffer = descr;
1406                         ifr.ifr_buffer.length = descrlen;
1407                         if (ioctl(s, SIOCGIFDESCR, &ifr) == 0) {
1408                                 if (ifr.ifr_buffer.buffer == descr) {
1409                                         if (strlen(descr) > 0)
1410                                                 printf("\tdescription: %s\n",
1411                                                     descr);
1412                                 } else if (ifr.ifr_buffer.length > descrlen) {
1413                                         descrlen = ifr.ifr_buffer.length;
1414                                         continue;
1415                                 }
1416                         }
1417                 } else
1418                         warn("unable to allocate memory for interface"
1419                             "description");
1420                 break;
1421         }
1422
1423         if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) == 0) {
1424                 if (ifr.ifr_curcap != 0) {
1425                         printb("\toptions", ifr.ifr_curcap, IFCAPBITS);
1426                         putchar('\n');
1427                 }
1428                 if (supmedia && ifr.ifr_reqcap != 0) {
1429                         printb("\tcapabilities", ifr.ifr_reqcap, IFCAPBITS);
1430                         putchar('\n');
1431                 }
1432         }
1433
1434         tunnel_status(s);
1435
1436         for (ift = ifa; ift != NULL; ift = ift->ifa_next) {
1437                 if (ift->ifa_addr == NULL)
1438                         continue;
1439                 if (strcmp(ifa->ifa_name, ift->ifa_name) != 0)
1440                         continue;
1441                 if (allfamilies) {
1442                         const struct afswtch *p;
1443                         p = af_getbyfamily(ift->ifa_addr->sa_family);
1444                         if (p != NULL && p->af_status != NULL)
1445                                 p->af_status(s, ift);
1446                 } else if (afp->af_af == ift->ifa_addr->sa_family)
1447                         afp->af_status(s, ift);
1448         }
1449 #if 0
1450         if (allfamilies || afp->af_af == AF_LINK) {
1451                 const struct afswtch *lafp;
1452
1453                 /*
1454                  * Hack; the link level address is received separately
1455                  * from the routing information so any address is not
1456                  * handled above.  Cobble together an entry and invoke
1457                  * the status method specially.
1458                  */
1459                 lafp = af_getbyname("lladdr");
1460                 if (lafp != NULL) {
1461                         info.rti_info[RTAX_IFA] = (struct sockaddr *)sdl;
1462                         lafp->af_status(s, &info);
1463                 }
1464         }
1465 #endif
1466         if (allfamilies)
1467                 af_other_status(s);
1468         else if (afp->af_other_status != NULL)
1469                 afp->af_other_status(s);
1470
1471         strlcpy(ifs.ifs_name, name, sizeof ifs.ifs_name);
1472         if (ioctl(s, SIOCGIFSTATUS, &ifs) == 0) 
1473                 printf("%s", ifs.ascii);
1474
1475         if (verbose > 0)
1476                 sfp_status(s, &ifr, verbose);
1477
1478         close(s);
1479         return;
1480 }
1481
1482 static void
1483 tunnel_status(int s)
1484 {
1485         af_all_tunnel_status(s);
1486 }
1487
1488 void
1489 Perror(const char *cmd)
1490 {
1491         switch (errno) {
1492
1493         case ENXIO:
1494                 errx(1, "%s: no such interface", cmd);
1495                 break;
1496
1497         case EPERM:
1498                 errx(1, "%s: permission denied", cmd);
1499                 break;
1500
1501         default:
1502                 err(1, "%s", cmd);
1503         }
1504 }
1505
1506 /*
1507  * Print a value a la the %b format of the kernel's printf
1508  */
1509 void
1510 printb(const char *s, unsigned v, const char *bits)
1511 {
1512         int i, any = 0;
1513         char c;
1514
1515         if (bits && *bits == 8)
1516                 printf("%s=%o", s, v);
1517         else
1518                 printf("%s=%x", s, v);
1519         if (bits) {
1520                 bits++;
1521                 putchar('<');
1522                 while ((i = *bits++) != '\0') {
1523                         if (v & (1u << (i-1))) {
1524                                 if (any)
1525                                         putchar(',');
1526                                 any = 1;
1527                                 for (; (c = *bits) > 32; bits++)
1528                                         putchar(c);
1529                         } else
1530                                 for (; *bits > 32; bits++)
1531                                         ;
1532                 }
1533                 putchar('>');
1534         }
1535 }
1536
1537 void
1538 print_vhid(const struct ifaddrs *ifa, const char *s)
1539 {
1540         struct if_data *ifd;
1541
1542         if (ifa->ifa_data == NULL)
1543                 return;
1544
1545         ifd = ifa->ifa_data;
1546         if (ifd->ifi_vhid == 0)
1547                 return;
1548         
1549         printf(" vhid %d", ifd->ifi_vhid);
1550 }
1551
1552 void
1553 ifmaybeload(const char *name)
1554 {
1555 #define MOD_PREFIX_LEN          3       /* "if_" */
1556         struct module_stat mstat;
1557         int i, fileid, modid;
1558         char ifkind[IFNAMSIZ + MOD_PREFIX_LEN], ifname[IFNAMSIZ], *dp;
1559         const char *cp;
1560         struct module_map_entry *mme;
1561         bool found;
1562
1563         /* loading suppressed by the user */
1564         if (noload)
1565                 return;
1566
1567         /* trim the interface number off the end */
1568         strlcpy(ifname, name, sizeof(ifname));
1569         for (dp = ifname; *dp != 0; dp++)
1570                 if (isdigit(*dp)) {
1571                         *dp = 0;
1572                         break;
1573                 }
1574
1575         /* Either derive it from the map or guess otherwise */
1576         *ifkind = '\0';
1577         found = false;
1578         for (i = 0; i < nitems(module_map); ++i) {
1579                 mme = &module_map[i];
1580                 if (strcmp(mme->ifname, ifname) == 0) {
1581                         strlcpy(ifkind, mme->kldname, sizeof(ifkind));
1582                         found = true;
1583                         break;
1584                 }
1585         }
1586
1587         /* We didn't have an alias for it... we'll guess. */
1588         if (!found) {
1589             /* turn interface and unit into module name */
1590             strlcpy(ifkind, "if_", sizeof(ifkind));
1591             strlcat(ifkind, ifname, sizeof(ifkind));
1592         }
1593
1594         /* scan files in kernel */
1595         mstat.version = sizeof(struct module_stat);
1596         for (fileid = kldnext(0); fileid > 0; fileid = kldnext(fileid)) {
1597                 /* scan modules in file */
1598                 for (modid = kldfirstmod(fileid); modid > 0;
1599                      modid = modfnext(modid)) {
1600                         if (modstat(modid, &mstat) < 0)
1601                                 continue;
1602                         /* strip bus name if present */
1603                         if ((cp = strchr(mstat.name, '/')) != NULL) {
1604                                 cp++;
1605                         } else {
1606                                 cp = mstat.name;
1607                         }
1608                         /*
1609                          * Is it already loaded?  Don't compare with ifname if
1610                          * we were specifically told which kld to use.  Doing
1611                          * so could lead to conflicts not trivially solved.
1612                          */
1613                         if ((!found && strcmp(ifname, cp) == 0) ||
1614                             strcmp(ifkind, cp) == 0)
1615                                 return;
1616                 }
1617         }
1618
1619         /*
1620          * Try to load the module.  But ignore failures, because ifconfig can't
1621          * infer the names of all drivers (eg mlx4en(4)).
1622          */
1623         (void) kldload(ifkind);
1624 }
1625
1626 static struct cmd basic_cmds[] = {
1627         DEF_CMD("up",           IFF_UP,         setifflags),
1628         DEF_CMD("down",         -IFF_UP,        setifflags),
1629         DEF_CMD("arp",          -IFF_NOARP,     setifflags),
1630         DEF_CMD("-arp",         IFF_NOARP,      setifflags),
1631         DEF_CMD("debug",        IFF_DEBUG,      setifflags),
1632         DEF_CMD("-debug",       -IFF_DEBUG,     setifflags),
1633         DEF_CMD_ARG("description",              setifdescr),
1634         DEF_CMD_ARG("descr",                    setifdescr),
1635         DEF_CMD("-description", 0,              unsetifdescr),
1636         DEF_CMD("-descr",       0,              unsetifdescr),
1637         DEF_CMD("promisc",      IFF_PPROMISC,   setifflags),
1638         DEF_CMD("-promisc",     -IFF_PPROMISC,  setifflags),
1639         DEF_CMD("add",          IFF_UP,         notealias),
1640         DEF_CMD("alias",        IFF_UP,         notealias),
1641         DEF_CMD("-alias",       -IFF_UP,        notealias),
1642         DEF_CMD("delete",       -IFF_UP,        notealias),
1643         DEF_CMD("remove",       -IFF_UP,        notealias),
1644 #ifdef notdef
1645 #define EN_SWABIPS      0x1000
1646         DEF_CMD("swabips",      EN_SWABIPS,     setifflags),
1647         DEF_CMD("-swabips",     -EN_SWABIPS,    setifflags),
1648 #endif
1649         DEF_CMD_ARG("netmask",                  setifnetmask),
1650         DEF_CMD_ARG("metric",                   setifmetric),
1651         DEF_CMD_ARG("broadcast",                setifbroadaddr),
1652         DEF_CMD_ARG2("tunnel",                  settunnel),
1653         DEF_CMD("-tunnel", 0,                   deletetunnel),
1654         DEF_CMD("deletetunnel", 0,              deletetunnel),
1655 #ifdef JAIL
1656         DEF_CMD_ARG("vnet",                     setifvnet),
1657         DEF_CMD_ARG("-vnet",                    setifrvnet),
1658 #endif
1659         DEF_CMD("link0",        IFF_LINK0,      setifflags),
1660         DEF_CMD("-link0",       -IFF_LINK0,     setifflags),
1661         DEF_CMD("link1",        IFF_LINK1,      setifflags),
1662         DEF_CMD("-link1",       -IFF_LINK1,     setifflags),
1663         DEF_CMD("link2",        IFF_LINK2,      setifflags),
1664         DEF_CMD("-link2",       -IFF_LINK2,     setifflags),
1665         DEF_CMD("monitor",      IFF_MONITOR,    setifflags),
1666         DEF_CMD("-monitor",     -IFF_MONITOR,   setifflags),
1667         DEF_CMD("mextpg",       IFCAP_MEXTPG,   setifcap),
1668         DEF_CMD("-mextpg",      -IFCAP_MEXTPG,  setifcap),
1669         DEF_CMD("staticarp",    IFF_STATICARP,  setifflags),
1670         DEF_CMD("-staticarp",   -IFF_STATICARP, setifflags),
1671         DEF_CMD("rxcsum6",      IFCAP_RXCSUM_IPV6,      setifcap),
1672         DEF_CMD("-rxcsum6",     -IFCAP_RXCSUM_IPV6,     setifcap),
1673         DEF_CMD("txcsum6",      IFCAP_TXCSUM_IPV6,      setifcap),
1674         DEF_CMD("-txcsum6",     -IFCAP_TXCSUM_IPV6,     setifcap),
1675         DEF_CMD("rxcsum",       IFCAP_RXCSUM,   setifcap),
1676         DEF_CMD("-rxcsum",      -IFCAP_RXCSUM,  setifcap),
1677         DEF_CMD("txcsum",       IFCAP_TXCSUM,   setifcap),
1678         DEF_CMD("-txcsum",      -IFCAP_TXCSUM,  setifcap),
1679         DEF_CMD("netcons",      IFCAP_NETCONS,  setifcap),
1680         DEF_CMD("-netcons",     -IFCAP_NETCONS, setifcap),
1681         DEF_CMD_ARG("pcp",                      setifpcp),
1682         DEF_CMD("-pcp", 0,                      disableifpcp),
1683         DEF_CMD("polling",      IFCAP_POLLING,  setifcap),
1684         DEF_CMD("-polling",     -IFCAP_POLLING, setifcap),
1685         DEF_CMD("tso6",         IFCAP_TSO6,     setifcap),
1686         DEF_CMD("-tso6",        -IFCAP_TSO6,    setifcap),
1687         DEF_CMD("tso4",         IFCAP_TSO4,     setifcap),
1688         DEF_CMD("-tso4",        -IFCAP_TSO4,    setifcap),
1689         DEF_CMD("tso",          IFCAP_TSO,      setifcap),
1690         DEF_CMD("-tso",         -IFCAP_TSO,     setifcap),
1691         DEF_CMD("toe",          IFCAP_TOE,      setifcap),
1692         DEF_CMD("-toe",         -IFCAP_TOE,     setifcap),
1693         DEF_CMD("lro",          IFCAP_LRO,      setifcap),
1694         DEF_CMD("-lro",         -IFCAP_LRO,     setifcap),
1695         DEF_CMD("txtls",        IFCAP_TXTLS,    setifcap),
1696         DEF_CMD("-txtls",       -IFCAP_TXTLS,   setifcap),
1697         DEF_CMD("wol",          IFCAP_WOL,      setifcap),
1698         DEF_CMD("-wol",         -IFCAP_WOL,     setifcap),
1699         DEF_CMD("wol_ucast",    IFCAP_WOL_UCAST,        setifcap),
1700         DEF_CMD("-wol_ucast",   -IFCAP_WOL_UCAST,       setifcap),
1701         DEF_CMD("wol_mcast",    IFCAP_WOL_MCAST,        setifcap),
1702         DEF_CMD("-wol_mcast",   -IFCAP_WOL_MCAST,       setifcap),
1703         DEF_CMD("wol_magic",    IFCAP_WOL_MAGIC,        setifcap),
1704         DEF_CMD("-wol_magic",   -IFCAP_WOL_MAGIC,       setifcap),
1705         DEF_CMD("txrtlmt",      IFCAP_TXRTLMT,  setifcap),
1706         DEF_CMD("-txrtlmt",     -IFCAP_TXRTLMT, setifcap),
1707         DEF_CMD("txtlsrtlmt",   IFCAP_TXTLS_RTLMT,      setifcap),
1708         DEF_CMD("-txtlsrtlmt",  -IFCAP_TXTLS_RTLMT,     setifcap),
1709         DEF_CMD("hwrxtstmp",    IFCAP_HWRXTSTMP,        setifcap),
1710         DEF_CMD("-hwrxtstmp",   -IFCAP_HWRXTSTMP,       setifcap),
1711         DEF_CMD("normal",       -IFF_LINK0,     setifflags),
1712         DEF_CMD("compress",     IFF_LINK0,      setifflags),
1713         DEF_CMD("noicmp",       IFF_LINK1,      setifflags),
1714         DEF_CMD_ARG("mtu",                      setifmtu),
1715         DEF_CMD_ARG("name",                     setifname),
1716 };
1717
1718 static __constructor void
1719 ifconfig_ctor(void)
1720 {
1721         size_t i;
1722
1723         for (i = 0; i < nitems(basic_cmds);  i++)
1724                 cmd_register(&basic_cmds[i]);
1725 }