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