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