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