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