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