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