Home | History | Annotate | Line # | Download | only in ifwatchd
ifwatchd.c revision 1.27.2.1
      1 /*	$NetBSD: ifwatchd.c,v 1.27.2.1 2016/11/04 14:49:26 pgoyette Exp $	*/
      2 #include <sys/cdefs.h>
      3 __RCSID("$NetBSD: ifwatchd.c,v 1.27.2.1 2016/11/04 14:49:26 pgoyette 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 
    112 	openlog(argv[0], LOG_PID|LOG_CONS, LOG_DAEMON);
    113 	while ((c = getopt(argc, argv, "qvhic:n:u:d:A:D:")) != -1) {
    114 		switch (c) {
    115 		case 'h':
    116 			usage();
    117 			return 0;
    118 
    119 		case 'i':
    120 			inhibit_initial = 1;
    121 			break;
    122 
    123 		case 'v':
    124 			verbose++;
    125 			break;
    126 
    127 		case 'q':
    128 			quiet = 1;
    129 			break;
    130 
    131 		case 'c':
    132 			carrier_script = optarg;
    133 			break;
    134 
    135 		case 'n':
    136 			no_carrier_script = optarg;
    137 			break;
    138 
    139 		case 'u':
    140 			up_script = optarg;
    141 			break;
    142 
    143 		case 'd':
    144 			down_script = optarg;
    145 			break;
    146 
    147 		case 'A':
    148 			arrival_script = optarg;
    149 			break;
    150 
    151 		case 'D':
    152 			departure_script = optarg;
    153 			break;
    154 
    155 		default:
    156 			errs++;
    157 			break;
    158 		}
    159 	}
    160 
    161 	if (errs)
    162 		usage();
    163 
    164 	argv += optind;
    165 	argc -= optind;
    166 
    167 	if (argc <= 0)
    168 		usage();
    169 
    170 	if (verbose) {
    171 		printf("up_script: %s\ndown_script: %s\n",
    172 			up_script, down_script);
    173 		printf("arrival_script: %s\ndeparture_script: %s\n",
    174 			arrival_script, departure_script);
    175 		printf("carrier_script: %s\nno_carrier_script: %s\n",
    176 			carrier_script, no_carrier_script);
    177 		printf("verbosity = %d\n", verbose);
    178 	}
    179 
    180 	while (argc > 0) {
    181 		list_interfaces(argv[0]);
    182 		argv++;
    183 		argc--;
    184 	}
    185 
    186 	if (!verbose)
    187 		daemon(0, 0);
    188 
    189 	s = socket(PF_ROUTE, SOCK_RAW, 0);
    190 	if (s < 0) {
    191 		syslog(LOG_ERR, "error opening routing socket: %m");
    192 		exit(EXIT_FAILURE);
    193 	}
    194 
    195 	if (!inhibit_initial)
    196 		run_initial_ups();
    197 
    198 	iov[0].iov_base = buf;
    199 	iov[0].iov_len = sizeof(buf);
    200 	memset(&msg, 0, sizeof(msg));
    201 	msg.msg_iov = iov;
    202 	msg.msg_iovlen = 1;
    203 
    204 	for (;;) {
    205 		n = recvmsg(s, &msg, 0);
    206 		if (n == -1) {
    207 			syslog(LOG_ERR, "recvmsg: %m");
    208 			exit(EXIT_FAILURE);
    209 		}
    210 		if (n != 0)
    211 			dispatch(iov[0].iov_base, n);
    212 	}
    213 
    214 	close(s);
    215 	free_interfaces();
    216 	closelog();
    217 
    218 	return EXIT_SUCCESS;
    219 }
    220 
    221 static void
    222 usage(void)
    223 {
    224 	fprintf(stderr,
    225 	    "usage:\n"
    226 	    "\tifwatchd [-hiqv] [-A arrival-script] [-D departure-script]\n"
    227 	    "\t\t  [-d down-script] [-u up-script]\n"
    228 	    "\t\t  [-c carrier-script] [-n no-carrier-script] ifname(s)\n"
    229 	    "\twhere:\n"
    230 	    "\t -A <cmd> specify command to run on interface arrival event\n"
    231 	    "\t -c <cmd> specify command to run on interface carrier-detect event\n"
    232 	    "\t -D <cmd> specify command to run on interface departure event\n"
    233 	    "\t -d <cmd> specify command to run on interface down event\n"
    234 	    "\t -n <cmd> specify command to run on interface no-carrier-detect event\n"
    235 	    "\t -h       show this help message\n"
    236 	    "\t -i       no (!) initial run of the up script if the interface\n"
    237 	    "\t          is already up on ifwatchd startup\n"
    238 	    "\t -q       quiet mode, don't syslog informational messages\n"
    239 	    "\t -u <cmd> specify command to run on interface up event\n"
    240 	    "\t -v       verbose/debug output, don't run in background\n");
    241 	exit(EXIT_FAILURE);
    242 }
    243 
    244 static void
    245 dispatch(const void *msg, size_t len)
    246 {
    247 	const struct rt_msghdr *hd = msg;
    248 
    249 	if (hd->rtm_version != RTM_VERSION)
    250 		return;
    251 
    252 	switch (hd->rtm_type) {
    253 	case RTM_NEWADDR:
    254 	case RTM_DELADDR:
    255 		check_addrs(msg);
    256 		break;
    257 	case RTM_IFANNOUNCE:
    258 		check_announce(msg);
    259 		break;
    260 	case RTM_IFINFO:
    261 		check_carrier(msg);
    262 		break;
    263 	case RTM_ADD:
    264 	case RTM_DELETE:
    265 	case RTM_CHANGE:
    266 	case RTM_LOSING:
    267 	case RTM_REDIRECT:
    268 	case RTM_MISS:
    269 	case RTM_IEEE80211:
    270 	case RTM_ONEWADDR:
    271 	case RTM_ODELADDR:
    272 	case RTM_OCHGADDR:
    273 		break;
    274 	default:
    275 		if (verbose)
    276 			printf("unknown message ignored (%d)\n", hd->rtm_type);
    277 		break;
    278 	}
    279 }
    280 
    281 static enum addrflag
    282 check_addrflags(int af, int addrflags)
    283 {
    284 
    285 	switch (af) {
    286 	case AF_INET:
    287 		if (addrflags & IN_IFF_NOTREADY)
    288 			return NOTREADY;
    289 		if (addrflags & IN_IFF_DETACHED)
    290 			return DETACHED;
    291 		break;
    292 	case AF_INET6:
    293 		if (addrflags & IN6_IFF_NOTREADY)
    294 			return NOTREADY;
    295 		if (addrflags & IN6_IFF_DETACHED)
    296 			return DETACHED;
    297 		break;
    298 	}
    299 	return READY;
    300 }
    301 
    302 static void
    303 check_addrs(const struct ifa_msghdr *ifam)
    304 {
    305 	const char *cp = (const char *)(ifam + 1);
    306 	const struct sockaddr *sa, *ifa = NULL, *brd = NULL;
    307 	unsigned i;
    308 	struct interface_data *ifd = NULL;
    309 	int aflag;
    310 	enum event ev;
    311 
    312 	if (ifam->ifam_addrs == 0)
    313 		return;
    314 	for (i = 1; i; i <<= 1) {
    315 		if ((i & ifam->ifam_addrs) == 0)
    316 			continue;
    317 		sa = (const struct sockaddr *)cp;
    318 		if (i == RTA_IFP) {
    319 			const struct sockaddr_dl *li;
    320 
    321 			li = (const struct sockaddr_dl *)sa;
    322 			if ((ifd = find_interface(li->sdl_index)) == NULL) {
    323 				if (verbose)
    324 					printf("ignoring change"
    325 					    " on interface #%d\n",
    326 					    li->sdl_index);
    327 				return;
    328 			}
    329 		} else if (i == RTA_IFA)
    330 			ifa = sa;
    331 		else if (i == RTA_BRD)
    332 			brd = sa;
    333 		RT_ADVANCE(cp, sa);
    334 	}
    335 	if (ifa != NULL && ifd != NULL) {
    336 		ev = ifam->ifam_type == RTM_DELADDR ? DOWN : UP;
    337 		aflag = check_addrflags(ifa->sa_family, ifam->ifam_addrflags);
    338 		if ((ev == UP && aflag == READY) || ev == DOWN)
    339 			invoke_script(ifd->ifname, ev, ifa, brd);
    340 	}
    341 }
    342 
    343 static void
    344 invoke_script(const char *ifname, enum event ev,
    345     const struct sockaddr *sa, const struct sockaddr *dest)
    346 {
    347 	char addr[NI_MAXHOST], daddr[NI_MAXHOST];
    348 	const char *script;
    349 	int status;
    350 
    351 	if (ifname == NULL)
    352 		return;
    353 
    354 	script = *scripts[ev];
    355 	if (script == NULL)
    356 		return;
    357 
    358 	addr[0] = daddr[0] = 0;
    359 	if (sa != NULL) {
    360 		const struct sockaddr_in *sin;
    361 		const struct sockaddr_in6 *sin6;
    362 
    363 		if (sa->sa_len == 0) {
    364 			syslog(LOG_ERR,
    365 			    "illegal socket address (sa_len == 0)");
    366 			return;
    367 		}
    368 		switch (sa->sa_family) {
    369 		case AF_INET:
    370 			sin = (const struct sockaddr_in *)sa;
    371 			if (sin->sin_addr.s_addr == INADDR_ANY ||
    372 			    sin->sin_addr.s_addr == INADDR_BROADCAST)
    373 				return;
    374 			break;
    375 		case AF_INET6:
    376 			sin6 = (const struct sockaddr_in6 *)sa;
    377 			if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))
    378 				return;
    379 			break;
    380 		default:
    381 			break;
    382 		}
    383 
    384 		if (getnameinfo(sa, sa->sa_len, addr, sizeof addr, NULL, 0,
    385 		    NI_NUMERICHOST)) {
    386 			if (verbose)
    387 				printf("getnameinfo failed\n");
    388 			return;	/* this address can not be handled */
    389 		}
    390 	}
    391 
    392 	if (dest != NULL) {
    393 		if (getnameinfo(dest, dest->sa_len, daddr, sizeof daddr,
    394 		    NULL, 0, NI_NUMERICHOST)) {
    395 			if (verbose)
    396 				printf("getnameinfo failed\n");
    397 			return;	/* this address can not be handled */
    398 		}
    399 	}
    400 
    401 	if (verbose)
    402 		(void) printf("calling: %s %s %s %s %s %s\n",
    403 		    script, ifname, DummyTTY, DummySpeed, addr, daddr);
    404 	if (!quiet)
    405 		syslog(LOG_INFO, "calling: %s %s %s %s %s %s\n",
    406 		    script, ifname, DummyTTY, DummySpeed, addr, daddr);
    407 
    408 	switch (vfork()) {
    409 	case -1:
    410 		syslog(LOG_ERR, "cannot fork: %m");
    411 		break;
    412 	case 0:
    413 		if (execl(script, script, ifname, DummyTTY, DummySpeed,
    414 		    addr, daddr, NULL) == -1) {
    415 			syslog(LOG_ERR, "could not execute \"%s\": %m",
    416 			    script);
    417 		}
    418 		_exit(EXIT_FAILURE);
    419 	default:
    420 		(void) wait(&status);
    421 	}
    422 }
    423 
    424 static void
    425 list_interfaces(const char *ifnames)
    426 {
    427 	char * names = strdup(ifnames);
    428 	char * name, *lasts;
    429 	static const char sep[] = " \t";
    430 	struct interface_data * p;
    431 
    432 	for (name = strtok_r(names, sep, &lasts);
    433 	    name != NULL;
    434 	    name = strtok_r(NULL, sep, &lasts)) {
    435 		p = malloc(sizeof(*p));
    436 		SLIST_INSERT_HEAD(&ifs, p, next);
    437 		p->last_carrier_status = -1;
    438 		p->ifname = strdup(name);
    439 		p->index = if_nametoindex(p->ifname);
    440 		if (!quiet)
    441 			syslog(LOG_INFO, "watching interface %s", p->ifname);
    442 		if (verbose)
    443 			printf("interface \"%s\" has index %d\n",
    444 			    p->ifname, p->index);
    445 	}
    446 	free(names);
    447 }
    448 
    449 static void
    450 check_carrier(const struct if_msghdr *ifm)
    451 {
    452 	struct interface_data * p;
    453 	int carrier_status;
    454 	enum event ev;
    455 
    456 	SLIST_FOREACH(p, &ifs, next)
    457 		if (p->index == ifm->ifm_index)
    458 			break;
    459 
    460 	if (p == NULL)
    461 		return;
    462 
    463 	/*
    464 	 * Treat it as an event worth handling if:
    465 	 * - the carrier status changed, or
    466 	 * - this is the first time we've been called, and
    467 	 * inhibit_initial is not set
    468 	 */
    469 	carrier_status = ifm->ifm_data.ifi_link_state;
    470 	if (carrier_status != p->last_carrier_status) {
    471 		switch (carrier_status) {
    472 		case LINK_STATE_UP:
    473 			ev = CARRIER;
    474 			break;
    475 		case LINK_STATE_DOWN:
    476 			ev = NO_CARRIER;
    477 			break;
    478 		default:
    479 			if (verbose)
    480 				printf("unknown link status ignored\n");
    481 			return;
    482 		}
    483 		invoke_script(p->ifname, ev, NULL, NULL);
    484 		p->last_carrier_status = carrier_status;
    485 	}
    486 }
    487 
    488 static void
    489 check_announce(const struct if_announcemsghdr *ifan)
    490 {
    491 	struct interface_data * p;
    492 	const char *ifname = ifan->ifan_name;
    493 
    494 	SLIST_FOREACH(p, &ifs, next) {
    495 		if (strcmp(p->ifname, ifname) != 0)
    496 			continue;
    497 
    498 		switch (ifan->ifan_what) {
    499 		case IFAN_ARRIVAL:
    500 			p->index = ifan->ifan_index;
    501 			invoke_script(p->ifname, ARRIVAL, NULL, NULL);
    502 			break;
    503 		case IFAN_DEPARTURE:
    504 			p->index = -1;
    505 			p->last_carrier_status = -1;
    506 			invoke_script(p->ifname, DEPARTURE, NULL, NULL);
    507 			break;
    508 		default:
    509 			if (verbose)
    510 				(void) printf("unknown announce: "
    511 				    "what=%d\n", ifan->ifan_what);
    512 			break;
    513 		}
    514 		return;
    515 	}
    516 }
    517 
    518 static void
    519 free_interfaces(void)
    520 {
    521 	struct interface_data * p;
    522 
    523 	while (!SLIST_EMPTY(&ifs)) {
    524 		p = SLIST_FIRST(&ifs);
    525 		SLIST_REMOVE_HEAD(&ifs, next);
    526 		free(p->ifname);
    527 		free(p);
    528 	}
    529 }
    530 
    531 static struct interface_data *
    532 find_interface(int idx)
    533 {
    534 	struct interface_data * p;
    535 
    536 	SLIST_FOREACH(p, &ifs, next)
    537 		if (p->index == idx)
    538 			return p;
    539 	return NULL;
    540 }
    541 
    542 static void
    543 run_initial_ups(void)
    544 {
    545 	struct interface_data * ifd;
    546 	struct ifaddrs *res = NULL, *p;
    547 	struct sockaddr *ifa;
    548 	int s, aflag;
    549 
    550 	s = socket(AF_INET, SOCK_DGRAM, 0);
    551 	if (s < 0)
    552 		return;
    553 
    554 	if (getifaddrs(&res) != 0)
    555 		goto out;
    556 
    557 	for (p = res; p; p = p->ifa_next) {
    558 		SLIST_FOREACH(ifd, &ifs, next) {
    559 			if (strcmp(ifd->ifname, p->ifa_name) == 0)
    560 				break;
    561 		}
    562 		if (ifd == NULL)
    563 			continue;
    564 
    565 		ifa = p->ifa_addr;
    566 		if (ifa != NULL && ifa->sa_family == AF_LINK)
    567 			invoke_script(ifd->ifname, ARRIVAL, NULL, NULL);
    568 
    569 		if ((p->ifa_flags & IFF_UP) == 0)
    570 			continue;
    571 		if (ifa == NULL)
    572 			continue;
    573 		if (ifa->sa_family == AF_LINK) {
    574 			struct ifmediareq ifmr;
    575 
    576 			memset(&ifmr, 0, sizeof(ifmr));
    577 			strncpy(ifmr.ifm_name, ifd->ifname,
    578 			    sizeof(ifmr.ifm_name));
    579 			if (ioctl(s, SIOCGIFMEDIA, &ifmr) != -1
    580 			    && (ifmr.ifm_status & IFM_AVALID)
    581 			    && (ifmr.ifm_status & IFM_ACTIVE)) {
    582 				invoke_script(ifd->ifname, CARRIER, NULL, NULL);
    583 				ifd->last_carrier_status =
    584 				    LINK_STATE_UP;
    585 			    }
    586 			continue;
    587 		}
    588 		aflag = check_addrflags(ifa->sa_family, p->ifa_addrflags);
    589 		if (aflag != READY)
    590 			continue;
    591 		invoke_script(ifd->ifname, UP, ifa, p->ifa_dstaddr);
    592 	}
    593 	freeifaddrs(res);
    594 out:
    595 	close(s);
    596 }
    597