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