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