router: skip parse_routes when ra_default > 1
[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                 uint32_t *leasetime, 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                 struct ifreq ifreq;
123                 strncpy(ifreq.ifr_name, iface->ifname, sizeof(ifreq.ifr_name));
124
125                 struct sockaddr_in *saddr = (struct sockaddr_in*)&ifreq.ifr_addr;
126                 struct sockaddr_in *smask = (struct sockaddr_in*)&ifreq.ifr_netmask;
127                 if (!(iface->dhcpv4_start.s_addr & htonl(0xffff0000)) &&
128                                 !(iface->dhcpv4_end.s_addr & htonl(0xffff0000)) &&
129                                 !ioctl(sock, SIOCGIFADDR, &ifreq)) {
130                         struct in_addr addr = saddr->sin_addr;
131
132                         ioctl(sock, SIOCGIFNETMASK, &ifreq);
133                         struct in_addr mask = smask->sin_addr;
134
135                         uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
136                         uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
137
138                         if (start && end && start < end &&
139                                         start > ntohl(addr.s_addr & ~mask.s_addr) &&
140                                         (start & ntohl(~mask.s_addr)) == start &&
141                                         (end & ntohl(~mask.s_addr)) == end) {
142                                 iface->dhcpv4_start.s_addr = htonl(start) |
143                                                 (addr.s_addr & mask.s_addr);
144                                 iface->dhcpv4_end.s_addr = htonl(end) |
145                                                 (addr.s_addr & mask.s_addr);
146                         } else if (ntohl(mask.s_addr) <= 0xfffffff0) {
147                                 start = addr.s_addr & mask.s_addr;
148                                 end = addr.s_addr & mask.s_addr;
149
150                                 if (ntohl(mask.s_addr) <= 0xffffff00) {
151                                         iface->dhcpv4_start.s_addr = start | htonl(100);
152                                         iface->dhcpv4_end.s_addr = end | htonl(250);
153                                 } else if (ntohl(mask.s_addr) <= 0xffffffc0) {
154                                         iface->dhcpv4_start.s_addr = start | htonl(10);
155                                         iface->dhcpv4_end.s_addr = end | htonl(60);
156                                 } else if (ntohl(mask.s_addr) <= 0xffffffe0) {
157                                         iface->dhcpv4_start.s_addr = start | htonl(10);
158                                         iface->dhcpv4_end.s_addr = end | htonl(30);
159                                 } else {
160                                         iface->dhcpv4_start.s_addr = start | htonl(3);
161                                         iface->dhcpv4_end.s_addr = end | htonl(12);
162                                 }
163                         }
164
165
166                 }
167
168                 // Parse static entries
169                 struct lease *lease;
170                 list_for_each_entry(lease, &leases, head) {
171                         // Construct entry
172                         size_t hostlen = strlen(lease->hostname) + 1;
173                         struct dhcpv4_assignment *a = calloc(1, sizeof(*a) + hostlen);
174                         if (!a) {
175                                 syslog(LOG_ERR, "Calloc failed for static lease on interface %s",
176                                         iface->ifname);
177                                 return -1;
178                         }
179                         if (lease->dhcpv4_leasetime >= 60)
180                                 a->leasetime = lease->dhcpv4_leasetime;
181                         a->addr = ntohl(lease->ipaddr.s_addr);
182                         memcpy(a->hwaddr, lease->mac.ether_addr_octet, sizeof(a->hwaddr));
183                         memcpy(a->hostname, lease->hostname, hostlen);
184                         /* Infinite valid */
185                         a->valid_until = 0;
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) & smask->sin_addr.s_addr) !=
210                                         (iface->dhcpv4_start.s_addr & smask->sin_addr.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 // Handler for DHCPv4 messages
251 static void handle_dhcpv4(void *addr, void *data, size_t len,
252                 struct interface *iface, _unused void *dest_addr)
253 {
254         if (!iface->dhcpv4)
255                 return;
256
257         struct dhcpv4_message *req = data;
258         if (len < offsetof(struct dhcpv4_message, options) + 4 ||
259                         req->op != DHCPV4_BOOTREQUEST || req->hlen != 6)
260                 return;
261
262         int sock = iface->dhcpv4_event.uloop.fd;
263         struct sockaddr_in ifaddr;
264         struct sockaddr_in ifnetmask;
265
266         syslog(LOG_NOTICE, "Got DHCPv4 request");
267
268         struct ifreq ifreq;
269         memcpy(ifreq.ifr_name, iface->ifname, sizeof(ifreq.ifr_name));
270         if (ioctl(sock, SIOCGIFADDR, &ifreq)) {
271                 syslog(LOG_WARNING, "DHCPv4 failed to detect address: %s", strerror(errno));
272                 return;
273         }
274
275         memcpy(&ifaddr, &ifreq.ifr_addr, sizeof(ifaddr));
276         if (ioctl(sock, SIOCGIFNETMASK, &ifreq))
277                 return;
278
279         memcpy(&ifnetmask, &ifreq.ifr_netmask, sizeof(ifnetmask));
280         uint32_t network = ifaddr.sin_addr.s_addr & ifnetmask.sin_addr.s_addr;
281
282         if ((iface->dhcpv4_start.s_addr & ifnetmask.sin_addr.s_addr) != network ||
283                         (iface->dhcpv4_end.s_addr & ifnetmask.sin_addr.s_addr) != network) {
284                 syslog(LOG_WARNING, "DHCPv4 range out of assigned network");
285                 return;
286         }
287
288         struct ifreq ifr = {.ifr_name = ""};
289         strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
290
291         struct dhcpv4_message reply = {
292                 .op = DHCPV4_BOOTREPLY,
293                 .htype = 1,
294                 .hlen = 6,
295                 .hops = 0,
296                 .xid = req->xid,
297                 .secs = 0,
298                 .flags = req->flags,
299                 .ciaddr = {INADDR_ANY},
300                 .giaddr = req->giaddr,
301                 .siaddr = ifaddr.sin_addr,
302         };
303         memcpy(reply.chaddr, req->chaddr, sizeof(reply.chaddr));
304
305         reply.options[0] = 0x63;
306         reply.options[1] = 0x82;
307         reply.options[2] = 0x53;
308         reply.options[3] = 0x63;
309
310         uint8_t *cookie = &reply.options[4];
311         uint8_t reqmsg = DHCPV4_MSG_REQUEST;
312         uint8_t msg = DHCPV4_MSG_ACK;
313
314         struct in_addr reqaddr = {INADDR_ANY};
315         uint32_t leasetime = 0;
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                 } else if (opt->type == DHCPV4_OPT_LEASETIME && opt->len == 4)
341                         memcpy(&leasetime, opt->data, 4);
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, &leasetime, 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                 uint32_t val;
388
389                 reply.yiaddr.s_addr = htonl(lease->addr);
390
391                 val = htonl(leasetime);
392                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_LEASETIME, 4, &val);
393
394                 if (leasetime != UINT32_MAX) {
395                         val = htonl(500 * leasetime / 1000);
396                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_RENEW, 4, &val);
397
398                         val = htonl(875 * leasetime / 1000);
399                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_REBIND, 4, &val);
400                 }
401
402                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_NETMASK, 4, &ifnetmask.sin_addr);
403
404                 if (lease->hostname[0])
405                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_HOSTNAME,
406                                         strlen(lease->hostname), lease->hostname);
407
408                 if (!ioctl(sock, SIOCGIFBRDADDR, &ifr)) {
409                         struct sockaddr_in *ina = (struct sockaddr_in*)&ifr.ifr_broadaddr;
410                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_BROADCAST, 4, &ina->sin_addr);
411                 }
412         }
413
414         if (!ioctl(sock, SIOCGIFMTU, &ifr)) {
415                 uint16_t mtu = htons(ifr.ifr_mtu);
416                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MTU, 2, &mtu);
417         }
418
419         if (iface->search && iface->search_len <= 255) {
420                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
421                                 iface->search_len, iface->search);
422         } else if (!res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
423                 uint8_t search_buf[256];
424                 int len = dn_comp(_res.dnsrch[0], search_buf,
425                                                 sizeof(search_buf), NULL, NULL);
426                 if (len > 0)
427                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
428                                         len, search_buf);
429         }
430
431         if (iface->dhcpv4_router_cnt == 0)
432                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER, 4, &ifaddr.sin_addr);
433         else
434                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER,
435                                 4 * iface->dhcpv4_router_cnt, iface->dhcpv4_router);
436
437
438         if (iface->dhcpv4_dns_cnt == 0)
439                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER, 4, &ifaddr.sin_addr);
440         else
441                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER,
442                                 4 * iface->dhcpv4_dns_cnt, iface->dhcpv4_dns);
443
444
445         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_END, 0, NULL);
446
447         struct sockaddr_in dest = *((struct sockaddr_in*)addr);
448         if (req->giaddr.s_addr) {
449                 /*
450                  * relay agent is configured, send reply to the agent
451                  */
452                 dest.sin_addr = req->giaddr;
453                 dest.sin_port = htons(DHCPV4_SERVER_PORT);
454         } else if (req->ciaddr.s_addr && req->ciaddr.s_addr != dest.sin_addr.s_addr) {
455                 /*
456                  * client has existing configuration (ciaddr is set) AND this address is
457                  * not the address it used for the dhcp message
458                  */
459                 dest.sin_addr = req->ciaddr;
460                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
461         } else if ((ntohs(req->flags) & DHCPV4_FLAG_BROADCAST) ||
462                         req->hlen != reply.hlen || !reply.yiaddr.s_addr) {
463                 /*
464                  * client requests a broadcast reply OR we can't offer an IP
465                  */
466                 dest.sin_addr.s_addr = INADDR_BROADCAST;
467                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
468         } else if (!req->ciaddr.s_addr && msg == DHCPV4_MSG_NAK) {
469                 /*
470                  * client has no previous configuration -> no IP, so we need to reply
471                  * with a broadcast packet
472                  */
473                 dest.sin_addr.s_addr = INADDR_BROADCAST;
474                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
475         } else {
476                 /*
477                  * send reply to the newly (in this proccess) allocated IP
478                  */
479                 dest.sin_addr = reply.yiaddr;
480                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
481
482                 struct arpreq arp = {.arp_flags = ATF_COM};
483                 memcpy(arp.arp_ha.sa_data, req->chaddr, 6);
484                 memcpy(&arp.arp_pa, &dest, sizeof(arp.arp_pa));
485                 memcpy(arp.arp_dev, iface->ifname, sizeof(arp.arp_dev));
486                 ioctl(sock, SIOCSARP, &arp);
487         }
488
489         if (dest.sin_addr.s_addr == INADDR_BROADCAST) {
490                 /*
491                  * reply goes to IP broadcast -> MAC broadcast
492                  */
493                 syslog(LOG_WARNING, "sending %s to ff:ff:ff:ff:ff:ff - %s",
494                                 dhcpv4_msg_to_string(msg),
495                                 inet_ntoa(dest.sin_addr));
496         } else {
497                 /*
498                  * reply is send directly to IP,
499                  * MAC is assumed to be the same as the request
500                  */
501                 syslog(LOG_WARNING, "sending %s to %x:%x:%x:%x:%x:%x - %s",
502                                 dhcpv4_msg_to_string(msg),
503                                 req->chaddr[0],req->chaddr[1],req->chaddr[2],
504                                 req->chaddr[3],req->chaddr[4],req->chaddr[5],
505                                 inet_ntoa(dest.sin_addr));
506         }
507
508         sendto(sock, &reply, sizeof(reply), MSG_DONTWAIT,
509                         (struct sockaddr*)&dest, sizeof(dest));
510 }
511
512 static bool dhcpv4_test(struct interface *iface, uint32_t try)
513 {
514         struct dhcpv4_assignment *c;
515         list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
516                 if (c->addr == try) {
517                         return false;
518                 }
519         }
520         return true;
521 }
522
523 static bool dhcpv4_assign(struct interface *iface,
524                 struct dhcpv4_assignment *assign, uint32_t raddr)
525 {
526         uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
527         uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
528         uint32_t count = end - start + 1;
529
530         // try to assign the IP the client asked for
531         if (start <= raddr && raddr <= end && dhcpv4_test(iface, raddr)) {
532                 assign->addr = raddr;
533                 list_add(&assign->head, &iface->dhcpv4_assignments);
534                 syslog(LOG_DEBUG, "assigning the IP the client asked for: %u.%u.%u.%u",
535                                 (assign->addr & 0xff000000) >> 24,
536                                 (assign->addr & 0x00ff0000) >> 16,
537                                 (assign->addr & 0x0000ff00) >> 8,
538                                 (assign->addr & 0x000000ff));
539                 return true;
540         }
541
542         // Seed RNG with checksum of hwaddress
543         uint32_t seed = 0;
544         for (size_t i = 0; i < sizeof(assign->hwaddr); ++i) {
545                 // Knuth's multiplicative method
546                 uint8_t o = assign->hwaddr[i];
547                 seed += (o*2654435761) % UINT32_MAX;
548         }
549         srand(seed);
550
551         uint32_t try = (((uint32_t)rand()) % count) + start;
552
553         if (list_empty(&iface->dhcpv4_assignments)) {
554                 assign->addr = try;
555                 list_add(&assign->head, &iface->dhcpv4_assignments);
556                 syslog(LOG_DEBUG, "assigning mapped IP (empty list): %u.%u.%u.%u",
557                                 (assign->addr & 0xff000000) >> 24,
558                                 (assign->addr & 0x00ff0000) >> 16,
559                                 (assign->addr & 0x0000ff00) >> 8,
560                                 (assign->addr & 0x000000ff));
561                 return true;
562         }
563
564         for (uint32_t i = 0; i < count; ++i) {
565                 if (dhcpv4_test(iface, try)) {
566                         /* test was successful: IP address is not assigned, assign it */
567                         assign->addr = try;
568                         list_add(&assign->head, &iface->dhcpv4_assignments);
569                         syslog(LOG_DEBUG, "assigning mapped IP: %u.%u.%u.%u (try %u of %u)",
570                                         (assign->addr & 0xff000000) >> 24,
571                                         (assign->addr & 0x00ff0000) >> 16,
572                                         (assign->addr & 0x0000ff00) >> 8,
573                                         (assign->addr & 0x000000ff), i, count);
574                         return true;
575                 }
576                 try = (((try - start) + 1) % count) + start;
577         }
578
579         syslog(LOG_DEBUG, "can't assign any IP address -> address space is full");
580         return false;
581 }
582
583
584 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
585                 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
586                 uint32_t *leasetime, const char *hostname)
587 {
588         struct dhcpv4_assignment *lease = NULL;
589         uint32_t raddr = ntohl(reqaddr.s_addr);
590         time_t now = odhcpd_time();
591
592         struct dhcpv4_assignment *c, *n, *a = NULL;
593         list_for_each_entry_safe(c, n, &iface->dhcpv4_assignments, head) {
594                 if (!memcmp(c->hwaddr, mac, 6)) {
595                         a = c;
596                         if (c->addr == raddr)
597                                 break;
598                 } else if (!INFINITE_VALID(c->valid_until) && c->valid_until < now) {
599                         list_del(&c->head);
600                         free(c);
601                 }
602         }
603
604         if (msg == DHCPV4_MSG_DISCOVER || msg == DHCPV4_MSG_REQUEST) {
605                 bool assigned = !!a;
606                 size_t hostlen = strlen(hostname) + 1;
607                 uint32_t my_leasetime;
608
609                 if (!a && !iface->no_dynamic_dhcp) { // Create new binding
610                         a = calloc(1, sizeof(*a) + hostlen);
611                         if (!a) {
612                                 syslog(LOG_ERR, "Failed to calloc binding on interface %s", iface->ifname);
613                                 return NULL;
614                         }
615                         memcpy(a->hwaddr, mac, sizeof(a->hwaddr));
616                         memcpy(a->hostname, hostname, hostlen);
617                         // Don't consider new assignment as infinite
618                         a->valid_until = now;
619
620                         assigned = dhcpv4_assign(iface, a, raddr);
621                 }
622
623                 if (assigned && !a->hostname[0] && hostname) {
624                         a = realloc(a, sizeof(*a) + hostlen);
625                         if (!a) {
626                                 syslog(LOG_ERR, "Failed to realloc binding on interface %s", iface->ifname);
627                                 return NULL;
628                         }
629                         memcpy(a->hostname, hostname, hostlen);
630
631                         // Fixup list
632                         a->head.next->prev = &a->head;
633                         a->head.prev->next = &a->head;
634                 }
635
636                 if (a->leasetime >= 60) {
637                         my_leasetime = a->leasetime;
638                 } else {
639                         my_leasetime = iface->dhcpv4_leasetime;
640                 }
641
642                 if ((*leasetime == 0) || (my_leasetime < *leasetime))
643                         *leasetime = my_leasetime;
644
645                 if (assigned) {
646                         bool is_discover = (msg == DHCPV4_MSG_DISCOVER);
647
648                         if (!INFINITE_VALID(a->valid_until))
649                                 // Was only a discover; mark binding for removal
650                                 a->valid_until = (is_discover ? now : ((*leasetime == UINT32_MAX) ?
651                                                         0 : (time_t)(now + *leasetime)));
652
653                         /* Mark assignment as bound */
654                         if (!is_discover)
655                                 a->flags |= OAF_BOUND;
656
657                 } else if (!assigned && a) { // Cleanup failed assignment
658                         free(a);
659                         a = NULL;
660                 }
661
662                 if (assigned && a)
663                         lease = a;
664         } else if (msg == DHCPV4_MSG_RELEASE && a) {
665                 a->flags &= ~OAF_BOUND;
666
667                 if (!INFINITE_VALID(a->valid_until))
668                         a->valid_until = now - 1;
669
670         } else if (msg == DHCPV4_MSG_DECLINE && a) {
671                 a->flags &= ~OAF_BOUND;
672
673                 if (!INFINITE_VALID(a->valid_until)) {
674                         memset(a->hwaddr, 0, sizeof(a->hwaddr));
675                         a->valid_until = now + 3600; // Block address for 1h
676                 }
677         }
678
679         dhcpv6_write_statefile();
680
681         return lease;
682 }
683