summaryrefslogtreecommitdiff
path: root/src/odhcp6c.c
blob: 6266aa484719feb5be7c4660b95df54e5cfb2a48 (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
/**
 * Copyright (C) 2012 Steven Barth <steven@midlink.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License v2 as published by
 * the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 */

#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <unistd.h>
#include <syslog.h>
#include <signal.h>
#include <string.h>
#include <stdbool.h>

#include <net/if.h>
#include <sys/wait.h>
#include <sys/syscall.h>

#include "odhcp6c.h"
#include "ra.h"


static void sighandler(int signal);
static int usage(void);


static uint8_t *state_data[_STATE_MAX] = {NULL};
static size_t state_len[_STATE_MAX] = {0};

static volatile int do_signal = 0;
static int urandom_fd = -1;
static bool bound = false;


int main(_unused int argc, char* const argv[])
{
	openlog("odhcp6c", LOG_PERROR | LOG_PID, LOG_DAEMON);

	// Allocate ressources
	const char *pidfile = NULL;
	const char *script = "/usr/sbin/odhcp6c-update";
	ssize_t l;
	uint8_t buf[134];
	char *optpos;
	uint16_t opttype;
	enum odhcp6c_ia_mode ia_na_mode = IA_MODE_TRY;

	bool help = false, daemonize = false;
	int c, request_pd = 0;
	while ((c = getopt(argc, argv, "N:P:c:r:s:hdp:")) != -1) {
		switch (c) {
		case 'N':
			if (!strcmp(optarg, "force"))
				ia_na_mode = IA_MODE_FORCE;
			else if (!strcmp(optarg, "none"))
				ia_na_mode = IA_MODE_NONE;
			else if (!strcmp(optarg, "try"))
				ia_na_mode = IA_MODE_TRY;
			else
				help = true;
			break;

		case 'P':
			request_pd = strtoul(optarg, NULL, 10);
			if (request_pd == 0)
				request_pd = -1;
			break;

		case 'c':
			l = script_unhexlify(&buf[4], sizeof(buf) - 4, optarg);
			if (l > 0) {
				buf[0] = 0;
				buf[1] = DHCPV6_OPT_CLIENTID;
				buf[2] = 0;
				buf[4] = l;
				odhcp6c_add_state(STATE_CLIENT_ID, buf, l + 4);
			} else {
				help = true;
			}
			break;

		case 'r':
			optpos = optarg;
			while (optpos[0]) {
				opttype = htons(strtoul(optarg, &optpos, 10));
				if (optpos == optarg)
					break;
				else if (optpos[0])
					optarg = &optpos[1];
				odhcp6c_add_state(STATE_ORO, &opttype, 2);
			}
			break;

		case 's':
			script = optarg;
			break;

		case 'd':
			daemonize = true;
			break;

		case 'p':
			pidfile = optarg;
			break;

		default:
			help = true;
			break;
		}
	}

	const char *ifname = argv[optind];

	if (help || !ifname)
		return usage();

	if ((urandom_fd = open("/dev/urandom", O_CLOEXEC | O_RDONLY)) < 0 ||
			init_dhcpv6(ifname, request_pd) || ra_init(ifname) ||
			script_init(script, ifname)) {
		syslog(LOG_ERR, "failed to initialize: %s", strerror(errno));
		return 3;
	}

	signal(SIGIO, sighandler);
	signal(SIGHUP, sighandler);
	signal(SIGINT, sighandler);
	signal(SIGCHLD, sighandler);
	signal(SIGTERM, sighandler);
	signal(SIGUSR1, sighandler);
	signal(SIGUSR2, sighandler);

	if (daemonize) {
		openlog("odhcp6c", LOG_PID, LOG_DAEMON); // Disable LOG_PERROR
		if (daemon(0, 0)) {
			syslog(LOG_ERR, "Failed to daemonize: %s",
					strerror(errno));
			return 4;
		}

		char pidbuf[128];
		if (!pidfile) {
			snprintf(pidbuf, sizeof(pidbuf),
					"/var/run/odhcp6c.%s.pid", ifname);
			pidfile = pidbuf;
		}

		int fd = open(pidfile, O_WRONLY | O_CREAT);
		if (fd >= 0) {
			char buf[8];
			int len = snprintf(buf, sizeof(buf), "%i\n", getpid());
			write(fd, buf, len);
			close(fd);
		}
	}

	script_call("started");

	while (do_signal != SIGTERM) { // Main logic
		odhcp6c_clear_state(STATE_SERVER_ID);
		odhcp6c_clear_state(STATE_SERVER_CAND);
		odhcp6c_clear_state(STATE_IA_PD);
		odhcp6c_clear_state(STATE_SNTP_IP);
		odhcp6c_clear_state(STATE_SNTP_FQDN);
		odhcp6c_clear_state(STATE_SIP_IP);
		odhcp6c_clear_state(STATE_SIP_FQDN);
		dhcpv6_set_ia_na_mode(ia_na_mode);
		bound = false;

		do_signal = 0;
		int res = dhcpv6_request(DHCPV6_MSG_SOLICIT);

		if (res < 0) {
			continue; // Might happen if we got a signal
		} else if (res == DHCPV6_STATELESS) { // Stateless mode
			while (do_signal == 0 || do_signal == SIGUSR1) {
				do_signal = 0;

				res = dhcpv6_request(DHCPV6_MSG_INFO_REQ);
				if (do_signal == SIGUSR1)
					continue;
				else if (res < 0)
					break;
				else if (res > 0)
					script_call("informed");

				bound = true;

				if (dhcpv6_poll_reconfigure() > 0)
					script_call("informed");
			}

			continue;
		}

		// Stateful mode
		if (dhcpv6_request(DHCPV6_MSG_REQUEST) < 0)
			continue;

		script_call("bound");
		bound = true;

		while (do_signal == 0 || do_signal == SIGUSR1) {
			// Renew Cycle
			// Wait for T1 to expire or until we get a reconfigure
			int res = dhcpv6_poll_reconfigure();
			if (res >= 0) {
				if (res > 0)
					script_call("updated");

				continue;
			}

			// Handle signal, if necessary
			if (do_signal == SIGUSR1)
				do_signal = 0; // Acknowledged
			else if (do_signal > 0)
				break; // Other signal type

			size_t ia_pd_len, ia_na_len, ia_pd_new, ia_na_new;
			odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
			odhcp6c_get_state(STATE_IA_NA, &ia_na_len);

			// If we have any IAs, send renew, otherwise request
			int r;
			if (ia_pd_len == 0 && ia_na_len == 0)
				r = dhcpv6_request(DHCPV6_MSG_REQUEST);
			else
				r = dhcpv6_request(DHCPV6_MSG_RENEW);
			if (r > 0) // Publish updates
				script_call("updated");
			if (r >= 0)
				continue; // Renew was successful

			odhcp6c_clear_state(STATE_SERVER_ID); // Remove binding

			// If we have IAs, try rebind otherwise restart
			res = dhcpv6_request(DHCPV6_MSG_REBIND);

			odhcp6c_get_state(STATE_IA_PD, &ia_pd_new);
			odhcp6c_get_state(STATE_IA_NA, &ia_na_new);
			if (res < 0 || (ia_pd_new == 0 && ia_pd_len) ||
					(ia_na_new == 0 && ia_na_len))
				break; // We lost all our IAs, restart
			else if (res > 0)
				script_call("rebound");
		}


		size_t ia_pd_len, ia_na_len, server_id_len;
		odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
		odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
		odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);

		// Add all prefixes to lost prefixes
		bound = false;
		script_call("unbound");

		if (server_id_len > 0 && (ia_pd_len > 0 || ia_na_len > 0))
			dhcpv6_request(DHCPV6_MSG_RELEASE);

		odhcp6c_clear_state(STATE_IA_NA);
		odhcp6c_clear_state(STATE_IA_PD);
	}

	script_call("stopped");
	return 0;
}


static int usage(void)
{
	const char buf[] =
	"Usage: odhcp6c [options] <interface>\n"
	"\nFeature options:\n"
	"	-N <mode>	Mode for requesting addresses [try|force|none]\n"
	"	-P <length>	Request IPv6-Prefix (0 = auto)\n"
	"	-c <clientid>	Override client-ID (base-16 encoded)\n"
	"	-r <options>	Options to be requested (comma-separated)\n"
	"	-s <script>	Status update script (/usr/sbin/odhcp6c-update)\n"
	"\nInvocation options:\n"
	"	-p <pidfile>	Set pidfile (/var/run/6relayd.pid)\n"
	"	-d		Daemonize\n"
	//"	-v		Increase logging verbosity\n"
	"	-h		Show this help\n\n";
	write(STDERR_FILENO, buf, sizeof(buf));
	return 1;
}


// Don't want to pull-in librt and libpthread just for a monotonic clock...
uint64_t odhcp6c_get_milli_time(void)
{
	struct timespec t = {0, 0};
	syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &t);
	return t.tv_sec * 1000 + t.tv_nsec / 1000000;
}


static uint8_t* odhcp6c_resize_state(enum odhcp6c_state state, ssize_t len)
{
	if (len == 0)
		return state_data[state] + state_len[state];

	uint8_t *n = realloc(state_data[state], state_len[state] + len);
	if (n || state_len[state] + len == 0) {
		state_data[state] = n;
		n += state_len[state];
		state_len[state] += len;
	}
	return n;
}


bool odhcp6c_signal_process(void)
{
	if (do_signal == SIGIO) {
		do_signal = 0;
		bool updated = ra_process();
		updated |= ra_rtnl_process();
		if (updated && bound) {
			odhcp6c_expire();
			script_call("ra-updated");
		}
	}

	return do_signal != 0;
}


void odhcp6c_clear_state(enum odhcp6c_state state)
{
	state_len[state] = 0;
}


void odhcp6c_add_state(enum odhcp6c_state state, const void *data, size_t len)
{
	uint8_t *n = odhcp6c_resize_state(state, len);
	if (n)
		memcpy(n, data, len);
}


size_t odhcp6c_remove_state(enum odhcp6c_state state, size_t offset, size_t len)
{
	uint8_t *data = state_data[state];
	ssize_t len_after = state_len[state] - (offset + len);
	if (len_after < 0)
		return state_len[state];

	memmove(data + offset, data + offset + len, len_after);
	return state_len[state] -= len;
}


void* odhcp6c_get_state(enum odhcp6c_state state, size_t *len)
{
	*len = state_len[state];
	return state_data[state];
}


struct odhcp6c_entry* odhcp6c_find_entry(enum odhcp6c_state state, const struct odhcp6c_entry *new)
{
	size_t len, cmplen = offsetof(struct odhcp6c_entry, target) + new->length / 8;
	struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
	struct odhcp6c_entry *x = NULL;

	for (struct odhcp6c_entry *c = start; !x && c < &start[len/sizeof(*c)]; ++c)
		if (!memcmp(c, new, cmplen))
			return c;

	return NULL;
}


void odhcp6c_update_entry_safe(enum odhcp6c_state state, const struct odhcp6c_entry *new, uint32_t safe)
{
	size_t len;
	struct odhcp6c_entry *x = odhcp6c_find_entry(state, new);
	struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);

	if (x && x->valid > new->valid && new->valid < safe)
		return;

	if (new->valid > 0) {
		if (x)
			*x = *new;
		else
			odhcp6c_add_state(state, new, sizeof(*new));
	} else if (x) {
		odhcp6c_remove_state(state, (x - start) * sizeof(*x), sizeof(*x));
	}
}


void odhcp6c_update_entry(enum odhcp6c_state state, const struct odhcp6c_entry *new)
{
	odhcp6c_update_entry_safe(state, new, 0);
}


static void odhcp6c_expire_list(enum odhcp6c_state state, uint32_t elapsed)
{
	size_t len;
	struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
	for (struct odhcp6c_entry *c = start; c < &start[len / sizeof(*c)]; ++c) {
		if (c->preferred < elapsed)
			c->preferred = 0;
		else if (c->preferred != UINT32_MAX)
			c->preferred -= elapsed;

		if (c->valid < elapsed)
			c->valid = 0;
		else if (c->valid != UINT32_MAX)
			c->valid -= elapsed;

		if (!c->valid)
			odhcp6c_remove_state(state, (c - start) * sizeof(*c), sizeof(*c));
	}
}


void odhcp6c_expire(void)
{
	static time_t last_update = 0;
	time_t now = odhcp6c_get_milli_time() / 1000;

	uint32_t elapsed = now - last_update;
	last_update = now;

	odhcp6c_expire_list(STATE_RA_PREFIX, elapsed);
	odhcp6c_expire_list(STATE_RA_ROUTE, elapsed);
	odhcp6c_expire_list(STATE_IA_NA, elapsed);
	odhcp6c_expire_list(STATE_IA_PD, elapsed);
}


void odhcp6c_random(void *buf, size_t len)
{
	read(urandom_fd, buf, len);
}


static void sighandler(int signal)
{
	if (signal == SIGCHLD)
		while (waitpid(-1, NULL, WNOHANG) > 0);
	else if (signal == SIGUSR1)
		do_signal = SIGUSR1;
	else if (signal == SIGUSR2)
		do_signal = SIGUSR2;
	else if (signal == SIGIO)
		do_signal = SIGIO;
	else
		do_signal = SIGTERM;
}