ifconfig(8): Use getifaddrs(3) from libc
[dragonfly.git] / sbin / ifconfig / ifconfig.c
1 /*
2  * Copyright (c) 1983, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD: src/sbin/ifconfig/ifconfig.c,v 1.113.2.4 2006/02/09 10:48:43 yar Exp $
30  */
31
32 #include <sys/param.h>
33 #include <sys/ioctl.h>
34 #include <sys/socket.h>
35 #include <sys/sysctl.h>
36 #include <sys/time.h>
37 #include <sys/module.h>
38 #include <sys/linker.h>
39 #include <sys/cdefs.h>
40
41 #include <net/ethernet.h>
42 #include <net/if.h>
43 #include <net/if_var.h>
44 #include <net/if_dl.h>
45 #include <net/if_types.h>
46 #include <net/route.h>
47
48 /* IP */
49 #include <netinet/in.h>
50 #include <netinet/in_var.h>
51 #include <arpa/inet.h>
52 #include <netdb.h>
53
54 #include <ctype.h>
55 #include <err.h>
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <ifaddrs.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63
64 #include "ifconfig.h"
65
66 /*
67  * Since "struct ifreq" is composed of various union members, callers
68  * should pay special attention to interpret the value.
69  * (.e.g. little/big endian difference in the structure.)
70  */
71 struct  ifreq ifr;
72
73 char    name[IFNAMSIZ];
74 int     setaddr;
75 int     setmask;
76 int     doalias;
77 int     clearaddr;
78 int     newaddr = 1;
79 int     verbose;
80 int     noload;
81
82 int     supmedia = 0;
83 int     printkeys = 0;          /* Print keying material for interfaces. */
84 int     printifname = 0;        /* Print the name of the created interface. */
85 int     exit_code = 0;
86
87 /* Formatter strings */
88 char    *f_inet, *f_inet6, *f_ether, *f_addr;
89
90 static  int ifconfig(int argc, char *const *argv, int iscreate,
91                      const struct afswtch *afp);
92 static  void status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
93                     struct ifaddrs *ifa);
94 static  void tunnel_status(int s);
95 static  void usage(void) __dead2;
96
97 static struct afswtch *af_getbyname(const char *name);
98 static struct afswtch *af_getbyfamily(int af);
99 static void af_other_status(int);
100 static void printifnamemaybe(void);
101 static void freeformat(void);
102 static void setformat(char *input);
103
104 static struct option *opts = NULL;
105
106 void
107 opt_register(struct option *p)
108 {
109         p->next = opts;
110         opts = p;
111 }
112
113 static void
114 usage(void)
115 {
116         char options[1024];
117         struct option *p;
118
119         /* XXX not right but close enough for now */
120         options[0] = '\0';
121         for (p = opts; p != NULL; p = p->next) {
122                 strlcat(options, p->opt_usage, sizeof(options));
123                 strlcat(options, " ", sizeof(options));
124         }
125
126         fprintf(stderr,
127         "usage: ifconfig %s[-n] [-f type:format] interface address_family\n"
128         "                [address [dest_address]] [parameters]\n"
129         "       ifconfig [-n] interface create\n"
130         "       ifconfig [-n] interface destroy\n"
131         "       ifconfig -a %s[-d] [-m] [-u] [-v] [address_family]\n"
132         "       ifconfig -l [-d] [-u] [address_family]\n"
133         "       ifconfig %s[-d] [-m] [-u] [-v]\n",
134                 options, options, options);
135         exit(1);
136 }
137
138 static void
139 printifnamemaybe(void)
140 {
141         if (printifname)
142                 printf("%s\n", name);
143 }
144
145 static void
146 freeformat(void)
147 {
148         if (f_inet != NULL)
149                 free(f_inet);
150         if (f_inet6 != NULL)
151                 free(f_inet6);
152         if (f_ether != NULL)
153                 free(f_ether);
154         if (f_addr != NULL)
155                 free(f_addr);
156 }
157
158 static void
159 setformat(char *input)
160 {
161         char *formatstr, *category, *modifier;
162         char **fp;
163
164         formatstr = strdup(input);
165         if (formatstr == NULL)
166                 err(1, "no memory to set format");
167
168         while ((category = strsep(&formatstr, ",")) != NULL) {
169                 modifier = strchr(category, ':');
170                 if (modifier == NULL || modifier[1] == '\0') {
171                         warnx("skip invalid format specification: %s\n",
172                               category);
173                         continue;
174                 }
175
176                 modifier[0] = '\0';
177                 modifier++;
178
179                 fp = NULL;
180                 if (strcmp(category, "addr") == 0)
181                         fp = &f_addr;
182                 else if (strcmp(category, "ether") == 0)
183                         fp = &f_ether;
184                 else if (strcmp(category, "inet") == 0)
185                         fp = &f_inet;
186                 else if (strcmp(category, "inet6") == 0)
187                         fp = &f_inet6;
188
189                 if (fp != NULL) {
190                         *fp = strdup(modifier);
191                         if (*fp == NULL)
192                                 err(1, "strdup");
193                 }
194         }
195
196         free(formatstr);
197 }
198
199
200 int
201 main(int argc, char *argv[])
202 {
203         int c, all, namesonly, downonly, uponly;
204         int ifindex;
205         const struct afswtch *afp = NULL;
206         const struct sockaddr_dl *sdl;
207         const char *ifname;
208         struct ifaddrs *ifap, *ifa;
209         struct ifreq paifr;
210         struct option *p;
211         size_t iflen;
212         char *envformat, *cp;
213         char options[1024];
214
215         all = downonly = uponly = namesonly = verbose = noload = 0;
216         f_inet = f_inet6 = f_ether = f_addr = NULL;
217
218         /*
219          * Ensure we print interface name when expected to,
220          * even if we terminate early due to error.
221          */
222         atexit(printifnamemaybe);
223
224         envformat = getenv("IFCONFIG_FORMAT");
225         if (envformat != NULL)
226                 setformat(envformat);
227
228         /* Parse leading line options */
229         strlcpy(options, "adf:klmnuv", sizeof(options));
230         for (p = opts; p != NULL; p = p->next)
231                 strlcat(options, p->opt, sizeof(options));
232         while ((c = getopt(argc, argv, options)) != -1) {
233                 switch (c) {
234                 case 'a':       /* scan all interfaces */
235                         all++;
236                         break;
237                 case 'd':       /* restrict scan to "down" interfaces */
238                         downonly++;
239                         break;
240                 case 'f':
241                         setformat(optarg);
242                         break;
243                 case 'k':
244                         printkeys++;
245                         break;
246                 case 'l':       /* scan interface names only */
247                         namesonly++;
248                         break;
249                 case 'm':       /* show media choices in status */
250                         supmedia = 1;
251                         break;
252                 case 'n':       /* suppress module loading */
253                         noload++;
254                         break;
255                 case 'u':       /* restrict scan to "up" interfaces */
256                         uponly++;
257                         break;
258                 case 'v':
259                         verbose++;
260                         break;
261                 default:
262                         for (p = opts; p != NULL; p = p->next)
263                                 if (p->opt[0] == c) {
264                                         p->cb(optarg);
265                                         break;
266                                 }
267                         if (p == NULL)
268                                 usage();
269                         break;
270                 }
271         }
272         argc -= optind;
273         argv += optind;
274
275         /* -l cannot be used with -a or -m */
276         if (namesonly && (all || supmedia))
277                 usage();
278
279         /* nonsense.. */
280         if (uponly && downonly)
281                 usage();
282
283         /* no arguments is equivalent to '-a' */
284         if (!namesonly && argc < 1)
285                 all = 1;
286
287         /* -a and -l allow an address family arg to limit the output */
288         if (all || namesonly) {
289                 if (argc > 1)
290                         usage();
291
292                 ifname = NULL;
293                 ifindex = 0;
294                 if (argc == 1) {
295                         afp = af_getbyname(*argv);
296                         if (afp == NULL)
297                                 usage();
298                         if (afp->af_name != NULL)
299                                 argc--, argv++;
300                         /* leave with afp non-zero */
301                 }
302         } else {
303                 /* not listing, need an argument */
304                 if (argc < 1)
305                         usage();
306
307                 ifname = *argv;
308                 argc--, argv++;
309
310                 /* check and maybe load support for this interface */
311                 ifmaybeload(ifname);
312
313                 ifindex = if_nametoindex(ifname);
314                 if (ifindex == 0) {
315                         /*
316                          * NOTE:  We must special-case the `create' command
317                          * right here as we would otherwise fail when trying
318                          * to find the interface.
319                          */
320                         if (argc > 0 && (strcmp(argv[0], "create") == 0 ||
321                             strcmp(argv[0], "plumb") == 0)) {
322                                 iflen = strlcpy(name, ifname, sizeof(name));
323                                 if (iflen >= sizeof(name))
324                                         errx(1, "%s: cloning name too long",
325                                             ifname);
326                                 ifconfig(argc, argv, 1, NULL);
327                                 exit(exit_code);
328                         }
329                         errx(1, "interface %s does not exist", ifname);
330                 } else {
331                         /*
332                          * Do not allow to use `create` command as hostname
333                          * if address family is not specified.
334                          */
335                         if (argc > 0 && (strcmp(argv[0], "create") == 0 ||
336                             strcmp(argv[0], "plumb") == 0)) {
337                                 if (argc == 1)
338                                         errx(1, "interface %s alreay exists",
339                                             ifname);
340                                 argc--, argv++;
341                         }
342                 }
343         }
344
345         /* Check for address family */
346         if (argc > 0) {
347                 afp = af_getbyname(*argv);
348                 if (afp != NULL)
349                         argc--, argv++;
350         }
351
352         if (getifaddrs(&ifap) != 0)
353                 err(1, "getifaddrs");
354
355         cp = NULL;
356         ifindex = 0;
357         for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
358                 memset(&paifr, 0, sizeof(paifr));
359                 strlcpy(paifr.ifr_name, ifa->ifa_name, sizeof(paifr.ifr_name));
360                 if (sizeof(paifr.ifr_addr) >= ifa->ifa_addr->sa_len) {
361                         memcpy(&paifr.ifr_addr, ifa->ifa_addr,
362                                ifa->ifa_addr->sa_len);
363                 }
364
365                 if (ifname != NULL && strcmp(ifname, ifa->ifa_name) != 0)
366                         continue;
367                 if (cp != NULL && strcmp(cp, ifa->ifa_name) == 0)
368                         continue;
369                 iflen = strlcpy(name, ifa->ifa_name, sizeof(name));
370                 if (iflen >= sizeof(name)) {
371                         warnx("%s: interface name too long, skipping",
372                               ifa->ifa_name);
373                         continue;
374                 }
375                 cp = ifa->ifa_name;
376
377                 if (downonly && (ifa->ifa_flags & IFF_UP) != 0)
378                         continue;
379                 if (uponly && (ifa->ifa_flags & IFF_UP) == 0)
380                         continue;
381
382                 if (ifa->ifa_addr->sa_family == AF_LINK)
383                         sdl = (const struct sockaddr_dl *)ifa->ifa_addr;
384                 else
385                         sdl = NULL;
386
387                 /* Are we just listing the interfaces? */
388                 if (namesonly) {
389                         if (afp == NULL ||
390                             afp->af_af != AF_LINK ||
391                             (sdl != NULL && sdl->sdl_type == IFT_ETHER)) {
392                                 printf("%s%s", (ifindex > 0 ? " " : ""), name);
393                                 ifindex++;
394                         }
395                         continue;
396                 }
397
398                 if (argc > 0)
399                         ifconfig(argc, argv, 0, afp);
400                 else
401                         status(afp, sdl, ifa);
402         }
403
404         if (namesonly)
405                 putchar('\n');
406
407         freeifaddrs(ifap);
408         freeformat();
409
410         return (exit_code);
411 }
412
413
414 static struct afswtch *afs = NULL;
415
416 void
417 af_register(struct afswtch *p)
418 {
419         p->af_next = afs;
420         afs = p;
421 }
422
423 static struct afswtch *
424 af_getbyname(const char *name)
425 {
426         struct afswtch *afp;
427
428         for (afp = afs; afp !=  NULL; afp = afp->af_next)
429                 if (strcmp(afp->af_name, name) == 0)
430                         return afp;
431         return NULL;
432 }
433
434 static struct afswtch *
435 af_getbyfamily(int af)
436 {
437         struct afswtch *afp;
438
439         for (afp = afs; afp != NULL; afp = afp->af_next)
440                 if (afp->af_af == af)
441                         return afp;
442         return NULL;
443 }
444
445 static void
446 af_other_status(int s)
447 {
448         struct afswtch *afp;
449         uint8_t afmask[howmany(AF_MAX, NBBY)];
450
451         memset(afmask, 0, sizeof(afmask));
452         for (afp = afs; afp != NULL; afp = afp->af_next) {
453                 if (afp->af_other_status == NULL)
454                         continue;
455                 if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
456                         continue;
457                 afp->af_other_status(s);
458                 setbit(afmask, afp->af_af);
459         }
460 }
461
462 static void
463 af_all_tunnel_status(int s)
464 {
465         struct afswtch *afp;
466         uint8_t afmask[howmany(AF_MAX, NBBY)];
467
468         memset(afmask, 0, sizeof(afmask));
469         for (afp = afs; afp != NULL; afp = afp->af_next) {
470                 if (afp->af_status_tunnel == NULL)
471                         continue;
472                 if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
473                         continue;
474                 afp->af_status_tunnel(s);
475                 setbit(afmask, afp->af_af);
476         }
477 }
478
479 static struct cmd *cmds = NULL;
480
481 void
482 cmd_register(struct cmd *p)
483 {
484         p->c_next = cmds;
485         cmds = p;
486 }
487
488 static const struct cmd *
489 cmd_lookup(const char *name, int iscreate)
490 {
491         const struct cmd *p;
492
493         for (p = cmds; p != NULL; p = p->c_next) {
494                 if (strcmp(name, p->c_name) == 0) {
495                         if (iscreate) {
496                                 if (p->c_iscloneop)
497                                         return p;
498                         } else {
499                                 if (!p->c_iscloneop)
500                                         return p;
501                         }
502                 }
503         }
504
505         return NULL;
506 }
507
508 struct callback {
509         callback_func *cb_func;
510         void    *cb_arg;
511         struct callback *cb_next;
512 };
513 static struct callback *callbacks = NULL;
514
515 void
516 callback_register(callback_func *func, void *arg)
517 {
518         struct callback *cb;
519
520         cb = malloc(sizeof(struct callback));
521         if (cb == NULL)
522                 errx(1, "unable to allocate memory for callback");
523         cb->cb_func = func;
524         cb->cb_arg = arg;
525         cb->cb_next = callbacks;
526         callbacks = cb;
527 }
528
529 /* specially-handled commands */
530 static void setifaddr(const char *, int, int, const struct afswtch *);
531 static const struct cmd setifaddr_cmd = DEF_CMD("ifaddr", 0, setifaddr);
532
533 static void setifdstaddr(const char *, int, int, const struct afswtch *);
534 static const struct cmd setifdstaddr_cmd =
535         DEF_CMD("ifdstaddr", 0, setifdstaddr);
536
537 static int
538 ifconfig(int argc, char *const *argv, int iscreate,
539          const struct afswtch *uafp)
540 {
541         const struct afswtch *afp, *nafp;
542         struct callback *cb;
543         int s;
544
545         strlcpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
546         afp = uafp != NULL ? uafp : af_getbyname("inet");
547 top:
548         ifr.ifr_addr.sa_family =
549                 afp->af_af == AF_LINK || afp->af_af == AF_UNSPEC ?
550                 AF_LOCAL : afp->af_af;
551
552         if ((s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0)) < 0 &&
553             (uafp != NULL || errno != EAFNOSUPPORT ||
554              (s = socket(AF_LOCAL, SOCK_DGRAM, 0)) < 0))
555                 err(1, "socket(family %u,SOCK_DGRAM)", ifr.ifr_addr.sa_family);
556
557         while (argc > 0) {
558                 const struct cmd *p;
559
560                 p = cmd_lookup(*argv, iscreate);
561
562                 if (iscreate && p == NULL) {
563                         /*
564                          * Push the clone create callback so the new
565                          * device is created and can be used for any
566                          * remaining arguments.
567                          */
568                         cb = callbacks;
569                         if (cb == NULL)
570                                 errx(1, "internal error, no callback");
571                         callbacks = cb->cb_next;
572                         cb->cb_func(s, cb->cb_arg);
573                         iscreate = 0;
574
575                         /*
576                          * After cloning, make sure we have an up-to-date name
577                          * in ifr_name.
578                          */
579                         strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
580
581                         /*
582                          * Handle any address family spec that
583                          * immediately follows and potentially
584                          * recreate the socket.
585                          */
586                         nafp = af_getbyname(*argv);
587                         if (nafp != NULL) {
588                                 argc--, argv++;
589                                 if (nafp != afp) {
590                                         close(s);
591                                         afp = nafp;
592                                         goto top;
593                                 }
594                         }
595                         /*
596                          * Look for a normal parameter.
597                          */
598                         continue;
599                 }
600                 if (p == NULL) {
601                         /*
602                          * Not a recognized command, choose between setting
603                          * the interface address and the dst address.
604                          */
605                         p = (setaddr ? &setifdstaddr_cmd : &setifaddr_cmd);
606                 }
607                 if (p->c_u.c_func || p->c_u.c_func2) {
608                         if (p->c_parameter == NEXTARG) {
609                                 if (argv[1] == NULL)
610                                         errx(1, "'%s' requires argument",
611                                             p->c_name);
612                                 p->c_u.c_func(argv[1], 0, s, afp);
613                                 argc--, argv++;
614                         } else if (p->c_parameter == OPTARG) {
615                                 p->c_u.c_func(argv[1], 0, s, afp);
616                                 if (argv[1] != NULL)
617                                         argc--, argv++;
618                         } else if (p->c_parameter == NEXTARG2) {
619                                 if (argc < 3)
620                                         errx(1, "'%s' requires 2 arguments",
621                                             p->c_name);
622                                 p->c_u.c_func2(argv[1], argv[2], s, afp);
623                                 argc -= 2, argv += 2;
624                         } else
625                                 p->c_u.c_func(*argv, p->c_parameter, s, afp);
626                 }
627                 argc--, argv++;
628         }
629
630         /*
631          * Do any post argument processing required by the address family.
632          */
633         if (afp->af_postproc != NULL)
634                 afp->af_postproc(s, afp);
635         /*
636          * Do deferred callbacks registered while processing
637          * command-line arguments.
638          */
639         for (cb = callbacks; cb != NULL; cb = cb->cb_next)
640                 cb->cb_func(s, cb->cb_arg);
641         /*
642          * Do deferred operations.
643          */
644         if (clearaddr) {
645                 if (afp->af_ridreq == NULL || afp->af_difaddr == 0) {
646                         warnx("interface %s cannot change %s addresses!",
647                               name, afp->af_name);
648                         clearaddr = 0;
649                 }
650         }
651         if (clearaddr) {
652                 int ret;
653                 strlcpy(afp->af_ridreq, name, sizeof ifr.ifr_name);
654                 ret = ioctl(s, afp->af_difaddr, afp->af_ridreq);
655                 if (ret < 0) {
656                         if (errno == EADDRNOTAVAIL && (doalias >= 0)) {
657                                 /* means no previous address for interface */
658                         } else
659                                 Perror("ioctl (SIOCDIFADDR)");
660                 }
661         }
662         if (newaddr) {
663                 if (afp->af_addreq == NULL || afp->af_aifaddr == 0) {
664                         warnx("interface %s cannot change %s addresses!",
665                               name, afp->af_name);
666                         newaddr = 0;
667                 }
668         }
669         if (newaddr && (setaddr || setmask)) {
670                 strlcpy(afp->af_addreq, name, sizeof ifr.ifr_name);
671                 if (ioctl(s, afp->af_aifaddr, afp->af_addreq) < 0)
672                         Perror("ioctl (SIOCAIFADDR)");
673         }
674
675         close(s);
676         return (0);
677 }
678
679 /*ARGSUSED*/
680 static void
681 setifaddr(const char *addr, int param, int s, const struct afswtch *afp)
682 {
683         if (afp->af_getaddr == NULL)
684                 return;
685         /*
686          * Delay the ioctl to set the interface addr until flags are all set.
687          * The address interpretation may depend on the flags,
688          * and the flags may change when the address is set.
689          */
690         setaddr++;
691         if (doalias == 0 && afp->af_af != AF_LINK)
692                 clearaddr = 1;
693         afp->af_getaddr(addr, (doalias >= 0 ? ADDR : RIDADDR));
694 }
695
696 static void
697 settunnel(const char *src, const char *dst, int s, const struct afswtch *afp)
698 {
699         struct addrinfo *srcres, *dstres;
700         int ecode;
701
702         if (afp->af_settunnel == NULL) {
703                 warn("address family %s does not support tunnel setup",
704                         afp->af_name);
705                 return;
706         }
707
708         if ((ecode = getaddrinfo(src, NULL, NULL, &srcres)) != 0)
709                 errx(1, "error in parsing address string: %s",
710                     gai_strerror(ecode));
711
712         if ((ecode = getaddrinfo(dst, NULL, NULL, &dstres)) != 0)
713                 errx(1, "error in parsing address string: %s",
714                     gai_strerror(ecode));
715
716         if (srcres->ai_addr->sa_family != dstres->ai_addr->sa_family)
717                 errx(1,
718                     "source and destination address families do not match");
719
720         afp->af_settunnel(s, srcres, dstres);
721
722         freeaddrinfo(srcres);
723         freeaddrinfo(dstres);
724 }
725
726 /* ARGSUSED */
727 static void
728 deletetunnel(const char *vname, int param, int s, const struct afswtch *afp)
729 {
730
731         if (ioctl(s, SIOCDIFPHYADDR, &ifr) < 0)
732                 err(1, "SIOCDIFPHYADDR");
733 }
734
735 static void
736 setifnetmask(const char *addr, int dummy __unused, int s,
737     const struct afswtch *afp)
738 {
739         if (afp->af_getaddr != NULL) {
740                 setmask++;
741                 afp->af_getaddr(addr, MASK);
742         }
743 }
744
745 static void
746 setifbroadaddr(const char *addr, int dummy __unused, int s,
747     const struct afswtch *afp)
748 {
749         if (afp->af_getaddr != NULL)
750                 afp->af_getaddr(addr, DSTADDR);
751 }
752
753 static void
754 notealias(const char *addr, int param, int s, const struct afswtch *afp)
755 {
756 #define rqtosa(x) (&(((struct ifreq *)(afp->x))->ifr_addr))
757         if (setaddr && doalias == 0 && param < 0)
758                 if (afp->af_addreq != NULL && afp->af_ridreq != NULL)
759                         bcopy((caddr_t)rqtosa(af_addreq),
760                               (caddr_t)rqtosa(af_ridreq),
761                               rqtosa(af_addreq)->sa_len);
762         doalias = param;
763         if (param < 0) {
764                 clearaddr = 1;
765                 newaddr = 0;
766         } else {
767                 clearaddr = 0;
768         }
769 #undef rqtosa
770 }
771
772 /*ARGSUSED*/
773 static void
774 setifdstaddr(const char *addr, int param __unused, int s,
775     const struct afswtch *afp)
776 {
777         if (afp->af_getaddr != NULL)
778                 afp->af_getaddr(addr, DSTADDR);
779 }
780
781 static void
782 setifflags(const char *vname, int value, int s, const struct afswtch *afp)
783 {
784         struct ifreq my_ifr;
785         int flags;
786
787         memset(&my_ifr, 0, sizeof(struct ifreq));
788         strlcpy(my_ifr.ifr_name, name, sizeof(my_ifr.ifr_name));
789
790         if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&my_ifr) < 0)
791                 Perror("ioctl (SIOCGIFFLAGS)");
792
793         flags = (my_ifr.ifr_flags & 0xffff) | (my_ifr.ifr_flagshigh << 16);
794         if (value < 0) {
795                 value = -value;
796                 flags &= ~value;
797         } else {
798                 flags |= value;
799         }
800         my_ifr.ifr_flags = flags & 0xffff;
801         my_ifr.ifr_flagshigh = flags >> 16;
802         if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&my_ifr) < 0)
803                 Perror(vname);
804 }
805
806 void
807 setifcap(const char *vname, int value, int s, const struct afswtch *afp)
808 {
809         int flags;
810
811         if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) < 0)
812                 Perror("ioctl (SIOCGIFCAP)");
813
814         flags = ifr.ifr_curcap;
815         if (value < 0) {
816                 value = -value;
817                 flags &= ~value;
818         } else {
819                 flags |= value;
820         }
821         ifr.ifr_reqcap = flags;
822         if (ioctl(s, SIOCSIFCAP, (caddr_t)&ifr) < 0)
823                 Perror(vname);
824 }
825
826 static void
827 setifmetric(const char *val, int dummy __unused, int s,
828     const struct afswtch *afp)
829 {
830         strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
831         ifr.ifr_metric = atoi(val);
832         if (ioctl(s, SIOCSIFMETRIC, (caddr_t)&ifr) < 0)
833                 err(1, "ioctl SIOCSIFMETRIC (set metric)");
834 }
835
836 static void
837 setifmtu(const char *val, int dummy __unused, int s,
838     const struct afswtch *afp)
839 {
840         strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
841         ifr.ifr_mtu = atoi(val);
842         if (ioctl(s, SIOCSIFMTU, (caddr_t)&ifr) < 0)
843                 err(1, "ioctl SIOCSIFMTU (set mtu)");
844 }
845
846 static void
847 setiftsolen(const char *val, int dummy __unused, int s,
848     const struct afswtch *afp)
849 {
850         strlcpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
851         ifr.ifr_tsolen = atoi(val);
852         if (ioctl(s, SIOCSIFTSOLEN, (caddr_t)&ifr) < 0)
853                 err(1, "ioctl SIOCSIFTSOLEN (set tsolen)");
854 }
855
856 static void
857 setifname(const char *val, int dummy __unused, int s,
858     const struct afswtch *afp)
859 {
860         char *newname;
861
862         strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
863
864         newname = strdup(val);
865         if (newname == NULL)
866                 err(1, "no memory to set ifname");
867         ifr.ifr_data = newname;
868         if (ioctl(s, SIOCSIFNAME, (caddr_t)&ifr) < 0) {
869                 free(newname);
870                 err(1, "ioctl SIOCSIFNAME (set name)");
871         }
872         printifname = 1;
873         strlcpy(name, newname, sizeof(name));
874         free(newname);
875 }
876
877 static void
878 setifpollcpu(const char *val, int dummy __unused, int s,
879     const struct afswtch *afp)
880 {
881         warnx("pollcpu is deprecated, use polling or npolling instead");
882         setifflags("npolling", IFF_NPOLLING, s, afp);
883 }
884
885
886 #define IFFBITS \
887 "\020\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5POINTOPOINT\6SMART\7RUNNING" \
888 "\10NOARP\11PROMISC\12ALLMULTI\14SIMPLEX\15LINK0\16LINK1\17LINK2" \
889 "\20MULTICAST\22PPROMISC\23MONITOR\24STATICARP\25NPOLLING\26IDIRECT"
890
891 #define IFCAPBITS \
892 "\020\1RXCSUM\2TXCSUM\3NETCONS\4VLAN_MTU\5VLAN_HWTAGGING\6JUMBO_MTU\7RSS" \
893 "\10VLAN_HWCSUM\11TSO"
894
895 /*
896  * Print the status of the interface.  If an address family was
897  * specified, show only it; otherwise, show them all.
898  */
899 static void
900 status(const struct afswtch *afp, const struct sockaddr_dl *sdl,
901        struct ifaddrs *ifa)
902 {
903         struct ifaddrs *ift;
904         int allfamilies, s;
905         struct ifstat ifs;
906
907         if (afp == NULL) {
908                 allfamilies = 1;
909                 ifr.ifr_addr.sa_family = AF_LOCAL;
910         } else {
911                 allfamilies = 0;
912                 ifr.ifr_addr.sa_family =
913                     afp->af_af == AF_LINK ? AF_LOCAL : afp->af_af;
914         }
915         strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
916
917         s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0);
918         if (s < 0)
919                 err(1, "socket(family %u,SOCK_DGRAM)", ifr.ifr_addr.sa_family);
920
921         printf("%s: ", name);
922         printb("flags", ifa->ifa_flags, IFFBITS);
923         if (ioctl(s, SIOCGIFMETRIC, &ifr) != -1)
924                 printf(" metric %d", ifr.ifr_metric);
925         if (ioctl(s, SIOCGIFMTU, &ifr) != -1)
926                 printf(" mtu %d", ifr.ifr_mtu);
927         putchar('\n');
928
929         if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) == 0) {
930                 if (ifr.ifr_curcap != 0) {
931                         printb("\toptions", ifr.ifr_curcap, IFCAPBITS);
932                         putchar('\n');
933                 }
934                 if (supmedia && ifr.ifr_reqcap != 0) {
935                         printb("\tcapabilities", ifr.ifr_reqcap, IFCAPBITS);
936                         putchar('\n');
937                         if (ifr.ifr_reqcap & IFCAP_TSO) {
938                                 if (ioctl(s, SIOCGIFTSOLEN,
939                                     (caddr_t)&ifr) == 0) {
940                                         printf("\ttsolen %d", ifr.ifr_tsolen);
941                                         putchar('\n');
942                                 }
943                         }
944                 }
945         }
946
947         tunnel_status(s);
948
949         for (ift = ifa; ift != NULL; ift = ift->ifa_next) {
950                 if (ift->ifa_addr == NULL)
951                         continue;
952                 if (strcmp(ifa->ifa_name, ift->ifa_name) != 0)
953                         continue;
954                 if (allfamilies) {
955                         const struct afswtch *p;
956                         p = af_getbyfamily(ift->ifa_addr->sa_family);
957                         if (p != NULL && p->af_status != NULL)
958                                 p->af_status(s, ift);
959                 } else if (afp->af_af == ift->ifa_addr->sa_family)
960                         afp->af_status(s, ift);
961         }
962 #if 0
963         if (allfamilies || afp->af_af == AF_LINK) {
964                 const struct afswtch *lafp;
965
966                 /*
967                  * Hack; the link level address is received separately
968                  * from the routing information so any address is not
969                  * handled above.  Cobble together an entry and invoke
970                  * the status method specially.
971                  */
972                 lafp = af_getbyname("lladdr");
973                 if (lafp != NULL) {
974                         info.rti_info[RTAX_IFA] = (struct sockaddr *)sdl;
975                         lafp->af_status(s, &info);
976                 }
977         }
978 #endif
979         if (allfamilies)
980                 af_other_status(s);
981         else if (afp->af_other_status != NULL)
982                 afp->af_other_status(s);
983
984         strlcpy(ifs.ifs_name, name, sizeof ifs.ifs_name);
985         if (ioctl(s, SIOCGIFSTATUS, &ifs) == 0)
986                 printf("%s", ifs.ascii);
987
988         close(s);
989         return;
990 }
991
992 static void
993 tunnel_status(int s)
994 {
995         af_all_tunnel_status(s);
996 }
997
998 void
999 Perror(const char *cmd)
1000 {
1001         switch (errno) {
1002
1003         case ENXIO:
1004                 errx(1, "%s: no such interface", cmd);
1005                 break;
1006
1007         case EPERM:
1008                 errx(1, "%s: permission denied", cmd);
1009                 break;
1010
1011         default:
1012                 err(1, "%s", cmd);
1013         }
1014 }
1015
1016 /*
1017  * Print a value a la the %pb%i format of the kernel's kprintf()
1018  */
1019 void
1020 printb(const char *s, unsigned v, const char *bits)
1021 {
1022         int i, any = 0;
1023         char c;
1024
1025         if (bits && *bits == 8)
1026                 printf("%s=%o", s, v);
1027         else
1028                 printf("%s=%x", s, v);
1029         bits++;
1030         if (bits) {
1031                 putchar('<');
1032                 while ((i = *bits++) != '\0') {
1033                         if (v & (1 << (i-1))) {
1034                                 if (any)
1035                                         putchar(',');
1036                                 any = 1;
1037                                 for (; (c = *bits) > 32; bits++)
1038                                         putchar(c);
1039                         } else
1040                                 for (; *bits > 32; bits++)
1041                                         ;
1042                 }
1043                 putchar('>');
1044         }
1045 }
1046
1047 void
1048 ifmaybeload(const char *name)
1049 {
1050 #define MOD_PREFIX_LEN          3       /* "if_" */
1051         struct module_stat mstat;
1052         int fileid, modid;
1053         char ifkind[IFNAMSIZ + MOD_PREFIX_LEN], ifname[IFNAMSIZ], *dp;
1054         const char *cp;
1055
1056         /* loading suppressed by the user */
1057         if (noload)
1058                 return;
1059
1060         /* trim the interface number off the end */
1061         strlcpy(ifname, name, sizeof(ifname));
1062         for (dp = ifname; *dp != 0; dp++)
1063                 if (isdigit(*dp)) {
1064                         *dp = 0;
1065                         break;
1066                 }
1067
1068         /* turn interface and unit into module name */
1069         strlcpy(ifkind, "if_", sizeof(ifkind));
1070         strlcat(ifkind, ifname, sizeof(ifkind));
1071
1072         /* scan files in kernel */
1073         mstat.version = sizeof(struct module_stat);
1074         for (fileid = kldnext(0); fileid > 0; fileid = kldnext(fileid)) {
1075                 /* scan modules in file */
1076                 for (modid = kldfirstmod(fileid); modid > 0;
1077                      modid = modfnext(modid)) {
1078                         if (modstat(modid, &mstat) < 0)
1079                                 continue;
1080                         /* strip bus name if present */
1081                         if ((cp = strchr(mstat.name, '/')) != NULL) {
1082                                 cp++;
1083                         } else {
1084                                 cp = mstat.name;
1085                         }
1086                         /* already loaded? */
1087                         if (strcmp(ifname, cp) == 0 ||
1088                             strcmp(ifkind, cp) == 0)
1089                                 return;
1090                 }
1091         }
1092
1093         /* not present, we should try to load it */
1094         kldload(ifkind);
1095 }
1096
1097 static struct cmd basic_cmds[] = {
1098         DEF_CMD("up",           IFF_UP,         setifflags),
1099         DEF_CMD("down",         -IFF_UP,        setifflags),
1100         DEF_CMD("arp",          -IFF_NOARP,     setifflags),
1101         DEF_CMD("-arp",         IFF_NOARP,      setifflags),
1102         DEF_CMD("debug",        IFF_DEBUG,      setifflags),
1103         DEF_CMD("-debug",       -IFF_DEBUG,     setifflags),
1104         DEF_CMD("promisc",      IFF_PPROMISC,   setifflags),
1105         DEF_CMD("-promisc",     -IFF_PPROMISC,  setifflags),
1106         DEF_CMD("add",          IFF_UP,         notealias),
1107         DEF_CMD("alias",        IFF_UP,         notealias),
1108         DEF_CMD("-alias",       -IFF_UP,        notealias),
1109         DEF_CMD("delete",       -IFF_UP,        notealias),
1110         DEF_CMD("remove",       -IFF_UP,        notealias),
1111 #ifdef notdef
1112 #define EN_SWABIPS      0x1000
1113         DEF_CMD("swabips",      EN_SWABIPS,     setifflags),
1114         DEF_CMD("-swabips",     -EN_SWABIPS,    setifflags),
1115 #endif
1116         DEF_CMD_ARG("netmask",                  setifnetmask),
1117         DEF_CMD_ARG("metric",                   setifmetric),
1118         DEF_CMD_ARG("broadcast",                setifbroadaddr),
1119         DEF_CMD_ARG2("tunnel",                  settunnel),
1120         DEF_CMD("-tunnel", 0,                   deletetunnel),
1121         DEF_CMD("deletetunnel", 0,              deletetunnel),
1122         DEF_CMD("link0",        IFF_LINK0,      setifflags),
1123         DEF_CMD("-link0",       -IFF_LINK0,     setifflags),
1124         DEF_CMD("link1",        IFF_LINK1,      setifflags),
1125         DEF_CMD("-link1",       -IFF_LINK1,     setifflags),
1126         DEF_CMD("link2",        IFF_LINK2,      setifflags),
1127         DEF_CMD("-link2",       -IFF_LINK2,     setifflags),
1128         DEF_CMD("monitor",      IFF_MONITOR,    setifflags),
1129         DEF_CMD("-monitor",     -IFF_MONITOR,   setifflags),
1130         DEF_CMD("staticarp",    IFF_STATICARP,  setifflags),
1131         DEF_CMD("-staticarp",   -IFF_STATICARP, setifflags),
1132         DEF_CMD("polling",      IFF_NPOLLING,   setifflags),
1133         DEF_CMD("-polling",     -IFF_NPOLLING,  setifflags),
1134         DEF_CMD("npolling",     IFF_NPOLLING,   setifflags),
1135         DEF_CMD("-npolling",    -IFF_NPOLLING,  setifflags),
1136         DEF_CMD("rxcsum",       IFCAP_RXCSUM,   setifcap),
1137         DEF_CMD("-rxcsum",      -IFCAP_RXCSUM,  setifcap),
1138         DEF_CMD("txcsum",       IFCAP_TXCSUM,   setifcap),
1139         DEF_CMD("-txcsum",      -IFCAP_TXCSUM,  setifcap),
1140         DEF_CMD("netcons",      IFCAP_NETCONS,  setifcap),
1141         DEF_CMD("-netcons",     -IFCAP_NETCONS, setifcap),
1142         DEF_CMD("rss",          IFCAP_RSS,      setifcap),
1143         DEF_CMD("-rss",         -IFCAP_RSS,     setifcap),
1144         DEF_CMD("tso",          IFCAP_TSO,      setifcap),
1145         DEF_CMD("-tso",         -IFCAP_TSO,     setifcap),
1146         DEF_CMD("normal",       -IFF_LINK0,     setifflags),
1147         DEF_CMD("compress",     IFF_LINK0,      setifflags),
1148         DEF_CMD("noicmp",       IFF_LINK1,      setifflags),
1149         DEF_CMD_ARG("mtu",                      setifmtu),
1150         DEF_CMD_ARG("name",                     setifname),
1151         DEF_CMD_ARG("pollcpu",                  setifpollcpu),
1152         DEF_CMD_ARG("tsolen",                   setiftsolen)
1153 };
1154
1155 static __constructor(101) void
1156 ifconfig_ctor(void)
1157 {
1158         size_t i;
1159
1160         for (i = 0; i < nitems(basic_cmds);  i++)
1161                 cmd_register(&basic_cmds[i]);
1162 }