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