Fix last commit
[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 <net/if.h>
24 #include <net/if_arp.h>
25 #include <netinet/ip.h>
26 #include <sys/ioctl.h>
27 #include <sys/timerfd.h>
28 #include <arpa/inet.h>
29
30 #include "odhcpd.h"
31 #include "dhcpv4.h"
32 #include "dhcpv6.h"
33
34
35 static void handle_dhcpv4(void *addr, void *data, size_t len,
36                 struct interface *iface);
37 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
38                 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
39                 const char *hostname);
40
41
42 // Create socket and register events
43 int init_dhcpv4(void)
44 {
45         return 0;
46 }
47
48
49 int setup_dhcpv4_interface(struct interface *iface, bool enable)
50 {
51         if (iface->dhcpv4_event.uloop.fd > 0) {
52                 close(iface->dhcpv4_event.uloop.fd);
53                 iface->dhcpv4_event.uloop.fd = -1;
54         }
55
56         if (iface->dhcpv4 && enable) {
57                 if (!iface->dhcpv4_assignments.next)
58                         INIT_LIST_HEAD(&iface->dhcpv4_assignments);
59
60                 int sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
61
62                 // Basic IPv6 configuration
63                 int val = 1;
64                 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
65                 setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &val, sizeof(val));
66                 setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &val, sizeof(val));
67
68                 val = IPTOS_PREC_INTERNETCONTROL;
69                 setsockopt(sock, IPPROTO_IP, IP_TOS, &val, sizeof(val));
70
71                 val = IP_PMTUDISC_DONT;
72                 setsockopt(sock, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val));
73
74                 setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE,
75                                 iface->ifname, strlen(iface->ifname));
76
77                 struct sockaddr_in bind_addr = {AF_INET, htons(DHCPV4_SERVER_PORT),
78                                         {INADDR_ANY}, {0}};
79
80                 if (bind(sock, (struct sockaddr*)&bind_addr, sizeof(bind_addr))) {
81                         syslog(LOG_ERR, "Failed to open DHCPv4 server socket: %s",
82                                         strerror(errno));
83                         return -1;
84                 }
85
86
87                 if (ntohl(iface->dhcpv4_start.s_addr) > ntohl(iface->dhcpv4_end.s_addr)) {
88                         syslog(LOG_ERR, "Invalid DHCP range");
89                         return -1;
90                 }
91
92                 // Create a range if not specified
93                 struct ifreq ifreq;
94                 strncpy(ifreq.ifr_name, iface->ifname, sizeof(ifreq.ifr_name));
95
96                 struct sockaddr_in *saddr = (struct sockaddr_in*)&ifreq.ifr_addr;
97                 struct sockaddr_in *smask = (struct sockaddr_in*)&ifreq.ifr_netmask;
98                 if (!(iface->dhcpv4_start.s_addr & htonl(0xffff0000)) &&
99                                 !(iface->dhcpv4_end.s_addr & htonl(0xffff0000)) &&
100                                 !ioctl(sock, SIOCGIFADDR, &ifreq)) {
101                         struct in_addr addr = saddr->sin_addr;
102
103                         ioctl(sock, SIOCGIFNETMASK, &ifreq);
104                         struct in_addr mask = smask->sin_addr;
105
106                         uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
107                         uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
108
109                         if (start && end && start < end &&
110                                         start > ntohl(addr.s_addr & ~mask.s_addr) &&
111                                         (start & ntohl(mask.s_addr)) == start &&
112                                         (end & ntohl(mask.s_addr)) == end) {
113                                 iface->dhcpv4_start.s_addr = htonl(start) |
114                                                 (addr.s_addr & mask.s_addr);
115                                 iface->dhcpv4_end.s_addr = htonl(end) |
116                                                 (addr.s_addr & mask.s_addr);
117                         } else if (ntohl(mask.s_addr) <= 0xffffffc0) {
118                                 start = addr.s_addr & mask.s_addr;
119                                 end = addr.s_addr & mask.s_addr;
120
121                                 if (ntohl(mask.s_addr) <= 0xffffff00) {
122                                         iface->dhcpv4_start.s_addr = start | htonl(100);
123                                         iface->dhcpv4_end.s_addr = end | htonl(250);
124                                 } else {
125                                         iface->dhcpv4_start.s_addr = start | htonl(10);
126                                         iface->dhcpv4_end.s_addr = end | htonl(59);
127                                 }
128                         }
129
130
131                 }
132
133                 // Parse static entries
134                 struct lease *lease;
135                 list_for_each_entry(lease, &leases, head) {
136                         // Construct entry
137                         size_t hostlen = strlen(lease->hostname) + 1;
138                         struct dhcpv4_assignment *a = calloc(1, sizeof(*a) + hostlen);
139
140                         a->addr = ntohl(lease->ipaddr.s_addr);
141                         memcpy(a->hwaddr, lease->mac.ether_addr_octet, sizeof(a->hwaddr));
142                         memcpy(a->hostname, lease->hostname, hostlen);
143
144                         // Assign to all interfaces
145                         struct dhcpv4_assignment *c;
146                         list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
147                                 if (c->addr > a->addr) {
148                                         list_add_tail(&a->head, &c->head);
149                                 } else if (c->addr == a->addr) {
150                                         // Already an assignment with that number
151                                         break;
152                                 }
153                         }
154
155                         if (!a->head.next)
156                                 free(a);
157                 }
158
159                 // Clean invalid assignments
160                 struct dhcpv4_assignment *a, *n;
161                 list_for_each_entry_safe(a, n, &iface->dhcpv4_assignments, head) {
162                         if ((htonl(a->addr) & smask->sin_addr.s_addr) !=
163                                         (saddr->sin_addr.s_addr & smask->sin_addr.s_addr)) {
164                                 list_del(&a->head);
165                                 free(a);
166                         }
167                 }
168
169
170                 if (iface->dhcpv4_leasetime < 60)
171                         iface->dhcpv4_leasetime = 43200;
172
173                 iface->dhcpv4_event.uloop.fd = sock;
174                 iface->dhcpv4_event.handle_dgram = handle_dhcpv4;
175                 odhcpd_register(&iface->dhcpv4_event);
176         } else if (iface->dhcpv4_assignments.next) {
177                 while (!list_empty(&iface->dhcpv4_assignments)) {
178                         struct dhcpv4_assignment *a = list_first_entry(&iface->dhcpv4_assignments,
179                                         struct dhcpv4_assignment, head);
180                         list_del(&a->head);
181                         free(a->hostname);
182                         free(a);
183                 }
184
185         }
186         return 0;
187 }
188
189
190 static void dhcpv4_put(struct dhcpv4_message *msg, uint8_t **cookie,
191                 uint8_t type, uint8_t len, const void *data)
192 {
193         uint8_t *c = *cookie;
194         if (*cookie + 2 + len > (uint8_t*)&msg[1])
195                 return;
196
197         *c++ = type;
198         *c++ = len;
199         memcpy(c, data, len);
200
201         *cookie = c + len;
202 }
203
204
205 // Simple DHCPv6-server for information requests
206 static void handle_dhcpv4(void *addr, void *data, size_t len,
207                 struct interface *iface)
208 {
209         if (!iface->dhcpv4)
210                 return;
211
212         struct dhcpv4_message *req = data;
213         if (len < offsetof(struct dhcpv4_message, options) + 4 ||
214                         req->op != DHCPV4_BOOTREQUEST || req->hlen != 6)
215                 return;
216
217         int sock = iface->dhcpv4_event.uloop.fd;
218         struct sockaddr_in ifaddr;
219         struct sockaddr_in ifnetmask;
220
221         syslog(LOG_NOTICE, "Got DHCPv4 request");
222
223         struct ifreq ifreq;
224         memcpy(ifreq.ifr_name, iface->ifname, sizeof(ifreq.ifr_name));
225         if (ioctl(sock, SIOCGIFADDR, &ifreq)) {
226                 syslog(LOG_WARNING, "DHCPv4 failed to detect address: %s", strerror(errno));
227                 return;
228         }
229
230         memcpy(&ifaddr, &ifreq.ifr_addr, sizeof(ifaddr));
231         if (ioctl(sock, SIOCGIFNETMASK, &ifreq))
232                 return;
233
234         memcpy(&ifnetmask, &ifreq.ifr_netmask, sizeof(ifnetmask));
235         uint32_t network = ifaddr.sin_addr.s_addr & ifnetmask.sin_addr.s_addr;
236
237         if ((iface->dhcpv4_start.s_addr & ifnetmask.sin_addr.s_addr) != network ||
238                         (iface->dhcpv4_end.s_addr & ifnetmask.sin_addr.s_addr) != network) {
239                 syslog(LOG_WARNING, "DHCPv4 range out of assigned network");
240                 return;
241         }
242
243         struct ifreq ifr = {.ifr_name = ""};
244         strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
245
246         struct dhcpv4_message reply = {
247                 .op = DHCPV4_BOOTREPLY,
248                 .htype = 1,
249                 .hlen = 6,
250                 .hops = 0,
251                 .xid = req->xid,
252                 .secs = 0,
253                 .flags = req->flags,
254                 .ciaddr = {INADDR_ANY},
255                 .giaddr = req->giaddr,
256                 .siaddr = ifaddr.sin_addr,
257         };
258         memcpy(reply.chaddr, req->chaddr, sizeof(reply.chaddr));
259
260         reply.options[0] = 0x63;
261         reply.options[1] = 0x82;
262         reply.options[2] = 0x53;
263         reply.options[3] = 0x63;
264
265         uint8_t *cookie = &reply.options[4];
266         uint8_t reqmsg = DHCPV4_MSG_REQUEST;
267         uint8_t msg = DHCPV4_MSG_ACK;
268
269         struct in_addr reqaddr = {INADDR_ANY};
270         char hostname[256];
271         hostname[0] = 0;
272
273         uint8_t *start = &req->options[4];
274         uint8_t *end = ((uint8_t*)data) + len;
275         struct dhcpv4_option *opt;
276         dhcpv4_for_each_option(start, end, opt) {
277                 if (opt->type == DHCPV4_OPT_MESSAGE && opt->len == 1) {
278                         reqmsg = opt->data[0];
279                 } else if (opt->type == DHCPV4_OPT_HOSTNAME && opt->len > 0) {
280                         memcpy(hostname, opt->data, opt->len);
281                         hostname[opt->len] = 0;
282                 } else if (opt->type == DHCPV4_OPT_IPADDRESS && opt->len == 4) {
283                         memcpy(&reqaddr, opt->data, 4);
284                 } else if (opt->type == DHCPV4_OPT_SERVERID && opt->len == 4) {
285                         if (memcmp(opt->data, &ifaddr.sin_addr, 4))
286                                 return;
287                 }
288         }
289
290         if (reqmsg != DHCPV4_MSG_DISCOVER && reqmsg != DHCPV4_MSG_REQUEST &&
291                         reqmsg != DHCPV4_MSG_INFORM && reqmsg != DHCPV4_MSG_DECLINE &&
292                         reqmsg != DHCPV4_MSG_RELEASE)
293                 return;
294
295         struct dhcpv4_assignment *lease = NULL;
296         if (reqmsg != DHCPV4_MSG_INFORM)
297                 lease = dhcpv4_lease(iface, reqmsg, req->chaddr, reqaddr, hostname);
298
299         if (!lease) {
300                 if (reqmsg == DHCPV4_MSG_REQUEST)
301                         msg = DHCPV4_MSG_NAK;
302                 else if (reqmsg == DHCPV4_MSG_DISCOVER)
303                         return;
304         } else if (reqmsg == DHCPV4_MSG_DISCOVER) {
305                 msg = DHCPV4_MSG_OFFER;
306         }
307
308         if (reqmsg == DHCPV4_MSG_DECLINE || reqmsg == DHCPV4_MSG_RELEASE)
309                 return;
310
311         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MESSAGE, 1, &msg);
312         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_SERVERID, 4, &ifaddr.sin_addr);
313
314         if (lease) {
315                 reply.yiaddr.s_addr = htonl(lease->addr);
316
317                 uint32_t val = htonl(iface->dhcpv4_leasetime);
318                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_LEASETIME, 4, &val);
319
320                 val = htonl(500 * iface->dhcpv4_leasetime / 1000);
321                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_RENEW, 4, &val);
322
323                 val = htonl(875 * iface->dhcpv4_leasetime / 1000);
324                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_REBIND, 4, &val);
325
326                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_NETMASK, 4, &ifnetmask.sin_addr);
327
328                 if (lease->hostname[0])
329                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_HOSTNAME,
330                                         strlen(lease->hostname), lease->hostname);
331
332                 if (!ioctl(sock, SIOCGIFBRDADDR, &ifr)) {
333                         struct sockaddr_in *ina = (struct sockaddr_in*)&ifr.ifr_broadaddr;
334                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_BROADCAST, 4, &ina->sin_addr);
335                 }
336         }
337
338         if (!ioctl(sock, SIOCGIFMTU, &ifr)) {
339                 uint16_t mtu = htons(ifr.ifr_mtu);
340                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_MTU, 2, &mtu);
341         }
342
343         if (iface->search) {
344                 char b[256];
345                 if (dn_expand(iface->search, iface->search + iface->search_len,
346                                 iface->search, b, sizeof(b)) > 0)
347                         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DOMAIN, strlen(b), b);
348         } else if (!res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
349                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DOMAIN,
350                                 strlen(_res.dnsrch[0]), _res.dnsrch[0]);
351         }
352
353         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_ROUTER, 4, &ifaddr.sin_addr);
354
355
356
357         if (iface->dhcpv4_dns_cnt == 0)
358                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER, 4, &ifaddr.sin_addr);
359         else
360                 dhcpv4_put(&reply, &cookie, DHCPV4_OPT_DNSSERVER,
361                                 4 * iface->dhcpv4_dns_cnt, iface->dhcpv4_dns);
362
363
364         dhcpv4_put(&reply, &cookie, DHCPV4_OPT_END, 0, NULL);
365
366         struct sockaddr_in dest = *((struct sockaddr_in*)addr);
367         if (req->giaddr.s_addr) {
368                 dest.sin_addr = req->giaddr;
369                 dest.sin_port = htons(DHCPV4_SERVER_PORT);
370         } else if (req->ciaddr.s_addr && req->ciaddr.s_addr != dest.sin_addr.s_addr) {
371                 dest.sin_addr = req->ciaddr;
372                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
373         } else if ((ntohs(req->flags) & DHCPV4_FLAG_BROADCAST) ||
374                         req->hlen != reply.hlen) {
375                 dest.sin_addr.s_addr = INADDR_BROADCAST;
376                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
377         } else {
378                 dest.sin_addr = reply.yiaddr;
379                 dest.sin_port = htons(DHCPV4_CLIENT_PORT);
380
381                 struct arpreq arp = {.arp_flags = ATF_COM};
382                 memcpy(arp.arp_ha.sa_data, req->chaddr, 6);
383                 memcpy(&arp.arp_pa, &dest, sizeof(arp.arp_pa));
384                 memcpy(arp.arp_dev, iface->ifname, sizeof(arp.arp_dev));
385                 ioctl(sock, SIOCSARP, &arp);
386         }
387
388         sendto(sock, &reply, sizeof(reply), MSG_DONTWAIT,
389                         (struct sockaddr*)&dest, sizeof(dest));
390 }
391
392
393 static bool dhcpv4_assign(struct interface *iface,
394                 struct dhcpv4_assignment *assign, uint32_t raddr)
395 {
396         const unsigned tries = 10;
397         uint32_t start = ntohl(iface->dhcpv4_start.s_addr);
398         uint32_t end = ntohl(iface->dhcpv4_end.s_addr);
399         uint32_t count = end - start + 1;
400
401         // Seed RNG with checksum of DUID
402         uint32_t seed = 0;
403         for (size_t i = 0; i < sizeof(assign->hwaddr); ++i)
404                 seed += assign->hwaddr[i];
405         srand(seed);
406
407         // Try to assign up to 100x
408         for (unsigned i = 0; i < tries; ++i) {
409                 uint32_t try = (((uint32_t)rand()) % count) + start;
410                 if (i == 0 && raddr >= start && raddr <= end)
411                         try = raddr;
412                 else if (i == tries - 1)
413                         try = start;
414
415                 if (list_empty(&iface->dhcpv4_assignments)) {
416                         assign->addr = try;
417                         list_add(&assign->head, &iface->dhcpv4_assignments);
418                         return true;
419                 }
420
421                 struct dhcpv4_assignment *c;
422                 list_for_each_entry(c, &iface->dhcpv4_assignments, head) {
423                         if (c->addr > try) {
424                                 assign->addr = try;
425                                 list_add_tail(&assign->head, &c->head);
426                                 return true;
427                         } else if (c->addr == try) {
428                                 if (i < tries - 1)
429                                         break;
430                                 else
431                                         ++try;
432                         }
433                 }
434         }
435
436         return false;
437 }
438
439
440 static struct dhcpv4_assignment* dhcpv4_lease(struct interface *iface,
441                 enum dhcpv4_msg msg, const uint8_t *mac, struct in_addr reqaddr,
442                 const char *hostname)
443 {
444         struct dhcpv4_assignment *lease = NULL;
445         uint32_t raddr = ntohl(reqaddr.s_addr);
446         time_t now = odhcpd_time();
447
448         struct dhcpv4_assignment *c, *n, *a = NULL;
449         list_for_each_entry_safe(c, n, &iface->dhcpv4_assignments, head) {
450                 if (c->addr == raddr && !memcmp(c->hwaddr, mac, 6)) {
451                         a = c;
452                         break;
453                 } else if (c->valid_until < now) {
454                         list_del(&c->head);
455                         free(c);
456                 }
457         }
458
459         bool update_state = false;
460         if (msg == DHCPV4_MSG_DISCOVER || msg == DHCPV4_MSG_REQUEST) {
461                 bool assigned = !!a;
462                 size_t hostlen = strlen(hostname) + 1;
463
464                 if (!a && !iface->no_dynamic_dhcp) { // Create new binding
465                         a = calloc(1, sizeof(*a) + hostlen);
466                         memcpy(a->hwaddr, mac, sizeof(a->hwaddr));
467                         memcpy(a->hostname, hostname, hostlen);
468
469                         assigned = dhcpv4_assign(iface, a, raddr);
470                 }
471
472                 if (assigned && !a->hostname[0] && hostname) {
473                         a = realloc(a, sizeof(*a) + hostlen);
474                         memcpy(a->hostname, hostname, hostlen);
475
476                         // Fixup list
477                         a->head.next->prev = &a->head;
478                         a->head.prev->next = &a->head;
479                 }
480
481                 // Was only a solicitation: mark binding for removal
482                 if (assigned && a->valid_until < now) {
483                         a->valid_until = (msg == DHCPV4_MSG_DISCOVER) ? 0 :
484                                         (now + iface->dhcpv4_leasetime);
485                 } else if (!assigned && a) { // Cleanup failed assignment
486                         free(a);
487                         a = NULL;
488                 }
489
490                 if (assigned && a)
491                         lease = a;
492         } else if (msg == DHCPV4_MSG_RELEASE) {
493                 if (a) {
494                         a->valid_until = 0;
495                         update_state = true;
496                 }
497         } else if (msg == DHCPV4_MSG_DECLINE) {
498                 memset(a->hwaddr, 0, sizeof(a->hwaddr));
499                 a->valid_until = now + 3600; // Block address for 1h
500                 update_state = true;
501         }
502
503         if (update_state)
504                 dhcpv6_write_statefile();
505
506         return lease;
507 }
508