Fix more memory corruption
[project/odhcpd.git] / src / odhcpd.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 #include <time.h>
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <stdio.h>
19 #include <resolv.h>
20 #include <getopt.h>
21 #include <stddef.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <signal.h>
26 #include <stdbool.h>
27
28 #include <arpa/inet.h>
29 #include <net/if.h>
30 #include <netinet/ip6.h>
31 #include <netpacket/packet.h>
32 #include <linux/rtnetlink.h>
33
34 #include <sys/socket.h>
35 #include <sys/ioctl.h>
36 #include <sys/epoll.h>
37 #include <sys/types.h>
38 #include <sys/wait.h>
39 #include <sys/syscall.h>
40
41 #include <libubox/uloop.h>
42 #include "odhcpd.h"
43
44
45
46 static int ioctl_sock;
47 static int rtnl_socket = -1;
48 static int rtnl_seq = 0;
49 static int urandom_fd = -1;
50
51
52 int main()
53 {
54         openlog("odhcpd", LOG_PERROR | LOG_PID, LOG_DAEMON);
55         uloop_init();
56
57         if (getuid() != 0) {
58                 syslog(LOG_ERR, "Must be run as root!");
59                 return 2;
60         }
61
62         ioctl_sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
63
64         if ((rtnl_socket = odhcpd_open_rtnl()) < 0) {
65                 syslog(LOG_ERR, "Unable to open socket: %s", strerror(errno));
66                 return 2;
67         }
68
69         if ((urandom_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC)) < 0)
70                 return 4;
71
72         signal(SIGUSR1, SIG_IGN);
73
74         if (init_router())
75                 return 4;
76
77         if (init_dhcpv6())
78                 return 4;
79
80         if (init_ndp())
81                 return 4;
82
83         if (init_dhcpv4())
84                 return 4;
85
86         if (init_ubus())
87                 return 4;
88
89         odhcpd_run();
90         return 0;
91 }
92
93 int odhcpd_open_rtnl(void)
94 {
95         int sock = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
96
97         // Connect to the kernel netlink interface
98         struct sockaddr_nl nl = {.nl_family = AF_NETLINK};
99         if (connect(sock, (struct sockaddr*)&nl, sizeof(nl))) {
100                 syslog(LOG_ERR, "Failed to connect to kernel rtnetlink: %s",
101                                 strerror(errno));
102                 return -1;
103         }
104
105         return sock;
106 }
107
108
109 // Read IPv6 MTU for interface
110 int odhcpd_get_interface_mtu(const char *ifname)
111 {
112         char buf[64];
113         const char *sysctl_pattern = "/proc/sys/net/ipv6/conf/%s/mtu";
114         snprintf(buf, sizeof(buf), sysctl_pattern, ifname);
115
116         int fd = open(buf, O_RDONLY);
117         ssize_t len = read(fd, buf, sizeof(buf) - 1);
118         close(fd);
119
120         if (len < 0)
121                 return -1;
122
123
124         buf[len] = 0;
125         return atoi(buf);
126
127 }
128
129
130 // Read IPv6 MAC for interface
131 int odhcpd_get_mac(const struct interface *iface, uint8_t mac[6])
132 {
133         struct ifreq ifr;
134         memset(&ifr, 0, sizeof(ifr));
135         strncpy(ifr.ifr_name, iface->ifname, sizeof(ifr.ifr_name));
136         if (ioctl(ioctl_sock, SIOCGIFHWADDR, &ifr) < 0)
137                 return -1;
138         memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
139         return 0;
140 }
141
142
143 // Forwards a packet on a specific interface
144 ssize_t odhcpd_send(int socket, struct sockaddr_in6 *dest,
145                 struct iovec *iov, size_t iov_len,
146                 const struct interface *iface)
147 {
148         // Construct headers
149         uint8_t cmsg_buf[CMSG_SPACE(sizeof(struct in6_pktinfo))] = {0};
150         struct msghdr msg = {(void*)dest, sizeof(*dest), iov, iov_len,
151                                 cmsg_buf, sizeof(cmsg_buf), 0};
152
153         // Set control data (define destination interface)
154         struct cmsghdr *chdr = CMSG_FIRSTHDR(&msg);
155         chdr->cmsg_level = IPPROTO_IPV6;
156         chdr->cmsg_type = IPV6_PKTINFO;
157         chdr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
158         struct in6_pktinfo *pktinfo = (struct in6_pktinfo*)CMSG_DATA(chdr);
159         pktinfo->ipi6_ifindex = iface->ifindex;
160
161         // Also set scope ID if link-local
162         if (IN6_IS_ADDR_LINKLOCAL(&dest->sin6_addr)
163                         || IN6_IS_ADDR_MC_LINKLOCAL(&dest->sin6_addr))
164                 dest->sin6_scope_id = iface->ifindex;
165
166         // IPV6_PKTINFO doesn't really work for IPv6-raw sockets (bug?)
167         if (dest->sin6_port == 0) {
168                 msg.msg_control = NULL;
169                 msg.msg_controllen = 0;
170         }
171
172         char ipbuf[INET6_ADDRSTRLEN];
173         inet_ntop(AF_INET6, &dest->sin6_addr, ipbuf, sizeof(ipbuf));
174
175         ssize_t sent = sendmsg(socket, &msg, MSG_DONTWAIT);
176         if (sent < 0)
177                 syslog(LOG_WARNING, "Failed to send to %s%%%s (%s)",
178                                 ipbuf, iface->ifname, strerror(errno));
179         else
180                 syslog(LOG_NOTICE, "Sent %li bytes to %s%%%s",
181                                 (long)sent, ipbuf, iface->ifname);
182         return sent;
183 }
184
185
186 // Detect an IPV6-address currently assigned to the given interface
187 ssize_t odhcpd_get_interface_addresses(int ifindex,
188                 struct odhcpd_ipaddr *addrs, size_t cnt)
189 {
190         struct {
191                 struct nlmsghdr nhm;
192                 struct ifaddrmsg ifa;
193         } req = {{sizeof(req), RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP,
194                         ++rtnl_seq, 0}, {AF_INET6, 0, 0, 0, ifindex}};
195         if (send(rtnl_socket, &req, sizeof(req), 0) < (ssize_t)sizeof(req))
196                 return 0;
197
198         uint8_t buf[8192];
199         ssize_t len = 0, ret = 0;
200
201         for (struct nlmsghdr *nhm = NULL; ; nhm = NLMSG_NEXT(nhm, len)) {
202                 while (len < 0 || !NLMSG_OK(nhm, (size_t)len)) {
203                         len = recv(rtnl_socket, buf, sizeof(buf), 0);
204                         nhm = (struct nlmsghdr*)buf;
205                         if (len < 0 || !NLMSG_OK(nhm, (size_t)len)) {
206                                 if (errno == EINTR)
207                                         continue;
208                                 else
209                                         return ret;
210                         }
211                 }
212
213                 if (nhm->nlmsg_type != RTM_NEWADDR)
214                         break;
215
216                 // Skip address but keep clearing socket buffer
217                 if (ret >= (ssize_t)cnt)
218                         continue;
219
220                 struct ifaddrmsg *ifa = NLMSG_DATA(nhm);
221                 if (ifa->ifa_scope != RT_SCOPE_UNIVERSE ||
222                                 ifa->ifa_index != (unsigned)ifindex)
223                         continue;
224
225                 struct rtattr *rta = (struct rtattr*)&ifa[1];
226                 size_t alen = NLMSG_PAYLOAD(nhm, sizeof(*ifa));
227                 memset(&addrs[ret], 0, sizeof(addrs[ret]));
228                 addrs[ret].prefix = ifa->ifa_prefixlen;
229
230                 while (RTA_OK(rta, alen)) {
231                         if (rta->rta_type == IFA_ADDRESS) {
232                                 memcpy(&addrs[ret].addr, RTA_DATA(rta),
233                                                 sizeof(struct in6_addr));
234                         } else if (rta->rta_type == IFA_CACHEINFO) {
235                                 struct ifa_cacheinfo *ifc = RTA_DATA(rta);
236                                 addrs[ret].preferred = ifc->ifa_prefered;
237                                 addrs[ret].valid = ifc->ifa_valid;
238                         }
239
240                         rta = RTA_NEXT(rta, alen);
241                 }
242
243                 if (ifa->ifa_flags & IFA_F_DEPRECATED)
244                         addrs[ret].preferred = 0;
245
246                 ++ret;
247         }
248
249         return ret;
250 }
251
252
253 struct interface* odhcpd_get_interface_by_index(int ifindex)
254 {
255         struct interface *iface;
256         list_for_each_entry(iface, &interfaces, head)
257                 if (iface->ifindex == ifindex)
258                         return iface;
259
260         return NULL;
261 }
262
263
264 struct interface* odhcpd_get_interface_by_name(const char *name)
265 {
266         struct interface *iface;
267         list_for_each_entry(iface, &interfaces, head)
268                 if (!strcmp(iface->ifname, name))
269                         return iface;
270
271         return NULL;
272 }
273
274
275 struct interface* odhcpd_get_master_interface(void)
276 {
277         struct interface *iface;
278         list_for_each_entry(iface, &interfaces, head)
279                 if (iface->master)
280                         return iface;
281
282         return NULL;
283 }
284
285
286 // Convenience function to receive and do basic validation of packets
287 static void odhcpd_receive_packets(struct uloop_fd *u, _unused unsigned int events)
288 {
289         struct odhcpd_event *e = container_of(u, struct odhcpd_event, uloop);
290
291         uint8_t data_buf[RELAYD_BUFFER_SIZE], cmsg_buf[128];
292         union {
293                 struct sockaddr_in6 in6;
294                 struct sockaddr_in in;
295                 struct sockaddr_ll ll;
296                 struct sockaddr_nl nl;
297         } addr;
298
299         while (true) {
300                 struct iovec iov = {data_buf, sizeof(data_buf)};
301                 struct msghdr msg = {&addr, sizeof(addr), &iov, 1,
302                                 cmsg_buf, sizeof(cmsg_buf), 0};
303
304                 ssize_t len = recvmsg(u->fd, &msg, MSG_DONTWAIT);
305                 if (len < 0) {
306                         if (errno == EAGAIN)
307                                 break;
308                         else
309                                 continue;
310                 }
311
312
313                 // Extract destination interface
314                 int destiface = 0;
315                 int *hlim = NULL;
316                 struct in6_pktinfo *pktinfo;
317                 struct in_pktinfo *pkt4info;
318                 for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL &&
319                                 destiface == 0; ch = CMSG_NXTHDR(&msg, ch)) {
320                         if (ch->cmsg_level == IPPROTO_IPV6 &&
321                                         ch->cmsg_type == IPV6_PKTINFO) {
322                                 pktinfo = (struct in6_pktinfo*)CMSG_DATA(ch);
323                                 destiface = pktinfo->ipi6_ifindex;
324                         } else if (ch->cmsg_level == IPPROTO_IP &&
325                                         ch->cmsg_type == IP_PKTINFO) {
326                                 pkt4info = (struct in_pktinfo*)CMSG_DATA(ch);
327                                 destiface = pkt4info->ipi_ifindex;
328                         } else if (ch->cmsg_level == IPPROTO_IPV6 &&
329                                         ch->cmsg_type == IPV6_HOPLIMIT) {
330                                 hlim = (int*)CMSG_DATA(ch);
331                         }
332                 }
333
334                 // Check hoplimit if received
335                 if (hlim && *hlim != 255)
336                         continue;
337
338                 // Detect interface for packet sockets
339                 if (addr.ll.sll_family == AF_PACKET)
340                         destiface = addr.ll.sll_ifindex;
341
342                 struct interface *iface =
343                                 odhcpd_get_interface_by_index(destiface);
344
345                 if (!iface && addr.nl.nl_family != AF_NETLINK)
346                         continue;
347
348                 char ipbuf[INET6_ADDRSTRLEN] = "kernel";
349                 if (addr.ll.sll_family == AF_PACKET &&
350                                 len >= (ssize_t)sizeof(struct ip6_hdr))
351                         inet_ntop(AF_INET6, &data_buf[8], ipbuf, sizeof(ipbuf));
352                 else if (addr.in6.sin6_family == AF_INET6)
353                         inet_ntop(AF_INET6, &addr.in6.sin6_addr, ipbuf, sizeof(ipbuf));
354                 else if (addr.in.sin_family == AF_INET)
355                         inet_ntop(AF_INET, &addr.in.sin_addr, ipbuf, sizeof(ipbuf));
356
357                 syslog(LOG_NOTICE, "--");
358                 syslog(LOG_NOTICE, "Received %li Bytes from %s%%%s", (long)len,
359                                 ipbuf, (iface) ? iface->ifname : "netlink");
360
361                 e->handle_dgram(&addr, data_buf, len, iface);
362         }
363 }
364
365 // Register events for the multiplexer
366 int odhcpd_register(struct odhcpd_event *event)
367 {
368         event->uloop.cb = odhcpd_receive_packets;
369         return uloop_fd_add(&event->uloop, ULOOP_READ);
370 }
371
372 void odhcpd_urandom(void *data, size_t len)
373 {
374         read(urandom_fd, data, len);
375 }
376
377
378 time_t odhcpd_time(void)
379 {
380         struct timespec ts;
381         syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &ts);
382         return ts.tv_sec;
383 }
384
385
386 static const char hexdigits[] = "0123456789abcdef";
387 static const int8_t hexvals[] = {
388     -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1,
389     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
390     -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
391      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
392     -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
393     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
394     -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
395     -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
396 };
397
398 ssize_t odhcpd_unhexlify(uint8_t *dst, size_t len, const char *src)
399 {
400         size_t c;
401         for (c = 0; c < len && src[0] && src[1]; ++c) {
402                 int8_t x = (int8_t)*src++;
403                 int8_t y = (int8_t)*src++;
404                 if (x < 0 || (x = hexvals[x]) < 0
405                                 || y < 0 || (y = hexvals[y]) < 0)
406                         return -1;
407                 dst[c] = x << 4 | y;
408                 while (((int8_t)*src) < 0 ||
409                                 (*src && hexvals[(uint8_t)*src] < 0))
410                         src++;
411         }
412
413         return c;
414 }
415
416
417 void odhcpd_hexlify(char *dst, const uint8_t *src, size_t len)
418 {
419         for (size_t i = 0; i < len; ++i) {
420                 *dst++ = hexdigits[src[i] >> 4];
421                 *dst++ = hexdigits[src[i] & 0x0f];
422         }
423         *dst = 0;
424 }