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