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