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