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