Initial 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 > now + 7200) != (iface->ia_addr[i].valid > now + 7200))
412                         change = true;
413
414         if (change) {
415                 struct dhcpv6_assignment *c;
416                 list_for_each_entry(c, &iface->ia_assignments, head)
417                         if (c != border)
418                                 apply_lease(iface, c, false);
419         }
420
421         memcpy(iface->ia_addr, addr, len * sizeof(*addr));
422         iface->ia_addr_len = len;
423
424         if (change) { // Addresses / prefixes have changed
425                 struct list_head reassign = LIST_HEAD_INIT(reassign);
426                 struct dhcpv6_assignment *c, *d;
427                 list_for_each_entry_safe(c, d, &iface->ia_assignments, head) {
428                         if (c->clid_len == 0 || c->valid_until < now)
429                                 continue;
430
431                         if (c->length < 128 && c->assigned >= border->assigned && c != border)
432                                 list_move(&c->head, &reassign);
433                         else if (c != border)
434                                 apply_lease(iface, c, true);
435
436                         if (c->accept_reconf && c->reconf_cnt == 0) {
437                                 c->reconf_cnt = 1;
438                                 c->reconf_sent = now;
439                                 send_reconf(iface, c);
440
441                                 // Leave all other assignments of that client alone
442                                 struct dhcpv6_assignment *a;
443                                 list_for_each_entry(a, &iface->ia_assignments, head)
444                                         if (a != c && a->clid_len == c->clid_len &&
445                                                         !memcmp(a->clid_data, c->clid_data, a->clid_len))
446                                                 c->reconf_cnt = INT_MAX;
447                         }
448                 }
449
450                 while (!list_empty(&reassign)) {
451                         c = list_first_entry(&reassign, struct dhcpv6_assignment, head);
452                         list_del(&c->head);
453                         if (!assign_pd(iface, c)) {
454                                 c->assigned = 0;
455                                 list_add(&c->head, &iface->ia_assignments);
456                         }
457                 }
458
459                 dhcpv6_write_statefile();
460         }
461 }
462
463
464 static void reconf_timer(struct uloop_timeout *event)
465 {
466         time_t now = odhcpd_time();
467         struct interface *iface;
468         list_for_each_entry(iface, &interfaces, head) {
469                 if (iface->dhcpv6 != RELAYD_SERVER || iface->ia_assignments.next == NULL)
470                         continue;
471
472                 struct dhcpv6_assignment *a, *n;
473                 list_for_each_entry_safe(a, n, &iface->ia_assignments, head) {
474                         if (a->valid_until < now) {
475                                 if ((a->length < 128 && a->clid_len > 0) ||
476                                                 (a->length == 128 && a->clid_len == 0)) {
477                                         list_del(&a->head);
478                                         free(a->hostname);
479                                         free(a);
480                                 }
481                         } else if (a->reconf_cnt > 0 && a->reconf_cnt < 8 &&
482                                         now > a->reconf_sent + (1 << a->reconf_cnt)) {
483                                 ++a->reconf_cnt;
484                                 a->reconf_sent = now;
485                                 send_reconf(iface, a);
486                         }
487                 }
488
489                 if (iface->ia_reconf) {
490                         update(iface);
491                         iface->ia_reconf = false;
492                 }
493         }
494
495         uloop_timeout_set(event, 2000);
496 }
497
498
499 static size_t append_reply(uint8_t *buf, size_t buflen, uint16_t status,
500                 const struct dhcpv6_ia_hdr *ia, struct dhcpv6_assignment *a,
501                 struct interface *iface, bool request)
502 {
503         if (buflen < sizeof(*ia) + sizeof(struct dhcpv6_ia_prefix))
504                 return 0;
505
506         struct dhcpv6_ia_hdr out = {ia->type, 0, ia->iaid, 0, 0};
507         size_t datalen = sizeof(out);
508         time_t now = odhcpd_time();
509
510         if (status) {
511                 struct __attribute__((packed)) {
512                         uint16_t type;
513                         uint16_t len;
514                         uint16_t value;
515                 } stat = {htons(DHCPV6_OPT_STATUS), htons(sizeof(stat) - 4),
516                                 htons(status)};
517
518                 memcpy(buf + datalen, &stat, sizeof(stat));
519                 datalen += sizeof(stat);
520         } else {
521                 if (a) {
522                         uint32_t pref = 3600;
523                         uint32_t valid = 3600;
524                         bool have_non_ula = false;
525                         for (size_t i = 0; i < iface->ia_addr_len; ++i)
526                                 if ((iface->ia_addr[i].addr.s6_addr[0] & 0xfe) != 0xfc)
527                                         have_non_ula = true;
528
529                         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
530                                 uint32_t prefix_pref = iface->ia_addr[i].preferred - now;
531                                 uint32_t prefix_valid = iface->ia_addr[i].valid - now;
532
533                                 if (iface->ia_addr[i].prefix > 64 ||
534                                                 iface->ia_addr[i].preferred <= (uint32_t)now)
535                                         continue;
536
537                                 // ULA-deprecation compatibility workaround
538                                 if ((iface->ia_addr[i].addr.s6_addr[0] & 0xfe) == 0xfc &&
539                                                 a->length == 128 && have_non_ula &&
540                                                 iface->deprecate_ula_if_public_avail)
541                                         continue;
542
543                                 if (prefix_pref > 86400)
544                                         prefix_pref = 86400;
545
546                                 if (prefix_valid > 86400)
547                                         prefix_valid = 86400;
548
549                                 if (a->length < 128) {
550                                         struct dhcpv6_ia_prefix p = {
551                                                 .type = htons(DHCPV6_OPT_IA_PREFIX),
552                                                 .len = htons(sizeof(p) - 4),
553                                                 .preferred = htonl(prefix_pref),
554                                                 .valid = htonl(prefix_valid),
555                                                 .prefix = a->length,
556                                                 .addr = iface->ia_addr[i].addr
557                                         };
558                                         p.addr.s6_addr32[1] |= htonl(a->assigned);
559
560                                         if (datalen + sizeof(p) > buflen || a->assigned == 0)
561                                                 continue;
562
563                                         memcpy(buf + datalen, &p, sizeof(p));
564                                         datalen += sizeof(p);
565                                 } else {
566                                         struct dhcpv6_ia_addr n = {
567                                                 .type = htons(DHCPV6_OPT_IA_ADDR),
568                                                 .len = htons(sizeof(n) - 4),
569                                                 .addr = iface->ia_addr[i].addr,
570                                                 .preferred = htonl(prefix_pref),
571                                                 .valid = htonl(prefix_valid)
572                                         };
573                                         n.addr.s6_addr32[3] = htonl(a->assigned);
574
575                                         if (datalen + sizeof(n) > buflen || a->assigned == 0)
576                                                 continue;
577
578                                         memcpy(buf + datalen, &n, sizeof(n));
579                                         datalen += sizeof(n);
580                                 }
581
582                                 // Calculate T1 / T2 based on non-deprecated addresses
583                                 if (prefix_pref > 0) {
584                                         if (prefix_pref < pref)
585                                                 pref = prefix_pref;
586
587                                         if (prefix_valid < valid)
588                                                 valid = prefix_valid;
589                                 }
590                         }
591
592                         a->valid_until = valid + now;
593                         out.t1 = htonl(pref * 5 / 10);
594                         out.t2 = htonl(pref * 8 / 10);
595
596                         if (!out.t1)
597                                 out.t1 = htonl(1);
598
599                         if (!out.t2)
600                                 out.t2 = htonl(1);
601                 }
602
603                 if (!request) {
604                         uint8_t *odata, *end = ((uint8_t*)ia) + htons(ia->len) + 4;
605                         uint16_t otype, olen;
606                         dhcpv6_for_each_option((uint8_t*)&ia[1], end, otype, olen, odata) {
607                                 struct dhcpv6_ia_prefix *p = (struct dhcpv6_ia_prefix*)&odata[-4];
608                                 struct dhcpv6_ia_addr *n = (struct dhcpv6_ia_addr*)&odata[-4];
609                                 if ((otype != DHCPV6_OPT_IA_PREFIX || olen < sizeof(*p) - 4) &&
610                                                 (otype != DHCPV6_OPT_IA_ADDR || olen < sizeof(*n) - 4))
611                                         continue;
612
613                                 bool found = false;
614                                 if (a) {
615                                         for (size_t i = 0; i < iface->ia_addr_len; ++i) {
616                                                 if (iface->ia_addr[i].prefix > 64 ||
617                                                                 iface->ia_addr[i].preferred <= (uint32_t)now)
618                                                         continue;
619
620                                                 struct in6_addr addr = iface->ia_addr[i].addr;
621                                                 if (ia->type == htons(DHCPV6_OPT_IA_PD)) {
622                                                         addr.s6_addr32[1] |= htonl(a->assigned);
623
624                                                         if (IN6_ARE_ADDR_EQUAL(&p->addr, &addr) &&
625                                                                         p->prefix == a->length)
626                                                                 found = true;
627                                                 } else {
628                                                         addr.s6_addr32[3] = htonl(a->assigned);
629
630                                                         if (IN6_ARE_ADDR_EQUAL(&n->addr, &addr))
631                                                                 found = true;
632                                                 }
633                                         }
634                                 }
635
636                                 if (!found) {
637                                         if (otype == DHCPV6_OPT_IA_PREFIX) {
638                                                 struct dhcpv6_ia_prefix inv = {
639                                                         .type = htons(DHCPV6_OPT_IA_PREFIX),
640                                                         .len = htons(sizeof(inv) - 4),
641                                                         .preferred = 0,
642                                                         .valid = 0,
643                                                         .prefix = p->prefix,
644                                                         .addr = p->addr
645                                                 };
646
647                                                 if (datalen + sizeof(inv) > buflen)
648                                                         continue;
649
650                                                 memcpy(buf + datalen, &inv, sizeof(inv));
651                                                 datalen += sizeof(inv);
652                                         } else {
653                                                 struct dhcpv6_ia_addr inv = {
654                                                         .type = htons(DHCPV6_OPT_IA_ADDR),
655                                                         .len = htons(sizeof(inv) - 4),
656                                                         .addr = n->addr,
657                                                         .preferred = 0,
658                                                         .valid = 0
659                                                 };
660
661                                                 if (datalen + sizeof(inv) > buflen)
662                                                         continue;
663
664                                                 memcpy(buf + datalen, &inv, sizeof(inv));
665                                                 datalen += sizeof(inv);
666                                         }
667                                 }
668                         }
669                 }
670         }
671
672         out.len = htons(datalen - 4);
673         memcpy(buf, &out, sizeof(out));
674         return datalen;
675 }
676
677
678 size_t dhcpv6_handle_ia(uint8_t *buf, size_t buflen, struct interface *iface,
679                 const struct sockaddr_in6 *addr, const void *data, const uint8_t *end)
680 {
681         time_t now = odhcpd_time();
682         size_t response_len = 0;
683         const struct dhcpv6_client_header *hdr = data;
684         uint8_t *start = (uint8_t*)&hdr[1], *odata;
685         uint16_t otype, olen;
686
687         // Find and parse client-id and hostname
688         bool accept_reconf = false;
689         uint8_t *clid_data = NULL, clid_len = 0, mac[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
690         char hostname[256];
691         size_t hostname_len = 0;
692         dhcpv6_for_each_option(start, end, otype, olen, odata) {
693                 if (otype == DHCPV6_OPT_CLIENTID) {
694                         clid_data = odata;
695                         clid_len = olen;
696
697                         if (olen == 14 && odata[0] == 0 && odata[1] == 1)
698                                 memcpy(mac, &odata[8], sizeof(mac));
699                         else if (olen == 10 && odata[0] == 0 && odata[1] == 3)
700                                 memcpy(mac, &odata[4], sizeof(mac));
701                 } else if (otype == DHCPV6_OPT_FQDN && olen >= 2 && olen <= 255) {
702                         uint8_t fqdn_buf[256];
703                         memcpy(fqdn_buf, odata, olen);
704                         fqdn_buf[olen++] = 0;
705
706                         if (dn_expand(&fqdn_buf[1], &fqdn_buf[olen], &fqdn_buf[1], hostname, sizeof(hostname)) > 0)
707                                 hostname_len = strcspn(hostname, ".");
708                 } else if (otype == DHCPV6_OPT_RECONF_ACCEPT) {
709                         accept_reconf = true;
710                 }
711         }
712
713         if (!clid_data || !clid_len || clid_len > 130)
714                 goto out;
715
716         update(iface);
717         bool update_state = false;
718
719         struct dhcpv6_assignment *first = NULL;
720         dhcpv6_for_each_option(start, end, otype, olen, odata) {
721                 bool is_pd = (otype == DHCPV6_OPT_IA_PD);
722                 bool is_na = (otype == DHCPV6_OPT_IA_NA);
723                 if (!is_pd && !is_na)
724                         continue;
725
726                 struct dhcpv6_ia_hdr *ia = (struct dhcpv6_ia_hdr*)&odata[-4];
727                 size_t ia_response_len = 0;
728                 uint8_t reqlen = (is_pd) ? 62 : 128;
729                 uint32_t reqhint = 0;
730
731                 // Parse request hint for IA-PD
732                 if (is_pd) {
733                         uint8_t *sdata;
734                         uint16_t stype, slen;
735                         dhcpv6_for_each_option(&ia[1], odata + olen, stype, slen, sdata) {
736                                 if (stype == DHCPV6_OPT_IA_PREFIX && slen >= sizeof(struct dhcpv6_ia_prefix) - 4) {
737                                         struct dhcpv6_ia_prefix *p = (struct dhcpv6_ia_prefix*)&sdata[-4];
738                                         if (p->prefix) {
739                                                 reqlen = p->prefix;
740                                                 reqhint = ntohl(p->addr.s6_addr32[1]);
741                                                 if (reqlen > 32 && reqlen <= 64)
742                                                         reqhint &= (1U << (64 - reqlen)) - 1;
743                                         }
744                                         break;
745                                 }
746                         }
747
748                         if (reqlen > 64)
749                                 reqlen = 64;
750                 }
751
752                 // Find assignment
753                 struct dhcpv6_assignment *c, *a = NULL;
754                 list_for_each_entry(c, &iface->ia_assignments, head) {
755                         if (((c->clid_len == clid_len && !memcmp(c->clid_data, clid_data, clid_len)) ||
756                                         (c->clid_len >= clid_len && !c->clid_data[0] && !c->clid_data[1]
757                                                 && !memcmp(c->mac, mac, sizeof(mac)))) &&
758                                         (c->iaid == ia->iaid || c->valid_until < now) &&
759                                         ((is_pd && c->length <= 64) || (is_na && c->length == 128))) {
760                                 a = c;
761
762                                 // Reset state
763                                 apply_lease(iface, a, false);
764                                 memcpy(a->clid_data, clid_data, clid_len);
765                                 a->clid_len = clid_len;
766                                 a->iaid = ia->iaid;
767                                 a->peer = *addr;
768                                 a->reconf_cnt = 0;
769                                 a->reconf_sent = 0;
770                                 break;
771                         }
772                 }
773
774                 // Generic message handling
775                 uint16_t status = DHCPV6_STATUS_OK;
776                 if (hdr->msg_type == DHCPV6_MSG_SOLICIT || hdr->msg_type == DHCPV6_MSG_REQUEST) {
777                         bool assigned = !!a;
778
779                         if (!a && !iface->no_dynamic_dhcp) { // Create new binding
780                                 a = calloc(1, sizeof(*a) + clid_len);
781                                 a->clid_len = clid_len;
782                                 a->iaid = ia->iaid;
783                                 a->length = reqlen;
784                                 a->peer = *addr;
785                                 a->assigned = reqhint;
786                                 if (first)
787                                         memcpy(a->key, first->key, sizeof(a->key));
788                                 else
789                                         odhcpd_urandom(a->key, sizeof(a->key));
790                                 memcpy(a->clid_data, clid_data, clid_len);
791
792                                 if (is_pd)
793                                         while (!(assigned = assign_pd(iface, a)) && ++a->length <= 64);
794                                 else
795                                         assigned = assign_na(iface, a);
796                         }
797
798                         if (!assigned || iface->ia_addr_len == 0) { // Set error status
799                                 status = (is_pd) ? DHCPV6_STATUS_NOPREFIXAVAIL : DHCPV6_STATUS_NOADDRSAVAIL;
800                         } else if (assigned && !first) { //
801                                 size_t handshake_len = 4;
802                                 buf[0] = 0;
803                                 buf[1] = DHCPV6_OPT_RECONF_ACCEPT;
804                                 buf[2] = 0;
805                                 buf[3] = 0;
806
807                                 if (hdr->msg_type == DHCPV6_MSG_REQUEST) {
808                                         struct dhcpv6_auth_reconfigure auth = {
809                                                 htons(DHCPV6_OPT_AUTH),
810                                                 htons(sizeof(auth) - 4),
811                                                 3, 1, 0,
812                                                 {htonl(time(NULL)), htonl(++serial)},
813                                                 1,
814                                                 {0}
815                                         };
816                                         memcpy(auth.key, a->key, sizeof(a->key));
817                                         memcpy(buf + handshake_len, &auth, sizeof(auth));
818                                         handshake_len += sizeof(auth);
819                                 }
820
821                                 buf += handshake_len;
822                                 buflen -= handshake_len;
823                                 response_len += handshake_len;
824
825                                 first = a;
826                         }
827
828                         ia_response_len = append_reply(buf, buflen, status, ia, a, iface, true);
829
830                         // Was only a solicitation: mark binding for removal
831                         if (assigned && hdr->msg_type == DHCPV6_MSG_SOLICIT) {
832                                 a->valid_until = 0;
833                         } else if (assigned && hdr->msg_type == DHCPV6_MSG_REQUEST) {
834                                 if (hostname_len > 0) {
835                                         a->hostname = realloc(a->hostname, hostname_len + 1);
836                                         memcpy(a->hostname, hostname, hostname_len);
837                                         a->hostname[hostname_len] = 0;
838                                 }
839                                 a->accept_reconf = accept_reconf;
840                                 apply_lease(iface, a, true);
841                                 update_state = true;
842                         } else if (!assigned && a) { // Cleanup failed assignment
843                                 free(a->hostname);
844                                 free(a);
845                         }
846                 } else if (hdr->msg_type == DHCPV6_MSG_RENEW ||
847                                 hdr->msg_type == DHCPV6_MSG_RELEASE ||
848                                 hdr->msg_type == DHCPV6_MSG_REBIND ||
849                                 hdr->msg_type == DHCPV6_MSG_DECLINE) {
850                         if (!a && hdr->msg_type != DHCPV6_MSG_REBIND) {
851                                 status = DHCPV6_STATUS_NOBINDING;
852                                 ia_response_len = append_reply(buf, buflen, status, ia, a, iface, false);
853                         } else if (hdr->msg_type == DHCPV6_MSG_RENEW ||
854                                         hdr->msg_type == DHCPV6_MSG_REBIND) {
855                                 ia_response_len = append_reply(buf, buflen, status, ia, a, iface, false);
856                                 if (a)
857                                         apply_lease(iface, a, true);
858                         } else if (hdr->msg_type == DHCPV6_MSG_RELEASE) {
859                                 a->valid_until = 0;
860                                 apply_lease(iface, a, false);
861                                 update_state = true;
862                         } else if (hdr->msg_type == DHCPV6_MSG_DECLINE && a->length == 128) {
863                                 a->clid_len = 0;
864                                 a->valid_until = now + 3600; // Block address for 1h
865                                 update_state = true;
866                         }
867                 } else if (hdr->msg_type == DHCPV6_MSG_CONFIRM) {
868                         // Always send NOTONLINK for CONFIRM so that clients restart connection
869                         status = DHCPV6_STATUS_NOTONLINK;
870                         ia_response_len = append_reply(buf, buflen, status, ia, a, iface, true);
871                 }
872
873                 buf += ia_response_len;
874                 buflen -= ia_response_len;
875                 response_len += ia_response_len;
876         }
877
878         if (hdr->msg_type == DHCPV6_MSG_RELEASE && response_len + 6 < buflen) {
879                 buf[0] = 0;
880                 buf[1] = DHCPV6_OPT_STATUS;
881                 buf[2] = 0;
882                 buf[3] = 2;
883                 buf[4] = 0;
884                 buf[5] = DHCPV6_STATUS_OK;
885                 response_len += 6;
886         }
887
888         if (update_state)
889                 dhcpv6_write_statefile();
890
891 out:
892         return response_len;
893 }