Merge pull request #46 from stargieg/master
[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 <limits.h>
24 #include <net/if.h>
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>
30
31 #include "odhcpd.h"
32 #include "dhcpv4.h"
33 #include "dhcpv6.h"
34
35
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);
41
42 // Create socket and register events
43 int init_dhcpv4(void)
44 {
45         return 0;
46 }
47
48 char *dhcpv4_msg_to_string(uint8_t reqmsg)
49 {
50         switch (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";
67         default:
68                 return "UNKNOWN";
69         }
70 }
71
72 int setup_dhcpv4_interface(struct interface *iface, bool enable)
73 {
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;
78         }
79
80         if (iface->dhcpv4 && enable) {
81                 if (!iface->dhcpv4_assignments.next)
82                         INIT_LIST_HEAD(&iface->dhcpv4_assignments);
83
84                 int sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
85                 if (sock < 0) {
86                         syslog(LOG_ERR, "Failed to create DHCPv4 server socket: %s",
87                                         strerror(errno));
88                         return -1;
89                 }
90
91                 // Basic IPv6 configuration
92                 int val = 1;
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));
96
97                 val = IPTOS_PREC_INTERNETCONTROL;
98                 setsockopt(sock, IPPROTO_IP, IP_TOS, &val, sizeof(val));
99
100                 val = IP_PMTUDISC_DONT;
101                 setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val));
102
103                 setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE,
104                                 iface->ifname, strlen(iface->ifname));
105
106                 struct sockaddr_in bind_addr = {AF_INET, htons(DHCPV4_SERVER_PORT),
107                                         {INADDR_ANY}, {0}};
108
109                 if (bind(sock, (struct sockaddr*)&bind_addr, sizeof(bind_addr))) {
110                         syslog(LOG_ERR, "Failed to open DHCPv4 server socket: %s",
111                                         strerror(errno));
112                         return -1;
113                 }
114
115
116                 if (ntohl(iface->dhcpv4_start.s_addr) > ntohl(iface->dhcpv4_end.s_addr)) {
117                         syslog(LOG_ERR, "Invalid DHCP range");
118                         return -1;
119                 }
120
121 #ifndef WITH_UBUS
122                 struct ifreq ifreq;
123                 strncpy(ifreq.ifr_name, iface->ifname, sizeof(ifreq.ifr_name));
124
125                 struct sockaddr_in *saddr = (struct sockaddr_in*)&ifreq.ifr_addr;
126                 struct sockaddr_in *smask = (struct sockaddr_in*)&ifreq.ifr_netmask;
127
128                 if (!ioctl(sock, SIOCGIFADDR, &ifreq)) {
129                         struct in_addr addr = saddr->sin_addr;
130                         iface->dhcpv4_addr.s_addr = addr.s_addr;
131                         ioctl(sock, SIOCGIFNETMASK, &ifreq);
132                         struct in_addr mask = smask->sin_addr;
133                         iface->dhcpv4_mask.s_addr = mask.s_addr;
134                 }
135 #else
136                 const char* saddr = ubus_get_address4(iface->name);
137                 struct in_addr addr;
138                 inet_pton(AF_INET,saddr, &addr);
139                 iface->dhcpv4_addr.s_addr = addr.s_addr;
140                 int bits = ubus_get_mask4(iface->name);
141                 struct in_addr mask;
142                 if (bits < -32 || bits > 32)
143                         bits = 0;
144
145                 mask.s_addr = bits ? htonl(~((1 << (32 - abs(bits))) - 1)) : 0;
146                 if (bits < 0)
147                         mask.s_addr = ~mask.s_addr;
148
149                 iface->dhcpv4_mask.s_addr = mask.s_addr;
150 #endif
151
152                 // Create a range if not specified
153                 if (!(iface->dhcpv4_start.s_addr & htonl(0xffff0000)) &&
154                                 !(iface->dhcpv4_end.s_addr & htonl(0xffff0000)) &&
155                                 iface->dhcpv4_addr.s_addr) {
156
157                         uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
158                         uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
159
160                         if (start && end && start < end &&
161                                         start > ntohl(addr.s_addr & ~mask.s_addr) &&
162                                         (start & ntohl(~mask.s_addr)) == start &&
163                                         (end & ntohl(~mask.s_addr)) == end) {
164                                 iface->dhcpv4_start.s_addr = htonl(start) |
165                                                 (addr.s_addr & mask.s_addr);
166                                 iface->dhcpv4_end.s_addr = htonl(end) |
167                                                 (addr.s_addr & mask.s_addr);
168                         } else if (ntohl(mask.s_addr) <= 0xfffffff0) {
169                                 start = addr.s_addr & mask.s_addr;
170                                 end = addr.s_addr & mask.s_addr;
171
172                                 if (ntohl(mask.s_addr) <= 0xffffff00) {
173                                         iface->dhcpv4_start.s_addr = start | htonl(100);
174                                         iface->dhcpv4_end.s_addr = end | htonl(250);
175                                 } else if (ntohl(mask.s_addr) <= 0xffffffc0) {
176                                         iface->dhcpv4_start.s_addr = start | htonl(10);
177                                         iface->dhcpv4_end.s_addr = end | htonl(60);
178                                 } else if (ntohl(mask.s_addr) <= 0xffffffe0) {
179                                         iface->dhcpv4_start.s_addr = start | htonl(10);
180                                         iface->dhcpv4_end.s_addr = end | htonl(30);
181                                 } else {
182                                         iface->dhcpv4_start.s_addr = start | htonl(3);
183                                         iface->dhcpv4_end.s_addr = end | htonl(12);
184                                 }
185                         }
186
187
188                 }
189                 syslog(LOG_WARNING, "DHCPv4 dhcp addr  %s", inet_ntoa(iface->dhcpv4_addr));
190                 syslog(LOG_WARNING, "DHCPv4 dhcp mask  %s", inet_ntoa(iface->dhcpv4_mask));
191                 syslog(LOG_WARNING, "DHCPv4 dhcp start %s", inet_ntoa(iface->dhcpv4_start));
192                 syslog(LOG_WARNING, "DHCPv4 dhcp end   %s", inet_ntoa(iface->dhcpv4_end));
193
194
195                 // Parse static entries
196                 struct lease *lease;
197                 list_for_each_entry(lease, &leases, head) {
198                         // Construct entry
199                         size_t hostlen = strlen(lease->hostname) + 1;
200                         struct dhcpv4_assignment *a = calloc(1, sizeof(*a) + hostlen);
201                         if (!a) {
202                                 syslog(LOG_ERR, "Calloc failed for static lease on interface %s",
203                                         iface->ifname);
204                                 return -1;
205                         }
206                         a->addr = ntohl(lease->ipaddr.s_addr);
207                         memcpy(a->hwaddr, lease->mac.ether_addr_octet, sizeof(a->hwaddr));
208                         memcpy(a->hostname, lease->hostname, hostlen);
209                         a->valid_until = LONG_MAX;
210
211                         // Assign to all interfaces
212                         struct dhcpv4_assignment *c;
213                         list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
214                                 if (c->addr > a->addr) {
215                                         list_add_tail(&a->head, &c->head);
216                                         break;
217                                 } else if (c->addr == a->addr) {
218                                         // Already an assignment with that number
219                                         break;
220                                 }
221                         }
222                         if (&c->head == &iface->dhcpv4_assignments) {
223                                 list_add(&a->head, &iface->dhcpv4_assignments);
224                         }
225
226                         if (!a->head.next)
227                                 free(a);
228                 }
229
230                 // Clean invalid assignments
231                 struct dhcpv4_assignment *a, *n;
232                 list_for_each_entry_safe(a, n, &iface->dhcpv4_assignments, head) {
233                         if ((htonl(a->addr) & mask.s_addr) !=
234                                         (iface->dhcpv4_start.s_addr & mask.s_addr)) {
235                                 list_del(&a->head);
236                                 free(a);
237                         }
238                 }
239
240
241                 if (iface->dhcpv4_leasetime < 60)
242                         iface->dhcpv4_leasetime = 43200;
243
244                 iface->dhcpv4_event.uloop.fd = sock;
245                 iface->dhcpv4_event.handle_dgram = handle_dhcpv4;
246                 odhcpd_register(&iface->dhcpv4_event);
247         } else if (iface->dhcpv4_assignments.next) {
248                 while (!list_empty(&iface->dhcpv4_assignments)) {
249                         struct dhcpv4_assignment *a = list_first_entry(&iface->dhcpv4_assignments,
250                                         struct dhcpv4_assignment, head);
251                         list_del(&a->head);
252                         free(a);
253                 }
254
255         }
256         return 0;
257 }
258
259
260 static void dhcpv4_put(struct dhcpv4_message *msg, uint8_t **cookie,
261                 uint8_t type, uint8_t len, const void *data)
262 {
263         uint8_t *c = *cookie;
264         if (*cookie + 2 + len > (uint8_t*)&msg[1])
265                 return;
266
267         *c++ = type;
268         *c++ = len;
269         memcpy(c, data, len);
270
271         *cookie = c + len;
272 }
273
274
275 // Simple DHCPv6-server for information requests
276 static void handle_dhcpv4(void *addr, void *data, size_t len,
277                 struct interface *iface, _unused void *dest_addr)
278 {
279         if (!iface->dhcpv4)
280                 return;
281
282         struct dhcpv4_message *req = data;
283         if (len < offsetof(struct dhcpv4_message, options) + 4 ||
284                         req->op != DHCPV4_BOOTREQUEST || req->hlen != 6)
285                 return;
286
287         int sock = iface->dhcpv4_event.uloop.fd;
288
289         syslog(LOG_NOTICE, "Got DHCPv4 request");
290
291         struct ifreq ifreq;
292         memcpy(ifreq.ifr_name, iface->ifname, sizeof(ifreq.ifr_name));
293         if (ioctl(sock, SIOCGIFADDR, &ifreq)) {
294                 syslog(LOG_WARNING, "DHCPv4 failed to detect address: %s", strerror(errno));
295                 return;
296         }
297
298         uint32_t network = iface->dhcpv4_addr.s_addr & iface->dhcpv4_mask.s_addr;
299
300         if ((iface->dhcpv4_start.s_addr & iface->dhcpv4_mask.s_addr) != network ||
301                         (iface->dhcpv4_end.s_addr & iface->dhcpv4_mask.s_addr) != network) {
302                 syslog(LOG_WARNING, "DHCPv4 range out of assigned network");
303                 return;
304         }
305
306         struct ifreq ifr = {.ifr_name = ""};
307         strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
308
309         struct dhcpv4_message reply = {
310                 .op = DHCPV4_BOOTREPLY,
311                 .htype = 1,
312                 .hlen = 6,
313                 .hops = 0,
314                 .xid = req->xid,
315                 .secs = 0,
316                 .flags = req->flags,
317                 .ciaddr = {INADDR_ANY},
318                 .giaddr = req->giaddr,
319                 .siaddr = iface->dhcpv4_addr,
320         };
321         memcpy(reply.chaddr, req->chaddr, sizeof(reply.chaddr));
322
323         reply.options[0] = 0x63;
324         reply.options[1] = 0x82;
325         reply.options[2] = 0x53;
326         reply.options[3] = 0x63;
327
328         uint8_t *cookie = &reply.options[4];
329         uint8_t reqmsg = DHCPV4_MSG_REQUEST;
330         uint8_t msg = DHCPV4_MSG_ACK;
331
332         struct in_addr reqaddr = {INADDR_ANY};
333         char hostname[256];
334         hostname[0] = 0;
335
336         uint8_t *start = &req->options[4];
337         uint8_t *end = ((uint8_t*)data) + len;
338         struct dhcpv4_option *opt;
339         dhcpv4_for_each_option(start, end, opt) {
340                 if (opt->type == DHCPV4_OPT_MESSAGE && opt->len == 1) {
341                         reqmsg = opt->data[0];
342                 } else if (opt->type == DHCPV4_OPT_HOSTNAME && opt->len > 0) {
343                         memcpy(hostname, opt->data, opt->len);
344                         hostname[opt->len] = 0;
345                 } else if (opt->type == DHCPV4_OPT_IPADDRESS && opt->len == 4) {
346                         memcpy(&reqaddr, opt->data, 4);
347                 } else if (opt->type == DHCPV4_OPT_SERVERID && opt->len == 4) {
348                         if (memcmp(opt->data, &iface->dhcpv4_addr, 4))
349                                 return;
350                 } else if (iface->filter_class && opt->type == DHCPV4_OPT_USER_CLASS) {
351                         uint8_t *c = opt->data, *cend = &opt->data[opt->len];
352                         for (; c < cend && &c[*c] < cend; c = &c[1 + *c]) {
353                                 size_t elen = strlen(iface->filter_class);
354                                 if (*c == elen && !memcmp(&c[1], iface->filter_class, elen))
355                                         return; // Ignore from homenet
356                         }
357                 }
358         }
359
360         if (reqmsg != DHCPV4_MSG_DISCOVER && reqmsg != DHCPV4_MSG_REQUEST &&
361                         reqmsg != DHCPV4_MSG_INFORM && reqmsg != DHCPV4_MSG_DECLINE &&
362                         reqmsg != DHCPV4_MSG_RELEASE)
363                 return;
364
365         struct dhcpv4_assignment *lease = NULL;
366         if (reqmsg != DHCPV4_MSG_INFORM)
367                 lease = dhcpv4_lease(iface, reqmsg, req->chaddr, reqaddr, hostname);
368
369         if (!lease) {
370                 if (reqmsg == DHCPV4_MSG_REQUEST)
371                         msg = DHCPV4_MSG_NAK;
372                 else if (reqmsg == DHCPV4_MSG_DISCOVER)
373                         return;
374         } else if (reqmsg == DHCPV4_MSG_DISCOVER) {
375                 msg = DHCPV4_MSG_OFFER;
376         } else if (reqmsg == DHCPV4_MSG_REQUEST && reqaddr.s_addr &&
377                         reqaddr.s_addr != htonl(lease->addr)) {
378                 msg = DHCPV4_MSG_NAK;
379                 /*
380                  * DHCP client requested an IP which we can't offer to him. Probably the
381                  * client changed the network. The reply type is set to DHCPV4_MSG_NAK,
382                  * because the client should not use that IP.
383                  *
384                  * For modern devices we build an answer that includes a valid IP, like
385                  * a DHCPV4_MSG_ACK. The client will use that IP and doesn't need to
386                  * perform additional DHCP round trips.
387                  *
388                  */
389         }
390
391         syslog(LOG_WARNING, "received %s from %x:%x:%x:%x:%x:%x",
392                         dhcpv4_msg_to_string(reqmsg),
393                         req->chaddr[0],req->chaddr[1],req->chaddr[2],
394                         req->chaddr[3],req->chaddr[4],req->chaddr[5]);
395
396         if (reqmsg == DHCPV4_MSG_DECLINE || reqmsg == DHCPV4_MSG_RELEASE)
397                 return;
398
399         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MESSAGE, 1, &msg);
400         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SERVERID, 4, &iface->dhcpv4_addr);
401
402         if (lease) {
403                 reply.yiaddr.s_addr = htonl(lease->addr);
404
405                 uint32_t val = htonl(iface->dhcpv4_leasetime);
406                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_LEASETIME, 4, &val);
407
408                 val = htonl(500 * iface->dhcpv4_leasetime / 1000);
409                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_RENEW, 4, &val);
410
411                 val = htonl(875 * iface->dhcpv4_leasetime / 1000);
412                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_REBIND, 4, &val);
413
414                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_NETMASK, 4, &iface->dhcpv4_mask);
415
416                 if (lease->hostname[0])
417                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_HOSTNAME,
418                                         strlen(lease->hostname), lease->hostname);
419
420                 if (!ioctl(sock, SIOCGIFBRDADDR, &ifr)) {
421                         struct sockaddr_in *ina = (struct sockaddr_in*)&ifr.ifr_broadaddr;
422                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_BROADCAST, 4, &ina->sin_addr);
423                 }
424         }
425
426         if (!ioctl(sock, SIOCGIFMTU, &ifr)) {
427                 uint16_t mtu = htons(ifr.ifr_mtu);
428                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MTU, 2, &mtu);
429         }
430
431         if (iface->search && iface->search_len <= 255) {
432                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
433                                 iface->search_len, iface->search);
434         } else if (!res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
435                 uint8_t search_buf[256];
436                 int len = dn_comp(_res.dnsrch[0], search_buf,
437                                                 sizeof(search_buf), NULL, NULL);
438                 if (len > 0)
439                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
440                                         len, search_buf);
441         }
442
443         if (iface->dhcpv4_router_cnt == 0)
444                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER, 4, &iface->dhcpv4_addr);
445         else
446                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER,
447                                 4 * iface->dhcpv4_router_cnt, iface->dhcpv4_router);
448
449
450         if (iface->dhcpv4_dns_cnt == 0)
451                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER, 4, &iface->dhcpv4_addr);
452         else
453                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER,
454                                 4 * iface->dhcpv4_dns_cnt, iface->dhcpv4_dns);
455
456
457         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_END, 0, NULL);
458
459         struct sockaddr_in dest = *((struct sockaddr_in*)addr);
460         if (req->giaddr.s_addr) {
461                 /*
462                  * relay agent is configured, send reply to the agent
463                  */
464                 dest.sin_addr = req->giaddr;
465                 dest.sin_port = htons(DHCPV4_SERVER_PORT);
466         } else if (req->ciaddr.s_addr && req->ciaddr.s_addr != dest.sin_addr.s_addr) {
467                 /*
468                  * client has existing configuration (ciaddr is set) AND this address is
469                  * not the address it used for the dhcp message
470                  */
471                 dest.sin_addr = req->ciaddr;
472                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
473         } else if ((ntohs(req->flags) & DHCPV4_FLAG_BROADCAST) ||
474                         req->hlen != reply.hlen || !reply.yiaddr.s_addr) {
475                 /*
476                  * client requests a broadcast reply OR we can't offer an IP
477                  */
478                 dest.sin_addr.s_addr = INADDR_BROADCAST;
479                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
480         } else if (!req->ciaddr.s_addr && msg == DHCPV4_MSG_NAK) {
481                 /*
482                  * client has no previous configuration -> no IP, so we need to reply
483                  * with a broadcast packet
484                  */
485                 dest.sin_addr.s_addr = INADDR_BROADCAST;
486                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
487         } else {
488                 /*
489                  * send reply to the newly (in this proccess) allocated IP
490                  */
491                 dest.sin_addr = reply.yiaddr;
492                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
493
494                 struct arpreq arp = {.arp_flags = ATF_COM};
495                 memcpy(arp.arp_ha.sa_data, req->chaddr, 6);
496                 memcpy(&arp.arp_pa, &dest, sizeof(arp.arp_pa));
497                 memcpy(arp.arp_dev, iface->ifname, sizeof(arp.arp_dev));
498                 ioctl(sock, SIOCSARP, &arp);
499         }
500
501         if (dest.sin_addr.s_addr == INADDR_BROADCAST) {
502                 /*
503                  * reply goes to IP broadcast -> MAC broadcast
504                  */
505                 syslog(LOG_WARNING, "sending %s to ff:ff:ff:ff:ff:ff - %s",
506                                 dhcpv4_msg_to_string(msg),
507                                 inet_ntoa(dest.sin_addr));
508         } else {
509                 /*
510                  * reply is send directly to IP,
511                  * MAC is assumed to be the same as the request
512                  */
513                 syslog(LOG_WARNING, "sending %s to %x:%x:%x:%x:%x:%x - %s",
514                                 dhcpv4_msg_to_string(msg),
515                                 req->chaddr[0],req->chaddr[1],req->chaddr[2],
516                                 req->chaddr[3],req->chaddr[4],req->chaddr[5],
517                                 inet_ntoa(dest.sin_addr));
518         }
519
520         sendto(sock, &reply, sizeof(reply), MSG_DONTWAIT,
521                         (struct sockaddr*)&dest, sizeof(dest));
522 }
523
524 static bool dhcpv4_test(struct interface *iface, uint32_t try)
525 {
526         struct dhcpv4_assignment *c;
527         list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
528                 if (c->addr == try) {
529                         return false;
530                 }
531         }
532         return true;
533 }
534
535 static bool dhcpv4_assign(struct interface *iface,
536                 struct dhcpv4_assignment *assign, uint32_t raddr)
537 {
538         uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
539         uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
540         uint32_t count = end - start + 1;
541
542         // try to assign the IP the client asked for
543         if (start <= raddr && raddr <= end && dhcpv4_test(iface, raddr)) {
544                 assign->addr = raddr;
545                 list_add(&assign->head, &iface->dhcpv4_assignments);
546                 syslog(LOG_DEBUG, "assigning the IP the client asked for: %u.%u.%u.%u",
547                                 (assign->addr & 0xff000000) >> 24,
548                                 (assign->addr & 0x00ff0000) >> 16,
549                                 (assign->addr & 0x0000ff00) >> 8,
550                                 (assign->addr & 0x000000ff));
551                 return true;
552         }
553
554         // Seed RNG with checksum of hwaddress
555         uint32_t seed = 0;
556         for (size_t i = 0; i < sizeof(assign->hwaddr); ++i) {
557                 // Knuth's multiplicative method
558                 uint8_t o = assign->hwaddr[i];
559                 seed += (o*2654435761) % UINT32_MAX;
560         }
561         srand(seed);
562
563         uint32_t try = (((uint32_t)rand()) % count) + start;
564
565         if (list_empty(&iface->dhcpv4_assignments)) {
566                 assign->addr = try;
567                 list_add(&assign->head, &iface->dhcpv4_assignments);
568                 syslog(LOG_DEBUG, "assigning mapped IP (empty list): %u.%u.%u.%u",
569                                 (assign->addr & 0xff000000) >> 24,
570                                 (assign->addr & 0x00ff0000) >> 16,
571                                 (assign->addr & 0x0000ff00) >> 8,
572                                 (assign->addr & 0x000000ff));
573                 return true;
574         }
575
576         for (uint32_t i = 0; i < count; ++i) {
577                 if (dhcpv4_test(iface, try)) {
578                         /* test was successful: IP address is not assigned, assign it */
579                         assign->addr = try;
580                         list_add(&assign->head, &iface->dhcpv4_assignments);
581                         syslog(LOG_DEBUG, "assigning mapped IP: %u.%u.%u.%u (try %u of %u)",
582                                         (assign->addr & 0xff000000) >> 24,
583                                         (assign->addr & 0x00ff0000) >> 16,
584                                         (assign->addr & 0x0000ff00) >> 8,
585                                         (assign->addr & 0x000000ff), i, count);
586                         return true;
587                 }
588                 try = (((try - start) + 1) % count) + start;
589         }
590
591         syslog(LOG_DEBUG, "can't assign any IP address -> address space is full");
592         return false;
593 }
594
595
596 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
597                 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
598                 const char *hostname)
599 {
600         struct dhcpv4_assignment *lease = NULL;
601         uint32_t raddr = ntohl(reqaddr.s_addr);
602         time_t now = odhcpd_time();
603
604         struct dhcpv4_assignment *c, *n, *a = NULL;
605         list_for_each_entry_safe(c, n, &iface->dhcpv4_assignments, head) {
606                 if (!memcmp(c->hwaddr, mac, 6)) {
607                         a = c;
608                         if (c->addr == raddr)
609                                 break;
610                 } else if (c->valid_until < now) {
611                         list_del(&c->head);
612                         free(c);
613                 }
614         }
615
616         if (msg == DHCPV4_MSG_DISCOVER || msg == DHCPV4_MSG_REQUEST) {
617                 bool assigned = !!a;
618                 size_t hostlen = strlen(hostname) + 1;
619
620                 if (!a && !iface->no_dynamic_dhcp) { // Create new binding
621                         a = calloc(1, sizeof(*a) + hostlen);
622                         if (!a) {
623                                 syslog(LOG_ERR, "Failed to calloc binding on interface %s", iface->ifname);
624                                 return NULL;
625                         }
626                         memcpy(a->hwaddr, mac, sizeof(a->hwaddr));
627                         memcpy(a->hostname, hostname, hostlen);
628
629                         assigned = dhcpv4_assign(iface, a, raddr);
630                 }
631
632                 if (assigned && !a->hostname[0] && hostname) {
633                         a = realloc(a, sizeof(*a) + hostlen);
634                         if (!a) {
635                                 syslog(LOG_ERR, "Failed to realloc binding on interface %s", iface->ifname);
636                                 return NULL;
637                         }
638                         memcpy(a->hostname, hostname, hostlen);
639
640                         // Fixup list
641                         a->head.next->prev = &a->head;
642                         a->head.prev->next = &a->head;
643                 }
644
645                 // Was only a solicitation: mark binding for removal
646                 if (assigned && a->valid_until < now) {
647                         a->valid_until = (msg == DHCPV4_MSG_DISCOVER) ? 0 :
648                                         (now + iface->dhcpv4_leasetime);
649                 } else if (!assigned && a) { // Cleanup failed assignment
650                         free(a);
651                         a = NULL;
652                 }
653
654                 if (assigned && a)
655                         lease = a;
656         } else if (msg == DHCPV4_MSG_RELEASE) {
657                 if (a && a->valid_until != LONG_MAX)
658                         a->valid_until = 0;
659         } else if (msg == DHCPV4_MSG_DECLINE && a && a->valid_until != LONG_MAX) {
660                 memset(a->hwaddr, 0, sizeof(a->hwaddr));
661                 a->valid_until = now + 3600; // Block address for 1h
662         }
663
664         dhcpv6_write_statefile();
665
666         return lease;
667 }
668