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