db6fe2e8c12e84e91b807bfe3ac781d5d6cf2182
[project/odhcp6c.git] / src / odhcp6c.c
1 /**
2 * Copyright (C) 2012-2014 Steven Barth <steven@midlink.org>
3 * Copyright (C) 2017-2018 Hans Dedecker <dedeckeh@gmail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License v2 as published by
7 * the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 */
15
16 #include <time.h>
17 #include <errno.h>
18 #include <ctype.h>
19 #include <fcntl.h>
20 #include <limits.h>
21 #include <resolv.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stddef.h>
25 #include <unistd.h>
26 #include <syslog.h>
27 #include <signal.h>
28 #include <string.h>
29 #include <strings.h>
30 #include <stdbool.h>
31
32 #include <net/if.h>
33 #include <sys/syscall.h>
34 #include <arpa/inet.h>
35 #include <linux/if_addr.h>
36
37 #include "odhcp6c.h"
38 #include "ra.h"
39
40 #ifndef IN6_IS_ADDR_UNIQUELOCAL
41 #define IN6_IS_ADDR_UNIQUELOCAL(a) \
42 ((((__const uint32_t *) (a))[0] & htonl (0xfe000000)) \
43 == htonl (0xfc000000))
44 #endif
45 #define ARRAY_SEP " ,\t"
46
47 static void sighandler(int signal);
48 static int usage(void);
49 static int add_opt(const uint16_t code, const uint8_t *data,
50 const uint16_t len);
51 static int parse_opt_data(const char *data, uint8_t **dst,
52 const unsigned int type, const bool array);
53 static int parse_opt(const char *opt);
54
55 static uint8_t *state_data[_STATE_MAX] = {NULL};
56 static size_t state_len[_STATE_MAX] = {0};
57
58 static volatile bool signal_io = false;
59 static volatile bool signal_usr1 = false;
60 static volatile bool signal_usr2 = false;
61 static volatile bool signal_term = false;
62
63 static int urandom_fd = -1, allow_slaac_only = 0;
64 static bool bound = false, release = true, ra = false;
65 static time_t last_update = 0;
66 static char *ifname = NULL;
67
68 static unsigned int script_sync_delay = 10;
69 static unsigned int script_accu_delay = 1;
70
71 static struct odhcp6c_opt opts[] = {
72 { .code = DHCPV6_OPT_CLIENTID, .flags = OPT_INTERNAL, .str = NULL },
73 { .code = DHCPV6_OPT_SERVERID, .flags = OPT_INTERNAL, .str = NULL },
74 { .code = DHCPV6_OPT_IA_NA, .flags = OPT_INTERNAL, .str= NULL },
75 { .code = DHCPV6_OPT_IA_TA, .flags = OPT_INTERNAL, .str = NULL },
76 { .code = DHCPV6_OPT_IA_ADDR, .flags = OPT_INTERNAL, .str = NULL },
77 { .code = DHCPV6_OPT_ORO, .flags = OPT_INTERNAL, .str = NULL },
78 { .code = DHCPV6_OPT_PREF, .flags = OPT_INTERNAL, .str = NULL },
79 { .code = DHCPV6_OPT_ELAPSED, .flags = OPT_INTERNAL, .str = NULL },
80 { .code = DHCPV6_OPT_RELAY_MSG, .flags = OPT_INTERNAL, .str = NULL },
81 { .code = DHCPV6_OPT_AUTH, .flags = OPT_U8, .str = "authentication" },
82 { .code = DHCPV6_OPT_UNICAST, .flags = OPT_INTERNAL, .str = NULL },
83 { .code = DHCPV6_OPT_STATUS, .flags = OPT_INTERNAL, .str = NULL },
84 { .code = DHCPV6_OPT_RAPID_COMMIT, .flags = OPT_INTERNAL, .str = NULL },
85 { .code = DHCPV6_OPT_USER_CLASS, .flags = OPT_USER_CLASS | OPT_ARRAY, .str = "userclass" },
86 { .code = DHCPV6_OPT_VENDOR_CLASS, .flags = OPT_U8, .str = "vendorclass" },
87 { .code = DHCPV6_OPT_INTERFACE_ID, .flags = OPT_INTERNAL, .str = NULL },
88 { .code = DHCPV6_OPT_RECONF_MESSAGE, .flags = OPT_INTERNAL, .str = NULL },
89 { .code = DHCPV6_OPT_RECONF_ACCEPT, .flags = OPT_INTERNAL, .str = NULL },
90 { .code = DHCPV6_OPT_RECONF_ACCEPT, .flags = OPT_INTERNAL, .str = NULL },
91 { .code = DHCPV6_OPT_DNS_SERVERS, .flags = OPT_IP6 | OPT_ARRAY, .str = "dns" },
92 { .code = DHCPV6_OPT_DNS_DOMAIN, .flags = OPT_DNS_STR, .str = "search" },
93 { .code = DHCPV6_OPT_IA_PD, .flags = OPT_INTERNAL, .str = NULL },
94 { .code = DHCPV6_OPT_IA_PREFIX, .flags = OPT_INTERNAL, .str = NULL },
95 { .code = DHCPV6_OPT_SNTP_SERVERS, .flags = OPT_IP6 | OPT_ARRAY, .str = "sntpservers" },
96 { .code = DHCPV6_OPT_INFO_REFRESH, .flags = OPT_INTERNAL, .str = NULL },
97 { .code = DHCPV6_OPT_NTP_SERVER, .flags = OPT_U8, .str = "ntpserver" },
98 { .code = DHCPV6_OPT_SIP_SERVER_D, .flags = OPT_DNS_STR, .str = "sipserver_d" },
99 { .code = DHCPV6_OPT_SIP_SERVER_A, .flags = OPT_IP6 | OPT_ARRAY, .str = "sipserver_a" },
100 { .code = DHCPV6_OPT_AFTR_NAME, .flags = OPT_INTERNAL, .str = NULL },
101 { .code = DHCPV6_OPT_PD_EXCLUDE, .flags = OPT_INTERNAL, .str = NULL },
102 { .code = DHCPV6_OPT_SOL_MAX_RT, .flags = OPT_INTERNAL, .str = NULL },
103 { .code = DHCPV6_OPT_INF_MAX_RT, .flags = OPT_INTERNAL, .str = NULL },
104 #ifdef EXT_CER_ID
105 { .code = DHCPV6_OPT_CER_ID, .flags = OPT_INTERNAL, .str = NULL },
106 #endif
107 { .code = DHCPV6_OPT_S46_RULE, .flags = OPT_INTERNAL, .str = NULL },
108 { .code = DHCPV6_OPT_S46_BR, .flags = OPT_INTERNAL, .str = NULL },
109 { .code = DHCPV6_OPT_S46_DMR, .flags = OPT_INTERNAL, .str = NULL },
110 { .code = DHCPV6_OPT_S46_V4V6BIND, .flags = OPT_INTERNAL, .str = NULL },
111 { .code = DHCPV6_OPT_S46_PORTPARAMS, .flags = OPT_INTERNAL, .str = NULL },
112 { .code = DHCPV6_OPT_S46_CONT_MAPE, .flags = OPT_INTERNAL, .str = NULL },
113 { .code = DHCPV6_OPT_S46_CONT_MAPT, .flags = OPT_INTERNAL, .str = NULL },
114 { .code = DHCPV6_OPT_S46_CONT_LW, .flags = OPT_INTERNAL, .str = NULL },
115 { .code = 0, .flags = 0, .str = NULL },
116 };
117
118 int main(_unused int argc, char* const argv[])
119 {
120 static struct in6_addr ifid = IN6ADDR_ANY_INIT;
121 // Allocate resources
122 const char *pidfile = NULL;
123 const char *script = "/usr/sbin/odhcp6c-update";
124 ssize_t l;
125 uint8_t buf[134];
126 char *optpos;
127 uint16_t opttype;
128 uint16_t optlen;
129 enum odhcp6c_ia_mode ia_na_mode = IA_MODE_TRY;
130 enum odhcp6c_ia_mode ia_pd_mode = IA_MODE_NONE;
131 int ia_pd_iaid_index = 0;
132 int sol_timeout = DHCPV6_SOL_MAX_RT;
133 int verbosity = 0;
134 bool help = false, daemonize = false;
135 int logopt = LOG_PID;
136 int c, res;
137 unsigned int client_options = DHCPV6_CLIENT_FQDN | DHCPV6_ACCEPT_RECONFIGURE;
138 unsigned int ra_options = RA_RDNSS_DEFAULT_LIFETIME;
139 unsigned int ra_holdoff_interval = RA_MIN_ADV_INTERVAL;
140
141 while ((c = getopt(argc, argv, "S::N:V:P:FB:c:i:r:Ru:x:s:kt:m:Lhedp:fav")) != -1) {
142 switch (c) {
143 case 'S':
144 allow_slaac_only = (optarg) ? atoi(optarg) : -1;
145 break;
146
147 case 'N':
148 if (!strcmp(optarg, "force")) {
149 ia_na_mode = IA_MODE_FORCE;
150 allow_slaac_only = -1;
151 } else if (!strcmp(optarg, "none"))
152 ia_na_mode = IA_MODE_NONE;
153 else if (!strcmp(optarg, "try"))
154 ia_na_mode = IA_MODE_TRY;
155 else
156 help = true;
157 break;
158
159 case 'V':
160 l = script_unhexlify(buf, sizeof(buf), optarg);
161 if (l) {
162 if (odhcp6c_add_state(STATE_VENDORCLASS, buf, l)) {
163 syslog(LOG_ERR, "Failed to set vendor-class option");
164 return 1;
165 }
166 } else
167 help = true;
168 break;
169
170 case 'P':
171 if (ia_pd_mode == IA_MODE_NONE)
172 ia_pd_mode = IA_MODE_TRY;
173
174 if (allow_slaac_only >= 0 && allow_slaac_only < 10)
175 allow_slaac_only = 10;
176
177 char *iaid_begin;
178 int iaid_len = 0;
179 int prefix_length = strtoul(optarg, &iaid_begin, 10);
180
181 if (*iaid_begin != '\0' && *iaid_begin != ',' && *iaid_begin != ':') {
182 syslog(LOG_ERR, "invalid argument: '%s'", optarg);
183 return 1;
184 }
185
186 struct odhcp6c_request_prefix prefix = { 0, prefix_length };
187
188 if (*iaid_begin == ',' && (iaid_len = strlen(iaid_begin)) > 1)
189 memcpy(&prefix.iaid, iaid_begin + 1, iaid_len > 4 ? 4 : iaid_len);
190 else if (*iaid_begin == ':')
191 prefix.iaid = htonl((uint32_t)strtoul(&iaid_begin[1], NULL, 16));
192 else
193 prefix.iaid = htonl(++ia_pd_iaid_index);
194
195 if (odhcp6c_add_state(STATE_IA_PD_INIT, &prefix, sizeof(prefix))) {
196 syslog(LOG_ERR, "Failed to set request IPv6-Prefix");
197 return 1;
198 }
199 break;
200
201 case 'F':
202 allow_slaac_only = -1;
203 ia_pd_mode = IA_MODE_FORCE;
204 break;
205
206 case 'c':
207 l = script_unhexlify(&buf[4], sizeof(buf) - 4, optarg);
208 if (l > 0) {
209 buf[0] = 0;
210 buf[1] = DHCPV6_OPT_CLIENTID;
211 buf[2] = 0;
212 buf[3] = l;
213 if (odhcp6c_add_state(STATE_CLIENT_ID, buf, l + 4)) {
214 syslog(LOG_ERR, "Failed to override client-ID");
215 return 1;
216 }
217 } else
218 help = true;
219 break;
220
221 case 'i':
222 if (inet_pton(AF_INET6, optarg, &ifid) != 1)
223 help = true;
224 break;
225
226 case 'r':
227 optpos = optarg;
228 while (optpos[0]) {
229 opttype = htons(strtoul(optarg, &optpos, 10));
230 if (optpos == optarg)
231 break;
232 else if (optpos[0])
233 optarg = &optpos[1];
234
235 if (odhcp6c_add_state(STATE_ORO, &opttype, 2)) {
236 syslog(LOG_ERR, "Failed to add requested option");
237 return 1;
238 }
239 }
240 break;
241
242 case 'R':
243 client_options |= DHCPV6_STRICT_OPTIONS;
244 break;
245
246 case 'u':
247 optlen = htons(strlen(optarg));
248 if (odhcp6c_add_state(STATE_USERCLASS, &optlen, 2) ||
249 odhcp6c_add_state(STATE_USERCLASS, optarg, strlen(optarg))) {
250 syslog(LOG_ERR, "Failed to set user-class option");
251 return 1;
252 }
253 break;
254
255 case 's':
256 script = optarg;
257 break;
258
259 case 'k':
260 release = false;
261 break;
262
263 case 't':
264 sol_timeout = atoi(optarg);
265 break;
266
267 case 'm':
268 ra_holdoff_interval = atoi(optarg);
269 break;
270
271 case 'L':
272 ra_options &= ~RA_RDNSS_DEFAULT_LIFETIME;
273 break;
274
275 case 'e':
276 logopt |= LOG_PERROR;
277 break;
278
279 case 'd':
280 daemonize = true;
281 break;
282
283 case 'p':
284 pidfile = optarg;
285 break;
286
287 case 'f':
288 client_options &= ~DHCPV6_CLIENT_FQDN;
289 break;
290
291 case 'a':
292 client_options &= ~DHCPV6_ACCEPT_RECONFIGURE;
293 break;
294
295 case 'v':
296 ++verbosity;
297 break;
298
299 case 'x':
300 res = parse_opt(optarg);
301 if (res) {
302 if (res > 0)
303 return res;
304
305 help = true;
306 }
307 break;
308
309 default:
310 help = true;
311 break;
312 }
313 }
314
315 if (allow_slaac_only > 0)
316 script_sync_delay = allow_slaac_only;
317
318 openlog("odhcp6c", logopt, LOG_DAEMON);
319 if (!verbosity)
320 setlogmask(LOG_UPTO(LOG_WARNING));
321
322 ifname = argv[optind];
323
324 if (help || !ifname)
325 return usage();
326
327 signal(SIGIO, sighandler);
328 signal(SIGHUP, sighandler);
329 signal(SIGINT, sighandler);
330 signal(SIGTERM, sighandler);
331 signal(SIGUSR1, sighandler);
332 signal(SIGUSR2, sighandler);
333
334 if ((urandom_fd = open("/dev/urandom", O_CLOEXEC | O_RDONLY)) < 0 ||
335 init_dhcpv6(ifname, client_options, sol_timeout) ||
336 ra_init(ifname, &ifid, ra_options, ra_holdoff_interval) ||
337 script_init(script, ifname)) {
338 syslog(LOG_ERR, "failed to initialize: %s", strerror(errno));
339 return 3;
340 }
341
342 if (daemonize) {
343 openlog("odhcp6c", LOG_PID, LOG_DAEMON); // Disable LOG_PERROR
344 if (daemon(0, 0)) {
345 syslog(LOG_ERR, "Failed to daemonize: %s",
346 strerror(errno));
347 return 4;
348 }
349
350 if (!pidfile) {
351 snprintf((char*)buf, sizeof(buf), "/var/run/odhcp6c.%s.pid", ifname);
352 pidfile = (char*)buf;
353 }
354
355 FILE *fp = fopen(pidfile, "w");
356 if (fp) {
357 fprintf(fp, "%i\n", getpid());
358 fclose(fp);
359 }
360 }
361
362 script_call("started", 0, false);
363
364 while (!signal_term) { // Main logic
365 odhcp6c_clear_state(STATE_SERVER_ID);
366 odhcp6c_clear_state(STATE_SERVER_ADDR);
367 odhcp6c_clear_state(STATE_IA_NA);
368 odhcp6c_clear_state(STATE_IA_PD);
369 odhcp6c_clear_state(STATE_SNTP_IP);
370 odhcp6c_clear_state(STATE_NTP_IP);
371 odhcp6c_clear_state(STATE_NTP_FQDN);
372 odhcp6c_clear_state(STATE_SIP_IP);
373 odhcp6c_clear_state(STATE_SIP_FQDN);
374 bound = false;
375
376 syslog(LOG_NOTICE, "(re)starting transaction on %s", ifname);
377
378 signal_usr1 = signal_usr2 = false;
379 int mode = dhcpv6_set_ia_mode(ia_na_mode, ia_pd_mode);
380 if (mode != DHCPV6_STATELESS)
381 mode = dhcpv6_request(DHCPV6_MSG_SOLICIT);
382
383 odhcp6c_signal_process();
384
385 if (mode < 0)
386 continue;
387
388 do {
389 res = dhcpv6_request(mode == DHCPV6_STATELESS ?
390 DHCPV6_MSG_INFO_REQ : DHCPV6_MSG_REQUEST);
391 bool signalled = odhcp6c_signal_process();
392
393 if (res > 0)
394 break;
395 else if (signalled) {
396 mode = -1;
397 break;
398 }
399
400 mode = dhcpv6_promote_server_cand();
401 } while (mode > DHCPV6_UNKNOWN);
402
403 if (mode < 0)
404 continue;
405
406 switch (mode) {
407 case DHCPV6_STATELESS:
408 bound = true;
409 syslog(LOG_NOTICE, "entering stateless-mode on %s", ifname);
410
411 while (!signal_usr2 && !signal_term) {
412 signal_usr1 = false;
413 script_call("informed", script_sync_delay, true);
414
415 res = dhcpv6_poll_reconfigure();
416 odhcp6c_signal_process();
417
418 if (res > 0)
419 continue;
420
421 if (signal_usr1) {
422 signal_usr1 = false; // Acknowledged
423 continue;
424 }
425
426 if (signal_usr2 || signal_term)
427 break;
428
429 res = dhcpv6_request(DHCPV6_MSG_INFO_REQ);
430 odhcp6c_signal_process();
431
432 if (signal_usr1)
433 continue;
434 else if (res < 0)
435 break;
436 }
437 break;
438
439 case DHCPV6_STATEFUL:
440 bound = true;
441 script_call("bound", script_sync_delay, true);
442 syslog(LOG_NOTICE, "entering stateful-mode on %s", ifname);
443
444 while (!signal_usr2 && !signal_term) {
445 // Renew Cycle
446 // Wait for T1 to expire or until we get a reconfigure
447 res = dhcpv6_poll_reconfigure();
448 odhcp6c_signal_process();
449 if (res > 0) {
450 script_call("updated", 0, false);
451 continue;
452 }
453
454 // Handle signal, if necessary
455 if (signal_usr1)
456 signal_usr1 = false; // Acknowledged
457
458 if (signal_usr2 || signal_term)
459 break; // Other signal type
460
461 // Send renew as T1 expired
462 res = dhcpv6_request(DHCPV6_MSG_RENEW);
463 odhcp6c_signal_process();
464
465 if (res > 0) { // Renew was succesfull
466 // Publish updates
467 script_call("updated", 0, false);
468 continue; // Renew was successful
469 }
470
471 odhcp6c_clear_state(STATE_SERVER_ID); // Remove binding
472 odhcp6c_clear_state(STATE_SERVER_ADDR);
473
474 size_t ia_pd_len, ia_na_len;
475 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
476 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
477
478 if (ia_pd_len == 0 && ia_na_len == 0)
479 break;
480
481 // If we have IAs, try rebind otherwise restart
482 res = dhcpv6_request(DHCPV6_MSG_REBIND);
483 odhcp6c_signal_process();
484
485 if (res > 0)
486 script_call("rebound", 0, true);
487 else
488 break;
489 }
490 break;
491
492 default:
493 break;
494 }
495
496 odhcp6c_expire();
497
498 size_t ia_pd_len, ia_na_len, server_id_len;
499 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
500 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
501 odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
502
503 // Add all prefixes to lost prefixes
504 bound = false;
505 script_call("unbound", 0, true);
506
507 if (server_id_len > 0 && (ia_pd_len > 0 || ia_na_len > 0) && release)
508 dhcpv6_request(DHCPV6_MSG_RELEASE);
509
510 odhcp6c_clear_state(STATE_IA_NA);
511 odhcp6c_clear_state(STATE_IA_PD);
512 }
513
514 script_call("stopped", 0, true);
515
516 return 0;
517 }
518
519 static int usage(void)
520 {
521 const char buf[] =
522 "Usage: odhcp6c [options] <interface>\n"
523 "\nFeature options:\n"
524 " -S <time> Wait at least <time> sec for a DHCP-server (0)\n"
525 " -N <mode> Mode for requesting addresses [try|force|none]\n"
526 " -P <length> Request IPv6-Prefix (0 = auto)\n"
527 " -F Force IPv6-Prefix\n"
528 " -V <class> Set vendor-class option (base-16 encoded)\n"
529 " -u <user-class> Set user-class option string\n"
530 " -x <opt>:<val> Add option opt (with value val) in sent packets (cumulative)\n"
531 " Examples of IPv6 address, string and base-16 encoded options:\n"
532 " -x dns:2001:2001::1,2001:2001::2 - option 23\n"
533 " -x 15:office - option 15 (userclass)\n"
534 " -x 0x1f4:ABBA - option 500\n"
535 " -c <clientid> Override client-ID (base-16 encoded 16-bit type + value)\n"
536 " -i <iface-id> Use a custom interface identifier for RA handling\n"
537 " -r <options> Options to be requested (comma-separated)\n"
538 " -R Do not request any options except those specified with -r\n"
539 " -s <script> Status update script (/usr/sbin/odhcp6c-update)\n"
540 " -a Don't send Accept Reconfigure option\n"
541 " -f Don't send Client FQDN option\n"
542 " -k Don't send a RELEASE when stopping\n"
543 " -t <seconds> Maximum timeout for DHCPv6-SOLICIT (120)\n"
544 " -m <seconds> Minimum time between accepting RA updates (3)\n"
545 " -L Ignore default lifetime for RDNSS records\n"
546 "\nInvocation options:\n"
547 " -p <pidfile> Set pidfile (/var/run/odhcp6c.pid)\n"
548 " -d Daemonize\n"
549 " -e Write logmessages to stderr\n"
550 " -v Increase logging verbosity\n"
551 " -h Show this help\n\n";
552 fputs(buf, stderr);
553
554 return 1;
555 }
556
557 // Don't want to pull-in librt and libpthread just for a monotonic clock...
558 uint64_t odhcp6c_get_milli_time(void)
559 {
560 struct timespec t = {0, 0};
561 syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &t);
562
563 return ((uint64_t)t.tv_sec) * 1000 + ((uint64_t)t.tv_nsec) / 1000000;
564 }
565
566 static uint8_t* odhcp6c_resize_state(enum odhcp6c_state state, ssize_t len)
567 {
568 if (len == 0)
569 return state_data[state] + state_len[state];
570 else if (state_len[state] + len > 1024)
571 return NULL;
572
573 uint8_t *n = realloc(state_data[state], state_len[state] + len);
574
575 if (n || state_len[state] + len == 0) {
576 state_data[state] = n;
577 n += state_len[state];
578 state_len[state] += len;
579 }
580
581 return n;
582 }
583
584 bool odhcp6c_signal_process(void)
585 {
586 while (signal_io) {
587 signal_io = false;
588
589 bool ra_updated = ra_process();
590
591 if (ra_link_up()) {
592 signal_usr2 = true;
593 ra = false;
594 }
595
596 if (ra_updated && (bound || allow_slaac_only >= 0)) {
597 script_call("ra-updated", (!ra && !bound) ?
598 script_sync_delay : script_accu_delay, false);
599 ra = true;
600 }
601 }
602
603 return signal_usr1 || signal_usr2 || signal_term;
604 }
605
606 void odhcp6c_clear_state(enum odhcp6c_state state)
607 {
608 state_len[state] = 0;
609 }
610
611 int odhcp6c_add_state(enum odhcp6c_state state, const void *data, size_t len)
612 {
613 uint8_t *n = odhcp6c_resize_state(state, len);
614
615 if (!n)
616 return -1;
617
618 memcpy(n, data, len);
619
620 return 0;
621 }
622
623 int odhcp6c_insert_state(enum odhcp6c_state state, size_t offset, const void *data, size_t len)
624 {
625 ssize_t len_after = state_len[state] - offset;
626 if (len_after < 0)
627 return -1;
628
629 uint8_t *n = odhcp6c_resize_state(state, len);
630
631 if (n) {
632 uint8_t *sdata = state_data[state];
633
634 memmove(sdata + offset + len, sdata + offset, len_after);
635 memcpy(sdata + offset, data, len);
636 }
637
638 return 0;
639 }
640
641 size_t odhcp6c_remove_state(enum odhcp6c_state state, size_t offset, size_t len)
642 {
643 uint8_t *data = state_data[state];
644 ssize_t len_after = state_len[state] - (offset + len);
645
646 if (len_after < 0)
647 return state_len[state];
648
649 memmove(data + offset, data + offset + len, len_after);
650
651 return state_len[state] -= len;
652 }
653
654 void* odhcp6c_move_state(enum odhcp6c_state state, size_t *len)
655 {
656 *len = state_len[state];
657 void *data = state_data[state];
658
659 state_len[state] = 0;
660 state_data[state] = NULL;
661
662 return data;
663 }
664
665 void* odhcp6c_get_state(enum odhcp6c_state state, size_t *len)
666 {
667 *len = state_len[state];
668
669 return state_data[state];
670 }
671
672 static struct odhcp6c_entry* odhcp6c_find_entry(enum odhcp6c_state state, const struct odhcp6c_entry *new)
673 {
674 size_t len, cmplen = offsetof(struct odhcp6c_entry, target) + ((new->length + 7) / 8);
675 uint8_t *start = odhcp6c_get_state(state, &len);
676
677 for (struct odhcp6c_entry *c = (struct odhcp6c_entry*)start;
678 (uint8_t*)c < &start[len] &&
679 (uint8_t*)odhcp6c_next_entry(c) <= &start[len];
680 c = odhcp6c_next_entry(c)) {
681 if (!memcmp(c, new, cmplen) && !memcmp(c->auxtarget, new->auxtarget, new->auxlen))
682 return c;
683 }
684
685 return NULL;
686 }
687
688 bool odhcp6c_update_entry(enum odhcp6c_state state, struct odhcp6c_entry *new,
689 uint32_t safe, unsigned int holdoff_interval)
690 {
691 size_t len;
692 struct odhcp6c_entry *x = odhcp6c_find_entry(state, new);
693 uint8_t *start = odhcp6c_get_state(state, &len);
694
695 if (x && x->valid > new->valid && new->valid < safe)
696 new->valid = safe;
697
698 if (new->valid > 0) {
699 if (x) {
700 if (holdoff_interval && new->valid >= x->valid &&
701 new->valid != UINT32_MAX &&
702 new->valid - x->valid < holdoff_interval &&
703 new->preferred >= x->preferred &&
704 new->preferred != UINT32_MAX &&
705 new->preferred - x->preferred < holdoff_interval)
706 return false;
707
708 x->valid = new->valid;
709 x->preferred = new->preferred;
710 x->t1 = new->t1;
711 x->t2 = new->t2;
712 x->iaid = new->iaid;
713 } else if (odhcp6c_add_state(state, new, odhcp6c_entry_size(new)))
714 return false;
715 } else if (x)
716 odhcp6c_remove_state(state, ((uint8_t*)x) - start, odhcp6c_entry_size(x));
717
718 return true;
719 }
720
721 static void odhcp6c_expire_list(enum odhcp6c_state state, uint32_t elapsed)
722 {
723 size_t len;
724 uint8_t *start = odhcp6c_get_state(state, &len);
725
726 for (struct odhcp6c_entry *c = (struct odhcp6c_entry*)start;
727 (uint8_t*)c < &start[len] &&
728 (uint8_t*)odhcp6c_next_entry(c) <= &start[len];
729 ) {
730 if (c->t1 < elapsed)
731 c->t1 = 0;
732 else if (c->t1 != UINT32_MAX)
733 c->t1 -= elapsed;
734
735 if (c->t2 < elapsed)
736 c->t2 = 0;
737 else if (c->t2 != UINT32_MAX)
738 c->t2 -= elapsed;
739
740 if (c->preferred < elapsed)
741 c->preferred = 0;
742 else if (c->preferred != UINT32_MAX)
743 c->preferred -= elapsed;
744
745 if (c->valid < elapsed)
746 c->valid = 0;
747 else if (c->valid != UINT32_MAX)
748 c->valid -= elapsed;
749
750 if (!c->valid) {
751 odhcp6c_remove_state(state, ((uint8_t*)c) - start, odhcp6c_entry_size(c));
752 start = odhcp6c_get_state(state, &len);
753 } else
754 c = odhcp6c_next_entry(c);
755 }
756 }
757
758 static uint8_t *odhcp6c_state_find_opt(const uint16_t code)
759 {
760 size_t opts_len;
761 uint8_t *odata, *opts = odhcp6c_get_state(STATE_OPTS, &opts_len);
762 uint16_t otype, olen;
763
764 dhcpv6_for_each_option(opts, &opts[opts_len], otype, olen, odata) {
765 if (otype == code)
766 return &odata[-4];
767 }
768
769 return NULL;
770 }
771
772 void odhcp6c_expire(void)
773 {
774 time_t now = odhcp6c_get_milli_time() / 1000;
775 uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
776
777 last_update = now;
778
779 odhcp6c_expire_list(STATE_RA_PREFIX, elapsed);
780 odhcp6c_expire_list(STATE_RA_ROUTE, elapsed);
781 odhcp6c_expire_list(STATE_RA_DNS, elapsed);
782 odhcp6c_expire_list(STATE_RA_SEARCH, elapsed);
783 odhcp6c_expire_list(STATE_IA_NA, elapsed);
784 odhcp6c_expire_list(STATE_IA_PD, elapsed);
785 }
786
787 uint32_t odhcp6c_elapsed(void)
788 {
789 return odhcp6c_get_milli_time() / 1000 - last_update;
790 }
791
792 int odhcp6c_random(void *buf, size_t len)
793 {
794 return read(urandom_fd, buf, len);
795 }
796
797 bool odhcp6c_is_bound(void)
798 {
799 return bound;
800 }
801
802 bool odhcp6c_addr_in_scope(const struct in6_addr *addr)
803 {
804 FILE *fd = fopen("/proc/net/if_inet6", "r");
805 int len;
806 char buf[256];
807
808 if (fd == NULL)
809 return false;
810
811 while (fgets(buf, sizeof(buf), fd)) {
812 struct in6_addr inet6_addr;
813 uint32_t flags, dummy;
814 unsigned int i;
815 char name[IF_NAMESIZE], addr_buf[33];
816
817 len = strlen(buf);
818
819 if ((len <= 0) || buf[len - 1] != '\n')
820 return false;
821
822 buf[--len] = '\0';
823
824 if (sscanf(buf, "%s %x %x %x %x %s",
825 addr_buf, &dummy, &dummy, &dummy, &flags, name) != 6)
826 return false;
827
828 if (strcmp(name, ifname) ||
829 (flags & (IFA_F_DADFAILED | IFA_F_TENTATIVE | IFA_F_DEPRECATED)))
830 continue;
831
832 for (i = 0; i < strlen(addr_buf); i++) {
833 if (!isxdigit(addr_buf[i]) || isupper(addr_buf[i]))
834 return false;
835 }
836
837 memset(&inet6_addr, 0, sizeof(inet6_addr));
838 for (i = 0; i < (strlen(addr_buf) / 2); i++) {
839 unsigned char byte;
840 static const char hex[] = "0123456789abcdef";
841 byte = ((index(hex, addr_buf[i * 2]) - hex) << 4) |
842 (index(hex, addr_buf[i * 2 + 1]) - hex);
843 inet6_addr.s6_addr[i] = byte;
844 }
845
846 if ((IN6_IS_ADDR_LINKLOCAL(&inet6_addr) == IN6_IS_ADDR_LINKLOCAL(addr)) &&
847 (IN6_IS_ADDR_UNIQUELOCAL(&inet6_addr) == IN6_IS_ADDR_UNIQUELOCAL(addr)))
848 return true;
849 }
850
851 return false;
852 }
853
854 static void sighandler(int signal)
855 {
856 if (signal == SIGUSR1)
857 signal_usr1 = true;
858 else if (signal == SIGUSR2)
859 signal_usr2 = true;
860 else if (signal == SIGIO)
861 signal_io = true;
862 else
863 signal_term = true;
864 }
865
866 static int add_opt(const uint16_t code, const uint8_t *data, const uint16_t len)
867 {
868 struct {
869 uint16_t code;
870 uint16_t len;
871 } opt_hdr = { htons(code), htons(len) };
872
873 if (odhcp6c_state_find_opt(code))
874 return -1;
875
876 if (odhcp6c_add_state(STATE_OPTS, &opt_hdr, sizeof(opt_hdr)) ||
877 odhcp6c_add_state(STATE_OPTS, data, len)) {
878 syslog(LOG_ERR, "Failed to add option %hu", code);
879 return 1;
880 }
881
882 return 0;
883 }
884
885 struct odhcp6c_opt *odhcp6c_find_opt(const uint16_t code)
886 {
887 struct odhcp6c_opt *opt = opts;
888
889 while (opt->code) {
890 if (opt->code == code)
891 return opt;
892
893 opt++;
894 }
895
896 return NULL;
897 }
898
899 static struct odhcp6c_opt *odhcp6c_find_opt_by_name(const char *name)
900 {
901 struct odhcp6c_opt *opt = opts;
902
903 if (!name || !strlen(name))
904 return NULL;
905
906 while (opt->code && (!opt->str || strcmp(opt->str, name)))
907 opt++;
908
909 return (opt->code > 0 ? opt : NULL);
910 }
911
912 /* Find first occurrence of any character in the string <needles>
913 * within the string <haystack>
914 * */
915 static char *get_sep_pos(const char *haystack, const char *needles)
916 {
917 unsigned int i;
918 char *first = NULL;
919
920 for (i = 0; i < strlen(needles); i++) {
921 char *found = strchr(haystack, needles[i]);
922 if (found && ((found < first) || (first == NULL)))
923 first = found;
924 }
925
926 return first;
927 }
928
929 static int parse_opt_u8(const char *src, uint8_t **dst)
930 {
931 int len = strlen(src);
932
933 *dst = realloc(*dst, len/2);
934 if (!*dst)
935 return -1;
936
937 return script_unhexlify(*dst, len, src);
938 }
939
940 static int parse_opt_dns_string(const char *src, uint8_t **dst, const bool array)
941 {
942 int i_len = strlen(src);
943 int o_len = 0;
944 char *sep = get_sep_pos(src, ARRAY_SEP);
945
946 if (sep && !array)
947 return -1;
948
949 do {
950 uint8_t tmp[256];
951
952 if (sep) {
953 *sep = 0;
954 sep++;
955 }
956
957 int len = dn_comp(src, tmp, sizeof(tmp), NULL, NULL);
958 if (len < 0)
959 return -1;
960
961 *dst = realloc(*dst, o_len + len);
962 if (!*dst)
963 return -1;
964
965 memcpy(&((*dst)[o_len]), tmp, len);
966
967 o_len += len;
968 i_len -= strlen(src) + (sep ? 1 : 0);
969 src = sep;
970
971 if (src)
972 sep = get_sep_pos(src, ARRAY_SEP);
973 } while (i_len);
974
975 return o_len;
976 }
977
978 static int parse_opt_ip6(const char *src, uint8_t **dst, const bool array)
979 {
980 int i_len = strlen(src);
981 int o_len = 0;
982 char *sep = get_sep_pos(src, ARRAY_SEP);
983
984 if (sep && !array)
985 return -1;
986
987 do {
988 int len = sizeof(struct in6_addr);
989
990 if (sep) {
991 *sep = 0;
992 sep++;
993 }
994
995 *dst = realloc(*dst, o_len + len);
996 if (!*dst)
997 return -1;
998
999 if (inet_pton(AF_INET6, src, &((*dst)[o_len])) < 1)
1000 return -1;
1001
1002 o_len += len;
1003 i_len -= strlen(src) + (sep ? 1 : 0);
1004 src = sep;
1005
1006 if (src)
1007 sep = get_sep_pos(src, ARRAY_SEP);
1008 } while (i_len);
1009
1010 return o_len;
1011 }
1012
1013 static int parse_opt_user_class(const char *src, uint8_t **dst, const bool array)
1014 {
1015 int i_len = strlen(src);
1016 int o_len = 0;
1017 char *sep = get_sep_pos(src, ARRAY_SEP);
1018
1019 if (sep && !array)
1020 return -1;
1021
1022 do {
1023 if (sep) {
1024 *sep = 0;
1025 sep++;
1026 }
1027 uint16_t str_len = strlen(src);
1028
1029 *dst = realloc(*dst, o_len + str_len + 2);
1030 if (!*dst)
1031 return -1;
1032
1033 struct user_class {
1034 uint16_t len;
1035 uint8_t data[];
1036 } *e = (struct user_class *)&((*dst)[o_len]);
1037
1038 e->len = ntohs(str_len);
1039 memcpy(e->data, src, str_len);
1040
1041 o_len += str_len + 2;
1042 i_len -= str_len + (sep ? 1 : 0);
1043 src = sep;
1044
1045 if (src)
1046 sep = get_sep_pos(src, ARRAY_SEP);
1047 } while (i_len);
1048
1049 return o_len;
1050 }
1051
1052 static int parse_opt_data(const char *data, uint8_t **dst, const unsigned int type,
1053 const bool array)
1054 {
1055 int ret = 0;
1056
1057 switch (type) {
1058 case OPT_U8:
1059 ret = parse_opt_u8(data, dst);
1060 break;
1061
1062 case OPT_DNS_STR:
1063 ret = parse_opt_dns_string(data, dst, array);
1064 break;
1065
1066 case OPT_IP6:
1067 ret = parse_opt_ip6(data, dst, array);
1068 break;
1069
1070 case OPT_USER_CLASS:
1071 ret = parse_opt_user_class(data, dst,array);
1072 break;
1073
1074 default:
1075 ret = -1;
1076 break;
1077 }
1078
1079 return ret;
1080 }
1081
1082 static int parse_opt(const char *opt)
1083 {
1084 uint32_t optn;
1085 char *data;
1086 uint8_t *payload = NULL;
1087 int payload_len;
1088 unsigned int type = OPT_U8;
1089 bool array = false;
1090 struct odhcp6c_opt *dopt = NULL;
1091 int ret = -1;
1092
1093 data = get_sep_pos(opt, ":");
1094 if (!data)
1095 return -1;
1096
1097 *data = '\0';
1098 data++;
1099
1100 if (strlen(opt) == 0 || strlen(data) == 0)
1101 return -1;
1102
1103 dopt = odhcp6c_find_opt_by_name(opt);
1104 if (!dopt) {
1105 char *e;
1106 optn = strtoul(opt, &e, 0);
1107 if (*e || e == opt || optn > USHRT_MAX)
1108 return -1;
1109
1110 dopt = odhcp6c_find_opt(optn);
1111 } else
1112 optn = dopt->code;
1113
1114 /* Check if the type for the content is well-known */
1115 if (dopt) {
1116 /* Refuse internal options */
1117 if (dopt->flags & OPT_INTERNAL)
1118 return -1;
1119
1120 type = dopt->flags & OPT_MASK_SIZE;
1121 array = ((dopt->flags & OPT_ARRAY) == OPT_ARRAY) ? true : false;
1122 }
1123
1124 payload_len = parse_opt_data(data, &payload, type, array);
1125 if (payload_len > 0)
1126 ret = add_opt(optn, payload, payload_len);
1127
1128 free(payload);
1129
1130 return ret;
1131 }