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