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