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