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