odhcpd: Display infinite valid lifetime as -1
[project/odhcpd.git] / src / dhcpv6-ia.c
1 /**
2  * Copyright (C) 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 "odhcpd.h"
16 #include "dhcpv6.h"
17 #include "dhcpv4.h"
18 #include "libubox/md5.h"
19 #include "libubox/usock.h"
20
21 #include <time.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <stdio.h>
25 #include <poll.h>
26 #include <alloca.h>
27 #include <resolv.h>
28 #include <limits.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <stdbool.h>
33 #include <arpa/inet.h>
34 #include <sys/timerfd.h>
35
36
37 static void reconf_timer(struct uloop_timeout *event);
38 static struct uloop_timeout reconf_event = {.cb = reconf_timer};
39 static uint32_t serial = 0;
40 static uint8_t statemd5[16];
41
42
43 int dhcpv6_ia_init(void)
44 {
45         uloop_timeout_set(&reconf_event, 2000);
46         return 0;
47 }
48
49
50 void free_dhcpv6_assignment(struct dhcpv6_assignment *c)
51 {
52         if (c->managed_sock.fd.registered) {
53                 ustream_free(&c->managed_sock.stream);
54                 close(c->managed_sock.fd.fd);
55         }
56
57         if (c->head.next)
58                 list_del(&c->head);
59
60         free(c->managed);
61         free(c->hostname);
62         free(c);
63 }
64
65
66 int setup_dhcpv6_ia_interface(struct interface *iface, bool enable)
67 {
68         if (!enable && iface->ia_assignments.next) {
69                 struct dhcpv6_assignment *c;
70                 while (!list_empty(&iface->ia_assignments)) {
71                         c = list_first_entry(&iface->ia_assignments, struct dhcpv6_assignment, head);
72                         free_dhcpv6_assignment(c);
73                 }
74         }
75
76         if (enable && iface->dhcpv6 == RELAYD_SERVER) {
77                 if (!iface->ia_assignments.next)
78                         INIT_LIST_HEAD(&iface->ia_assignments);
79
80                 if (list_empty(&iface->ia_assignments)) {
81                         struct dhcpv6_assignment *border = calloc(1, sizeof(*border));
82                         if (!border) {
83                                 syslog(LOG_ERR, "Calloc failed for border on interface %s", iface->ifname);
84                                 return -1;
85                         }
86                         
87                         border->length = 64;
88                         list_add(&border->head, &iface->ia_assignments);
89                 }
90
91                 // Parse static entries
92                 struct lease *lease;
93                 list_for_each_entry(lease, &leases, head) {
94                         // Construct entry
95                         size_t duid_len = lease->duid_len ? lease->duid_len : 14;
96                         struct dhcpv6_assignment *a = calloc(1, sizeof(*a) + duid_len);
97                         if (!a) {
98                                 syslog(LOG_ERR, "Calloc failed for static lease assignment on interface %s",
99                                         iface->ifname);
100                                 return -1;
101                         }
102
103                         if (lease->dhcpv4_leasetime > 0)
104                                 a->leasetime = lease->dhcpv4_leasetime;
105
106                         a->clid_len = duid_len;
107                         a->length = 128;
108                         if (lease->hostid) {
109                                 a->assigned = lease->hostid;
110                         } else {
111                                 uint32_t i4a = ntohl(lease->ipaddr.s_addr) & 0xff;
112                                 a->assigned = ((i4a / 100) << 8) | (((i4a % 100) / 10) << 4) | (i4a % 10);
113                         }
114                         odhcpd_urandom(a->key, sizeof(a->key));
115                         memcpy(a->clid_data, lease->duid, lease->duid_len);
116                         memcpy(a->mac, lease->mac.ether_addr_octet, sizeof(a->mac));
117
118                         // Assign to all interfaces
119                         struct dhcpv6_assignment *c;
120                         list_for_each_entry(c, &iface->ia_assignments, head) {
121                                 if (c->length != 128 || c->assigned > a->assigned) {
122                                         list_add_tail(&a->head, &c->head);
123                                         break;
124                                 } else if (c->assigned == a->assigned) {
125                                         // Already an assignment with that number
126                                         break;
127                                 }
128                         }
129
130                         if (a->head.next) {
131                                 if (lease->hostname[0]) {
132                                         free(a->hostname);
133                                         a->hostname = strdup(lease->hostname);
134                                 }
135                         } else {
136                                 free(a->hostname);
137                                 free(a);
138                         }
139                 }
140         }
141         return 0;
142 }
143
144
145 static int send_reconf(struct interface *iface, struct dhcpv6_assignment *assign)
146 {
147         struct {
148                 struct dhcpv6_client_header hdr;
149                 uint16_t srvid_type;
150                 uint16_t srvid_len;
151                 uint16_t duid_type;
152                 uint16_t hardware_type;
153                 uint8_t mac[6];
154                 uint16_t msg_type;
155                 uint16_t msg_len;
156                 uint8_t msg_id;
157                 struct dhcpv6_auth_reconfigure auth;
158                 uint16_t clid_type;
159                 uint16_t clid_len;
160                 uint8_t clid_data[128];
161         } __attribute__((packed)) reconf_msg = {
162                 .hdr = {DHCPV6_MSG_RECONFIGURE, {0, 0, 0}},
163                 .srvid_type = htons(DHCPV6_OPT_SERVERID),
164                 .srvid_len = htons(10),
165                 .duid_type = htons(3),
166                 .hardware_type = htons(1),
167                 .msg_type = htons(DHCPV6_OPT_RECONF_MSG),
168                 .msg_len = htons(1),
169                 .msg_id = DHCPV6_MSG_RENEW,
170                 .auth = {htons(DHCPV6_OPT_AUTH),
171                                 htons(sizeof(reconf_msg.auth) - 4), 3, 1, 0,
172                                 {htonl(time(NULL)), htonl(++serial)}, 2, {0}},
173                 .clid_type = htons(DHCPV6_OPT_CLIENTID),
174                 .clid_len = htons(assign->clid_len),
175                 .clid_data = {0},
176         };
177
178         odhcpd_get_mac(iface, reconf_msg.mac);
179         memcpy(reconf_msg.clid_data, assign->clid_data, assign->clid_len);
180         struct iovec iov = {&reconf_msg, sizeof(reconf_msg) - 128 + assign->clid_len};
181
182         md5_ctx_t md5;
183         uint8_t secretbytes[64];
184         memset(secretbytes, 0, sizeof(secretbytes));
185         memcpy(secretbytes, assign->key, sizeof(assign->key));
186
187         for (size_t i = 0; i < sizeof(secretbytes); ++i)
188                 secretbytes[i] ^= 0x36;
189
190         md5_begin(&md5);
191         md5_hash(secretbytes, sizeof(secretbytes), &md5);
192         md5_hash(iov.iov_base, iov.iov_len, &md5);
193         md5_end(reconf_msg.auth.key, &md5);
194
195         for (size_t i = 0; i < sizeof(secretbytes); ++i) {
196                 secretbytes[i] ^= 0x36;
197                 secretbytes[i] ^= 0x5c;
198         }
199
200         md5_begin(&md5);
201         md5_hash(secretbytes, sizeof(secretbytes), &md5);
202         md5_hash(reconf_msg.auth.key, 16, &md5);
203         md5_end(reconf_msg.auth.key, &md5);
204
205         return odhcpd_send(iface->dhcpv6_event.uloop.fd, &assign->peer, &iov, 1, iface);
206 }
207
208
209 void dhcpv6_write_statefile(void)
210 {
211         md5_ctx_t md5;
212         md5_begin(&md5);
213
214         if (config.dhcp_statefile) {
215                 time_t now = odhcpd_time(), wall_time = time(NULL);
216                 int fd = open(config.dhcp_statefile, O_CREAT | O_WRONLY | O_CLOEXEC, 0644);
217                 if (fd < 0)
218                         return;
219
220                 lockf(fd, F_LOCK, 0);
221                 if (ftruncate(fd, 0) < 0) {}
222
223                 FILE *fp = fdopen(fd, "w");
224                 if (!fp) {
225                         close(fd);
226                         return;
227                 }
228
229                 struct interface *iface;
230                 list_for_each_entry(iface, &interfaces, head) {
231                         if (iface->dhcpv6 != RELAYD_SERVER && iface->dhcpv4 != RELAYD_SERVER)
232                                 continue;
233
234                         if (iface->dhcpv6 == RELAYD_SERVER && iface->ia_assignments.next) {
235                                 struct dhcpv6_assignment *c;
236                                 list_for_each_entry(c, &iface->ia_assignments, head) {
237                                         if (c->clid_len == 0 || c->managed_size < 0)
238                                                 continue;
239
240                                         char ipbuf[INET6_ADDRSTRLEN];
241                                         char leasebuf[512];
242                                         char duidbuf[264];
243                                         odhcpd_hexlify(duidbuf, c->clid_data, c->clid_len);
244
245                                         // iface DUID iaid hostname lifetime assigned length [addrs...]
246                                         int l = snprintf(leasebuf, sizeof(leasebuf), "# %s %s %x %s %ld %x %u ",
247                                                         iface->ifname, duidbuf, ntohl(c->iaid),
248                                                         (c->hostname ? c->hostname : "-"),
249                                                         (c->valid_until > now ?
250                                                                 (c->valid_until - now + wall_time) :
251                                                                 (INFINITE_VALID(c->valid_until) ? -1 : 0)),
252                                                         c->assigned, (unsigned)c->length);
253
254                                         struct in6_addr addr;
255                                         struct odhcpd_ipaddr *addrs = (c->managed) ? c->managed : iface->ia_addr;
256                                         size_t addrlen = (c->managed) ? (size_t)c->managed_size : iface->ia_addr_len;
257                                         size_t m = 0;
258
259                                         for (size_t i = 0; i < addrlen; ++i)
260                                                 if (addrs[i].preferred > addrs[m].preferred ||
261                                                                 (addrs[i].preferred == addrs[m].preferred &&
262                                                                                 memcmp(&addrs[i].addr, &addrs[m].addr, 16) > 0))
263                                                         m = i;
264
265                                         for (size_t i = 0; i < addrlen; ++i) {
266                                                 if (addrs[i].prefix > 96 || (!INFINITE_VALID(c->valid_until) && c->valid_until <= now) ||
267                                                                 (iface->managed < RELAYD_MANAGED_NO_AFLAG && i != m &&
268                                                                                 addrs[i].prefix == 64))
269                                                         continue;
270
271                                                 addr = addrs[i].addr;
272                                                 if (c->length == 128)
273                                                         addr.s6_addr32[3] = htonl(c->assigned);
274                                                 else
275                                                         addr.s6_addr32[1] |= htonl(c->assigned);
276
277                                                 inet_ntop(AF_INET6, &addr, ipbuf, sizeof(ipbuf) - 1);
278
279                                                 if (c->length == 128 && c->hostname) {
280                                                         fputs(ipbuf, fp);
281
282                                                         char b[256];
283                                                         if (dn_expand(iface->search, iface->search + iface->search_len,
284                                                                         iface->search, b, sizeof(b)) > 0)
285                                                                 fprintf(fp, "\t%s.%s", c->hostname, b);
286
287                                                         fprintf(fp, "\t%s\n", c->hostname);
288                                                         md5_hash(ipbuf, strlen(ipbuf), &md5);
289                                                         md5_hash(c->hostname, strlen(c->hostname), &md5);
290                                                 }
291
292                                                 l += snprintf(leasebuf + l, sizeof(leasebuf) - l, "%s/%d ", ipbuf,
293                                                                 (c->managed_size) ? addrs[i].prefix : c->length);
294                                         }
295                                         leasebuf[l - 1] = '\n';
296                                         fwrite(leasebuf, 1, l, fp);
297                                 }
298                         }
299
300                         if (iface->dhcpv4 == RELAYD_SERVER && iface->dhcpv4_assignments.next) {
301                                 struct dhcpv4_assignment *c;
302                                 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
303                                         char ipbuf[INET6_ADDRSTRLEN];
304                                         char leasebuf[512];
305                                         char duidbuf[16];
306                                         odhcpd_hexlify(duidbuf, c->hwaddr, sizeof(c->hwaddr));
307
308                                         // iface DUID iaid hostname lifetime assigned length [addrs...]
309                                         int l = snprintf(leasebuf, sizeof(leasebuf), "# %s %s ipv4 %s %ld %x 32 ",
310                                                         iface->ifname, duidbuf,
311                                                         (c->hostname ? c->hostname : "-"),
312                                                         (c->valid_until > now ?
313                                                                 (c->valid_until - now + wall_time) :
314                                                                 (INFINITE_VALID(c->valid_until) ? -1 : 0)),
315                                                         c->addr);
316
317                                         struct in_addr addr = {htonl(c->addr)};
318                                         inet_ntop(AF_INET, &addr, ipbuf, sizeof(ipbuf) - 1);
319
320                                         if (c->hostname[0]) {
321                                                 fputs(ipbuf, fp);
322
323                                                 char b[256];
324                                                 if (dn_expand(iface->search, iface->search + iface->search_len,
325                                                                 iface->search, b, sizeof(b)) > 0)
326                                                         fprintf(fp, "\t%s.%s", c->hostname, b);
327
328                                                 fprintf(fp, "\t%s\n", c->hostname);
329                                                 md5_hash(ipbuf, strlen(ipbuf), &md5);
330                                                 md5_hash(c->hostname, strlen(c->hostname), &md5);
331                                         }
332
333                                         l += snprintf(leasebuf + l, sizeof(leasebuf) - l, "%s/32 ", ipbuf);
334                                         leasebuf[l - 1] = '\n';
335                                         fwrite(leasebuf, 1, l, fp);
336                                 }
337                         }
338                 }
339
340                 fclose(fp);
341         }
342
343         uint8_t newmd5[16];
344         md5_end(newmd5, &md5);
345
346         if (config.dhcp_cb && memcmp(newmd5, statemd5, sizeof(newmd5))) {
347                 memcpy(statemd5, newmd5, sizeof(statemd5));
348                 char *argv[2] = {config.dhcp_cb, NULL};
349                 if (!vfork()) {
350                         execv(argv[0], argv);
351                         _exit(128);
352                 }
353         }
354 }
355
356
357 static void apply_lease(struct interface *iface, struct dhcpv6_assignment *a, bool add)
358 {
359         if (a->length > 64 || a->managed_size < 0)
360                 return;
361
362         struct odhcpd_ipaddr *addrs = (a->managed) ? a->managed : iface->ia_addr;
363         size_t addrlen = (a->managed) ? (size_t)a->managed_size : iface->ia_addr_len;
364
365         for (size_t i = 0; i < addrlen; ++i) {
366                 struct in6_addr prefix = addrs[i].addr;
367                 prefix.s6_addr32[1] |= htonl(a->assigned);
368                 odhcpd_setup_route(&prefix, (a->managed_size) ? addrs[i].prefix : a->length,
369                                 iface, &a->peer.sin6_addr, 1024, add);
370         }
371 }
372
373
374 // More data was received from TCP connection
375 static void managed_handle_pd_data(struct ustream *s, _unused int bytes_new)
376 {
377         struct dhcpv6_assignment *c = container_of(s, struct dhcpv6_assignment, managed_sock);
378         time_t now = odhcpd_time();
379         bool first = c->managed_size < 0;
380
381         for (;;) {
382                 int pending;
383                 char *data = ustream_get_read_buf(s, &pending);
384                 char *end = memmem(data, pending, "\n\n", 2);
385
386                 if (!end)
387                         break;
388
389                 end += 2;
390                 end[-1] = 0;
391
392                 c->managed_size = 0;
393                 if (c->accept_reconf)
394                         c->reconf_cnt = 1;
395
396                 char *saveptr;
397                 for (char *line = strtok_r(data, "\n", &saveptr); line; line = strtok_r(NULL, "\n", &saveptr)) {
398                         c->managed = realloc(c->managed, (c->managed_size + 1) * sizeof(*c->managed));
399                         struct odhcpd_ipaddr *n = &c->managed[c->managed_size];
400
401                         char *saveptr2, *x = strtok_r(line, "/", &saveptr2);
402                         if (!x || inet_pton(AF_INET6, x, &n->addr) < 1)
403                                 continue;
404
405                         x = strtok_r(NULL, ",", &saveptr2);
406                         if (sscanf(x, "%hhu", &n->prefix) < 1)
407                                 continue;
408
409                         x = strtok_r(NULL, ",", &saveptr2);
410                         if (sscanf(x, "%u", &n->preferred) < 1)
411                                 continue;
412
413                         x = strtok_r(NULL, ",", &saveptr2);
414                         if (sscanf(x, "%u", &n->valid) < 1)
415                                 continue;
416
417                         if (n->preferred > n->valid)
418                                 continue;
419
420                         if (UINT32_MAX - now < n->preferred)
421                                 n->preferred = UINT32_MAX;
422                         else
423                                 n->preferred += now;
424
425                         if (UINT32_MAX - now < n->valid)
426                                 n->valid = UINT32_MAX;
427                         else
428                                 n->valid += now;
429
430                         n->dprefix = 0;
431
432                         ++c->managed_size;
433                 }
434
435                 ustream_consume(s, end - data);
436         }
437
438         if (first && c->managed_size == 0)
439                 free_dhcpv6_assignment(c);
440         else if (first)
441                 c->valid_until = now + 150;
442 }
443
444
445 // TCP transmission has ended, either because of success or timeout or other error
446 static void managed_handle_pd_done(struct ustream *s)
447 {
448         struct dhcpv6_assignment *c = container_of(s, struct dhcpv6_assignment, managed_sock);
449         c->valid_until = odhcpd_time() + 15;
450         c->managed_size = 0;
451         if (c->accept_reconf)
452                 c->reconf_cnt = 1;
453 }
454
455
456
457 static bool assign_pd(struct interface *iface, struct dhcpv6_assignment *assign)
458 {
459         struct dhcpv6_assignment *c;
460
461         if (iface->dhcpv6_pd_manager[0]) {
462                 int fd = usock(USOCK_UNIX | USOCK_TCP, iface->dhcpv6_pd_manager, NULL);
463                 if (fd >= 0) {
464                         char iaidbuf[298];
465                         odhcpd_hexlify(iaidbuf, assign->clid_data, assign->clid_len);
466
467                         assign->managed_sock.stream.notify_read = managed_handle_pd_data;
468                         assign->managed_sock.stream.notify_state = managed_handle_pd_done;
469                         ustream_fd_init(&assign->managed_sock, fd);
470                         ustream_printf(&assign->managed_sock.stream, "%s,%x\n::/%d,0,0\n\n",
471                                         iaidbuf, assign->iaid, assign->length);
472                         ustream_write_pending(&assign->managed_sock.stream);
473                         assign->managed_size = -1;
474                         assign->valid_until = odhcpd_time() + 15;
475                         list_add(&assign->head, &iface->ia_assignments);
476
477                         // Wait initial period of up to 250ms for immediate assignment
478                         struct pollfd pfd = { .fd = fd, .events = POLLIN };
479                         poll(&pfd, 1, 250);
480                         managed_handle_pd_data(&assign->managed_sock.stream, 0);
481
482                         if (fcntl(fd, F_GETFL) >= 0 && assign->managed_size > 0)
483                                 return true;
484                 }
485
486                 return false;
487         } else if (iface->ia_addr_len < 1) {
488                 return false;
489         }
490
491         // Try honoring the hint first
492         uint32_t current = 1, asize = (1 << (64 - assign->length)) - 1;
493         if (assign->assigned) {
494                 list_for_each_entry(c, &iface->ia_assignments, head) {
495                         if (c->length == 128 || c->length == 0)
496                                 continue;
497
498                         if (assign->assigned >= current && assign->assigned + asize < c->assigned) {
499                                 list_add_tail(&assign->head, &c->head);
500                                 apply_lease(iface, assign, true);
501                                 return true;
502                         }
503
504                         if (c->assigned != 0)
505                                 current = (c->assigned + (1 << (64 - c->length)));
506                 }
507         }
508
509         // Fallback to a variable assignment
510         current = 1;
511         list_for_each_entry(c, &iface->ia_assignments, head) {
512                 if (c->length == 128 || c->length == 0)
513                         continue;
514
515                 current = (current + asize) & (~asize);
516                 if (current + asize < c->assigned) {
517                         assign->assigned = current;
518                         list_add_tail(&assign->head, &c->head);
519                         apply_lease(iface, assign, true);
520                         return true;
521                 }
522
523                 if (c->assigned != 0)
524                         current = (c->assigned + (1 << (64 - c->length)));
525         }
526
527         return false;
528 }
529
530
531 static bool assign_na(struct interface *iface, struct dhcpv6_assignment *assign)
532 {
533         // Seed RNG with checksum of DUID
534         uint32_t seed = 0;
535         for (size_t i = 0; i < assign->clid_len; ++i)
536                 seed += assign->clid_data[i];
537         srand(seed);
538
539         // Try to assign up to 100x
540         for (size_t i = 0; i < 100; ++i) {
541                 uint32_t try;
542                 do try = ((uint32_t)rand()) % 0x0fff; while (try < 0x100);
543
544                 struct dhcpv6_assignment *c;
545                 list_for_each_entry(c, &iface->ia_assignments, head) {
546                         if (c->length == 0)
547                                 continue;
548
549                         if (c->assigned > try || c->length != 128) {
550                                 assign->assigned = try;
551                                 list_add_tail(&assign->head, &c->head);
552                                 return true;
553                         } else if (c->assigned == try) {
554                                 break;
555                         }
556                 }
557         }
558
559         return false;
560 }
561
562 void dhcpv6_ia_preupdate(struct interface *iface)
563 {
564         if (iface->dhcpv6 != RELAYD_SERVER)
565                 return;
566
567         struct dhcpv6_assignment *c, *border = list_last_entry(
568                         &iface->ia_assignments, struct dhcpv6_assignment, head);
569         list_for_each_entry(c, &iface->ia_assignments, head)
570                 if (c != border && !iface->managed)
571                         apply_lease(iface, c, false);
572 }
573
574 void dhcpv6_ia_postupdate(struct interface *iface, time_t now)
575 {
576         if (iface->dhcpv6 != RELAYD_SERVER)
577                 return;
578
579         int minprefix = -1;
580         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
581                 if (iface->ia_addr[i].preferred > (uint32_t)now &&
582                                 iface->ia_addr[i].prefix < 64 &&
583                                 iface->ia_addr[i].prefix > minprefix)
584                         minprefix = iface->ia_addr[i].prefix;
585         }
586
587         struct dhcpv6_assignment *border = list_last_entry(
588                         &iface->ia_assignments, struct dhcpv6_assignment, head);
589         if (minprefix > 32 && minprefix <= 64)
590                 border->assigned = 1U << (64 - minprefix);
591         else
592                 border->assigned = 0;
593
594         struct list_head reassign = LIST_HEAD_INIT(reassign);
595         struct dhcpv6_assignment *c, *d;
596         list_for_each_entry_safe(c, d, &iface->ia_assignments, head) {
597                 if (c->clid_len == 0 || (!INFINITE_VALID(c->valid_until) && c->valid_until < now) ||
598                                 c->managed_size)
599                         continue;
600
601                 if (c->length < 128 && c->assigned >= border->assigned && c != border)
602                         list_move(&c->head, &reassign);
603                 else if (c != border)
604                         apply_lease(iface, c, true);
605
606                 if (c->accept_reconf && c->reconf_cnt == 0) {
607                         c->reconf_cnt = 1;
608                         c->reconf_sent = now;
609                         send_reconf(iface, c);
610
611                         // Leave all other assignments of that client alone
612                         struct dhcpv6_assignment *a;
613                         list_for_each_entry(a, &iface->ia_assignments, head)
614                                 if (a != c && a->clid_len == c->clid_len &&
615                                                 !memcmp(a->clid_data, c->clid_data, a->clid_len))
616                                         c->reconf_cnt = INT_MAX;
617                 }
618         }
619
620         while (!list_empty(&reassign)) {
621                 c = list_first_entry(&reassign, struct dhcpv6_assignment, head);
622                 list_del(&c->head);
623                 if (!assign_pd(iface, c)) {
624                         c->assigned = 0;
625                         list_add(&c->head, &iface->ia_assignments);
626                 }
627         }
628
629         dhcpv6_write_statefile();
630 }
631
632
633 static void reconf_timer(struct uloop_timeout *event)
634 {
635         time_t now = odhcpd_time();
636         struct interface *iface;
637         list_for_each_entry(iface, &interfaces, head) {
638                 if (iface->dhcpv6 != RELAYD_SERVER || iface->ia_assignments.next == NULL)
639                         continue;
640
641                 struct dhcpv6_assignment *a, *n;
642                 list_for_each_entry_safe(a, n, &iface->ia_assignments, head) {
643                         if (!INFINITE_VALID(a->valid_until) && a->valid_until < now) {
644                                 if ((a->length < 128 && a->clid_len > 0) ||
645                                                 (a->length == 128 && a->clid_len == 0)) {
646                                         list_del(&a->head);
647                                         free_dhcpv6_assignment(a);
648                                 }
649                         } else if (a->reconf_cnt > 0 && a->reconf_cnt < 8 &&
650                                         now > a->reconf_sent + (1 << a->reconf_cnt)) {
651                                 ++a->reconf_cnt;
652                                 a->reconf_sent = now;
653                                 send_reconf(iface, a);
654                         }
655                 }
656         }
657         uloop_timeout_set(event, 2000);
658 }
659
660
661 static size_t append_reply(uint8_t *buf, size_t buflen, uint16_t status,
662                 const struct dhcpv6_ia_hdr *ia, struct dhcpv6_assignment *a,
663                 struct interface *iface, bool request)
664 {
665         if (buflen < sizeof(*ia) + sizeof(struct dhcpv6_ia_prefix))
666                 return 0;
667
668         struct dhcpv6_ia_hdr out = {ia->type, 0, ia->iaid, 0, 0};
669         size_t datalen = sizeof(out);
670         time_t now = odhcpd_time();
671
672         if (status) {
673                 struct __attribute__((packed)) {
674                         uint16_t type;
675                         uint16_t len;
676                         uint16_t value;
677                 } stat = {htons(DHCPV6_OPT_STATUS), htons(sizeof(stat) - 4),
678                                 htons(status)};
679
680                 memcpy(buf + datalen, &stat, sizeof(stat));
681                 datalen += sizeof(stat);
682         } else {
683                 if (a) {
684                         uint32_t leasetime;
685                         if (a->leasetime > 0) {
686                                 leasetime = a->leasetime;
687                         } else {
688                                 leasetime = iface->dhcpv4_leasetime;
689                         }
690                         if (leasetime == 0)
691                                 leasetime = 3600;
692                         else if (leasetime < 60)
693                                 leasetime = 60;
694
695                         uint32_t pref = leasetime;
696                         uint32_t valid = leasetime;
697
698                         struct odhcpd_ipaddr *addrs = (a->managed) ? a->managed : iface->ia_addr;
699                         size_t addrlen = (a->managed) ? (size_t)a->managed_size : iface->ia_addr_len;
700                         size_t m = 0;
701
702                         for (size_t i = 0; i < addrlen; ++i)
703                                 if (addrs[i].preferred > addrs[m].preferred ||
704                                                 (addrs[i].preferred == addrs[m].preferred &&
705                                                                 memcmp(&addrs[i].addr, &addrs[m].addr, 16) > 0))
706                                         m = i;
707
708                         for (size_t i = 0; i < addrlen; ++i) {
709                                 uint32_t prefix_pref = addrs[i].preferred;
710                                 uint32_t prefix_valid = addrs[i].valid;
711
712                                 if (addrs[i].prefix > 96 ||
713                                                 addrs[i].preferred <= (uint32_t)now)
714                                         continue;
715
716                                 if (prefix_pref != UINT32_MAX)
717                                         prefix_pref -= now;
718
719                                 if (prefix_valid != UINT32_MAX)
720                                         prefix_valid -= now;
721
722                                 if (a->length < 128) {
723                                         struct dhcpv6_ia_prefix p = {
724                                                 .type = htons(DHCPV6_OPT_IA_PREFIX),
725                                                 .len = htons(sizeof(p) - 4),
726                                                 .preferred = htonl(prefix_pref),
727                                                 .valid = htonl(prefix_valid),
728                                                 .prefix = (a->managed_size) ? addrs[i].prefix : a->length,
729                                                 .addr = addrs[i].addr
730                                         };
731                                         p.addr.s6_addr32[1] |= htonl(a->assigned);
732
733                                         size_t entrlen = sizeof(p) - 4;
734
735                                         if (datalen + entrlen + 4 > buflen ||
736                                                         (a->assigned == 0 && a->managed_size == 0) ||
737                                                         (!a->managed_size && a->length <= addrs[i].prefix))
738                                                 continue;
739
740                                         memcpy(buf + datalen, &p, sizeof(p));
741                                         datalen += entrlen + 4;
742                                 } else {
743                                         struct dhcpv6_ia_addr n = {
744                                                 .type = htons(DHCPV6_OPT_IA_ADDR),
745                                                 .len = htons(sizeof(n) - 4),
746                                                 .addr = addrs[i].addr,
747                                                 .preferred = htonl(prefix_pref),
748                                                 .valid = htonl(prefix_valid)
749                                         };
750                                         n.addr.s6_addr32[3] = htonl(a->assigned);
751                                         size_t entrlen = sizeof(n) - 4;
752
753                                         if (iface->managed < RELAYD_MANAGED_NO_AFLAG && i != m &&
754                                                         addrs[i].prefix <= 64)
755                                                 continue;
756
757                                         if (datalen + entrlen + 4 > buflen || a->assigned == 0)
758                                                 continue;
759
760                                         memcpy(buf + datalen, &n, sizeof(n));
761                                         datalen += entrlen + 4;
762                                 }
763
764                                 // Calculate T1 / T2 based on non-deprecated addresses
765                                 if (prefix_pref > 0) {
766                                         if (prefix_pref < pref)
767                                                 pref = prefix_pref;
768
769                                         if (prefix_valid < valid)
770                                                 valid = prefix_valid;
771                                 }
772                         }
773
774                         /* UINT32_MAX is considered as infinite leasetime */
775                         a->valid_until = (valid == UINT32_MAX) ? 0 : valid + now;
776                         out.t1 = htonl((pref == UINT32_MAX) ? pref : pref * 5 / 10);
777                         out.t2 = htonl((pref == UINT32_MAX) ? pref : pref * 8 / 10);
778
779                         if (!out.t1)
780                                 out.t1 = htonl(1);
781
782                         if (!out.t2)
783                                 out.t2 = htonl(1);
784                 }
785
786                 if (!request) {
787                         uint8_t *odata, *end = ((uint8_t*)ia) + htons(ia->len) + 4;
788                         uint16_t otype, olen;
789                         dhcpv6_for_each_option((uint8_t*)&ia[1], end, otype, olen, odata) {
790                                 struct dhcpv6_ia_prefix *p = (struct dhcpv6_ia_prefix*)&odata[-4];
791                                 struct dhcpv6_ia_addr *n = (struct dhcpv6_ia_addr*)&odata[-4];
792                                 if ((otype != DHCPV6_OPT_IA_PREFIX || olen < sizeof(*p) - 4) &&
793                                                 (otype != DHCPV6_OPT_IA_ADDR || olen < sizeof(*n) - 4))
794                                         continue;
795
796                                 bool found = false;
797                                 if (a) {
798                                         struct odhcpd_ipaddr *addrs = (a->managed) ? a->managed : iface->ia_addr;
799                                         size_t addrlen = (a->managed) ? (size_t)a->managed_size : iface->ia_addr_len;
800
801                                         for (size_t i = 0; i < addrlen; ++i) {
802                                                 if (addrs[i].prefix > 96 ||
803                                                                 addrs[i].preferred <= (uint32_t)now)
804                                                         continue;
805
806                                                 struct in6_addr addr = addrs[i].addr;
807                                                 if (ia->type == htons(DHCPV6_OPT_IA_PD)) {
808                                                         addr.s6_addr32[1] |= htonl(a->assigned);
809
810                                                         if (!memcmp(&p->addr, &addr, sizeof(addr)) &&
811                                                                         p->prefix == ((a->managed) ? addrs[i].prefix : a->length))
812                                                                 found = true;
813                                                 } else {
814                                                         addr.s6_addr32[3] = htonl(a->assigned);
815
816                                                         if (!memcmp(&n->addr, &addr, sizeof(addr)))
817                                                                 found = true;
818                                                 }
819                                         }
820                                 }
821
822                                 if (!found) {
823                                         if (otype == DHCPV6_OPT_IA_PREFIX) {
824                                                 struct dhcpv6_ia_prefix inv = {
825                                                         .type = htons(DHCPV6_OPT_IA_PREFIX),
826                                                         .len = htons(sizeof(inv) - 4),
827                                                         .preferred = 0,
828                                                         .valid = 0,
829                                                         .prefix = p->prefix,
830                                                         .addr = p->addr
831                                                 };
832
833                                                 if (datalen + sizeof(inv) > buflen)
834                                                         continue;
835
836                                                 memcpy(buf + datalen, &inv, sizeof(inv));
837                                                 datalen += sizeof(inv);
838                                         } else {
839                                                 struct dhcpv6_ia_addr inv = {
840                                                         .type = htons(DHCPV6_OPT_IA_ADDR),
841                                                         .len = htons(sizeof(inv) - 4),
842                                                         .addr = n->addr,
843                                                         .preferred = 0,
844                                                         .valid = 0
845                                                 };
846
847                                                 if (datalen + sizeof(inv) > buflen)
848                                                         continue;
849
850                                                 memcpy(buf + datalen, &inv, sizeof(inv));
851                                                 datalen += sizeof(inv);
852                                         }
853                                 }
854                         }
855                 }
856         }
857
858         out.len = htons(datalen - 4);
859         memcpy(buf, &out, sizeof(out));
860         return datalen;
861 }
862
863
864 static void dhcpv6_log(uint8_t msgtype, struct interface *iface, time_t now,
865                 const char *duidbuf, bool is_pd, struct dhcpv6_assignment *a, int code)
866 {
867         const char *type = "UNKNOWN";
868         const char *status = "UNKNOWN";
869
870         if (msgtype == DHCPV6_MSG_RENEW)
871                 return;
872
873         switch (msgtype) {
874         case DHCPV6_MSG_SOLICIT:
875                 type = "SOLICIT";
876                 break;
877         case DHCPV6_MSG_REQUEST:
878                 type = "REQUEST";
879                 break;
880         case DHCPV6_MSG_CONFIRM:
881                 type = "CONFIRM";
882                 break;
883         case DHCPV6_MSG_RENEW:
884                 type = "RENEW";
885                 break;
886         case DHCPV6_MSG_REBIND:
887                 type = "REBIND";
888                 break;
889         case DHCPV6_MSG_RELEASE:
890                 type = "RELEASE";
891                 break;
892         case DHCPV6_MSG_DECLINE:
893                 type = "DECLINE";
894                 break;
895         }
896
897         switch (code) {
898         case DHCPV6_STATUS_OK:
899                 status = "ok";
900                 break;
901         case DHCPV6_STATUS_NOADDRSAVAIL:
902                 status = "no addresses available";
903                 break;
904         case DHCPV6_STATUS_NOBINDING:
905                 status = "no binding";
906                 break;
907         case DHCPV6_STATUS_NOTONLINK:
908                 status = "not on-link";
909                 break;
910         case DHCPV6_STATUS_NOPREFIXAVAIL:
911                 status = "no prefix available";
912                 break;
913         }
914
915         char leasebuf[256] = "";
916
917         if (a) {
918                 struct odhcpd_ipaddr *addrs = (a->managed) ? a->managed : iface->ia_addr;
919                 size_t addrlen = (a->managed) ? (size_t)a->managed_size : iface->ia_addr_len;
920                 size_t lbsize = 0;
921                 char addrbuf[INET6_ADDRSTRLEN];
922
923                 for (size_t i = 0; i < addrlen; ++i) {
924                         if (addrs[i].prefix > 96 || addrs[i].preferred <= (uint32_t)now)
925                                 continue;
926
927                         struct in6_addr addr = addrs[i].addr;
928                         int prefix = a->managed ? addrs[i].prefix : a->length;
929                         if (prefix == 128)
930                                 addr.s6_addr32[3] = htonl(a->assigned);
931                         else
932                                 addr.s6_addr32[1] |= htonl(a->assigned);
933
934                         inet_ntop(AF_INET6, &addr, addrbuf, sizeof(addrbuf));
935                         lbsize += snprintf(leasebuf + lbsize, sizeof(leasebuf) - lbsize, "%s/%d ", addrbuf, prefix);
936                 }
937         }
938
939         syslog(LOG_WARNING, "DHCPV6 %s %s from %s on %s: %s %s", type, (is_pd) ? "IA_PD" : "IA_NA",
940                         duidbuf, iface->ifname, status, leasebuf);
941 }
942
943
944
945 ssize_t dhcpv6_handle_ia(uint8_t *buf, size_t buflen, struct interface *iface,
946                 const struct sockaddr_in6 *addr, const void *data, const uint8_t *end)
947 {
948         time_t now = odhcpd_time();
949         size_t response_len = 0;
950         const struct dhcpv6_client_header *hdr = data;
951         uint8_t *start = (uint8_t*)&hdr[1], *odata;
952         uint16_t otype, olen;
953
954         // Find and parse client-id and hostname
955         bool accept_reconf = false;
956         uint8_t *clid_data = NULL, clid_len = 0, mac[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
957         char hostname[256];
958         size_t hostname_len = 0;
959         bool notonlink = false;
960         char duidbuf[261];
961
962         dhcpv6_for_each_option(start, end, otype, olen, odata) {
963                 if (otype == DHCPV6_OPT_CLIENTID) {
964                         clid_data = odata;
965                         clid_len = olen;
966
967                         if (olen == 14 && odata[0] == 0 && odata[1] == 1)
968                                 memcpy(mac, &odata[8], sizeof(mac));
969                         else if (olen == 10 && odata[0] == 0 && odata[1] == 3)
970                                 memcpy(mac, &odata[4], sizeof(mac));
971
972                         if (olen <= 130)
973                                 odhcpd_hexlify(duidbuf, odata, olen);
974                 } else if (otype == DHCPV6_OPT_FQDN && olen >= 2 && olen <= 255) {
975                         uint8_t fqdn_buf[256];
976                         memcpy(fqdn_buf, odata, olen);
977                         fqdn_buf[olen++] = 0;
978
979                         if (dn_expand(&fqdn_buf[1], &fqdn_buf[olen], &fqdn_buf[1], hostname, sizeof(hostname)) > 0)
980                                 hostname_len = strcspn(hostname, ".");
981                 } else if (otype == DHCPV6_OPT_RECONF_ACCEPT) {
982                         accept_reconf = true;
983                 }
984         }
985
986         if (!clid_data || !clid_len || clid_len > 130)
987                 goto out;
988
989         struct dhcpv6_assignment *first = NULL;
990         dhcpv6_for_each_option(start, end, otype, olen, odata) {
991                 bool is_pd = (otype == DHCPV6_OPT_IA_PD);
992                 bool is_na = (otype == DHCPV6_OPT_IA_NA);
993                 bool ia_addr_present = false;
994                 if (!is_pd && !is_na)
995                         continue;
996
997                 struct dhcpv6_ia_hdr *ia = (struct dhcpv6_ia_hdr*)&odata[-4];
998                 size_t ia_response_len = 0;
999                 uint8_t reqlen = (is_pd) ? 62 : 128;
1000                 uint32_t reqhint = 0;
1001
1002                 // Parse request hint for IA-PD
1003                 if (is_pd) {
1004                         uint8_t *sdata;
1005                         uint16_t stype, slen;
1006                         dhcpv6_for_each_option(&ia[1], odata + olen, stype, slen, sdata) {
1007                                 if (stype != DHCPV6_OPT_IA_PREFIX || slen < sizeof(struct dhcpv6_ia_prefix) - 4)
1008                                         continue;
1009
1010                                 struct dhcpv6_ia_prefix *p = (struct dhcpv6_ia_prefix*)&sdata[-4];
1011                                 if (p->prefix) {
1012                                         reqlen = p->prefix;
1013                                         reqhint = ntohl(p->addr.s6_addr32[1]);
1014                                         if (reqlen > 32 && reqlen <= 64)
1015                                                 reqhint &= (1U << (64 - reqlen)) - 1;
1016                                 }
1017                         }
1018
1019                         if (reqlen > 64)
1020                                 reqlen = 64;
1021                 } else if (is_na) {
1022                         uint8_t *sdata;
1023                         uint16_t stype, slen;
1024                         dhcpv6_for_each_option(&ia[1], odata + olen, stype, slen, sdata) {
1025                                 if (stype != DHCPV6_OPT_IA_ADDR || slen < sizeof(struct dhcpv6_ia_addr) - 4)
1026                                         continue;
1027
1028                                 ia_addr_present = true;
1029                         }
1030                 }
1031
1032                 // Find assignment
1033                 struct dhcpv6_assignment *c, *a = NULL;
1034                 list_for_each_entry(c, &iface->ia_assignments, head) {
1035                         if (((c->clid_len == clid_len && !memcmp(c->clid_data, clid_data, clid_len)) ||
1036                                         (c->clid_len >= clid_len && !c->clid_data[0] && !c->clid_data[1]
1037                                                 && !memcmp(c->mac, mac, sizeof(mac)))) &&
1038                                         (c->iaid == ia->iaid || (!INFINITE_VALID(c->valid_until) && c->valid_until < now)) &&
1039                                         ((is_pd && c->length <= 64) || (is_na && c->length == 128))) {
1040                                 a = c;
1041
1042                                 // Reset state
1043                                 apply_lease(iface, a, false);
1044                                 memcpy(a->clid_data, clid_data, clid_len);
1045                                 a->clid_len = clid_len;
1046                                 a->iaid = ia->iaid;
1047                                 a->peer = *addr;
1048                                 a->reconf_cnt = 0;
1049                                 a->reconf_sent = 0;
1050                                 break;
1051                         }
1052                 }
1053
1054                 // Generic message handling
1055                 uint16_t status = DHCPV6_STATUS_OK;
1056                 if (a && a->managed_size < 0) {
1057                         return -1;
1058                 } else if (hdr->msg_type == DHCPV6_MSG_SOLICIT || hdr->msg_type == DHCPV6_MSG_REQUEST) {
1059                         bool assigned = !!a;
1060
1061                         if (!a && !iface->no_dynamic_dhcp) { // Create new binding
1062                                 a = calloc(1, sizeof(*a) + clid_len);
1063                                 if (a) {
1064                                         a->clid_len = clid_len;
1065                                         a->iaid = ia->iaid;
1066                                         a->length = reqlen;
1067                                         a->peer = *addr;
1068                                         a->assigned = reqhint;
1069
1070                                         if (first)
1071                                                 memcpy(a->key, first->key, sizeof(a->key));
1072                                         else
1073                                                 odhcpd_urandom(a->key, sizeof(a->key));
1074                                         memcpy(a->clid_data, clid_data, clid_len);
1075
1076                                         if (is_pd)
1077                                                 while (!(assigned = assign_pd(iface, a)) &&
1078                                                                 !a->managed_size && ++a->length <= 64);
1079                                         else
1080                                                 assigned = assign_na(iface, a);
1081
1082                                         if (a->managed_size && !assigned)
1083                                                 return -1;
1084                                 }
1085                         }
1086
1087                         if (!assigned || iface->ia_addr_len == 0) { // Set error status
1088                                 status = (is_pd) ? DHCPV6_STATUS_NOPREFIXAVAIL : DHCPV6_STATUS_NOADDRSAVAIL;
1089                         } else if (assigned && !first) { //
1090                                 size_t handshake_len = 4;
1091                                 buf[0] = 0;
1092                                 buf[1] = DHCPV6_OPT_RECONF_ACCEPT;
1093                                 buf[2] = 0;
1094                                 buf[3] = 0;
1095
1096                                 if (hdr->msg_type == DHCPV6_MSG_REQUEST) {
1097                                         struct dhcpv6_auth_reconfigure auth = {
1098                                                 htons(DHCPV6_OPT_AUTH),
1099                                                 htons(sizeof(auth) - 4),
1100                                                 3, 1, 0,
1101                                                 {htonl(time(NULL)), htonl(++serial)},
1102                                                 1,
1103                                                 {0}
1104                                         };
1105                                         memcpy(auth.key, a->key, sizeof(a->key));
1106                                         memcpy(buf + handshake_len, &auth, sizeof(auth));
1107                                         handshake_len += sizeof(auth);
1108                                 }
1109
1110                                 buf += handshake_len;
1111                                 buflen -= handshake_len;
1112                                 response_len += handshake_len;
1113
1114                                 first = a;
1115                         }
1116
1117                         ia_response_len = append_reply(buf, buflen, status, ia, a, iface, true);
1118
1119                         // Was only a solicitation: mark binding for removal
1120                         if (assigned && hdr->msg_type == DHCPV6_MSG_SOLICIT) {
1121                                 a->valid_until = now;
1122                         } else if (assigned && hdr->msg_type == DHCPV6_MSG_REQUEST) {
1123                                 if (hostname_len > 0) {
1124                                         a->hostname = realloc(a->hostname, hostname_len + 1);
1125                                         if (a->hostname) {
1126                                                 memcpy(a->hostname, hostname, hostname_len);
1127                                                 a->hostname[hostname_len] = 0;
1128                                         }
1129                                 }
1130                                 a->accept_reconf = accept_reconf;
1131                                 apply_lease(iface, a, true);
1132                         } else if (!assigned && a && a->managed_size == 0) { // Cleanup failed assignment
1133                                 free_dhcpv6_assignment(a);
1134                         }
1135                 } else if (hdr->msg_type == DHCPV6_MSG_RENEW ||
1136                                 hdr->msg_type == DHCPV6_MSG_RELEASE ||
1137                                 hdr->msg_type == DHCPV6_MSG_REBIND ||
1138                                 hdr->msg_type == DHCPV6_MSG_DECLINE) {
1139                         if (!a && hdr->msg_type != DHCPV6_MSG_REBIND) {
1140                                 status = DHCPV6_STATUS_NOBINDING;
1141                                 ia_response_len = append_reply(buf, buflen, status, ia, a, iface, false);
1142                         } else if (hdr->msg_type == DHCPV6_MSG_RENEW ||
1143                                         hdr->msg_type == DHCPV6_MSG_REBIND) {
1144                                 ia_response_len = append_reply(buf, buflen, status, ia, a, iface, false);
1145                                 if (a)
1146                                         apply_lease(iface, a, true);
1147                         } else if (hdr->msg_type == DHCPV6_MSG_RELEASE) {
1148                                 a->valid_until = now - 1;
1149                                 apply_lease(iface, a, false);
1150                         } else if (hdr->msg_type == DHCPV6_MSG_DECLINE && a->length == 128) {
1151                                 a->clid_len = 0;
1152                                 a->valid_until = now + 3600; // Block address for 1h
1153                         }
1154                 } else if (hdr->msg_type == DHCPV6_MSG_CONFIRM && ia_addr_present) {
1155                         // Send NOTONLINK for CONFIRM with addr present so that clients restart connection
1156                         status = DHCPV6_STATUS_NOTONLINK;
1157                         ia_response_len = append_reply(buf, buflen, status, ia, a, iface, true);
1158                         notonlink = true;
1159                 }
1160
1161                 buf += ia_response_len;
1162                 buflen -= ia_response_len;
1163                 response_len += ia_response_len;
1164                 dhcpv6_log(hdr->msg_type, iface, now, duidbuf, is_pd, a, status);
1165         }
1166
1167         if ((hdr->msg_type == DHCPV6_MSG_RELEASE || hdr->msg_type == DHCPV6_MSG_DECLINE || notonlink) &&
1168                         response_len + 6 < buflen) {
1169                 buf[0] = 0;
1170                 buf[1] = DHCPV6_OPT_STATUS;
1171                 buf[2] = 0;
1172                 buf[3] = 2;
1173                 buf[4] = 0;
1174                 buf[5] = (notonlink) ? DHCPV6_STATUS_NOTONLINK : DHCPV6_STATUS_OK;
1175                 response_len += 6;
1176         }
1177
1178         dhcpv6_write_statefile();
1179
1180 out:
1181         return response_len;
1182 }