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