]> git.decadent.org.uk Git - odhcp6c.git/blob - src/odhcp6c.c
Be less verbose by default and add -v flag
[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                 char pidbuf[128];
258                 if (!pidfile) {
259                         snprintf(pidbuf, sizeof(pidbuf),
260                                         "/var/run/odhcp6c.%s.pid", ifname);
261                         pidfile = pidbuf;
262                 }
263
264                 int fd = open(pidfile, O_WRONLY | O_CREAT, 0644);
265                 if (fd >= 0) {
266                         char buf[8];
267                         int len = snprintf(buf, sizeof(buf), "%i\n", getpid());
268                         write(fd, buf, len);
269                         close(fd);
270                 }
271         }
272
273         script_call("started");
274
275         while (!signal_term) { // Main logic
276                 odhcp6c_clear_state(STATE_SERVER_ID);
277                 odhcp6c_clear_state(STATE_SERVER_ADDR);
278                 odhcp6c_clear_state(STATE_IA_NA);
279                 odhcp6c_clear_state(STATE_IA_PD);
280                 odhcp6c_clear_state(STATE_SNTP_IP);
281                 odhcp6c_clear_state(STATE_NTP_IP);
282                 odhcp6c_clear_state(STATE_NTP_FQDN);
283                 odhcp6c_clear_state(STATE_SIP_IP);
284                 odhcp6c_clear_state(STATE_SIP_FQDN);
285                 dhcpv6_set_ia_mode(ia_na_mode, ia_pd_mode);
286                 bound = false;
287
288                 syslog(LOG_NOTICE, "(re)starting transaction on %s", ifname);
289
290                 signal_usr1 = signal_usr2 = false;
291                 int mode = dhcpv6_request(DHCPV6_MSG_SOLICIT);
292                 odhcp6c_signal_process();
293
294                 if (mode < 0)
295                         continue;
296
297                 do {
298                         int res = dhcpv6_request(mode == DHCPV6_STATELESS ?
299                                         DHCPV6_MSG_INFO_REQ : DHCPV6_MSG_REQUEST);
300                         bool signalled = odhcp6c_signal_process();
301
302                         if (res > 0)
303                                 break;
304                         else if (signalled) {
305                                 mode = -1;
306                                 break;
307                         }
308
309                         mode = dhcpv6_promote_server_cand();
310                 } while (mode > DHCPV6_UNKNOWN);
311
312                 if (mode < 0)
313                         continue;
314
315                 switch (mode) {
316                 case DHCPV6_STATELESS:
317                         bound = true;
318                         syslog(LOG_NOTICE, "entering stateless-mode on %s", ifname);
319
320                         while (!signal_usr2 && !signal_term) {
321                                 signal_usr1 = false;
322                                 script_call("informed");
323
324                                 int res = dhcpv6_poll_reconfigure();
325                                 odhcp6c_signal_process();
326
327                                 if (res > 0)
328                                         continue;
329
330                                 if (signal_usr1) {
331                                         signal_usr1 = false; // Acknowledged
332                                         continue;
333                                 }
334                                 if (signal_usr2 || signal_term)
335                                         break;
336
337                                 res = dhcpv6_request(DHCPV6_MSG_INFO_REQ);
338                                 odhcp6c_signal_process();
339                                 if (signal_usr1)
340                                         continue;
341                                 else if (res < 0)
342                                         break;
343                         }
344                         break;
345
346                 case DHCPV6_STATEFUL:
347                         bound = true;
348                         script_call("bound");
349                         syslog(LOG_NOTICE, "entering stateful-mode on %s", ifname);
350
351                         while (!signal_usr2 && !signal_term) {
352                                 // Renew Cycle
353                                 // Wait for T1 to expire or until we get a reconfigure
354                                 int res = dhcpv6_poll_reconfigure();
355                                 odhcp6c_signal_process();
356                                 if (res > 0) {
357                                         script_call("updated");
358                                         continue;
359                                 }
360
361                                 // Handle signal, if necessary
362                                 if (signal_usr1)
363                                         signal_usr1 = false; // Acknowledged
364                                 if (signal_usr2 || signal_term)
365                                         break; // Other signal type
366
367                                 // Send renew as T1 expired
368                                 res = dhcpv6_request(DHCPV6_MSG_RENEW);
369                                 odhcp6c_signal_process();
370                                 if (res > 0) { // Renew was succesfull
371                                         // Publish updates
372                                         script_call("updated");
373                                         continue; // Renew was successful
374                                 }
375
376                                 odhcp6c_clear_state(STATE_SERVER_ID); // Remove binding
377                                 odhcp6c_clear_state(STATE_SERVER_ADDR);
378
379                                 size_t ia_pd_len, ia_na_len;
380                                 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
381                                 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
382
383                                 if (ia_pd_len == 0 && ia_na_len == 0)
384                                         break;
385
386                                 // If we have IAs, try rebind otherwise restart
387                                 res = dhcpv6_request(DHCPV6_MSG_REBIND);
388                                 odhcp6c_signal_process();
389
390                                 if (res > 0)
391                                         script_call("rebound");
392                                 else {
393                                         break;
394                                 }
395                         }
396                         break;
397
398                 default:
399                         break;
400                 }
401
402                 size_t ia_pd_len, ia_na_len, server_id_len;
403                 odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
404                 odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
405                 odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
406
407                 // Add all prefixes to lost prefixes
408                 bound = false;
409                 script_call("unbound");
410
411                 if (server_id_len > 0 && (ia_pd_len > 0 || ia_na_len > 0) && release)
412                         dhcpv6_request(DHCPV6_MSG_RELEASE);
413
414                 odhcp6c_clear_state(STATE_IA_NA);
415                 odhcp6c_clear_state(STATE_IA_PD);
416         }
417
418         script_call("stopped");
419         return 0;
420 }
421
422
423 static int usage(void)
424 {
425         const char buf[] =
426         "Usage: odhcp6c [options] <interface>\n"
427         "\nFeature options:\n"
428         "       -S <time>       Wait at least <time> sec for a DHCP-server (0)\n"
429         "       -N <mode>       Mode for requesting addresses [try|force|none]\n"
430         "       -P <length>     Request IPv6-Prefix (0 = auto)\n"
431         "       -F              Force IPv6-Prefix\n"
432         "       -V <class>      Set vendor-class option (base-16 encoded)\n"
433         "       -u <user-class> Set user-class option string\n"
434         "       -c <clientid>   Override client-ID (base-16 encoded)\n"
435         "       -i <iface-id>   Use a custom interface identifier for RA handling\n"
436         "       -r <options>    Options to be requested (comma-separated)\n"
437         "       -R              Do not request any options except those specified with -r\n"
438         "       -s <script>     Status update script (/usr/sbin/odhcp6c-update)\n"
439         "       -a              Don't send Accept Reconfigure option\n"
440         "       -f              Don't send Client FQDN option\n"
441         "       -k              Don't send a RELEASE when stopping\n"
442         "       -t <seconds>    Maximum timeout for DHCPv6-SOLICIT (3600)\n"
443         "       -m <seconds>    Minimum time between accepting updates (30)\n"
444         "\nInvocation options:\n"
445         "       -p <pidfile>    Set pidfile (/var/run/odhcp6c.pid)\n"
446         "       -d              Daemonize\n"
447         "       -e              Write logmessages to stderr\n"
448         "       -v              Increase logging verbosity\n"
449         "       -h              Show this help\n\n";
450         write(STDERR_FILENO, buf, sizeof(buf));
451         return 1;
452 }
453
454
455 // Don't want to pull-in librt and libpthread just for a monotonic clock...
456 uint64_t odhcp6c_get_milli_time(void)
457 {
458         struct timespec t = {0, 0};
459         syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &t);
460         return ((uint64_t)t.tv_sec) * 1000 + ((uint64_t)t.tv_nsec) / 1000000;
461 }
462
463
464 static uint8_t* odhcp6c_resize_state(enum odhcp6c_state state, ssize_t len)
465 {
466         if (len == 0)
467                 return state_data[state] + state_len[state];
468         else if (state_len[state] + len > 1024)
469                 return NULL;
470
471         uint8_t *n = realloc(state_data[state], state_len[state] + len);
472         if (n || state_len[state] + len == 0) {
473                 state_data[state] = n;
474                 n += state_len[state];
475                 state_len[state] += len;
476         }
477         return n;
478 }
479
480
481 bool odhcp6c_signal_process(void)
482 {
483         while (signal_io) {
484                 signal_io = false;
485
486                 bool ra_updated = ra_process();
487
488                 if (ra_link_up())
489                         signal_usr2 = true;
490
491                 if (ra_updated && (bound || allow_slaac_only >= 0))
492                         script_call("ra-updated"); // Immediate process urgent events
493         }
494
495         return signal_usr1 || signal_usr2 || signal_term;
496 }
497
498
499 void odhcp6c_clear_state(enum odhcp6c_state state)
500 {
501         state_len[state] = 0;
502 }
503
504
505 void odhcp6c_add_state(enum odhcp6c_state state, const void *data, size_t len)
506 {
507         uint8_t *n = odhcp6c_resize_state(state, len);
508         if (n)
509                 memcpy(n, data, len);
510 }
511
512 void odhcp6c_insert_state(enum odhcp6c_state state, size_t offset, const void *data, size_t len)
513 {
514         ssize_t len_after = state_len[state] - offset;
515         if (len_after < 0)
516                 return;
517
518         uint8_t *n = odhcp6c_resize_state(state, len);
519         if (n) {
520                 uint8_t *sdata = state_data[state];
521
522                 memmove(sdata + offset + len, sdata + offset, len_after);
523                 memcpy(sdata + offset, data, len);
524         }
525 }
526
527 size_t odhcp6c_remove_state(enum odhcp6c_state state, size_t offset, size_t len)
528 {
529         uint8_t *data = state_data[state];
530         ssize_t len_after = state_len[state] - (offset + len);
531         if (len_after < 0)
532                 return state_len[state];
533
534         memmove(data + offset, data + offset + len, len_after);
535         return state_len[state] -= len;
536 }
537
538
539 void* odhcp6c_move_state(enum odhcp6c_state state, size_t *len)
540 {
541         *len = state_len[state];
542         void *data = state_data[state];
543
544         state_len[state] = 0;
545         state_data[state] = NULL;
546
547         return data;
548 }
549
550
551 void* odhcp6c_get_state(enum odhcp6c_state state, size_t *len)
552 {
553         *len = state_len[state];
554         return state_data[state];
555 }
556
557
558 struct odhcp6c_entry* odhcp6c_find_entry(enum odhcp6c_state state, const struct odhcp6c_entry *new)
559 {
560         size_t len, cmplen = offsetof(struct odhcp6c_entry, target) + new->length / 8;
561         struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
562         struct odhcp6c_entry *x = NULL;
563
564         for (struct odhcp6c_entry *c = start; !x && c < &start[len/sizeof(*c)]; ++c)
565                 if (!memcmp(c, new, cmplen))
566                         return c;
567
568         return NULL;
569 }
570
571
572 bool odhcp6c_update_entry_safe(enum odhcp6c_state state, struct odhcp6c_entry *new, uint32_t safe)
573 {
574         size_t len;
575         struct odhcp6c_entry *x = odhcp6c_find_entry(state, new);
576         struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
577
578         if (x && x->valid > new->valid && new->valid < safe)
579                 new->valid = safe;
580
581         if (new->valid > 0) {
582                 if (x) {
583                         if (new->valid >= x->valid && new->valid != UINT32_MAX &&
584                                         new->valid - x->valid < min_update_interval &&
585                                         new->preferred >= x->preferred &&
586                                         new->preferred != UINT32_MAX &&
587                                         new->preferred - x->preferred < min_update_interval &&
588                                         x->class == new->class)
589                                 return false;
590                         x->valid = new->valid;
591                         x->preferred = new->preferred;
592                         x->t1 = new->t1;
593                         x->t2 = new->t2;
594                         x->class = new->class;
595                         x->iaid = new->iaid;
596                 } else {
597                         odhcp6c_add_state(state, new, sizeof(*new));
598                 }
599         } else if (x) {
600                 odhcp6c_remove_state(state, (x - start) * sizeof(*x), sizeof(*x));
601         }
602         return true;
603 }
604
605
606 bool odhcp6c_update_entry(enum odhcp6c_state state, struct odhcp6c_entry *new)
607 {
608         return odhcp6c_update_entry_safe(state, new, 0);
609 }
610
611
612 static void odhcp6c_expire_list(enum odhcp6c_state state, uint32_t elapsed)
613 {
614         size_t len;
615         struct odhcp6c_entry *start = odhcp6c_get_state(state, &len);
616         for (struct odhcp6c_entry *c = start; c < &start[len / sizeof(*c)]; ++c) {
617                 if (c->t1 < elapsed)
618                         c->t1 = 0;
619                 else if (c->t1 != UINT32_MAX)
620                         c->t1 -= elapsed;
621
622                 if (c->t2 < elapsed)
623                         c->t2 = 0;
624                 else if (c->t2 != UINT32_MAX)
625                         c->t2 -= elapsed;
626
627                 if (c->preferred < elapsed)
628                         c->preferred = 0;
629                 else if (c->preferred != UINT32_MAX)
630                         c->preferred -= elapsed;
631
632                 if (c->valid < elapsed)
633                         c->valid = 0;
634                 else if (c->valid != UINT32_MAX)
635                         c->valid -= elapsed;
636
637                 if (!c->valid)
638                         odhcp6c_remove_state(state, (c - start) * sizeof(*c), sizeof(*c));
639         }
640 }
641
642
643 void odhcp6c_expire(void)
644 {
645         time_t now = odhcp6c_get_milli_time() / 1000;
646         uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
647         last_update = now;
648
649         odhcp6c_expire_list(STATE_RA_PREFIX, elapsed);
650         odhcp6c_expire_list(STATE_RA_ROUTE, elapsed);
651         odhcp6c_expire_list(STATE_RA_DNS, elapsed);
652         odhcp6c_expire_list(STATE_IA_NA, elapsed);
653         odhcp6c_expire_list(STATE_IA_PD, elapsed);
654 }
655
656
657 uint32_t odhcp6c_elapsed(void)
658 {
659         return odhcp6c_get_milli_time() / 1000 - last_update;
660 }
661
662
663 void odhcp6c_random(void *buf, size_t len)
664 {
665         read(urandom_fd, buf, len);
666 }
667
668 bool odhcp6c_is_bound(void)
669 {
670         return bound;
671 }
672
673 static void sighandler(int signal)
674 {
675         if (signal == SIGCHLD)
676                 while (waitpid(-1, NULL, WNOHANG) > 0);
677         else if (signal == SIGUSR1)
678                 signal_usr1 = true;
679         else if (signal == SIGUSR2)
680                 signal_usr2 = true;
681         else if (signal == SIGIO)
682                 signal_io = true;
683         else
684                 signal_term = true;
685 }