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