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