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