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