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