Wait at least 15 seconds for managed PD to be acknowledged
[project/odhcpd.git] / src / dhcpv4.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
16 #include <time.h>
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <unistd.h>
20 #include <stddef.h>
21 #include <stdlib.h>
22 #include <resolv.h>
23 #include <net/if.h>
24 #include <net/if_arp.h>
25 #include <netinet/ip.h>
26 #include <sys/ioctl.h>
27 #include <sys/timerfd.h>
28 #include <arpa/inet.h>
29
30 #include "odhcpd.h"
31 #include "dhcpv4.h"
32 #include "dhcpv6.h"
33
34
35 static void handle_dhcpv4(void *addr, void *data, size_t len,
36                 struct interface *iface);
37 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
38                 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
39                 const char *hostname);
40 static const char *excluded_class = "HOMENET";
41
42 // Create socket and register events
43 int init_dhcpv4(void)
44 {
45         return 0;
46 }
47
48
49 int setup_dhcpv4_interface(struct interface *iface, bool enable)
50 {
51         if (iface->dhcpv4_event.uloop.fd > 0) {
52                 uloop_fd_delete(&iface->dhcpv4_event.uloop);
53                 close(iface->dhcpv4_event.uloop.fd);
54                 iface->dhcpv4_event.uloop.fd = -1;
55         }
56
57         if (iface->dhcpv4 && enable) {
58                 if (!iface->dhcpv4_assignments.next)
59                         INIT_LIST_HEAD(&iface->dhcpv4_assignments);
60
61                 int sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
62                 if (sock < 0) {
63                         syslog(LOG_ERR, "Failed to create DHCPv4 server socket: %s",
64                                         strerror(errno));
65                         return -1;
66                 }
67
68                 // Basic IPv6 configuration
69                 int val = 1;
70                 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
71                 setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &val, sizeof(val));
72                 setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &val, sizeof(val));
73
74                 val = IPTOS_PREC_INTERNETCONTROL;
75                 setsockopt(sock, IPPROTO_IP, IP_TOS, &val, sizeof(val));
76
77                 val = IP_PMTUDISC_DONT;
78                 setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val));
79
80                 setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE,
81                                 iface->ifname, strlen(iface->ifname));
82
83                 struct sockaddr_in bind_addr = {AF_INET, htons(DHCPV4_SERVER_PORT),
84                                         {INADDR_ANY}, {0}};
85
86                 if (bind(sock, (struct sockaddr*)&bind_addr, sizeof(bind_addr))) {
87                         syslog(LOG_ERR, "Failed to open DHCPv4 server socket: %s",
88                                         strerror(errno));
89                         return -1;
90                 }
91
92
93                 if (ntohl(iface->dhcpv4_start.s_addr) > ntohl(iface->dhcpv4_end.s_addr)) {
94                         syslog(LOG_ERR, "Invalid DHCP range");
95                         return -1;
96                 }
97
98                 // Create a range if not specified
99                 struct ifreq ifreq;
100                 strncpy(ifreq.ifr_name, iface->ifname, sizeof(ifreq.ifr_name));
101
102                 struct sockaddr_in *saddr = (struct sockaddr_in*)&ifreq.ifr_addr;
103                 struct sockaddr_in *smask = (struct sockaddr_in*)&ifreq.ifr_netmask;
104                 if (!(iface->dhcpv4_start.s_addr & htonl(0xffff0000)) &&
105                                 !(iface->dhcpv4_end.s_addr & htonl(0xffff0000)) &&
106                                 !ioctl(sock, SIOCGIFADDR, &ifreq)) {
107                         struct in_addr addr = saddr->sin_addr;
108
109                         ioctl(sock, SIOCGIFNETMASK, &ifreq);
110                         struct in_addr mask = smask->sin_addr;
111
112                         uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
113                         uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
114
115                         if (start && end && start < end &&
116                                         start > ntohl(addr.s_addr & ~mask.s_addr) &&
117                                         (start & ntohl(mask.s_addr)) == start &&
118                                         (end & ntohl(mask.s_addr)) == end) {
119                                 iface->dhcpv4_start.s_addr = htonl(start) |
120                                                 (addr.s_addr & mask.s_addr);
121                                 iface->dhcpv4_end.s_addr = htonl(end) |
122                                                 (addr.s_addr & mask.s_addr);
123                         } else if (ntohl(mask.s_addr) <= 0xffffffc0) {
124                                 start = addr.s_addr & mask.s_addr;
125                                 end = addr.s_addr & mask.s_addr;
126
127                                 if (ntohl(mask.s_addr) <= 0xffffff00) {
128                                         iface->dhcpv4_start.s_addr = start | htonl(100);
129                                         iface->dhcpv4_end.s_addr = end | htonl(250);
130                                 } else {
131                                         iface->dhcpv4_start.s_addr = start | htonl(10);
132                                         iface->dhcpv4_end.s_addr = end | htonl(59);
133                                 }
134                         }
135
136
137                 }
138
139                 // Parse static entries
140                 struct lease *lease;
141                 list_for_each_entry(lease, &leases, head) {
142                         // Construct entry
143                         size_t hostlen = strlen(lease->hostname) + 1;
144                         struct dhcpv4_assignment *a = calloc(1, sizeof(*a) + hostlen);
145                         if (!a) {
146                                 syslog(LOG_ERR, "Calloc failed for static lease on interface %s",
147                                         iface->ifname);
148                                 return -1;
149                         }
150                         a->addr = ntohl(lease->ipaddr.s_addr);
151                         memcpy(a->hwaddr, lease->mac.ether_addr_octet, sizeof(a->hwaddr));
152                         memcpy(a->hostname, lease->hostname, hostlen);
153
154                         // Assign to all interfaces
155                         struct dhcpv4_assignment *c;
156                         list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
157                                 if (c->addr > a->addr) {
158                                         list_add_tail(&a->head, &c->head);
159                                 } else if (c->addr == a->addr) {
160                                         // Already an assignment with that number
161                                         break;
162                                 }
163                         }
164
165                         if (!a->head.next)
166                                 free(a);
167                 }
168
169                 // Clean invalid assignments
170                 struct dhcpv4_assignment *a, *n;
171                 list_for_each_entry_safe(a, n, &iface->dhcpv4_assignments, head) {
172                         if ((htonl(a->addr) & smask->sin_addr.s_addr) !=
173                                         (saddr->sin_addr.s_addr & smask->sin_addr.s_addr)) {
174                                 list_del(&a->head);
175                                 free(a);
176                         }
177                 }
178
179
180                 if (iface->dhcpv4_leasetime < 60)
181                         iface->dhcpv4_leasetime = 43200;
182
183                 iface->dhcpv4_event.uloop.fd = sock;
184                 iface->dhcpv4_event.handle_dgram = handle_dhcpv4;
185                 odhcpd_register(&iface->dhcpv4_event);
186         } else if (iface->dhcpv4_assignments.next) {
187                 while (!list_empty(&iface->dhcpv4_assignments)) {
188                         struct dhcpv4_assignment *a = list_first_entry(&iface->dhcpv4_assignments,
189                                         struct dhcpv4_assignment, head);
190                         list_del(&a->head);
191                         free(a->hostname);
192                         free(a);
193                 }
194
195         }
196         return 0;
197 }
198
199
200 static void dhcpv4_put(struct dhcpv4_message *msg, uint8_t **cookie,
201                 uint8_t type, uint8_t len, const void *data)
202 {
203         uint8_t *c = *cookie;
204         if (*cookie + 2 + len > (uint8_t*)&msg[1])
205                 return;
206
207         *c++ = type;
208         *c++ = len;
209         memcpy(c, data, len);
210
211         *cookie = c + len;
212 }
213
214
215 // Simple DHCPv6-server for information requests
216 static void handle_dhcpv4(void *addr, void *data, size_t len,
217                 struct interface *iface)
218 {
219         if (!iface->dhcpv4)
220                 return;
221
222         struct dhcpv4_message *req = data;
223         if (len < offsetof(struct dhcpv4_message, options) + 4 ||
224                         req->op != DHCPV4_BOOTREQUEST || req->hlen != 6)
225                 return;
226
227         int sock = iface->dhcpv4_event.uloop.fd;
228         struct sockaddr_in ifaddr;
229         struct sockaddr_in ifnetmask;
230
231         syslog(LOG_NOTICE, "Got DHCPv4 request");
232
233         struct ifreq ifreq;
234         memcpy(ifreq.ifr_name, iface->ifname, sizeof(ifreq.ifr_name));
235         if (ioctl(sock, SIOCGIFADDR, &ifreq)) {
236                 syslog(LOG_WARNING, "DHCPv4 failed to detect address: %s", strerror(errno));
237                 return;
238         }
239
240         memcpy(&ifaddr, &ifreq.ifr_addr, sizeof(ifaddr));
241         if (ioctl(sock, SIOCGIFNETMASK, &ifreq))
242                 return;
243
244         memcpy(&ifnetmask, &ifreq.ifr_netmask, sizeof(ifnetmask));
245         uint32_t network = ifaddr.sin_addr.s_addr & ifnetmask.sin_addr.s_addr;
246
247         if ((iface->dhcpv4_start.s_addr & ifnetmask.sin_addr.s_addr) != network ||
248                         (iface->dhcpv4_end.s_addr & ifnetmask.sin_addr.s_addr) != network) {
249                 syslog(LOG_WARNING, "DHCPv4 range out of assigned network");
250                 return;
251         }
252
253         struct ifreq ifr = {.ifr_name = ""};
254         strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
255
256         struct dhcpv4_message reply = {
257                 .op = DHCPV4_BOOTREPLY,
258                 .htype = 1,
259                 .hlen = 6,
260                 .hops = 0,
261                 .xid = req->xid,
262                 .secs = 0,
263                 .flags = req->flags,
264                 .ciaddr = {INADDR_ANY},
265                 .giaddr = req->giaddr,
266                 .siaddr = ifaddr.sin_addr,
267         };
268         memcpy(reply.chaddr, req->chaddr, sizeof(reply.chaddr));
269
270         reply.options[0] = 0x63;
271         reply.options[1] = 0x82;
272         reply.options[2] = 0x53;
273         reply.options[3] = 0x63;
274
275         uint8_t *cookie = &reply.options[4];
276         uint8_t reqmsg = DHCPV4_MSG_REQUEST;
277         uint8_t msg = DHCPV4_MSG_ACK;
278
279         struct in_addr reqaddr = {INADDR_ANY};
280         char hostname[256];
281         hostname[0] = 0;
282
283         uint8_t *start = &req->options[4];
284         uint8_t *end = ((uint8_t*)data) + len;
285         struct dhcpv4_option *opt;
286         dhcpv4_for_each_option(start, end, opt) {
287                 if (opt->type == DHCPV4_OPT_MESSAGE && opt->len == 1) {
288                         reqmsg = opt->data[0];
289                 } else if (opt->type == DHCPV4_OPT_HOSTNAME && opt->len > 0) {
290                         memcpy(hostname, opt->data, opt->len);
291                         hostname[opt->len] = 0;
292                 } else if (opt->type == DHCPV4_OPT_IPADDRESS && opt->len == 4) {
293                         memcpy(&reqaddr, opt->data, 4);
294                 } else if (opt->type == DHCPV4_OPT_SERVERID && opt->len == 4) {
295                         if (memcmp(opt->data, &ifaddr.sin_addr, 4))
296                                 return;
297                 } else if (opt->type == DHCPV4_OPT_USER_CLASS) {
298                         uint8_t *c = opt->data, *cend = &opt->data[opt->len];
299                         for (; c < cend && &c[*c] < cend; c = &c[1 + *c]) {
300                                 size_t elen = strlen(excluded_class);
301                                 if (*c == elen && !memcmp(&c[1], excluded_class, elen))
302                                         return; // Ignore from homenet
303                         }
304                 }
305         }
306
307         if (reqmsg != DHCPV4_MSG_DISCOVER && reqmsg != DHCPV4_MSG_REQUEST &&
308                         reqmsg != DHCPV4_MSG_INFORM && reqmsg != DHCPV4_MSG_DECLINE &&
309                         reqmsg != DHCPV4_MSG_RELEASE)
310                 return;
311
312         struct dhcpv4_assignment *lease = NULL;
313         if (reqmsg != DHCPV4_MSG_INFORM)
314                 lease = dhcpv4_lease(iface, reqmsg, req->chaddr, reqaddr, hostname);
315
316         if (!lease) {
317                 if (reqmsg == DHCPV4_MSG_REQUEST)
318                         msg = DHCPV4_MSG_NAK;
319                 else if (reqmsg == DHCPV4_MSG_DISCOVER)
320                         return;
321         } else if (reqmsg == DHCPV4_MSG_DISCOVER) {
322                 msg = DHCPV4_MSG_OFFER;
323         }
324
325         if (reqmsg == DHCPV4_MSG_DECLINE || reqmsg == DHCPV4_MSG_RELEASE)
326                 return;
327
328         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MESSAGE, 1, &msg);
329         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SERVERID, 4, &ifaddr.sin_addr);
330
331         if (lease) {
332                 reply.yiaddr.s_addr = htonl(lease->addr);
333
334                 uint32_t val = htonl(iface->dhcpv4_leasetime);
335                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_LEASETIME, 4, &val);
336
337                 val = htonl(500 * iface->dhcpv4_leasetime / 1000);
338                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_RENEW, 4, &val);
339
340                 val = htonl(875 * iface->dhcpv4_leasetime / 1000);
341                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_REBIND, 4, &val);
342
343                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_NETMASK, 4, &ifnetmask.sin_addr);
344
345                 if (lease->hostname[0])
346                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_HOSTNAME,
347                                         strlen(lease->hostname), lease->hostname);
348
349                 if (!ioctl(sock, SIOCGIFBRDADDR, &ifr)) {
350                         struct sockaddr_in *ina = (struct sockaddr_in*)&ifr.ifr_broadaddr;
351                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_BROADCAST, 4, &ina->sin_addr);
352                 }
353         }
354
355         if (!ioctl(sock, SIOCGIFMTU, &ifr)) {
356                 uint16_t mtu = htons(ifr.ifr_mtu);
357                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MTU, 2, &mtu);
358         }
359
360         if (iface->search) {
361                 char b[256];
362                 if (dn_expand(iface->search, iface->search + iface->search_len,
363                                 iface->search, b, sizeof(b)) > 0)
364                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DOMAIN, strlen(b), b);
365         } else if (!res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
366                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DOMAIN,
367                                 strlen(_res.dnsrch[0]), _res.dnsrch[0]);
368         }
369
370         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER, 4, &ifaddr.sin_addr);
371
372
373
374         if (iface->dhcpv4_dns_cnt == 0)
375                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER, 4, &ifaddr.sin_addr);
376         else
377                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER,
378                                 4 * iface->dhcpv4_dns_cnt, iface->dhcpv4_dns);
379
380
381         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_END, 0, NULL);
382
383         struct sockaddr_in dest = *((struct sockaddr_in*)addr);
384         if (req->giaddr.s_addr) {
385                 dest.sin_addr = req->giaddr;
386                 dest.sin_port = htons(DHCPV4_SERVER_PORT);
387         } else if (req->ciaddr.s_addr && req->ciaddr.s_addr != dest.sin_addr.s_addr) {
388                 dest.sin_addr = req->ciaddr;
389                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
390         } else if ((ntohs(req->flags) & DHCPV4_FLAG_BROADCAST) ||
391                         req->hlen != reply.hlen) {
392                 dest.sin_addr.s_addr = INADDR_BROADCAST;
393                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
394         } else {
395                 dest.sin_addr = reply.yiaddr;
396                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
397
398                 struct arpreq arp = {.arp_flags = ATF_COM};
399                 memcpy(arp.arp_ha.sa_data, req->chaddr, 6);
400                 memcpy(&arp.arp_pa, &dest, sizeof(arp.arp_pa));
401                 memcpy(arp.arp_dev, iface->ifname, sizeof(arp.arp_dev));
402                 ioctl(sock, SIOCSARP, &arp);
403         }
404
405         sendto(sock, &reply, sizeof(reply), MSG_DONTWAIT,
406                         (struct sockaddr*)&dest, sizeof(dest));
407 }
408
409
410 static bool dhcpv4_assign(struct interface *iface,
411                 struct dhcpv4_assignment *assign, uint32_t raddr)
412 {
413         const unsigned tries = 10;
414         uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
415         uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
416         uint32_t count = end - start + 1;
417
418         // Seed RNG with checksum of DUID
419         uint32_t seed = 0;
420         for (size_t i = 0; i < sizeof(assign->hwaddr); ++i)
421                 seed += assign->hwaddr[i];
422         srand(seed);
423
424         // Try to assign up to 100x
425         for (unsigned i = 0; i < tries; ++i) {
426                 uint32_t try = (((uint32_t)rand()) % count) + start;
427                 if (i == 0 && raddr >= start && raddr <= end)
428                         try = raddr;
429                 else if (i == tries - 1)
430                         try = start;
431
432                 if (list_empty(&iface->dhcpv4_assignments)) {
433                         assign->addr = try;
434                         list_add(&assign->head, &iface->dhcpv4_assignments);
435                         return true;
436                 }
437
438                 struct dhcpv4_assignment *c;
439                 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
440                         if (c->addr > try) {
441                                 assign->addr = try;
442                                 list_add_tail(&assign->head, &c->head);
443                                 return true;
444                         } else if (c->addr == try) {
445                                 if (i < tries - 1)
446                                         break;
447                                 else
448                                         ++try;
449                         }
450                 }
451         }
452
453         return false;
454 }
455
456
457 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
458                 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
459                 const char *hostname)
460 {
461         struct dhcpv4_assignment *lease = NULL;
462         uint32_t raddr = ntohl(reqaddr.s_addr);
463         time_t now = odhcpd_time();
464
465         struct dhcpv4_assignment *c, *n, *a = NULL;
466         list_for_each_entry_safe(c, n, &iface->dhcpv4_assignments, head) {
467                 if (c->addr == raddr && !memcmp(c->hwaddr, mac, 6)) {
468                         a = c;
469                         break;
470                 } else if (c->valid_until < now) {
471                         list_del(&c->head);
472                         free(c);
473                 }
474         }
475
476         bool update_state = false;
477         if (msg == DHCPV4_MSG_DISCOVER || msg == DHCPV4_MSG_REQUEST) {
478                 bool assigned = !!a;
479                 size_t hostlen = strlen(hostname) + 1;
480
481                 if (!a && !iface->no_dynamic_dhcp) { // Create new binding
482                         a = calloc(1, sizeof(*a) + hostlen);
483                         if (!a) {
484                                 syslog(LOG_ERR, "Failed to calloc binding on interface %s", iface->ifname);
485                                 return NULL;
486                         }
487                         memcpy(a->hwaddr, mac, sizeof(a->hwaddr));
488                         memcpy(a->hostname, hostname, hostlen);
489
490                         assigned = dhcpv4_assign(iface, a, raddr);
491                 }
492
493                 if (assigned && !a->hostname[0] && hostname) {
494                         a = realloc(a, sizeof(*a) + hostlen);
495                         if (!a) {
496                                 syslog(LOG_ERR, "Failed to realloc binding on interface %s", iface->ifname);
497                                 return NULL;
498                         }
499                         memcpy(a->hostname, hostname, hostlen);
500
501                         // Fixup list
502                         a->head.next->prev = &a->head;
503                         a->head.prev->next = &a->head;
504                 }
505
506                 // Was only a solicitation: mark binding for removal
507                 if (assigned && a->valid_until < now) {
508                         a->valid_until = (msg == DHCPV4_MSG_DISCOVER) ? 0 :
509                                         (now + iface->dhcpv4_leasetime);
510                 } else if (!assigned && a) { // Cleanup failed assignment
511                         free(a);
512                         a = NULL;
513                 }
514
515                 if (assigned && a)
516                         lease = a;
517         } else if (msg == DHCPV4_MSG_RELEASE) {
518                 if (a) {
519                         a->valid_until = 0;
520                         update_state = true;
521                 }
522         } else if (msg == DHCPV4_MSG_DECLINE) {
523                 memset(a->hwaddr, 0, sizeof(a->hwaddr));
524                 a->valid_until = now + 3600; // Block address for 1h
525                 update_state = true;
526         }
527
528         if (update_state)
529                 dhcpv6_write_statefile();
530
531         return lease;
532 }
533