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