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