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