2 * Copyright (C) 2012-2014 Steven Barth <steven@midlink.org>
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.
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.
30 #include <sys/syscall.h>
31 #include <arpa/inet.h>
32 #include <linux/if_addr.h>
38 #ifndef IN6_IS_ADDR_UNIQUELOCAL
39 #define IN6_IS_ADDR_UNIQUELOCAL(a) \
40 ((((__const uint32_t *) (a))[0] & htonl (0xfe000000)) \
41 == htonl (0xfc000000))
44 static void sighandler(int signal);
45 static int usage(void);
47 static uint8_t *state_data[_STATE_MAX] = {NULL};
48 static size_t state_len[_STATE_MAX] = {0};
50 static volatile bool signal_io = false;
51 static volatile bool signal_usr1 = false;
52 static volatile bool signal_usr2 = false;
53 static volatile bool signal_term = false;
55 static int urandom_fd = -1, allow_slaac_only = 0;
56 static bool bound = false, release = true, ra = false;
57 static time_t last_update = 0;
58 static char *ifname = NULL;
60 static unsigned int min_update_interval = DEFAULT_MIN_UPDATE_INTERVAL;
61 static unsigned int script_sync_delay = 10;
62 static unsigned int script_accu_delay = 1;
64 int main(_unused int argc, char* const argv[])
66 // Allocate ressources
67 const char *pidfile = NULL;
68 const char *script = "/usr/sbin/odhcp6c-update";
74 enum odhcp6c_ia_mode ia_na_mode = IA_MODE_TRY;
75 enum odhcp6c_ia_mode ia_pd_mode = IA_MODE_NONE;
76 int ia_pd_iaid_index = 0;
77 static struct in6_addr ifid = IN6ADDR_ANY_INIT;
78 int sol_timeout = DHCPV6_SOL_MAX_RT;
82 bool help = false, daemonize = false;
85 unsigned int client_options = DHCPV6_CLIENT_FQDN | DHCPV6_ACCEPT_RECONFIGURE;
86 unsigned int ra_options = RA_RDNSS_DEFAULT_LIFETIME;
88 while ((c = getopt(argc, argv, "S::N:V:P:FB:c:i:r:Ru:s:kt:m:Lhedp:fav")) != -1) {
91 allow_slaac_only = (optarg) ? atoi(optarg) : -1;
95 if (!strcmp(optarg, "force")) {
96 ia_na_mode = IA_MODE_FORCE;
97 allow_slaac_only = -1;
98 } else if (!strcmp(optarg, "none")) {
99 ia_na_mode = IA_MODE_NONE;
100 } else if (!strcmp(optarg, "try")) {
101 ia_na_mode = IA_MODE_TRY;
108 l = script_unhexlify(buf, sizeof(buf), optarg);
112 odhcp6c_add_state(STATE_VENDORCLASS, buf, l);
116 if (ia_pd_mode == IA_MODE_NONE)
117 ia_pd_mode = IA_MODE_TRY;
119 if (allow_slaac_only >= 0 && allow_slaac_only < 10)
120 allow_slaac_only = 10;
125 int prefix_length = strtoul(optarg, &iaid_begin, 10);
127 if (*iaid_begin != '\0' && *iaid_begin != ',' && *iaid_begin != ':') {
128 syslog(LOG_ERR, "invalid argument: '%s'", optarg);
132 struct odhcp6c_request_prefix prefix = { 0, prefix_length };
134 if (*iaid_begin == ',' && (iaid_len = strlen(iaid_begin)) > 1)
135 memcpy(&prefix.iaid, iaid_begin + 1, iaid_len > 4 ? 4 : iaid_len);
136 else if (*iaid_begin == ':')
137 prefix.iaid = htonl((uint32_t)strtoul(&iaid_begin[1], NULL, 16));
139 prefix.iaid = htonl(++ia_pd_iaid_index);
141 odhcp6c_add_state(STATE_IA_PD_INIT, &prefix, sizeof(prefix));
146 allow_slaac_only = -1;
147 ia_pd_mode = IA_MODE_FORCE;
151 l = script_unhexlify(&buf[4], sizeof(buf) - 4, optarg);
154 buf[1] = DHCPV6_OPT_CLIENTID;
157 odhcp6c_add_state(STATE_CLIENT_ID, buf, l + 4);
164 if (inet_pton(AF_INET6, optarg, &ifid) != 1)
171 opttype = htons(strtoul(optarg, &optpos, 10));
172 if (optpos == optarg)
176 odhcp6c_add_state(STATE_ORO, &opttype, 2);
181 client_options |= DHCPV6_STRICT_OPTIONS;
185 optlen = htons(strlen(optarg));
186 odhcp6c_add_state(STATE_USERCLASS, &optlen, 2);
187 odhcp6c_add_state(STATE_USERCLASS, optarg, strlen(optarg));
199 sol_timeout = atoi(optarg);
203 min_update_interval = atoi(optarg);
207 ra_options &= ~RA_RDNSS_DEFAULT_LIFETIME;
211 logopt |= LOG_PERROR;
223 client_options &= ~DHCPV6_CLIENT_FQDN;
227 client_options &= ~DHCPV6_ACCEPT_RECONFIGURE;
240 if (allow_slaac_only > 0)
241 script_sync_delay = allow_slaac_only;
243 openlog("odhcp6c", logopt, LOG_DAEMON);
245 setlogmask(LOG_UPTO(LOG_WARNING));
247 ifname = argv[optind];
252 signal(SIGIO, sighandler);
253 signal(SIGHUP, sighandler);
254 signal(SIGINT, sighandler);
255 signal(SIGTERM, sighandler);
256 signal(SIGUSR1, sighandler);
257 signal(SIGUSR2, sighandler);
259 if ((urandom_fd = open("/dev/urandom", O_CLOEXEC | O_RDONLY)) < 0 ||
260 init_dhcpv6(ifname, client_options, sol_timeout) ||
261 ra_init(ifname, &ifid, ra_options) ||
262 script_init(script, ifname)) {
263 syslog(LOG_ERR, "failed to initialize: %s", strerror(errno));
268 openlog("odhcp6c", LOG_PID, LOG_DAEMON); // Disable LOG_PERROR
270 syslog(LOG_ERR, "Failed to daemonize: %s",
276 snprintf((char*)buf, sizeof(buf), "/var/run/odhcp6c.%s.pid", ifname);
277 pidfile = (char*)buf;
280 FILE *fp = fopen(pidfile, "w");
282 fprintf(fp, "%i\n", getpid());
287 script_call("started", 0, false);
289 while (!signal_term) { // Main logic
290 odhcp6c_clear_state(STATE_SERVER_ID);
291 odhcp6c_clear_state(STATE_SERVER_ADDR);
292 odhcp6c_clear_state(STATE_IA_NA);
293 odhcp6c_clear_state(STATE_IA_PD);
294 odhcp6c_clear_state(STATE_SNTP_IP);
295 odhcp6c_clear_state(STATE_NTP_IP);
296 odhcp6c_clear_state(STATE_NTP_FQDN);
297 odhcp6c_clear_state(STATE_SIP_IP);
298 odhcp6c_clear_state(STATE_SIP_FQDN);
301 syslog(LOG_NOTICE, "(re)starting transaction on %s", ifname);
303 signal_usr1 = signal_usr2 = false;
304 int mode = dhcpv6_set_ia_mode(ia_na_mode, ia_pd_mode);
305 if (mode != DHCPV6_STATELESS)
306 mode = dhcpv6_request(DHCPV6_MSG_SOLICIT);
307 odhcp6c_signal_process();
313 int res = dhcpv6_request(mode == DHCPV6_STATELESS ?
314 DHCPV6_MSG_INFO_REQ : DHCPV6_MSG_REQUEST);
315 bool signalled = odhcp6c_signal_process();
319 else if (signalled) {
324 mode = dhcpv6_promote_server_cand();
325 } while (mode > DHCPV6_UNKNOWN);
331 case DHCPV6_STATELESS:
333 syslog(LOG_NOTICE, "entering stateless-mode on %s", ifname);
335 while (!signal_usr2 && !signal_term) {
337 script_call("informed", script_sync_delay, true);
339 int res = dhcpv6_poll_reconfigure();
340 odhcp6c_signal_process();
346 signal_usr1 = false; // Acknowledged
349 if (signal_usr2 || signal_term)
352 res = dhcpv6_request(DHCPV6_MSG_INFO_REQ);
353 odhcp6c_signal_process();
361 case DHCPV6_STATEFUL:
363 script_call("bound", script_sync_delay, true);
364 syslog(LOG_NOTICE, "entering stateful-mode on %s", ifname);
366 while (!signal_usr2 && !signal_term) {
368 // Wait for T1 to expire or until we get a reconfigure
369 int res = dhcpv6_poll_reconfigure();
370 odhcp6c_signal_process();
372 script_call("updated", 0, false);
376 // Handle signal, if necessary
378 signal_usr1 = false; // Acknowledged
379 if (signal_usr2 || signal_term)
380 break; // Other signal type
382 // Send renew as T1 expired
383 res = dhcpv6_request(DHCPV6_MSG_RENEW);
384 odhcp6c_signal_process();
385 if (res > 0) { // Renew was succesfull
387 script_call("updated", 0, false);
388 continue; // Renew was successful
391 odhcp6c_clear_state(STATE_SERVER_ID); // Remove binding
392 odhcp6c_clear_state(STATE_SERVER_ADDR);
394 size_t ia_pd_len, ia_na_len;
395 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
396 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
398 if (ia_pd_len == 0 && ia_na_len == 0)
401 // If we have IAs, try rebind otherwise restart
402 res = dhcpv6_request(DHCPV6_MSG_REBIND);
403 odhcp6c_signal_process();
406 script_call("rebound", 0, true);
419 size_t ia_pd_len, ia_na_len, server_id_len;
420 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
421 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
422 odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
424 // Add all prefixes to lost prefixes
426 script_call("unbound", 0, true);
428 if (server_id_len > 0 && (ia_pd_len > 0 || ia_na_len > 0) && release)
429 dhcpv6_request(DHCPV6_MSG_RELEASE);
431 odhcp6c_clear_state(STATE_IA_NA);
432 odhcp6c_clear_state(STATE_IA_PD);
435 script_call("stopped", 0, true);
440 static int usage(void)
443 "Usage: odhcp6c [options] <interface>\n"
444 "\nFeature options:\n"
445 " -S <time> Wait at least <time> sec for a DHCP-server (0)\n"
446 " -N <mode> Mode for requesting addresses [try|force|none]\n"
447 " -P <length> Request IPv6-Prefix (0 = auto)\n"
448 " -F Force IPv6-Prefix\n"
449 " -V <class> Set vendor-class option (base-16 encoded)\n"
450 " -u <user-class> Set user-class option string\n"
451 " -c <clientid> Override client-ID (base-16 encoded 16-bit type + value)\n"
452 " -i <iface-id> Use a custom interface identifier for RA handling\n"
453 " -r <options> Options to be requested (comma-separated)\n"
454 " -R Do not request any options except those specified with -r\n"
455 " -s <script> Status update script (/usr/sbin/odhcp6c-update)\n"
456 " -a Don't send Accept Reconfigure option\n"
457 " -f Don't send Client FQDN option\n"
458 " -k Don't send a RELEASE when stopping\n"
459 " -t <seconds> Maximum timeout for DHCPv6-SOLICIT (120)\n"
460 " -m <seconds> Minimum time between accepting updates (30)\n"
461 " -L Ignore default lifetime for RDNSS records\n"
462 "\nInvocation options:\n"
463 " -p <pidfile> Set pidfile (/var/run/odhcp6c.pid)\n"
465 " -e Write logmessages to stderr\n"
466 " -v Increase logging verbosity\n"
467 " -h Show this help\n\n";
473 // Don't want to pull-in librt and libpthread just for a monotonic clock...
474 uint64_t odhcp6c_get_milli_time(void)
476 struct timespec t = {0, 0};
477 syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &t);
478 return ((uint64_t)t.tv_sec) * 1000 + ((uint64_t)t.tv_nsec) / 1000000;
482 static uint8_t* odhcp6c_resize_state(enum odhcp6c_state state, ssize_t len)
485 return state_data[state] + state_len[state];
486 else if (state_len[state] + len > 1024)
489 uint8_t *n = realloc(state_data[state], state_len[state] + len);
490 if (n || state_len[state] + len == 0) {
491 state_data[state] = n;
492 n += state_len[state];
493 state_len[state] += len;
499 bool odhcp6c_signal_process(void)
504 bool ra_updated = ra_process();
511 if (ra_updated && (bound || allow_slaac_only >= 0)) {
512 script_call("ra-updated", (!ra && !bound) ?
513 script_sync_delay : script_accu_delay, false);
518 return signal_usr1 || signal_usr2 || signal_term;
522 void odhcp6c_clear_state(enum odhcp6c_state state)
524 state_len[state] = 0;
528 void odhcp6c_add_state(enum odhcp6c_state state, const void *data, size_t len)
530 uint8_t *n = odhcp6c_resize_state(state, len);
532 memcpy(n, data, len);
535 int odhcp6c_insert_state(enum odhcp6c_state state, size_t offset, const void *data, size_t len)
537 ssize_t len_after = state_len[state] - offset;
541 uint8_t *n = odhcp6c_resize_state(state, len);
543 uint8_t *sdata = state_data[state];
545 memmove(sdata + offset + len, sdata + offset, len_after);
546 memcpy(sdata + offset, data, len);
552 size_t odhcp6c_remove_state(enum odhcp6c_state state, size_t offset, size_t len)
554 uint8_t *data = state_data[state];
555 ssize_t len_after = state_len[state] - (offset + len);
557 return state_len[state];
559 memmove(data + offset, data + offset + len, len_after);
560 return state_len[state] -= len;
564 void* odhcp6c_move_state(enum odhcp6c_state state, size_t *len)
566 *len = state_len[state];
567 void *data = state_data[state];
569 state_len[state] = 0;
570 state_data[state] = NULL;
576 void* odhcp6c_get_state(enum odhcp6c_state state, size_t *len)
578 *len = state_len[state];
579 return state_data[state];
583 static struct odhcp6c_entry* odhcp6c_find_entry(enum odhcp6c_state state, const struct odhcp6c_entry *new)
585 size_t len, cmplen = offsetof(struct odhcp6c_entry, target) + ((new->length + 7) / 8);
586 uint8_t *start = odhcp6c_get_state(state, &len);
588 for (struct odhcp6c_entry *c = (struct odhcp6c_entry*)start;
589 (uint8_t*)c < &start[len] &&
590 (uint8_t*)odhcp6c_next_entry(c) <= &start[len];
591 c = odhcp6c_next_entry(c))
592 if (!memcmp(c, new, cmplen) && !memcmp(c->auxtarget, new->auxtarget, new->auxlen))
599 bool odhcp6c_update_entry(enum odhcp6c_state state, struct odhcp6c_entry *new,
600 uint32_t safe, bool filterexcess)
603 struct odhcp6c_entry *x = odhcp6c_find_entry(state, new);
604 uint8_t *start = odhcp6c_get_state(state, &len);
606 if (x && x->valid > new->valid && new->valid < safe)
609 if (new->valid > 0) {
611 if (filterexcess && new->valid >= x->valid &&
612 new->valid != UINT32_MAX &&
613 new->valid - x->valid < min_update_interval &&
614 new->preferred >= x->preferred &&
615 new->preferred != UINT32_MAX &&
616 new->preferred - x->preferred < min_update_interval)
618 x->valid = new->valid;
619 x->preferred = new->preferred;
624 odhcp6c_add_state(state, new, odhcp6c_entry_size(new));
627 odhcp6c_remove_state(state, ((uint8_t*)x) - start, odhcp6c_entry_size(x));
633 static void odhcp6c_expire_list(enum odhcp6c_state state, uint32_t elapsed)
636 uint8_t *start = odhcp6c_get_state(state, &len);
637 for (struct odhcp6c_entry *c = (struct odhcp6c_entry*)start;
638 (uint8_t*)c < &start[len] &&
639 (uint8_t*)odhcp6c_next_entry(c) <= &start[len];
643 else if (c->t1 != UINT32_MAX)
648 else if (c->t2 != UINT32_MAX)
651 if (c->preferred < elapsed)
653 else if (c->preferred != UINT32_MAX)
654 c->preferred -= elapsed;
656 if (c->valid < elapsed)
658 else if (c->valid != UINT32_MAX)
662 odhcp6c_remove_state(state, ((uint8_t*)c) - start, odhcp6c_entry_size(c));
663 start = odhcp6c_get_state(state, &len);
665 c = odhcp6c_next_entry(c);
671 void odhcp6c_expire(void)
673 time_t now = odhcp6c_get_milli_time() / 1000;
674 uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
677 odhcp6c_expire_list(STATE_RA_PREFIX, elapsed);
678 odhcp6c_expire_list(STATE_RA_ROUTE, elapsed);
679 odhcp6c_expire_list(STATE_RA_DNS, elapsed);
680 odhcp6c_expire_list(STATE_RA_SEARCH, elapsed);
681 odhcp6c_expire_list(STATE_IA_NA, elapsed);
682 odhcp6c_expire_list(STATE_IA_PD, elapsed);
686 uint32_t odhcp6c_elapsed(void)
688 return odhcp6c_get_milli_time() / 1000 - last_update;
692 int odhcp6c_random(void *buf, size_t len)
694 return read(urandom_fd, buf, len);
697 bool odhcp6c_is_bound(void)
702 bool odhcp6c_addr_in_scope(const struct in6_addr *addr)
704 FILE *fd = fopen("/proc/net/if_inet6", "r");
711 while (fgets(buf, sizeof(buf), fd)) {
712 struct in6_addr inet6_addr;
713 uint32_t flags, dummy;
715 char name[8], addr_buf[32];
719 if ((len <= 0) || buf[len - 1] != '\n')
724 if (sscanf(buf, "%s %x %x %x %x %s",
725 addr_buf, &dummy, &dummy, &dummy, &flags, name) != 6)
728 if (strcmp(name, ifname) ||
729 (flags & (IFA_F_DADFAILED | IFA_F_TENTATIVE | IFA_F_DEPRECATED)))
732 for (i = 0; i < sizeof(addr_buf); i++) {
733 if (!isxdigit(addr_buf[i]) || isupper(addr_buf[i]))
737 memset(&inet6_addr, 0, sizeof(inet6_addr));
738 for (i = 0; i < (sizeof(addr_buf) / 2); i++) {
740 static const char hex[] = "0123456789abcdef";
741 byte = ((index(hex, addr_buf[i * 2]) - hex) << 4) |
742 (index(hex, addr_buf[i * 2 + 1]) - hex);
743 inet6_addr.s6_addr[i] = byte;
746 if ((IN6_IS_ADDR_LINKLOCAL(&inet6_addr) == IN6_IS_ADDR_LINKLOCAL(addr)) &&
747 (IN6_IS_ADDR_UNIQUELOCAL(&inet6_addr) == IN6_IS_ADDR_UNIQUELOCAL(addr)))
753 static void sighandler(int signal)
755 if (signal == SIGUSR1)
757 else if (signal == SIGUSR2)
759 else if (signal == SIGIO)