odhcp6c: sync and accumulate RA & DHCPv6 events correctly
[project/odhcp6c.git] / src / odhcp6c.c
1 /**
2 * Copyright (C) 2012-2014 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/syscall.h>
29 #include <arpa/inet.h>
30
31 #include "odhcp6c.h"
32 #include "ra.h"
33
34
35
36 static void sighandler(int signal);
37 static int usage(void);
38
39 static uint8_t *state_data[_STATE_MAX] = {NULL};
40 static size_t state_len[_STATE_MAX] = {0};
41
42 static volatile bool signal_io = false;
43 static volatile bool signal_usr1 = false;
44 static volatile bool signal_usr2 = false;
45 static volatile bool signal_term = false;
46
47 static int urandom_fd = -1, allow_slaac_only = 0;
48 static bool bound = false, release = true, ra = false;
49 static time_t last_update = 0;
50
51 static unsigned int min_update_interval = DEFAULT_MIN_UPDATE_INTERVAL;
52 static unsigned int script_sync_delay = 10;
53 static unsigned int script_accu_delay = 1;
54
55 int main(_unused int argc, char* const argv[])
56 {
57 // Allocate ressources
58 const char *pidfile = NULL;
59 const char *script = "/usr/sbin/odhcp6c-update";
60 ssize_t l;
61 uint8_t buf[134];
62 char *optpos;
63 uint16_t opttype;
64 uint16_t optlen;
65 enum odhcp6c_ia_mode ia_na_mode = IA_MODE_TRY;
66 enum odhcp6c_ia_mode ia_pd_mode = IA_MODE_NONE;
67 int ia_pd_iaid_index = 0;
68 static struct in6_addr ifid = IN6ADDR_ANY_INIT;
69 int sol_timeout = DHCPV6_SOL_MAX_RT;
70 int verbosity = 0;
71
72
73 bool help = false, daemonize = false;
74 int logopt = LOG_PID;
75 int c;
76 unsigned int client_options = DHCPV6_CLIENT_FQDN | DHCPV6_ACCEPT_RECONFIGURE;
77
78 while ((c = getopt(argc, argv, "S::N:V:P:FB:c:i:r:Ru:s:kt:m:hedp:fav")) != -1) {
79 switch (c) {
80 case 'S':
81 allow_slaac_only = (optarg) ? atoi(optarg) : -1;
82 break;
83
84 case 'N':
85 if (!strcmp(optarg, "force")) {
86 ia_na_mode = IA_MODE_FORCE;
87 allow_slaac_only = -1;
88 } else if (!strcmp(optarg, "none")) {
89 ia_na_mode = IA_MODE_NONE;
90 } else if (!strcmp(optarg, "try")) {
91 ia_na_mode = IA_MODE_TRY;
92 } else{
93 help = true;
94 }
95 break;
96
97 case 'V':
98 l = script_unhexlify(buf, sizeof(buf), optarg);
99 if (!l)
100 help=true;
101
102 odhcp6c_add_state(STATE_VENDORCLASS, buf, l);
103
104 break;
105 case 'P':
106 if (ia_pd_mode == IA_MODE_NONE)
107 ia_pd_mode = IA_MODE_TRY;
108
109 if (allow_slaac_only >= 0 && allow_slaac_only < 10)
110 allow_slaac_only = 10;
111
112 char *iaid_begin;
113 int iaid_len = 0;
114
115 int prefix_length = strtoul(optarg, &iaid_begin, 10);
116
117 if (*iaid_begin != '\0' && *iaid_begin != ',' && *iaid_begin != ':') {
118 syslog(LOG_ERR, "invalid argument: '%s'", optarg);
119 return 1;
120 }
121
122 struct odhcp6c_request_prefix prefix = { 0, prefix_length };
123
124 if (*iaid_begin == ',' && (iaid_len = strlen(iaid_begin)) > 1)
125 memcpy(&prefix.iaid, iaid_begin + 1, iaid_len > 4 ? 4 : iaid_len);
126 else if (*iaid_begin == ':')
127 prefix.iaid = htonl((uint32_t)strtoul(&iaid_begin[1], NULL, 16));
128 else
129 prefix.iaid = htonl(++ia_pd_iaid_index);
130
131 odhcp6c_add_state(STATE_IA_PD_INIT, &prefix, sizeof(prefix));
132
133 break;
134
135 case 'F':
136 allow_slaac_only = -1;
137 ia_pd_mode = IA_MODE_FORCE;
138 break;
139
140 case 'c':
141 l = script_unhexlify(&buf[4], sizeof(buf) - 4, optarg);
142 if (l > 0) {
143 buf[0] = 0;
144 buf[1] = DHCPV6_OPT_CLIENTID;
145 buf[2] = 0;
146 buf[3] = l;
147 odhcp6c_add_state(STATE_CLIENT_ID, buf, l + 4);
148 } else {
149 help = true;
150 }
151 break;
152
153 case 'i':
154 if (inet_pton(AF_INET6, optarg, &ifid) != 1)
155 help = true;
156 break;
157
158 case 'r':
159 optpos = optarg;
160 while (optpos[0]) {
161 opttype = htons(strtoul(optarg, &optpos, 10));
162 if (optpos == optarg)
163 break;
164 else if (optpos[0])
165 optarg = &optpos[1];
166 odhcp6c_add_state(STATE_ORO, &opttype, 2);
167 }
168 break;
169
170 case 'R':
171 client_options |= DHCPV6_STRICT_OPTIONS;
172 break;
173
174 case 'u':
175 optlen = htons(strlen(optarg));
176 odhcp6c_add_state(STATE_USERCLASS, &optlen, 2);
177 odhcp6c_add_state(STATE_USERCLASS, optarg, strlen(optarg));
178 break;
179
180 case 's':
181 script = optarg;
182 break;
183
184 case 'k':
185 release = false;
186 break;
187
188 case 't':
189 sol_timeout = atoi(optarg);
190 break;
191
192 case 'm':
193 min_update_interval = atoi(optarg);
194 break;
195
196 case 'e':
197 logopt |= LOG_PERROR;
198 break;
199
200 case 'd':
201 daemonize = true;
202 break;
203
204 case 'p':
205 pidfile = optarg;
206 break;
207
208 case 'f':
209 client_options &= ~DHCPV6_CLIENT_FQDN;
210 break;
211
212 case 'a':
213 client_options &= ~DHCPV6_ACCEPT_RECONFIGURE;
214 break;
215
216 case 'v':
217 ++verbosity;
218 break;
219
220 default:
221 help = true;
222 break;
223 }
224 }
225
226 if (allow_slaac_only > 0)
227 script_sync_delay = allow_slaac_only;
228
229 openlog("odhcp6c", logopt, LOG_DAEMON);
230 if (!verbosity)
231 setlogmask(LOG_UPTO(LOG_WARNING));
232
233 const char *ifname = argv[optind];
234
235 if (help || !ifname)
236 return usage();
237
238 signal(SIGIO, sighandler);
239 signal(SIGHUP, sighandler);
240 signal(SIGINT, sighandler);
241 signal(SIGTERM, sighandler);
242 signal(SIGUSR1, sighandler);
243 signal(SIGUSR2, sighandler);
244
245 if ((urandom_fd = open("/dev/urandom", O_CLOEXEC | O_RDONLY)) < 0 ||
246 init_dhcpv6(ifname, client_options, sol_timeout) ||
247 ra_init(ifname, &ifid) || script_init(script, ifname)) {
248 syslog(LOG_ERR, "failed to initialize: %s", strerror(errno));
249 return 3;
250 }
251
252 if (daemonize) {
253 openlog("odhcp6c", LOG_PID, LOG_DAEMON); // Disable LOG_PERROR
254 if (daemon(0, 0)) {
255 syslog(LOG_ERR, "Failed to daemonize: %s",
256 strerror(errno));
257 return 4;
258 }
259
260 if (!pidfile) {
261 snprintf((char*)buf, sizeof(buf), "/var/run/odhcp6c.%s.pid", ifname);
262 pidfile = (char*)buf;
263 }
264
265 FILE *fp = fopen(pidfile, "w");
266 if (fp) {
267 fprintf(fp, "%i\n", getpid());
268 fclose(fp);
269 }
270 }
271
272 script_call("started", 0, false);
273
274 while (!signal_term) { // Main logic
275 odhcp6c_clear_state(STATE_SERVER_ID);
276 odhcp6c_clear_state(STATE_SERVER_ADDR);
277 odhcp6c_clear_state(STATE_IA_NA);
278 odhcp6c_clear_state(STATE_IA_PD);
279 odhcp6c_clear_state(STATE_SNTP_IP);
280 odhcp6c_clear_state(STATE_NTP_IP);
281 odhcp6c_clear_state(STATE_NTP_FQDN);
282 odhcp6c_clear_state(STATE_SIP_IP);
283 odhcp6c_clear_state(STATE_SIP_FQDN);
284 bound = false;
285
286 syslog(LOG_NOTICE, "(re)starting transaction on %s", ifname);
287
288 signal_usr1 = signal_usr2 = false;
289 int mode = dhcpv6_set_ia_mode(ia_na_mode, ia_pd_mode);
290 if (mode != DHCPV6_STATELESS)
291 mode = dhcpv6_request(DHCPV6_MSG_SOLICIT);
292 odhcp6c_signal_process();
293
294 if (mode < 0)
295 continue;
296
297 do {
298 int res = dhcpv6_request(mode == DHCPV6_STATELESS ?
299 DHCPV6_MSG_INFO_REQ : DHCPV6_MSG_REQUEST);
300 bool signalled = odhcp6c_signal_process();
301
302 if (res > 0)
303 break;
304 else if (signalled) {
305 mode = -1;
306 break;
307 }
308
309 mode = dhcpv6_promote_server_cand();
310 } while (mode > DHCPV6_UNKNOWN);
311
312 if (mode < 0)
313 continue;
314
315 switch (mode) {
316 case DHCPV6_STATELESS:
317 bound = true;
318 syslog(LOG_NOTICE, "entering stateless-mode on %s", ifname);
319
320 while (!signal_usr2 && !signal_term) {
321 signal_usr1 = false;
322 script_call("informed", script_sync_delay, true);
323
324 int res = dhcpv6_poll_reconfigure();
325 odhcp6c_signal_process();
326
327 if (res > 0)
328 continue;
329
330 if (signal_usr1) {
331 signal_usr1 = false; // Acknowledged
332 continue;
333 }
334 if (signal_usr2 || signal_term)
335 break;
336
337 res = dhcpv6_request(DHCPV6_MSG_INFO_REQ);
338 odhcp6c_signal_process();
339 if (signal_usr1)
340 continue;
341 else if (res < 0)
342 break;
343 }
344 break;
345
346 case DHCPV6_STATEFUL:
347 bound = true;
348 script_call("bound", script_sync_delay, true);
349 syslog(LOG_NOTICE, "entering stateful-mode on %s", ifname);
350
351 while (!signal_usr2 && !signal_term) {
352 // Renew Cycle
353 // Wait for T1 to expire or until we get a reconfigure
354 int res = dhcpv6_poll_reconfigure();
355 odhcp6c_signal_process();
356 if (res > 0) {
357 script_call("updated", 0, false);
358 continue;
359 }
360
361 // Handle signal, if necessary
362 if (signal_usr1)
363 signal_usr1 = false; // Acknowledged
364 if (signal_usr2 || signal_term)
365 break; // Other signal type
366
367 // Send renew as T1 expired
368 res = dhcpv6_request(DHCPV6_MSG_RENEW);
369 odhcp6c_signal_process();
370 if (res > 0) { // Renew was succesfull
371 // Publish updates
372 script_call("updated", 0, false);
373 continue; // Renew was successful
374 }
375
376 odhcp6c_clear_state(STATE_SERVER_ID); // Remove binding
377 odhcp6c_clear_state(STATE_SERVER_ADDR);
378
379 size_t ia_pd_len, ia_na_len;
380 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
381 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
382
383 if (ia_pd_len == 0 && ia_na_len == 0)
384 break;
385
386 // If we have IAs, try rebind otherwise restart
387 res = dhcpv6_request(DHCPV6_MSG_REBIND);
388 odhcp6c_signal_process();
389
390 if (res > 0)
391 script_call("rebound", 0, true);
392 else {
393 break;
394 }
395 }
396 break;
397
398 default:
399 break;
400 }
401
402 odhcp6c_expire();
403
404 size_t ia_pd_len, ia_na_len, server_id_len;
405 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
406 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
407 odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
408
409 // Add all prefixes to lost prefixes
410 bound = false;
411 script_call("unbound", 0, true);
412
413 if (server_id_len > 0 && (ia_pd_len > 0 || ia_na_len > 0) && release)
414 dhcpv6_request(DHCPV6_MSG_RELEASE);
415
416 odhcp6c_clear_state(STATE_IA_NA);
417 odhcp6c_clear_state(STATE_IA_PD);
418 }
419
420 script_call("stopped", 0, true);
421 return 0;
422 }
423
424
425 static int usage(void)
426 {
427 const char buf[] =
428 "Usage: odhcp6c [options] <interface>\n"
429 "\nFeature options:\n"
430 " -S <time> Wait at least <time> sec for a DHCP-server (0)\n"
431 " -N <mode> Mode for requesting addresses [try|force|none]\n"
432 " -P <length> Request IPv6-Prefix (0 = auto)\n"
433 " -F Force IPv6-Prefix\n"
434 " -V <class> Set vendor-class option (base-16 encoded)\n"
435 " -u <user-class> Set user-class option string\n"
436 " -c <clientid> Override client-ID (base-16 encoded 16-bit type + value)\n"
437 " -i <iface-id> Use a custom interface identifier for RA handling\n"
438 " -r <options> Options to be requested (comma-separated)\n"
439 " -R Do not request any options except those specified with -r\n"
440 " -s <script> Status update script (/usr/sbin/odhcp6c-update)\n"
441 " -a Don't send Accept Reconfigure option\n"
442 " -f Don't send Client FQDN option\n"
443 " -k Don't send a RELEASE when stopping\n"
444 " -t <seconds> Maximum timeout for DHCPv6-SOLICIT (120)\n"
445 " -m <seconds> Minimum time between accepting updates (30)\n"
446 "\nInvocation options:\n"
447 " -p <pidfile> Set pidfile (/var/run/odhcp6c.pid)\n"
448 " -d Daemonize\n"
449 " -e Write logmessages to stderr\n"
450 " -v Increase logging verbosity\n"
451 " -h Show this help\n\n";
452 fputs(buf, stderr);
453 return 1;
454 }
455
456
457 // Don't want to pull-in librt and libpthread just for a monotonic clock...
458 uint64_t odhcp6c_get_milli_time(void)
459 {
460 struct timespec t = {0, 0};
461 syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &t);
462 return ((uint64_t)t.tv_sec) * 1000 + ((uint64_t)t.tv_nsec) / 1000000;
463 }
464
465
466 static uint8_t* odhcp6c_resize_state(enum odhcp6c_state state, ssize_t len)
467 {
468 if (len == 0)
469 return state_data[state] + state_len[state];
470 else if (state_len[state] + len > 1024)
471 return NULL;
472
473 uint8_t *n = realloc(state_data[state], state_len[state] + len);
474 if (n || state_len[state] + len == 0) {
475 state_data[state] = n;
476 n += state_len[state];
477 state_len[state] += len;
478 }
479 return n;
480 }
481
482
483 bool odhcp6c_signal_process(void)
484 {
485 while (signal_io) {
486 signal_io = false;
487
488 bool ra_updated = ra_process();
489
490 if (ra_link_up()) {
491 signal_usr2 = true;
492 ra = false;
493 }
494
495 if (ra_updated && (bound || allow_slaac_only >= 0)) {
496 script_call("ra-updated", (!ra && !bound) ?
497 script_sync_delay : script_accu_delay, false);
498 ra = true;
499 }
500 }
501
502 return signal_usr1 || signal_usr2 || signal_term;
503 }
504
505
506 void odhcp6c_clear_state(enum odhcp6c_state state)
507 {
508 state_len[state] = 0;
509 }
510
511
512 void odhcp6c_add_state(enum odhcp6c_state state, const void *data, size_t len)
513 {
514 uint8_t *n = odhcp6c_resize_state(state, len);
515 if (n)
516 memcpy(n, data, len);
517 }
518
519 void odhcp6c_insert_state(enum odhcp6c_state state, size_t offset, const void *data, size_t len)
520 {
521 ssize_t len_after = state_len[state] - offset;
522 if (len_after < 0)
523 return;
524
525 uint8_t *n = odhcp6c_resize_state(state, len);
526 if (n) {
527 uint8_t *sdata = state_data[state];
528
529 memmove(sdata + offset + len, sdata + offset, len_after);
530 memcpy(sdata + offset, data, len);
531 }
532 }
533
534 size_t odhcp6c_remove_state(enum odhcp6c_state state, size_t offset, size_t len)
535 {
536 uint8_t *data = state_data[state];
537 ssize_t len_after = state_len[state] - (offset + len);
538 if (len_after < 0)
539 return state_len[state];
540
541 memmove(data + offset, data + offset + len, len_after);
542 return state_len[state] -= len;
543 }
544
545
546 void* odhcp6c_move_state(enum odhcp6c_state state, size_t *len)
547 {
548 *len = state_len[state];
549 void *data = state_data[state];
550
551 state_len[state] = 0;
552 state_data[state] = NULL;
553
554 return data;
555 }
556
557
558 void* odhcp6c_get_state(enum odhcp6c_state state, size_t *len)
559 {
560 *len = state_len[state];
561 return state_data[state];
562 }
563
564
565 static struct odhcp6c_entry* odhcp6c_find_entry(enum odhcp6c_state state, const struct odhcp6c_entry *new)
566 {
567 size_t len, cmplen = offsetof(struct odhcp6c_entry, target) + ((new->length + 7) / 8);
568 uint8_t *start = odhcp6c_get_state(state, &len);
569
570 for (struct odhcp6c_entry *c = (struct odhcp6c_entry*)start;
571 (uint8_t*)c < &start[len] && &c->auxtarget[c->auxlen] <= &start[len];
572 c = (struct odhcp6c_entry*)(&c->auxtarget[c->auxlen]))
573 if (!memcmp(c, new, cmplen) && !memcmp(c->auxtarget, new->auxtarget, new->auxlen))
574 return c;
575
576 return NULL;
577 }
578
579
580 bool odhcp6c_update_entry(enum odhcp6c_state state, struct odhcp6c_entry *new,
581 uint32_t safe, bool filterexcess)
582 {
583 size_t len;
584 struct odhcp6c_entry *x = odhcp6c_find_entry(state, new);
585 uint8_t *start = odhcp6c_get_state(state, &len);
586
587 if (x && x->valid > new->valid && new->valid < safe)
588 new->valid = safe;
589
590 if (new->valid > 0) {
591 if (x) {
592 if (filterexcess && new->valid >= x->valid &&
593 new->valid != UINT32_MAX &&
594 new->valid - x->valid < min_update_interval &&
595 new->preferred >= x->preferred &&
596 new->preferred != UINT32_MAX &&
597 new->preferred - x->preferred < min_update_interval)
598 return false;
599 x->valid = new->valid;
600 x->preferred = new->preferred;
601 x->t1 = new->t1;
602 x->t2 = new->t2;
603 x->iaid = new->iaid;
604 } else {
605 odhcp6c_add_state(state, new, sizeof(*new) + new->auxlen);
606 }
607 } else if (x) {
608 odhcp6c_remove_state(state, ((uint8_t*)x) - start, sizeof(*x) + x->auxlen);
609 }
610 return true;
611 }
612
613
614 static void odhcp6c_expire_list(enum odhcp6c_state state, uint32_t elapsed)
615 {
616 size_t len;
617 uint8_t *start = odhcp6c_get_state(state, &len);
618 for (struct odhcp6c_entry *c = (struct odhcp6c_entry*)start;
619 (uint8_t*)c < &start[len] && &c->auxtarget[c->auxlen] <= &start[len];
620 c = (struct odhcp6c_entry*)(&c->auxtarget[c->auxlen])) {
621 if (c->t1 < elapsed)
622 c->t1 = 0;
623 else if (c->t1 != UINT32_MAX)
624 c->t1 -= elapsed;
625
626 if (c->t2 < elapsed)
627 c->t2 = 0;
628 else if (c->t2 != UINT32_MAX)
629 c->t2 -= elapsed;
630
631 if (c->preferred < elapsed)
632 c->preferred = 0;
633 else if (c->preferred != UINT32_MAX)
634 c->preferred -= elapsed;
635
636 if (c->valid < elapsed)
637 c->valid = 0;
638 else if (c->valid != UINT32_MAX)
639 c->valid -= elapsed;
640
641 if (!c->valid)
642 odhcp6c_remove_state(state, ((uint8_t*)c) - start, sizeof(*c) + c->auxlen);
643 }
644 }
645
646
647 void odhcp6c_expire(void)
648 {
649 time_t now = odhcp6c_get_milli_time() / 1000;
650 uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
651 last_update = now;
652
653 odhcp6c_expire_list(STATE_RA_PREFIX, elapsed);
654 odhcp6c_expire_list(STATE_RA_ROUTE, elapsed);
655 odhcp6c_expire_list(STATE_RA_DNS, elapsed);
656 odhcp6c_expire_list(STATE_RA_SEARCH, elapsed);
657 odhcp6c_expire_list(STATE_IA_NA, elapsed);
658 odhcp6c_expire_list(STATE_IA_PD, elapsed);
659 }
660
661
662 uint32_t odhcp6c_elapsed(void)
663 {
664 return odhcp6c_get_milli_time() / 1000 - last_update;
665 }
666
667
668 int odhcp6c_random(void *buf, size_t len)
669 {
670 return read(urandom_fd, buf, len);
671 }
672
673 bool odhcp6c_is_bound(void)
674 {
675 return bound;
676 }
677
678 static void sighandler(int signal)
679 {
680 if (signal == SIGUSR1)
681 signal_usr1 = true;
682 else if (signal == SIGUSR2)
683 signal_usr2 = true;
684 else if (signal == SIGIO)
685 signal_io = true;
686 else
687 signal_term = true;
688 }