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))) {
124 struct in_addr addr = ubus_get_address4(iface->ifname);
126 struct in_addr mask = ubus_get_mask4(iface->ifname);
128 uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
129 uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
131 if (start && end && start < end &&
132 start > ntohl(addr.s_addr & ~mask.s_addr) &&
133 (start & ntohl(~mask.s_addr)) == start &&
134 (end & ntohl(~mask.s_addr)) == end) {
135 iface->dhcpv4_start.s_addr = htonl(start) |
136 (addr.s_addr & mask.s_addr);
137 iface->dhcpv4_end.s_addr = htonl(end) |
138 (addr.s_addr & mask.s_addr);
139 } else if (ntohl(mask.s_addr) <= 0xfffffff0) {
140 start = addr.s_addr & mask.s_addr;
141 end = addr.s_addr & mask.s_addr;
143 if (ntohl(mask.s_addr) <= 0xffffff00) {
144 iface->dhcpv4_start.s_addr = start | htonl(100);
145 iface->dhcpv4_end.s_addr = end | htonl(250);
146 } else if (ntohl(mask.s_addr) <= 0xffffffc0) {
147 iface->dhcpv4_start.s_addr = start | htonl(10);
148 iface->dhcpv4_end.s_addr = end | htonl(60);
149 } else if (ntohl(mask.s_addr) <= 0xffffffe0) {
150 iface->dhcpv4_start.s_addr = start | htonl(10);
151 iface->dhcpv4_end.s_addr = end | htonl(30);
153 iface->dhcpv4_start.s_addr = start | htonl(3);
154 iface->dhcpv4_end.s_addr = end | htonl(12);
161 // Parse static entries
163 list_for_each_entry(lease, &leases, head) {
165 size_t hostlen = strlen(lease->hostname) + 1;
166 struct dhcpv4_assignment *a = calloc(1, sizeof(*a) + hostlen);
168 syslog(LOG_ERR, "Calloc failed for static lease on interface %s",
172 a->addr = ntohl(lease->ipaddr.s_addr);
173 memcpy(a->hwaddr, lease->mac.ether_addr_octet, sizeof(a->hwaddr));
174 memcpy(a->hostname, lease->hostname, hostlen);
175 a->valid_until = LONG_MAX;
177 // Assign to all interfaces
178 struct dhcpv4_assignment *c;
179 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
180 if (c->addr > a->addr) {
181 list_add_tail(&a->head, &c->head);
183 } else if (c->addr == a->addr) {
184 // Already an assignment with that number
188 if (&c->head == &iface->dhcpv4_assignments) {
189 list_add(&a->head, &iface->dhcpv4_assignments);
196 // Clean invalid assignments
197 struct dhcpv4_assignment *a, *n;
198 list_for_each_entry_safe(a, n, &iface->dhcpv4_assignments, head) {
199 if ((htonl(a->addr) & smask->sin_addr.s_addr) !=
200 (iface->dhcpv4_start.s_addr & smask->sin_addr.s_addr)) {
207 if (iface->dhcpv4_leasetime < 60)
208 iface->dhcpv4_leasetime = 43200;
210 iface->dhcpv4_event.uloop.fd = sock;
211 iface->dhcpv4_event.handle_dgram = handle_dhcpv4;
212 odhcpd_register(&iface->dhcpv4_event);
213 } else if (iface->dhcpv4_assignments.next) {
214 while (!list_empty(&iface->dhcpv4_assignments)) {
215 struct dhcpv4_assignment *a = list_first_entry(&iface->dhcpv4_assignments,
216 struct dhcpv4_assignment, head);
226 static void dhcpv4_put(struct dhcpv4_message *msg, uint8_t **cookie,
227 uint8_t type, uint8_t len, const void *data)
229 uint8_t *c = *cookie;
230 if (*cookie + 2 + len > (uint8_t*)&msg[1])
235 memcpy(c, data, len);
241 // Simple DHCPv6-server for information requests
242 static void handle_dhcpv4(void *addr, void *data, size_t len,
243 struct interface *iface, _unused void *dest_addr)
248 struct dhcpv4_message *req = data;
249 if (len < offsetof(struct dhcpv4_message, options) + 4 ||
250 req->op != DHCPV4_BOOTREQUEST || req->hlen != 6)
253 int sock = iface->dhcpv4_event.uloop.fd;
254 struct sockaddr_in ifaddr;
255 struct sockaddr_in ifnetmask;
257 syslog(LOG_NOTICE, "Got DHCPv4 request");
260 memcpy(ifreq.ifr_name, iface->ifname, sizeof(ifreq.ifr_name));
261 if (ioctl(sock, SIOCGIFADDR, &ifreq)) {
262 syslog(LOG_WARNING, "DHCPv4 failed to detect address: %s", strerror(errno));
266 memcpy(&ifaddr, &ifreq.ifr_addr, sizeof(ifaddr));
267 if (ioctl(sock, SIOCGIFNETMASK, &ifreq))
270 memcpy(&ifnetmask, &ifreq.ifr_netmask, sizeof(ifnetmask));
271 uint32_t network = ifaddr.sin_addr.s_addr & ifnetmask.sin_addr.s_addr;
273 if ((iface->dhcpv4_start.s_addr & ifnetmask.sin_addr.s_addr) != network ||
274 (iface->dhcpv4_end.s_addr & ifnetmask.sin_addr.s_addr) != network) {
275 syslog(LOG_WARNING, "DHCPv4 range out of assigned network");
279 struct ifreq ifr = {.ifr_name = ""};
280 strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
282 struct dhcpv4_message reply = {
283 .op = DHCPV4_BOOTREPLY,
290 .ciaddr = {INADDR_ANY},
291 .giaddr = req->giaddr,
292 .siaddr = ifaddr.sin_addr,
294 memcpy(reply.chaddr, req->chaddr, sizeof(reply.chaddr));
296 reply.options[0] = 0x63;
297 reply.options[1] = 0x82;
298 reply.options[2] = 0x53;
299 reply.options[3] = 0x63;
301 uint8_t *cookie = &reply.options[4];
302 uint8_t reqmsg = DHCPV4_MSG_REQUEST;
303 uint8_t msg = DHCPV4_MSG_ACK;
305 struct in_addr reqaddr = {INADDR_ANY};
309 uint8_t *start = &req->options[4];
310 uint8_t *end = ((uint8_t*)data) + len;
311 struct dhcpv4_option *opt;
312 dhcpv4_for_each_option(start, end, opt) {
313 if (opt->type == DHCPV4_OPT_MESSAGE && opt->len == 1) {
314 reqmsg = opt->data[0];
315 } else if (opt->type == DHCPV4_OPT_HOSTNAME && opt->len > 0) {
316 memcpy(hostname, opt->data, opt->len);
317 hostname[opt->len] = 0;
318 } else if (opt->type == DHCPV4_OPT_IPADDRESS && opt->len == 4) {
319 memcpy(&reqaddr, opt->data, 4);
320 } else if (opt->type == DHCPV4_OPT_SERVERID && opt->len == 4) {
321 if (memcmp(opt->data, &ifaddr.sin_addr, 4))
323 } else if (iface->filter_class && opt->type == DHCPV4_OPT_USER_CLASS) {
324 uint8_t *c = opt->data, *cend = &opt->data[opt->len];
325 for (; c < cend && &c[*c] < cend; c = &c[1 + *c]) {
326 size_t elen = strlen(iface->filter_class);
327 if (*c == elen && !memcmp(&c[1], iface->filter_class, elen))
328 return; // Ignore from homenet
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, hostname);
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 %x:%x:%x:%x:%x:%x",
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.sin_addr);
376 reply.yiaddr.s_addr = htonl(lease->addr);
378 uint32_t val = htonl(iface->dhcpv4_leasetime);
379 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_LEASETIME, 4, &val);
381 val = htonl(500 * iface->dhcpv4_leasetime / 1000);
382 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_RENEW, 4, &val);
384 val = htonl(875 * iface->dhcpv4_leasetime / 1000);
385 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_REBIND, 4, &val);
387 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_NETMASK, 4, &ifnetmask.sin_addr);
389 if (lease->hostname[0])
390 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_HOSTNAME,
391 strlen(lease->hostname), lease->hostname);
393 if (!ioctl(sock, SIOCGIFBRDADDR, &ifr)) {
394 struct sockaddr_in *ina = (struct sockaddr_in*)&ifr.ifr_broadaddr;
395 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_BROADCAST, 4, &ina->sin_addr);
399 if (!ioctl(sock, SIOCGIFMTU, &ifr)) {
400 uint16_t mtu = htons(ifr.ifr_mtu);
401 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MTU, 2, &mtu);
404 if (iface->search && iface->search_len <= 255) {
405 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
406 iface->search_len, iface->search);
407 } else if (!res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
408 uint8_t search_buf[256];
409 int len = dn_comp(_res.dnsrch[0], search_buf,
410 sizeof(search_buf), NULL, NULL);
412 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
416 if (iface->dhcpv4_router_cnt == 0)
417 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER, 4, &ifaddr.sin_addr);
419 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER,
420 4 * iface->dhcpv4_router_cnt, iface->dhcpv4_router);
423 if (iface->dhcpv4_dns_cnt == 0)
424 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER, 4, &ifaddr.sin_addr);
426 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER,
427 4 * iface->dhcpv4_dns_cnt, iface->dhcpv4_dns);
430 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_END, 0, NULL);
432 struct sockaddr_in dest = *((struct sockaddr_in*)addr);
433 if (req->giaddr.s_addr) {
435 * relay agent is configured, send reply to the agent
437 dest.sin_addr = req->giaddr;
438 dest.sin_port = htons(DHCPV4_SERVER_PORT);
439 } else if (req->ciaddr.s_addr && req->ciaddr.s_addr != dest.sin_addr.s_addr) {
441 * client has existing configuration (ciaddr is set) AND this address is
442 * not the address it used for the dhcp message
444 dest.sin_addr = req->ciaddr;
445 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
446 } else if ((ntohs(req->flags) & DHCPV4_FLAG_BROADCAST) ||
447 req->hlen != reply.hlen || !reply.yiaddr.s_addr) {
449 * client requests a broadcast reply OR we can't offer an IP
451 dest.sin_addr.s_addr = INADDR_BROADCAST;
452 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
453 } else if (!req->ciaddr.s_addr && msg == DHCPV4_MSG_NAK) {
455 * client has no previous configuration -> no IP, so we need to reply
456 * with a broadcast packet
458 dest.sin_addr.s_addr = INADDR_BROADCAST;
459 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
462 * send reply to the newly (in this proccess) allocated IP
464 dest.sin_addr = reply.yiaddr;
465 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
467 struct arpreq arp = {.arp_flags = ATF_COM};
468 memcpy(arp.arp_ha.sa_data, req->chaddr, 6);
469 memcpy(&arp.arp_pa, &dest, sizeof(arp.arp_pa));
470 memcpy(arp.arp_dev, iface->ifname, sizeof(arp.arp_dev));
471 ioctl(sock, SIOCSARP, &arp);
474 if (dest.sin_addr.s_addr == INADDR_BROADCAST) {
476 * reply goes to IP broadcast -> MAC broadcast
478 syslog(LOG_WARNING, "sending %s to ff:ff:ff:ff:ff:ff - %s",
479 dhcpv4_msg_to_string(msg),
480 inet_ntoa(dest.sin_addr));
483 * reply is send directly to IP,
484 * MAC is assumed to be the same as the request
486 syslog(LOG_WARNING, "sending %s to %x:%x:%x:%x:%x:%x - %s",
487 dhcpv4_msg_to_string(msg),
488 req->chaddr[0],req->chaddr[1],req->chaddr[2],
489 req->chaddr[3],req->chaddr[4],req->chaddr[5],
490 inet_ntoa(dest.sin_addr));
493 sendto(sock, &reply, sizeof(reply), MSG_DONTWAIT,
494 (struct sockaddr*)&dest, sizeof(dest));
497 static bool dhcpv4_test(struct interface *iface, uint32_t try)
499 struct dhcpv4_assignment *c;
500 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
501 if (c->addr == try) {
508 static bool dhcpv4_assign(struct interface *iface,
509 struct dhcpv4_assignment *assign, uint32_t raddr)
511 uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
512 uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
513 uint32_t count = end - start + 1;
515 // try to assign the IP the client asked for
516 if (start <= raddr && raddr <= end && dhcpv4_test(iface, raddr)) {
517 assign->addr = raddr;
518 list_add(&assign->head, &iface->dhcpv4_assignments);
519 syslog(LOG_DEBUG, "assigning the IP the client asked for: %u.%u.%u.%u",
520 (assign->addr & 0xff000000) >> 24,
521 (assign->addr & 0x00ff0000) >> 16,
522 (assign->addr & 0x0000ff00) >> 8,
523 (assign->addr & 0x000000ff));
527 // Seed RNG with checksum of hwaddress
529 for (size_t i = 0; i < sizeof(assign->hwaddr); ++i) {
530 // Knuth's multiplicative method
531 uint8_t o = assign->hwaddr[i];
532 seed += (o*2654435761) % UINT32_MAX;
536 uint32_t try = (((uint32_t)rand()) % count) + start;
538 if (list_empty(&iface->dhcpv4_assignments)) {
540 list_add(&assign->head, &iface->dhcpv4_assignments);
541 syslog(LOG_DEBUG, "assigning mapped IP (empty list): %u.%u.%u.%u",
542 (assign->addr & 0xff000000) >> 24,
543 (assign->addr & 0x00ff0000) >> 16,
544 (assign->addr & 0x0000ff00) >> 8,
545 (assign->addr & 0x000000ff));
549 for (uint32_t i = 0; i < count; ++i) {
550 if (dhcpv4_test(iface, try)) {
551 /* test was successful: IP address is not assigned, assign it */
553 list_add(&assign->head, &iface->dhcpv4_assignments);
554 syslog(LOG_DEBUG, "assigning mapped IP: %u.%u.%u.%u (try %u of %u)",
555 (assign->addr & 0xff000000) >> 24,
556 (assign->addr & 0x00ff0000) >> 16,
557 (assign->addr & 0x0000ff00) >> 8,
558 (assign->addr & 0x000000ff), i, count);
561 try = (((try - start) + 1) % count) + start;
564 syslog(LOG_DEBUG, "can't assign any IP address -> address space is full");
569 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
570 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
571 const char *hostname)
573 struct dhcpv4_assignment *lease = NULL;
574 uint32_t raddr = ntohl(reqaddr.s_addr);
575 time_t now = odhcpd_time();
577 struct dhcpv4_assignment *c, *n, *a = NULL;
578 list_for_each_entry_safe(c, n, &iface->dhcpv4_assignments, head) {
579 if (!memcmp(c->hwaddr, mac, 6)) {
581 if (c->addr == raddr)
583 } else if (c->valid_until < now) {
589 if (msg == DHCPV4_MSG_DISCOVER || msg == DHCPV4_MSG_REQUEST) {
591 size_t hostlen = strlen(hostname) + 1;
593 if (!a && !iface->no_dynamic_dhcp) { // Create new binding
594 a = calloc(1, sizeof(*a) + hostlen);
596 syslog(LOG_ERR, "Failed to calloc binding on interface %s", iface->ifname);
599 memcpy(a->hwaddr, mac, sizeof(a->hwaddr));
600 memcpy(a->hostname, hostname, hostlen);
602 assigned = dhcpv4_assign(iface, a, raddr);
605 if (assigned && !a->hostname[0] && hostname) {
606 a = realloc(a, sizeof(*a) + hostlen);
608 syslog(LOG_ERR, "Failed to realloc binding on interface %s", iface->ifname);
611 memcpy(a->hostname, hostname, hostlen);
614 a->head.next->prev = &a->head;
615 a->head.prev->next = &a->head;
618 // Was only a solicitation: mark binding for removal
619 if (assigned && a->valid_until < now) {
620 a->valid_until = (msg == DHCPV4_MSG_DISCOVER) ? 0 :
621 (now + iface->dhcpv4_leasetime);
622 } else if (!assigned && a) { // Cleanup failed assignment
629 } else if (msg == DHCPV4_MSG_RELEASE) {
630 if (a && a->valid_until != LONG_MAX)
632 } else if (msg == DHCPV4_MSG_DECLINE && a && a->valid_until != LONG_MAX) {
633 memset(a->hwaddr, 0, sizeof(a->hwaddr));
634 a->valid_until = now + 3600; // Block address for 1h
637 dhcpv6_write_statefile();