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