Fix last commit
[project/odhcpd.git] / src / dhcpv6-ia.c
1 /**
2  * Copyright (C) 2013 Steven Barth <steven@midlink.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License v2 as published by
6  * the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  */
14
15 #include "odhcpd.h"
16 #include "dhcpv6.h"
17 #include "dhcpv4.h"
18 #include "md5.h"
19
20 #include <time.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <alloca.h>
24 #include <resolv.h>
25 #include <limits.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <arpa/inet.h>
29 #include <sys/timerfd.h>
30
31
32 static void update(struct interface *iface);
33 static void reconf_timer(struct uloop_timeout *event);
34 static struct uloop_timeout reconf_event = {.cb = reconf_timer};
35 static int socket_fd = -1;
36 static uint32_t serial = 0;
37
38
39 int dhcpv6_ia_init(int dhcpv6_socket)
40 {
41         socket_fd = dhcpv6_socket;
42         uloop_timeout_set(&reconf_event, 2000);
43         return 0;
44 }
45
46
47 int setup_dhcpv6_ia_interface(struct interface *iface, bool enable)
48 {
49         if (!enable && iface->ia_assignments.next) {
50                 struct dhcpv6_assignment *c;
51                 while (!list_empty(&iface->ia_assignments)) {
52                         c = list_first_entry(&iface->ia_assignments, struct dhcpv6_assignment, head);
53                         list_del(&c->head);
54                         free(c);
55                 }
56         }
57
58         if (iface->dhcpv6 == RELAYD_SERVER) {
59                 if (!iface->ia_assignments.next)
60                         INIT_LIST_HEAD(&iface->ia_assignments);
61
62                 if (list_empty(&iface->ia_assignments)) {
63                         struct dhcpv6_assignment *border = calloc(1, sizeof(*border));
64                         border->length = 64;
65                         list_add(&border->head, &iface->ia_assignments);
66                 }
67
68                 update(iface);
69
70                 // Parse static entries
71                 struct lease *lease;
72                 list_for_each_entry(lease, &leases, head) {
73                         // Construct entry
74                         struct dhcpv6_assignment *a = calloc(1, sizeof(*a) + lease->duid_len);
75                         a->clid_len = lease->duid_len;
76                         a->length = 128;
77                         a->assigned = lease->hostid;
78                         odhcpd_urandom(a->key, sizeof(a->key));
79                         memcpy(a->clid_data, lease->duid, a->clid_len);
80                         memcpy(a->mac, lease->mac.ether_addr_octet, sizeof(a->mac));
81
82                         // Assign to all interfaces
83                         struct dhcpv6_assignment *c;
84                         list_for_each_entry(c, &iface->ia_assignments, head) {
85                                 if (c->length != 128 || c->assigned > a->assigned) {
86                                         list_add_tail(&a->head, &c->head);
87                                 } else if (c->assigned == a->assigned) {
88                                         // Already an assignment with that number
89                                         break;
90                                 }
91                         }
92
93                         if (a->head.next) {
94                                 if (lease->hostname[0]) {
95                                         free(a->hostname);
96                                         a->hostname = strdup(lease->hostname);
97                                 }
98                         } else {
99                                 free(a);
100                         }
101                 }
102         }
103         return 0;
104 }
105
106
107 static int send_reconf(struct interface *iface, struct dhcpv6_assignment *assign)
108 {
109         struct {
110                 struct dhcpv6_client_header hdr;
111                 uint16_t srvid_type;
112                 uint16_t srvid_len;
113                 uint16_t duid_type;
114                 uint16_t hardware_type;
115                 uint8_t mac[6];
116                 uint16_t msg_type;
117                 uint16_t msg_len;
118                 uint8_t msg_id;
119                 struct dhcpv6_auth_reconfigure auth;
120                 uint16_t clid_type;
121                 uint16_t clid_len;
122                 uint8_t clid_data[128];
123         } __attribute__((packed)) reconf_msg = {
124                 .hdr = {DHCPV6_MSG_RECONFIGURE, {0, 0, 0}},
125                 .srvid_type = htons(DHCPV6_OPT_SERVERID),
126                 .srvid_len = htons(10),
127                 .duid_type = htons(3),
128                 .hardware_type = htons(1),
129                 .msg_type = htons(DHCPV6_OPT_RECONF_MSG),
130                 .msg_len = htons(1),
131                 .msg_id = DHCPV6_MSG_RENEW,
132                 .auth = {htons(DHCPV6_OPT_AUTH),
133                                 htons(sizeof(reconf_msg.auth) - 4), 3, 1, 0,
134                                 {htonl(time(NULL)), htonl(++serial)}, 2, {0}},
135                 .clid_type = htons(DHCPV6_OPT_CLIENTID),
136                 .clid_len = htons(assign->clid_len),
137                 .clid_data = {0},
138         };
139
140         odhcpd_get_mac(iface, reconf_msg.mac);
141         memcpy(reconf_msg.clid_data, assign->clid_data, assign->clid_len);
142         struct iovec iov = {&reconf_msg, sizeof(reconf_msg) - 128 + assign->clid_len};
143
144         md5_ctx_t md5;
145         uint8_t secretbytes[16];
146         memcpy(secretbytes, assign->key, sizeof(secretbytes));
147
148         for (size_t i = 0; i < sizeof(secretbytes); ++i)
149                 secretbytes[i] ^= 0x36;
150
151         md5_begin(&md5);
152         md5_hash(secretbytes, sizeof(secretbytes), &md5);
153         md5_hash(iov.iov_base, iov.iov_len, &md5);
154         md5_end(reconf_msg.auth.key, &md5);
155
156         for (size_t i = 0; i < sizeof(secretbytes); ++i) {
157                 secretbytes[i] ^= 0x36;
158                 secretbytes[i] ^= 0x5c;
159         }
160
161         md5_begin(&md5);
162         md5_hash(secretbytes, sizeof(secretbytes), &md5);
163         md5_hash(reconf_msg.auth.key, 16, &md5);
164         md5_end(reconf_msg.auth.key, &md5);
165
166         return odhcpd_send(socket_fd, &assign->peer, &iov, 1, iface);
167 }
168
169
170 void dhcpv6_write_statefile(void)
171 {
172         if (config.dhcp_statefile) {
173                 time_t now = odhcpd_time(), wall_time = time(NULL);
174                 int fd = open(config.dhcp_statefile, O_CREAT | O_WRONLY | O_CLOEXEC, 0644);
175                 if (fd < 0)
176                         return;
177
178                 lockf(fd, F_LOCK, 0);
179                 ftruncate(fd, 0);
180
181                 FILE *fp = fdopen(fd, "w");
182                 if (!fp) {
183                         close(fd);
184                         return;
185                 }
186
187                 struct interface *iface;
188                 list_for_each_entry(iface, &interfaces, head) {
189                         if (iface->dhcpv6 != RELAYD_SERVER && iface->dhcpv4 != RELAYD_SERVER)
190                                 continue;
191
192                         if (iface->dhcpv6 == RELAYD_SERVER) {
193                                 struct dhcpv6_assignment *c;
194                                 list_for_each_entry(c, &iface->ia_assignments, head) {
195                                         if (c->clid_len == 0)
196                                                 continue;
197
198                                         char ipbuf[INET6_ADDRSTRLEN];
199                                         char leasebuf[512];
200                                         char duidbuf[264];
201                                         odhcpd_hexlify(duidbuf, c->clid_data, c->clid_len);
202
203                                         // iface DUID iaid hostname lifetime assigned length [addrs...]
204                                         int l = snprintf(leasebuf, sizeof(leasebuf), "# %s %s %x %s %u %x %u ",
205                                                         iface->ifname, duidbuf, ntohl(c->iaid),
206                                                         (c->hostname ? c->hostname : "-"),
207                                                         (unsigned)(c->valid_until > now ?
208                                                                         (c->valid_until - now + wall_time) : 0),
209                                                         c->assigned, (unsigned)c->length);
210
211                                         struct in6_addr addr;
212                                         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
213                                                 if (iface->ia_addr[i].prefix > 64)
214                                                         continue;
215
216                                                 addr = iface->ia_addr[i].addr;
217                                                 if (c->length == 128)
218                                                         addr.s6_addr32[3] = htonl(c->assigned);
219                                                 else
220                                                         addr.s6_addr32[1] |= htonl(c->assigned);
221                                                 inet_ntop(AF_INET6, &addr, ipbuf, sizeof(ipbuf) - 1);
222
223                                                 if (c->length == 128 && c->hostname && i == 0)
224                                                         fprintf(fp, "%s\t%s\n", ipbuf, c->hostname);
225
226                                                 l += snprintf(leasebuf + l, sizeof(leasebuf) - l, "%s/%hhu ", ipbuf, c->length);
227                                         }
228                                         leasebuf[l - 1] = '\n';
229                                         fwrite(leasebuf, 1, l, fp);
230                                 }
231                         }
232
233                         if (iface->dhcpv4 == RELAYD_SERVER) {
234                                 struct dhcpv4_assignment *c;
235                                 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
236                                         char ipbuf[INET6_ADDRSTRLEN];
237                                         char leasebuf[512];
238                                         char duidbuf[16];
239                                         odhcpd_hexlify(duidbuf, c->hwaddr, sizeof(c->hwaddr));
240
241                                         // iface DUID iaid hostname lifetime assigned length [addrs...]
242                                         int l = snprintf(leasebuf, sizeof(leasebuf), "# %s %s ipv4 %s %u %x 32 ",
243                                                         iface->ifname, duidbuf,
244                                                         (c->hostname ? c->hostname : "-"),
245                                                         (unsigned)(c->valid_until > now ?
246                                                                         (c->valid_until - now + wall_time) : 0),
247                                                         c->addr);
248
249                                         struct in_addr addr = {htonl(c->addr)};
250                                         inet_ntop(AF_INET, &addr, ipbuf, sizeof(ipbuf) - 1);
251
252                                         if (c->hostname[0])
253                                                 fprintf(fp, "%s\t%s\n", ipbuf, c->hostname);
254
255                                         l += snprintf(leasebuf + l, sizeof(leasebuf) - l, "%s/32 ", ipbuf);
256                                         leasebuf[l - 1] = '\n';
257                                         fwrite(leasebuf, 1, l, fp);
258                                 }
259                         }
260                 }
261
262                 fclose(fp);
263         }
264
265         if (config.dhcp_cb) {
266                 char *argv[2] = {config.dhcp_cb, NULL};
267                 if (!vfork()) {
268                         execv(argv[0], argv);
269                         _exit(128);
270                 }
271         }
272 }
273
274
275 static void apply_lease(struct interface *iface, struct dhcpv6_assignment *a, bool add)
276 {
277         if (a->length > 64)
278                 return;
279
280         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
281                 struct in6_addr prefix = iface->ia_addr[i].addr;
282                 prefix.s6_addr32[1] |= htonl(a->assigned);
283                 odhcpd_setup_route(&prefix, a->length, iface, &a->peer.sin6_addr, add);
284         }
285 }
286
287
288 static bool assign_pd(struct interface *iface, struct dhcpv6_assignment *assign)
289 {
290         struct dhcpv6_assignment *c;
291         if (iface->ia_addr_len < 1)
292                 return false;
293
294         // Try honoring the hint first
295         uint32_t current = 1, asize = (1 << (64 - assign->length)) - 1;
296         if (assign->assigned) {
297                 list_for_each_entry(c, &iface->ia_assignments, head) {
298                         if (c->length == 128)
299                                 continue;
300
301                         if (assign->assigned >= current && assign->assigned + asize < c->assigned) {
302                                 list_add_tail(&assign->head, &c->head);
303                                 apply_lease(iface, assign, true);
304                                 return true;
305                         }
306
307                         if (c->assigned != 0)
308                                 current = (c->assigned + (1 << (64 - c->length)));
309                 }
310         }
311
312         // Fallback to a variable assignment
313         current = 1;
314         list_for_each_entry(c, &iface->ia_assignments, head) {
315                 if (c->length == 128)
316                         continue;
317
318                 current = (current + asize) & (~asize);
319                 if (current + asize < c->assigned) {
320                         assign->assigned = current;
321                         list_add_tail(&assign->head, &c->head);
322                         apply_lease(iface, assign, true);
323                         return true;
324                 }
325
326                 if (c->assigned != 0)
327                         current = (c->assigned + (1 << (64 - c->length)));
328         }
329
330         return false;
331 }
332
333
334 static bool assign_na(struct interface *iface, struct dhcpv6_assignment *assign)
335 {
336         if (iface->ia_addr_len < 1)
337                 return false;
338
339         // Seed RNG with checksum of DUID
340         uint32_t seed = 0;
341         for (size_t i = 0; i < assign->clid_len; ++i)
342                 seed += assign->clid_data[i];
343         srand(seed);
344
345         // Try to assign up to 100x
346         for (size_t i = 0; i < 100; ++i) {
347                 uint32_t try;
348                 do try = ((uint32_t)rand()) % 0x0fff; while (try < 0x100);
349
350                 struct dhcpv6_assignment *c;
351                 list_for_each_entry(c, &iface->ia_assignments, head) {
352                         if (c->assigned > try || c->length != 128) {
353                                 assign->assigned = try;
354                                 list_add_tail(&assign->head, &c->head);
355                                 return true;
356                         } else if (c->assigned == try) {
357                                 break;
358                         }
359                 }
360         }
361
362         return false;
363 }
364
365
366 static int prefixcmp(const void *va, const void *vb)
367 {
368         const struct odhcpd_ipaddr *a = va, *b = vb;
369         uint32_t a_pref = ((a->addr.s6_addr[0] & 0xfe) != 0xfc) ? a->preferred : 1;
370         uint32_t b_pref = ((b->addr.s6_addr[0] & 0xfe) != 0xfc) ? b->preferred : 1;
371         return (a_pref < b_pref) ? 1 : (a_pref > b_pref) ? -1 : 0;
372 }
373
374
375 static void update(struct interface *iface)
376 {
377         struct odhcpd_ipaddr addr[8];
378         memset(addr, 0, sizeof(addr));
379         int len = odhcpd_get_interface_addresses(iface->ifindex, addr, 8);
380
381         if (len < 0)
382                 return;
383
384         qsort(addr, len, sizeof(*addr), prefixcmp);
385
386         time_t now = odhcpd_time();
387         int minprefix = -1;
388
389         for (int i = 0; i < len; ++i) {
390                 if (addr[i].prefix > minprefix)
391                         minprefix = addr[i].prefix;
392
393                 addr[i].addr.s6_addr32[2] = 0;
394                 addr[i].addr.s6_addr32[3] = 0;
395
396                 if (addr[i].preferred < UINT32_MAX - now)
397                         addr[i].preferred += now;
398
399                 if (addr[i].valid < UINT32_MAX - now)
400                         addr[i].valid += now;
401         }
402
403         struct dhcpv6_assignment *border = list_last_entry(&iface->ia_assignments, struct dhcpv6_assignment, head);
404         border->assigned = 1 << (64 - minprefix);
405
406         bool change = len != (int)iface->ia_addr_len;
407         for (int i = 0; !change && i < len; ++i)
408                 if (addr[i].addr.s6_addr32[0] != iface->ia_addr[i].addr.s6_addr32[0] ||
409                                 addr[i].addr.s6_addr32[1] != iface->ia_addr[i].addr.s6_addr32[1] ||
410                                 (addr[i].preferred > 0) != (iface->ia_addr[i].preferred > 0) ||
411                                 (addr[i].valid > (uint32_t)now + 7200) !=
412                                                 (iface->ia_addr[i].valid > (uint32_t)now + 7200))
413                         change = true;
414
415         if (change) {
416                 struct dhcpv6_assignment *c;
417                 list_for_each_entry(c, &iface->ia_assignments, head)
418                         if (c != border)
419                                 apply_lease(iface, c, false);
420         }
421
422         memcpy(iface->ia_addr, addr, len * sizeof(*addr));
423         iface->ia_addr_len = len;
424
425         if (change) { // Addresses / prefixes have changed
426                 struct list_head reassign = LIST_HEAD_INIT(reassign);
427                 struct dhcpv6_assignment *c, *d;
428                 list_for_each_entry_safe(c, d, &iface->ia_assignments, head) {
429                         if (c->clid_len == 0 || c->valid_until < now)
430                                 continue;
431
432                         if (c->length < 128 && c->assigned >= border->assigned && c != border)
433                                 list_move(&c->head, &reassign);
434                         else if (c != border)
435                                 apply_lease(iface, c, true);
436
437                         if (c->accept_reconf && c->reconf_cnt == 0) {
438                                 c->reconf_cnt = 1;
439                                 c->reconf_sent = now;
440                                 send_reconf(iface, c);
441
442                                 // Leave all other assignments of that client alone
443                                 struct dhcpv6_assignment *a;
444                                 list_for_each_entry(a, &iface->ia_assignments, head)
445                                         if (a != c && a->clid_len == c->clid_len &&
446                                                         !memcmp(a->clid_data, c->clid_data, a->clid_len))
447                                                 c->reconf_cnt = INT_MAX;
448                         }
449                 }
450
451                 while (!list_empty(&reassign)) {
452                         c = list_first_entry(&reassign, struct dhcpv6_assignment, head);
453                         list_del(&c->head);
454                         if (!assign_pd(iface, c)) {
455                                 c->assigned = 0;
456                                 list_add(&c->head, &iface->ia_assignments);
457                         }
458                 }
459
460                 dhcpv6_write_statefile();
461         }
462 }
463
464
465 static void reconf_timer(struct uloop_timeout *event)
466 {
467         time_t now = odhcpd_time();
468         struct interface *iface;
469         list_for_each_entry(iface, &interfaces, head) {
470                 if (iface->dhcpv6 != RELAYD_SERVER || iface->ia_assignments.next == NULL)
471                         continue;
472
473                 struct dhcpv6_assignment *a, *n;
474                 list_for_each_entry_safe(a, n, &iface->ia_assignments, head) {
475                         if (a->valid_until < now) {
476                                 if ((a->length < 128 && a->clid_len > 0) ||
477                                                 (a->length == 128 && a->clid_len == 0)) {
478                                         list_del(&a->head);
479                                         free(a->hostname);
480                                         free(a);
481                                 }
482                         } else if (a->reconf_cnt > 0 && a->reconf_cnt < 8 &&
483                                         now > a->reconf_sent + (1 << a->reconf_cnt)) {
484                                 ++a->reconf_cnt;
485                                 a->reconf_sent = now;
486                                 send_reconf(iface, a);
487                         }
488                 }
489
490                 if (iface->ia_reconf) {
491                         update(iface);
492                         iface->ia_reconf = false;
493                 }
494         }
495
496         uloop_timeout_set(event, 2000);
497 }
498
499
500 static size_t append_reply(uint8_t *buf, size_t buflen, uint16_t status,
501                 const struct dhcpv6_ia_hdr *ia, struct dhcpv6_assignment *a,
502                 struct interface *iface, bool request)
503 {
504         if (buflen < sizeof(*ia) + sizeof(struct dhcpv6_ia_prefix))
505                 return 0;
506
507         struct dhcpv6_ia_hdr out = {ia->type, 0, ia->iaid, 0, 0};
508         size_t datalen = sizeof(out);
509         time_t now = odhcpd_time();
510
511         if (status) {
512                 struct __attribute__((packed)) {
513                         uint16_t type;
514                         uint16_t len;
515                         uint16_t value;
516                 } stat = {htons(DHCPV6_OPT_STATUS), htons(sizeof(stat) - 4),
517                                 htons(status)};
518
519                 memcpy(buf + datalen, &stat, sizeof(stat));
520                 datalen += sizeof(stat);
521         } else {
522                 if (a) {
523                         uint32_t pref = 3600;
524                         uint32_t valid = 3600;
525                         bool have_non_ula = false;
526                         for (size_t i = 0; i < iface->ia_addr_len; ++i)
527                                 if ((iface->ia_addr[i].addr.s6_addr[0] & 0xfe) != 0xfc)
528                                         have_non_ula = true;
529
530                         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
531                                 uint32_t prefix_pref = iface->ia_addr[i].preferred - now;
532                                 uint32_t prefix_valid = iface->ia_addr[i].valid - now;
533
534                                 if (iface->ia_addr[i].prefix > 64 ||
535                                                 iface->ia_addr[i].preferred <= (uint32_t)now)
536                                         continue;
537
538                                 // ULA-deprecation compatibility workaround
539                                 if ((iface->ia_addr[i].addr.s6_addr[0] & 0xfe) == 0xfc &&
540                                                 a->length == 128 && have_non_ula &&
541                                                 iface->deprecate_ula_if_public_avail)
542                                         continue;
543
544                                 if (prefix_pref > 86400)
545                                         prefix_pref = 86400;
546
547                                 if (prefix_valid > 86400)
548                                         prefix_valid = 86400;
549
550                                 if (a->length < 128) {
551                                         struct dhcpv6_ia_prefix p = {
552                                                 .type = htons(DHCPV6_OPT_IA_PREFIX),
553                                                 .len = htons(sizeof(p) - 4),
554                                                 .preferred = htonl(prefix_pref),
555                                                 .valid = htonl(prefix_valid),
556                                                 .prefix = a->length,
557                                                 .addr = iface->ia_addr[i].addr
558                                         };
559                                         p.addr.s6_addr32[1] |= htonl(a->assigned);
560
561                                         if (datalen + sizeof(p) > buflen || a->assigned == 0)
562                                                 continue;
563
564                                         memcpy(buf + datalen, &p, sizeof(p));
565                                         datalen += sizeof(p);
566                                 } else {
567                                         struct dhcpv6_ia_addr n = {
568                                                 .type = htons(DHCPV6_OPT_IA_ADDR),
569                                                 .len = htons(sizeof(n) - 4),
570                                                 .addr = iface->ia_addr[i].addr,
571                                                 .preferred = htonl(prefix_pref),
572                                                 .valid = htonl(prefix_valid)
573                                         };
574                                         n.addr.s6_addr32[3] = htonl(a->assigned);
575
576                                         if (datalen + sizeof(n) > buflen || a->assigned == 0)
577                                                 continue;
578
579                                         memcpy(buf + datalen, &n, sizeof(n));
580                                         datalen += sizeof(n);
581                                 }
582
583                                 // Calculate T1 / T2 based on non-deprecated addresses
584                                 if (prefix_pref > 0) {
585                                         if (prefix_pref < pref)
586                                                 pref = prefix_pref;
587
588                                         if (prefix_valid < valid)
589                                                 valid = prefix_valid;
590                                 }
591                         }
592
593                         a->valid_until = valid + now;
594                         out.t1 = htonl(pref * 5 / 10);
595                         out.t2 = htonl(pref * 8 / 10);
596
597                         if (!out.t1)
598                                 out.t1 = htonl(1);
599
600                         if (!out.t2)
601                                 out.t2 = htonl(1);
602                 }
603
604                 if (!request) {
605                         uint8_t *odata, *end = ((uint8_t*)ia) + htons(ia->len) + 4;
606                         uint16_t otype, olen;
607                         dhcpv6_for_each_option((uint8_t*)&ia[1], end, otype, olen, odata) {
608                                 struct dhcpv6_ia_prefix *p = (struct dhcpv6_ia_prefix*)&odata[-4];
609                                 struct dhcpv6_ia_addr *n = (struct dhcpv6_ia_addr*)&odata[-4];
610                                 if ((otype != DHCPV6_OPT_IA_PREFIX || olen < sizeof(*p) - 4) &&
611                                                 (otype != DHCPV6_OPT_IA_ADDR || olen < sizeof(*n) - 4))
612                                         continue;
613
614                                 bool found = false;
615                                 if (a) {
616                                         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
617                                                 if (iface->ia_addr[i].prefix > 64 ||
618                                                                 iface->ia_addr[i].preferred <= (uint32_t)now)
619                                                         continue;
620
621                                                 struct in6_addr addr = iface->ia_addr[i].addr;
622                                                 if (ia->type == htons(DHCPV6_OPT_IA_PD)) {
623                                                         addr.s6_addr32[1] |= htonl(a->assigned);
624
625                                                         if (IN6_ARE_ADDR_EQUAL(&p->addr, &addr) &&
626                                                                         p->prefix == a->length)
627                                                                 found = true;
628                                                 } else {
629                                                         addr.s6_addr32[3] = htonl(a->assigned);
630
631                                                         if (IN6_ARE_ADDR_EQUAL(&n->addr, &addr))
632                                                                 found = true;
633                                                 }
634                                         }
635                                 }
636
637                                 if (!found) {
638                                         if (otype == DHCPV6_OPT_IA_PREFIX) {
639                                                 struct dhcpv6_ia_prefix inv = {
640                                                         .type = htons(DHCPV6_OPT_IA_PREFIX),
641                                                         .len = htons(sizeof(inv) - 4),
642                                                         .preferred = 0,
643                                                         .valid = 0,
644                                                         .prefix = p->prefix,
645                                                         .addr = p->addr
646                                                 };
647
648                                                 if (datalen + sizeof(inv) > buflen)
649                                                         continue;
650
651                                                 memcpy(buf + datalen, &inv, sizeof(inv));
652                                                 datalen += sizeof(inv);
653                                         } else {
654                                                 struct dhcpv6_ia_addr inv = {
655                                                         .type = htons(DHCPV6_OPT_IA_ADDR),
656                                                         .len = htons(sizeof(inv) - 4),
657                                                         .addr = n->addr,
658                                                         .preferred = 0,
659                                                         .valid = 0
660                                                 };
661
662                                                 if (datalen + sizeof(inv) > buflen)
663                                                         continue;
664
665                                                 memcpy(buf + datalen, &inv, sizeof(inv));
666                                                 datalen += sizeof(inv);
667                                         }
668                                 }
669                         }
670                 }
671         }
672
673         out.len = htons(datalen - 4);
674         memcpy(buf, &out, sizeof(out));
675         return datalen;
676 }
677
678
679 size_t dhcpv6_handle_ia(uint8_t *buf, size_t buflen, struct interface *iface,
680                 const struct sockaddr_in6 *addr, const void *data, const uint8_t *end)
681 {
682         time_t now = odhcpd_time();
683         size_t response_len = 0;
684         const struct dhcpv6_client_header *hdr = data;
685         uint8_t *start = (uint8_t*)&hdr[1], *odata;
686         uint16_t otype, olen;
687
688         // Find and parse client-id and hostname
689         bool accept_reconf = false;
690         uint8_t *clid_data = NULL, clid_len = 0, mac[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
691         char hostname[256];
692         size_t hostname_len = 0;
693         dhcpv6_for_each_option(start, end, otype, olen, odata) {
694                 if (otype == DHCPV6_OPT_CLIENTID) {
695                         clid_data = odata;
696                         clid_len = olen;
697
698                         if (olen == 14 && odata[0] == 0 && odata[1] == 1)
699                                 memcpy(mac, &odata[8], sizeof(mac));
700                         else if (olen == 10 && odata[0] == 0 && odata[1] == 3)
701                                 memcpy(mac, &odata[4], sizeof(mac));
702                 } else if (otype == DHCPV6_OPT_FQDN && olen >= 2 && olen <= 255) {
703                         uint8_t fqdn_buf[256];
704                         memcpy(fqdn_buf, odata, olen);
705                         fqdn_buf[olen++] = 0;
706
707                         if (dn_expand(&fqdn_buf[1], &fqdn_buf[olen], &fqdn_buf[1], hostname, sizeof(hostname)) > 0)
708                                 hostname_len = strcspn(hostname, ".");
709                 } else if (otype == DHCPV6_OPT_RECONF_ACCEPT) {
710                         accept_reconf = true;
711                 }
712         }
713
714         if (!clid_data || !clid_len || clid_len > 130)
715                 goto out;
716
717         update(iface);
718         bool update_state = false;
719
720         struct dhcpv6_assignment *first = NULL;
721         dhcpv6_for_each_option(start, end, otype, olen, odata) {
722                 bool is_pd = (otype == DHCPV6_OPT_IA_PD);
723                 bool is_na = (otype == DHCPV6_OPT_IA_NA);
724                 if (!is_pd && !is_na)
725                         continue;
726
727                 struct dhcpv6_ia_hdr *ia = (struct dhcpv6_ia_hdr*)&odata[-4];
728                 size_t ia_response_len = 0;
729                 uint8_t reqlen = (is_pd) ? 62 : 128;
730                 uint32_t reqhint = 0;
731
732                 // Parse request hint for IA-PD
733                 if (is_pd) {
734                         uint8_t *sdata;
735                         uint16_t stype, slen;
736                         dhcpv6_for_each_option(&ia[1], odata + olen, stype, slen, sdata) {
737                                 if (stype == DHCPV6_OPT_IA_PREFIX && slen >= sizeof(struct dhcpv6_ia_prefix) - 4) {
738                                         struct dhcpv6_ia_prefix *p = (struct dhcpv6_ia_prefix*)&sdata[-4];
739                                         if (p->prefix) {
740                                                 reqlen = p->prefix;
741                                                 reqhint = ntohl(p->addr.s6_addr32[1]);
742                                                 if (reqlen > 32 && reqlen <= 64)
743                                                         reqhint &= (1U << (64 - reqlen)) - 1;
744                                         }
745                                         break;
746                                 }
747                         }
748
749                         if (reqlen > 64)
750                                 reqlen = 64;
751                 }
752
753                 // Find assignment
754                 struct dhcpv6_assignment *c, *a = NULL;
755                 list_for_each_entry(c, &iface->ia_assignments, head) {
756                         if (((c->clid_len == clid_len && !memcmp(c->clid_data, clid_data, clid_len)) ||
757                                         (c->clid_len >= clid_len && !c->clid_data[0] && !c->clid_data[1]
758                                                 && !memcmp(c->mac, mac, sizeof(mac)))) &&
759                                         (c->iaid == ia->iaid || c->valid_until < now) &&
760                                         ((is_pd && c->length <= 64) || (is_na && c->length == 128))) {
761                                 a = c;
762
763                                 // Reset state
764                                 apply_lease(iface, a, false);
765                                 memcpy(a->clid_data, clid_data, clid_len);
766                                 a->clid_len = clid_len;
767                                 a->iaid = ia->iaid;
768                                 a->peer = *addr;
769                                 a->reconf_cnt = 0;
770                                 a->reconf_sent = 0;
771                                 break;
772                         }
773                 }
774
775                 // Generic message handling
776                 uint16_t status = DHCPV6_STATUS_OK;
777                 if (hdr->msg_type == DHCPV6_MSG_SOLICIT || hdr->msg_type == DHCPV6_MSG_REQUEST) {
778                         bool assigned = !!a;
779
780                         if (!a && !iface->no_dynamic_dhcp) { // Create new binding
781                                 a = calloc(1, sizeof(*a) + clid_len);
782                                 a->clid_len = clid_len;
783                                 a->iaid = ia->iaid;
784                                 a->length = reqlen;
785                                 a->peer = *addr;
786                                 a->assigned = reqhint;
787                                 if (first)
788                                         memcpy(a->key, first->key, sizeof(a->key));
789                                 else
790                                         odhcpd_urandom(a->key, sizeof(a->key));
791                                 memcpy(a->clid_data, clid_data, clid_len);
792
793                                 if (is_pd)
794                                         while (!(assigned = assign_pd(iface, a)) && ++a->length <= 64);
795                                 else
796                                         assigned = assign_na(iface, a);
797                         }
798
799                         if (!assigned || iface->ia_addr_len == 0) { // Set error status
800                                 status = (is_pd) ? DHCPV6_STATUS_NOPREFIXAVAIL : DHCPV6_STATUS_NOADDRSAVAIL;
801                         } else if (assigned && !first) { //
802                                 size_t handshake_len = 4;
803                                 buf[0] = 0;
804                                 buf[1] = DHCPV6_OPT_RECONF_ACCEPT;
805                                 buf[2] = 0;
806                                 buf[3] = 0;
807
808                                 if (hdr->msg_type == DHCPV6_MSG_REQUEST) {
809                                         struct dhcpv6_auth_reconfigure auth = {
810                                                 htons(DHCPV6_OPT_AUTH),
811                                                 htons(sizeof(auth) - 4),
812                                                 3, 1, 0,
813                                                 {htonl(time(NULL)), htonl(++serial)},
814                                                 1,
815                                                 {0}
816                                         };
817                                         memcpy(auth.key, a->key, sizeof(a->key));
818                                         memcpy(buf + handshake_len, &auth, sizeof(auth));
819                                         handshake_len += sizeof(auth);
820                                 }
821
822                                 buf += handshake_len;
823                                 buflen -= handshake_len;
824                                 response_len += handshake_len;
825
826                                 first = a;
827                         }
828
829                         ia_response_len = append_reply(buf, buflen, status, ia, a, iface, true);
830
831                         // Was only a solicitation: mark binding for removal
832                         if (assigned && hdr->msg_type == DHCPV6_MSG_SOLICIT) {
833                                 a->valid_until = 0;
834                         } else if (assigned && hdr->msg_type == DHCPV6_MSG_REQUEST) {
835                                 if (hostname_len > 0) {
836                                         a->hostname = realloc(a->hostname, hostname_len + 1);
837                                         memcpy(a->hostname, hostname, hostname_len);
838                                         a->hostname[hostname_len] = 0;
839                                 }
840                                 a->accept_reconf = accept_reconf;
841                                 apply_lease(iface, a, true);
842                                 update_state = true;
843                         } else if (!assigned && a) { // Cleanup failed assignment
844                                 free(a->hostname);
845                                 free(a);
846                         }
847                 } else if (hdr->msg_type == DHCPV6_MSG_RENEW ||
848                                 hdr->msg_type == DHCPV6_MSG_RELEASE ||
849                                 hdr->msg_type == DHCPV6_MSG_REBIND ||
850                                 hdr->msg_type == DHCPV6_MSG_DECLINE) {
851                         if (!a && hdr->msg_type != DHCPV6_MSG_REBIND) {
852                                 status = DHCPV6_STATUS_NOBINDING;
853                                 ia_response_len = append_reply(buf, buflen, status, ia, a, iface, false);
854                         } else if (hdr->msg_type == DHCPV6_MSG_RENEW ||
855                                         hdr->msg_type == DHCPV6_MSG_REBIND) {
856                                 ia_response_len = append_reply(buf, buflen, status, ia, a, iface, false);
857                                 if (a)
858                                         apply_lease(iface, a, true);
859                         } else if (hdr->msg_type == DHCPV6_MSG_RELEASE) {
860                                 a->valid_until = 0;
861                                 apply_lease(iface, a, false);
862                                 update_state = true;
863                         } else if (hdr->msg_type == DHCPV6_MSG_DECLINE && a->length == 128) {
864                                 a->clid_len = 0;
865                                 a->valid_until = now + 3600; // Block address for 1h
866                                 update_state = true;
867                         }
868                 } else if (hdr->msg_type == DHCPV6_MSG_CONFIRM) {
869                         // Always send NOTONLINK for CONFIRM so that clients restart connection
870                         status = DHCPV6_STATUS_NOTONLINK;
871                         ia_response_len = append_reply(buf, buflen, status, ia, a, iface, true);
872                 }
873
874                 buf += ia_response_len;
875                 buflen -= ia_response_len;
876                 response_len += ia_response_len;
877         }
878
879         if (hdr->msg_type == DHCPV6_MSG_RELEASE && response_len + 6 < buflen) {
880                 buf[0] = 0;
881                 buf[1] = DHCPV6_OPT_STATUS;
882                 buf[2] = 0;
883                 buf[3] = 2;
884                 buf[4] = 0;
885                 buf[5] = DHCPV6_STATUS_OK;
886                 response_len += 6;
887         }
888
889         if (update_state)
890                 dhcpv6_write_statefile();
891
892 out:
893         return response_len;
894 }