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