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