Avoid updating too often if ISP spams RAs
[project/odhcp6c.git] / src / odhcp6c.c
1 /**
2 * Copyright (C) 2012-2013 Steven Barth <steven@midlink.org>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License v2 as published by
6 * the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 */
14
15 #include <time.h>
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <stddef.h>
21 #include <unistd.h>
22 #include <syslog.h>
23 #include <signal.h>
24 #include <string.h>
25 #include <stdbool.h>
26
27 #include <net/if.h>
28 #include <sys/wait.h>
29 #include <sys/syscall.h>
30 #include <arpa/inet.h>
31
32 #include "odhcp6c.h"
33 #include "ra.h"
34
35
36 static void sighandler(int signal);
37 static int usage(void);
38
39
40 static uint8_t *state_data[_STATE_MAX] = {NULL};
41 static size_t state_len[_STATE_MAX] = {0};
42
43 static volatile int do_signal = 0;
44 static int urandom_fd = -1, allow_slaac_only = 0;
45 static bool bound = false, release = true;
46 static time_t last_update = 0;
47
48
49 int main(_unused int argc, char* const argv[])
50 {
51 // Allocate ressources
52 const char *pidfile = NULL;
53 const char *script = "/usr/sbin/odhcp6c-update";
54 ssize_t l;
55 uint8_t buf[134];
56 char *optpos;
57 uint16_t opttype;
58 enum odhcp6c_ia_mode ia_na_mode = IA_MODE_TRY;
59 enum odhcp6c_ia_mode ia_pd_mode = IA_MODE_TRY;
60 static struct in6_addr ifid = IN6ADDR_ANY_INIT;
61 int sol_timeout = 120;
62
63 bool help = false, daemonize = false;
64 int logopt = LOG_PID;
65 int c, request_pd = 0;
66 while ((c = getopt(argc, argv, "S::N:P:Fc:i:r:s:kt:hedp:")) != -1) {
67 switch (c) {
68 case 'S':
69 allow_slaac_only = (optarg) ? atoi(optarg) : -1;
70 break;
71
72 case 'N':
73 if (!strcmp(optarg, "force")) {
74 ia_na_mode = IA_MODE_FORCE;
75 allow_slaac_only = -1;
76 } else if (!strcmp(optarg, "none")) {
77 ia_na_mode = IA_MODE_NONE;
78 } else if (!strcmp(optarg, "try")) {
79 ia_na_mode = IA_MODE_TRY;
80 } else{
81 help = true;
82 }
83 break;
84
85 case 'P':
86 if (allow_slaac_only >= 0 && allow_slaac_only < 10)
87 allow_slaac_only = 10;
88
89 request_pd = strtoul(optarg, NULL, 10);
90 if (request_pd == 0)
91 request_pd = -1;
92
93 ia_pd_mode = IA_MODE_TRY;
94 break;
95
96 case 'F':
97 allow_slaac_only = -1;
98 ia_pd_mode = IA_MODE_FORCE;
99 break;
100
101 case 'c':
102 l = script_unhexlify(&buf[4], sizeof(buf) - 4, optarg);
103 if (l > 0) {
104 buf[0] = 0;
105 buf[1] = DHCPV6_OPT_CLIENTID;
106 buf[2] = 0;
107 buf[3] = l;
108 odhcp6c_add_state(STATE_CLIENT_ID, buf, l + 4);
109 } else {
110 help = true;
111 }
112 break;
113
114 case 'i':
115 if (inet_pton(AF_INET6, optarg, &ifid) != 1)
116 help = true;
117 break;
118
119 case 'r':
120 optpos = optarg;
121 while (optpos[0]) {
122 opttype = htons(strtoul(optarg, &optpos, 10));
123 if (optpos == optarg)
124 break;
125 else if (optpos[0])
126 optarg = &optpos[1];
127 odhcp6c_add_state(STATE_ORO, &opttype, 2);
128 }
129 break;
130
131 case 's':
132 script = optarg;
133 break;
134
135 case 'k':
136 release = false;
137 break;
138
139 case 't':
140 sol_timeout = atoi(optarg);
141 break;
142
143 case 'e':
144 logopt |= LOG_PERROR;
145 break;
146
147 case 'd':
148 daemonize = true;
149 break;
150
151 case 'p':
152 pidfile = optarg;
153 break;
154
155 default:
156 help = true;
157 break;
158 }
159 }
160
161 openlog("odhcp6c", logopt, LOG_DAEMON);
162 const char *ifname = argv[optind];
163
164 if (help || !ifname)
165 return usage();
166
167 signal(SIGIO, sighandler);
168 signal(SIGHUP, sighandler);
169 signal(SIGINT, sighandler);
170 signal(SIGCHLD, sighandler);
171 signal(SIGTERM, sighandler);
172 signal(SIGUSR1, sighandler);
173 signal(SIGUSR2, sighandler);
174
175 if ((urandom_fd = open("/dev/urandom", O_CLOEXEC | O_RDONLY)) < 0 ||
176 init_dhcpv6(ifname, request_pd, sol_timeout) ||
177 ra_init(ifname, &ifid) || script_init(script, ifname)) {
178 syslog(LOG_ERR, "failed to initialize: %s", strerror(errno));
179 return 3;
180 }
181
182 if (daemonize) {
183 openlog("odhcp6c", LOG_PID, LOG_DAEMON); // Disable LOG_PERROR
184 if (daemon(0, 0)) {
185 syslog(LOG_ERR, "Failed to daemonize: %s",
186 strerror(errno));
187 return 4;
188 }
189
190 char pidbuf[128];
191 if (!pidfile) {
192 snprintf(pidbuf, sizeof(pidbuf),
193 "/var/run/odhcp6c.%s.pid", ifname);
194 pidfile = pidbuf;
195 }
196
197 int fd = open(pidfile, O_WRONLY | O_CREAT);
198 if (fd >= 0) {
199 char buf[8];
200 int len = snprintf(buf, sizeof(buf), "%i\n", getpid());
201 write(fd, buf, len);
202 close(fd);
203 }
204 }
205
206 script_call("started");
207
208 while (do_signal != SIGTERM) { // Main logic
209 odhcp6c_clear_state(STATE_SERVER_ID);
210 odhcp6c_clear_state(STATE_IA_NA);
211 odhcp6c_clear_state(STATE_IA_PD);
212 odhcp6c_clear_state(STATE_SNTP_IP);
213 odhcp6c_clear_state(STATE_SNTP_FQDN);
214 odhcp6c_clear_state(STATE_SIP_IP);
215 odhcp6c_clear_state(STATE_SIP_FQDN);
216 dhcpv6_set_ia_mode(ia_na_mode, ia_pd_mode);
217 bound = false;
218
219 // Server candidates need deep-delete
220 size_t cand_len;
221 struct dhcpv6_server_cand *cand = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
222 for (size_t i = 0; i < cand_len / sizeof(*cand); ++i) {
223 free(cand[i].ia_na);
224 free(cand[i].ia_pd);
225 }
226 odhcp6c_clear_state(STATE_SERVER_CAND);
227
228 syslog(LOG_NOTICE, "(re)starting transaction on %s", ifname);
229
230 do_signal = 0;
231 int res = dhcpv6_request(DHCPV6_MSG_SOLICIT);
232 odhcp6c_signal_process();
233
234 if (res < 0) {
235 continue; // Might happen if we got a signal
236 } else if (res == DHCPV6_STATELESS) { // Stateless mode
237 while (do_signal == 0 || do_signal == SIGUSR1) {
238 do_signal = 0;
239
240 res = dhcpv6_request(DHCPV6_MSG_INFO_REQ);
241 odhcp6c_signal_process();
242 if (do_signal == SIGUSR1)
243 continue;
244 else if (res < 0)
245 break;
246 else if (res > 0)
247 script_call("informed");
248
249 bound = true;
250 syslog(LOG_NOTICE, "entering stateless-mode on %s", ifname);
251
252 if (dhcpv6_poll_reconfigure() > 0)
253 script_call("informed");
254 }
255
256 continue;
257 }
258
259 // Stateful mode
260 if (dhcpv6_request(DHCPV6_MSG_REQUEST) < 0)
261 continue;
262
263 odhcp6c_signal_process();
264 script_call("bound");
265 bound = true;
266 syslog(LOG_NOTICE, "entering stateful-mode on %s", ifname);
267
268 while (do_signal == 0 || do_signal == SIGUSR1) {
269 // Renew Cycle
270 // Wait for T1 to expire or until we get a reconfigure
271 int res = dhcpv6_poll_reconfigure();
272 odhcp6c_signal_process();
273 if (res >= 0) {
274 if (res > 0)
275 script_call("updated");
276
277 continue;
278 }
279
280 // Handle signal, if necessary
281 if (do_signal == SIGUSR1)
282 do_signal = 0; // Acknowledged
283 else if (do_signal > 0)
284 break; // Other signal type
285
286 size_t ia_pd_len, ia_na_len, ia_pd_new, ia_na_new;
287 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
288 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
289
290 // If we have any IAs, send renew, otherwise request
291 int r;
292 if (ia_pd_len == 0 && ia_na_len == 0)
293 r = dhcpv6_request(DHCPV6_MSG_REQUEST);
294 else
295 r = dhcpv6_request(DHCPV6_MSG_RENEW);
296 odhcp6c_signal_process();
297 if (r > 0) // Publish updates
298 script_call("updated");
299 if (r >= 0)
300 continue; // Renew was successful
301
302 odhcp6c_clear_state(STATE_SERVER_ID); // Remove binding
303
304 // If we have IAs, try rebind otherwise restart
305 res = dhcpv6_request(DHCPV6_MSG_REBIND);
306 odhcp6c_signal_process();
307
308 odhcp6c_get_state(STATE_IA_PD, &ia_pd_new);
309 odhcp6c_get_state(STATE_IA_NA, &ia_na_new);
310 if (res < 0 || (ia_pd_new == 0 && ia_pd_len) ||
311 (ia_na_new == 0 && ia_na_len))
312 break; // We lost all our IAs, restart
313 else if (res > 0)
314 script_call("rebound");
315 }
316
317
318 size_t ia_pd_len, ia_na_len, server_id_len;
319 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
320 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
321 odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
322
323 // Add all prefixes to lost prefixes
324 bound = false;
325 script_call("unbound");
326
327 if (server_id_len > 0 && (ia_pd_len > 0 || ia_na_len > 0) && release)
328 dhcpv6_request(DHCPV6_MSG_RELEASE);
329
330 odhcp6c_clear_state(STATE_IA_NA);
331 odhcp6c_clear_state(STATE_IA_PD);
332 }
333
334 script_call("stopped");
335 return 0;
336 }
337
338
339 static int usage(void)
340 {
341 const char buf[] =
342 "Usage: odhcp6c [options] <interface>\n"
343 "\nFeature options:\n"
344 " -S <time> Wait at least <time> sec for a DHCP-server (0)\n"
345 " -N <mode> Mode for requesting addresses [try|force|none]\n"
346 " -P <length> Request IPv6-Prefix (0 = auto)\n"
347 " -F Force IPv6-Prefix\n"
348 " -c <clientid> Override client-ID (base-16 encoded)\n"
349 " -i <iface-id> Use a custom interface identifier for RA handling\n"
350 " -r <options> Options to be requested (comma-separated)\n"
351 " -s <script> Status update script (/usr/sbin/odhcp6c-update)\n"
352 " -k Don't send a RELEASE when stopping\n"
353 " -t <seconds> Maximum timeout for DHCPv6-SOLICIT (120)\n"
354 "\nInvocation options:\n"
355 " -p <pidfile> Set pidfile (/var/run/6relayd.pid)\n"
356 " -d Daemonize\n"
357 " -e Write logmessages to stderr\n"
358 //" -v Increase logging verbosity\n"
359 " -h Show this help\n\n";
360 write(STDERR_FILENO, buf, sizeof(buf));
361 return 1;
362 }
363
364
365 // Don't want to pull-in librt and libpthread just for a monotonic clock...
366 uint64_t odhcp6c_get_milli_time(void)
367 {
368 struct timespec t = {0, 0};
369 syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &t);
370 return t.tv_sec * 1000 + t.tv_nsec / 1000000;
371 }
372
373
374 static uint8_t* odhcp6c_resize_state(enum odhcp6c_state state, ssize_t len)
375 {
376 if (len == 0)
377 return state_data[state] + state_len[state];
378 else if (state_len[state] + len > 1024)
379 return NULL;
380
381 uint8_t *n = realloc(state_data[state], state_len[state] + len);
382 if (n || state_len[state] + len == 0) {
383 state_data[state] = n;
384 n += state_len[state];
385 state_len[state] += len;
386 }
387 return n;
388 }
389
390
391 bool odhcp6c_signal_process(void)
392 {
393 if (do_signal == SIGIO) {
394 do_signal = 0;
395 bool ra_updated = ra_process();
396
397 if (ra_updated && (bound || allow_slaac_only == 0))
398 script_call("ra-updated"); // Immediate process urgent events
399 else if (ra_updated && !bound && allow_slaac_only > 0)
400 script_delay_call("ra-updated", allow_slaac_only);
401 }
402
403 return do_signal != 0;
404 }
405
406
407 void odhcp6c_clear_state(enum odhcp6c_state state)
408 {
409 state_len[state] = 0;
410 }
411
412
413 void odhcp6c_add_state(enum odhcp6c_state state, const void *data, size_t len)
414 {
415 uint8_t *n = odhcp6c_resize_state(state, len);
416 if (n)
417 memcpy(n, data, len);
418 }
419
420
421 size_t odhcp6c_remove_state(enum odhcp6c_state state, size_t offset, size_t len)
422 {
423 uint8_t *data = state_data[state];
424 ssize_t len_after = state_len[state] - (offset + len);
425 if (len_after < 0)
426 return state_len[state];
427
428 memmove(data + offset, data + offset + len, len_after);
429 return state_len[state] -= len;
430 }
431
432
433 void* odhcp6c_move_state(enum odhcp6c_state state, size_t *len)
434 {
435 *len = state_len[state];
436 void *data = state_data[state];
437
438 state_len[state] = 0;
439 state_data[state] = NULL;
440
441 return data;
442 }
443
444
445 void* odhcp6c_get_state(enum odhcp6c_state state, size_t *len)
446 {
447 *len = state_len[state];
448 return state_data[state];
449 }
450
451
452 struct odhcp6c_entry* odhcp6c_find_entry(enum odhcp6c_state state, const struct odhcp6c_entry *new)
453 {
454 size_t len, cmplen = offsetof(struct odhcp6c_entry, target) + new->length / 8;
455 struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
456 struct odhcp6c_entry *x = NULL;
457
458 for (struct odhcp6c_entry *c = start; !x && c < &start[len/sizeof(*c)]; ++c)
459 if (!memcmp(c, new, cmplen))
460 return c;
461
462 return NULL;
463 }
464
465
466 bool odhcp6c_update_entry_safe(enum odhcp6c_state state, struct odhcp6c_entry *new, uint32_t safe)
467 {
468 size_t len;
469 struct odhcp6c_entry *x = odhcp6c_find_entry(state, new);
470 struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
471 bool changed = true;
472
473 if (x && x->valid > new->valid && new->valid < safe)
474 new->valid = safe;
475
476 if (new->valid > 0) {
477 if (x) {
478 if (new->valid >= x->valid && new->valid - x->valid < 60 &&
479 new->preferred >= x->preferred &&
480 new->preferred - x->preferred < 60 &&
481 x->class == new->class)
482 changed = false;
483 x->valid = new->valid;
484 x->preferred = new->preferred;
485 x->class = new->class;
486 } else {
487 odhcp6c_add_state(state, new, sizeof(*new));
488 }
489 } else if (x) {
490 odhcp6c_remove_state(state, (x - start) * sizeof(*x), sizeof(*x));
491 }
492 return changed;
493 }
494
495
496 bool odhcp6c_update_entry(enum odhcp6c_state state, struct odhcp6c_entry *new)
497 {
498 return odhcp6c_update_entry_safe(state, new, 0);
499 }
500
501
502 static void odhcp6c_expire_list(enum odhcp6c_state state, uint32_t elapsed)
503 {
504 size_t len;
505 struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
506 for (struct odhcp6c_entry *c = start; c < &start[len / sizeof(*c)]; ++c) {
507 if (c->preferred < elapsed)
508 c->preferred = 0;
509 else if (c->preferred != UINT32_MAX)
510 c->preferred -= elapsed;
511
512 if (c->valid < elapsed)
513 c->valid = 0;
514 else if (c->valid != UINT32_MAX)
515 c->valid -= elapsed;
516
517 if (!c->valid)
518 odhcp6c_remove_state(state, (c - start) * sizeof(*c), sizeof(*c));
519 }
520 }
521
522
523 void odhcp6c_expire(void)
524 {
525 time_t now = odhcp6c_get_milli_time() / 1000;
526 uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
527 last_update = now;
528
529 odhcp6c_expire_list(STATE_RA_PREFIX, elapsed);
530 odhcp6c_expire_list(STATE_RA_ROUTE, elapsed);
531 odhcp6c_expire_list(STATE_RA_DNS, elapsed);
532 odhcp6c_expire_list(STATE_IA_NA, elapsed);
533 odhcp6c_expire_list(STATE_IA_PD, elapsed);
534 }
535
536
537 uint32_t odhcp6c_elapsed(void)
538 {
539 return odhcp6c_get_milli_time() / 1000 - last_update;
540 }
541
542
543 void odhcp6c_random(void *buf, size_t len)
544 {
545 read(urandom_fd, buf, len);
546 }
547
548
549 static void sighandler(int signal)
550 {
551 if (signal == SIGCHLD)
552 while (waitpid(-1, NULL, WNOHANG) > 0);
553 else if (signal == SIGUSR1)
554 do_signal = SIGUSR1;
555 else if (signal == SIGUSR2)
556 do_signal = SIGUSR2;
557 else if (signal == SIGIO)
558 do_signal = SIGIO;
559 else
560 do_signal = SIGTERM;
561 }