summaryrefslogtreecommitdiff
path: root/usr.sbin/ifstated/ifstated.c
blob: f85ac86f2981312977d13fb2535f65de58168763 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
/*	$OpenBSD: ifstated.c,v 1.27 2006/02/01 23:23:37 mpf Exp $	*/

/*
 * Copyright (c) 2004 Marco Pfatschbacher <mpf@openbsd.org>
 * Copyright (c) 2004 Ryan McBride <mcbride@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * ifstated listens to link_state transitions on interfaces
 * and executes predefined commands.
 */

#include <sys/types.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/wait.h>

#include <net/if.h>
#include <net/route.h>
#include <netinet/in.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
#include <err.h>
#include <event.h>
#include <util.h>
#include <unistd.h>
#include <syslog.h>
#include <stdarg.h>
#include <ifaddrs.h>

#include "ifstated.h"

struct	 ifsd_config *conf = NULL, *newconf = NULL;

int	 opts = 0;
int	 opt_debug = 0;
int	 opt_inhibit = 0;
char	*configfile = "/etc/ifstated.conf";
struct event	rt_msg_ev, sighup_ev, startup_ev, sigchld_ev;

void	startup_handler(int, short, void *);
void	sighup_handler(int, short, void *);
int	load_config(void);
void	sigchld_handler(int, short, void *);
void	rt_msg_handler(int, short, void *);
void	external_handler(int, short, void *);
void	external_exec(struct ifsd_external *, int);
void	check_external_status(struct ifsd_state *);
void	external_evtimer_setup(struct ifsd_state *, int);
void	scan_ifstate(int, int, int);
int	scan_ifstate_single(int, int, struct ifsd_state *);
void	fetch_state(void);
void	usage(void);
void	adjust_expressions(struct ifsd_expression_list *, int);
void	adjust_external_expressions(struct ifsd_state *);
void	eval_state(struct ifsd_state *);
int	state_change(void);
void	do_action(struct ifsd_action *);
void	remove_action(struct ifsd_action *, struct ifsd_state *);
void	remove_expression(struct ifsd_expression *, struct ifsd_state *);
void	log_init(int);
void	logit(int, const char *, ...);

void
usage(void)
{
	extern char *__progname;

	fprintf(stderr, "usage: %s [-dhinv] [-D macro=value] [-f file]\n",
	    __progname);
	exit(1);
}

int
main(int argc, char *argv[])
{
	struct timeval tv;
	int ch;

	while ((ch = getopt(argc, argv, "dD:f:hniv")) != -1) {
		switch (ch) {
		case 'd':
			opt_debug = 1;
			break;
		case 'D':
			if (cmdline_symset(optarg) < 0)
				errx(1, "could not parse macro definition %s",
				    optarg);
			break;
		case 'f':
			configfile = optarg;
			break;
		case 'h':
			usage();
			break;
		case 'n':
			opts |= IFSD_OPT_NOACTION;
			break;
		case 'i':
			opt_inhibit = 1;
			break;
		case 'v':
			if (opts & IFSD_OPT_VERBOSE)
				opts |= IFSD_OPT_VERBOSE2;
			opts |= IFSD_OPT_VERBOSE;
			break;
		default:
			usage();
		}
	}

	if (opts & IFSD_OPT_NOACTION) {
		if ((newconf = parse_config(configfile, opts)) == NULL)
			exit(1);
		warnx("configuration OK");
		exit(0);
	}

	if (!opt_debug) {
		daemon(0, 0);
		setproctitle(NULL);
	}

	event_init();
	log_init(opt_debug);

	signal_set(&sigchld_ev, SIGCHLD, sigchld_handler, &sigchld_ev);
	signal_add(&sigchld_ev, NULL);

	/* Loading the config needs to happen in the event loop */
	tv.tv_usec = 0;
	tv.tv_sec = 0;
	evtimer_set(&startup_ev, startup_handler, &startup_ev);
	evtimer_add(&startup_ev, &tv);

	event_loop(0);
	exit(0);
}

void
startup_handler(int fd, short event, void *arg)
{
	int rt_fd;

	if ((rt_fd = socket(PF_ROUTE, SOCK_RAW, 0)) < 0)
		err(1, "no routing socket");

	if (load_config() != 0) {
		logit(IFSD_LOG_NORMAL, "unable to load config");
		exit(1);
	}

	event_set(&rt_msg_ev, rt_fd, EV_READ|EV_PERSIST,
	    rt_msg_handler, &rt_msg_ev);
	event_add(&rt_msg_ev, NULL);

	signal_set(&sighup_ev, SIGHUP, sighup_handler, &sighup_ev);
	signal_add(&sighup_ev, NULL);

	logit(IFSD_LOG_NORMAL, "started");
}

void
sighup_handler(int fd, short event, void *arg)
{
	logit(IFSD_LOG_NORMAL, "reloading config");
	if (load_config() != 0)
		logit(IFSD_LOG_NORMAL, "unable to reload config");
}

int
load_config(void)
{
	if ((newconf = parse_config(configfile, opts)) == NULL)
		return (-1);
	if (conf != NULL)
		clear_config(conf);
	conf = newconf;
	conf->always.entered = time(NULL);
	fetch_state();
	external_evtimer_setup(&conf->always, IFSD_EVTIMER_ADD);
	adjust_external_expressions(&conf->always);
	eval_state(&conf->always);
	if (conf->curstate != NULL) {
		logit(IFSD_LOG_NORMAL,
		    "initial state: %s", conf->curstate->name);
		conf->curstate->entered = time(NULL);
		conf->nextstate = conf->curstate;
		conf->curstate = NULL;
		while (state_change())
			do_action(conf->curstate->always);
	}
	return (0);
}

void
rt_msg_handler(int fd, short event, void *arg)
{
	char msg[2048];
	struct rt_msghdr *rtm = (struct rt_msghdr *)&msg;
	struct if_msghdr ifm;
	int len;

	len = read(fd, msg, sizeof(msg));

	/* XXX ignore errors? */
	if (len < sizeof(struct rt_msghdr))
		return;

	if (rtm->rtm_version != RTM_VERSION)
		return;

	if (rtm->rtm_type != RTM_IFINFO)
		return;

	memcpy(&ifm, rtm, sizeof(ifm));
	scan_ifstate(ifm.ifm_index, ifm.ifm_data.ifi_link_state, 1);
}

void
sigchld_handler(int fd, short event, void *arg)
{
	check_external_status(&conf->always);
	if (conf->curstate != NULL)
		check_external_status(conf->curstate);
}

void
external_handler(int fd, short event, void *arg)
{
	struct ifsd_external *external = (struct ifsd_external *)arg;
	struct timeval tv;

	/* re-schedule */
	tv.tv_usec = 0;
	tv.tv_sec = external->frequency;
	evtimer_set(&external->ev, external_handler, external);
	evtimer_add(&external->ev, &tv);

	/* execute */
	external_exec(external, 1);
}

void
external_exec(struct ifsd_external *external, int async)
{
	char *argp[] = {"sh", "-c", NULL, NULL};
	pid_t pid;
	int s;

	if (external->pid > 0) {
		logit(IFSD_LOG_NORMAL,
		    "previous command %s [%d] still running, killing it",
		    external->command, external->pid);
		kill(external->pid, SIGKILL);
		waitpid(external->pid, &s, 0);
		external->pid = 0;
	}

	argp[2] = external->command;
	logit(IFSD_LOG_VERBOSE, "running %s", external->command);
	pid = fork();
	if (pid < 0) {
		logit(IFSD_LOG_QUIET, "fork error");
	} else if (pid == 0) {
		execv("/bin/sh", argp);
		_exit(1);
		/* NOTREACHED */
	} else {
		external->pid = pid;
	}
	if (!async) {
		waitpid(external->pid, &s, 0);
		external->pid = 0;
		if (WIFEXITED(s))
			external->prevstatus = WEXITSTATUS(s);
	}
}

void
adjust_external_expressions(struct ifsd_state *state)
{
	struct ifsd_external *external;
	struct ifsd_expression_list expressions;

	TAILQ_INIT(&expressions);
	TAILQ_FOREACH(external, &state->external_tests, entries) {
		struct ifsd_expression *expression;

		if (external->prevstatus == -1)
			continue;

		TAILQ_FOREACH(expression, &external->expressions, entries) {
			TAILQ_INSERT_TAIL(&expressions,
			    expression, eval);
			expression->truth = !external->prevstatus;
		}
		adjust_expressions(&expressions, conf->maxdepth);
	}
}

void
check_external_status(struct ifsd_state *state)
{
	struct ifsd_external *external, *end = NULL;
	int status, s, changed = 0;

	/* Do this manually; change ordering so the oldest is first */
	external = TAILQ_FIRST(&state->external_tests);
	while (external != NULL && external != end) {
		struct ifsd_external *newexternal;

		newexternal = TAILQ_NEXT(external, entries);

		if (external->pid <= 0)
			goto loop;

		if (wait4(external->pid, &s, WNOHANG, NULL) == 0)
			goto loop;

		external->pid = 0;
		if (end == NULL)
			end = external;
		if (WIFEXITED(s))
			status = WEXITSTATUS(s);
		else {
			logit(IFSD_LOG_QUIET,
			    "%s exited abnormally", external->command);
			goto loop;
		}

		if (external->prevstatus != status &&
		    (external->prevstatus != -1 || !opt_inhibit)) {
			changed = 1;
			external->prevstatus = status;
		}
		external->lastexec = time(NULL);
		TAILQ_REMOVE(&state->external_tests, external, entries);
		TAILQ_INSERT_TAIL(&state->external_tests, external, entries);
loop:
		external = newexternal;
	}

	if (changed) {
		adjust_external_expressions(state);
		eval_state(state);
	}
}

void
external_evtimer_setup(struct ifsd_state *state, int action)
{
	struct ifsd_external *external;
	int s;

	if (state != NULL) {
		switch (action) {
		case IFSD_EVTIMER_ADD:
			TAILQ_FOREACH(external,
			    &state->external_tests, entries) {
				struct timeval tv;

				/* run it once right away */
				external_exec(external, 0);

				/* schedule it for later */
				tv.tv_usec = 0;
				tv.tv_sec = external->frequency;
				evtimer_set(&external->ev, external_handler,
				    external);
				evtimer_add(&external->ev, &tv);
			}
			break;
		case IFSD_EVTIMER_DEL:
			TAILQ_FOREACH(external,
			    &state->external_tests, entries) {
				if (external->pid > 0) {
					kill(external->pid, SIGKILL);
					waitpid(external->pid, &s, 0);
					external->pid = 0;
				}
				evtimer_del(&external->ev);
			}
			break;
		}
	}
}

int
scan_ifstate_single(int ifindex, int s, struct ifsd_state *state)
{
	struct ifsd_ifstate *ifstate;
	struct ifsd_expression_list expressions;
	int changed = 0;

	TAILQ_INIT(&expressions);

	TAILQ_FOREACH(ifstate, &state->interface_states, entries) {
		if (ifstate->ifindex == ifindex) {
			if (ifstate->prevstate != s &&
			    (ifstate->prevstate != -1 || !opt_inhibit)) {
				struct ifsd_expression *expression;
				int truth;

				truth = (ifstate->ifstate == s);

				TAILQ_FOREACH(expression,
				    &ifstate->expressions, entries) {
					expression->truth = truth;
					TAILQ_INSERT_TAIL(&expressions,
					    expression, eval);
					changed = 1;
				}
				ifstate->prevstate = s;
			}
		}
	}

	if (changed)
		adjust_expressions(&expressions, conf->maxdepth);
	return (changed);
}

void
scan_ifstate(int ifindex, int s, int do_eval)
{
	struct ifsd_state *state;
	int cur_eval = 0;

	if (scan_ifstate_single(ifindex, s, &conf->always) && do_eval)
		eval_state(&conf->always);
	TAILQ_FOREACH(state, &conf->states, entries) {
		if (scan_ifstate_single(ifindex, s, state) &&
		    (do_eval && state == conf->curstate))
			cur_eval = 1;
	}
	/* execute actions _after_ all expressions have been adjusted */
	if (cur_eval)
		eval_state(conf->curstate);
}

/*
 * Do a bottom-up ajustment of the expression tree's truth value,
 * level-by-level to ensure that each expression's subexpressions have been
 * evaluated.
 */
void
adjust_expressions(struct ifsd_expression_list *expressions, int depth)
{
	struct ifsd_expression_list nexpressions;
	struct ifsd_expression *expression;

	TAILQ_INIT(&nexpressions);
	while ((expression = TAILQ_FIRST(expressions)) != NULL) {
		TAILQ_REMOVE(expressions, expression, eval);
		if (expression->depth == depth) {
			struct ifsd_expression *te;

			switch (expression->type) {
			case IFSD_OPER_AND:
				expression->truth = expression->left->truth &&
				    expression->right->truth;
				break;
			case IFSD_OPER_OR:
				expression->truth = expression->left->truth ||
				    expression->right->truth;
				break;
			case IFSD_OPER_NOT:
				expression->truth = !expression->right->truth;
				break;
			default:
				break;
			}
			if (expression->parent != NULL) {
				if (TAILQ_EMPTY(&nexpressions))
				te = NULL;
				TAILQ_FOREACH(te, &nexpressions, eval)
					if (expression->parent == te)
						break;
				if (te == NULL)
					TAILQ_INSERT_TAIL(&nexpressions,
					    expression->parent, eval);
			}
		} else
			TAILQ_INSERT_TAIL(&nexpressions, expression, eval);
	}
	if (depth > 0)
		adjust_expressions(&nexpressions, depth - 1);
}

void
eval_state(struct ifsd_state *state)
{
	struct ifsd_external *external = TAILQ_FIRST(&state->external_tests);
	if (external == NULL || external->lastexec >= state->entered ||
	    external->lastexec == 0) {
		do_action(state->always);
		while (state_change())
			do_action(conf->curstate->always);
	}
}

/*
 *If a previous action included a state change, process it.
 */
int
state_change(void)
{
	if (conf->nextstate != NULL && conf->curstate != conf->nextstate) {
		logit(IFSD_LOG_NORMAL, "changing state to %s",
		    conf->nextstate->name);
		if (conf->curstate != NULL) {
			evtimer_del(&conf->curstate->ev);
			external_evtimer_setup(conf->curstate,
			    IFSD_EVTIMER_DEL);
		}
		conf->curstate = conf->nextstate;
		conf->nextstate = NULL;
		conf->curstate->entered = time(NULL);
		external_evtimer_setup(conf->curstate, IFSD_EVTIMER_ADD);
		adjust_external_expressions(conf->curstate);
		do_action(conf->curstate->init);
		return (1);
	}
	return (0);
}

/*
 * Run recursively through the tree of actions.
 */
void
do_action(struct ifsd_action *action)
{
	struct ifsd_action *subaction;

	switch (action->type) {
	case IFSD_ACTION_COMMAND:
		logit(IFSD_LOG_NORMAL, "running %s", action->act.command);
		system(action->act.command);
		break;
	case IFSD_ACTION_CHANGESTATE:
		conf->nextstate = action->act.nextstate;
		break;
	case IFSD_ACTION_CONDITION:
		if ((action->act.c.expression != NULL &&
		    action->act.c.expression->truth) ||
		    action->act.c.expression == NULL) {
			TAILQ_FOREACH(subaction, &action->act.c.actions,
			    entries)
				do_action(subaction);
		}
		break;
	default:
		logit(IFSD_LOG_DEBUG, "do_action: unknown action %d",
		    action->type);
		break;
	}
}

/*
 * Fetch the current link states.
 */
void
fetch_state(void)
{
	struct ifaddrs *ifap, *ifa;
	char *oname = NULL;
	int sock = socket(AF_INET, SOCK_DGRAM, 0);

	if (getifaddrs(&ifap) != 0)
		err(1, "getifaddrs");

	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
		struct ifreq ifr;
		struct if_data  ifrdat;

		if (oname && !strcmp(oname, ifa->ifa_name))
			continue;
		oname = ifa->ifa_name;

		strlcpy(ifr.ifr_name, ifa->ifa_name, sizeof(ifr.ifr_name));
		ifr.ifr_data = (caddr_t)&ifrdat;

		if (ioctl(sock, SIOCGIFDATA, (caddr_t)&ifr) == -1)
			continue;

		scan_ifstate(if_nametoindex(ifa->ifa_name),
		    ifrdat.ifi_link_state, 0);
	}
	freeifaddrs(ifap);
	close(sock);
}



/*
 * Clear the config.
 */
void
clear_config(struct ifsd_config *oconf)
{
	struct ifsd_state *state;

	external_evtimer_setup(&conf->always, IFSD_EVTIMER_DEL);
	if (conf != NULL && conf->curstate != NULL)
		external_evtimer_setup(conf->curstate, IFSD_EVTIMER_DEL);
	while ((state = TAILQ_FIRST(&oconf->states)) != NULL) {
		TAILQ_REMOVE(&oconf->states, state, entries);
		remove_action(state->init, state);
		remove_action(state->always, state);
		free(state->name);
		free(state);
	}
	remove_action(oconf->always.init, &oconf->always);
	remove_action(oconf->always.always, &oconf->always);
	free(oconf);
}

void
remove_action(struct ifsd_action *action, struct ifsd_state *state)
{
	struct ifsd_action *subaction;

	if (action == NULL || state == NULL)
		return;

	switch (action->type) {
	case IFSD_ACTION_LOG:
		free(action->act.logmessage);
		break;
	case IFSD_ACTION_COMMAND:
		free(action->act.command);
		break;
	case IFSD_ACTION_CHANGESTATE:
		break;
	case IFSD_ACTION_CONDITION:
		if (action->act.c.expression != NULL)
			remove_expression(action->act.c.expression, state);
		while ((subaction =
		    TAILQ_FIRST(&action->act.c.actions)) != NULL) {
			TAILQ_REMOVE(&action->act.c.actions,
			    subaction, entries);
			remove_action(subaction, state);
		}
	}
	free(action);
}

void
remove_expression(struct ifsd_expression *expression,
    struct ifsd_state *state)
{
	switch (expression->type) {
	case IFSD_OPER_IFSTATE:
		TAILQ_REMOVE(&expression->u.ifstate->expressions, expression,
		    entries);
		if (--expression->u.ifstate->refcount == 0) {
			TAILQ_REMOVE(&state->interface_states,
			    expression->u.ifstate, entries);
			free(expression->u.ifstate);
		}
		break;
	case IFSD_OPER_EXTERNAL:
		TAILQ_REMOVE(&expression->u.external->expressions, expression,
		    entries);
		if (--expression->u.external->refcount == 0) {
			TAILQ_REMOVE(&state->external_tests,
			    expression->u.external, entries);
			free(expression->u.external->command);
			event_del(&expression->u.external->ev);
			free(expression->u.external);
		}
		break;
	default:
		if (expression->left != NULL)
			remove_expression(expression->left, state);
		if (expression->right != NULL)
			remove_expression(expression->right, state);
		break;
	}
	free(expression);
}

void
log_init(int n_debug)
{
	extern char	*__progname;

	if (!n_debug)
		openlog(__progname, LOG_PID | LOG_NDELAY, LOG_DAEMON);
}

void
logit(int level, const char *fmt, ...)
{
	va_list	 ap;
	char	*nfmt;

	if (conf == NULL || level > conf->loglevel)
		return;

	va_start(ap, fmt);
	if (opt_debug) {
		/* best effort in out of mem situations */
		if (asprintf(&nfmt, "ifstated: %s\n", fmt) != -1) {
			vfprintf(stderr, nfmt, ap);
			free(nfmt);
		} else {
			vfprintf(stderr, fmt, ap);
			fprintf(stderr, "\n");
		}
	} else
		vsyslog(LOG_NOTICE, fmt, ap);

	va_end(ap);
}