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