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