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