aboutsummaryrefslogtreecommitdiffstats
path: root/pingu.c
blob: 20479011212dedf63d9f435426fffbcd87a0b161 (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

#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <sys/queue.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "icmp.h"
#include "pingu.h"
#include "xlib.h"

#ifndef DEFAULT_CONFIG
#define DEFAULT_CONFIG "/etc/pingu/pingu.conf"
#endif

#ifndef DEFAULT_PIDFILE
#define DEFAULT_PIDFILE "/var/run/pingu.pid"
#endif

int pingu_verbose = 0, pid_file_fd = 0, pingu_daemonize = 0;
char *pid_file = DEFAULT_PIDFILE;
int interval = 30;
float default_timeout = 1.0;
int default_retry = 5;
int default_required_replies = 2;
char *default_up_action = NULL;
char *default_down_action = NULL;
char *default_route_script = NULL;

struct provider {
	struct sockaddr_in address;
	char *name;
	char *interface;
	char *gateway;
	char *up_action;
	char *down_action;
	int status;
	int retry;
	int required_replies;
	float timeout;
	SLIST_ENTRY(provider) provider_list;
};

SLIST_HEAD(provider_list, provider);

#if 0
int skip(char **str, int whitespace)
{
	char *
	while (isspace(*p)) {
		if (*p == '\0')
			return;
		p++;
	}
}
#endif

/* note: this overwrite the line buffer */
void parse_line(char *line, char **key, char **value)
{
	char *p;

	/* strip comments and trailng \n */
	p = strpbrk(line, "#\n");
	if (p)
		*p = '\0';

	(*value) = NULL;
	if (line[0] == '\0') {
		(*key) = NULL;
		return;
	}
	
	/* skip leading whitespace */
	while (isspace(*p)) {
		if (*p == '\0')
			return;
		p++;
	}
	(*key) = line;

	/* find space between keyword and value */
	p = line;
	while (!isspace(*p)) {
		if (*p == '\0')
			return;
		p++;
	}
	*p++ = '\0';

	/* find value */
	while (isspace(*p)) {
		if (*p == '\0')
			return;
		p++;
	}
	(*value) = p;
}

int read_config(const char *file, struct provider_list *head)
{
	FILE *f = fopen(file, "r");
	struct provider *p = NULL;
	int i = 0, lineno = 0;
	char line[256];
	if (f == NULL) {
		log_perror(file);
		return -1;
	}
	while (fgets(line, sizeof(line), f)) {
		char *key, *value;
		lineno++;
		parse_line(line, &key, &value);
		if (key == NULL)
			continue;

		if (strcmp(key, "host") == 0) {
			p = xmalloc(sizeof(struct provider));
			memset(p, 0, sizeof(struct provider));
			if (init_sockaddr(&p->address, value) < 0)
				return 1;
			p->gateway = xstrdup(value);
			p->status = 1; /* online by default */
			p->retry = default_retry;
			p->timeout = default_timeout;
			p->up_action = default_up_action;
			p->down_action = default_down_action;
			p->required_replies = default_required_replies;
			SLIST_INSERT_HEAD(head, p, provider_list);
			continue;
		}
		if (p == NULL) {
			if (strcmp(key, "interval") == 0) {
				interval = atoi(value);
			} else if (strcmp(key, "retry") == 0) {
				default_retry = atoi(value);
			} else if (strcmp(key, "required") == 0) {
				default_required_replies = atoi(value);
			} else if (strcmp(key, "timeout") == 0) {
				default_timeout = atof(value);
			} else if (strcmp(key, "up-action") == 0) {
				default_up_action = xstrdup(value);
			} else if (strcmp(key, "down-action") == 0) {
				default_down_action = xstrdup(value);
			} else if (strcmp(key, "route-script") == 0) {
				default_route_script = xstrdup(value);
			} else 
				log_error("host not specified");
		} else if (strcmp(key, "interface") == 0) {
			p->interface = xstrdup(value);
		} else if (strcmp(key, "gateway") == 0) {
			if (p->gateway)
				free(p->gateway);
			p->gateway = xstrdup(value);
		} else if (strcmp(key, "name") == 0) {
			p->name = xstrdup(value);
		} else if (strcmp(key, "up-action") == 0) {
			p->up_action = xstrdup(value);
		} else if (strcmp(key, "down-action") == 0) {
			p->down_action = xstrdup(value);
		} else if (strcmp(key, "retry") == 0) {
			p->retry = atoi(value);
		} else if (strcmp(key, "required") == 0) {
			p->required_replies = atoi(value);
		} else if (strcmp(key, "timeout") == 0) {
			p->timeout = atof(value);
		} else {
			log_error("Unknown keyword '%s' on line %i", key,
				  lineno);
		}
	}
	return 0;
}

/* returns true if it get at least required_replies/retries replies */
int ping_status(struct sockaddr_in *to, int *seq, int retries, 
		int required_replies, float timeout, const char *iface)
{
	__u8 buf[1500];
	struct iphdr *ip = (struct iphdr *) buf;
	struct icmphdr *icp;
	struct sockaddr_in from;
	int retry;
	int replies = 0;
	int len = sizeof(struct iphdr) + sizeof(struct icmphdr);
	int fd = icmp_open(timeout);

	if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, iface, 
		       (iface == NULL) ? 0 : strlen(iface)+1) == -1)
		goto close_fd;

	for (retry = 0; retry < retries && replies < required_replies; retry++) {
		icmp_send_ping(fd, (struct sockaddr *) to, sizeof(*to),
			       *seq, len);
		(*seq)++;
		(*seq) &= 0xffff;
		if ((len = icmp_read_reply(fd, (struct sockaddr *) &from,
					   sizeof(from), buf, sizeof(buf))) <= 0)
			continue;

		icp = (struct icmphdr *) &buf[ip->ihl * 4];
		if (icp->type == ICMP_ECHOREPLY && icp->un.echo.id == getpid()) {
			replies++;
		}
	}
close_fd:
	icmp_close(fd);
#if 0
	printf("address=%s, replies=%i, required=%i\n",  
	       inet_ntoa(to->sin_addr), replies, required_replies);
#endif
	return (replies >= required_replies);
}

static void print_version(const char *program)
{
	printf("%s " PINGU_VERSION "\n", program);
}

int usage(const char *program)
{
	print_version(program);
	fprintf(stderr, "usage: %s [-dh] [-c CONFIG] [-p PIDFILE]\n"
		"options:\n"
       		" -c  Read configuration from FILE (default is " 
			DEFAULT_CONFIG ")\n"
		" -d  Fork to background (damonize)\n"
		" -h  Show this help\n"
		" -p  Use PIDFILE as pidfile (default is " 
			DEFAULT_PIDFILE ")\n"
		" -V  Print version and exit\n"
		"\n",
		program);
	return 1;
}

#if 0
void dump_provider(struct provider *p)
{		
	printf("router:      %s\n"
	       "provider:    %s\n"
	       "interface:   %s\n"
	       "up-action:   %s\n"
	       "down-action: %s\n"
	       "p->status:   %i\n"
	       "\n",
	       inet_ntoa(p->address.sin_addr), p->name, p->interface,
	       p->up_action, p->down_action, p->status);
}
#endif

char *get_provider_gateway(struct provider *p)
{
	if (p->gateway != NULL)
		return p->gateway;
	return inet_ntoa(p->address.sin_addr);
}

void exec_route_change(struct provider_list *head)
{
	struct provider *p;
	char **args;
	int i = 0, status;
	pid_t pid;

	if (default_route_script == NULL)
		return;

	SLIST_FOREACH(p, head, provider_list) {
		i++;
	}
	args = xmalloc(sizeof(char *) * (i + 2));

	i = 0;
	args[i++] = default_route_script;
	SLIST_FOREACH(p, head, provider_list) {
		if (p->status)
			args[i++] = get_provider_gateway(p);
	}
	args[i] = NULL;
	pid = fork();
	switch (pid) {
	case -1:
		log_perror("fork");
		goto free_and_return;
		break;
	case 0:
		execvp(default_route_script, args);
		log_perror(args[0]);
		exit(1);
	default:
		wait(&status);
	}

free_and_return:
	free(args);
	return;
}

void ping_loop(struct provider_list *head, int interval)
{
	struct provider *p;
	int seq = 0, change;
	while (1) {
		change = 0;
		SLIST_FOREACH(p, head, provider_list) {
			int status;
			status = ping_status(&p->address, &seq, p->retry,
					     p->required_replies, p->timeout,
					     p->interface);
			if (status != p->status) {
				change++;
				p->status = status;
				if (status)
					system(p->up_action);
				else
					system(p->down_action);
			}
		}
		if (change)
			exec_route_change(head);

		sleep(interval);

	}
}

static void remove_pid_file(void)
{
	if (pid_file_fd != 0) {
		close(pid_file_fd);
		pid_file_fd = 0;
		remove(pid_file);
	}
}

static int daemonize(void)
{
	char tmp[16];
	pid_t pid;

	pid = fork();
	if (pid < 0)
		return -1;
	if (pid > 0)
		exit(0);

	if (setsid() < 0)
		return -1;

	pid = fork();
	if (pid < 0)
		return -1;
	if (pid > 0)
		exit(0);

	if (chdir("/") < 0)
		return -1;

	pid_file_fd = open(pid_file, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
	if (pid_file_fd < 0) {
		log_error("Unable to open %s: %s.", pid_file, strerror(errno));
		return -1;
	}

	if (flock(pid_file_fd, LOCK_EX | LOCK_NB) < 0) {
		log_error("Unable to lock pid file (already running?).");
		close(pid_file_fd);
		pid_file_fd = 0;
		return -1;
	}

	ftruncate(pid_file_fd, 0);
	write(pid_file_fd, tmp, sprintf(tmp, "%d\n", getpid()));
	atexit(remove_pid_file);

	freopen("/dev/null", "r", stdin);
	freopen("/dev/null", "w", stdout);
	freopen("/dev/null", "w", stderr);

	umask(0);

	return 0;
}

int main(int argc, char *argv[])
{
	int c, debug_mode = 0;
	struct provider_list providers;
	char *config_file = DEFAULT_CONFIG;

	while ((c = getopt(argc, argv, "c:dhp:V")) != -1) {
		switch (c) {
		case 'c':
			config_file = optarg;
			break;
		case 'd':
			pingu_daemonize++;
			break;
		case 'h':
			return usage(basename(argv[0]));
		case 'p':
			pid_file = optarg;
			break;
		case 'V':
			print_version(basename(argv[0]));
			return 0;
		}
	}

	argc -= optind;
	argv += optind;

	SLIST_INIT(&providers);
	if (read_config(config_file, &providers) == -1)
		return 1;

	if (pingu_daemonize) {
		if (daemonize() == -1)
			return 1;
	}

	ping_loop(&providers, interval);

	return 0;
}