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