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