Home | History | Annotate | Line # | Download | only in ifwatchd
ifwatchd.c revision 1.32
      1 /*	$NetBSD: ifwatchd.c,v 1.32 2016/09/21 20:31:31 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 <arpa/inet.h>
     52 
     53 #include <paths.h>
     54 #include <stdio.h>
     55 #include <stdlib.h>
     56 #include <string.h>
     57 #include <unistd.h>
     58 #include <netdb.h>
     59 #include <err.h>
     60 #include <ifaddrs.h>
     61 #include <syslog.h>
     62 
     63 enum event { ARRIVAL, DEPARTURE, UP, DOWN, CARRIER, NO_CARRIER };
     64 
     65 /* local functions */
     66 __dead static void usage(void);
     67 static void dispatch(const void *, size_t);
     68 static void check_addrs(const struct ifa_msghdr *ifam);
     69 static void invoke_script(const struct sockaddr *sa, const struct sockaddr *dst,
     70     enum event ev, int ifindex, const char *ifname_hint);
     71 static void list_interfaces(const char *ifnames);
     72 static void check_announce(const struct if_announcemsghdr *ifan);
     73 static void check_carrier(const struct if_msghdr *ifm);
     74 static void rescan_interfaces(void);
     75 static void free_interfaces(void);
     76 static struct interface_data * find_interface(int index);
     77 static void run_initial_ups(void);
     78 
     79 #ifdef SPPP_IF_SUPPORT
     80 static int check_is_connected(const char * ifname, int def_retvalue);
     81 #define if_is_connected(X)	(check_is_connected((X), 1))
     82 #define if_is_not_connected(X)	(!check_is_connected((X), 0))
     83 #else
     84 #define	if_is_connected(X)	1
     85 #define	if_is_not_connected(X)	1
     86 #endif
     87 
     88 /* global variables */
     89 static int verbose = 0, quiet = 0;
     90 static int inhibit_initial = 0;
     91 static const char *arrival_script = NULL;
     92 static const char *departure_script = NULL;
     93 static const char *up_script = NULL;
     94 static const char *down_script = NULL;
     95 static const char *carrier_script = NULL;
     96 static const char *no_carrier_script = NULL;
     97 static const char DummyTTY[] = _PATH_DEVNULL;
     98 static const char DummySpeed[] = "9600";
     99 static const char **scripts[] = {
    100 	&arrival_script,
    101 	&departure_script,
    102 	&up_script,
    103 	&down_script,
    104 	&carrier_script,
    105 	&no_carrier_script
    106 };
    107 
    108 struct interface_data {
    109 	SLIST_ENTRY(interface_data) next;
    110 	int index;
    111 	int last_carrier_status;
    112 	char * ifname;
    113 };
    114 static SLIST_HEAD(,interface_data) ifs = SLIST_HEAD_INITIALIZER(ifs);
    115 
    116 int
    117 main(int argc, char **argv)
    118 {
    119 	int c, s, n;
    120 	int errs = 0;
    121 	struct msghdr msg;
    122 	struct iovec iov[1];
    123 	char buf[2048];
    124 
    125 	openlog(argv[0], LOG_PID|LOG_CONS, LOG_DAEMON);
    126 	while ((c = getopt(argc, argv, "qvhic:n:u:d:A:D:")) != -1) {
    127 		switch (c) {
    128 		case 'h':
    129 			usage();
    130 			return 0;
    131 
    132 		case 'i':
    133 			inhibit_initial = 1;
    134 			break;
    135 
    136 		case 'v':
    137 			verbose++;
    138 			break;
    139 
    140 		case 'q':
    141 			quiet = 1;
    142 			break;
    143 
    144 		case 'c':
    145 			carrier_script = optarg;
    146 			break;
    147 
    148 		case 'n':
    149 			no_carrier_script = optarg;
    150 			break;
    151 
    152 		case 'u':
    153 			up_script = optarg;
    154 			break;
    155 
    156 		case 'd':
    157 			down_script = optarg;
    158 			break;
    159 
    160 		case 'A':
    161 			arrival_script = optarg;
    162 			break;
    163 
    164 		case 'D':
    165 			departure_script = optarg;
    166 			break;
    167 
    168 		default:
    169 			errs++;
    170 			break;
    171 		}
    172 	}
    173 
    174 	if (errs)
    175 		usage();
    176 
    177 	argv += optind;
    178 	argc -= optind;
    179 
    180 	if (argc <= 0)
    181 		usage();
    182 
    183 	if (verbose) {
    184 		printf("up_script: %s\ndown_script: %s\n",
    185 			up_script, down_script);
    186 		printf("arrival_script: %s\ndeparture_script: %s\n",
    187 			arrival_script, departure_script);
    188 		printf("carrier_script: %s\nno_carrier_script: %s\n",
    189 			carrier_script, no_carrier_script);
    190 		printf("verbosity = %d\n", verbose);
    191 	}
    192 
    193 	while (argc > 0) {
    194 		list_interfaces(argv[0]);
    195 		argv++;
    196 		argc--;
    197 	}
    198 
    199 	if (!verbose)
    200 		daemon(0, 0);
    201 
    202 	s = socket(PF_ROUTE, SOCK_RAW, 0);
    203 	if (s < 0) {
    204 		syslog(LOG_ERR, "error opening routing socket: %m");
    205 		perror("open routing socket");
    206 		exit(EXIT_FAILURE);
    207 	}
    208 
    209 	if (!inhibit_initial)
    210 		run_initial_ups();
    211 
    212 	iov[0].iov_base = buf;
    213 	iov[0].iov_len = sizeof(buf);
    214 	memset(&msg, 0, sizeof(msg));
    215 	msg.msg_iov = iov;
    216 	msg.msg_iovlen = 1;
    217 
    218 	for (;;) {
    219 		n = recvmsg(s, &msg, 0);
    220 		if (n == -1) {
    221 			syslog(LOG_ERR, "recvmsg: %m");
    222 			exit(EXIT_FAILURE);
    223 		}
    224 		if (n != 0)
    225 			dispatch(iov[0].iov_base, n);
    226 	}
    227 
    228 	close(s);
    229 	free_interfaces();
    230 	closelog();
    231 
    232 	return EXIT_SUCCESS;
    233 }
    234 
    235 static void
    236 usage(void)
    237 {
    238 	fprintf(stderr,
    239 	    "usage:\n"
    240 	    "\tifwatchd [-hiqv] [-A arrival-script] [-D departure-script]\n"
    241 	    "\t\t  [-d down-script] [-u up-script]\n"
    242 	    "\t\t  [-c carrier-script] [-n no-carrier-script] ifname(s)\n"
    243 	    "\twhere:\n"
    244 	    "\t -A <cmd> specify command to run on interface arrival event\n"
    245 	    "\t -c <cmd> specify command to run on interface carrier-detect event\n"
    246 	    "\t -D <cmd> specify command to run on interface departure event\n"
    247 	    "\t -d <cmd> specify command to run on interface down event\n"
    248 	    "\t -n <cmd> specify command to run on interface no-carrier-detect event\n"
    249 	    "\t -h       show this help message\n"
    250 	    "\t -i       no (!) initial run of the up script if the interface\n"
    251 	    "\t          is already up on ifwatchd startup\n"
    252 	    "\t -q       quiet mode, don't syslog informational messages\n"
    253 	    "\t -u <cmd> specify command to run on interface up event\n"
    254 	    "\t -v       verbose/debug output, don't run in background\n");
    255 	exit(EXIT_FAILURE);
    256 }
    257 
    258 static void
    259 dispatch(const void *msg, size_t len)
    260 {
    261 	const struct rt_msghdr *hd = msg;
    262 
    263 	if (hd->rtm_version != RTM_VERSION)
    264 		return;
    265 
    266 	switch (hd->rtm_type) {
    267 	case RTM_NEWADDR:
    268 	case RTM_DELADDR:
    269 		check_addrs(msg);
    270 		break;
    271 	case RTM_IFANNOUNCE:
    272 		rescan_interfaces();
    273 		check_announce(msg);
    274 		break;
    275 	case RTM_IFINFO:
    276 		check_carrier(msg);
    277 		break;
    278 	case RTM_ADD:
    279 	case RTM_DELETE:
    280 	case RTM_CHANGE:
    281 	case RTM_LOSING:
    282 	case RTM_REDIRECT:
    283 	case RTM_MISS:
    284 	case RTM_IEEE80211:
    285 	case RTM_ONEWADDR:
    286 	case RTM_ODELADDR:
    287 	case RTM_OCHGADDR:
    288 		break;
    289 	default:
    290 		if (verbose)
    291 			printf("unknown message ignored (%d)\n", hd->rtm_type);
    292 		break;
    293 	}
    294 }
    295 
    296 static void
    297 check_addrs(const struct ifa_msghdr *ifam)
    298 {
    299 	const char *cp = (const char *)(ifam + 1);
    300 	const struct sockaddr *sa, *ifa = NULL, *brd = NULL;
    301 	unsigned i;
    302 	struct interface_data *ifd = NULL;
    303 	enum event ev;
    304 
    305 	if (ifam->ifam_addrs == 0)
    306 		return;
    307 	for (i = 1; i; i <<= 1) {
    308 		if ((i & ifam->ifam_addrs) == 0)
    309 			continue;
    310 		sa = (const struct sockaddr *)cp;
    311 		if (i == RTA_IFP) {
    312 			const struct sockaddr_dl *li;
    313 
    314 			li = (const struct sockaddr_dl *)sa;
    315 			if ((ifd = find_interface(li->sdl_index)) == NULL) {
    316 				if (verbose)
    317 					printf("ignoring change"
    318 					    " on interface #%d\n",
    319 					    li->sdl_index);
    320 				return;
    321 			}
    322 		} else if (i == RTA_IFA)
    323 			ifa = sa;
    324 		else if (i == RTA_BRD)
    325 			brd = sa;
    326 		RT_ADVANCE(cp, sa);
    327 	}
    328 	if (ifa != NULL && ifd != NULL) {
    329 		ev = ifam->ifam_type == RTM_DELADDR ? DOWN : UP;
    330 		if ((ev == UP && if_is_connected(ifd->ifname)) ||
    331 		    (ev == DOWN && if_is_not_connected(ifd->ifname)))
    332 			invoke_script(ifa, brd, ev, ifd->index, ifd->ifname);
    333 	}
    334 }
    335 
    336 static void
    337 invoke_script(const struct sockaddr *sa, const struct sockaddr *dest,
    338     enum event ev, int ifindex, const char *ifname_hint)
    339 {
    340 	char addr[NI_MAXHOST], daddr[NI_MAXHOST], ifname_buf[IFNAMSIZ];
    341 	const char * volatile ifname;
    342 	const char *script;
    343 	int status;
    344 
    345 	if (sa != NULL && sa->sa_len == 0) {
    346 		fprintf(stderr, "illegal socket address (sa_len == 0)\n");
    347 		return;
    348 	}
    349 	if (sa != NULL && sa->sa_family == AF_INET6) {
    350 		struct sockaddr_in6 sin6;
    351 
    352 		memcpy(&sin6, (const struct sockaddr_in6 *)sa, sizeof (sin6));
    353 		if (IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr))
    354 			return;
    355 	}
    356 
    357 	addr[0] = daddr[0] = 0;
    358 	ifname = if_indextoname(ifindex, ifname_buf);
    359 	ifname = ifname ? ifname : ifname_hint;
    360 	if (ifname == NULL)
    361 		return;
    362 
    363 	if (sa != NULL) {
    364 		if (getnameinfo(sa, sa->sa_len, addr, sizeof addr, NULL, 0,
    365 		    NI_NUMERICHOST)) {
    366 			if (verbose)
    367 				printf("getnameinfo failed\n");
    368 			return;	/* this address can not be handled */
    369 		}
    370 	}
    371 	if (dest != NULL) {
    372 		if (getnameinfo(dest, dest->sa_len, daddr, sizeof daddr,
    373 		    NULL, 0, NI_NUMERICHOST)) {
    374 			if (verbose)
    375 				printf("getnameinfo failed\n");
    376 			return;	/* this address can not be handled */
    377 		}
    378 	}
    379 
    380 	script = *scripts[ev];
    381 	if (script == NULL) return;
    382 
    383 	if (verbose)
    384 		(void) printf("calling: %s %s %s %s %s %s\n",
    385 		    script, ifname, DummyTTY, DummySpeed, addr, daddr);
    386 	if (!quiet)
    387 		syslog(LOG_INFO, "calling: %s %s %s %s %s %s\n",
    388 		    script, ifname, DummyTTY, DummySpeed, addr, daddr);
    389 
    390 	switch (vfork()) {
    391 	case -1:
    392 		fprintf(stderr, "cannot fork\n");
    393 		break;
    394 	case 0:
    395 		if (execl(script, script, ifname, DummyTTY, DummySpeed,
    396 		    addr, daddr, NULL) == -1) {
    397 			syslog(LOG_ERR, "could not execute \"%s\": %m",
    398 			    script);
    399 			perror(script);
    400 		}
    401 		_exit(EXIT_FAILURE);
    402 	default:
    403 		(void) wait(&status);
    404 	}
    405 }
    406 
    407 static void
    408 list_interfaces(const char *ifnames)
    409 {
    410 	char * names = strdup(ifnames);
    411 	char * name, *lasts;
    412 	static const char sep[] = " \t";
    413 	struct interface_data * p;
    414 
    415 	for (name = strtok_r(names, sep, &lasts);
    416 	    name != NULL;
    417 	    name = strtok_r(NULL, sep, &lasts)) {
    418 		p = malloc(sizeof(*p));
    419 		SLIST_INSERT_HEAD(&ifs, p, next);
    420 		p->last_carrier_status = -1;
    421 		p->ifname = strdup(name);
    422 		p->index = if_nametoindex(p->ifname);
    423 		if (!quiet)
    424 			syslog(LOG_INFO, "watching interface %s", p->ifname);
    425 		if (verbose)
    426 			printf("interface \"%s\" has index %d\n",
    427 			    p->ifname, p->index);
    428 	}
    429 	free(names);
    430 }
    431 
    432 static void
    433 check_carrier(const struct if_msghdr *ifm)
    434 {
    435 	struct interface_data * p;
    436 	int carrier_status;
    437 	enum event ev;
    438 
    439 	SLIST_FOREACH(p, &ifs, next)
    440 		if (p->index == ifm->ifm_index)
    441 			break;
    442 
    443 	if (p == NULL)
    444 		return;
    445 
    446 	/*
    447 	 * Treat it as an event worth handling if:
    448 	 * - the carrier status changed, or
    449 	 * - this is the first time we've been called, and
    450 	 * inhibit_initial is not set
    451 	 */
    452 	carrier_status = ifm->ifm_data.ifi_link_state;
    453 	if ((carrier_status != p->last_carrier_status) ||
    454 	    ((p->last_carrier_status == -1) && !inhibit_initial)) {
    455 		switch (carrier_status) {
    456 		case LINK_STATE_UP:
    457 			ev = CARRIER;
    458 			break;
    459 		case LINK_STATE_DOWN:
    460 			ev = NO_CARRIER;
    461 			break;
    462 		default:
    463 			if (verbose)
    464 				printf("unknown link status ignored\n");
    465 			return;
    466 		}
    467 		invoke_script(NULL, NULL, ev, ifm->ifm_index, p->ifname);
    468 		p->last_carrier_status = carrier_status;
    469 	}
    470 }
    471 
    472 static void
    473 check_announce(const struct if_announcemsghdr *ifan)
    474 {
    475 	struct interface_data * p;
    476 	const char *ifname = ifan->ifan_name;
    477 
    478 	SLIST_FOREACH(p, &ifs, next) {
    479 		if (strcmp(p->ifname, ifname) != 0)
    480 			continue;
    481 
    482 		switch (ifan->ifan_what) {
    483 		case IFAN_ARRIVAL:
    484 			invoke_script(NULL, NULL, ARRIVAL, p->index,
    485 			    NULL);
    486 			break;
    487 		case IFAN_DEPARTURE:
    488 			invoke_script(NULL, NULL, DEPARTURE, p->index,
    489 			    p->ifname);
    490 			break;
    491 		default:
    492 			if (verbose)
    493 				(void) printf("unknown announce: "
    494 				    "what=%d\n", ifan->ifan_what);
    495 			break;
    496 		}
    497 		return;
    498 	}
    499 }
    500 
    501 static void
    502 rescan_interfaces(void)
    503 {
    504 	struct interface_data * p;
    505 
    506 	SLIST_FOREACH(p, &ifs, next) {
    507 		p->index = if_nametoindex(p->ifname);
    508 		if (verbose)
    509 			printf("interface \"%s\" has index %d\n", p->ifname,
    510 			    p->index);
    511 	}
    512 }
    513 
    514 static void
    515 free_interfaces(void)
    516 {
    517 	struct interface_data * p;
    518 
    519 	while (!SLIST_EMPTY(&ifs)) {
    520 		p = SLIST_FIRST(&ifs);
    521 		SLIST_REMOVE_HEAD(&ifs, next);
    522 		free(p->ifname);
    523 		free(p);
    524 	}
    525 }
    526 
    527 static struct interface_data *
    528 find_interface(int idx)
    529 {
    530 	struct interface_data * p;
    531 
    532 	SLIST_FOREACH(p, &ifs, next)
    533 		if (p->index == idx)
    534 			return p;
    535 	return NULL;
    536 }
    537 
    538 static void
    539 run_initial_ups(void)
    540 {
    541 	struct interface_data * ifd;
    542 	struct ifaddrs *res = NULL, *p;
    543 	int s;
    544 
    545 	s = socket(AF_INET, SOCK_DGRAM, 0);
    546 	if (s < 0)
    547 		return;
    548 
    549 	if (getifaddrs(&res) != 0)
    550 		goto out;
    551 
    552 	for (p = res; p; p = p->ifa_next) {
    553 		SLIST_FOREACH(ifd, &ifs, next) {
    554 			if (strcmp(ifd->ifname, p->ifa_name) == 0)
    555 				break;
    556 		}
    557 		if (ifd == NULL)
    558 			continue;
    559 
    560 		if (p->ifa_addr && p->ifa_addr->sa_family == AF_LINK)
    561 			invoke_script(NULL, NULL, ARRIVAL, ifd->index,
    562 			    NULL);
    563 
    564 		if ((p->ifa_flags & IFF_UP) == 0)
    565 			continue;
    566 		if (p->ifa_addr == NULL)
    567 			continue;
    568 		if (p->ifa_addr->sa_family == AF_LINK) {
    569 			struct ifmediareq ifmr;
    570 
    571 			memset(&ifmr, 0, sizeof(ifmr));
    572 			strncpy(ifmr.ifm_name, ifd->ifname,
    573 			    sizeof(ifmr.ifm_name));
    574 			if (ioctl(s, SIOCGIFMEDIA, &ifmr) != -1
    575 			    && (ifmr.ifm_status & IFM_AVALID)
    576 			    && (ifmr.ifm_status & IFM_ACTIVE)) {
    577 				invoke_script(NULL, NULL, CARRIER,
    578 				    ifd->index, ifd->ifname);
    579 				ifd->last_carrier_status =
    580 				    LINK_STATE_UP;
    581 			    }
    582 			continue;
    583 		}
    584 		if (if_is_connected(ifd->ifname))
    585 			invoke_script(p->ifa_addr, p->ifa_dstaddr, UP,
    586 			    ifd->index, ifd->ifname);
    587 	}
    588 	freeifaddrs(res);
    589 out:
    590 	close(s);
    591 }
    592 
    593 #ifdef SPPP_IF_SUPPORT
    594 /*
    595  * Special case support for in-kernel PPP interfaces.
    596  * If these are IFF_UP, but have not yet connected or completed authentication
    597  * we don't want to call the up script in the initial interface scan (there
    598  * will be an UP event generated later, when IPCP completes, anyway).
    599  *
    600  * If this is no if_spppsubr.c based interface, this ioctl just fails and we
    601  * treat is as connected.
    602  */
    603 static int
    604 check_is_connected(const char *ifname, int def_retval)
    605 {
    606 	int s, error;
    607 	struct spppstatus oldstatus;
    608 	struct spppstatusncp status;
    609 
    610 	memset(&status, 0, sizeof status);
    611 	strncpy(status.ifname, ifname, sizeof status.ifname);
    612 	memset(&oldstatus, 0, sizeof oldstatus);
    613 	strncpy(oldstatus.ifname, ifname, sizeof oldstatus.ifname);
    614 
    615 	s = socket(AF_INET, SOCK_DGRAM, 0);
    616 	if (s < 0)
    617 		return 1;	/* no idea how to handle this... */
    618 	error = ioctl(s, SPPPGETSTATUSNCP, &status);
    619 	if (error != 0) {
    620 		error = ioctl(s, SPPPGETSTATUS, &oldstatus);
    621 		if (error != 0) {
    622 			/* not if_spppsubr.c based - return default */
    623 			close(s);
    624 			return def_retval;
    625 		} else {
    626 			/* can't query NCPs, so use default */
    627 			status.phase = oldstatus.phase;
    628 			status.ncpup = def_retval;
    629 		}
    630 	}
    631 	close(s);
    632 
    633 	return status.phase == SPPP_PHASE_NETWORK && status.ncpup > 0;
    634 }
    635 #endif
    636