Home | History | Annotate | Line # | Download | only in ifwatchd
ifwatchd.c revision 1.28
      1 /*	$NetBSD: ifwatchd.c,v 1.28 2016/09/21 14:46:55 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 	switch (hd->rtm_type) {
    266 	case RTM_NEWADDR:
    267 		ev = UP;
    268 		goto work;
    269 	case RTM_DELADDR:
    270 		ev = DOWN;
    271 		goto work;
    272 	case RTM_IFANNOUNCE:
    273 		rescan_interfaces();
    274 		check_announce((struct if_announcemsghdr *)msg);
    275 		return;
    276 	case RTM_IFINFO:
    277 		ifmp = (struct if_msghdr*)msg;
    278 		check_carrier(ifmp->ifm_index, ifmp->ifm_data.ifi_link_state);
    279 		return;
    280 	case RTM_ADD:
    281 	case RTM_DELETE:
    282 	case RTM_CHANGE:
    283 	case RTM_LOSING:
    284 	case RTM_REDIRECT:
    285 	case RTM_MISS:
    286 	case RTM_IEEE80211:
    287 		return;
    288 	}
    289 	if (verbose)
    290 		printf("unknown message ignored (%d)\n", hd->rtm_type);
    291 	return;
    292 
    293 work:
    294 	ifam = (struct ifa_msghdr *)msg;
    295 	check_addrs((char *)(ifam + 1), ifam->ifam_addrs, ev);
    296 }
    297 
    298 static void
    299 check_addrs(char *cp, int addrs, enum event ev)
    300 {
    301 	struct sockaddr *sa, *ifa = NULL, *brd = NULL;
    302 	char ifname_buf[IFNAMSIZ];
    303 	const char *ifname;
    304 	int ifndx = 0;
    305 	unsigned i;
    306 
    307 	if (addrs == 0)
    308 		return;
    309 	for (i = 1; i; i <<= 1) {
    310 		if ((i & addrs) == 0)
    311 			continue;
    312 		sa = (struct sockaddr *)cp;
    313 		if (i == RTA_IFP) {
    314 			struct sockaddr_dl * li = (struct sockaddr_dl*)sa;
    315 			ifndx = li->sdl_index;
    316 			if (!find_interface(ifndx)) {
    317 				if (verbose)
    318 					printf("ignoring change on interface #%d\n", ifndx);
    319 				return;
    320 			}
    321 		} else if (i == RTA_IFA)
    322 			ifa = sa;
    323 		else if (i == RTA_BRD)
    324 			brd = sa;
    325 		RT_ADVANCE(cp, sa);
    326 	}
    327 	if (ifa != NULL) {
    328 		ifname = if_indextoname(ifndx, ifname_buf);
    329 		if (ifname == NULL || ev < UP)
    330 			invoke_script(ifa, brd, ev, ifndx, ifname);
    331 		else if (ev == UP) {
    332 			if (if_is_connected(ifname))
    333 				invoke_script(ifa, brd, ev, ifndx, ifname);
    334 		} else if (ev == DOWN) {
    335 			if (if_is_not_connected(ifname))
    336 				invoke_script(ifa, brd, ev, ifndx, ifname);
    337 		}
    338 	}
    339 }
    340 
    341 static void
    342 invoke_script(struct sockaddr *sa, struct sockaddr *dest, enum event ev,
    343     int ifindex, const char *ifname_hint)
    344 {
    345 	char addr[NI_MAXHOST], daddr[NI_MAXHOST], ifname_buf[IFNAMSIZ];
    346 	const char * volatile ifname;
    347 	const char *script;
    348 	int status;
    349 
    350 	if (sa != NULL && sa->sa_len == 0) {
    351 		fprintf(stderr, "illegal socket address (sa_len == 0)\n");
    352 		return;
    353 	}
    354 	if (sa != NULL && sa->sa_family == AF_INET6) {
    355 		struct sockaddr_in6 sin6;
    356 
    357 		(void) memcpy(&sin6, (struct sockaddr_in6 *)sa, sizeof (sin6));
    358 		if (IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr))
    359 			return;
    360 	}
    361 
    362 	addr[0] = daddr[0] = 0;
    363 	ifname = if_indextoname(ifindex, ifname_buf);
    364 	ifname = ifname ? ifname : ifname_hint;
    365 	if (ifname == NULL)
    366 		return;
    367 
    368 	if (sa != NULL) {
    369 		if (getnameinfo(sa, sa->sa_len, addr, sizeof addr, NULL, 0,
    370 		    NI_NUMERICHOST)) {
    371 			if (verbose)
    372 				printf("getnameinfo failed\n");
    373 			return;	/* this address can not be handled */
    374 		}
    375 	}
    376 	if (dest != NULL) {
    377 		if (getnameinfo(dest, dest->sa_len, daddr, sizeof daddr,
    378 		    NULL, 0, NI_NUMERICHOST)) {
    379 			if (verbose)
    380 				printf("getnameinfo failed\n");
    381 			return;	/* this address can not be handled */
    382 		}
    383 	}
    384 
    385 	script = *scripts[ev];
    386 	if (script == NULL) return;
    387 
    388 	if (verbose)
    389 		(void) printf("calling: %s %s %s %s %s %s\n",
    390 		    script, ifname, DummyTTY, DummySpeed, addr, daddr);
    391 	if (!quiet)
    392 		syslog(LOG_INFO, "calling: %s %s %s %s %s %s\n",
    393 		    script, ifname, DummyTTY, DummySpeed, addr, daddr);
    394 
    395 	switch (vfork()) {
    396 	case -1:
    397 		fprintf(stderr, "cannot fork\n");
    398 		break;
    399 	case 0:
    400 		if (execl(script, script, ifname, DummyTTY, DummySpeed,
    401 		    addr, daddr, NULL) == -1) {
    402 			syslog(LOG_ERR, "could not execute \"%s\": %m",
    403 			    script);
    404 			perror(script);
    405 		}
    406 		_exit(EXIT_FAILURE);
    407 	default:
    408 		(void) wait(&status);
    409 	}
    410 }
    411 
    412 static void
    413 list_interfaces(const char *ifnames)
    414 {
    415 	char * names = strdup(ifnames);
    416 	char * name, *lasts;
    417 	static const char sep[] = " \t";
    418 	struct interface_data * p;
    419 
    420 	for (name = strtok_r(names, sep, &lasts);
    421 	    name != NULL;
    422 	    name = strtok_r(NULL, sep, &lasts)) {
    423 		p = malloc(sizeof(*p));
    424 		SLIST_INSERT_HEAD(&ifs, p, next);
    425 		p->last_carrier_status = -1;
    426 		p->ifname = strdup(name);
    427 		p->index = if_nametoindex(p->ifname);
    428 		if (!quiet)
    429 			syslog(LOG_INFO, "watching interface %s", p->ifname);
    430 		if (verbose)
    431 			printf("interface \"%s\" has index %d\n",
    432 			    p->ifname, p->index);
    433 	}
    434 	free(names);
    435 }
    436 
    437 static void
    438 check_carrier(int if_index, int carrier_status)
    439 {
    440 	struct interface_data * p;
    441 	enum event ev;
    442 
    443 	SLIST_FOREACH(p, &ifs, next)
    444 		if (p->index == if_index)
    445 			break;
    446 
    447 	if (p == NULL)
    448 		return;
    449 
    450 	/*
    451 	 * Treat it as an event worth handling if:
    452 	 * - the carrier status changed, or
    453 	 * - this is the first time we've been called, and
    454 	 * inhibit_initial is not set
    455 	 */
    456 
    457 	if ((carrier_status != p->last_carrier_status) ||
    458 	    ((p->last_carrier_status == -1) && !inhibit_initial)) {
    459 		switch (carrier_status) {
    460 		case LINK_STATE_UP:
    461 			ev = CARRIER;
    462 			break;
    463 		case LINK_STATE_DOWN:
    464 			ev = NO_CARRIER;
    465 			break;
    466 		default:
    467 			if (verbose)
    468 				printf("unknown link status ignored\n");
    469 			return;
    470 		}
    471 		invoke_script(NULL, NULL, ev, if_index, p->ifname);
    472 		p->last_carrier_status = carrier_status;
    473 	}
    474 }
    475 
    476 static void
    477 check_announce(struct if_announcemsghdr *ifan)
    478 {
    479 	struct interface_data * p;
    480 	const char *ifname = ifan->ifan_name;
    481 
    482 	SLIST_FOREACH(p, &ifs, next) {
    483 		if (strcmp(p->ifname, ifname) != 0)
    484 			continue;
    485 
    486 		switch (ifan->ifan_what) {
    487 		case IFAN_ARRIVAL:
    488 			invoke_script(NULL, NULL, ARRIVAL, p->index,
    489 			    NULL);
    490 			break;
    491 		case IFAN_DEPARTURE:
    492 			invoke_script(NULL, NULL, DEPARTURE, p->index,
    493 			    p->ifname);
    494 			break;
    495 		default:
    496 			if (verbose)
    497 				(void) printf("unknown announce: "
    498 				    "what=%d\n", ifan->ifan_what);
    499 			break;
    500 		}
    501 		return;
    502 	}
    503 }
    504 
    505 static void
    506 rescan_interfaces(void)
    507 {
    508 	struct interface_data * p;
    509 
    510 	SLIST_FOREACH(p, &ifs, next) {
    511 		p->index = if_nametoindex(p->ifname);
    512 		if (verbose)
    513 			printf("interface \"%s\" has index %d\n", p->ifname,
    514 			    p->index);
    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 int
    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 1;
    539 	return 0;
    540 }
    541 
    542 static void
    543 run_initial_ups(void)
    544 {
    545 	struct interface_data * ifd;
    546 	struct ifaddrs *res = NULL, *p;
    547 	int s;
    548 
    549 	s = socket(AF_INET, SOCK_DGRAM, 0);
    550 	if (s < 0)
    551 		return;
    552 
    553 	if (getifaddrs(&res) != 0)
    554 		goto out;
    555 
    556 	for (p = res; p; p = p->ifa_next) {
    557 		SLIST_FOREACH(ifd, &ifs, next) {
    558 			if (strcmp(ifd->ifname, p->ifa_name) == 0)
    559 				break;
    560 		}
    561 		if (ifd == NULL)
    562 			continue;
    563 
    564 		if (p->ifa_addr && p->ifa_addr->sa_family == AF_LINK)
    565 			invoke_script(NULL, NULL, ARRIVAL, ifd->index,
    566 			    NULL);
    567 
    568 		if ((p->ifa_flags & IFF_UP) == 0)
    569 			continue;
    570 		if (p->ifa_addr == NULL)
    571 			continue;
    572 		if (p->ifa_addr->sa_family == AF_LINK) {
    573 			struct ifmediareq ifmr;
    574 
    575 			memset(&ifmr, 0, sizeof(ifmr));
    576 			strncpy(ifmr.ifm_name, ifd->ifname,
    577 			    sizeof(ifmr.ifm_name));
    578 			if (ioctl(s, SIOCGIFMEDIA, &ifmr) != -1
    579 			    && (ifmr.ifm_status & IFM_AVALID)
    580 			    && (ifmr.ifm_status & IFM_ACTIVE)) {
    581 				invoke_script(NULL, NULL, CARRIER,
    582 				    ifd->index, ifd->ifname);
    583 				ifd->last_carrier_status =
    584 				    LINK_STATE_UP;
    585 			    }
    586 			continue;
    587 		}
    588 		if (if_is_connected(ifd->ifname))
    589 			invoke_script(p->ifa_addr, p->ifa_dstaddr, UP,
    590 			    ifd->index, ifd->ifname);
    591 	}
    592 	freeifaddrs(res);
    593 out:
    594 	close(s);
    595 }
    596 
    597 #ifdef SPPP_IF_SUPPORT
    598 /*
    599  * Special case support for in-kernel PPP interfaces.
    600  * If these are IFF_UP, but have not yet connected or completed authentication
    601  * we don't want to call the up script in the initial interface scan (there
    602  * will be an UP event generated later, when IPCP completes, anyway).
    603  *
    604  * If this is no if_spppsubr.c based interface, this ioctl just fails and we
    605  * treat is as connected.
    606  */
    607 static int
    608 check_is_connected(const char *ifname, int def_retval)
    609 {
    610 	int s, error;
    611 	struct spppstatus oldstatus;
    612 	struct spppstatusncp status;
    613 
    614 	memset(&status, 0, sizeof status);
    615 	strncpy(status.ifname, ifname, sizeof status.ifname);
    616 	memset(&oldstatus, 0, sizeof oldstatus);
    617 	strncpy(oldstatus.ifname, ifname, sizeof oldstatus.ifname);
    618 
    619 	s = socket(AF_INET, SOCK_DGRAM, 0);
    620 	if (s < 0)
    621 		return 1;	/* no idea how to handle this... */
    622 	error = ioctl(s, SPPPGETSTATUSNCP, &status);
    623 	if (error != 0) {
    624 		error = ioctl(s, SPPPGETSTATUS, &oldstatus);
    625 		if (error != 0) {
    626 			/* not if_spppsubr.c based - return default */
    627 			close(s);
    628 			return def_retval;
    629 		} else {
    630 			/* can't query NCPs, so use default */
    631 			status.phase = oldstatus.phase;
    632 			status.ncpup = def_retval;
    633 		}
    634 	}
    635 	close(s);
    636 
    637 	return status.phase == SPPP_PHASE_NETWORK && status.ncpup > 0;
    638 }
    639 #endif
    640