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