1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29 #include <ifaddrs.h>
30
31 #include <async_safe/log.h>
32 #include <cutils/misc.h> // FIRST_APPLICATION_UID
33 #include <errno.h>
34 #include <linux/if_packet.h>
35 #include <net/if.h>
36 #include <netinet/in.h>
37 #include <stdint.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42
43 #include "private/ErrnoRestorer.h"
44
45 #include "bionic_netlink.h"
46
47 // The public ifaddrs struct is full of pointers. Rather than track several
48 // different allocations, we use a maximally-sized structure with the public
49 // part at offset 0, and pointers into its hidden tail.
50 struct ifaddrs_storage {
51 // Must come first, so that `ifaddrs_storage` is-a `ifaddrs`.
52 ifaddrs ifa;
53
54 // The interface index, so we can match RTM_NEWADDR messages with
55 // earlier RTM_NEWLINK messages (to copy the interface flags).
56 int interface_index;
57
58 // Storage for the pointers in `ifa`.
59 sockaddr_storage addr;
60 sockaddr_storage netmask;
61 sockaddr_storage ifa_ifu;
62 char name[IFNAMSIZ + 1];
63
ifaddrs_storageifaddrs_storage64 explicit ifaddrs_storage(ifaddrs** list) {
65 memset(this, 0, sizeof(*this));
66
67 // push_front onto `list`.
68 ifa.ifa_next = *list;
69 *list = reinterpret_cast<ifaddrs*>(this);
70 }
71
SetAddressifaddrs_storage72 void SetAddress(int family, const void* data, size_t byteCount) {
73 // The kernel currently uses the order IFA_ADDRESS, IFA_LOCAL, IFA_BROADCAST
74 // in inet_fill_ifaddr, but let's not assume that will always be true...
75 if (ifa.ifa_addr == nullptr) {
76 // This is an IFA_ADDRESS and haven't seen an IFA_LOCAL yet, so assume this is the
77 // local address. SetLocalAddress will fix things if we later see an IFA_LOCAL.
78 ifa.ifa_addr = CopyAddress(family, data, byteCount, &addr);
79 } else {
80 // We already saw an IFA_LOCAL, which implies this is a destination address.
81 ifa.ifa_dstaddr = CopyAddress(family, data, byteCount, &ifa_ifu);
82 }
83 }
84
SetBroadcastAddressifaddrs_storage85 void SetBroadcastAddress(int family, const void* data, size_t byteCount) {
86 // ifa_broadaddr and ifa_dstaddr overlap in a union. Unfortunately, it's possible
87 // to have an interface with both. Keeping the last thing the kernel gives us seems
88 // to be glibc 2.19's behavior too, so our choice is being source compatible with
89 // badly-written code that assumes ifa_broadaddr and ifa_dstaddr are interchangeable
90 // or supporting interfaces with both addresses configured. My assumption is that
91 // bad code is more common than weird network interfaces...
92 ifa.ifa_broadaddr = CopyAddress(family, data, byteCount, &ifa_ifu);
93 }
94
SetLocalAddressifaddrs_storage95 void SetLocalAddress(int family, const void* data, size_t byteCount) {
96 // The kernel source says "for point-to-point IFA_ADDRESS is DESTINATION address,
97 // local address is supplied in IFA_LOCAL attribute".
98 // -- http://lxr.free-electrons.com/source/include/uapi/linux/if_addr.h#L17
99
100 // So copy any existing IFA_ADDRESS into ifa_dstaddr...
101 if (ifa.ifa_addr != nullptr) {
102 ifa.ifa_dstaddr = reinterpret_cast<sockaddr*>(memcpy(&ifa_ifu, &addr, sizeof(addr)));
103 }
104 // ...and then put this IFA_LOCAL into ifa_addr.
105 ifa.ifa_addr = CopyAddress(family, data, byteCount, &addr);
106 }
107
108 // Netlink gives us the prefix length as a bit count. We need to turn
109 // that into a BSD-compatible netmask represented by a sockaddr*.
SetNetmaskifaddrs_storage110 void SetNetmask(int family, size_t prefix_length) {
111 // ...and work out the netmask from the prefix length.
112 netmask.ss_family = family;
113 uint8_t* dst = SockaddrBytes(family, &netmask);
114 memset(dst, 0xff, prefix_length / 8);
115 if ((prefix_length % 8) != 0) {
116 dst[prefix_length/8] = (0xff << (8 - (prefix_length % 8)));
117 }
118 ifa.ifa_netmask = reinterpret_cast<sockaddr*>(&netmask);
119 }
120
SetPacketAttributesifaddrs_storage121 void SetPacketAttributes(int ifindex, unsigned short hatype, unsigned char halen) {
122 sockaddr_ll* sll = reinterpret_cast<sockaddr_ll*>(&addr);
123 sll->sll_ifindex = ifindex;
124 sll->sll_hatype = hatype;
125 sll->sll_halen = halen;
126 }
127
128 private:
CopyAddressifaddrs_storage129 sockaddr* CopyAddress(int family, const void* data, size_t byteCount, sockaddr_storage* ss) {
130 // Netlink gives us the address family in the header, and the
131 // sockaddr_in or sockaddr_in6 bytes as the payload. We need to
132 // stitch the two bits together into the sockaddr that's part of
133 // our portable interface.
134 ss->ss_family = family;
135 memcpy(SockaddrBytes(family, ss), data, byteCount);
136
137 // For IPv6 we might also have to set the scope id.
138 if (family == AF_INET6 && (IN6_IS_ADDR_LINKLOCAL(data) || IN6_IS_ADDR_MC_LINKLOCAL(data))) {
139 reinterpret_cast<sockaddr_in6*>(ss)->sin6_scope_id = interface_index;
140 }
141
142 return reinterpret_cast<sockaddr*>(ss);
143 }
144
145 // Returns a pointer to the first byte in the address data (which is
146 // stored in network byte order).
SockaddrBytesifaddrs_storage147 uint8_t* SockaddrBytes(int family, sockaddr_storage* ss) {
148 if (family == AF_INET) {
149 sockaddr_in* ss4 = reinterpret_cast<sockaddr_in*>(ss);
150 return reinterpret_cast<uint8_t*>(&ss4->sin_addr);
151 } else if (family == AF_INET6) {
152 sockaddr_in6* ss6 = reinterpret_cast<sockaddr_in6*>(ss);
153 return reinterpret_cast<uint8_t*>(&ss6->sin6_addr);
154 } else if (family == AF_PACKET) {
155 sockaddr_ll* sll = reinterpret_cast<sockaddr_ll*>(ss);
156 return reinterpret_cast<uint8_t*>(&sll->sll_addr);
157 }
158 return nullptr;
159 }
160 };
161
__getifaddrs_callback(void * context,nlmsghdr * hdr)162 static void __getifaddrs_callback(void* context, nlmsghdr* hdr) {
163 ifaddrs** out = reinterpret_cast<ifaddrs**>(context);
164
165 if (hdr->nlmsg_type == RTM_NEWLINK) {
166 ifinfomsg* ifi = reinterpret_cast<ifinfomsg*>(NLMSG_DATA(hdr));
167
168 // Create a new ifaddr entry, and set the interface index and flags.
169 ifaddrs_storage* new_addr = new ifaddrs_storage(out);
170 new_addr->interface_index = ifi->ifi_index;
171 new_addr->ifa.ifa_flags = ifi->ifi_flags;
172
173 // Go through the various bits of information and find the name.
174 rtattr* rta = IFLA_RTA(ifi);
175 size_t rta_len = IFLA_PAYLOAD(hdr);
176 while (RTA_OK(rta, rta_len)) {
177 if (rta->rta_type == IFLA_ADDRESS) {
178 if (RTA_PAYLOAD(rta) < sizeof(new_addr->addr)) {
179 new_addr->SetAddress(AF_PACKET, RTA_DATA(rta), RTA_PAYLOAD(rta));
180 new_addr->SetPacketAttributes(ifi->ifi_index, ifi->ifi_type, RTA_PAYLOAD(rta));
181 }
182 } else if (rta->rta_type == IFLA_BROADCAST) {
183 if (RTA_PAYLOAD(rta) < sizeof(new_addr->ifa_ifu)) {
184 new_addr->SetBroadcastAddress(AF_PACKET, RTA_DATA(rta), RTA_PAYLOAD(rta));
185 new_addr->SetPacketAttributes(ifi->ifi_index, ifi->ifi_type, RTA_PAYLOAD(rta));
186 }
187 } else if (rta->rta_type == IFLA_IFNAME) {
188 if (RTA_PAYLOAD(rta) < sizeof(new_addr->name)) {
189 memcpy(new_addr->name, RTA_DATA(rta), RTA_PAYLOAD(rta));
190 new_addr->ifa.ifa_name = new_addr->name;
191 }
192 }
193 rta = RTA_NEXT(rta, rta_len);
194 }
195 } else if (hdr->nlmsg_type == RTM_NEWADDR) {
196 ifaddrmsg* msg = reinterpret_cast<ifaddrmsg*>(NLMSG_DATA(hdr));
197
198 // We might already know about this interface from an RTM_NEWLINK message.
199 const ifaddrs_storage* known_addr = reinterpret_cast<const ifaddrs_storage*>(*out);
200 while (known_addr != nullptr && known_addr->interface_index != static_cast<int>(msg->ifa_index)) {
201 known_addr = reinterpret_cast<const ifaddrs_storage*>(known_addr->ifa.ifa_next);
202 }
203
204 // Create a new ifaddr entry, and set the interface index.
205 ifaddrs_storage* new_addr = new ifaddrs_storage(out);
206 new_addr->interface_index = static_cast<int>(msg->ifa_index);
207
208 // If this is a known interface, copy what we already know.
209 // If we don't know about this interface yet, we try to resolve the name and flags using ioctl
210 // calls during postprocessing.
211 if (known_addr != nullptr) {
212 strcpy(new_addr->name, known_addr->name);
213 new_addr->ifa.ifa_name = new_addr->name;
214 new_addr->ifa.ifa_flags = known_addr->ifa.ifa_flags;
215 }
216
217 // Go through the various bits of information and find the name, address
218 // and any broadcast/destination address.
219 rtattr* rta = IFA_RTA(msg);
220 size_t rta_len = IFA_PAYLOAD(hdr);
221 while (RTA_OK(rta, rta_len)) {
222 if (rta->rta_type == IFA_ADDRESS) {
223 if (msg->ifa_family == AF_INET || msg->ifa_family == AF_INET6) {
224 new_addr->SetAddress(msg->ifa_family, RTA_DATA(rta), RTA_PAYLOAD(rta));
225 new_addr->SetNetmask(msg->ifa_family, msg->ifa_prefixlen);
226 }
227 } else if (rta->rta_type == IFA_BROADCAST) {
228 if (msg->ifa_family == AF_INET) {
229 new_addr->SetBroadcastAddress(msg->ifa_family, RTA_DATA(rta), RTA_PAYLOAD(rta));
230 if (known_addr == nullptr) {
231 // We did not read the broadcast flag from an RTM_NEWLINK message.
232 // Ensure that it is set.
233 new_addr->ifa.ifa_flags |= IFF_BROADCAST;
234 }
235 }
236 } else if (rta->rta_type == IFA_LOCAL) {
237 if (msg->ifa_family == AF_INET || msg->ifa_family == AF_INET6) {
238 new_addr->SetLocalAddress(msg->ifa_family, RTA_DATA(rta), RTA_PAYLOAD(rta));
239 }
240 } else if (rta->rta_type == IFA_LABEL) {
241 if (RTA_PAYLOAD(rta) < sizeof(new_addr->name)) {
242 memcpy(new_addr->name, RTA_DATA(rta), RTA_PAYLOAD(rta));
243 new_addr->ifa.ifa_name = new_addr->name;
244 }
245 }
246 rta = RTA_NEXT(rta, rta_len);
247 }
248 }
249 }
250
resolve_or_remove_nameless_interfaces(ifaddrs ** list)251 static void resolve_or_remove_nameless_interfaces(ifaddrs** list) {
252 ifaddrs_storage* addr = reinterpret_cast<ifaddrs_storage*>(*list);
253 ifaddrs_storage* prev_addr = nullptr;
254 while (addr != nullptr) {
255 ifaddrs* next_addr = addr->ifa.ifa_next;
256
257 // Try resolving interfaces without a name first.
258 if (strlen(addr->name) == 0) {
259 if (if_indextoname(addr->interface_index, addr->name) != nullptr) {
260 addr->ifa.ifa_name = addr->name;
261 }
262 }
263
264 // If the interface could not be resolved, remove it.
265 if (strlen(addr->name) == 0) {
266 if (prev_addr == nullptr) {
267 *list = next_addr;
268 } else {
269 prev_addr->ifa.ifa_next = next_addr;
270 }
271 free(addr);
272 } else {
273 prev_addr = addr;
274 }
275
276 addr = reinterpret_cast<ifaddrs_storage*>(next_addr);
277 }
278 }
279
get_interface_flags_via_ioctl(ifaddrs ** list)280 static void get_interface_flags_via_ioctl(ifaddrs** list) {
281 ScopedFd s(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
282 if (s.get() == -1) {
283 async_safe_format_log(ANDROID_LOG_ERROR, "libc",
284 "socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC) failed in ifaddrs: %m");
285 return;
286 }
287
288 for (ifaddrs_storage* addr = reinterpret_cast<ifaddrs_storage*>(*list); addr != nullptr;
289 addr = reinterpret_cast<ifaddrs_storage*>(addr->ifa.ifa_next)) {
290 ifreq ifr = {};
291 strlcpy(ifr.ifr_name, addr->ifa.ifa_name, sizeof(ifr.ifr_name));
292 if (ioctl(s.get(), SIOCGIFFLAGS, &ifr) != -1) {
293 addr->ifa.ifa_flags = ifr.ifr_flags;
294 } else {
295 async_safe_format_log(ANDROID_LOG_ERROR, "libc",
296 "ioctl(SIOCGIFFLAGS) for \"%s\" failed in ifaddrs: %m",
297 addr->ifa.ifa_name);
298 }
299 }
300 }
301
getifaddrs(ifaddrs ** out)302 int getifaddrs(ifaddrs** out) {
303 // We construct the result directly into `out`, so terminate the list.
304 *out = nullptr;
305
306 // Open the netlink socket and ask for all the links and addresses.
307 NetlinkConnection nc;
308 // SELinux policy only allows RTM_GETLINK messages to be sent by system apps.
309 bool getlink_success = false;
310 if (getuid() < FIRST_APPLICATION_UID) {
311 getlink_success = nc.SendRequest(RTM_GETLINK) && nc.ReadResponses(__getifaddrs_callback, out);
312 }
313 bool getaddr_success =
314 nc.SendRequest(RTM_GETADDR) && nc.ReadResponses(__getifaddrs_callback, out);
315
316 if (!getaddr_success) {
317 freeifaddrs(*out);
318 // Ensure that callers crash if they forget to check for success.
319 *out = nullptr;
320 return -1;
321 }
322
323 if (!getlink_success) {
324 // If we weren't able to depend on GETLINK messages, it's possible some
325 // interfaces never got their name set. Resolve them using if_indextoname or remove them.
326 resolve_or_remove_nameless_interfaces(out);
327 // Similarly, without GETLINK messages, interfaces will not have their flags set.
328 // Resolve them using the SIOCGIFFLAGS ioctl call.
329 get_interface_flags_via_ioctl(out);
330 }
331
332 return 0;
333 }
334
freeifaddrs(ifaddrs * list)335 void freeifaddrs(ifaddrs* list) {
336 while (list != nullptr) {
337 ifaddrs* current = list;
338 list = list->ifa_next;
339 free(current);
340 }
341 }
342