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