2 * Copyright (C) 2012-2013 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.
31 #include <sys/syscall.h>
32 #include <arpa/inet.h>
33 #include <linux/if_addr.h>
42 #ifndef IN6_IS_ADDR_UNIQUELOCAL
43 #define IN6_IS_ADDR_UNIQUELOCAL(a) \
44 ((((__const uint32_t *) (a))[0] & htonl (0xfe000000)) \
45 == htonl (0xfc000000))
48 static void sighandler(int signal);
49 static int usage(void);
51 static uint8_t *state_data[_STATE_MAX] = {NULL};
52 static size_t state_len[_STATE_MAX] = {0};
54 static volatile int do_signal = 0;
55 static int urandom_fd = -1, allow_slaac_only = 0;
56 static bool bound = false, release = true;
57 static time_t last_update = 0;
58 static char *ifname = NULL;
60 int main(_unused int argc, char* const argv[])
62 // Allocate ressources
63 const char *pidfile = NULL;
64 const char *script = "/usr/sbin/odhcp6c-update";
69 enum odhcp6c_ia_mode ia_na_mode = IA_MODE_TRY;
70 enum odhcp6c_ia_mode ia_pd_mode = IA_MODE_TRY;
71 static struct in6_addr ifid = IN6ADDR_ANY_INIT;
72 int sol_timeout = 120;
75 int bfd_interval = 0, bfd_loss = 3;
78 bool help = false, daemonize = false;
80 int c, request_pd = 0;
81 while ((c = getopt(argc, argv, "S::N:P:FB:c:i:r:s:kt:hedp:")) != -1) {
84 allow_slaac_only = (optarg) ? atoi(optarg) : -1;
88 if (!strcmp(optarg, "force")) {
89 ia_na_mode = IA_MODE_FORCE;
90 allow_slaac_only = -1;
91 } else if (!strcmp(optarg, "none")) {
92 ia_na_mode = IA_MODE_NONE;
93 } else if (!strcmp(optarg, "try")) {
94 ia_na_mode = IA_MODE_TRY;
101 if (allow_slaac_only >= 0 && allow_slaac_only < 10)
102 allow_slaac_only = 10;
104 request_pd = strtoul(optarg, NULL, 10);
111 allow_slaac_only = -1;
112 ia_pd_mode = IA_MODE_FORCE;
117 bfd_interval = atoi(optarg);
122 l = script_unhexlify(&buf[4], sizeof(buf) - 4, optarg);
125 buf[1] = DHCPV6_OPT_CLIENTID;
128 odhcp6c_add_state(STATE_CLIENT_ID, buf, l + 4);
135 if (inet_pton(AF_INET6, optarg, &ifid) != 1)
142 opttype = htons(strtoul(optarg, &optpos, 10));
143 if (optpos == optarg)
147 odhcp6c_add_state(STATE_ORO, &opttype, 2);
160 sol_timeout = atoi(optarg);
164 logopt |= LOG_PERROR;
181 openlog("odhcp6c", logopt, LOG_DAEMON);
182 ifname = argv[optind];
187 signal(SIGIO, sighandler);
188 signal(SIGHUP, sighandler);
189 signal(SIGINT, sighandler);
190 signal(SIGCHLD, sighandler);
191 signal(SIGTERM, sighandler);
192 signal(SIGUSR1, sighandler);
193 signal(SIGUSR2, sighandler);
195 if ((urandom_fd = open("/dev/urandom", O_CLOEXEC | O_RDONLY)) < 0 ||
196 init_dhcpv6(ifname, request_pd, sol_timeout) ||
197 ra_init(ifname, &ifid) || script_init(script, ifname)) {
198 syslog(LOG_ERR, "failed to initialize: %s", strerror(errno));
203 openlog("odhcp6c", LOG_PID, LOG_DAEMON); // Disable LOG_PERROR
205 syslog(LOG_ERR, "Failed to daemonize: %s",
212 snprintf(pidbuf, sizeof(pidbuf),
213 "/var/run/odhcp6c.%s.pid", ifname);
217 int fd = open(pidfile, O_WRONLY | O_CREAT);
220 int len = snprintf(buf, sizeof(buf), "%i\n", getpid());
226 script_call("started");
228 while (do_signal != SIGTERM) { // Main logic
229 odhcp6c_clear_state(STATE_SERVER_ID);
230 odhcp6c_clear_state(STATE_IA_NA);
231 odhcp6c_clear_state(STATE_IA_PD);
232 odhcp6c_clear_state(STATE_SNTP_IP);
233 odhcp6c_clear_state(STATE_SNTP_FQDN);
234 odhcp6c_clear_state(STATE_SIP_IP);
235 odhcp6c_clear_state(STATE_SIP_FQDN);
236 dhcpv6_set_ia_mode(ia_na_mode, ia_pd_mode);
239 // Server candidates need deep-delete
241 struct dhcpv6_server_cand *cand = odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
242 for (size_t i = 0; i < cand_len / sizeof(*cand); ++i) {
246 odhcp6c_clear_state(STATE_SERVER_CAND);
248 syslog(LOG_NOTICE, "(re)starting transaction on %s", ifname);
251 int res = dhcpv6_request(DHCPV6_MSG_SOLICIT);
252 odhcp6c_signal_process();
255 continue; // Might happen if we got a signal
256 } else if (res == DHCPV6_STATELESS) { // Stateless mode
257 while (do_signal == 0 || do_signal == SIGUSR1) {
260 res = dhcpv6_request(DHCPV6_MSG_INFO_REQ);
261 odhcp6c_signal_process();
262 if (do_signal == SIGUSR1)
267 script_call("informed");
270 syslog(LOG_NOTICE, "entering stateless-mode on %s", ifname);
272 if (dhcpv6_poll_reconfigure() > 0)
273 script_call("informed");
280 if (dhcpv6_request(DHCPV6_MSG_REQUEST) <= 0)
283 odhcp6c_signal_process();
284 script_call("bound");
286 syslog(LOG_NOTICE, "entering stateful-mode on %s", ifname);
288 if (bfd_interval > 0)
289 bfd_start(ifname, bfd_loss, bfd_interval);
292 while (do_signal == 0 || do_signal == SIGUSR1) {
294 // Wait for T1 to expire or until we get a reconfigure
295 int res = dhcpv6_poll_reconfigure();
296 odhcp6c_signal_process();
298 script_call("updated");
302 // Handle signal, if necessary
303 if (do_signal == SIGUSR1)
304 do_signal = 0; // Acknowledged
305 else if (do_signal > 0)
306 break; // Other signal type
308 size_t ia_pd_len, ia_na_len, ia_pd_new, ia_na_new;
309 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
310 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
312 // If we have any IAs, send renew, otherwise request
314 if (ia_pd_len == 0 && ia_na_len == 0)
315 r = dhcpv6_request(DHCPV6_MSG_REQUEST);
317 r = dhcpv6_request(DHCPV6_MSG_RENEW);
318 odhcp6c_signal_process();
319 if (r > 0) { // Renew was succesfull
321 script_call("updated");
322 continue; // Renew was successful
325 odhcp6c_clear_state(STATE_SERVER_ID); // Remove binding
327 // If we have IAs, try rebind otherwise restart
328 res = dhcpv6_request(DHCPV6_MSG_REBIND);
329 odhcp6c_signal_process();
331 odhcp6c_get_state(STATE_IA_PD, &ia_pd_new);
332 odhcp6c_get_state(STATE_IA_NA, &ia_na_new);
333 if (res <= 0 || (ia_pd_new == 0 && ia_pd_len) ||
334 (ia_na_new == 0 && ia_na_len))
335 break; // We lost all our IAs, restart
337 script_call("rebound");
345 size_t ia_pd_len, ia_na_len, server_id_len;
346 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
347 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
348 odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
350 // Add all prefixes to lost prefixes
352 script_call("unbound");
354 if (server_id_len > 0 && (ia_pd_len > 0 || ia_na_len > 0) && release)
355 dhcpv6_request(DHCPV6_MSG_RELEASE);
357 odhcp6c_clear_state(STATE_IA_NA);
358 odhcp6c_clear_state(STATE_IA_PD);
361 script_call("stopped");
366 static int usage(void)
369 "Usage: odhcp6c [options] <interface>\n"
370 "\nFeature options:\n"
371 " -S <time> Wait at least <time> sec for a DHCP-server (0)\n"
372 " -N <mode> Mode for requesting addresses [try|force|none]\n"
373 " -P <length> Request IPv6-Prefix (0 = auto)\n"
374 " -F Force IPv6-Prefix\n"
376 " -B <interval> Enable BFD ping check\n"
378 " -c <clientid> Override client-ID (base-16 encoded)\n"
379 " -i <iface-id> Use a custom interface identifier for RA handling\n"
380 " -r <options> Options to be requested (comma-separated)\n"
381 " -s <script> Status update script (/usr/sbin/odhcp6c-update)\n"
382 " -k Don't send a RELEASE when stopping\n"
383 " -t <seconds> Maximum timeout for DHCPv6-SOLICIT (120)\n"
384 "\nInvocation options:\n"
385 " -p <pidfile> Set pidfile (/var/run/6relayd.pid)\n"
387 " -e Write logmessages to stderr\n"
388 //" -v Increase logging verbosity\n"
389 " -h Show this help\n\n";
390 write(STDERR_FILENO, buf, sizeof(buf));
395 // Don't want to pull-in librt and libpthread just for a monotonic clock...
396 uint64_t odhcp6c_get_milli_time(void)
398 struct timespec t = {0, 0};
399 syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &t);
400 return t.tv_sec * 1000 + t.tv_nsec / 1000000;
404 static uint8_t* odhcp6c_resize_state(enum odhcp6c_state state, ssize_t len)
407 return state_data[state] + state_len[state];
408 else if (state_len[state] + len > 1024)
411 uint8_t *n = realloc(state_data[state], state_len[state] + len);
412 if (n || state_len[state] + len == 0) {
413 state_data[state] = n;
414 n += state_len[state];
415 state_len[state] += len;
421 bool odhcp6c_signal_process(void)
423 if (do_signal == SIGIO) {
425 bool ra_updated = ra_process();
430 if (ra_updated && (bound || allow_slaac_only == 0))
431 script_call("ra-updated"); // Immediate process urgent events
432 else if (ra_updated && !bound && allow_slaac_only > 0)
433 script_delay_call("ra-updated", allow_slaac_only);
440 return do_signal != 0;
444 void odhcp6c_clear_state(enum odhcp6c_state state)
446 state_len[state] = 0;
450 void odhcp6c_add_state(enum odhcp6c_state state, const void *data, size_t len)
452 uint8_t *n = odhcp6c_resize_state(state, len);
454 memcpy(n, data, len);
458 size_t odhcp6c_remove_state(enum odhcp6c_state state, size_t offset, size_t len)
460 uint8_t *data = state_data[state];
461 ssize_t len_after = state_len[state] - (offset + len);
463 return state_len[state];
465 memmove(data + offset, data + offset + len, len_after);
466 return state_len[state] -= len;
470 void* odhcp6c_move_state(enum odhcp6c_state state, size_t *len)
472 *len = state_len[state];
473 void *data = state_data[state];
475 state_len[state] = 0;
476 state_data[state] = NULL;
482 void* odhcp6c_get_state(enum odhcp6c_state state, size_t *len)
484 *len = state_len[state];
485 return state_data[state];
489 struct odhcp6c_entry* odhcp6c_find_entry(enum odhcp6c_state state, const struct odhcp6c_entry *new)
491 size_t len, cmplen = offsetof(struct odhcp6c_entry, target) + new->length / 8;
492 struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
493 struct odhcp6c_entry *x = NULL;
495 for (struct odhcp6c_entry *c = start; !x && c < &start[len/sizeof(*c)]; ++c)
496 if (!memcmp(c, new, cmplen))
503 bool odhcp6c_update_entry_safe(enum odhcp6c_state state, struct odhcp6c_entry *new, uint32_t safe)
506 struct odhcp6c_entry *x = odhcp6c_find_entry(state, new);
507 struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
509 if (x && x->valid > new->valid && new->valid < safe)
512 if (new->valid > 0) {
514 if (new->valid >= x->valid && new->valid - x->valid < 60 &&
515 new->preferred >= x->preferred &&
516 new->preferred - x->preferred < 60 &&
517 x->class == new->class)
519 x->valid = new->valid;
520 x->preferred = new->preferred;
523 x->class = new->class;
525 odhcp6c_add_state(state, new, sizeof(*new));
528 odhcp6c_remove_state(state, (x - start) * sizeof(*x), sizeof(*x));
534 bool odhcp6c_update_entry(enum odhcp6c_state state, struct odhcp6c_entry *new)
536 return odhcp6c_update_entry_safe(state, new, 0);
540 static void odhcp6c_expire_list(enum odhcp6c_state state, uint32_t elapsed)
543 struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
544 for (struct odhcp6c_entry *c = start; c < &start[len / sizeof(*c)]; ++c) {
547 else if (c->t1 != UINT32_MAX)
552 else if (c->t2 != UINT32_MAX)
555 if (c->preferred < elapsed)
557 else if (c->preferred != UINT32_MAX)
558 c->preferred -= elapsed;
560 if (c->valid < elapsed)
562 else if (c->valid != UINT32_MAX)
566 odhcp6c_remove_state(state, (c - start) * sizeof(*c), sizeof(*c));
571 void odhcp6c_expire(void)
573 time_t now = odhcp6c_get_milli_time() / 1000;
574 uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
577 odhcp6c_expire_list(STATE_RA_PREFIX, elapsed);
578 odhcp6c_expire_list(STATE_RA_ROUTE, elapsed);
579 odhcp6c_expire_list(STATE_RA_DNS, elapsed);
580 odhcp6c_expire_list(STATE_IA_NA, elapsed);
581 odhcp6c_expire_list(STATE_IA_PD, elapsed);
585 uint32_t odhcp6c_elapsed(void)
587 return odhcp6c_get_milli_time() / 1000 - last_update;
591 void odhcp6c_random(void *buf, size_t len)
593 read(urandom_fd, buf, len);
597 bool odhcp6c_is_bound(void)
603 bool odhcp6c_addr_in_scope(const struct in6_addr *addr)
605 FILE *fd = fopen("/proc/net/if_inet6", "r");
612 while (fgets(buf, sizeof(buf), fd)) {
613 struct in6_addr inet6_addr;
614 uint32_t flags, dummy;
616 char name[8], addr_buf[32];
620 if ((len <= 0) || buf[len - 1] != '\n')
625 if (sscanf(buf, "%s %x %x %x %x %s",
626 addr_buf, &dummy, &dummy, &dummy, &flags, name) != 6)
629 if (strcmp(name, ifname) ||
630 (flags & (IFA_F_DADFAILED | IFA_F_TENTATIVE | IFA_F_DEPRECATED)))
633 for (i = 0; i < sizeof(addr_buf); i++) {
634 if (!isxdigit(addr_buf[i]) || isupper(addr_buf[i]))
638 memset(&inet6_addr, 0, sizeof(inet6_addr));
639 for (i = 0; i < (sizeof(addr_buf) / 2); i++) {
641 static const char hex[] = "0123456789abcdef";
642 byte = ((index(hex, addr_buf[i * 2]) - hex) << 4) |
643 (index(hex, addr_buf[i * 2 + 1]) - hex);
644 inet6_addr.s6_addr[i] = byte;
647 if ((IN6_IS_ADDR_LINKLOCAL(&inet6_addr) == IN6_IS_ADDR_LINKLOCAL(addr)) &&
648 (IN6_IS_ADDR_UNIQUELOCAL(&inet6_addr) == IN6_IS_ADDR_UNIQUELOCAL(addr)))
654 static void sighandler(int signal)
656 if (signal == SIGCHLD)
657 while (waitpid(-1, NULL, WNOHANG) > 0);
658 else if (signal == SIGUSR1)
660 else if (signal == SIGUSR2)
662 else if (signal == SIGIO)