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