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