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