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