2 * Copyright (C) 2012-2013 Steven Barth <steven@midlink.org>
3 * Copyright (C) 2016 Hans Dedecker <dedeckeh@gmail.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License v2 as published by
7 * the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
26 #include <net/if_arp.h>
27 #include <netinet/ip.h>
28 #include <sys/ioctl.h>
29 #include <sys/timerfd.h>
30 #include <arpa/inet.h>
36 static void free_dhcpv4_assignment(struct dhcpv4_assignment *a);
37 static void handle_dhcpv4(void *addr, void *data, size_t len,
38 struct interface *iface, void *dest_addr);
39 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
40 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
41 uint32_t *leasetime, const char *hostname, const size_t hostname_len);
43 /* Create socket and register events */
49 int setup_dhcpv4_interface(struct interface *iface, bool enable)
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;
57 if (iface->dhcpv4 && enable) {
58 if (!iface->dhcpv4_assignments.next)
59 INIT_LIST_HEAD(&iface->dhcpv4_assignments);
61 int sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
63 syslog(LOG_ERR, "Failed to create DHCPv4 server socket: %s",
68 /* Basic IPv4 configuration */
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));
74 val = IPTOS_PREC_INTERNETCONTROL;
75 setsockopt(sock, IPPROTO_IP, IP_TOS, &val, sizeof(val));
77 val = IP_PMTUDISC_DONT;
78 setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val));
80 setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE,
81 iface->ifname, strlen(iface->ifname));
83 struct sockaddr_in bind_addr = {AF_INET, htons(DHCPV4_SERVER_PORT),
86 if (bind(sock, (struct sockaddr*)&bind_addr, sizeof(bind_addr))) {
87 syslog(LOG_ERR, "Failed to open DHCPv4 server socket: %s",
93 if (ntohl(iface->dhcpv4_start.s_addr) > ntohl(iface->dhcpv4_end.s_addr)) {
94 syslog(LOG_ERR, "Invalid DHCP range");
98 uint32_t mask = iface->addr4 && iface->addr4[0].prefix ?
99 htonl(~((1 << (32 - iface->addr4[0].prefix)) - 1)) : 0xffffffff;
101 /* Create a range if not specified */
102 if (!(iface->dhcpv4_start.s_addr & htonl(0xffff0000)) &&
103 !(iface->dhcpv4_end.s_addr & htonl(0xffff0000)) &&
105 struct in_addr *addr = &iface->addr4[0].addr.in;
107 uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
108 uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
110 if (start && end && start < end &&
111 start > ntohl(addr->s_addr & ~mask) &&
112 (start & ntohl(~mask)) == start &&
113 (end & ntohl(~mask)) == end) {
114 iface->dhcpv4_start.s_addr = htonl(start) |
115 (addr->s_addr & mask);
116 iface->dhcpv4_end.s_addr = htonl(end) |
117 (addr->s_addr & mask);
118 } else if (ntohl(mask) <= 0xfffffff0) {
119 start = addr->s_addr & mask;
120 end = addr->s_addr & mask;
122 if (ntohl(mask) <= 0xffffff00) {
123 iface->dhcpv4_start.s_addr = start | htonl(100);
124 iface->dhcpv4_end.s_addr = end | htonl(250);
125 } else if (ntohl(mask) <= 0xffffffc0) {
126 iface->dhcpv4_start.s_addr = start | htonl(10);
127 iface->dhcpv4_end.s_addr = end | htonl(60);
128 } else if (ntohl(mask) <= 0xffffffe0) {
129 iface->dhcpv4_start.s_addr = start | htonl(10);
130 iface->dhcpv4_end.s_addr = end | htonl(30);
132 iface->dhcpv4_start.s_addr = start | htonl(3);
133 iface->dhcpv4_end.s_addr = end | htonl(12);
138 /* Parse static entries */
140 list_for_each_entry(lease, &leases, head) {
141 /* Construct entry */
142 struct dhcpv4_assignment *a = calloc(1, sizeof(*a));
144 syslog(LOG_ERR, "Calloc failed for static lease on interface %s",
149 a->leasetime = lease->dhcpv4_leasetime;
151 a->addr = ntohl(lease->ipaddr.s_addr);
152 memcpy(a->hwaddr, lease->mac.ether_addr_octet, sizeof(a->hwaddr));
153 /* Static assignment */
154 a->flags |= OAF_STATIC;
158 /* Assign to all interfaces */
159 struct dhcpv4_assignment *c;
160 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
161 if (c->addr > a->addr) {
162 list_add_tail(&a->head, &c->head);
164 } else if (c->addr == a->addr)
165 /* Already an assignment with that number */
169 if (&c->head == &iface->dhcpv4_assignments)
170 list_add(&a->head, &iface->dhcpv4_assignments);
173 if (lease->hostname[0]) {
175 a->hostname = strdup(lease->hostname);
178 free_dhcpv4_assignment(a);
181 // Clean invalid assignments
182 struct dhcpv4_assignment *a, *n;
183 list_for_each_entry_safe(a, n, &iface->dhcpv4_assignments, head) {
184 if ((htonl(a->addr) & mask) !=
185 (iface->dhcpv4_start.s_addr & mask))
186 free_dhcpv4_assignment(a);
189 iface->dhcpv4_event.uloop.fd = sock;
190 iface->dhcpv4_event.handle_dgram = handle_dhcpv4;
191 odhcpd_register(&iface->dhcpv4_event);
192 } else if (iface->dhcpv4_assignments.next) {
193 while (!list_empty(&iface->dhcpv4_assignments))
194 free_dhcpv4_assignment(list_first_entry(&iface->dhcpv4_assignments,
195 struct dhcpv4_assignment, head));
200 static char *dhcpv4_msg_to_string(uint8_t reqmsg)
203 case (DHCPV4_MSG_DISCOVER):
204 return "DHCPV4_MSG_DISCOVER";
205 case (DHCPV4_MSG_OFFER):
206 return "DHCPV4_MSG_OFFER";
207 case (DHCPV4_MSG_REQUEST):
208 return "DHCPV4_MSG_REQUEST";
209 case (DHCPV4_MSG_DECLINE):
210 return "DHCPV4_MSG_DECLINE";
211 case (DHCPV4_MSG_ACK):
212 return "DHCPV4_MSG_ACK";
213 case (DHCPV4_MSG_NAK):
214 return "DHCPV4_MSG_NAK";
215 case (DHCPV4_MSG_RELEASE):
216 return "DHCPV4_MSG_RELEASE";
217 case (DHCPV4_MSG_INFORM):
218 return "DHCPV4_MSG_INFORM";
224 static void free_dhcpv4_assignment(struct dhcpv4_assignment *a)
233 static void dhcpv4_put(struct dhcpv4_message *msg, uint8_t **cookie,
234 uint8_t type, uint8_t len, const void *data)
236 uint8_t *c = *cookie;
237 if (*cookie + 2 + len > (uint8_t*)&msg[1])
242 memcpy(c, data, len);
247 // Handler for DHCPv4 messages
248 static void handle_dhcpv4(void *addr, void *data, size_t len,
249 struct interface *iface, _unused void *dest_addr)
254 struct dhcpv4_message *req = data;
255 if (len < offsetof(struct dhcpv4_message, options) + 4 ||
256 req->op != DHCPV4_BOOTREQUEST || req->hlen != 6)
260 syslog(LOG_NOTICE, "Got DHCPv4 request");
262 if (!iface->addr4_len) {
263 syslog(LOG_WARNING, "DHCPv4 no address found on %s", iface->name);
267 struct in_addr *ifaddr = &iface->addr4[0].addr.in;
268 struct in_addr *ifbroadcast = &iface->addr4[0].broadcast;
269 uint32_t mask = iface->addr4[0].prefix ? htonl(~((1 << (32 - iface->addr4[0].prefix)) - 1)) : 0;
270 uint32_t network = iface->addr4[0].addr.in.s_addr & mask;
271 int sock = iface->dhcpv4_event.uloop.fd;
273 if ((iface->dhcpv4_start.s_addr & mask) != network ||
274 (iface->dhcpv4_end.s_addr & mask) != network) {
275 syslog(LOG_WARNING, "DHCPv4 range out of assigned network");
279 struct dhcpv4_message reply = {
280 .op = DHCPV4_BOOTREPLY,
287 .ciaddr = {INADDR_ANY},
288 .giaddr = req->giaddr,
291 memcpy(reply.chaddr, req->chaddr, sizeof(reply.chaddr));
293 reply.options[0] = 0x63;
294 reply.options[1] = 0x82;
295 reply.options[2] = 0x53;
296 reply.options[3] = 0x63;
298 uint8_t *cookie = &reply.options[4];
299 uint8_t reqmsg = DHCPV4_MSG_REQUEST;
300 uint8_t msg = DHCPV4_MSG_ACK;
302 struct in_addr reqaddr = {INADDR_ANY};
303 uint32_t leasetime = 0;
304 size_t hostname_len = 0;
307 uint8_t *start = &req->options[4];
308 uint8_t *end = ((uint8_t*)data) + len;
309 struct dhcpv4_option *opt;
310 dhcpv4_for_each_option(start, end, opt) {
311 if (opt->type == DHCPV4_OPT_MESSAGE && opt->len == 1)
312 reqmsg = opt->data[0];
313 else if (opt->type == DHCPV4_OPT_HOSTNAME && opt->len > 0) {
314 hostname_len = opt->len;
315 memcpy(hostname, opt->data, hostname_len);
316 hostname[hostname_len] = 0;
317 } else if (opt->type == DHCPV4_OPT_IPADDRESS && opt->len == 4)
318 memcpy(&reqaddr, opt->data, 4);
319 else if (opt->type == DHCPV4_OPT_SERVERID && opt->len == 4) {
320 if (memcmp(opt->data, ifaddr, 4))
322 } else if (iface->filter_class && opt->type == DHCPV4_OPT_USER_CLASS) {
323 uint8_t *c = opt->data, *cend = &opt->data[opt->len];
324 for (; c < cend && &c[*c] < cend; c = &c[1 + *c]) {
325 size_t elen = strlen(iface->filter_class);
326 if (*c == elen && !memcmp(&c[1], iface->filter_class, elen))
327 return; // Ignore from homenet
329 } else if (opt->type == DHCPV4_OPT_LEASETIME && opt->len == 4)
330 memcpy(&leasetime, opt->data, 4);
333 if (reqmsg != DHCPV4_MSG_DISCOVER && reqmsg != DHCPV4_MSG_REQUEST &&
334 reqmsg != DHCPV4_MSG_INFORM && reqmsg != DHCPV4_MSG_DECLINE &&
335 reqmsg != DHCPV4_MSG_RELEASE)
338 struct dhcpv4_assignment *lease = NULL;
339 if (reqmsg != DHCPV4_MSG_INFORM)
340 lease = dhcpv4_lease(iface, reqmsg, req->chaddr, reqaddr,
341 &leasetime, hostname, hostname_len);
344 if (reqmsg == DHCPV4_MSG_REQUEST)
345 msg = DHCPV4_MSG_NAK;
346 else if (reqmsg == DHCPV4_MSG_DISCOVER)
348 } else if (reqmsg == DHCPV4_MSG_DISCOVER)
349 msg = DHCPV4_MSG_OFFER;
350 else if (reqmsg == DHCPV4_MSG_REQUEST && reqaddr.s_addr &&
351 reqaddr.s_addr != htonl(lease->addr)) {
352 msg = DHCPV4_MSG_NAK;
354 * DHCP client requested an IP which we can't offer to him. Probably the
355 * client changed the network. The reply type is set to DHCPV4_MSG_NAK,
356 * because the client should not use that IP.
358 * For modern devices we build an answer that includes a valid IP, like
359 * a DHCPV4_MSG_ACK. The client will use that IP and doesn't need to
360 * perform additional DHCP round trips.
365 syslog(LOG_WARNING, "received %s from %02x:%02x:%02x:%02x:%02x:%02x",
366 dhcpv4_msg_to_string(reqmsg),
367 req->chaddr[0],req->chaddr[1],req->chaddr[2],
368 req->chaddr[3],req->chaddr[4],req->chaddr[5]);
370 if (reqmsg == DHCPV4_MSG_DECLINE || reqmsg == DHCPV4_MSG_RELEASE)
373 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MESSAGE, 1, &msg);
374 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SERVERID, 4, ifaddr);
379 reply.yiaddr.s_addr = htonl(lease->addr);
381 val = htonl(leasetime);
382 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_LEASETIME, 4, &val);
384 if (leasetime != UINT32_MAX) {
385 val = htonl(500 * leasetime / 1000);
386 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_RENEW, 4, &val);
388 val = htonl(875 * leasetime / 1000);
389 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_REBIND, 4, &val);
392 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_NETMASK, 4, &mask);
395 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_HOSTNAME,
396 strlen(lease->hostname), lease->hostname);
398 if (ifbroadcast->s_addr != INADDR_ANY)
399 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_BROADCAST, 4, ifbroadcast);
402 struct ifreq ifr = {.ifr_name = ""};
403 strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
405 if (!ioctl(sock, SIOCGIFMTU, &ifr)) {
406 uint16_t mtu = htons(ifr.ifr_mtu);
407 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MTU, 2, &mtu);
410 if (iface->search && iface->search_len <= 255)
411 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
412 iface->search_len, iface->search);
413 else if (!res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
414 uint8_t search_buf[256];
415 int len = dn_comp(_res.dnsrch[0], search_buf,
416 sizeof(search_buf), NULL, NULL);
418 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
422 if (iface->dhcpv4_router_cnt == 0)
423 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER, 4, ifaddr);
425 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER,
426 4 * iface->dhcpv4_router_cnt, iface->dhcpv4_router);
429 if (iface->dhcpv4_dns_cnt == 0)
430 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER, 4, ifaddr);
432 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER,
433 4 * iface->dhcpv4_dns_cnt, iface->dhcpv4_dns);
436 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_END, 0, NULL);
438 struct sockaddr_in dest = *((struct sockaddr_in*)addr);
439 if (req->giaddr.s_addr) {
441 * relay agent is configured, send reply to the agent
443 dest.sin_addr = req->giaddr;
444 dest.sin_port = htons(DHCPV4_SERVER_PORT);
445 } else if (req->ciaddr.s_addr && req->ciaddr.s_addr != dest.sin_addr.s_addr) {
447 * client has existing configuration (ciaddr is set) AND this address is
448 * not the address it used for the dhcp message
450 dest.sin_addr = req->ciaddr;
451 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
452 } else if ((ntohs(req->flags) & DHCPV4_FLAG_BROADCAST) ||
453 req->hlen != reply.hlen || !reply.yiaddr.s_addr) {
455 * client requests a broadcast reply OR we can't offer an IP
457 dest.sin_addr.s_addr = INADDR_BROADCAST;
458 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
459 } else if (!req->ciaddr.s_addr && msg == DHCPV4_MSG_NAK) {
461 * client has no previous configuration -> no IP, so we need to reply
462 * with a broadcast packet
464 dest.sin_addr.s_addr = INADDR_BROADCAST;
465 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
468 * send reply to the newly (in this proccess) allocated IP
470 dest.sin_addr = reply.yiaddr;
471 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
473 struct arpreq arp = {.arp_flags = ATF_COM};
474 memcpy(arp.arp_ha.sa_data, req->chaddr, 6);
475 memcpy(&arp.arp_pa, &dest, sizeof(arp.arp_pa));
476 memcpy(arp.arp_dev, iface->ifname, sizeof(arp.arp_dev));
477 ioctl(sock, SIOCSARP, &arp);
480 if (dest.sin_addr.s_addr == INADDR_BROADCAST)
481 /* reply goes to IP broadcast -> MAC broadcast */
482 syslog(LOG_WARNING, "sending %s to ff:ff:ff:ff:ff:ff - %s",
483 dhcpv4_msg_to_string(msg),
484 inet_ntoa(dest.sin_addr));
487 * reply is send directly to IP,
488 * MAC is assumed to be the same as the request
490 syslog(LOG_WARNING, "sending %s to %02x:%02x:%02x:%02x:%02x:%02x - %s",
491 dhcpv4_msg_to_string(msg),
492 req->chaddr[0],req->chaddr[1],req->chaddr[2],
493 req->chaddr[3],req->chaddr[4],req->chaddr[5],
494 inet_ntoa(dest.sin_addr));
496 sendto(sock, &reply, sizeof(reply), MSG_DONTWAIT,
497 (struct sockaddr*)&dest, sizeof(dest));
500 static bool dhcpv4_test(struct interface *iface, uint32_t try)
502 struct dhcpv4_assignment *c;
503 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
512 static bool dhcpv4_assign(struct interface *iface,
513 struct dhcpv4_assignment *assign, uint32_t raddr)
515 uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
516 uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
517 uint32_t count = end - start + 1;
519 // try to assign the IP the client asked for
520 if (start <= raddr && raddr <= end && dhcpv4_test(iface, raddr)) {
521 assign->addr = raddr;
522 syslog(LOG_INFO, "assigning the IP the client asked for: %u.%u.%u.%u",
523 (assign->addr & 0xff000000) >> 24,
524 (assign->addr & 0x00ff0000) >> 16,
525 (assign->addr & 0x0000ff00) >> 8,
526 (assign->addr & 0x000000ff));
530 // Seed RNG with checksum of hwaddress
532 for (size_t i = 0; i < sizeof(assign->hwaddr); ++i) {
533 // Knuth's multiplicative method
534 uint8_t o = assign->hwaddr[i];
535 seed += (o*2654435761) % UINT32_MAX;
540 uint32_t try = (((uint32_t)rand()) % count) + start;
542 if (list_empty(&iface->dhcpv4_assignments)) {
544 syslog(LOG_INFO, "assigning mapped IP (empty list): %u.%u.%u.%u",
545 (assign->addr & 0xff000000) >> 24,
546 (assign->addr & 0x00ff0000) >> 16,
547 (assign->addr & 0x0000ff00) >> 8,
548 (assign->addr & 0x000000ff));
552 for (uint32_t i = 0; i < count; ++i) {
553 if (dhcpv4_test(iface, try)) {
554 /* test was successful: IP address is not assigned, assign it */
556 syslog(LOG_DEBUG, "assigning mapped IP: %u.%u.%u.%u (try %u of %u)",
557 (assign->addr & 0xff000000) >> 24,
558 (assign->addr & 0x00ff0000) >> 16,
559 (assign->addr & 0x0000ff00) >> 8,
560 (assign->addr & 0x000000ff), i, count);
563 try = (((try - start) + 1) % count) + start;
566 syslog(LOG_WARNING, "can't assign any IP address -> address space is full");
571 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
572 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
573 uint32_t *leasetime, const char *hostname, const size_t hostname_len)
575 struct dhcpv4_assignment *lease = NULL;
576 uint32_t raddr = ntohl(reqaddr.s_addr);
577 time_t now = odhcpd_time();
579 struct dhcpv4_assignment *c, *n, *a = NULL;
580 list_for_each_entry_safe(c, n, &iface->dhcpv4_assignments, head) {
581 if (!memcmp(c->hwaddr, mac, 6)) {
583 if (c->addr == raddr)
585 } else if (!INFINITE_VALID(c->valid_until) && c->valid_until < now)
586 free_dhcpv4_assignment(c);
589 if (msg == DHCPV4_MSG_DISCOVER || msg == DHCPV4_MSG_REQUEST) {
592 if (!a && !iface->no_dynamic_dhcp) {
593 /* Create new binding */
594 a = calloc(1, sizeof(*a));
596 syslog(LOG_ERR, "Failed to calloc binding on interface %s", iface->ifname);
599 memcpy(a->hwaddr, mac, sizeof(a->hwaddr));
600 /* Don't consider new assignment as infinite */
601 a->valid_until = now;
603 assigned = dhcpv4_assign(iface, a, raddr);
605 list_add(&a->head, &iface->dhcpv4_assignments);
609 uint32_t my_leasetime;
612 my_leasetime = a->leasetime;
614 my_leasetime = iface->dhcpv4_leasetime;
616 if ((*leasetime == 0) || (my_leasetime < *leasetime))
617 *leasetime = my_leasetime;
619 if (msg == DHCPV4_MSG_DISCOVER) {
620 a->flags &= ~OAF_BOUND;
622 if (!(a->flags & OAF_STATIC))
623 a->valid_until = now;
625 if (hostname_len > 0) {
626 a->hostname = realloc(a->hostname, hostname_len + 1);
628 memcpy(a->hostname, hostname, hostname_len);
629 a->hostname[hostname_len] = 0;
633 a->flags |= OAF_BOUND;
635 if (!(a->flags & OAF_STATIC))
636 a->valid_until = ((*leasetime == UINT32_MAX) ? 0 : (time_t)(now + *leasetime));
638 } else if (!assigned && a) {
639 /* Cleanup failed assignment */
640 free_dhcpv4_assignment(a);
646 } else if (msg == DHCPV4_MSG_RELEASE && a) {
647 a->flags &= ~OAF_BOUND;
649 if (!(a->flags & OAF_STATIC))
650 a->valid_until = now - 1;
652 } else if (msg == DHCPV4_MSG_DECLINE && a) {
653 a->flags &= ~OAF_BOUND;
655 if (!(a->flags & OAF_STATIC)) {
656 memset(a->hwaddr, 0, sizeof(a->hwaddr));
657 a->valid_until = now + 3600; /* Block address for 1h */
661 dhcpv6_write_statefile();