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