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