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