2de7409deb9383a2143d44827aa32603121134ce
[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  * 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  * $FreeBSD: src/sbin/ifconfig/ifconfig.c,v 1.113.2.4 2006/02/09 10:48:43 yar Exp $
30  * $DragonFly: src/sbin/ifconfig/ifconfig.c,v 1.26 2006/04/02 03:33:59 sephe Exp $
31  */
32
33 #include <sys/param.h>
34 #include <sys/ioctl.h>
35 #include <sys/socket.h>
36 #include <sys/sysctl.h>
37 #include <sys/time.h>
38 #include <sys/module.h>
39 #include <sys/linker.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 <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62
63 #include "ifconfig.h"
64
65 /*
66  * This macro returns the size of a struct sockaddr when passed
67  * through a routing socket. Basically we round up sa_len to
68  * a multiple of sizeof(long), with a minimum of sizeof(long).
69  * The check for a NULL pointer is just a convenience, probably never used.
70  * The case sa_len == 0 should only apply to empty structures.
71  */     
72 #define SA_SIZE(sa)                                             \
73     (  (!(sa) || ((struct sockaddr *)(sa))->sa_len == 0) ?      \
74         sizeof(long)            :                               \
75         1 + ( (((struct sockaddr *)(sa))->sa_len - 1) | (sizeof(long) - 1) ) )
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 int     flags;
86 int     setaddr;
87 int     setipdst;
88 int     setmask;
89 int     doalias;
90 int     clearaddr;
91 int     newaddr = 1;
92 int     verbose;
93
94 int     supmedia = 0;
95 int     printkeys = 0;          /* Print keying material for interfaces. */
96 int     printname = 0;          /* Print the name of the created interface. */
97
98 static  int ifconfig(int argc, char *const *argv, const struct afswtch *afp);
99 static  void status(const struct afswtch *afp, int addrcount,
100                     struct sockaddr_dl *sdl, struct if_msghdr *ifm,
101                     struct ifa_msghdr *ifam);
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         int need_nl = 0, count = 0;
147         const struct afswtch *afp = NULL;
148         int addrcount, ifindex;
149         struct if_msghdr *ifm, *nextifm;
150         struct ifa_msghdr *ifam;
151         struct sockaddr_dl *sdl;
152         char *buf, *lim, *next;
153         size_t needed;
154         int mib[6];
155         char options[1024];
156         struct option *p;
157
158         all = downonly = uponly = namesonly = verbose = 0;
159
160         /* Parse leading line options */
161         strlcpy(options, "adklmuv", sizeof(options));
162         for (p = opts; p != NULL; p = p->next)
163                 strlcat(options, p->opt, sizeof(options));
164         while ((c = getopt(argc, argv, options)) != -1) {
165                 switch (c) {
166                 case 'a':       /* scan all interfaces */
167                         all++;
168                         break;
169                 case 'd':       /* restrict scan to "down" interfaces */
170                         downonly++;
171                         break;
172                 case 'k':
173                         printkeys++;
174                         break;
175                 case 'l':       /* scan interface names only */
176                         namesonly++;
177                         break;
178                 case 'm':       /* show media choices in status */
179                         supmedia = 1;
180                         break;
181                 case 'u':       /* restrict scan to "up" interfaces */
182                         uponly++;
183                         break;
184                 case 'v':
185                         verbose++;
186                         break;
187                 default:
188                         for (p = opts; p != NULL; p = p->next)
189                                 if (p->opt[0] == c) {
190                                         p->cb(optarg);
191                                         break;
192                                 }
193                         if (p == NULL)
194                                 usage();
195                         break;
196                 }
197         }
198         argc -= optind;
199         argv += optind;
200
201         /* -l cannot be used with -a or -m */
202         if (namesonly && (all || supmedia))
203                 usage();
204
205         /* nonsense.. */
206         if (uponly && downonly)
207                 usage();
208
209         /* no arguments is equivalent to '-a' */
210         if (!namesonly && argc < 1)
211                 all = 1;
212
213         /* -a and -l allow an address family arg to limit the output */
214         if (all || namesonly) {
215                 if (argc > 1)
216                         usage();
217
218                 ifindex = 0;
219                 if (argc == 1) {
220                         afp = af_getbyname(*argv);
221                         if (afp == NULL)
222                                 usage();
223                         if (afp->af_name != NULL)
224                                 argc--, argv++;
225                         /* leave with afp non-zero */
226                 }
227         } else {
228                 /* not listing, need an argument */
229                 if (argc < 1)
230                         usage();
231
232                 strncpy(name, *argv, sizeof(name));
233                 argc--, argv++;
234
235                 /* check and maybe load support for this interface */
236                 ifmaybeload(name);
237
238                 /*
239                  * NOTE:  We must special-case the `create' command right
240                  * here as we would otherwise fail when trying to find
241                  * the interface.
242                  */
243                 if (argc > 0 && (strcmp(argv[0], "create") == 0 ||
244                     strcmp(argv[0], "plumb") == 0)) {
245                         clone_create();
246                         argc--, argv++;
247                         if (argc == 0)
248                                 goto end;
249                 }
250                 ifindex = if_nametoindex(name);
251                 if (ifindex == 0)
252                         errx(1, "interface %s does not exist", name);
253         }
254
255         /* Check for address family */
256         if (argc > 0) {
257                 afp = af_getbyname(*argv);
258                 if (afp != NULL)
259                         argc--, argv++;
260         }
261
262 retry:
263         mib[0] = CTL_NET;
264         mib[1] = PF_ROUTE;
265         mib[2] = 0;
266         mib[3] = 0;                     /* address family */
267         mib[4] = NET_RT_IFLIST;
268         mib[5] = ifindex;               /* interface index */
269
270         /* if particular family specified, only ask about it */
271         if (afp != NULL)
272                 mib[3] = afp->af_af;
273
274         if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
275                 errx(1, "iflist-sysctl-estimate");
276         if ((buf = malloc(needed)) == NULL)
277                 errx(1, "malloc");
278         if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
279                 if (errno == ENOMEM && count++ < 10) {
280                         warnx("Routing table grew, retrying");
281                         free(buf);
282                         sleep(1);
283                         goto retry;
284                 }
285                 errx(1, "actual retrieval of interface table");
286         }
287         lim = buf + needed;
288
289         next = buf;
290         while (next < lim) {
291
292                 ifm = (struct if_msghdr *)next;
293                 
294                 if (ifm->ifm_type == RTM_IFINFO) {
295 #ifdef notyet
296                         if (ifm->ifm_data.ifi_datalen == 0)
297                                 ifm->ifm_data.ifi_datalen = sizeof(struct if_data);
298                         sdl = (struct sockaddr_dl *)((char *)ifm + sizeof(struct if_msghdr) -
299                             sizeof(struct if_data) + ifm->ifm_data.ifi_datalen);
300 #else
301                         sdl = (struct sockaddr_dl *)(ifm + 1);
302 #endif
303                         flags = ifm->ifm_flags;
304                 } else {
305                         fprintf(stderr, "out of sync parsing NET_RT_IFLIST\n");
306                         fprintf(stderr, "expected %d, got %d\n", RTM_IFINFO,
307                                 ifm->ifm_type);
308                         fprintf(stderr, "msglen = %d\n", ifm->ifm_msglen);
309                         fprintf(stderr, "buf:%p, next:%p, lim:%p\n", buf, next,
310                                 lim);
311                         exit (1);
312                 }
313
314                 next += ifm->ifm_msglen;
315                 ifam = NULL;
316                 addrcount = 0;
317                 while (next < lim) {
318
319                         nextifm = (struct if_msghdr *)next;
320
321                         if (nextifm->ifm_type != RTM_NEWADDR)
322                                 break;
323
324                         if (ifam == NULL)
325                                 ifam = (struct ifa_msghdr *)nextifm;
326
327                         addrcount++;
328                         next += nextifm->ifm_msglen;
329                 }
330                 memcpy(name, sdl->sdl_data,
331                     sizeof(name) < sdl->sdl_nlen ?
332                     sizeof(name)-1 : sdl->sdl_nlen);
333                 name[sizeof(name) < sdl->sdl_nlen ?
334                     sizeof(name)-1 : sdl->sdl_nlen] = '\0';
335
336                 if (all || namesonly) {
337                         if (uponly)
338                                 if ((flags & IFF_UP) == 0)
339                                         continue; /* not up */
340                         if (downonly)
341                                 if (flags & IFF_UP)
342                                         continue; /* not down */
343                         if (namesonly) {
344                                 if (afp == NULL || afp->af_af != AF_LINK ||
345                                     sdl->sdl_type == IFT_ETHER) {
346                                         if (need_nl)
347                                                 putchar(' ');
348                                         fputs(name, stdout);
349                                         need_nl++;
350                                 }
351                                 continue;
352                         }
353                 }
354
355                 if (argc > 0)
356                         ifconfig(argc, argv, afp);
357                 else
358                         status(afp, addrcount, sdl, ifm, ifam);
359         }
360         free(buf);
361
362         if (namesonly && need_nl > 0)
363                 putchar('\n');
364 end:
365         if (printname)
366                 printf("%s\n", name);
367
368         exit (0);
369 }
370
371 static struct afswtch *afs = NULL;
372
373 void
374 af_register(struct afswtch *p)
375 {
376         p->af_next = afs;
377         afs = p;
378 }
379
380 static struct afswtch *
381 af_getbyname(const char *name)
382 {
383         struct afswtch *afp;
384
385         for (afp = afs; afp !=  NULL; afp = afp->af_next)
386                 if (strcmp(afp->af_name, name) == 0)
387                         return afp;
388         return NULL;
389 }
390
391 static struct afswtch *
392 af_getbyfamily(int af)
393 {
394         struct afswtch *afp;
395
396         for (afp = afs; afp != NULL; afp = afp->af_next)
397                 if (afp->af_af == af)
398                         return afp;
399         return NULL;
400 }
401
402 static void
403 af_other_status(int s)
404 {
405         struct afswtch *afp;
406         uint8_t afmask[howmany(AF_MAX, NBBY)];
407
408         memset(afmask, 0, sizeof(afmask));
409         for (afp = afs; afp != NULL; afp = afp->af_next) {
410                 if (afp->af_other_status == NULL)
411                         continue;
412                 if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
413                         continue;
414                 afp->af_other_status(s);
415                 setbit(afmask, afp->af_af);
416         }
417 }
418
419 static void
420 af_all_tunnel_status(int s)
421 {
422         struct afswtch *afp;
423         uint8_t afmask[howmany(AF_MAX, NBBY)];
424
425         memset(afmask, 0, sizeof(afmask));
426         for (afp = afs; afp != NULL; afp = afp->af_next) {
427                 if (afp->af_status_tunnel == NULL)
428                         continue;
429                 if (afp->af_af != AF_UNSPEC && isset(afmask, afp->af_af))
430                         continue;
431                 afp->af_status_tunnel(s);
432                 setbit(afmask, afp->af_af);
433         }
434 }
435
436 static struct cmd *cmds = NULL;
437
438 void
439 cmd_register(struct cmd *p)
440 {
441         p->c_next = cmds;
442         cmds = p;
443 }
444
445 static const struct cmd *
446 cmd_lookup(const char *name)
447 {
448 #define N(a)    (sizeof(a)/sizeof(a[0]))
449         const struct cmd *p;
450
451         for (p = cmds; p != NULL; p = p->c_next)
452                 if (strcmp(name, p->c_name) == 0)
453                         return p;
454         return NULL;
455 #undef N
456 }
457
458 struct callback {
459         callback_func *cb_func;
460         void    *cb_arg;
461         struct callback *cb_next;
462 };
463 static struct callback *callbacks = NULL;
464
465 void
466 callback_register(callback_func *func, void *arg)
467 {
468         struct callback *cb;
469
470         cb = malloc(sizeof(struct callback));
471         if (cb == NULL)
472                 errx(1, "unable to allocate memory for callback");
473         cb->cb_func = func;
474         cb->cb_arg = arg;
475         cb->cb_next = callbacks;
476         callbacks = cb;
477 }
478
479 /* specially-handled commands */
480 static void setifaddr(const char *, int, int, const struct afswtch *);
481 static const struct cmd setifaddr_cmd = DEF_CMD("ifaddr", 0, setifaddr);
482
483 static void setifdstaddr(const char *, int, int, const struct afswtch *);
484 static const struct cmd setifdstaddr_cmd =
485         DEF_CMD("ifdstaddr", 0, setifdstaddr);
486
487 static int
488 ifconfig(int argc, char *const *argv, const struct afswtch *afp)
489 {
490         struct callback *cb;
491         int s;
492
493         if (afp == NULL)
494                 afp = af_getbyname("inet");
495         ifr.ifr_addr.sa_family =
496                 afp->af_af == AF_LINK || afp->af_af == AF_UNSPEC ?
497                 AF_INET : afp->af_af;
498         strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
499
500         if ((s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0)) < 0)
501                 err(1, "socket(family %u,SOCK_DGRAM", ifr.ifr_addr.sa_family);
502
503         while (argc > 0) {
504                 const struct cmd *p;
505
506                 p = cmd_lookup(*argv);
507                 if (p == NULL) {
508                         /*
509                          * Not a recognized command, choose between setting
510                          * the interface address and the dst address.
511                          */
512                         p = (setaddr ? &setifdstaddr_cmd : &setifaddr_cmd);
513                 }
514                 if (p->c_u.c_func || p->c_u.c_func2) {
515                         if (p->c_parameter == NEXTARG) {
516                                 if (argv[1] == NULL)
517                                         errx(1, "'%s' requires argument",
518                                             p->c_name);
519                                 p->c_u.c_func(argv[1], 0, s, afp);
520                                 argc--, argv++;
521                         } else if (p->c_parameter == OPTARG) {
522                                 p->c_u.c_func(argv[1], 0, s, afp);
523                                 if (argv[1] != NULL)
524                                         argc--, argv++;
525                         } else if (p->c_parameter == NEXTARG2) {
526                                 if (argc < 3)
527                                         errx(1, "'%s' requires 2 arguments",
528                                             p->c_name);
529                                 p->c_u.c_func2(argv[1], argv[2], s, afp);
530                                 argc -= 2, argv += 2;
531                         } else
532                                 p->c_u.c_func(*argv, p->c_parameter, s, afp);
533                 }
534                 argc--, argv++;
535         }
536
537         /*
538          * Do any post argument processing required by the address family.
539          */
540         if (afp->af_postproc != NULL)
541                 afp->af_postproc(s, afp);
542         /*
543          * Do deferred callbacks registered while processing
544          * command-line arguments.
545          */
546         for (cb = callbacks; cb != NULL; cb = cb->cb_next)
547                 cb->cb_func(s, cb->cb_arg);
548         /*
549          * Do deferred operations.
550          */
551         if (clearaddr) {
552                 if (afp->af_ridreq == NULL || afp->af_difaddr == 0) {
553                         warnx("interface %s cannot change %s addresses!",
554                               name, afp->af_name);
555                         clearaddr = 0;
556                 }
557         }
558         if (clearaddr) {
559                 int ret;
560                 strncpy(afp->af_ridreq, name, sizeof ifr.ifr_name);
561                 ret = ioctl(s, afp->af_difaddr, afp->af_ridreq);
562                 if (ret < 0) {
563                         if (errno == EADDRNOTAVAIL && (doalias >= 0)) {
564                                 /* means no previous address for interface */
565                         } else
566                                 Perror("ioctl (SIOCDIFADDR)");
567                 }
568         }
569         if (newaddr) {
570                 if (afp->af_addreq == NULL || afp->af_aifaddr == 0) {
571                         warnx("interface %s cannot change %s addresses!",
572                               name, afp->af_name);
573                         newaddr = 0;
574                 }
575         }
576         if (newaddr && (setaddr || setmask)) {
577                 strncpy(afp->af_addreq, name, sizeof ifr.ifr_name);
578                 if (ioctl(s, afp->af_aifaddr, afp->af_addreq) < 0)
579                         Perror("ioctl (SIOCAIFADDR)");
580         }
581
582         close(s);
583         return(0);
584 }
585
586 /*ARGSUSED*/
587 static void
588 setifaddr(const char *addr, int param, int s, const struct afswtch *afp)
589 {
590         if (afp->af_getaddr == NULL)
591                 return;
592         /*
593          * Delay the ioctl to set the interface addr until flags are all set.
594          * The address interpretation may depend on the flags,
595          * and the flags may change when the address is set.
596          */
597         setaddr++;
598         if (doalias == 0 && afp->af_af != AF_LINK)
599                 clearaddr = 1;
600         afp->af_getaddr(addr, (doalias >= 0 ? ADDR : RIDADDR));
601 }
602
603 static void
604 settunnel(const char *src, const char *dst, int s, const struct afswtch *afp)
605 {
606         struct addrinfo *srcres, *dstres;
607         int ecode;
608
609         if (afp->af_settunnel == NULL) {
610                 warn("address family %s does not support tunnel setup",
611                         afp->af_name);
612                 return;
613         }
614
615         if ((ecode = getaddrinfo(src, NULL, NULL, &srcres)) != 0)
616                 errx(1, "error in parsing address string: %s",
617                     gai_strerror(ecode));
618
619         if ((ecode = getaddrinfo(dst, NULL, NULL, &dstres)) != 0)  
620                 errx(1, "error in parsing address string: %s",
621                     gai_strerror(ecode));
622
623         if (srcres->ai_addr->sa_family != dstres->ai_addr->sa_family)
624                 errx(1,
625                     "source and destination address families do not match");
626
627         afp->af_settunnel(s, srcres, dstres);
628
629         freeaddrinfo(srcres);
630         freeaddrinfo(dstres);
631 }
632
633 /* ARGSUSED */
634 static void
635 deletetunnel(const char *vname, int param, int s, const struct afswtch *afp)
636 {
637
638         if (ioctl(s, SIOCDIFPHYADDR, &ifr) < 0)
639                 err(1, "SIOCDIFPHYADDR");
640 }
641
642 static void
643 setifnetmask(const char *addr, int dummy __unused, int s,
644     const struct afswtch *afp)
645 {
646         if (afp->af_getaddr != NULL) {
647                 setmask++;
648                 afp->af_getaddr(addr, MASK);
649         }
650 }
651
652 static void
653 setifbroadaddr(const char *addr, int dummy __unused, int s,
654     const struct afswtch *afp)
655 {
656         if (afp->af_getaddr != NULL)
657                 afp->af_getaddr(addr, DSTADDR);
658 }
659
660 static void
661 setifipdst(const char *addr, int dummy __unused, int s,
662     const struct afswtch *afp)
663 {
664         const struct afswtch *inet;
665
666         inet = af_getbyname("inet");
667         if (inet == NULL)
668                 return;
669         inet->af_getaddr(addr, DSTADDR);
670         setipdst++;
671         clearaddr = 0;
672         newaddr = 0;
673 }
674
675 static void
676 notealias(const char *addr, int param, int s, const struct afswtch *afp)
677 {
678 #define rqtosa(x) (&(((struct ifreq *)(afp->x))->ifr_addr))
679         if (setaddr && doalias == 0 && param < 0)
680                 if (afp->af_addreq != NULL && afp->af_ridreq != NULL)
681                         bcopy((caddr_t)rqtosa(af_addreq),
682                               (caddr_t)rqtosa(af_ridreq),
683                               rqtosa(af_addreq)->sa_len);
684         doalias = param;
685         if (param < 0) {
686                 clearaddr = 1;
687                 newaddr = 0;
688         } else
689                 clearaddr = 0;
690 #undef rqtosa
691 }
692
693 /*ARGSUSED*/
694 static void
695 setifdstaddr(const char *addr, int param __unused, int s, 
696     const struct afswtch *afp)
697 {
698         if (afp->af_getaddr != NULL)
699                 afp->af_getaddr(addr, DSTADDR);
700 }
701
702 /*
703  * Note: doing an SIOCIGIFFLAGS scribbles on the union portion
704  * of the ifreq structure, which may confuse other parts of ifconfig.
705  * Make a private copy so we can avoid that.
706  */
707 static void
708 setifflags(const char *vname, int value, int s, const struct afswtch *afp)
709 {
710         struct ifreq            my_ifr;
711
712         bcopy((char *)&ifr, (char *)&my_ifr, sizeof(struct ifreq));
713
714         if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&my_ifr) < 0) {
715                 Perror("ioctl (SIOCGIFFLAGS)");
716                 exit(1);
717         }
718         strncpy(my_ifr.ifr_name, name, sizeof (my_ifr.ifr_name));
719         flags = (my_ifr.ifr_flags & 0xffff) | (my_ifr.ifr_flagshigh << 16);
720
721         if (value < 0) {
722                 value = -value;
723                 flags &= ~value;
724         } else
725                 flags |= value;
726         my_ifr.ifr_flags = flags & 0xffff;
727         my_ifr.ifr_flagshigh = flags >> 16;
728         if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&my_ifr) < 0)
729                 Perror(vname);
730 }
731
732 void
733 setifcap(const char *vname, int value, int s, const struct afswtch *afp)
734 {
735
736         if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) < 0) {
737                 Perror("ioctl (SIOCGIFCAP)");
738                 exit(1);
739         }
740         flags = ifr.ifr_curcap;
741         if (value < 0) {
742                 value = -value;
743                 flags &= ~value;
744         } else
745                 flags |= value;
746         ifr.ifr_reqcap = flags;
747         if (ioctl(s, SIOCSIFCAP, (caddr_t)&ifr) < 0)
748                 Perror(vname);
749 }
750
751 static void
752 setifmetric(const char *val, int dummy __unused, int s, 
753     const struct afswtch *afp)
754 {
755         strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
756         ifr.ifr_metric = atoi(val);
757         if (ioctl(s, SIOCSIFMETRIC, (caddr_t)&ifr) < 0)
758                 warn("ioctl (set metric)");
759 }
760
761 static void
762 setifmtu(const char *val, int dummy __unused, int s, 
763     const struct afswtch *afp)
764 {
765         strncpy(ifr.ifr_name, name, sizeof (ifr.ifr_name));
766         ifr.ifr_mtu = atoi(val);
767         if (ioctl(s, SIOCSIFMTU, (caddr_t)&ifr) < 0)
768                 warn("ioctl (set mtu)");
769 }
770
771 static void
772 setifname(const char *val, int dummy __unused, int s, 
773     const struct afswtch *afp)
774 {
775         char *newname;
776
777         newname = strdup(val);
778         if (newname == NULL) {
779                 warn("no memory to set ifname");
780                 return;
781         }
782         ifr.ifr_data = newname;
783         if (ioctl(s, SIOCSIFNAME, (caddr_t)&ifr) < 0) {
784                 warn("ioctl (set name)");
785                 free(newname);
786                 return;
787         }
788         strlcpy(name, newname, sizeof(name));
789         free(newname);
790
791         /*
792          * Even if we just created the interface, we don't need to print
793          * its name because we just nailed it down separately.
794          */
795         printname = 0;
796 }
797
798 /*
799  * Expand the compacted form of addresses as returned via the
800  * configuration read via sysctl().
801  */
802 static void
803 rt_xaddrs(caddr_t cp, caddr_t cplim, struct rt_addrinfo *rtinfo)
804 {
805         struct sockaddr *sa;
806         int i;
807
808         memset(rtinfo->rti_info, 0, sizeof(rtinfo->rti_info));
809         for (i = 0; (i < RTAX_MAX) && (cp < cplim); i++) {
810                 if ((rtinfo->rti_addrs & (1 << i)) == 0)
811                         continue;
812                 rtinfo->rti_info[i] = sa = (struct sockaddr *)cp;
813                 cp += SA_SIZE(sa);
814         }
815 }
816
817 #define IFFBITS \
818 "\020\1UP\2BROADCAST\3DEBUG\4LOOPBACK\5POINTOPOINT\6SMART\7RUNNING" \
819 "\10NOARP\11PROMISC\12ALLMULTI\13OACTIVE\14SIMPLEX\15LINK0\16LINK1\17LINK2" \
820 "\20MULTICAST\21POLLING\22PPROMISC\23MONITOR\24STATICARP\25NEEDSGIANT"
821
822 #define IFCAPBITS \
823 "\020\1RXCSUM\2TXCSUM\3NETCONS\4VLAN_MTU\5VLAN_HWTAGGING\6JUMBO_MTU\7POLLING"
824
825 /*
826  * Print the status of the interface.  If an address family was
827  * specified, show only it; otherwise, show them all.
828  */
829 static void
830 status(const struct afswtch *afp, int addrcount, struct sockaddr_dl *sdl,
831     struct if_msghdr *ifm, struct ifa_msghdr *ifam)
832 {
833         struct  rt_addrinfo info;
834         int allfamilies, s;
835         struct ifstat ifs;
836
837         if (afp == NULL) {
838                 allfamilies = 1;
839                 afp = af_getbyname("inet");
840         } else
841                 allfamilies = 0;
842
843         ifr.ifr_addr.sa_family = afp->af_af == AF_LINK ? AF_INET : afp->af_af;
844         strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
845
846         s = socket(ifr.ifr_addr.sa_family, SOCK_DGRAM, 0);
847         if (s < 0)
848                 err(1, "socket(family %u,SOCK_DGRAM)", ifr.ifr_addr.sa_family);
849
850         printf("%s: ", name);
851         printb("flags", flags, IFFBITS);
852         if (ifm->ifm_data.ifi_metric)
853                 printf(" metric %ld", ifm->ifm_data.ifi_metric);
854         if (ifm->ifm_data.ifi_mtu)
855                 printf(" mtu %ld", ifm->ifm_data.ifi_mtu);
856         putchar('\n');
857
858         if (ioctl(s, SIOCGIFCAP, (caddr_t)&ifr) == 0) {
859                 if (ifr.ifr_curcap != 0) {
860                         printb("\toptions", ifr.ifr_curcap, IFCAPBITS);
861                         putchar('\n');
862                 }
863                 if (supmedia && ifr.ifr_reqcap != 0) {
864                         printb("\tcapabilities", ifr.ifr_reqcap, IFCAPBITS);
865                         putchar('\n');
866                 }
867         }
868
869         tunnel_status(s);
870
871         while (addrcount > 0) {
872                 info.rti_addrs = ifam->ifam_addrs;
873                 /* Expand the compacted addresses */
874                 rt_xaddrs((char *)(ifam + 1), ifam->ifam_msglen + (char *)ifam,
875                           &info);
876
877                 if (allfamilies) {
878                         const struct afswtch *p;
879                         p = af_getbyfamily(info.rti_info[RTAX_IFA]->sa_family);
880                         if (p != NULL && p->af_status != NULL)
881                                 p->af_status(s, &info);
882                 } else if (afp->af_af == info.rti_info[RTAX_IFA]->sa_family)
883                         afp->af_status(s, &info);
884                 addrcount--;
885                 ifam = (struct ifa_msghdr *)((char *)ifam + ifam->ifam_msglen);
886         }
887         if (allfamilies || afp->af_af == AF_LINK) {
888                 const struct afswtch *lafp;
889
890                 /*
891                  * Hack; the link level address is received separately
892                  * from the routing information so any address is not
893                  * handled above.  Cobble together an entry and invoke
894                  * the status method specially.
895                  */
896                 lafp = af_getbyname("lladdr");
897                 if (lafp != NULL) {
898                         info.rti_info[RTAX_IFA] = (struct sockaddr *)sdl;
899                         lafp->af_status(s, &info);
900                 }
901         }
902         if (allfamilies)
903                 af_other_status(s);
904         else if (afp->af_other_status != NULL)
905                 afp->af_other_status(s);
906
907         strncpy(ifs.ifs_name, name, sizeof ifs.ifs_name);
908         if (ioctl(s, SIOCGIFSTATUS, &ifs) == 0) 
909                 printf("%s", ifs.ascii);
910
911         close(s);
912         return;
913 }
914
915 static void
916 tunnel_status(int s)
917 {
918         af_all_tunnel_status(s);
919 }
920
921 void
922 Perror(const char *cmd)
923 {
924         switch (errno) {
925
926         case ENXIO:
927                 errx(1, "%s: no such interface", cmd);
928                 break;
929
930         case EPERM:
931                 errx(1, "%s: permission denied", cmd);
932                 break;
933
934         default:
935                 err(1, "%s", cmd);
936         }
937 }
938
939 /*
940  * Print a value a la the %b format of the kernel's printf
941  */
942 void
943 printb(const char *s, unsigned v, const char *bits)
944 {
945         int i, any = 0;
946         char c;
947
948         if (bits && *bits == 8)
949                 printf("%s=%o", s, v);
950         else
951                 printf("%s=%x", s, v);
952         bits++;
953         if (bits) {
954                 putchar('<');
955                 while ((i = *bits++) != '\0') {
956                         if (v & (1 << (i-1))) {
957                                 if (any)
958                                         putchar(',');
959                                 any = 1;
960                                 for (; (c = *bits) > 32; bits++)
961                                         putchar(c);
962                         } else
963                                 for (; *bits > 32; bits++)
964                                         ;
965                 }
966                 putchar('>');
967         }
968 }
969
970 void
971 ifmaybeload(char *name)
972 {
973         struct module_stat mstat;
974         int fileid, modid;
975         char ifkind[35], *cp, *dp;
976
977         /* turn interface and unit into module name */
978         strcpy(ifkind, "if_");
979         for (cp = name, dp = ifkind + 3;
980             (*cp != 0) && !isdigit(*cp); cp++, dp++)
981                 *dp = *cp;
982         *dp = 0;
983
984         /* scan files in kernel */
985         mstat.version = sizeof(struct module_stat);
986         for (fileid = kldnext(0); fileid > 0; fileid = kldnext(fileid)) {
987                 /* scan modules in file */
988                 for (modid = kldfirstmod(fileid); modid > 0;
989                      modid = modfnext(modid)) {
990                         if (modstat(modid, &mstat) < 0)
991                                 continue;
992                         /* strip bus name if present */
993                         if ((cp = strchr(mstat.name, '/')) != NULL) {
994                                 cp++;
995                         } else {
996                                 cp = mstat.name;
997                         }
998                         /* already loaded? */
999                         if (strncmp(name, cp, strlen(cp)) == 0 ||
1000                             strncmp(ifkind, cp, strlen(cp)) == 0)
1001                                 return;
1002                 }
1003         }
1004
1005         /* not present, we should try to load it */
1006         kldload(ifkind);
1007 }
1008
1009 static struct cmd basic_cmds[] = {
1010         DEF_CMD("up",           IFF_UP,         setifflags),
1011         DEF_CMD("down",         -IFF_UP,        setifflags),
1012         DEF_CMD("arp",          -IFF_NOARP,     setifflags),
1013         DEF_CMD("-arp",         IFF_NOARP,      setifflags),
1014         DEF_CMD("debug",        IFF_DEBUG,      setifflags),
1015         DEF_CMD("-debug",       -IFF_DEBUG,     setifflags),
1016         DEF_CMD("promisc",      IFF_PPROMISC,   setifflags),
1017         DEF_CMD("-promisc",     -IFF_PPROMISC,  setifflags),
1018         DEF_CMD("add",          IFF_UP,         notealias),
1019         DEF_CMD("alias",        IFF_UP,         notealias),
1020         DEF_CMD("-alias",       -IFF_UP,        notealias),
1021         DEF_CMD("delete",       -IFF_UP,        notealias),
1022         DEF_CMD("remove",       -IFF_UP,        notealias),
1023 #ifdef notdef
1024 #define EN_SWABIPS      0x1000
1025         DEF_CMD("swabips",      EN_SWABIPS,     setifflags),
1026         DEF_CMD("-swabips",     -EN_SWABIPS,    setifflags),
1027 #endif
1028         DEF_CMD_ARG("netmask",                  setifnetmask),
1029         DEF_CMD_ARG("metric",                   setifmetric),
1030         DEF_CMD_ARG("broadcast",                setifbroadaddr),
1031 #ifndef NO_IPX
1032         DEF_CMD_ARG("ipdst",                    setifipdst),
1033 #endif
1034         DEF_CMD_ARG2("tunnel",                  settunnel),
1035         DEF_CMD("-tunnel", 0,                   deletetunnel),
1036         DEF_CMD("deletetunnel", 0,              deletetunnel),
1037         DEF_CMD("link0",        IFF_LINK0,      setifflags),
1038         DEF_CMD("-link0",       -IFF_LINK0,     setifflags),
1039         DEF_CMD("link1",        IFF_LINK1,      setifflags),
1040         DEF_CMD("-link1",       -IFF_LINK1,     setifflags),
1041         DEF_CMD("link2",        IFF_LINK2,      setifflags),
1042         DEF_CMD("-link2",       -IFF_LINK2,     setifflags),
1043 #ifdef notyet
1044         DEF_CMD("monitor",      IFF_MONITOR,    setifflags),
1045         DEF_CMD("-monitor",     -IFF_MONITOR,   setifflags),
1046         DEF_CMD("staticarp",    IFF_STATICARP,  setifflags),
1047         DEF_CMD("-staticarp",   -IFF_STATICARP, setifflags),
1048 #endif
1049         DEF_CMD("polling",      IFF_POLLING,    setifcap),
1050         DEF_CMD("-polling",     -IFF_POLLING,   setifcap),
1051         DEF_CMD("rxcsum",       IFCAP_RXCSUM,   setifcap),
1052         DEF_CMD("-rxcsum",      -IFCAP_RXCSUM,  setifcap),
1053         DEF_CMD("txcsum",       IFCAP_TXCSUM,   setifcap),
1054         DEF_CMD("-txcsum",      -IFCAP_TXCSUM,  setifcap),
1055         DEF_CMD("netcons",      IFCAP_NETCONS,  setifcap),
1056         DEF_CMD("-netcons",     -IFCAP_NETCONS, setifcap),
1057         DEF_CMD("normal",       -IFF_LINK0,     setifflags),
1058         DEF_CMD("compress",     IFF_LINK0,      setifflags),
1059         DEF_CMD("noicmp",       IFF_LINK1,      setifflags),
1060         DEF_CMD_ARG("mtu",                      setifmtu),
1061         DEF_CMD_ARG("name",                     setifname),
1062 };
1063
1064 static __constructor void
1065 ifconfig_ctor(void)
1066 {
1067 #define N(a)    (sizeof(a) / sizeof(a[0]))
1068         int i;
1069
1070         for (i = 0; i < N(basic_cmds);  i++)
1071                 cmd_register(&basic_cmds[i]);
1072 #undef N
1073 }