ifwatchd.c revision 1.34 1 /* $NetBSD: ifwatchd.c,v 1.34 2016/09/29 13:36:30 roy Exp $ */
2
3 /*-
4 * Copyright (c) 2002, 2003 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Martin Husemann <martin (at) NetBSD.org>.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * Define this for special treatment of sys/net/if_spppsubr.c based interfaces.
34 */
35 #define SPPP_IF_SUPPORT
36
37 #include <sys/types.h>
38 #include <sys/param.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #include <sys/queue.h>
42 #include <sys/wait.h>
43 #include <net/if.h>
44 #include <net/if_dl.h>
45 #include <net/if_media.h>
46 #ifdef SPPP_IF_SUPPORT
47 #include <net/if_sppp.h>
48 #endif
49 #include <net/route.h>
50 #include <netinet/in.h>
51 #include <netinet/in_var.h>
52 #include <arpa/inet.h>
53
54 #include <paths.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <unistd.h>
59 #include <netdb.h>
60 #include <err.h>
61 #include <ifaddrs.h>
62 #include <syslog.h>
63
64 enum event { ARRIVAL, DEPARTURE, UP, DOWN, CARRIER, NO_CARRIER };
65 enum addrflag { NOTREADY, DETACHED, READY };
66
67 /* local functions */
68 __dead static void usage(void);
69 static void dispatch(const void *, size_t);
70 static enum addrflag check_addrflags(int af, int addrflags);
71 static void check_addrs(const struct ifa_msghdr *ifam);
72 static void invoke_script(const struct sockaddr *sa, const struct sockaddr *dst,
73 enum event ev, int ifindex, const char *ifname_hint);
74 static void list_interfaces(const char *ifnames);
75 static void check_announce(const struct if_announcemsghdr *ifan);
76 static void check_carrier(const struct if_msghdr *ifm);
77 static void rescan_interfaces(void);
78 static void free_interfaces(void);
79 static struct interface_data * find_interface(int index);
80 static void run_initial_ups(void);
81
82 #ifdef SPPP_IF_SUPPORT
83 static int check_is_connected(const char * ifname, int def_retvalue);
84 #define if_is_connected(X) (check_is_connected((X), 1))
85 #define if_is_not_connected(X) (!check_is_connected((X), 0))
86 #else
87 #define if_is_connected(X) 1
88 #define if_is_not_connected(X) 1
89 #endif
90
91 /* global variables */
92 static int verbose = 0, quiet = 0;
93 static int inhibit_initial = 0;
94 static const char *arrival_script = NULL;
95 static const char *departure_script = NULL;
96 static const char *up_script = NULL;
97 static const char *down_script = NULL;
98 static const char *carrier_script = NULL;
99 static const char *no_carrier_script = NULL;
100 static const char DummyTTY[] = _PATH_DEVNULL;
101 static const char DummySpeed[] = "9600";
102 static const char **scripts[] = {
103 &arrival_script,
104 &departure_script,
105 &up_script,
106 &down_script,
107 &carrier_script,
108 &no_carrier_script
109 };
110
111 struct interface_data {
112 SLIST_ENTRY(interface_data) next;
113 int index;
114 int last_carrier_status;
115 char * ifname;
116 };
117 static SLIST_HEAD(,interface_data) ifs = SLIST_HEAD_INITIALIZER(ifs);
118
119 int
120 main(int argc, char **argv)
121 {
122 int c, s, n;
123 int errs = 0;
124 struct msghdr msg;
125 struct iovec iov[1];
126 char buf[2048];
127
128 openlog(argv[0], LOG_PID|LOG_CONS, LOG_DAEMON);
129 while ((c = getopt(argc, argv, "qvhic:n:u:d:A:D:")) != -1) {
130 switch (c) {
131 case 'h':
132 usage();
133 return 0;
134
135 case 'i':
136 inhibit_initial = 1;
137 break;
138
139 case 'v':
140 verbose++;
141 break;
142
143 case 'q':
144 quiet = 1;
145 break;
146
147 case 'c':
148 carrier_script = optarg;
149 break;
150
151 case 'n':
152 no_carrier_script = optarg;
153 break;
154
155 case 'u':
156 up_script = optarg;
157 break;
158
159 case 'd':
160 down_script = optarg;
161 break;
162
163 case 'A':
164 arrival_script = optarg;
165 break;
166
167 case 'D':
168 departure_script = optarg;
169 break;
170
171 default:
172 errs++;
173 break;
174 }
175 }
176
177 if (errs)
178 usage();
179
180 argv += optind;
181 argc -= optind;
182
183 if (argc <= 0)
184 usage();
185
186 if (verbose) {
187 printf("up_script: %s\ndown_script: %s\n",
188 up_script, down_script);
189 printf("arrival_script: %s\ndeparture_script: %s\n",
190 arrival_script, departure_script);
191 printf("carrier_script: %s\nno_carrier_script: %s\n",
192 carrier_script, no_carrier_script);
193 printf("verbosity = %d\n", verbose);
194 }
195
196 while (argc > 0) {
197 list_interfaces(argv[0]);
198 argv++;
199 argc--;
200 }
201
202 if (!verbose)
203 daemon(0, 0);
204
205 s = socket(PF_ROUTE, SOCK_RAW, 0);
206 if (s < 0) {
207 syslog(LOG_ERR, "error opening routing socket: %m");
208 perror("open routing socket");
209 exit(EXIT_FAILURE);
210 }
211
212 if (!inhibit_initial)
213 run_initial_ups();
214
215 iov[0].iov_base = buf;
216 iov[0].iov_len = sizeof(buf);
217 memset(&msg, 0, sizeof(msg));
218 msg.msg_iov = iov;
219 msg.msg_iovlen = 1;
220
221 for (;;) {
222 n = recvmsg(s, &msg, 0);
223 if (n == -1) {
224 syslog(LOG_ERR, "recvmsg: %m");
225 exit(EXIT_FAILURE);
226 }
227 if (n != 0)
228 dispatch(iov[0].iov_base, n);
229 }
230
231 close(s);
232 free_interfaces();
233 closelog();
234
235 return EXIT_SUCCESS;
236 }
237
238 static void
239 usage(void)
240 {
241 fprintf(stderr,
242 "usage:\n"
243 "\tifwatchd [-hiqv] [-A arrival-script] [-D departure-script]\n"
244 "\t\t [-d down-script] [-u up-script]\n"
245 "\t\t [-c carrier-script] [-n no-carrier-script] ifname(s)\n"
246 "\twhere:\n"
247 "\t -A <cmd> specify command to run on interface arrival event\n"
248 "\t -c <cmd> specify command to run on interface carrier-detect event\n"
249 "\t -D <cmd> specify command to run on interface departure event\n"
250 "\t -d <cmd> specify command to run on interface down event\n"
251 "\t -n <cmd> specify command to run on interface no-carrier-detect event\n"
252 "\t -h show this help message\n"
253 "\t -i no (!) initial run of the up script if the interface\n"
254 "\t is already up on ifwatchd startup\n"
255 "\t -q quiet mode, don't syslog informational messages\n"
256 "\t -u <cmd> specify command to run on interface up event\n"
257 "\t -v verbose/debug output, don't run in background\n");
258 exit(EXIT_FAILURE);
259 }
260
261 static void
262 dispatch(const void *msg, size_t len)
263 {
264 const struct rt_msghdr *hd = msg;
265
266 if (hd->rtm_version != RTM_VERSION)
267 return;
268
269 switch (hd->rtm_type) {
270 case RTM_NEWADDR:
271 case RTM_DELADDR:
272 check_addrs(msg);
273 break;
274 case RTM_IFANNOUNCE:
275 rescan_interfaces();
276 check_announce(msg);
277 break;
278 case RTM_IFINFO:
279 check_carrier(msg);
280 break;
281 case RTM_ADD:
282 case RTM_DELETE:
283 case RTM_CHANGE:
284 case RTM_LOSING:
285 case RTM_REDIRECT:
286 case RTM_MISS:
287 case RTM_IEEE80211:
288 case RTM_ONEWADDR:
289 case RTM_ODELADDR:
290 case RTM_OCHGADDR:
291 break;
292 default:
293 if (verbose)
294 printf("unknown message ignored (%d)\n", hd->rtm_type);
295 break;
296 }
297 }
298
299 static enum addrflag
300 check_addrflags(int af, int addrflags)
301 {
302
303 switch (af) {
304 case AF_INET:
305 if (addrflags & IN_IFF_NOTREADY)
306 return NOTREADY;
307 if (addrflags & IN_IFF_DETACHED)
308 return DETACHED;
309 break;
310 case AF_INET6:
311 if (addrflags & IN6_IFF_NOTREADY)
312 return NOTREADY;
313 if (addrflags & IN6_IFF_DETACHED)
314 return DETACHED;
315 break;
316 }
317 return READY;
318 }
319
320 static void
321 check_addrs(const struct ifa_msghdr *ifam)
322 {
323 const char *cp = (const char *)(ifam + 1);
324 const struct sockaddr *sa, *ifa = NULL, *brd = NULL;
325 unsigned i;
326 struct interface_data *ifd = NULL;
327 int aflag;
328 enum event ev;
329
330 if (ifam->ifam_addrs == 0)
331 return;
332 for (i = 1; i; i <<= 1) {
333 if ((i & ifam->ifam_addrs) == 0)
334 continue;
335 sa = (const struct sockaddr *)cp;
336 if (i == RTA_IFP) {
337 const struct sockaddr_dl *li;
338
339 li = (const struct sockaddr_dl *)sa;
340 if ((ifd = find_interface(li->sdl_index)) == NULL) {
341 if (verbose)
342 printf("ignoring change"
343 " on interface #%d\n",
344 li->sdl_index);
345 return;
346 }
347 } else if (i == RTA_IFA)
348 ifa = sa;
349 else if (i == RTA_BRD)
350 brd = sa;
351 RT_ADVANCE(cp, sa);
352 }
353 if (ifa != NULL && ifd != NULL) {
354 ev = ifam->ifam_type == RTM_DELADDR ? DOWN : UP;
355 aflag = check_addrflags(ifa->sa_family, ifam->ifam_addrflags);
356 if (ev == UP) {
357 if (aflag == NOTREADY)
358 return;
359 if (aflag == DETACHED)
360 return; /* XXX set ev to DOWN? */
361 }
362 if ((ev == UP && if_is_connected(ifd->ifname)) ||
363 (ev == DOWN && if_is_not_connected(ifd->ifname)))
364 invoke_script(ifa, brd, ev, ifd->index, ifd->ifname);
365 }
366 }
367
368 static void
369 invoke_script(const struct sockaddr *sa, const struct sockaddr *dest,
370 enum event ev, int ifindex, const char *ifname_hint)
371 {
372 char addr[NI_MAXHOST], daddr[NI_MAXHOST], ifname_buf[IFNAMSIZ];
373 const char * volatile ifname;
374 const char *script;
375 int status;
376
377 if (sa != NULL) {
378 if (sa->sa_len == 0) {
379 fprintf(stderr,
380 "illegal socket address (sa_len == 0)\n");
381 return;
382 }
383 switch (sa->sa_family) {
384 case AF_INET:
385 {
386 const struct sockaddr_in *sin;
387
388 sin = (const struct sockaddr_in *)sa;
389 if (sin->sin_addr.s_addr == INADDR_ANY ||
390 sin->sin_addr.s_addr == INADDR_BROADCAST)
391 return;
392 }
393 case AF_INET6:
394 {
395 const struct sockaddr_in6 *sin6;
396
397 sin6 = (const struct sockaddr_in6 *)sa;
398 if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))
399 return;
400 }
401 }
402 }
403
404 addr[0] = daddr[0] = 0;
405 ifname = if_indextoname(ifindex, ifname_buf);
406 ifname = ifname ? ifname : ifname_hint;
407 if (ifname == NULL)
408 return;
409
410 if (sa != NULL) {
411 if (getnameinfo(sa, sa->sa_len, addr, sizeof addr, NULL, 0,
412 NI_NUMERICHOST)) {
413 if (verbose)
414 printf("getnameinfo failed\n");
415 return; /* this address can not be handled */
416 }
417 }
418 if (dest != NULL) {
419 if (getnameinfo(dest, dest->sa_len, daddr, sizeof daddr,
420 NULL, 0, NI_NUMERICHOST)) {
421 if (verbose)
422 printf("getnameinfo failed\n");
423 return; /* this address can not be handled */
424 }
425 }
426
427 script = *scripts[ev];
428 if (script == NULL) return;
429
430 if (verbose)
431 (void) printf("calling: %s %s %s %s %s %s\n",
432 script, ifname, DummyTTY, DummySpeed, addr, daddr);
433 if (!quiet)
434 syslog(LOG_INFO, "calling: %s %s %s %s %s %s\n",
435 script, ifname, DummyTTY, DummySpeed, addr, daddr);
436
437 switch (vfork()) {
438 case -1:
439 fprintf(stderr, "cannot fork\n");
440 break;
441 case 0:
442 if (execl(script, script, ifname, DummyTTY, DummySpeed,
443 addr, daddr, NULL) == -1) {
444 syslog(LOG_ERR, "could not execute \"%s\": %m",
445 script);
446 perror(script);
447 }
448 _exit(EXIT_FAILURE);
449 default:
450 (void) wait(&status);
451 }
452 }
453
454 static void
455 list_interfaces(const char *ifnames)
456 {
457 char * names = strdup(ifnames);
458 char * name, *lasts;
459 static const char sep[] = " \t";
460 struct interface_data * p;
461
462 for (name = strtok_r(names, sep, &lasts);
463 name != NULL;
464 name = strtok_r(NULL, sep, &lasts)) {
465 p = malloc(sizeof(*p));
466 SLIST_INSERT_HEAD(&ifs, p, next);
467 p->last_carrier_status = -1;
468 p->ifname = strdup(name);
469 p->index = if_nametoindex(p->ifname);
470 if (!quiet)
471 syslog(LOG_INFO, "watching interface %s", p->ifname);
472 if (verbose)
473 printf("interface \"%s\" has index %d\n",
474 p->ifname, p->index);
475 }
476 free(names);
477 }
478
479 static void
480 check_carrier(const struct if_msghdr *ifm)
481 {
482 struct interface_data * p;
483 int carrier_status;
484 enum event ev;
485
486 SLIST_FOREACH(p, &ifs, next)
487 if (p->index == ifm->ifm_index)
488 break;
489
490 if (p == NULL)
491 return;
492
493 /*
494 * Treat it as an event worth handling if:
495 * - the carrier status changed, or
496 * - this is the first time we've been called, and
497 * inhibit_initial is not set
498 */
499 carrier_status = ifm->ifm_data.ifi_link_state;
500 if ((carrier_status != p->last_carrier_status) ||
501 ((p->last_carrier_status == -1) && !inhibit_initial)) {
502 switch (carrier_status) {
503 case LINK_STATE_UP:
504 ev = CARRIER;
505 break;
506 case LINK_STATE_DOWN:
507 ev = NO_CARRIER;
508 break;
509 default:
510 if (verbose)
511 printf("unknown link status ignored\n");
512 return;
513 }
514 invoke_script(NULL, NULL, ev, ifm->ifm_index, p->ifname);
515 p->last_carrier_status = carrier_status;
516 }
517 }
518
519 static void
520 check_announce(const struct if_announcemsghdr *ifan)
521 {
522 struct interface_data * p;
523 const char *ifname = ifan->ifan_name;
524
525 SLIST_FOREACH(p, &ifs, next) {
526 if (strcmp(p->ifname, ifname) != 0)
527 continue;
528
529 switch (ifan->ifan_what) {
530 case IFAN_ARRIVAL:
531 invoke_script(NULL, NULL, ARRIVAL, p->index,
532 NULL);
533 break;
534 case IFAN_DEPARTURE:
535 invoke_script(NULL, NULL, DEPARTURE, p->index,
536 p->ifname);
537 break;
538 default:
539 if (verbose)
540 (void) printf("unknown announce: "
541 "what=%d\n", ifan->ifan_what);
542 break;
543 }
544 return;
545 }
546 }
547
548 static void
549 rescan_interfaces(void)
550 {
551 struct interface_data * p;
552
553 SLIST_FOREACH(p, &ifs, next) {
554 p->index = if_nametoindex(p->ifname);
555 if (verbose)
556 printf("interface \"%s\" has index %d\n", p->ifname,
557 p->index);
558 }
559 }
560
561 static void
562 free_interfaces(void)
563 {
564 struct interface_data * p;
565
566 while (!SLIST_EMPTY(&ifs)) {
567 p = SLIST_FIRST(&ifs);
568 SLIST_REMOVE_HEAD(&ifs, next);
569 free(p->ifname);
570 free(p);
571 }
572 }
573
574 static struct interface_data *
575 find_interface(int idx)
576 {
577 struct interface_data * p;
578
579 SLIST_FOREACH(p, &ifs, next)
580 if (p->index == idx)
581 return p;
582 return NULL;
583 }
584
585 static void
586 run_initial_ups(void)
587 {
588 struct interface_data * ifd;
589 struct ifaddrs *res = NULL, *p;
590 struct sockaddr *ifa;
591 int s, aflag;
592
593 s = socket(AF_INET, SOCK_DGRAM, 0);
594 if (s < 0)
595 return;
596
597 if (getifaddrs(&res) != 0)
598 goto out;
599
600 for (p = res; p; p = p->ifa_next) {
601 SLIST_FOREACH(ifd, &ifs, next) {
602 if (strcmp(ifd->ifname, p->ifa_name) == 0)
603 break;
604 }
605 if (ifd == NULL)
606 continue;
607
608 ifa = p->ifa_addr;
609 if (ifa != NULL && ifa->sa_family == AF_LINK)
610 invoke_script(NULL, NULL, ARRIVAL, ifd->index,
611 NULL);
612
613 if ((p->ifa_flags & IFF_UP) == 0)
614 continue;
615 if (ifa == NULL)
616 continue;
617 if (ifa->sa_family == AF_LINK) {
618 struct ifmediareq ifmr;
619
620 memset(&ifmr, 0, sizeof(ifmr));
621 strncpy(ifmr.ifm_name, ifd->ifname,
622 sizeof(ifmr.ifm_name));
623 if (ioctl(s, SIOCGIFMEDIA, &ifmr) != -1
624 && (ifmr.ifm_status & IFM_AVALID)
625 && (ifmr.ifm_status & IFM_ACTIVE)) {
626 invoke_script(NULL, NULL, CARRIER,
627 ifd->index, ifd->ifname);
628 ifd->last_carrier_status =
629 LINK_STATE_UP;
630 }
631 continue;
632 }
633 aflag = check_addrflags(ifa->sa_family, p->ifa_addrflags);
634 if (aflag != READY)
635 continue;
636 if (if_is_connected(ifd->ifname))
637 invoke_script(ifa, p->ifa_dstaddr, UP,
638 ifd->index, ifd->ifname);
639 }
640 freeifaddrs(res);
641 out:
642 close(s);
643 }
644
645 #ifdef SPPP_IF_SUPPORT
646 /*
647 * Special case support for in-kernel PPP interfaces.
648 * If these are IFF_UP, but have not yet connected or completed authentication
649 * we don't want to call the up script in the initial interface scan (there
650 * will be an UP event generated later, when IPCP completes, anyway).
651 *
652 * If this is no if_spppsubr.c based interface, this ioctl just fails and we
653 * treat is as connected.
654 */
655 static int
656 check_is_connected(const char *ifname, int def_retval)
657 {
658 int s, error;
659 struct spppstatus oldstatus;
660 struct spppstatusncp status;
661
662 memset(&status, 0, sizeof status);
663 strncpy(status.ifname, ifname, sizeof status.ifname);
664 memset(&oldstatus, 0, sizeof oldstatus);
665 strncpy(oldstatus.ifname, ifname, sizeof oldstatus.ifname);
666
667 s = socket(AF_INET, SOCK_DGRAM, 0);
668 if (s < 0)
669 return 1; /* no idea how to handle this... */
670 error = ioctl(s, SPPPGETSTATUSNCP, &status);
671 if (error != 0) {
672 error = ioctl(s, SPPPGETSTATUS, &oldstatus);
673 if (error != 0) {
674 /* not if_spppsubr.c based - return default */
675 close(s);
676 return def_retval;
677 } else {
678 /* can't query NCPs, so use default */
679 status.phase = oldstatus.phase;
680 status.ncpup = def_retval;
681 }
682 }
683 close(s);
684
685 return status.phase == SPPP_PHASE_NETWORK && status.ncpup > 0;
686 }
687 #endif
688