2 * Copyright (C) 2012-2013 Steven Barth <steven@midlink.org>
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.
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.
25 #include <net/if_arp.h>
26 #include <netinet/ip.h>
27 #include <sys/ioctl.h>
28 #include <sys/timerfd.h>
29 #include <arpa/inet.h>
36 static void handle_dhcpv4(void *addr, void *data, size_t len,
37 struct interface *iface, void *dest_addr);
38 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
39 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
40 const char *hostname);
42 // Create socket and register events
48 char *dhcpv4_msg_to_string(uint8_t reqmsg)
51 case (DHCPV4_MSG_DISCOVER):
52 return "DHCPV4_MSG_DISCOVER";
53 case (DHCPV4_MSG_OFFER):
54 return "DHCPV4_MSG_OFFER";
55 case (DHCPV4_MSG_REQUEST):
56 return "DHCPV4_MSG_REQUEST";
57 case (DHCPV4_MSG_DECLINE):
58 return "DHCPV4_MSG_DECLINE";
59 case (DHCPV4_MSG_ACK):
60 return "DHCPV4_MSG_ACK";
61 case (DHCPV4_MSG_NAK):
62 return "DHCPV4_MSG_NAK";
63 case (DHCPV4_MSG_RELEASE):
64 return "DHCPV4_MSG_RELEASE";
65 case (DHCPV4_MSG_INFORM):
66 return "DHCPV4_MSG_INFORM";
72 int setup_dhcpv4_interface(struct interface *iface, bool enable)
74 if (iface->dhcpv4_event.uloop.fd > 0) {
75 uloop_fd_delete(&iface->dhcpv4_event.uloop);
76 close(iface->dhcpv4_event.uloop.fd);
77 iface->dhcpv4_event.uloop.fd = -1;
80 if (iface->dhcpv4 && enable) {
81 if (!iface->dhcpv4_assignments.next)
82 INIT_LIST_HEAD(&iface->dhcpv4_assignments);
84 int sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
86 syslog(LOG_ERR, "Failed to create DHCPv4 server socket: %s",
91 // Basic IPv6 configuration
93 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
94 setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &val, sizeof(val));
95 setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &val, sizeof(val));
97 val = IPTOS_PREC_INTERNETCONTROL;
98 setsockopt(sock, IPPROTO_IP, IP_TOS, &val, sizeof(val));
100 val = IP_PMTUDISC_DONT;
101 setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val));
103 setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE,
104 iface->ifname, strlen(iface->ifname));
106 struct sockaddr_in bind_addr = {AF_INET, htons(DHCPV4_SERVER_PORT),
109 if (bind(sock, (struct sockaddr*)&bind_addr, sizeof(bind_addr))) {
110 syslog(LOG_ERR, "Failed to open DHCPv4 server socket: %s",
116 if (ntohl(iface->dhcpv4_start.s_addr) > ntohl(iface->dhcpv4_end.s_addr)) {
117 syslog(LOG_ERR, "Invalid DHCP range");
121 // Create a range if not specified
122 if (!(iface->dhcpv4_start.s_addr & htonl(0xffff0000)) &&
123 !(iface->dhcpv4_end.s_addr & htonl(0xffff0000))) {
125 struct in_addr *saddr = ubus_get_address4(iface->name);
126 struct in_addr addr = { .s_addr = saddr->s_addr } ;
127 struct in_addr *smask = ubus_get_mask4(iface->name);
128 struct in_addr mask = { .s_addr = smask->s_addr } ;
130 uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
131 uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
133 if (start && end && start < end &&
134 start > ntohl(addr.s_addr & ~mask.s_addr) &&
135 (start & ntohl(~mask.s_addr)) == start &&
136 (end & ntohl(~mask.s_addr)) == end) {
137 iface->dhcpv4_start.s_addr = htonl(start) |
138 (addr.s_addr & mask.s_addr);
139 iface->dhcpv4_end.s_addr = htonl(end) |
140 (addr.s_addr & mask.s_addr);
141 } else if (ntohl(mask.s_addr) <= 0xfffffff0) {
142 start = addr.s_addr & mask.s_addr;
143 end = addr.s_addr & mask.s_addr;
145 if (ntohl(mask.s_addr) <= 0xffffff00) {
146 iface->dhcpv4_start.s_addr = start | htonl(100);
147 iface->dhcpv4_end.s_addr = end | htonl(250);
148 } else if (ntohl(mask.s_addr) <= 0xffffffc0) {
149 iface->dhcpv4_start.s_addr = start | htonl(10);
150 iface->dhcpv4_end.s_addr = end | htonl(60);
151 } else if (ntohl(mask.s_addr) <= 0xffffffe0) {
152 iface->dhcpv4_start.s_addr = start | htonl(10);
153 iface->dhcpv4_end.s_addr = end | htonl(30);
155 iface->dhcpv4_start.s_addr = start | htonl(3);
156 iface->dhcpv4_end.s_addr = end | htonl(12);
163 // Parse static entries
165 list_for_each_entry(lease, &leases, head) {
167 size_t hostlen = strlen(lease->hostname) + 1;
168 struct dhcpv4_assignment *a = calloc(1, sizeof(*a) + hostlen);
170 syslog(LOG_ERR, "Calloc failed for static lease on interface %s",
174 a->addr = ntohl(lease->ipaddr.s_addr);
175 memcpy(a->hwaddr, lease->mac.ether_addr_octet, sizeof(a->hwaddr));
176 memcpy(a->hostname, lease->hostname, hostlen);
177 a->valid_until = LONG_MAX;
179 // Assign to all interfaces
180 struct dhcpv4_assignment *c;
181 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
182 if (c->addr > a->addr) {
183 list_add_tail(&a->head, &c->head);
185 } else if (c->addr == a->addr) {
186 // Already an assignment with that number
190 if (&c->head == &iface->dhcpv4_assignments) {
191 list_add(&a->head, &iface->dhcpv4_assignments);
198 // Clean invalid assignments
199 struct dhcpv4_assignment *a, *n;
200 struct in_addr *smask = ubus_get_mask4(iface->name);
201 struct in_addr mask = { .s_addr = smask->s_addr } ;
202 list_for_each_entry_safe(a, n, &iface->dhcpv4_assignments, head) {
203 if ((htonl(a->addr) & mask.s_addr) !=
204 (iface->dhcpv4_start.s_addr & mask.s_addr)) {
211 if (iface->dhcpv4_leasetime < 60)
212 iface->dhcpv4_leasetime = 43200;
214 iface->dhcpv4_event.uloop.fd = sock;
215 iface->dhcpv4_event.handle_dgram = handle_dhcpv4;
216 odhcpd_register(&iface->dhcpv4_event);
217 } else if (iface->dhcpv4_assignments.next) {
218 while (!list_empty(&iface->dhcpv4_assignments)) {
219 struct dhcpv4_assignment *a = list_first_entry(&iface->dhcpv4_assignments,
220 struct dhcpv4_assignment, head);
230 static void dhcpv4_put(struct dhcpv4_message *msg, uint8_t **cookie,
231 uint8_t type, uint8_t len, const void *data)
233 uint8_t *c = *cookie;
234 if (*cookie + 2 + len > (uint8_t*)&msg[1])
239 memcpy(c, data, len);
245 // Simple DHCPv6-server for information requests
246 static void handle_dhcpv4(void *addr, void *data, size_t len,
247 struct interface *iface, _unused void *dest_addr)
252 struct dhcpv4_message *req = data;
253 if (len < offsetof(struct dhcpv4_message, options) + 4 ||
254 req->op != DHCPV4_BOOTREQUEST || req->hlen != 6)
257 int sock = iface->dhcpv4_event.uloop.fd;
258 struct sockaddr_in ifaddr;
259 struct sockaddr_in ifnetmask;
261 syslog(LOG_NOTICE, "Got DHCPv4 request");
264 memcpy(ifreq.ifr_name, iface->ifname, sizeof(ifreq.ifr_name));
265 if (ioctl(sock, SIOCGIFADDR, &ifreq)) {
266 syslog(LOG_WARNING, "DHCPv4 failed to detect address: %s", strerror(errno));
270 memcpy(&ifaddr, &ifreq.ifr_addr, sizeof(ifaddr));
271 if (ioctl(sock, SIOCGIFNETMASK, &ifreq))
274 memcpy(&ifnetmask, &ifreq.ifr_netmask, sizeof(ifnetmask));
275 uint32_t network = ifaddr.sin_addr.s_addr & ifnetmask.sin_addr.s_addr;
277 if ((iface->dhcpv4_start.s_addr & ifnetmask.sin_addr.s_addr) != network ||
278 (iface->dhcpv4_end.s_addr & ifnetmask.sin_addr.s_addr) != network) {
279 syslog(LOG_WARNING, "DHCPv4 range out of assigned network");
283 struct ifreq ifr = {.ifr_name = ""};
284 strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
286 struct dhcpv4_message reply = {
287 .op = DHCPV4_BOOTREPLY,
294 .ciaddr = {INADDR_ANY},
295 .giaddr = req->giaddr,
296 .siaddr = ifaddr.sin_addr,
298 memcpy(reply.chaddr, req->chaddr, sizeof(reply.chaddr));
300 reply.options[0] = 0x63;
301 reply.options[1] = 0x82;
302 reply.options[2] = 0x53;
303 reply.options[3] = 0x63;
305 uint8_t *cookie = &reply.options[4];
306 uint8_t reqmsg = DHCPV4_MSG_REQUEST;
307 uint8_t msg = DHCPV4_MSG_ACK;
309 struct in_addr reqaddr = {INADDR_ANY};
313 uint8_t *start = &req->options[4];
314 uint8_t *end = ((uint8_t*)data) + len;
315 struct dhcpv4_option *opt;
316 dhcpv4_for_each_option(start, end, opt) {
317 if (opt->type == DHCPV4_OPT_MESSAGE && opt->len == 1) {
318 reqmsg = opt->data[0];
319 } else if (opt->type == DHCPV4_OPT_HOSTNAME && opt->len > 0) {
320 memcpy(hostname, opt->data, opt->len);
321 hostname[opt->len] = 0;
322 } else if (opt->type == DHCPV4_OPT_IPADDRESS && opt->len == 4) {
323 memcpy(&reqaddr, opt->data, 4);
324 } else if (opt->type == DHCPV4_OPT_SERVERID && opt->len == 4) {
325 if (memcmp(opt->data, &ifaddr.sin_addr, 4))
327 } else if (iface->filter_class && opt->type == DHCPV4_OPT_USER_CLASS) {
328 uint8_t *c = opt->data, *cend = &opt->data[opt->len];
329 for (; c < cend && &c[*c] < cend; c = &c[1 + *c]) {
330 size_t elen = strlen(iface->filter_class);
331 if (*c == elen && !memcmp(&c[1], iface->filter_class, elen))
332 return; // Ignore from homenet
337 if (reqmsg != DHCPV4_MSG_DISCOVER && reqmsg != DHCPV4_MSG_REQUEST &&
338 reqmsg != DHCPV4_MSG_INFORM && reqmsg != DHCPV4_MSG_DECLINE &&
339 reqmsg != DHCPV4_MSG_RELEASE)
342 struct dhcpv4_assignment *lease = NULL;
343 if (reqmsg != DHCPV4_MSG_INFORM)
344 lease = dhcpv4_lease(iface, reqmsg, req->chaddr, reqaddr, hostname);
347 if (reqmsg == DHCPV4_MSG_REQUEST)
348 msg = DHCPV4_MSG_NAK;
349 else if (reqmsg == DHCPV4_MSG_DISCOVER)
351 } else if (reqmsg == DHCPV4_MSG_DISCOVER) {
352 msg = DHCPV4_MSG_OFFER;
353 } else if (reqmsg == DHCPV4_MSG_REQUEST && reqaddr.s_addr &&
354 reqaddr.s_addr != htonl(lease->addr)) {
355 msg = DHCPV4_MSG_NAK;
357 * DHCP client requested an IP which we can't offer to him. Probably the
358 * client changed the network. The reply type is set to DHCPV4_MSG_NAK,
359 * because the client should not use that IP.
361 * For modern devices we build an answer that includes a valid IP, like
362 * a DHCPV4_MSG_ACK. The client will use that IP and doesn't need to
363 * perform additional DHCP round trips.
368 syslog(LOG_WARNING, "received %s from %x:%x:%x:%x:%x:%x",
369 dhcpv4_msg_to_string(reqmsg),
370 req->chaddr[0],req->chaddr[1],req->chaddr[2],
371 req->chaddr[3],req->chaddr[4],req->chaddr[5]);
373 if (reqmsg == DHCPV4_MSG_DECLINE || reqmsg == DHCPV4_MSG_RELEASE)
376 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MESSAGE, 1, &msg);
377 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SERVERID, 4, &ifaddr.sin_addr);
380 reply.yiaddr.s_addr = htonl(lease->addr);
382 uint32_t val = htonl(iface->dhcpv4_leasetime);
383 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_LEASETIME, 4, &val);
385 val = htonl(500 * iface->dhcpv4_leasetime / 1000);
386 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_RENEW, 4, &val);
388 val = htonl(875 * iface->dhcpv4_leasetime / 1000);
389 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_REBIND, 4, &val);
391 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_NETMASK, 4, &ifnetmask.sin_addr);
393 if (lease->hostname[0])
394 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_HOSTNAME,
395 strlen(lease->hostname), lease->hostname);
397 if (!ioctl(sock, SIOCGIFBRDADDR, &ifr)) {
398 struct sockaddr_in *ina = (struct sockaddr_in*)&ifr.ifr_broadaddr;
399 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_BROADCAST, 4, &ina->sin_addr);
403 if (!ioctl(sock, SIOCGIFMTU, &ifr)) {
404 uint16_t mtu = htons(ifr.ifr_mtu);
405 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MTU, 2, &mtu);
408 if (iface->search && iface->search_len <= 255) {
409 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
410 iface->search_len, iface->search);
411 } else if (!res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
412 uint8_t search_buf[256];
413 int len = dn_comp(_res.dnsrch[0], search_buf,
414 sizeof(search_buf), NULL, NULL);
416 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
420 if (iface->dhcpv4_router_cnt == 0)
421 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER, 4, &ifaddr.sin_addr);
423 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER,
424 4 * iface->dhcpv4_router_cnt, iface->dhcpv4_router);
427 if (iface->dhcpv4_dns_cnt == 0)
428 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER, 4, &ifaddr.sin_addr);
430 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER,
431 4 * iface->dhcpv4_dns_cnt, iface->dhcpv4_dns);
434 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_END, 0, NULL);
436 struct sockaddr_in dest = *((struct sockaddr_in*)addr);
437 if (req->giaddr.s_addr) {
439 * relay agent is configured, send reply to the agent
441 dest.sin_addr = req->giaddr;
442 dest.sin_port = htons(DHCPV4_SERVER_PORT);
443 } else if (req->ciaddr.s_addr && req->ciaddr.s_addr != dest.sin_addr.s_addr) {
445 * client has existing configuration (ciaddr is set) AND this address is
446 * not the address it used for the dhcp message
448 dest.sin_addr = req->ciaddr;
449 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
450 } else if ((ntohs(req->flags) & DHCPV4_FLAG_BROADCAST) ||
451 req->hlen != reply.hlen || !reply.yiaddr.s_addr) {
453 * client requests a broadcast reply OR we can't offer an IP
455 dest.sin_addr.s_addr = INADDR_BROADCAST;
456 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
457 } else if (!req->ciaddr.s_addr && msg == DHCPV4_MSG_NAK) {
459 * client has no previous configuration -> no IP, so we need to reply
460 * with a broadcast packet
462 dest.sin_addr.s_addr = INADDR_BROADCAST;
463 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
466 * send reply to the newly (in this proccess) allocated IP
468 dest.sin_addr = reply.yiaddr;
469 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
471 struct arpreq arp = {.arp_flags = ATF_COM};
472 memcpy(arp.arp_ha.sa_data, req->chaddr, 6);
473 memcpy(&arp.arp_pa, &dest, sizeof(arp.arp_pa));
474 memcpy(arp.arp_dev, iface->ifname, sizeof(arp.arp_dev));
475 ioctl(sock, SIOCSARP, &arp);
478 if (dest.sin_addr.s_addr == INADDR_BROADCAST) {
480 * 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 %x:%x:%x:%x:%x:%x - %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));
497 sendto(sock, &reply, sizeof(reply), MSG_DONTWAIT,
498 (struct sockaddr*)&dest, sizeof(dest));
501 static bool dhcpv4_test(struct interface *iface, uint32_t try)
503 struct dhcpv4_assignment *c;
504 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
505 if (c->addr == try) {
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 list_add(&assign->head, &iface->dhcpv4_assignments);
523 syslog(LOG_DEBUG, "assigning the IP the client asked for: %u.%u.%u.%u",
524 (assign->addr & 0xff000000) >> 24,
525 (assign->addr & 0x00ff0000) >> 16,
526 (assign->addr & 0x0000ff00) >> 8,
527 (assign->addr & 0x000000ff));
531 // Seed RNG with checksum of hwaddress
533 for (size_t i = 0; i < sizeof(assign->hwaddr); ++i) {
534 // Knuth's multiplicative method
535 uint8_t o = assign->hwaddr[i];
536 seed += (o*2654435761) % UINT32_MAX;
540 uint32_t try = (((uint32_t)rand()) % count) + start;
542 if (list_empty(&iface->dhcpv4_assignments)) {
544 list_add(&assign->head, &iface->dhcpv4_assignments);
545 syslog(LOG_DEBUG, "assigning mapped IP (empty list): %u.%u.%u.%u",
546 (assign->addr & 0xff000000) >> 24,
547 (assign->addr & 0x00ff0000) >> 16,
548 (assign->addr & 0x0000ff00) >> 8,
549 (assign->addr & 0x000000ff));
553 for (uint32_t i = 0; i < count; ++i) {
554 if (dhcpv4_test(iface, try)) {
555 /* test was successful: IP address is not assigned, assign it */
557 list_add(&assign->head, &iface->dhcpv4_assignments);
558 syslog(LOG_DEBUG, "assigning mapped IP: %u.%u.%u.%u (try %u of %u)",
559 (assign->addr & 0xff000000) >> 24,
560 (assign->addr & 0x00ff0000) >> 16,
561 (assign->addr & 0x0000ff00) >> 8,
562 (assign->addr & 0x000000ff), i, count);
565 try = (((try - start) + 1) % count) + start;
568 syslog(LOG_DEBUG, "can't assign any IP address -> address space is full");
573 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
574 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
575 const char *hostname)
577 struct dhcpv4_assignment *lease = NULL;
578 uint32_t raddr = ntohl(reqaddr.s_addr);
579 time_t now = odhcpd_time();
581 struct dhcpv4_assignment *c, *n, *a = NULL;
582 list_for_each_entry_safe(c, n, &iface->dhcpv4_assignments, head) {
583 if (!memcmp(c->hwaddr, mac, 6)) {
585 if (c->addr == raddr)
587 } else if (c->valid_until < now) {
593 if (msg == DHCPV4_MSG_DISCOVER || msg == DHCPV4_MSG_REQUEST) {
595 size_t hostlen = strlen(hostname) + 1;
597 if (!a && !iface->no_dynamic_dhcp) { // Create new binding
598 a = calloc(1, sizeof(*a) + hostlen);
600 syslog(LOG_ERR, "Failed to calloc binding on interface %s", iface->ifname);
603 memcpy(a->hwaddr, mac, sizeof(a->hwaddr));
604 memcpy(a->hostname, hostname, hostlen);
606 assigned = dhcpv4_assign(iface, a, raddr);
609 if (assigned && !a->hostname[0] && hostname) {
610 a = realloc(a, sizeof(*a) + hostlen);
612 syslog(LOG_ERR, "Failed to realloc binding on interface %s", iface->ifname);
615 memcpy(a->hostname, hostname, hostlen);
618 a->head.next->prev = &a->head;
619 a->head.prev->next = &a->head;
622 // Was only a solicitation: mark binding for removal
623 if (assigned && a->valid_until < now) {
624 a->valid_until = (msg == DHCPV4_MSG_DISCOVER) ? 0 :
625 (now + iface->dhcpv4_leasetime);
626 } else if (!assigned && a) { // Cleanup failed assignment
633 } else if (msg == DHCPV4_MSG_RELEASE) {
634 if (a && a->valid_until != LONG_MAX)
636 } else if (msg == DHCPV4_MSG_DECLINE && a && a->valid_until != LONG_MAX) {
637 memset(a->hwaddr, 0, sizeof(a->hwaddr));
638 a->valid_until = now + 3600; // Block address for 1h
641 dhcpv6_write_statefile();