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[0].prefix ? htonl(~((1 << (32 - iface->addr4[0].prefix)) - 1)) : 0;
100 /* Create a range if not specified */
101 if (!(iface->dhcpv4_start.s_addr & htonl(0xffff0000)) &&
102 !(iface->dhcpv4_end.s_addr & htonl(0xffff0000)) &&
104 struct in_addr *addr = &iface->addr4[0].addr.in;
106 uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
107 uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
109 if (start && end && start < end &&
110 start > ntohl(addr->s_addr & ~mask) &&
111 (start & ntohl(~mask)) == start &&
112 (end & ntohl(~mask)) == end) {
113 iface->dhcpv4_start.s_addr = htonl(start) |
114 (addr->s_addr & mask);
115 iface->dhcpv4_end.s_addr = htonl(end) |
116 (addr->s_addr & mask);
117 } else if (ntohl(mask) <= 0xfffffff0) {
118 start = addr->s_addr & mask;
119 end = addr->s_addr & mask;
121 if (ntohl(mask) <= 0xffffff00) {
122 iface->dhcpv4_start.s_addr = start | htonl(100);
123 iface->dhcpv4_end.s_addr = end | htonl(250);
124 } else if (ntohl(mask) <= 0xffffffc0) {
125 iface->dhcpv4_start.s_addr = start | htonl(10);
126 iface->dhcpv4_end.s_addr = end | htonl(60);
127 } else if (ntohl(mask) <= 0xffffffe0) {
128 iface->dhcpv4_start.s_addr = start | htonl(10);
129 iface->dhcpv4_end.s_addr = end | htonl(30);
131 iface->dhcpv4_start.s_addr = start | htonl(3);
132 iface->dhcpv4_end.s_addr = end | htonl(12);
137 /* Parse static entries */
139 list_for_each_entry(lease, &leases, head) {
140 /* Construct entry */
141 struct dhcpv4_assignment *a = calloc(1, sizeof(*a));
143 syslog(LOG_ERR, "Calloc failed for static lease on interface %s",
148 a->leasetime = lease->dhcpv4_leasetime;
150 a->addr = ntohl(lease->ipaddr.s_addr);
151 memcpy(a->hwaddr, lease->mac.ether_addr_octet, sizeof(a->hwaddr));
152 /* Static assignment */
153 a->flags |= OAF_STATIC;
157 /* Assign to all interfaces */
158 struct dhcpv4_assignment *c;
159 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
160 if (c->addr > a->addr) {
161 list_add_tail(&a->head, &c->head);
163 } else if (c->addr == a->addr)
164 /* Already an assignment with that number */
168 if (&c->head == &iface->dhcpv4_assignments)
169 list_add(&a->head, &iface->dhcpv4_assignments);
172 if (lease->hostname[0]) {
174 a->hostname = strdup(lease->hostname);
177 free_dhcpv4_assignment(a);
180 // Clean invalid assignments
181 struct dhcpv4_assignment *a, *n;
182 list_for_each_entry_safe(a, n, &iface->dhcpv4_assignments, head) {
183 if ((htonl(a->addr) & mask) !=
184 (iface->dhcpv4_start.s_addr & mask))
185 free_dhcpv4_assignment(a);
188 iface->dhcpv4_event.uloop.fd = sock;
189 iface->dhcpv4_event.handle_dgram = handle_dhcpv4;
190 odhcpd_register(&iface->dhcpv4_event);
191 } else if (iface->dhcpv4_assignments.next) {
192 while (!list_empty(&iface->dhcpv4_assignments))
193 free_dhcpv4_assignment(list_first_entry(&iface->dhcpv4_assignments,
194 struct dhcpv4_assignment, head));
199 static char *dhcpv4_msg_to_string(uint8_t reqmsg)
202 case (DHCPV4_MSG_DISCOVER):
203 return "DHCPV4_MSG_DISCOVER";
204 case (DHCPV4_MSG_OFFER):
205 return "DHCPV4_MSG_OFFER";
206 case (DHCPV4_MSG_REQUEST):
207 return "DHCPV4_MSG_REQUEST";
208 case (DHCPV4_MSG_DECLINE):
209 return "DHCPV4_MSG_DECLINE";
210 case (DHCPV4_MSG_ACK):
211 return "DHCPV4_MSG_ACK";
212 case (DHCPV4_MSG_NAK):
213 return "DHCPV4_MSG_NAK";
214 case (DHCPV4_MSG_RELEASE):
215 return "DHCPV4_MSG_RELEASE";
216 case (DHCPV4_MSG_INFORM):
217 return "DHCPV4_MSG_INFORM";
223 static void free_dhcpv4_assignment(struct dhcpv4_assignment *a)
232 static void dhcpv4_put(struct dhcpv4_message *msg, uint8_t **cookie,
233 uint8_t type, uint8_t len, const void *data)
235 uint8_t *c = *cookie;
236 if (*cookie + 2 + len > (uint8_t*)&msg[1])
241 memcpy(c, data, len);
246 // Handler for DHCPv4 messages
247 static void handle_dhcpv4(void *addr, void *data, size_t len,
248 struct interface *iface, _unused void *dest_addr)
253 struct dhcpv4_message *req = data;
254 if (len < offsetof(struct dhcpv4_message, options) + 4 ||
255 req->op != DHCPV4_BOOTREQUEST || req->hlen != 6)
259 syslog(LOG_NOTICE, "Got DHCPv4 request");
261 if (!iface->addr4_len) {
262 syslog(LOG_WARNING, "DHCPv4 no address found on %s", iface->name);
266 struct in_addr *ifaddr = &iface->addr4[0].addr.in;
267 struct in_addr *ifbroadcast = &iface->addr4[0].broadcast;
268 uint32_t mask = iface->addr4[0].prefix ? htonl(~((1 << (32 - iface->addr4[0].prefix)) - 1)) : 0;
269 uint32_t network = iface->addr4[0].addr.in.s_addr & mask;
270 int sock = iface->dhcpv4_event.uloop.fd;
272 if ((iface->dhcpv4_start.s_addr & mask) != network ||
273 (iface->dhcpv4_end.s_addr & mask) != network) {
274 syslog(LOG_WARNING, "DHCPv4 range out of assigned network");
278 struct dhcpv4_message reply = {
279 .op = DHCPV4_BOOTREPLY,
286 .ciaddr = {INADDR_ANY},
287 .giaddr = req->giaddr,
290 memcpy(reply.chaddr, req->chaddr, sizeof(reply.chaddr));
292 reply.options[0] = 0x63;
293 reply.options[1] = 0x82;
294 reply.options[2] = 0x53;
295 reply.options[3] = 0x63;
297 uint8_t *cookie = &reply.options[4];
298 uint8_t reqmsg = DHCPV4_MSG_REQUEST;
299 uint8_t msg = DHCPV4_MSG_ACK;
301 struct in_addr reqaddr = {INADDR_ANY};
302 uint32_t leasetime = 0;
303 size_t hostname_len = 0;
306 uint8_t *start = &req->options[4];
307 uint8_t *end = ((uint8_t*)data) + len;
308 struct dhcpv4_option *opt;
309 dhcpv4_for_each_option(start, end, opt) {
310 if (opt->type == DHCPV4_OPT_MESSAGE && opt->len == 1)
311 reqmsg = opt->data[0];
312 else if (opt->type == DHCPV4_OPT_HOSTNAME && opt->len > 0) {
313 hostname_len = opt->len;
314 memcpy(hostname, opt->data, hostname_len);
315 hostname[hostname_len] = 0;
316 } else if (opt->type == DHCPV4_OPT_IPADDRESS && opt->len == 4)
317 memcpy(&reqaddr, opt->data, 4);
318 else if (opt->type == DHCPV4_OPT_SERVERID && opt->len == 4) {
319 if (memcmp(opt->data, ifaddr, 4))
321 } else if (iface->filter_class && opt->type == DHCPV4_OPT_USER_CLASS) {
322 uint8_t *c = opt->data, *cend = &opt->data[opt->len];
323 for (; c < cend && &c[*c] < cend; c = &c[1 + *c]) {
324 size_t elen = strlen(iface->filter_class);
325 if (*c == elen && !memcmp(&c[1], iface->filter_class, elen))
326 return; // Ignore from homenet
328 } else if (opt->type == DHCPV4_OPT_LEASETIME && opt->len == 4)
329 memcpy(&leasetime, opt->data, 4);
332 if (reqmsg != DHCPV4_MSG_DISCOVER && reqmsg != DHCPV4_MSG_REQUEST &&
333 reqmsg != DHCPV4_MSG_INFORM && reqmsg != DHCPV4_MSG_DECLINE &&
334 reqmsg != DHCPV4_MSG_RELEASE)
337 struct dhcpv4_assignment *lease = NULL;
338 if (reqmsg != DHCPV4_MSG_INFORM)
339 lease = dhcpv4_lease(iface, reqmsg, req->chaddr, reqaddr,
340 &leasetime, hostname, hostname_len);
343 if (reqmsg == DHCPV4_MSG_REQUEST)
344 msg = DHCPV4_MSG_NAK;
345 else if (reqmsg == DHCPV4_MSG_DISCOVER)
347 } else if (reqmsg == DHCPV4_MSG_DISCOVER)
348 msg = DHCPV4_MSG_OFFER;
349 else if (reqmsg == DHCPV4_MSG_REQUEST && reqaddr.s_addr &&
350 reqaddr.s_addr != htonl(lease->addr)) {
351 msg = DHCPV4_MSG_NAK;
353 * DHCP client requested an IP which we can't offer to him. Probably the
354 * client changed the network. The reply type is set to DHCPV4_MSG_NAK,
355 * because the client should not use that IP.
357 * For modern devices we build an answer that includes a valid IP, like
358 * a DHCPV4_MSG_ACK. The client will use that IP and doesn't need to
359 * perform additional DHCP round trips.
364 syslog(LOG_WARNING, "received %s from %02x:%02x:%02x:%02x:%02x:%02x",
365 dhcpv4_msg_to_string(reqmsg),
366 req->chaddr[0],req->chaddr[1],req->chaddr[2],
367 req->chaddr[3],req->chaddr[4],req->chaddr[5]);
369 if (reqmsg == DHCPV4_MSG_DECLINE || reqmsg == DHCPV4_MSG_RELEASE)
372 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MESSAGE, 1, &msg);
373 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SERVERID, 4, ifaddr);
378 reply.yiaddr.s_addr = htonl(lease->addr);
380 val = htonl(leasetime);
381 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_LEASETIME, 4, &val);
383 if (leasetime != UINT32_MAX) {
384 val = htonl(500 * leasetime / 1000);
385 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_RENEW, 4, &val);
387 val = htonl(875 * leasetime / 1000);
388 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_REBIND, 4, &val);
391 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_NETMASK, 4, &mask);
394 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_HOSTNAME,
395 strlen(lease->hostname), lease->hostname);
397 if (ifbroadcast->s_addr != INADDR_ANY)
398 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_BROADCAST, 4, ifbroadcast);
401 struct ifreq ifr = {.ifr_name = ""};
402 strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
404 if (!ioctl(sock, SIOCGIFMTU, &ifr)) {
405 uint16_t mtu = htons(ifr.ifr_mtu);
406 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MTU, 2, &mtu);
409 if (iface->search && iface->search_len <= 255)
410 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
411 iface->search_len, iface->search);
412 else if (!res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
413 uint8_t search_buf[256];
414 int len = dn_comp(_res.dnsrch[0], search_buf,
415 sizeof(search_buf), NULL, NULL);
417 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
421 if (iface->dhcpv4_router_cnt == 0)
422 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER, 4, ifaddr);
424 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER,
425 4 * iface->dhcpv4_router_cnt, iface->dhcpv4_router);
428 if (iface->dhcpv4_dns_cnt == 0)
429 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER, 4, ifaddr);
431 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER,
432 4 * iface->dhcpv4_dns_cnt, iface->dhcpv4_dns);
435 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_END, 0, NULL);
437 struct sockaddr_in dest = *((struct sockaddr_in*)addr);
438 if (req->giaddr.s_addr) {
440 * relay agent is configured, send reply to the agent
442 dest.sin_addr = req->giaddr;
443 dest.sin_port = htons(DHCPV4_SERVER_PORT);
444 } else if (req->ciaddr.s_addr && req->ciaddr.s_addr != dest.sin_addr.s_addr) {
446 * client has existing configuration (ciaddr is set) AND this address is
447 * not the address it used for the dhcp message
449 dest.sin_addr = req->ciaddr;
450 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
451 } else if ((ntohs(req->flags) & DHCPV4_FLAG_BROADCAST) ||
452 req->hlen != reply.hlen || !reply.yiaddr.s_addr) {
454 * client requests a broadcast reply OR we can't offer an IP
456 dest.sin_addr.s_addr = INADDR_BROADCAST;
457 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
458 } else if (!req->ciaddr.s_addr && msg == DHCPV4_MSG_NAK) {
460 * client has no previous configuration -> no IP, so we need to reply
461 * with a broadcast packet
463 dest.sin_addr.s_addr = INADDR_BROADCAST;
464 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
467 * send reply to the newly (in this proccess) allocated IP
469 dest.sin_addr = reply.yiaddr;
470 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
472 struct arpreq arp = {.arp_flags = ATF_COM};
473 memcpy(arp.arp_ha.sa_data, req->chaddr, 6);
474 memcpy(&arp.arp_pa, &dest, sizeof(arp.arp_pa));
475 memcpy(arp.arp_dev, iface->ifname, sizeof(arp.arp_dev));
476 ioctl(sock, SIOCSARP, &arp);
479 if (dest.sin_addr.s_addr == INADDR_BROADCAST)
480 /* reply goes to IP broadcast -> MAC broadcast */
481 syslog(LOG_WARNING, "sending %s to ff:ff:ff:ff:ff:ff - %s",
482 dhcpv4_msg_to_string(msg),
483 inet_ntoa(dest.sin_addr));
486 * reply is send directly to IP,
487 * MAC is assumed to be the same as the request
489 syslog(LOG_WARNING, "sending %s to %02x:%02x:%02x:%02x:%02x:%02x - %s",
490 dhcpv4_msg_to_string(msg),
491 req->chaddr[0],req->chaddr[1],req->chaddr[2],
492 req->chaddr[3],req->chaddr[4],req->chaddr[5],
493 inet_ntoa(dest.sin_addr));
495 sendto(sock, &reply, sizeof(reply), MSG_DONTWAIT,
496 (struct sockaddr*)&dest, sizeof(dest));
499 static bool dhcpv4_test(struct interface *iface, uint32_t try)
501 struct dhcpv4_assignment *c;
502 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
511 static bool dhcpv4_assign(struct interface *iface,
512 struct dhcpv4_assignment *assign, uint32_t raddr)
514 uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
515 uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
516 uint32_t count = end - start + 1;
518 // try to assign the IP the client asked for
519 if (start <= raddr && raddr <= end && dhcpv4_test(iface, raddr)) {
520 assign->addr = raddr;
521 syslog(LOG_INFO, "assigning the IP the client asked for: %u.%u.%u.%u",
522 (assign->addr & 0xff000000) >> 24,
523 (assign->addr & 0x00ff0000) >> 16,
524 (assign->addr & 0x0000ff00) >> 8,
525 (assign->addr & 0x000000ff));
529 // Seed RNG with checksum of hwaddress
531 for (size_t i = 0; i < sizeof(assign->hwaddr); ++i) {
532 // Knuth's multiplicative method
533 uint8_t o = assign->hwaddr[i];
534 seed += (o*2654435761) % UINT32_MAX;
539 uint32_t try = (((uint32_t)rand()) % count) + start;
541 if (list_empty(&iface->dhcpv4_assignments)) {
543 syslog(LOG_INFO, "assigning mapped IP (empty list): %u.%u.%u.%u",
544 (assign->addr & 0xff000000) >> 24,
545 (assign->addr & 0x00ff0000) >> 16,
546 (assign->addr & 0x0000ff00) >> 8,
547 (assign->addr & 0x000000ff));
551 for (uint32_t i = 0; i < count; ++i) {
552 if (dhcpv4_test(iface, try)) {
553 /* test was successful: IP address is not assigned, assign it */
555 syslog(LOG_DEBUG, "assigning mapped IP: %u.%u.%u.%u (try %u of %u)",
556 (assign->addr & 0xff000000) >> 24,
557 (assign->addr & 0x00ff0000) >> 16,
558 (assign->addr & 0x0000ff00) >> 8,
559 (assign->addr & 0x000000ff), i, count);
562 try = (((try - start) + 1) % count) + start;
565 syslog(LOG_WARNING, "can't assign any IP address -> address space is full");
570 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
571 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
572 uint32_t *leasetime, const char *hostname, const size_t hostname_len)
574 struct dhcpv4_assignment *lease = NULL;
575 uint32_t raddr = ntohl(reqaddr.s_addr);
576 time_t now = odhcpd_time();
578 struct dhcpv4_assignment *c, *n, *a = NULL;
579 list_for_each_entry_safe(c, n, &iface->dhcpv4_assignments, head) {
580 if (!memcmp(c->hwaddr, mac, 6)) {
582 if (c->addr == raddr)
584 } else if (!INFINITE_VALID(c->valid_until) && c->valid_until < now)
585 free_dhcpv4_assignment(c);
588 if (msg == DHCPV4_MSG_DISCOVER || msg == DHCPV4_MSG_REQUEST) {
591 if (!a && !iface->no_dynamic_dhcp) {
592 /* Create new binding */
593 a = calloc(1, sizeof(*a));
595 syslog(LOG_ERR, "Failed to calloc binding on interface %s", iface->ifname);
598 memcpy(a->hwaddr, mac, sizeof(a->hwaddr));
599 /* Don't consider new assignment as infinite */
600 a->valid_until = now;
602 assigned = dhcpv4_assign(iface, a, raddr);
604 list_add(&a->head, &iface->dhcpv4_assignments);
608 uint32_t my_leasetime;
611 my_leasetime = a->leasetime;
613 my_leasetime = iface->dhcpv4_leasetime;
615 if ((*leasetime == 0) || (my_leasetime < *leasetime))
616 *leasetime = my_leasetime;
618 if (msg == DHCPV4_MSG_DISCOVER) {
619 a->flags &= ~OAF_BOUND;
621 if (!(a->flags & OAF_STATIC))
622 a->valid_until = now;
624 if (hostname_len > 0) {
625 a->hostname = realloc(a->hostname, hostname_len + 1);
627 memcpy(a->hostname, hostname, hostname_len);
628 a->hostname[hostname_len] = 0;
632 a->flags |= OAF_BOUND;
634 if (!(a->flags & OAF_STATIC))
635 a->valid_until = ((*leasetime == UINT32_MAX) ? 0 : (time_t)(now + *leasetime));
637 } else if (!assigned && a) {
638 /* Cleanup failed assignment */
639 free_dhcpv4_assignment(a);
645 } else if (msg == DHCPV4_MSG_RELEASE && a) {
646 a->flags &= ~OAF_BOUND;
648 if (!(a->flags & OAF_STATIC))
649 a->valid_until = now - 1;
651 } else if (msg == DHCPV4_MSG_DECLINE && a) {
652 a->flags &= ~OAF_BOUND;
654 if (!(a->flags & OAF_STATIC)) {
655 memset(a->hwaddr, 0, sizeof(a->hwaddr));
656 a->valid_until = now + 3600; /* Block address for 1h */
660 dhcpv6_write_statefile();