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