c8d40f63b84641d85abbb0bec40d096c68e94c0e
[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                 syslog(LOG_NOTICE, "(re)starting transaction on %s", ifname);
240
241                 do_signal = 0;
242                 int mode = dhcpv6_request(DHCPV6_MSG_SOLICIT);
243                 odhcp6c_signal_process();
244
245                 if (mode < 0)
246                         continue;
247
248                 do {
249                         int res = dhcpv6_request(mode == DHCPV6_STATELESS ?
250                                         DHCPV6_MSG_INFO_REQ : DHCPV6_MSG_REQUEST);
251
252                         odhcp6c_signal_process();
253                         if (res > 0)
254                                 break;
255                         else if (do_signal > 0) {
256                                 mode = -1;
257                                 break;
258                         }
259
260                         mode = dhcpv6_promote_server_cand();
261                 } while (mode > DHCPV6_UNKNOWN);
262
263                 if (mode < 0)
264                         continue;
265
266                 switch (mode) {
267                 case DHCPV6_STATELESS:
268                         bound = true;
269                         syslog(LOG_NOTICE, "entering stateless-mode on %s", ifname);
270
271                         while (do_signal == 0 || do_signal == SIGUSR1) {
272                                 do_signal = 0;
273                                 script_call("informed");                                        
274
275                                 int res = dhcpv6_poll_reconfigure();
276                                 odhcp6c_signal_process();
277
278                                 if (res > 0)
279                                         continue;
280
281                                 if (do_signal == SIGUSR1) {
282                                         do_signal = 0; // Acknowledged
283                                         continue;
284                                 } else if (do_signal > 0)
285                                         break;
286
287                                 res = dhcpv6_request(DHCPV6_MSG_INFO_REQ);
288                                 odhcp6c_signal_process();
289                                 if (do_signal == SIGUSR1)
290                                         continue;
291                                 else if (res < 0)
292                                         break;
293                         }
294                         break;
295
296                 case DHCPV6_STATEFUL:
297                         script_call("bound");
298                         bound = true;
299                         syslog(LOG_NOTICE, "entering stateful-mode on %s", ifname);
300 #ifdef EXT_BFD_PING
301                         if (bfd_interval > 0)
302                                 bfd_start(ifname, bfd_loss, bfd_interval);
303 #endif
304
305                         while (do_signal == 0 || do_signal == SIGUSR1) {
306                                 // Renew Cycle
307                                 // Wait for T1 to expire or until we get a reconfigure
308                                 int res = dhcpv6_poll_reconfigure();
309                                 odhcp6c_signal_process();
310                                 if (res > 0) {
311                                         script_call("updated");
312                                         continue;
313                                 }
314
315                                 // Handle signal, if necessary
316                                 if (do_signal == SIGUSR1)
317                                         do_signal = 0; // Acknowledged
318                                 else if (do_signal > 0)
319                                         break; // Other signal type
320
321                                 // If we have any IAs, send renew, otherwise request
322                                 res = dhcpv6_request(DHCPV6_MSG_RENEW);
323                                 odhcp6c_signal_process();
324                                 if (res > 0) { // Renew was succesfull
325                                         // Publish updates
326                                         script_call("updated");
327                                         continue; // Renew was successful
328                                 }
329                                 
330                                 odhcp6c_clear_state(STATE_SERVER_ID); // Remove binding
331
332                                 // If we have IAs, try rebind otherwise restart
333                                 res = dhcpv6_request(DHCPV6_MSG_REBIND);
334                                 odhcp6c_signal_process();
335
336                                 if (res > 0)
337                                         script_call("rebound");
338                                 else {
339 #ifdef EXT_BFD_PING
340                                         bfd_stop();
341 #endif
342                                         break;
343                                 }
344                         }
345                         break;
346
347                 default:
348                         break;
349                 }
350
351                 size_t ia_pd_len, ia_na_len, server_id_len;
352                 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
353                 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
354                 odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
355
356                 // Add all prefixes to lost prefixes
357                 bound = false;
358                 script_call("unbound");
359
360                 if (server_id_len > 0 && (ia_pd_len > 0 || ia_na_len > 0) && release)
361                         dhcpv6_request(DHCPV6_MSG_RELEASE);
362
363                 odhcp6c_clear_state(STATE_IA_NA);
364                 odhcp6c_clear_state(STATE_IA_PD);
365         }
366
367         script_call("stopped");
368         return 0;
369 }
370
371
372 static int usage(void)
373 {
374         const char buf[] =
375         "Usage: odhcp6c [options] <interface>\n"
376         "\nFeature options:\n"
377         "       -S <time>       Wait at least <time> sec for a DHCP-server (0)\n"
378         "       -N <mode>       Mode for requesting addresses [try|force|none]\n"
379         "       -P <length>     Request IPv6-Prefix (0 = auto)\n"
380         "       -F              Force IPv6-Prefix\n"
381 #ifdef EXT_BFD_PING
382         "       -B <interval>   Enable BFD ping check\n"
383 #endif
384         "       -c <clientid>   Override client-ID (base-16 encoded)\n"
385         "       -i <iface-id>   Use a custom interface identifier for RA handling\n"
386         "       -r <options>    Options to be requested (comma-separated)\n"
387         "       -s <script>     Status update script (/usr/sbin/odhcp6c-update)\n"
388         "       -k              Don't send a RELEASE when stopping\n"
389         "       -t <seconds>    Maximum timeout for DHCPv6-SOLICIT (120)\n"
390         "\nInvocation options:\n"
391         "       -p <pidfile>    Set pidfile (/var/run/6relayd.pid)\n"
392         "       -d              Daemonize\n"
393         "       -e              Write logmessages to stderr\n"
394         //"     -v              Increase logging verbosity\n"
395         "       -h              Show this help\n\n";
396         write(STDERR_FILENO, buf, sizeof(buf));
397         return 1;
398 }
399
400
401 // Don't want to pull-in librt and libpthread just for a monotonic clock...
402 uint64_t odhcp6c_get_milli_time(void)
403 {
404         struct timespec t = {0, 0};
405         syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &t);
406         return t.tv_sec * 1000 + t.tv_nsec / 1000000;
407 }
408
409
410 static uint8_t* odhcp6c_resize_state(enum odhcp6c_state state, ssize_t len)
411 {
412         if (len == 0)
413                 return state_data[state] + state_len[state];
414         else if (state_len[state] + len > 1024)
415                 return NULL;
416
417         uint8_t *n = realloc(state_data[state], state_len[state] + len);
418         if (n || state_len[state] + len == 0) {
419                 state_data[state] = n;
420                 n += state_len[state];
421                 state_len[state] += len;
422         }
423         return n;
424 }
425
426
427 bool odhcp6c_signal_process(void)
428 {
429         if (do_signal == SIGIO) {
430                 do_signal = 0;
431                 bool ra_updated = ra_process();
432
433                 if (ra_link_up())
434                         do_signal = SIGUSR2;
435
436                 if (ra_updated && (bound || allow_slaac_only == 0))
437                         script_call("ra-updated"); // Immediate process urgent events
438                 else if (ra_updated && !bound && allow_slaac_only > 0)
439                         script_delay_call("ra-updated", allow_slaac_only);
440
441 #ifdef EXT_BFD_PING
442                 bfd_receive();
443 #endif
444         }
445
446         return do_signal != 0;
447 }
448
449
450 void odhcp6c_clear_state(enum odhcp6c_state state)
451 {
452         state_len[state] = 0;
453 }
454
455
456 void odhcp6c_add_state(enum odhcp6c_state state, const void *data, size_t len)
457 {
458         uint8_t *n = odhcp6c_resize_state(state, len);
459         if (n)
460                 memcpy(n, data, len);
461 }
462
463 void odhcp6c_insert_state(enum odhcp6c_state state, size_t offset, const void *data, size_t len)
464 {
465         ssize_t len_after = state_len[state] - offset;
466         if (len_after < 0)
467                 return;
468
469         uint8_t *n = odhcp6c_resize_state(state, len);
470         if (n) {
471                 uint8_t *sdata = state_data[state];
472                 
473                 memmove(sdata + offset + len, sdata + offset, len_after);
474                 memcpy(sdata + offset, data, len);
475         }
476 }
477
478 size_t odhcp6c_remove_state(enum odhcp6c_state state, size_t offset, size_t len)
479 {
480         uint8_t *data = state_data[state];
481         ssize_t len_after = state_len[state] - (offset + len);
482         if (len_after < 0)
483                 return state_len[state];
484
485         memmove(data + offset, data + offset + len, len_after);
486         return state_len[state] -= len;
487 }
488
489
490 void* odhcp6c_move_state(enum odhcp6c_state state, size_t *len)
491 {
492         *len = state_len[state];
493         void *data = state_data[state];
494
495         state_len[state] = 0;
496         state_data[state] = NULL;
497
498         return data;
499 }
500
501
502 void* odhcp6c_get_state(enum odhcp6c_state state, size_t *len)
503 {
504         *len = state_len[state];
505         return state_data[state];
506 }
507
508
509 struct odhcp6c_entry* odhcp6c_find_entry(enum odhcp6c_state state, const struct odhcp6c_entry *new)
510 {
511         size_t len, cmplen = offsetof(struct odhcp6c_entry, target) + new->length / 8;
512         struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
513         struct odhcp6c_entry *x = NULL;
514
515         for (struct odhcp6c_entry *c = start; !x && c < &start[len/sizeof(*c)]; ++c)
516                 if (!memcmp(c, new, cmplen))
517                         return c;
518
519         return NULL;
520 }
521
522
523 bool odhcp6c_update_entry_safe(enum odhcp6c_state state, struct odhcp6c_entry *new, uint32_t safe)
524 {
525         size_t len;
526         struct odhcp6c_entry *x = odhcp6c_find_entry(state, new);
527         struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
528
529         if (x && x->valid > new->valid && new->valid < safe)
530                 new->valid = safe;
531
532         if (new->valid > 0) {
533                 if (x) {
534                         if (new->valid >= x->valid && new->valid - x->valid < 60 &&
535                                         new->preferred >= x->preferred &&
536                                         new->preferred - x->preferred < 60 &&
537                                         x->class == new->class)
538                                 return false;
539                         x->valid = new->valid;
540                         x->preferred = new->preferred;
541                         x->t1 = new->t1;
542                         x->t2 = new->t2;
543                         x->class = new->class;
544                 } else {
545                         odhcp6c_add_state(state, new, sizeof(*new));
546                 }
547         } else if (x) {
548                 odhcp6c_remove_state(state, (x - start) * sizeof(*x), sizeof(*x));
549         }
550         return true;
551 }
552
553
554 bool odhcp6c_update_entry(enum odhcp6c_state state, struct odhcp6c_entry *new)
555 {
556         return odhcp6c_update_entry_safe(state, new, 0);
557 }
558
559
560 static void odhcp6c_expire_list(enum odhcp6c_state state, uint32_t elapsed)
561 {
562         size_t len;
563         struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
564         for (struct odhcp6c_entry *c = start; c < &start[len / sizeof(*c)]; ++c) {
565                 if (c->t1 < elapsed)
566                         c->t1 = 0;
567                 else if (c->t1 != UINT32_MAX)
568                         c->t1 -= elapsed;
569
570                 if (c->t2 < elapsed)
571                         c->t2 = 0;
572                 else if (c->t2 != UINT32_MAX)
573                         c->t2 -= elapsed;
574
575                 if (c->preferred < elapsed)
576                         c->preferred = 0;
577                 else if (c->preferred != UINT32_MAX)
578                         c->preferred -= elapsed;
579
580                 if (c->valid < elapsed)
581                         c->valid = 0;
582                 else if (c->valid != UINT32_MAX)
583                         c->valid -= elapsed;
584
585                 if (!c->valid)
586                         odhcp6c_remove_state(state, (c - start) * sizeof(*c), sizeof(*c));
587         }
588 }
589
590
591 void odhcp6c_expire(void)
592 {
593         time_t now = odhcp6c_get_milli_time() / 1000;
594         uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
595         last_update = now;
596
597         odhcp6c_expire_list(STATE_RA_PREFIX, elapsed);
598         odhcp6c_expire_list(STATE_RA_ROUTE, elapsed);
599         odhcp6c_expire_list(STATE_RA_DNS, elapsed);
600         odhcp6c_expire_list(STATE_IA_NA, elapsed);
601         odhcp6c_expire_list(STATE_IA_PD, elapsed);
602 }
603
604
605 uint32_t odhcp6c_elapsed(void)
606 {
607         return odhcp6c_get_milli_time() / 1000 - last_update;
608 }
609
610
611 void odhcp6c_random(void *buf, size_t len)
612 {
613         read(urandom_fd, buf, len);
614 }
615
616
617 bool odhcp6c_is_bound(void)
618 {
619         return bound;
620 }
621
622
623 bool odhcp6c_addr_in_scope(const struct in6_addr *addr)
624 {
625         FILE *fd = fopen("/proc/net/if_inet6", "r");
626         int len;
627         char buf[256];
628
629         if (fd == NULL)
630                 return false;
631
632         while (fgets(buf, sizeof(buf), fd)) {
633                 struct in6_addr inet6_addr;
634                 uint32_t flags, dummy;
635                 unsigned int i;
636                 char name[8], addr_buf[32];
637
638                 len = strlen(buf);
639
640                 if ((len <= 0) || buf[len - 1] != '\n')
641                         return false;
642
643                 buf[--len] = '\0';
644
645                 if (sscanf(buf, "%s %x %x %x %x %s",
646                                 addr_buf, &dummy, &dummy, &dummy, &flags, name) != 6)
647                         return false;
648
649                 if (strcmp(name, ifname) ||
650                         (flags & (IFA_F_DADFAILED | IFA_F_TENTATIVE | IFA_F_DEPRECATED)))
651                         continue;
652
653                 for (i = 0; i < sizeof(addr_buf); i++) {
654                         if (!isxdigit(addr_buf[i]) || isupper(addr_buf[i]))
655                                 return false;
656                 }
657
658                 memset(&inet6_addr, 0, sizeof(inet6_addr));
659                 for (i = 0; i < (sizeof(addr_buf) / 2); i++) {
660                         unsigned char byte;
661                         static const char hex[] = "0123456789abcdef";
662                         byte = ((index(hex, addr_buf[i * 2]) - hex) << 4) |
663                                 (index(hex, addr_buf[i * 2 + 1]) - hex);
664                         inet6_addr.s6_addr[i] = byte;
665                 }
666
667                 if ((IN6_IS_ADDR_LINKLOCAL(&inet6_addr) == IN6_IS_ADDR_LINKLOCAL(addr)) &&
668                         (IN6_IS_ADDR_UNIQUELOCAL(&inet6_addr) == IN6_IS_ADDR_UNIQUELOCAL(addr)))
669                         return true;
670         }
671         return false;
672 }
673
674 static void sighandler(int signal)
675 {
676         if (signal == SIGCHLD)
677                 while (waitpid(-1, NULL, WNOHANG) > 0);
678         else if (signal == SIGUSR1)
679                 do_signal = SIGUSR1;
680         else if (signal == SIGUSR2)
681                 do_signal = SIGUSR2;
682         else if (signal == SIGIO)
683                 do_signal = SIGIO;
684         else
685                 do_signal = SIGTERM;
686 }