dhcpv4: fix error checking in dhcpv4_setup_interface()
[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 <libubox/md5.h>
33
34 #include "odhcpd.h"
35 #include "dhcpv4.h"
36 #include "dhcpv6.h"
37
38 static void dhcpv4_netevent_cb(unsigned long event, struct netevent_handler_info *info);
39 static int setup_dhcpv4_addresses(struct interface *iface);
40 static void update_static_assignments(struct interface *iface);
41 static void valid_until_cb(struct uloop_timeout *event);
42 static void handle_addrlist_change(struct interface *iface);
43 static void free_dhcpv4_assignment(struct dhcpv4_assignment *a);
44 static void dhcpv4_fr_start(struct dhcpv4_assignment *a);
45 static void dhcpv4_fr_stop(struct dhcpv4_assignment *a);
46 static void handle_dhcpv4(void *addr, void *data, size_t len,
47                 struct interface *iface, void *dest_addr);
48 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
49                 enum dhcpv4_msg msg, const uint8_t *mac, const uint32_t reqaddr,
50                 uint32_t *leasetime, const char *hostname, const size_t hostname_len,
51                 const bool accept_fr_nonce, bool *incl_fr_opt, uint32_t *fr_serverid);
52
53 static struct netevent_handler dhcpv4_netevent_handler = { .cb = dhcpv4_netevent_cb, };
54 static struct uloop_timeout valid_until_timeout = {.cb = valid_until_cb};
55 static uint32_t serial = 0;
56
57 struct odhcpd_ref_ip {
58         struct list_head head;
59         int ref_cnt;
60         struct odhcpd_ipaddr addr;
61 };
62
63 /* Create socket and register events */
64 int dhcpv4_init(void)
65 {
66         uloop_timeout_set(&valid_until_timeout, 1000);
67         netlink_add_netevent_handler(&dhcpv4_netevent_handler);
68
69         return 0;
70 }
71
72 int dhcpv4_setup_interface(struct interface *iface, bool enable)
73 {
74         int ret = 0;
75
76         if (iface->dhcpv4_event.uloop.fd > 0) {
77                 uloop_fd_delete(&iface->dhcpv4_event.uloop);
78                 close(iface->dhcpv4_event.uloop.fd);
79                 iface->dhcpv4_event.uloop.fd = -1;
80         }
81
82         if (iface->dhcpv4 && enable) {
83                 struct sockaddr_in bind_addr = {AF_INET, htons(DHCPV4_SERVER_PORT),
84                                         {INADDR_ANY}, {0}};
85                 int val = 1;
86
87                 if (!iface->dhcpv4_assignments.next)
88                         INIT_LIST_HEAD(&iface->dhcpv4_assignments);
89
90                 if (!iface->dhcpv4_fr_ips.next)
91                         INIT_LIST_HEAD(&iface->dhcpv4_fr_ips);
92
93                 iface->dhcpv4_event.uloop.fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
94                 if (iface->dhcpv4_event.uloop.fd < 0) {
95                         syslog(LOG_ERR, "socket(AF_INET): %m");
96                         ret = -1;
97                         goto out;
98                 }
99
100                 /* Basic IPv4 configuration */
101                 if (setsockopt(iface->dhcpv4_event.uloop.fd, SOL_SOCKET, SO_REUSEADDR,
102                                         &val, sizeof(val)) < 0) {
103                         syslog(LOG_ERR, "setsockopt(SO_REUSEADDR): %m");
104                         ret = -1;
105                         goto out;
106                 }
107
108                 if (setsockopt(iface->dhcpv4_event.uloop.fd, SOL_SOCKET, SO_BROADCAST,
109                                         &val, sizeof(val)) < 0) {
110                         syslog(LOG_ERR, "setsockopt(SO_BROADCAST): %m");
111                         ret = -1;
112                         goto out;
113                 }
114
115                 if (setsockopt(iface->dhcpv4_event.uloop.fd, IPPROTO_IP, IP_PKTINFO,
116                                         &val, sizeof(val)) < 0) {
117                         syslog(LOG_ERR, "setsockopt(IP_PKTINFO): %m");
118                         ret = -1;
119                         goto out;
120                 }
121
122                 val = IPTOS_PREC_INTERNETCONTROL;
123                 if (setsockopt(iface->dhcpv4_event.uloop.fd, IPPROTO_IP, IP_TOS,
124                                         &val, sizeof(val)) < 0) {
125                         syslog(LOG_ERR, "setsockopt(IP_TOS): %m");
126                         ret = -1;
127                         goto out;
128                 }
129
130                 val = IP_PMTUDISC_DONT;
131                 if (setsockopt(iface->dhcpv4_event.uloop.fd, IPPROTO_IP, IP_MTU_DISCOVER,
132                                         &val, sizeof(val)) < 0) {
133                         syslog(LOG_ERR, "setsockopt(IP_MTU_DISCOVER): %m");
134                         ret = -1;
135                         goto out;
136                 }
137
138                 if (setsockopt(iface->dhcpv4_event.uloop.fd, SOL_SOCKET, SO_BINDTODEVICE,
139                                         iface->ifname, strlen(iface->ifname)) < 0) {
140                         syslog(LOG_ERR, "setsockopt(SO_BINDTODEVICE): %m");
141                         ret = -1;
142                         goto out;
143                 }
144
145                 if (bind(iface->dhcpv4_event.uloop.fd, (struct sockaddr*)&bind_addr,
146                                         sizeof(bind_addr)) < 0) {
147                         syslog(LOG_ERR, "bind(): %m");
148                         ret = -1;
149                         goto out;
150                 }
151
152                 if (setup_dhcpv4_addresses(iface) < 0) {
153                         ret = -1;
154                         goto out;
155                 }
156
157                 iface->dhcpv4_event.handle_dgram = handle_dhcpv4;
158                 odhcpd_register(&iface->dhcpv4_event);
159
160                 update_static_assignments(iface);
161         } else if (iface->dhcpv4_assignments.next) {
162                 while (!list_empty(&iface->dhcpv4_assignments))
163                         free_dhcpv4_assignment(list_first_entry(&iface->dhcpv4_assignments,
164                                                         struct dhcpv4_assignment, head));
165         }
166
167 out:
168         if (ret < 0 && iface->dhcpv4_event.uloop.fd > 0) {
169                 close(iface->dhcpv4_event.uloop.fd);
170                 iface->dhcpv4_event.uloop.fd = -1;
171         }
172
173         return ret;
174 }
175
176
177 static void dhcpv4_netevent_cb(unsigned long event, struct netevent_handler_info *info)
178 {
179         struct interface *iface = info->iface;
180
181         if (!iface || iface->dhcpv4 == MODE_DISABLED)
182                 return;
183
184         switch (event) {
185         case NETEV_IFINDEX_CHANGE:
186                 dhcpv4_setup_interface(iface, true);
187                 break;
188         case NETEV_ADDRLIST_CHANGE:
189                 handle_addrlist_change(iface);
190                 break;
191         default:
192                 break;
193         }
194 }
195
196 static struct dhcpv4_assignment *find_assignment_by_hwaddr(struct interface *iface, const uint8_t *hwaddr)
197 {
198         struct dhcpv4_assignment *a;
199
200         list_for_each_entry(a, &iface->dhcpv4_assignments, head)
201                 if (!memcmp(a->hwaddr, hwaddr, 6))
202                         return a;
203
204         return NULL;
205 }
206
207 static struct dhcpv4_assignment *find_assignment_by_addr(struct interface *iface, const uint32_t addr)
208 {
209         struct dhcpv4_assignment *a;
210
211         list_for_each_entry(a, &iface->dhcpv4_assignments, head)
212                 if (a->addr == addr)
213                         return a;
214
215         return NULL;
216 }
217
218 static int setup_dhcpv4_addresses(struct interface *iface)
219 {
220         iface->dhcpv4_start_ip.s_addr = INADDR_ANY;
221         iface->dhcpv4_end_ip.s_addr = INADDR_ANY;
222         iface->dhcpv4_local.s_addr = INADDR_ANY;
223         iface->dhcpv4_bcast.s_addr = INADDR_ANY;
224         iface->dhcpv4_mask.s_addr = INADDR_ANY;
225
226         /* Sanity checks */
227         if (iface->dhcpv4_start.s_addr & htonl(0xffff0000) ||
228             iface->dhcpv4_end.s_addr & htonl(0xffff0000) ||
229             ntohl(iface->dhcpv4_start.s_addr) > ntohl(iface->dhcpv4_end.s_addr)) {
230                 syslog(LOG_ERR, "invalid DHCP range for %s", iface->name);
231                 return -1;
232         }
233
234         if (!iface->addr4_len) {
235                 syslog(LOG_WARNING, "no network(s) available on %s", iface->name);
236                 return -1;
237         }
238
239         uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
240         uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
241
242         for (size_t i = 0; i < iface->addr4_len && start && end; i++) {
243                 struct in_addr *addr = &iface->addr4[i].addr.in;
244                 struct in_addr mask;
245
246                 odhcpd_bitlen2netmask(false, iface->addr4[i].prefix, &mask);
247                 if ((start & ntohl(~mask.s_addr)) == start &&
248                             (end & ntohl(~mask.s_addr)) == end) {
249                         iface->dhcpv4_start_ip.s_addr = htonl(start) |
250                                                         (addr->s_addr & mask.s_addr);
251                         iface->dhcpv4_end_ip.s_addr = htonl(end) |
252                                                         (addr->s_addr & mask.s_addr);
253                         iface->dhcpv4_local = *addr;
254                         iface->dhcpv4_bcast = iface->addr4[i].broadcast;
255                         iface->dhcpv4_mask = mask;
256                         return 0;
257                 }
258         }
259
260         /* Don't allocate IP range for subnets bigger than 28 */
261         if (iface->addr4[0].prefix > 28) {
262                 syslog(LOG_WARNING, "auto allocation of DHCP range fails on %s", iface->name);
263                 return -1;
264         }
265
266         iface->dhcpv4_local = iface->addr4[0].addr.in;
267         iface->dhcpv4_bcast = iface->addr4[0].broadcast;
268         odhcpd_bitlen2netmask(false, iface->addr4[0].prefix, &iface->dhcpv4_mask);
269         end = start = iface->dhcpv4_local.s_addr & iface->dhcpv4_mask.s_addr;
270
271         /* Auto allocate ranges */
272         if (ntohl(iface->dhcpv4_mask.s_addr) <= 0xffffff00) {
273                 iface->dhcpv4_start_ip.s_addr = start | htonl(100);
274                 iface->dhcpv4_end_ip.s_addr = end | htonl(250);
275         } else if (ntohl(iface->dhcpv4_mask.s_addr) <= 0xffffffc0) {
276                 iface->dhcpv4_start_ip.s_addr = start | htonl(10);
277                 iface->dhcpv4_end_ip.s_addr = end | htonl(60);
278         } else if (ntohl(iface->dhcpv4_mask.s_addr) <= 0xffffffe0) {
279                 iface->dhcpv4_start_ip.s_addr = start | htonl(10);
280                 iface->dhcpv4_end_ip.s_addr = end | htonl(30);
281         } else {
282                 iface->dhcpv4_start_ip.s_addr = start | htonl(3);
283                 iface->dhcpv4_end_ip.s_addr = end | htonl(12);
284         }
285
286         return 0;
287 }
288
289 static void update_static_assignments(struct interface *iface)
290 {
291         struct dhcpv4_assignment *a, *c;
292
293         /* Cleanup static entries not belonging to the network */
294         list_for_each_entry_safe(a, c, &iface->dhcpv4_assignments, head) {
295                 if ((a->flags & OAF_STATIC) &&
296                                 ((a->addr & iface->dhcpv4_mask.s_addr) !=
297                                  (iface->dhcpv4_start.s_addr & iface->dhcpv4_mask.s_addr)))
298                         free_dhcpv4_assignment(a);
299         }
300
301         /* Parse static entries */
302         struct lease *lease;
303         list_for_each_entry(lease, &leases, head) {
304                 if ((iface->dhcpv4_start_ip.s_addr & iface->dhcpv4_mask.s_addr) !=
305                                 (lease->ipaddr.s_addr & iface->dhcpv4_mask.s_addr)) {
306                         continue;
307                 }
308
309                 a = find_assignment_by_hwaddr(iface, lease->mac.ether_addr_octet);
310
311                 if (!a) {
312                         /* Check if there's an assignment with the specified IP address */
313                         if (find_assignment_by_addr(iface, lease->ipaddr.s_addr))
314                                 continue;
315
316                         /* Construct entry */
317                         a = calloc(1, sizeof(*a));
318                         if (!a) {
319                                 syslog(LOG_ERR, "Calloc failed for static lease on interface %s",
320                                         iface->ifname);
321                                 continue;
322                         }
323                         memcpy(a->hwaddr, lease->mac.ether_addr_octet, sizeof(a->hwaddr));
324                 }
325
326                 a->leasetime = lease->dhcpv4_leasetime;
327
328                 a->addr = lease->ipaddr.s_addr;
329                 /* Static assignment */
330                 a->flags |= OAF_STATIC;
331                 /* Infinite valid */
332                 a->valid_until = 0;
333                 a->iface = iface;
334                 if (lease->hostname[0]) {
335                         free(a->hostname);
336                         a->hostname = strdup(lease->hostname);
337                 }
338
339                 /* Assign to all interfaces */
340                 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
341                         if (ntohl(c->addr) > ntohl(a->addr)) {
342                                 list_add_tail(&a->head, &c->head);
343                                 break;
344                         }
345                 }
346
347                 if (&c->head == &iface->dhcpv4_assignments)
348                         list_add(&a->head, &iface->dhcpv4_assignments);
349         }
350 }
351
352 static void inc_ref_cnt_ip(struct odhcpd_ref_ip **ptr, struct odhcpd_ref_ip *ip)
353 {
354         *ptr = ip;
355         ip->ref_cnt++;
356 }
357
358 static void decr_ref_cnt_ip(struct odhcpd_ref_ip **ptr, struct interface *iface)
359 {
360         struct odhcpd_ref_ip *ip = *ptr;
361
362         if (--ip->ref_cnt == 0) {
363                 netlink_setup_addr(&ip->addr, iface->ifindex, false, false);
364
365                 list_del(&ip->head);
366                 free(ip);
367         }
368
369         *ptr = NULL;
370 }
371
372 static bool leases_require_fr(struct interface *iface, struct odhcpd_ipaddr *addr,
373                                 uint32_t mask)
374 {
375         struct dhcpv4_assignment *a = NULL;
376         struct odhcpd_ref_ip *fr_ip = NULL;
377
378         list_for_each_entry(a, &iface->dhcpv4_assignments, head) {
379                 if ((a->accept_fr_nonce || iface->dhcpv4_forcereconf) &&
380                     !a->fr_ip &&
381                     ((a->addr & mask) == (addr->addr.in.s_addr & mask))) {
382                         if (!fr_ip) {
383                                 fr_ip = calloc(1, sizeof(*fr_ip));
384                                 if (!fr_ip)
385                                         break;
386
387                                 list_add(&fr_ip->head, &iface->dhcpv4_fr_ips);
388                                 fr_ip->addr = *addr;
389                         }
390                         inc_ref_cnt_ip(&a->fr_ip, fr_ip);
391                 }
392         }
393
394         return fr_ip ? true : false;
395 }
396
397 static void valid_until_cb(struct uloop_timeout *event)
398 {
399         time_t now = odhcpd_time();
400         struct interface *iface;
401         list_for_each_entry(iface, &interfaces, head) {
402                 if (iface->dhcpv4 != MODE_SERVER || iface->dhcpv4_assignments.next == NULL)
403                         continue;
404
405                 struct dhcpv4_assignment *a, *n;
406                 list_for_each_entry_safe(a, n, &iface->dhcpv4_assignments, head) {
407                         if (!INFINITE_VALID(a->valid_until) && a->valid_until < now)
408                                 free_dhcpv4_assignment(a);
409                 }
410         }
411         uloop_timeout_set(event, 1000);
412 }
413
414 static void handle_addrlist_change(struct interface *iface)
415 {
416         struct odhcpd_ipaddr ip;
417         struct odhcpd_ref_ip *a;
418         struct dhcpv4_assignment *c;
419         uint32_t mask = iface->dhcpv4_mask.s_addr;
420
421         memset(&ip, 0, sizeof(ip));
422         ip.addr.in = iface->dhcpv4_local;
423         ip.prefix = odhcpd_netmask2bitlen(false, &iface->dhcpv4_mask);
424         ip.broadcast = iface->dhcpv4_bcast;
425
426         setup_dhcpv4_addresses(iface);
427
428         if ((ip.addr.in.s_addr & mask) ==
429             (iface->dhcpv4_local.s_addr & iface->dhcpv4_mask.s_addr))
430                 return;
431
432         if (ip.addr.in.s_addr && !leases_require_fr(iface, &ip, mask))
433                 return;
434
435         if (iface->dhcpv4_local.s_addr == INADDR_ANY || list_empty(&iface->dhcpv4_fr_ips))
436                 return;
437
438         a = list_first_entry(&iface->dhcpv4_fr_ips, struct odhcpd_ref_ip, head);
439
440         if (netlink_setup_addr(&a->addr, iface->ifindex, false, true)) {
441                 syslog(LOG_ERR, "Failed to add ip address");
442                 return;
443         }
444
445         list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
446                 if ((c->flags & OAF_BOUND) && c->fr_ip && !c->fr_cnt) {
447                         if (c->accept_fr_nonce || iface->dhcpv4_forcereconf)
448                                 dhcpv4_fr_start(c);
449                         else
450                                 dhcpv4_fr_stop(c);
451                 }
452         }
453 }
454
455 static char *dhcpv4_msg_to_string(uint8_t reqmsg)
456 {
457         switch (reqmsg) {
458         case (DHCPV4_MSG_DISCOVER):
459                 return "DHCPV4_MSG_DISCOVER";
460         case (DHCPV4_MSG_OFFER):
461                 return "DHCPV4_MSG_OFFER";
462         case (DHCPV4_MSG_REQUEST):
463                 return "DHCPV4_MSG_REQUEST";
464         case (DHCPV4_MSG_DECLINE):
465                 return "DHCPV4_MSG_DECLINE";
466         case (DHCPV4_MSG_ACK):
467                 return "DHCPV4_MSG_ACK";
468         case (DHCPV4_MSG_NAK):
469                 return "DHCPV4_MSG_NAK";
470         case (DHCPV4_MSG_RELEASE):
471                 return "DHCPV4_MSG_RELEASE";
472         case (DHCPV4_MSG_INFORM):
473                 return "DHCPV4_MSG_INFORM";
474         case (DHCPV4_MSG_FORCERENEW):
475                 return "DHCPV4_MSG_FORCERENEW";
476         default:
477                 return "UNKNOWN";
478         }
479 }
480
481 static void free_dhcpv4_assignment(struct dhcpv4_assignment *a)
482 {
483         if (a->head.next)
484                 list_del(&a->head);
485
486         if (a->fr_ip)
487                 dhcpv4_fr_stop(a);
488
489         free(a->hostname);
490         free(a);
491 }
492
493 static void dhcpv4_put(struct dhcpv4_message *msg, uint8_t **cookie,
494                 uint8_t type, uint8_t len, const void *data)
495 {
496         uint8_t *c = *cookie;
497         uint8_t *end = (uint8_t *)msg + sizeof(*msg);
498
499         if (*cookie + 2 + len > end)
500                 return;
501
502         *c++ = type;
503         *c++ = len;
504         memcpy(c, data, len);
505
506         *cookie = c + len;
507 }
508
509 static void dhcpv4_fr_send(struct dhcpv4_assignment *a)
510 {
511         struct dhcpv4_message fr_msg = {
512                 .op = DHCPV4_BOOTREPLY,
513                 .htype = 1,
514                 .hlen = 6,
515                 .hops = 0,
516                 .secs = 0,
517                 .flags = 0,
518                 .ciaddr = {INADDR_ANY},
519                 .yiaddr = {INADDR_ANY},
520                 .siaddr = {INADDR_ANY},
521                 .giaddr = {INADDR_ANY},
522                 .chaddr = {0},
523                 .sname = {0},
524                 .file = {0},
525         };
526         struct dhcpv4_auth_forcerenew *auth_o, auth = {
527                 .protocol = 3,
528                 .algorithm = 1,
529                 .rdm = 0,
530                 .replay = {htonl(time(NULL)), htonl(++serial)},
531                 .type = 2,
532                 .key = {0},
533         };
534         struct interface *iface = a->iface;
535
536         odhcpd_urandom(&fr_msg.xid, sizeof(fr_msg.xid));
537         memcpy(fr_msg.chaddr, a->hwaddr, fr_msg.hlen);
538
539         fr_msg.options[0] = 0x63;
540         fr_msg.options[1] = 0x82;
541         fr_msg.options[2] = 0x53;
542         fr_msg.options[3] = 0x63;
543
544         uint8_t *cookie = &fr_msg.options[4];
545         uint8_t msg = DHCPV4_MSG_FORCERENEW;
546
547         dhcpv4_put(&fr_msg, &cookie, DHCPV4_OPT_MESSAGE, 1, &msg);
548         if (a->accept_fr_nonce) {
549                 dhcpv4_put(&fr_msg, &cookie, DHCPV4_OPT_AUTHENTICATION, sizeof(auth), &auth);
550                 auth_o = (struct dhcpv4_auth_forcerenew *)(cookie - sizeof(auth));
551                 dhcpv4_put(&fr_msg, &cookie, DHCPV4_OPT_END, 0, NULL);
552
553                 md5_ctx_t md5;
554                 uint8_t secretbytes[64];
555                 memset(secretbytes, 0, sizeof(secretbytes));
556                 memcpy(secretbytes, a->key, sizeof(a->key));
557
558                 for (size_t i = 0; i < sizeof(secretbytes); ++i)
559                         secretbytes[i] ^= 0x36;
560
561                 md5_begin(&md5);
562                 md5_hash(secretbytes, sizeof(secretbytes), &md5);
563                 md5_hash(&fr_msg, sizeof(fr_msg), &md5);
564                 md5_end(auth_o->key, &md5);
565
566                 for (size_t i = 0; i < sizeof(secretbytes); ++i) {
567                         secretbytes[i] ^= 0x36;
568                         secretbytes[i] ^= 0x5c;
569                 }
570
571                 md5_begin(&md5);
572                 md5_hash(secretbytes, sizeof(secretbytes), &md5);
573                 md5_hash(auth_o->key, sizeof(auth_o->key), &md5);
574                 md5_end(auth_o->key, &md5);
575         } else {
576                 dhcpv4_put(&fr_msg, &cookie, DHCPV4_OPT_SERVERID, 4,
577                                 &a->fr_ip->addr.addr.in.s_addr);
578                 dhcpv4_put(&fr_msg, &cookie, DHCPV4_OPT_END, 0, NULL);
579         }
580
581         struct sockaddr_in dest;
582         memset(&dest, 0, sizeof(dest));
583         dest.sin_family = AF_INET;
584         dest.sin_port = htons(DHCPV4_CLIENT_PORT);
585         dest.sin_addr.s_addr = a->addr;
586
587         syslog(LOG_WARNING, "sending %s to %02x:%02x:%02x:%02x:%02x:%02x - %s",
588                         dhcpv4_msg_to_string(msg),
589                         a->hwaddr[0], a->hwaddr[1], a->hwaddr[2],
590                         a->hwaddr[3], a->hwaddr[4], a->hwaddr[5],
591                         inet_ntoa(dest.sin_addr));
592
593         sendto(iface->dhcpv4_event.uloop.fd, &fr_msg, sizeof(fr_msg),
594                         MSG_DONTWAIT, (struct sockaddr*)&dest, sizeof(dest));
595 }
596
597 static void dhcpv4_fr_timer(struct uloop_timeout *event)
598 {
599         struct dhcpv4_assignment *a = container_of(event, struct dhcpv4_assignment, fr_timer);
600
601         if (a->fr_cnt > 0 && a->fr_cnt < 8) {
602                 dhcpv4_fr_send(a);
603                 uloop_timeout_set(&a->fr_timer, 1000 << a->fr_cnt);
604                 a->fr_cnt++;
605         } else
606                 dhcpv4_fr_stop(a);
607 }
608
609 static void dhcpv4_fr_start(struct dhcpv4_assignment *a)
610 {
611         uloop_timeout_set(&a->fr_timer, 1000 << a->fr_cnt);
612         a->fr_timer.cb = dhcpv4_fr_timer;
613         a->fr_cnt++;
614
615         dhcpv4_fr_send(a);
616 }
617
618 static void dhcpv4_fr_stop(struct dhcpv4_assignment *a)
619 {
620         uloop_timeout_cancel(&a->fr_timer);
621         decr_ref_cnt_ip(&a->fr_ip, a->iface);
622         a->fr_cnt = 0;
623         a->fr_timer.cb = NULL;
624 }
625
626 // Handler for DHCPv4 messages
627 static void handle_dhcpv4(void *addr, void *data, size_t len,
628                 struct interface *iface, _unused void *dest_addr)
629 {
630         if (!iface->dhcpv4)
631                 return;
632
633         struct dhcpv4_message *req = data;
634         if (len < offsetof(struct dhcpv4_message, options) + 4 ||
635                         req->op != DHCPV4_BOOTREQUEST || req->hlen != 6)
636                 return;
637
638
639         syslog(LOG_NOTICE, "Got DHCPv4 request");
640
641         if (!iface->dhcpv4_start_ip.s_addr && !iface->dhcpv4_end_ip.s_addr) {
642                 syslog(LOG_WARNING, "No DHCP range available on %s", iface->name);
643                 return;
644         }
645
646         int sock = iface->dhcpv4_event.uloop.fd;
647
648         struct dhcpv4_message reply = {
649                 .op = DHCPV4_BOOTREPLY,
650                 .htype = req->htype,
651                 .hlen = req->hlen,
652                 .hops = 0,
653                 .xid = req->xid,
654                 .secs = 0,
655                 .flags = req->flags,
656                 .ciaddr = {INADDR_ANY},
657                 .giaddr = req->giaddr,
658                 .siaddr = iface->dhcpv4_local,
659         };
660         memcpy(reply.chaddr, req->chaddr, sizeof(reply.chaddr));
661
662         reply.options[0] = 0x63;
663         reply.options[1] = 0x82;
664         reply.options[2] = 0x53;
665         reply.options[3] = 0x63;
666
667         uint8_t *cookie = &reply.options[4];
668         uint8_t reqmsg = DHCPV4_MSG_REQUEST;
669         uint8_t msg = DHCPV4_MSG_ACK;
670
671         uint32_t reqaddr = INADDR_ANY;
672         uint32_t leasetime = 0;
673         size_t hostname_len = 0;
674         char hostname[256];
675         bool accept_fr_nonce = false;
676         bool incl_fr_opt = false;
677
678         uint8_t *start = &req->options[4];
679         uint8_t *end = ((uint8_t*)data) + len;
680         struct dhcpv4_option *opt;
681         dhcpv4_for_each_option(start, end, opt) {
682                 if (opt->type == DHCPV4_OPT_MESSAGE && opt->len == 1)
683                         reqmsg = opt->data[0];
684                 else if (opt->type == DHCPV4_OPT_HOSTNAME && opt->len > 0) {
685                         hostname_len = opt->len;
686                         memcpy(hostname, opt->data, hostname_len);
687                         hostname[hostname_len] = 0;
688                 } else if (opt->type == DHCPV4_OPT_IPADDRESS && opt->len == 4)
689                         memcpy(&reqaddr, opt->data, 4);
690                 else if (opt->type == DHCPV4_OPT_SERVERID && opt->len == 4) {
691                         if (memcmp(opt->data, &iface->dhcpv4_local, 4))
692                                 return;
693                 } else if (iface->filter_class && opt->type == DHCPV4_OPT_USER_CLASS) {
694                         uint8_t *c = opt->data, *cend = &opt->data[opt->len];
695                         for (; c < cend && &c[*c] < cend; c = &c[1 + *c]) {
696                                 size_t elen = strlen(iface->filter_class);
697                                 if (*c == elen && !memcmp(&c[1], iface->filter_class, elen))
698                                         return; // Ignore from homenet
699                         }
700                 } else if (opt->type == DHCPV4_OPT_LEASETIME && opt->len == 4)
701                         memcpy(&leasetime, opt->data, 4);
702                 else if (opt->type == DHCPV4_OPT_FORCERENEW_NONCE_CAPABLE && opt->len > 0) {
703                         for (uint8_t i = 0; i < opt->len; i++) {
704                                 if (opt->data[i] == 1) {
705                                         accept_fr_nonce = true;
706                                         break;
707                                 }
708                         }
709
710                 }
711         }
712
713         if (reqmsg != DHCPV4_MSG_DISCOVER && reqmsg != DHCPV4_MSG_REQUEST &&
714                         reqmsg != DHCPV4_MSG_INFORM && reqmsg != DHCPV4_MSG_DECLINE &&
715                         reqmsg != DHCPV4_MSG_RELEASE)
716                 return;
717
718         struct dhcpv4_assignment *lease = NULL;
719         uint32_t serverid = iface->dhcpv4_local.s_addr;
720         uint32_t fr_serverid = INADDR_ANY;
721
722         if (reqmsg != DHCPV4_MSG_INFORM)
723                 lease = dhcpv4_lease(iface, reqmsg, req->chaddr, reqaddr,
724                                         &leasetime, hostname, hostname_len,
725                                         accept_fr_nonce, &incl_fr_opt, &fr_serverid);
726
727         if (!lease) {
728                 if (reqmsg == DHCPV4_MSG_REQUEST)
729                         msg = DHCPV4_MSG_NAK;
730                 else if (reqmsg == DHCPV4_MSG_DISCOVER)
731                         return;
732         } else if (reqmsg == DHCPV4_MSG_DISCOVER)
733                 msg = DHCPV4_MSG_OFFER;
734         else if (reqmsg == DHCPV4_MSG_REQUEST &&
735                         ((reqaddr && reqaddr != lease->addr) ||
736                          (req->ciaddr.s_addr && req->ciaddr.s_addr != lease->addr))) {
737                 msg = DHCPV4_MSG_NAK;
738                 /*
739                  * DHCP client requested an IP which we can't offer to him. Probably the
740                  * client changed the network or the network has been changed. The reply
741                  * type is set to DHCPV4_MSG_NAK, because the client should not use that IP.
742                  *
743                  * For modern devices we build an answer that includes a valid IP, like
744                  * a DHCPV4_MSG_ACK. The client will use that IP and doesn't need to
745                  * perform additional DHCP round trips.
746                  *
747                  */
748
749                 /*
750                  *
751                  * Buggy clients do serverid checking in nack messages; therefore set the
752                  * serverid in nack messages triggered by a previous force renew equal to
753                  * the server id in use at that time by the server
754                  *
755                  */
756                 if (fr_serverid)
757                         serverid = fr_serverid;
758
759                 if (req->ciaddr.s_addr &&
760                                 ((iface->dhcpv4_start_ip.s_addr & iface->dhcpv4_mask.s_addr) !=
761                                  (req->ciaddr.s_addr & iface->dhcpv4_mask.s_addr)))
762                         req->ciaddr.s_addr = INADDR_ANY;
763         }
764
765         syslog(LOG_WARNING, "received %s from %02x:%02x:%02x:%02x:%02x:%02x",
766                         dhcpv4_msg_to_string(reqmsg),
767                         req->chaddr[0],req->chaddr[1],req->chaddr[2],
768                         req->chaddr[3],req->chaddr[4],req->chaddr[5]);
769
770 #ifdef WITH_UBUS
771         if (reqmsg == DHCPV4_MSG_RELEASE)
772                 ubus_bcast_dhcp_event("dhcp.release", req->chaddr, req->hlen,
773                                         &req->ciaddr, hostname, iface->ifname);
774 #endif
775         if (reqmsg == DHCPV4_MSG_DECLINE || reqmsg == DHCPV4_MSG_RELEASE)
776                 return;
777
778         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MESSAGE, 1, &msg);
779         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SERVERID, 4, &serverid);
780
781         if (lease) {
782                 uint32_t val;
783
784                 reply.yiaddr.s_addr = lease->addr;
785
786                 val = htonl(leasetime);
787                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_LEASETIME, 4, &val);
788
789                 if (leasetime != UINT32_MAX) {
790                         val = htonl(500 * leasetime / 1000);
791                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_RENEW, 4, &val);
792
793                         val = htonl(875 * leasetime / 1000);
794                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_REBIND, 4, &val);
795                 }
796
797                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_NETMASK, 4,
798                                 &iface->dhcpv4_mask.s_addr);
799
800                 if (lease->hostname)
801                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_HOSTNAME,
802                                         strlen(lease->hostname), lease->hostname);
803
804                 if (iface->dhcpv4_bcast.s_addr != INADDR_ANY)
805                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_BROADCAST, 4, &iface->dhcpv4_bcast);
806
807                 if (incl_fr_opt) {
808                         if (reqmsg == DHCPV4_MSG_REQUEST) {
809                                 struct dhcpv4_auth_forcerenew auth = {
810                                         .protocol = 3,
811                                         .algorithm = 1,
812                                         .rdm = 0,
813                                         .replay = {htonl(time(NULL)), htonl(++serial)},
814                                         .type = 1,
815                                         .key = {0},
816                                 };
817
818                                 memcpy(auth.key, lease->key, sizeof(auth.key));
819                                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_AUTHENTICATION, sizeof(auth), &auth);
820                         } else {
821                                 uint8_t one = 1;
822                                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_FORCERENEW_NONCE_CAPABLE,
823                                         sizeof(one), &one);
824                         }
825                 }
826         }
827
828         struct ifreq ifr;
829
830         memset(&ifr, 0, sizeof(ifr));
831         strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name) - 1);
832
833         if (!ioctl(sock, SIOCGIFMTU, &ifr)) {
834                 uint16_t mtu = htons(ifr.ifr_mtu);
835                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MTU, 2, &mtu);
836         }
837
838         if (iface->search && iface->search_len <= 255)
839                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
840                                 iface->search_len, iface->search);
841         else if (!res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
842                 uint8_t search_buf[256];
843                 int len = dn_comp(_res.dnsrch[0], search_buf,
844                                                 sizeof(search_buf), NULL, NULL);
845                 if (len > 0)
846                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SEARCH_DOMAIN,
847                                         len, search_buf);
848         }
849
850         if (iface->dhcpv4_router_cnt == 0)
851                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER, 4, &iface->dhcpv4_local);
852         else
853                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER,
854                                 4 * iface->dhcpv4_router_cnt, iface->dhcpv4_router);
855
856
857         if (iface->dhcpv4_dns_cnt == 0)
858                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER, 4, &iface->dhcpv4_local);
859         else
860                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER,
861                                 4 * iface->dhcpv4_dns_cnt, iface->dhcpv4_dns);
862
863
864         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_END, 0, NULL);
865
866         struct sockaddr_in dest = *((struct sockaddr_in*)addr);
867         if (req->giaddr.s_addr) {
868                 /*
869                  * relay agent is configured, send reply to the agent
870                  */
871                 dest.sin_addr = req->giaddr;
872                 dest.sin_port = htons(DHCPV4_SERVER_PORT);
873         } else if (req->ciaddr.s_addr && req->ciaddr.s_addr != dest.sin_addr.s_addr) {
874                 /*
875                  * client has existing configuration (ciaddr is set) AND this address is
876                  * not the address it used for the dhcp message
877                  */
878                 dest.sin_addr = req->ciaddr;
879                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
880         } else if ((ntohs(req->flags) & DHCPV4_FLAG_BROADCAST) ||
881                         req->hlen != reply.hlen || !reply.yiaddr.s_addr) {
882                 /*
883                  * client requests a broadcast reply OR we can't offer an IP
884                  */
885                 dest.sin_addr.s_addr = INADDR_BROADCAST;
886                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
887         } else if (!req->ciaddr.s_addr && msg == DHCPV4_MSG_NAK) {
888                 /*
889                  * client has no previous configuration -> no IP, so we need to reply
890                  * with a broadcast packet
891                  */
892                 dest.sin_addr.s_addr = INADDR_BROADCAST;
893                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
894         } else {
895                 /*
896                  * send reply to the newly (in this proccess) allocated IP
897                  */
898                 dest.sin_addr = reply.yiaddr;
899                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
900
901                 struct arpreq arp = {.arp_flags = ATF_COM};
902                 memcpy(arp.arp_ha.sa_data, req->chaddr, 6);
903                 memcpy(&arp.arp_pa, &dest, sizeof(arp.arp_pa));
904                 memcpy(arp.arp_dev, iface->ifname, sizeof(arp.arp_dev));
905                 ioctl(sock, SIOCSARP, &arp);
906         }
907
908         if (dest.sin_addr.s_addr == INADDR_BROADCAST)
909                 /* reply goes to IP broadcast -> MAC broadcast */
910                 syslog(LOG_WARNING, "sending %s to ff:ff:ff:ff:ff:ff - %s",
911                                 dhcpv4_msg_to_string(msg),
912                                 inet_ntoa(dest.sin_addr));
913         else
914                 /*
915                  * reply is send directly to IP,
916                  * MAC is assumed to be the same as the request
917                  */
918                 syslog(LOG_WARNING, "sending %s to %02x:%02x:%02x:%02x:%02x:%02x - %s",
919                                 dhcpv4_msg_to_string(msg),
920                                 req->chaddr[0],req->chaddr[1],req->chaddr[2],
921                                 req->chaddr[3],req->chaddr[4],req->chaddr[5],
922                                 inet_ntoa(dest.sin_addr));
923
924         sendto(sock, &reply, sizeof(reply), MSG_DONTWAIT,
925                         (struct sockaddr*)&dest, sizeof(dest));
926
927 #ifdef WITH_UBUS
928         if (msg == DHCPV4_MSG_ACK)
929                 ubus_bcast_dhcp_event("dhcp.ack", req->chaddr, req->hlen, &reply.yiaddr,
930                                         hostname, iface->ifname);
931 #endif
932 }
933
934 static bool dhcpv4_assign(struct interface *iface,
935                 struct dhcpv4_assignment *assign, uint32_t raddr)
936 {
937         uint32_t start = ntohl(iface->dhcpv4_start_ip.s_addr);
938         uint32_t end = ntohl(iface->dhcpv4_end_ip.s_addr);
939         uint32_t count = end - start + 1;
940
941         // try to assign the IP the client asked for
942         if (start <= ntohl(raddr) && ntohl(raddr) <= end &&
943                         !find_assignment_by_addr(iface, raddr)) {
944                 assign->addr = raddr;
945                 syslog(LOG_INFO, "assigning the IP the client asked for: %u.%u.%u.%u",
946                                 ((uint8_t *)&assign->addr)[0],
947                                 ((uint8_t *)&assign->addr)[1],
948                                 ((uint8_t *)&assign->addr)[2],
949                                 ((uint8_t *)&assign->addr)[3]);
950                 return true;
951         }
952
953         // Seed RNG with checksum of hwaddress
954         uint32_t seed = 0;
955         for (size_t i = 0; i < sizeof(assign->hwaddr); ++i) {
956                 // Knuth's multiplicative method
957                 uint8_t o = assign->hwaddr[i];
958                 seed += (o*2654435761) % UINT32_MAX;
959         }
960
961         srand(seed);
962
963         uint32_t try = (((uint32_t)rand()) % count) + start;
964
965         if (list_empty(&iface->dhcpv4_assignments)) {
966                 assign->addr = htonl(try);
967                 syslog(LOG_INFO, "assigning mapped IP (empty list): %u.%u.%u.%u",
968                                 ((uint8_t *)&assign->addr)[0],
969                                 ((uint8_t *)&assign->addr)[1],
970                                 ((uint8_t *)&assign->addr)[2],
971                                 ((uint8_t *)&assign->addr)[3]);
972                 return true;
973         }
974
975         for (uint32_t i = 0; i < count; ++i) {
976                 if (!find_assignment_by_addr(iface, htonl(try))) {
977                         /* test was successful: IP address is not assigned, assign it */
978                         assign->addr = htonl(try);
979                         syslog(LOG_DEBUG, "assigning mapped IP: %u.%u.%u.%u (try %u of %u)",
980                                         ((uint8_t *)&assign->addr)[0],
981                                         ((uint8_t *)&assign->addr)[1],
982                                         ((uint8_t *)&assign->addr)[2],
983                                         ((uint8_t *)&assign->addr)[3],
984                                         i, count);
985                         return true;
986                 }
987                 try = (((try - start) + 1) % count) + start;
988         }
989
990         syslog(LOG_WARNING, "can't assign any IP address -> address space is full");
991         return false;
992 }
993
994
995 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
996                 enum dhcpv4_msg msg, const uint8_t *mac, const uint32_t reqaddr,
997                 uint32_t *leasetime, const char *hostname, const size_t hostname_len,
998                 const bool accept_fr_nonce, bool *incl_fr_opt, uint32_t *fr_serverid)
999 {
1000         struct dhcpv4_assignment *a = find_assignment_by_hwaddr(iface, mac);
1001         struct dhcpv4_assignment *lease = NULL;
1002         time_t now = odhcpd_time();
1003
1004         if (a && (a->flags & OAF_BOUND) && a->fr_ip) {
1005                 *fr_serverid = a->fr_ip->addr.addr.in.s_addr;
1006                 dhcpv4_fr_stop(a);
1007         }
1008
1009         if (msg == DHCPV4_MSG_DISCOVER || msg == DHCPV4_MSG_REQUEST) {
1010                 bool assigned = !!a;
1011
1012                 if (!a) {
1013                         if (!iface->no_dynamic_dhcp) {
1014                                 /* Create new binding */
1015                                 a = calloc(1, sizeof(*a));
1016                                 if (!a) {
1017                                         syslog(LOG_ERR, "Failed to calloc binding on interface %s",
1018                                                         iface->ifname);
1019                                         return NULL;
1020                                 }
1021                                 memcpy(a->hwaddr, mac, sizeof(a->hwaddr));
1022                                 /* Don't consider new assignment as infinite */
1023                                 a->valid_until = now;
1024
1025                                 assigned = dhcpv4_assign(iface, a, reqaddr);
1026                                 if (assigned) {
1027                                         a->iface = iface;
1028                                         list_add(&a->head, &iface->dhcpv4_assignments);
1029                                 }
1030                         }
1031                 } else if ((a->addr & iface->dhcpv4_mask.s_addr) !=
1032                                 (iface->dhcpv4_start_ip.s_addr & iface->dhcpv4_mask.s_addr)) {
1033                         list_del(&a->head);
1034
1035                         assigned = dhcpv4_assign(iface, a, reqaddr);
1036                         if (assigned)
1037                                 list_add(&a->head, &iface->dhcpv4_assignments);
1038                 }
1039
1040                 if (assigned) {
1041                         uint32_t my_leasetime;
1042
1043                         if (a->leasetime)
1044                                 my_leasetime = a->leasetime;
1045                         else
1046                                 my_leasetime = iface->dhcpv4_leasetime;
1047
1048                         if ((*leasetime == 0) || (my_leasetime < *leasetime))
1049                                 *leasetime = my_leasetime;
1050
1051                         if (msg == DHCPV4_MSG_DISCOVER) {
1052                                 a->flags &= ~OAF_BOUND;
1053
1054                                 *incl_fr_opt = accept_fr_nonce;
1055                                 if (!(a->flags & OAF_STATIC))
1056                                         a->valid_until = now;
1057                         } else {
1058                                 if (hostname_len > 0) {
1059                                         a->hostname = realloc(a->hostname, hostname_len + 1);
1060                                         if (a->hostname) {
1061                                                 memcpy(a->hostname, hostname, hostname_len);
1062                                                 a->hostname[hostname_len] = 0;
1063                                         }
1064                                 }
1065
1066                                 if (!(a->flags & OAF_BOUND)) {
1067                                         a->accept_fr_nonce = accept_fr_nonce;
1068                                         *incl_fr_opt = accept_fr_nonce;
1069                                         odhcpd_urandom(a->key, sizeof(a->key));
1070                                         a->flags |= OAF_BOUND;
1071                                 } else
1072                                         *incl_fr_opt = false;
1073
1074                                 if (!(a->flags & OAF_STATIC))
1075                                         a->valid_until = ((*leasetime == UINT32_MAX) ? 0 : (time_t)(now + *leasetime));
1076                         }
1077                 } else if (!assigned && a) {
1078                         /* Cleanup failed assignment */
1079                         free_dhcpv4_assignment(a);
1080                         a = NULL;
1081                 }
1082
1083                 if (assigned && a)
1084                         lease = a;
1085         } else if (msg == DHCPV4_MSG_RELEASE && a) {
1086                 a->flags &= ~OAF_BOUND;
1087
1088                 if (!(a->flags & OAF_STATIC))
1089                         a->valid_until = now - 1;
1090
1091         } else if (msg == DHCPV4_MSG_DECLINE && a) {
1092                 a->flags &= ~OAF_BOUND;
1093
1094                 if (!(a->flags & OAF_STATIC)) {
1095                         memset(a->hwaddr, 0, sizeof(a->hwaddr));
1096                         a->valid_until = now + 3600; /* Block address for 1h */
1097                 }
1098         }
1099
1100         dhcpv6_write_statefile();
1101
1102         return lease;
1103 }