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