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