ifwatchd.c revision 1.33 1 /* $NetBSD: ifwatchd.c,v 1.33 2016/09/21 21:07:29 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 && sa->sa_len == 0) {
378 fprintf(stderr, "illegal socket address (sa_len == 0)\n");
379 return;
380 }
381 if (sa != NULL && sa->sa_family == AF_INET6) {
382 struct sockaddr_in6 sin6;
383
384 memcpy(&sin6, (const struct sockaddr_in6 *)sa, sizeof (sin6));
385 if (IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr))
386 return;
387 }
388
389 addr[0] = daddr[0] = 0;
390 ifname = if_indextoname(ifindex, ifname_buf);
391 ifname = ifname ? ifname : ifname_hint;
392 if (ifname == NULL)
393 return;
394
395 if (sa != NULL) {
396 if (getnameinfo(sa, sa->sa_len, addr, sizeof addr, NULL, 0,
397 NI_NUMERICHOST)) {
398 if (verbose)
399 printf("getnameinfo failed\n");
400 return; /* this address can not be handled */
401 }
402 }
403 if (dest != NULL) {
404 if (getnameinfo(dest, dest->sa_len, daddr, sizeof daddr,
405 NULL, 0, NI_NUMERICHOST)) {
406 if (verbose)
407 printf("getnameinfo failed\n");
408 return; /* this address can not be handled */
409 }
410 }
411
412 script = *scripts[ev];
413 if (script == NULL) return;
414
415 if (verbose)
416 (void) printf("calling: %s %s %s %s %s %s\n",
417 script, ifname, DummyTTY, DummySpeed, addr, daddr);
418 if (!quiet)
419 syslog(LOG_INFO, "calling: %s %s %s %s %s %s\n",
420 script, ifname, DummyTTY, DummySpeed, addr, daddr);
421
422 switch (vfork()) {
423 case -1:
424 fprintf(stderr, "cannot fork\n");
425 break;
426 case 0:
427 if (execl(script, script, ifname, DummyTTY, DummySpeed,
428 addr, daddr, NULL) == -1) {
429 syslog(LOG_ERR, "could not execute \"%s\": %m",
430 script);
431 perror(script);
432 }
433 _exit(EXIT_FAILURE);
434 default:
435 (void) wait(&status);
436 }
437 }
438
439 static void
440 list_interfaces(const char *ifnames)
441 {
442 char * names = strdup(ifnames);
443 char * name, *lasts;
444 static const char sep[] = " \t";
445 struct interface_data * p;
446
447 for (name = strtok_r(names, sep, &lasts);
448 name != NULL;
449 name = strtok_r(NULL, sep, &lasts)) {
450 p = malloc(sizeof(*p));
451 SLIST_INSERT_HEAD(&ifs, p, next);
452 p->last_carrier_status = -1;
453 p->ifname = strdup(name);
454 p->index = if_nametoindex(p->ifname);
455 if (!quiet)
456 syslog(LOG_INFO, "watching interface %s", p->ifname);
457 if (verbose)
458 printf("interface \"%s\" has index %d\n",
459 p->ifname, p->index);
460 }
461 free(names);
462 }
463
464 static void
465 check_carrier(const struct if_msghdr *ifm)
466 {
467 struct interface_data * p;
468 int carrier_status;
469 enum event ev;
470
471 SLIST_FOREACH(p, &ifs, next)
472 if (p->index == ifm->ifm_index)
473 break;
474
475 if (p == NULL)
476 return;
477
478 /*
479 * Treat it as an event worth handling if:
480 * - the carrier status changed, or
481 * - this is the first time we've been called, and
482 * inhibit_initial is not set
483 */
484 carrier_status = ifm->ifm_data.ifi_link_state;
485 if ((carrier_status != p->last_carrier_status) ||
486 ((p->last_carrier_status == -1) && !inhibit_initial)) {
487 switch (carrier_status) {
488 case LINK_STATE_UP:
489 ev = CARRIER;
490 break;
491 case LINK_STATE_DOWN:
492 ev = NO_CARRIER;
493 break;
494 default:
495 if (verbose)
496 printf("unknown link status ignored\n");
497 return;
498 }
499 invoke_script(NULL, NULL, ev, ifm->ifm_index, p->ifname);
500 p->last_carrier_status = carrier_status;
501 }
502 }
503
504 static void
505 check_announce(const struct if_announcemsghdr *ifan)
506 {
507 struct interface_data * p;
508 const char *ifname = ifan->ifan_name;
509
510 SLIST_FOREACH(p, &ifs, next) {
511 if (strcmp(p->ifname, ifname) != 0)
512 continue;
513
514 switch (ifan->ifan_what) {
515 case IFAN_ARRIVAL:
516 invoke_script(NULL, NULL, ARRIVAL, p->index,
517 NULL);
518 break;
519 case IFAN_DEPARTURE:
520 invoke_script(NULL, NULL, DEPARTURE, p->index,
521 p->ifname);
522 break;
523 default:
524 if (verbose)
525 (void) printf("unknown announce: "
526 "what=%d\n", ifan->ifan_what);
527 break;
528 }
529 return;
530 }
531 }
532
533 static void
534 rescan_interfaces(void)
535 {
536 struct interface_data * p;
537
538 SLIST_FOREACH(p, &ifs, next) {
539 p->index = if_nametoindex(p->ifname);
540 if (verbose)
541 printf("interface \"%s\" has index %d\n", p->ifname,
542 p->index);
543 }
544 }
545
546 static void
547 free_interfaces(void)
548 {
549 struct interface_data * p;
550
551 while (!SLIST_EMPTY(&ifs)) {
552 p = SLIST_FIRST(&ifs);
553 SLIST_REMOVE_HEAD(&ifs, next);
554 free(p->ifname);
555 free(p);
556 }
557 }
558
559 static struct interface_data *
560 find_interface(int idx)
561 {
562 struct interface_data * p;
563
564 SLIST_FOREACH(p, &ifs, next)
565 if (p->index == idx)
566 return p;
567 return NULL;
568 }
569
570 static void
571 run_initial_ups(void)
572 {
573 struct interface_data * ifd;
574 struct ifaddrs *res = NULL, *p;
575 struct sockaddr *ifa;
576 int s, aflag;
577
578 s = socket(AF_INET, SOCK_DGRAM, 0);
579 if (s < 0)
580 return;
581
582 if (getifaddrs(&res) != 0)
583 goto out;
584
585 for (p = res; p; p = p->ifa_next) {
586 SLIST_FOREACH(ifd, &ifs, next) {
587 if (strcmp(ifd->ifname, p->ifa_name) == 0)
588 break;
589 }
590 if (ifd == NULL)
591 continue;
592
593 ifa = p->ifa_addr;
594 if (ifa != NULL && ifa->sa_family == AF_LINK)
595 invoke_script(NULL, NULL, ARRIVAL, ifd->index,
596 NULL);
597
598 if ((p->ifa_flags & IFF_UP) == 0)
599 continue;
600 if (ifa == NULL)
601 continue;
602 if (ifa->sa_family == AF_LINK) {
603 struct ifmediareq ifmr;
604
605 memset(&ifmr, 0, sizeof(ifmr));
606 strncpy(ifmr.ifm_name, ifd->ifname,
607 sizeof(ifmr.ifm_name));
608 if (ioctl(s, SIOCGIFMEDIA, &ifmr) != -1
609 && (ifmr.ifm_status & IFM_AVALID)
610 && (ifmr.ifm_status & IFM_ACTIVE)) {
611 invoke_script(NULL, NULL, CARRIER,
612 ifd->index, ifd->ifname);
613 ifd->last_carrier_status =
614 LINK_STATE_UP;
615 }
616 continue;
617 }
618 aflag = check_addrflags(ifa->sa_family, p->ifa_addrflags);
619 if (aflag != READY)
620 continue;
621 if (if_is_connected(ifd->ifname))
622 invoke_script(ifa, p->ifa_dstaddr, UP,
623 ifd->index, ifd->ifname);
624 }
625 freeifaddrs(res);
626 out:
627 close(s);
628 }
629
630 #ifdef SPPP_IF_SUPPORT
631 /*
632 * Special case support for in-kernel PPP interfaces.
633 * If these are IFF_UP, but have not yet connected or completed authentication
634 * we don't want to call the up script in the initial interface scan (there
635 * will be an UP event generated later, when IPCP completes, anyway).
636 *
637 * If this is no if_spppsubr.c based interface, this ioctl just fails and we
638 * treat is as connected.
639 */
640 static int
641 check_is_connected(const char *ifname, int def_retval)
642 {
643 int s, error;
644 struct spppstatus oldstatus;
645 struct spppstatusncp status;
646
647 memset(&status, 0, sizeof status);
648 strncpy(status.ifname, ifname, sizeof status.ifname);
649 memset(&oldstatus, 0, sizeof oldstatus);
650 strncpy(oldstatus.ifname, ifname, sizeof oldstatus.ifname);
651
652 s = socket(AF_INET, SOCK_DGRAM, 0);
653 if (s < 0)
654 return 1; /* no idea how to handle this... */
655 error = ioctl(s, SPPPGETSTATUSNCP, &status);
656 if (error != 0) {
657 error = ioctl(s, SPPPGETSTATUS, &oldstatus);
658 if (error != 0) {
659 /* not if_spppsubr.c based - return default */
660 close(s);
661 return def_retval;
662 } else {
663 /* can't query NCPs, so use default */
664 status.phase = oldstatus.phase;
665 status.ncpup = def_retval;
666 }
667 }
668 close(s);
669
670 return status.phase == SPPP_PHASE_NETWORK && status.ncpup > 0;
671 }
672 #endif
673