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