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