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