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