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