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