]> git.decadent.org.uk Git - odhcp6c.git/blob - src/dhcpv6.c
Be less verbose when sending solicits
[odhcp6c.git] / src / dhcpv6.c
1 /**
2  * Copyright (C) 2012-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 <time.h>
16 #include <fcntl.h>
17 #include <errno.h>
18 #include <stdlib.h>
19 #include <signal.h>
20 #include <limits.h>
21 #include <resolv.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <syslog.h>
25 #include <stdbool.h>
26 #include <sys/time.h>
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30
31 #include <net/if.h>
32 #include <net/ethernet.h>
33
34 #include "odhcp6c.h"
35 #include "md5.h"
36
37
38 #define ALL_DHCPV6_RELAYS {{{0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
39                 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02}}}
40 #define DHCPV6_CLIENT_PORT 546
41 #define DHCPV6_SERVER_PORT 547
42 #define DHCPV6_DUID_LLADDR 3
43 #define DHCPV6_REQ_DELAY 1
44
45
46 static bool dhcpv6_response_is_valid(const void *buf, ssize_t len,
47                 const uint8_t transaction[3], enum dhcpv6_msg type);
48
49 static int dhcpv6_parse_ia(void *opt, void *end);
50
51 static int dhcpv6_calc_refresh_timers(void);
52 static void dhcpv6_handle_status_code(_unused const enum dhcpv6_msg orig,
53                 const uint16_t code, const void *status_msg, const int len,
54                 int *ret);
55 static void dhcpv6_handle_ia_status_code(const enum dhcpv6_msg orig,
56                 const struct dhcpv6_ia_hdr *ia_hdr, const uint16_t code,
57                 const void *status_msg, const int len,
58                 bool handled_status_codes[_DHCPV6_Status_Max],
59                 int *ret);
60
61 static reply_handler dhcpv6_handle_reply;
62 static reply_handler dhcpv6_handle_advert;
63 static reply_handler dhcpv6_handle_rebind_reply;
64 static reply_handler dhcpv6_handle_reconfigure;
65 static int dhcpv6_commit_advert(void);
66
67
68
69 // RFC 3315 - 5.5 Timeout and Delay values
70 static struct dhcpv6_retx dhcpv6_retx[_DHCPV6_MSG_MAX] = {
71         [DHCPV6_MSG_UNKNOWN] = {false, 1, 120, 0, "<POLL>",
72                         dhcpv6_handle_reconfigure, NULL},
73         [DHCPV6_MSG_SOLICIT] = {true, 1, 3600, 0, "SOLICIT",
74                         dhcpv6_handle_advert, dhcpv6_commit_advert},
75         [DHCPV6_MSG_REQUEST] = {true, 1, 30, 10, "REQUEST",
76                         dhcpv6_handle_reply, NULL},
77         [DHCPV6_MSG_RENEW] = {false, 10, 600, 0, "RENEW",
78                         dhcpv6_handle_reply, NULL},
79         [DHCPV6_MSG_REBIND] = {false, 10, 600, 0, "REBIND",
80                         dhcpv6_handle_rebind_reply, NULL},
81         [DHCPV6_MSG_RELEASE] = {false, 1, 0, 5, "RELEASE", NULL, NULL},
82         [DHCPV6_MSG_DECLINE] = {false, 1, 0, 5, "DECLINE", NULL, NULL},
83         [DHCPV6_MSG_INFO_REQ] = {true, 1, 120, 0, "INFOREQ",
84                         dhcpv6_handle_reply, NULL},
85 };
86
87
88 // Sockets
89 static int sock = -1;
90 static int ifindex = -1;
91 static int64_t t1 = 0, t2 = 0, t3 = 0;
92
93 // IA states
94 static int request_prefix = -1;
95 static enum odhcp6c_ia_mode na_mode = IA_MODE_NONE, pd_mode = IA_MODE_NONE;
96 static bool accept_reconfig = false;
97
98 // Reconfigure key
99 static uint8_t reconf_key[16];
100
101
102
103 int init_dhcpv6(const char *ifname, int request_pd, int sol_timeout)
104 {
105         request_prefix = request_pd;
106         dhcpv6_retx[DHCPV6_MSG_SOLICIT].max_timeo = sol_timeout;
107
108         sock = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
109
110         // Detect interface
111         struct ifreq ifr;
112         strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
113         if (ioctl(sock, SIOCGIFINDEX, &ifr))
114                 return -1;
115         ifindex = ifr.ifr_ifindex;
116
117         // Create client DUID
118         size_t client_id_len;
119         odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
120         if (client_id_len == 0) {
121                 ioctl(sock, SIOCGIFHWADDR, &ifr);
122                 uint8_t duid[14] = {0, DHCPV6_OPT_CLIENTID, 0, 10, 0,
123                                 DHCPV6_DUID_LLADDR, 0, 1};
124                 memcpy(&duid[8], ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
125
126                 uint8_t zero[ETHER_ADDR_LEN] = {0, 0, 0, 0, 0, 0};
127                 struct ifreq ifs[100], *ifp, *ifend;
128                 struct ifconf ifc;
129                 ifc.ifc_req = ifs;
130                 ifc.ifc_len = sizeof(ifs);
131
132                 if (!memcmp(&duid[8], zero, ETHER_ADDR_LEN) &&
133                                 ioctl(sock, SIOCGIFCONF, &ifc) >= 0) {
134                         // If our interface doesn't have an address...
135                         ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
136                         for (ifp = ifc.ifc_req; ifp < ifend &&
137                                         !memcmp(&duid[8], zero, 6); ifp++) {
138                                 memcpy(ifr.ifr_name, ifp->ifr_name,
139                                                 sizeof(ifr.ifr_name));
140                                 ioctl(sock, SIOCGIFHWADDR, &ifr);
141                                 memcpy(&duid[8], ifr.ifr_hwaddr.sa_data,
142                                                 ETHER_ADDR_LEN);
143                         }
144                 }
145
146                 odhcp6c_add_state(STATE_CLIENT_ID, duid, sizeof(duid));
147         }
148
149         // Create ORO
150         uint16_t oro[] = {
151                         htons(DHCPV6_OPT_SIP_SERVER_D),
152                         htons(DHCPV6_OPT_SIP_SERVER_A),
153                         htons(DHCPV6_OPT_DNS_SERVERS),
154                         htons(DHCPV6_OPT_DNS_DOMAIN),
155                         htons(DHCPV6_OPT_NTP_SERVER),
156                         htons(DHCPV6_OPT_SIP_SERVER_A),
157                         htons(DHCPV6_OPT_AFTR_NAME),
158                         htons(DHCPV6_OPT_PD_EXCLUDE),
159 #ifdef EXT_PREFIX_CLASS
160                         htons(DHCPV6_OPT_PREFIX_CLASS),
161 #endif
162         };
163         odhcp6c_add_state(STATE_ORO, oro, sizeof(oro));
164
165
166         // Configure IPv6-options
167         int val = 1;
168         setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &val, sizeof(val));
169         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
170         val = 0;
171         setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &val, sizeof(val));
172         setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen(ifname));
173
174         struct sockaddr_in6 client_addr = { .sin6_family = AF_INET6,
175                 .sin6_port = htons(DHCPV6_CLIENT_PORT), .sin6_flowinfo = 0 };
176         if (bind(sock, (struct sockaddr*)&client_addr, sizeof(client_addr)))
177                 return -1;
178
179         return 0;
180 }
181
182
183 void dhcpv6_set_ia_mode(enum odhcp6c_ia_mode na, enum odhcp6c_ia_mode pd)
184 {
185         na_mode = na;
186         pd_mode = pd;
187 }
188
189
190 static void dhcpv6_send(enum dhcpv6_msg type, uint8_t trid[3], uint32_t ecs)
191 {
192         // Build FQDN
193         char fqdn_buf[256];
194         gethostname(fqdn_buf, sizeof(fqdn_buf));
195         struct {
196                 uint16_t type;
197                 uint16_t len;
198                 uint8_t flags;
199                 uint8_t data[256];
200         } fqdn;
201         size_t fqdn_len = 5 + dn_comp(fqdn_buf, fqdn.data,
202                         sizeof(fqdn.data), NULL, NULL);
203         fqdn.type = htons(DHCPV6_OPT_FQDN);
204         fqdn.len = htons(fqdn_len - 4);
205         fqdn.flags = 0;
206
207
208         // Build Client ID
209         size_t cl_id_len;
210         void *cl_id = odhcp6c_get_state(STATE_CLIENT_ID, &cl_id_len);
211
212         // Get Server ID
213         size_t srv_id_len;
214         void *srv_id = odhcp6c_get_state(STATE_SERVER_ID, &srv_id_len);
215
216         // Build IA_PDs
217         size_t ia_pd_entries, ia_pd_len = 0;
218         struct odhcp6c_entry *e = odhcp6c_get_state(STATE_IA_PD, &ia_pd_entries);
219         ia_pd_entries /= sizeof(*e);
220         struct dhcpv6_ia_hdr hdr_ia_pd = {
221                 htons(DHCPV6_OPT_IA_PD),
222                 htons(sizeof(hdr_ia_pd) - 4),
223                 1, 0, 0
224         };
225
226
227         uint8_t *ia_pd = alloca(ia_pd_entries * (sizeof(struct dhcpv6_ia_prefix) + 10));
228         for (size_t i = 0; i < ia_pd_entries; ++i) {
229                 uint8_t ex_len = 0;
230                 if (e[i].priority > 0)
231                         ex_len = ((e[i].priority - e[i].length - 1) / 8) + 6;
232
233                 struct dhcpv6_ia_prefix p = {
234                         .type = htons(DHCPV6_OPT_IA_PREFIX),
235                         .len = htons(sizeof(p) - 4U + ex_len),
236                         .prefix = e[i].length,
237                         .addr = e[i].target
238                 };
239
240                 memcpy(ia_pd + ia_pd_len, &p, sizeof(p));
241                 ia_pd_len += sizeof(p);
242
243                 if (ex_len) {
244                         ia_pd[ia_pd_len++] = 0;
245                         ia_pd[ia_pd_len++] = DHCPV6_OPT_PD_EXCLUDE;
246                         ia_pd[ia_pd_len++] = 0;
247                         ia_pd[ia_pd_len++] = ex_len - 4;
248                         ia_pd[ia_pd_len++] = e[i].priority;
249
250                         uint32_t excl = ntohl(e[i].router.s6_addr32[1]);
251                         excl >>= (64 - e[i].priority);
252                         excl <<= 8 - ((e[i].priority - e[i].length) % 8);
253
254                         for (size_t i = ex_len - 5; i > 0; --i, excl >>= 8)
255                                 ia_pd[ia_pd_len + i] = excl & 0xff;
256                         ia_pd_len += ex_len - 5;
257                 }
258         }
259
260         struct dhcpv6_ia_prefix pref = {
261                 .type = htons(DHCPV6_OPT_IA_PREFIX),
262                 .len = htons(25), .prefix = request_prefix
263         };
264         if (request_prefix > 0 && ia_pd_len == 0 && type == DHCPV6_MSG_SOLICIT) {
265                 ia_pd = (uint8_t*)&pref;
266                 ia_pd_len = sizeof(pref);
267         }
268         hdr_ia_pd.len = htons(ntohs(hdr_ia_pd.len) + ia_pd_len);
269
270         // Build IA_NAs
271         size_t ia_na_entries, ia_na_len = 0;
272         void *ia_na = NULL;
273         e = odhcp6c_get_state(STATE_IA_NA, &ia_na_entries);
274         ia_na_entries /= sizeof(*e);
275
276         struct dhcpv6_ia_hdr hdr_ia_na = {
277                 htons(DHCPV6_OPT_IA_NA),
278                 htons(sizeof(hdr_ia_na) - 4),
279                 1, 0, 0
280         };
281
282         struct dhcpv6_ia_addr pa[ia_na_entries];
283         for (size_t i = 0; i < ia_na_entries; ++i) {
284                 pa[i].type = htons(DHCPV6_OPT_IA_ADDR);
285                 pa[i].len = htons(sizeof(pa[i]) - 4U);
286                 pa[i].addr = e[i].target;
287                 pa[i].preferred = 0;
288                 pa[i].valid = 0;
289         }
290
291         ia_na = pa;
292         ia_na_len = sizeof(pa);
293         hdr_ia_na.len = htons(ntohs(hdr_ia_na.len) + ia_na_len);
294
295         // Reconfigure Accept
296         struct {
297                 uint16_t type;
298                 uint16_t length;
299         } reconf_accept = {htons(DHCPV6_OPT_RECONF_ACCEPT), 0};
300
301         // Request Information Refresh
302         uint16_t oro_refresh = htons(DHCPV6_OPT_INFO_REFRESH);
303
304         // Prepare Header
305         size_t oro_len;
306         void *oro = odhcp6c_get_state(STATE_ORO, &oro_len);
307         struct {
308                 uint8_t type;
309                 uint8_t trid[3];
310                 uint16_t elapsed_type;
311                 uint16_t elapsed_len;
312                 uint16_t elapsed_value;
313                 uint16_t oro_type;
314                 uint16_t oro_len;
315         } hdr = {
316                 type, {trid[0], trid[1], trid[2]},
317                 htons(DHCPV6_OPT_ELAPSED), htons(2),
318                         htons((ecs > 0xffff) ? 0xffff : ecs),
319                 htons(DHCPV6_OPT_ORO), htons(oro_len),
320         };
321
322         struct iovec iov[] = {
323                 {&hdr, sizeof(hdr)},
324                 {oro, oro_len},
325                 {&oro_refresh, 0},
326                 {cl_id, cl_id_len},
327                 {srv_id, srv_id_len},
328                 {&reconf_accept, sizeof(reconf_accept)},
329                 {&fqdn, fqdn_len},
330                 {&hdr_ia_na, sizeof(hdr_ia_na)},
331                 {ia_na, ia_na_len},
332                 {&hdr_ia_pd, sizeof(hdr_ia_pd)},
333                 {ia_pd, ia_pd_len},
334         };
335
336         size_t cnt = ARRAY_SIZE(iov);
337         if (type == DHCPV6_MSG_INFO_REQ) {
338                 cnt = 5;
339                 iov[2].iov_len = sizeof(oro_refresh);
340                 hdr.oro_len = htons(oro_len + sizeof(oro_refresh));
341         } else if (!request_prefix) {
342                 cnt = 9;
343         }
344
345         // Disable IAs if not used
346         if (type != DHCPV6_MSG_SOLICIT) {
347                 iov[5].iov_len = 0;
348                 if (ia_na_len == 0)
349                         iov[7].iov_len = 0;
350                 if (ia_pd_len == 0)
351                         iov[9].iov_len = 0;
352         }
353
354         if (na_mode == IA_MODE_NONE)
355                 iov[7].iov_len = 0;
356
357         struct sockaddr_in6 srv = {AF_INET6, htons(DHCPV6_SERVER_PORT),
358                 0, ALL_DHCPV6_RELAYS, ifindex};
359         struct msghdr msg = {&srv, sizeof(srv), iov, cnt, NULL, 0, 0};
360
361         sendmsg(sock, &msg, 0);
362 }
363
364
365 static int64_t dhcpv6_rand_delay(int64_t time)
366 {
367         int random;
368         odhcp6c_random(&random, sizeof(random));
369         return (time * ((int64_t)random % 1000LL)) / 10000LL;
370 }
371
372
373 int dhcpv6_request(enum dhcpv6_msg type)
374 {
375         uint8_t buf[1536], rc = 0;
376         uint64_t timeout = UINT32_MAX;
377         struct dhcpv6_retx *retx = &dhcpv6_retx[type];
378
379         if (retx->delay) {
380                 struct timespec ts = {0, 0};
381                 ts.tv_nsec = dhcpv6_rand_delay(10 * DHCPV6_REQ_DELAY);
382                 nanosleep(&ts, NULL);
383         }
384
385         if (type == DHCPV6_MSG_UNKNOWN)
386                 timeout = t1;
387         else if (type == DHCPV6_MSG_RENEW)
388                 timeout = (t2 > t1) ? t2 - t1 : 0;
389         else if (type == DHCPV6_MSG_REBIND)
390                 timeout = (t3 > t2) ? t3 - t2 : 0;
391
392         if (timeout == 0)
393                 return -1;
394
395         syslog(LOG_NOTICE, "Starting %s transaction (timeout %llus, max rc %d)",
396                         retx->name, (unsigned long long)timeout, retx->max_rc);
397
398         uint64_t start = odhcp6c_get_milli_time(), round_start = start, elapsed;
399
400         // Generate transaction ID
401         uint8_t trid[3] = {0, 0, 0};
402         if (type != DHCPV6_MSG_UNKNOWN)
403                 odhcp6c_random(trid, sizeof(trid));
404         ssize_t len = -1;
405         int64_t rto = 0;
406
407         do {
408                 if (rto == 0) {
409                         int64_t delay = dhcpv6_rand_delay(retx->init_timeo * 1000);
410
411                         // First RT MUST be strictly greater than IRT for solicit messages (RFC3313 17.1.2)
412                         while (type == DHCPV6_MSG_SOLICIT && delay <= 0)
413                                 delay = dhcpv6_rand_delay(retx->init_timeo * 1000);
414
415                         rto = (retx->init_timeo * 1000 + delay);
416                 }
417                 else
418                         rto = (2 * rto + dhcpv6_rand_delay(rto));
419
420                 if (retx->max_timeo && (rto >= retx->max_timeo * 1000))
421                         rto = retx->max_timeo * 1000 +
422                                 dhcpv6_rand_delay(retx->max_timeo * 1000);
423
424                 // Calculate end for this round and elapsed time
425                 uint64_t round_end = round_start + rto;
426                 elapsed = round_start - start;
427
428                 // Don't wait too long
429                 if (round_end - start > timeout * 1000)
430                         round_end = timeout * 1000 + start;
431
432                 // Built and send package
433                 if (type != DHCPV6_MSG_UNKNOWN) {
434                         if (type != DHCPV6_MSG_SOLICIT)
435                                 syslog(LOG_NOTICE, "Send %s message (elapsed %llums, rc %d)",
436                                                 retx->name, (unsigned long long)elapsed, rc);
437                         dhcpv6_send(type, trid, elapsed / 10);
438                         rc++;
439                 }
440
441                 // Receive rounds
442                 for (; len < 0 && round_start < round_end;
443                                 round_start = odhcp6c_get_milli_time()) {
444                         // Check for pending signal
445                         if (odhcp6c_signal_process())
446                                 return -1;
447
448                         // Set timeout for receiving
449                         uint64_t t = round_end - round_start;
450                         struct timeval timeout = {t / 1000, (t % 1000) * 1000};
451                         setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
452                                         &timeout, sizeof(timeout));
453
454                         // Receive cycle
455                         len = recv(sock, buf, sizeof(buf), 0);
456
457                         if (!dhcpv6_response_is_valid(buf, len, trid, type))
458                                 len = -1;
459
460                         if (len > 0) {
461                                 uint8_t *opt = &buf[4];
462                                 uint8_t *opt_end = opt + len - 4;
463
464                                 round_start = odhcp6c_get_milli_time();
465                                 elapsed = round_start - start;
466                                 syslog(LOG_NOTICE, "Got a valid reply after "
467                                                 "%llums", (unsigned long long)elapsed);
468
469                                 if (retx->handler_reply)
470                                         len = retx->handler_reply(
471                                                         type, rc, opt, opt_end);
472
473                                 if (len > 0 && round_end - round_start > 1000)
474                                         round_end = 1000 + round_start;
475                         }
476                 }
477
478                 // Allow
479                 if (retx->handler_finish)
480                         len = retx->handler_finish();
481         } while (len < 0 && ((elapsed / 1000 < timeout) && (!retx->max_rc || rc < retx->max_rc)));
482
483         return len;
484 }
485
486
487 static bool dhcpv6_response_is_valid(const void *buf, ssize_t len,
488                 const uint8_t transaction[3], enum dhcpv6_msg type)
489 {
490         const struct dhcpv6_header *rep = buf;
491         if (len < (ssize_t)sizeof(*rep) || memcmp(rep->tr_id,
492                         transaction, sizeof(rep->tr_id)))
493                 return false; // Invalid reply
494
495         if (type == DHCPV6_MSG_SOLICIT) {
496                 if (rep->msg_type != DHCPV6_MSG_ADVERT &&
497                                 rep->msg_type != DHCPV6_MSG_REPLY)
498                         return false;
499         } else if (type == DHCPV6_MSG_UNKNOWN) {
500                 if (!accept_reconfig || rep->msg_type != DHCPV6_MSG_RECONF)
501                         return false;
502         } else if (rep->msg_type != DHCPV6_MSG_REPLY) {
503                 return false;
504         }
505
506         uint8_t *end = ((uint8_t*)buf) + len, *odata;
507         uint16_t otype, olen;
508         bool clientid_ok = false, serverid_ok = false, rcauth_ok = false;
509
510         size_t client_id_len, server_id_len;
511         void *client_id = odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
512         void *server_id = odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
513
514         dhcpv6_for_each_option(&rep[1], end, otype, olen, odata) {
515                 if (otype == DHCPV6_OPT_CLIENTID) {
516                         clientid_ok = (olen + 4U == client_id_len) && !memcmp(
517                                         &odata[-4], client_id, client_id_len);
518                 } else if (otype == DHCPV6_OPT_SERVERID) {
519                         serverid_ok = (olen + 4U == server_id_len) && !memcmp(
520                                         &odata[-4], server_id, server_id_len);
521                 } else if (otype == DHCPV6_OPT_AUTH && olen == -4 +
522                                 sizeof(struct dhcpv6_auth_reconfigure)) {
523                         struct dhcpv6_auth_reconfigure *r = (void*)&odata[-4];
524                         if (r->protocol != 3 || r->algorithm != 1 || r->reconf_type != 2)
525                                 continue;
526
527                         md5_state_t md5;
528                         uint8_t serverhash[16], secretbytes[16], hash[16];
529                         memcpy(serverhash, r->key, sizeof(serverhash));
530                         memset(r->key, 0, sizeof(r->key));
531                         memcpy(secretbytes, reconf_key, sizeof(secretbytes));
532
533                         for (size_t i = 0; i < sizeof(secretbytes); ++i)
534                                 secretbytes[i] ^= 0x36;
535
536                         md5_init(&md5);
537                         md5_append(&md5, secretbytes, sizeof(secretbytes));
538                         md5_append(&md5, buf, len);
539                         md5_finish(&md5, hash);
540
541                         for (size_t i = 0; i < sizeof(secretbytes); ++i) {
542                                 secretbytes[i] ^= 0x36;
543                                 secretbytes[i] ^= 0x5c;
544                         }
545
546                         md5_init(&md5);
547                         md5_append(&md5, secretbytes, sizeof(secretbytes));
548                         md5_append(&md5, hash, 16);
549                         md5_finish(&md5, hash);
550
551                         rcauth_ok = !memcmp(hash, serverhash, sizeof(hash));
552                 }
553         }
554
555         if (rep->msg_type == DHCPV6_MSG_RECONF && !rcauth_ok)
556                 return false;
557
558         return clientid_ok && (serverid_ok || server_id_len == 0);
559 }
560
561
562 int dhcpv6_poll_reconfigure(void)
563 {
564         int ret = dhcpv6_request(DHCPV6_MSG_UNKNOWN);
565         if (ret != -1)
566                 ret = dhcpv6_request(ret);
567
568         return ret;
569 }
570
571
572 static int dhcpv6_handle_reconfigure(_unused enum dhcpv6_msg orig, const int rc,
573                 const void *opt, const void *end)
574 {
575         // TODO: should verify the reconfigure message
576         uint16_t otype, olen;
577         uint8_t *odata, msg = DHCPV6_MSG_RENEW;
578         dhcpv6_for_each_option(opt, end, otype, olen, odata)
579                 if (otype == DHCPV6_OPT_RECONF_MESSAGE && olen == 1 && (
580                                 odata[0] == DHCPV6_MSG_RENEW ||
581                                 odata[0] == DHCPV6_MSG_INFO_REQ))
582                         msg = odata[0];
583
584         dhcpv6_handle_reply(DHCPV6_MSG_UNKNOWN, rc, NULL, NULL);
585         return msg;
586 }
587
588
589 // Collect all advertised servers
590 static int dhcpv6_handle_advert(enum dhcpv6_msg orig, const int rc,
591                 const void *opt, const void *end)
592 {
593         uint16_t olen, otype;
594         uint8_t *odata, pref = 0;
595         struct dhcpv6_server_cand cand = {false, false, 0, 0, {0}, NULL, NULL, 0, 0};
596         bool have_na = false;
597         int have_pd = 0;
598
599         dhcpv6_for_each_option(opt, end, otype, olen, odata) {
600                 if (orig == DHCPV6_MSG_SOLICIT &&
601                                 (otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA) &&
602                                 olen > sizeof(struct dhcpv6_ia_hdr)) {
603                         struct dhcpv6_ia_hdr *ia_hdr = (void*)(&odata[-4]);
604                         dhcpv6_parse_ia(ia_hdr, odata + olen + sizeof(*ia_hdr));
605                 }
606
607                 if (otype == DHCPV6_OPT_SERVERID && olen <= 130) {
608                         memcpy(cand.duid, odata, olen);
609                         cand.duid_len = olen;
610                 } else if (otype == DHCPV6_OPT_STATUS && olen >= 2) {
611                         int error = ((int)odata[0] << 8 | (int)odata[1]);
612
613                         switch (error) {
614                         case DHCPV6_NoPrefixAvail:
615                                 // Status code on global level
616                                 if (pd_mode == IA_MODE_FORCE)
617                                         return -1;
618                                 cand.preference -= 2000;
619                                 break;
620
621                         case DHCPV6_NoAddrsAvail:
622                                 // Status code on global level
623                                 if (na_mode == IA_MODE_FORCE)
624                                         return -1;
625                                 break;
626
627                         default :
628                                 break;
629                         }
630                 } else if (otype == DHCPV6_OPT_PREF && olen >= 1 &&
631                                 cand.preference >= 0) {
632                         cand.preference = pref = odata[0];
633                 } else if (otype == DHCPV6_OPT_RECONF_ACCEPT) {
634                         cand.wants_reconfigure = true;
635                 } else if (otype == DHCPV6_OPT_IA_PD && request_prefix) {
636                         struct dhcpv6_ia_hdr *h = (struct dhcpv6_ia_hdr*)&odata[-4];
637                         uint8_t *oend = odata + olen, *d;
638                         dhcpv6_for_each_option(&h[1], oend, otype, olen, d) {
639                                 if (otype == DHCPV6_OPT_IA_PREFIX && (olen + 4) >=
640                                                 (uint16_t)sizeof(struct dhcpv6_ia_prefix)) {
641                                         struct dhcpv6_ia_prefix *p = (struct dhcpv6_ia_prefix*)&d[-4];
642                                         have_pd = p->prefix;
643                                 }
644                         }
645                 } else if (otype == DHCPV6_OPT_IA_NA) {
646                         struct dhcpv6_ia_hdr *h = (struct dhcpv6_ia_hdr*)&odata[-4];
647                         uint8_t *oend = odata + olen, *d;
648                         dhcpv6_for_each_option(&h[1], oend, otype, olen, d)
649                                 if (otype == DHCPV6_OPT_IA_ADDR)
650                                         have_na = true;
651                 }
652         }
653
654         if ((!have_na && na_mode == IA_MODE_FORCE) ||
655                         (!have_pd && pd_mode == IA_MODE_FORCE))
656                 return -1;
657
658         if (na_mode != IA_MODE_NONE && !have_na) {
659                 cand.has_noaddravail = true;
660                 cand.preference -= 1000;
661         }
662
663         if (pd_mode != IA_MODE_NONE) {
664                 if (have_pd)
665                         cand.preference += 2000 + (128 - have_pd);
666                 else
667                         cand.preference -= 2000;
668         }
669
670         if (cand.duid_len > 0) {
671                 cand.ia_na = odhcp6c_move_state(STATE_IA_NA, &cand.ia_na_len);
672                 cand.ia_pd = odhcp6c_move_state(STATE_IA_PD, &cand.ia_pd_len);
673                 odhcp6c_add_state(STATE_SERVER_CAND, &cand, sizeof(cand));
674         }
675
676         if (orig == DHCPV6_MSG_SOLICIT) {
677                 odhcp6c_clear_state(STATE_IA_NA);
678                 odhcp6c_clear_state(STATE_IA_PD);
679         }
680
681         return (rc > 1 || (pref == 255 && cand.preference > 0)) ? 1 : -1;
682 }
683
684
685 static int dhcpv6_commit_advert(void)
686 {
687         size_t cand_len;
688         struct dhcpv6_server_cand *c = NULL, *cand =
689                         odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
690
691         bool retry = false;
692         for (size_t i = 0; i < cand_len / sizeof(*c); ++i) {
693                 if (cand[i].has_noaddravail)
694                         retry = true; // We want to try again
695
696                 if (!c || c->preference < cand[i].preference)
697                         c = &cand[i];
698         }
699
700         if (retry && na_mode == IA_MODE_TRY) {
701                 // We give it a second try without the IA_NA
702                 na_mode = IA_MODE_NONE;
703                 return dhcpv6_request(DHCPV6_MSG_SOLICIT);
704         }
705
706         if (c) {
707                 uint16_t hdr[2] = {htons(DHCPV6_OPT_SERVERID),
708                                 htons(c->duid_len)};
709                 odhcp6c_add_state(STATE_SERVER_ID, hdr, sizeof(hdr));
710                 odhcp6c_add_state(STATE_SERVER_ID, c->duid, c->duid_len);
711                 accept_reconfig = c->wants_reconfigure;
712                 if (c->ia_na_len)
713                         odhcp6c_add_state(STATE_IA_NA, c->ia_na, c->ia_na_len);
714                 if (c->ia_pd_len)
715                         odhcp6c_add_state(STATE_IA_PD, c->ia_pd, c->ia_pd_len);
716         }
717
718         for (size_t i = 0; i < cand_len / sizeof(*c); ++i) {
719                 free(cand[i].ia_na);
720                 free(cand[i].ia_pd);
721         }
722         odhcp6c_clear_state(STATE_SERVER_CAND);
723
724         if (!c)
725                 return -1;
726         else if ((request_prefix && c->ia_pd_len) || (na_mode != IA_MODE_NONE && c->ia_na_len))
727                 return DHCPV6_STATEFUL;
728         else
729                 return DHCPV6_STATELESS;
730 }
731
732
733 static int dhcpv6_handle_rebind_reply(enum dhcpv6_msg orig, const int rc,
734                 const void *opt, const void *end)
735 {
736         dhcpv6_handle_advert(orig, rc, opt, end);
737         if (dhcpv6_commit_advert() < 0) {
738                 dhcpv6_handle_reply(DHCPV6_MSG_UNKNOWN, rc, NULL, NULL);
739                 return -1;
740         }
741
742         return dhcpv6_handle_reply(orig, rc, opt, end);
743 }
744
745
746 static int dhcpv6_handle_reply(enum dhcpv6_msg orig, _unused const int rc,
747                 const void *opt, const void *end)
748 {
749         uint8_t *odata;
750         uint16_t otype, olen;
751         uint32_t refresh = UINT32_MAX;
752         int ret = 1;
753         bool handled_status_codes[_DHCPV6_Status_Max] = { false, };
754
755         odhcp6c_expire();
756
757         if (orig == DHCPV6_MSG_UNKNOWN) {
758                 static time_t last_update = 0;
759                 time_t now = odhcp6c_get_milli_time() / 1000;
760
761                 uint32_t elapsed = (last_update > 0) ? now - last_update : 0;
762                 last_update = now;
763
764                 t1 -= elapsed;
765                 t2 -= elapsed;
766                 t3 -= elapsed;
767
768                 if (t1 < 0)
769                         t1 = 0;
770
771                 if (t2 < 0)
772                         t2 = 0;
773
774                 if (t3 < 0)
775                         t3 = 0;
776         }
777
778         if (orig == DHCPV6_MSG_REQUEST && !odhcp6c_is_bound()) {
779                 // Delete NA and PD we have in the state from the Advert
780                 odhcp6c_clear_state(STATE_IA_NA);
781                 odhcp6c_clear_state(STATE_IA_PD);
782         }
783
784         if (opt) {
785                 odhcp6c_clear_state(STATE_DNS);
786                 odhcp6c_clear_state(STATE_SEARCH);
787                 odhcp6c_clear_state(STATE_SNTP_IP);
788                 odhcp6c_clear_state(STATE_SNTP_FQDN);
789                 odhcp6c_clear_state(STATE_SIP_IP);
790                 odhcp6c_clear_state(STATE_SIP_FQDN);
791                 odhcp6c_clear_state(STATE_AFTR_NAME);
792         }
793
794         // Parse and find all matching IAs
795         dhcpv6_for_each_option(opt, end, otype, olen, odata) {
796                 if ((otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA)
797                                 && olen > sizeof(struct dhcpv6_ia_hdr)) {
798                         struct dhcpv6_ia_hdr *ia_hdr = (void*)(&odata[-4]);
799
800                         // Test ID
801                         if (ia_hdr->iaid != 1)
802                                 continue;
803
804                         uint16_t code = DHCPV6_Success;
805                         uint16_t stype, slen;
806                         uint8_t *sdata;
807                         // Get and handle status code
808                         dhcpv6_for_each_option(&ia_hdr[1], odata + olen,
809                                         stype, slen, sdata) {
810                                 if (stype == DHCPV6_OPT_STATUS && slen >= 2) {
811                                         uint8_t *mdata = (slen > 2) ? &sdata[2] : NULL;
812                                         uint16_t mlen = (slen > 2) ? slen - 2 : 0;
813
814                                         code = ((int)sdata[0]) << 8 | ((int)sdata[1]);
815
816                                         if (code == DHCPV6_Success)
817                                                 continue;
818
819                                         dhcpv6_handle_ia_status_code(orig, ia_hdr,
820                                                 code, mdata, mlen, handled_status_codes, &ret);
821
822
823                                         if (ret > 0)
824                                                 return ret;
825                                         break;
826                                 }
827                         }
828
829                         if (code != DHCPV6_Success)
830                                 continue;
831
832                         dhcpv6_parse_ia(ia_hdr, odata + olen + sizeof(*ia_hdr));
833                 } else if (otype == DHCPV6_OPT_STATUS && olen >= 2) {
834                         uint8_t *mdata = (olen > 2) ? &odata[2] : NULL;
835                         uint16_t mlen = (olen > 2) ? olen - 2 : 0;
836                         uint16_t code = ((int)odata[0]) << 8 | ((int)odata[1]);
837
838                         dhcpv6_handle_status_code(orig, code, mdata, mlen, &ret);
839                 }
840                 else if (otype == DHCPV6_OPT_DNS_SERVERS) {
841                         if (olen % 16 == 0)
842                                 odhcp6c_add_state(STATE_DNS, odata, olen);
843                 } else if (otype == DHCPV6_OPT_DNS_DOMAIN) {
844                         odhcp6c_add_state(STATE_SEARCH, odata, olen);
845                 } else if (otype == DHCPV6_OPT_NTP_SERVER) {
846                         uint16_t stype, slen;
847                         uint8_t *sdata;
848                         // Test status and bail if error
849                         dhcpv6_for_each_option(odata, odata + olen,
850                                         stype, slen, sdata) {
851                                 if (slen == 16 && (stype == NTP_MC_ADDR ||
852                                                 stype == NTP_SRV_ADDR))
853                                         odhcp6c_add_state(STATE_SNTP_IP,
854                                                         sdata, slen);
855                                 else if (slen > 0 && stype == NTP_SRV_FQDN)
856                                         odhcp6c_add_state(STATE_SNTP_FQDN,
857                                                         sdata, slen);
858                         }
859                 } else if (otype == DHCPV6_OPT_SIP_SERVER_A) {
860                         if (olen == 16)
861                                 odhcp6c_add_state(STATE_SIP_IP, odata, olen);
862                 } else if (otype == DHCPV6_OPT_SIP_SERVER_D) {
863                         odhcp6c_add_state(STATE_SIP_FQDN, odata, olen);
864                 } else if (otype == DHCPV6_OPT_INFO_REFRESH && olen >= 4) {
865                         refresh = ntohl(*((uint32_t*)odata));
866                 } else if (otype == DHCPV6_OPT_AUTH && olen == -4 +
867                                 sizeof(struct dhcpv6_auth_reconfigure)) {
868                         struct dhcpv6_auth_reconfigure *r = (void*)&odata[-4];
869                         if (r->protocol == 3 && r->algorithm == 1 &&
870                                         r->reconf_type == 1)
871                                 memcpy(reconf_key, r->key, sizeof(r->key));
872                 } else if (otype == DHCPV6_OPT_AFTR_NAME && olen > 3) {
873                         size_t cur_len;
874                         odhcp6c_get_state(STATE_AFTR_NAME, &cur_len);
875                         if (cur_len == 0)
876                                 odhcp6c_add_state(STATE_AFTR_NAME, odata, olen);
877                 } else if (otype != DHCPV6_OPT_CLIENTID &&
878                                 otype != DHCPV6_OPT_SERVERID) {
879                         odhcp6c_add_state(STATE_CUSTOM_OPTS,
880                                         &odata[-4], olen + 4);
881                 }
882         }
883
884         if (orig != DHCPV6_MSG_INFO_REQ) {
885                 // Update refresh timers if no fatal status code was received
886                 if ((ret > 0) && dhcpv6_calc_refresh_timers()) {
887                         switch (orig) {
888                         case DHCPV6_MSG_RENEW:
889                                 // Send further renews if T1 is not set
890                                 if (!t1)
891                                         ret = -1;
892                                 break;
893                         case DHCPV6_MSG_REBIND:
894                                 // Send further rebinds if T1 and T2 is not set
895                                 if (!t1 && !t2)
896                                         ret = -1;
897                                 break;
898
899                         default :
900                                 break;
901                         }
902                 }
903         }
904         else if (ret > 0)
905                 t1 = refresh;
906
907         return ret;
908 }
909
910
911 static int dhcpv6_parse_ia(void *opt, void *end)
912 {
913         struct dhcpv6_ia_hdr *ia_hdr = (struct dhcpv6_ia_hdr *)opt;
914         int parsed_ia = 0;
915         uint32_t t1, t2;
916         uint16_t otype, olen;
917         uint8_t *odata;
918
919         t1 = ntohl(ia_hdr->t1);
920         t2 = ntohl(ia_hdr->t2);
921
922         if (t1 > t2)
923                 return 0;
924
925         // Update address IA
926         dhcpv6_for_each_option(&ia_hdr[1], end, otype, olen, odata) {
927                 struct odhcp6c_entry entry = {IN6ADDR_ANY_INIT, 0, 0,
928                                 IN6ADDR_ANY_INIT, 0, 0, 0, 0, 0};
929
930                 if (otype == DHCPV6_OPT_IA_PREFIX) {
931                         struct dhcpv6_ia_prefix *prefix = (void*)&odata[-4];
932                         if (olen + 4U < sizeof(*prefix))
933                                 continue;
934
935                         entry.valid = ntohl(prefix->valid);
936                         entry.preferred = ntohl(prefix->preferred);
937
938                         if (entry.preferred > entry.valid)
939                                 continue;
940
941                         entry.t1 = (t1 ? t1 : (entry.preferred != UINT32_MAX ? 0.5 * entry.preferred : UINT32_MAX));
942                         entry.t2 = (t2 ? t2 : (entry.preferred != UINT32_MAX ? 0.8 * entry.preferred : UINT32_MAX));
943                         if (entry.t1 > entry.t2)
944                                 entry.t1 = entry.t2;
945
946                         entry.length = prefix->prefix;
947                         entry.target = prefix->addr;
948                         uint16_t stype, slen;
949                         uint8_t *sdata;
950
951 #ifdef EXT_PREFIX_CLASS
952                         // Find prefix class, if any
953                         dhcpv6_for_each_option(&prefix[1], odata + olen,
954                                         stype, slen, sdata)
955                                 if (stype == DHCPV6_OPT_PREFIX_CLASS && slen == 2)
956                                         entry.class = sdata[0] << 8 | sdata[1];
957 #endif
958
959                         // Parse PD-exclude
960                         bool ok = true;
961                         dhcpv6_for_each_option(odata + sizeof(*prefix) - 4U,
962                                         odata + olen, stype, slen, sdata) {
963                                 if (stype != DHCPV6_OPT_PD_EXCLUDE || slen < 2)
964                                         continue;
965
966                                 uint8_t elen = sdata[0];
967                                 if (elen > 64)
968                                         elen = 64;
969
970                                 if (elen <= 32 || elen <= entry.length) {
971                                         ok = false;
972                                         continue;
973                                 }
974
975
976                                 uint8_t bytes = ((elen - entry.length - 1) / 8) + 1;
977                                 if (slen <= bytes) {
978                                         ok = false;
979                                         continue;
980                                 }
981
982                                 uint32_t exclude = 0;
983                                 do {
984                                         exclude = exclude << 8 | sdata[bytes];
985                                 } while (--bytes);
986
987                                 exclude >>= 8 - ((elen - entry.length) % 8);
988                                 exclude <<= 64 - elen;
989
990                                 // Abusing router & priority fields for exclusion
991                                 entry.router = entry.target;
992                                 entry.router.s6_addr32[1] |= htonl(exclude);
993                                 entry.priority = elen;
994                         }
995
996                         if (ok) {
997                                 odhcp6c_update_entry(STATE_IA_PD, &entry);
998                                 parsed_ia++;
999                         }
1000
1001                         entry.priority = 0;
1002                         memset(&entry.router, 0, sizeof(entry.router));
1003                 } else if (otype == DHCPV6_OPT_IA_ADDR) {
1004                         struct dhcpv6_ia_addr *addr = (void*)&odata[-4];
1005                         if (olen + 4U < sizeof(*addr))
1006                                 continue;
1007
1008                         entry.preferred = ntohl(addr->preferred);
1009                         entry.valid = ntohl(addr->valid);
1010
1011                         if (entry.preferred > entry.valid)
1012                                 continue;
1013
1014                         entry.t1 = (t1 ? t1 : (entry.preferred != UINT32_MAX ? 0.5 * entry.preferred : UINT32_MAX));
1015                         entry.t2 = (t2 ? t2 : (entry.preferred != UINT32_MAX ? 0.8 * entry.preferred : UINT32_MAX));
1016                         if (entry.t1 > entry.t2)
1017                                 entry.t1 = entry.t2;
1018
1019                         entry.length = 128;
1020                         entry.target = addr->addr;
1021
1022 #ifdef EXT_PREFIX_CLASS
1023                         uint16_t stype, slen;
1024                         uint8_t *sdata;
1025                         // Find prefix class, if any
1026                         dhcpv6_for_each_option(&addr[1], odata + olen,
1027                                         stype, slen, sdata)
1028                                 if (stype == DHCPV6_OPT_PREFIX_CLASS && slen == 2)
1029                                         entry.class = sdata[0] << 8 | sdata[1];
1030 #endif
1031
1032                         odhcp6c_update_entry(STATE_IA_NA, &entry);
1033                         parsed_ia++;
1034                 }
1035         }
1036         return parsed_ia;
1037 }
1038
1039
1040 static int dhcpv6_calc_refresh_timers(void)
1041 {
1042         struct odhcp6c_entry *e;
1043         size_t ia_na_entries, ia_pd_entries, i;
1044         int64_t l_t1 = UINT32_MAX, l_t2 = UINT32_MAX, l_t3 = 0;
1045
1046         e = odhcp6c_get_state(STATE_IA_NA, &ia_na_entries);
1047         ia_na_entries /= sizeof(*e);
1048         for (i = 0; i < ia_na_entries; i++) {
1049                 if (e[i].t1 < l_t1)
1050                         l_t1 = e[i].t1;
1051
1052                 if (e[i].t2 < l_t2)
1053                         l_t2 = e[i].t2;
1054
1055                 if (e[i].valid > l_t3)
1056                         l_t3 = e[i].valid;
1057         }
1058
1059         e = odhcp6c_get_state(STATE_IA_PD, &ia_pd_entries);
1060         ia_pd_entries /= sizeof(*e);
1061         for (i = 0; i < ia_pd_entries; i++) {
1062                 if (e[i].t1 < l_t1)
1063                         l_t1 = e[i].t1;
1064
1065                 if (e[i].t2 < l_t2)
1066                         l_t2 = e[i].t2;
1067
1068                 if (e[i].valid > l_t3)
1069                         l_t3 = e[i].valid;
1070         }
1071
1072         if (ia_pd_entries || ia_na_entries) {
1073                 t1 = l_t1;
1074                 t2 = l_t2;
1075                 t3 = l_t3;
1076         }
1077
1078         return (int)(ia_pd_entries + ia_na_entries);
1079 }
1080
1081
1082 static void dhcpv6_log_status_code(const uint16_t code, const char *scope,
1083                 const void *status_msg, const int len)
1084 {
1085         uint8_t buf[len + 3];
1086
1087         memset(buf, 0, sizeof(buf));
1088         if (len) {
1089                 buf[0] = '(';
1090                 memcpy(&buf[1], status_msg, len);
1091                 buf[len + 1] = ')';
1092         }
1093
1094         syslog(LOG_WARNING, "Server returned %s status %i %s",
1095                 scope, code, buf);
1096 }
1097
1098
1099 static void dhcpv6_handle_status_code(const enum dhcpv6_msg orig,
1100                 const uint16_t code, const void *status_msg, const int len,
1101                 int *ret)
1102 {
1103         dhcpv6_log_status_code(code, "message", status_msg, len);
1104
1105         switch (code) {
1106         case DHCPV6_UnspecFail:
1107                 // Generic failure
1108                 *ret = 0;
1109                 break;
1110
1111         case DHCPV6_UseMulticast:
1112                 // TODO handle multicast status code
1113                 break;
1114
1115         case DHCPV6_NoAddrsAvail:
1116         case DHCPV6_NoPrefixAvail:
1117                 if (orig == DHCPV6_MSG_REQUEST)
1118                         *ret = 0; // Failure
1119                 break;
1120
1121         default:
1122                 break;
1123         }
1124 }
1125
1126
1127 static void dhcpv6_handle_ia_status_code(const enum dhcpv6_msg orig,
1128                 const struct dhcpv6_ia_hdr *ia_hdr, const uint16_t code,
1129                 const void *status_msg, const int len,
1130                 bool handled_status_codes[_DHCPV6_Status_Max], int *ret)
1131 {
1132         dhcpv6_log_status_code(code, ia_hdr->type == DHCPV6_OPT_IA_NA ?
1133                 "IA_NA" : "IA_PD", status_msg, len);
1134
1135         switch (code) {
1136         case DHCPV6_NoBinding:
1137                 switch (orig) {
1138                 case DHCPV6_MSG_RENEW:
1139                 case DHCPV6_MSG_REBIND:
1140                         if ((*ret > 0) && !handled_status_codes[code])
1141                                 *ret = dhcpv6_request(DHCPV6_MSG_REQUEST);
1142                         break;
1143
1144                 default:
1145                         break;
1146                 }
1147                 break;
1148
1149         case DHCPV6_NoAddrsAvail:
1150         case DHCPV6_NoPrefixAvail:
1151                 switch (orig) {
1152                 case DHCPV6_MSG_REQUEST:
1153                         if (*ret != 0)
1154                                 *ret = 0;
1155                         break;
1156                 default:
1157                         break;
1158                 }
1159                 break;
1160
1161         case DHCPV6_NotOnLink:
1162                 // TODO handle not onlink in case of confirm
1163                 break;
1164
1165         default:
1166                 break;
1167         }
1168 }