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