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