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