blob: a67b4e1e543b65a764481d90f894ecee63b3c1af [file] [log] [blame]
Dmitry Shmidt2eab1f72012-07-26 16:08:02 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
Sasha Levitskiy329c3b42012-07-30 16:11:23 -07008 * http://www.apache.org/licenses/LICENSE-2.0
Dmitry Shmidt2eab1f72012-07-26 16:08:02 -07009 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Lorenzo Colitti37f2e372013-04-12 00:44:06 +090017#include <dirent.h>
Dan Albertaa1be2b2015-01-06 09:36:17 -080018#include <errno.h>
Elliott Hughes5f4938f2015-01-28 11:22:38 -080019#include <malloc.h>
Chenbo Feng7e974052018-02-28 22:57:21 -080020#include <net/if.h>
Luke Huangf7782042018-08-08 13:13:04 +080021#include <net/if_arp.h>
Erik Klineb218a872016-07-04 09:57:18 +090022#include <sys/socket.h>
Dmitry Shmidt2eab1f72012-07-26 16:08:02 -070023
Joel Scherpelz31e25992017-03-24 12:40:00 +090024#include <functional>
Luke Huangf7782042018-08-08 13:13:04 +080025
Dmitry Shmidt2eab1f72012-07-26 16:08:02 -070026#define LOG_TAG "InterfaceController"
Elliott Hughesbbd56262015-12-04 15:45:10 -080027#include <android-base/file.h>
Joel Scherpelzde937962017-06-01 13:20:21 +090028#include <android-base/properties.h>
Elliott Hughesbbd56262015-12-04 15:45:10 -080029#include <android-base/stringprintf.h>
Erik Kline38e51f12018-09-06 20:14:44 +090030#include <android-base/strings.h>
Luke Huangf7782042018-08-08 13:13:04 +080031#include <linux/if_ether.h>
Logan Chien3f461482018-04-23 14:31:32 +080032#include <log/log.h>
Erik Klinec296f092016-08-02 15:22:53 +090033#include <netutils/ifc.h>
Lorenzo Colitti70afde62013-03-04 17:58:40 +090034
Joel Scherpelzde937962017-06-01 13:20:21 +090035#include <android/net/INetd.h>
36#include <netdutils/Misc.h>
37#include <netdutils/Slice.h>
38#include <netdutils/Syscalls.h>
39
Dmitry Shmidt2eab1f72012-07-26 16:08:02 -070040#include "InterfaceController.h"
Sreeram Ramachandrana4811802014-04-10 12:10:24 -070041#include "RouteController.h"
Dmitry Shmidt2eab1f72012-07-26 16:08:02 -070042
Erik Klineb218a872016-07-04 09:57:18 +090043using android::base::ReadFileToString;
Joel Scherpelzde937962017-06-01 13:20:21 +090044using android::base::StringPrintf;
Erik Kline38e51f12018-09-06 20:14:44 +090045using android::base::Trim;
Dan Albert5407e142015-03-16 10:05:59 -070046using android::base::WriteStringToFile;
Joel Scherpelzde937962017-06-01 13:20:21 +090047using android::net::INetd;
Lorenzo Colitti7035f222017-02-13 18:29:00 +090048using android::net::RouteController;
Nathan Harold172f8e42018-04-19 13:10:19 -070049using android::netdutils::isOk;
Joel Scherpelzde937962017-06-01 13:20:21 +090050using android::netdutils::makeSlice;
51using android::netdutils::sSyscalls;
Erik Kline38e51f12018-09-06 20:14:44 +090052using android::netdutils::Status;
Joel Scherpelzde937962017-06-01 13:20:21 +090053using android::netdutils::statusFromErrno;
Erik Kline38e51f12018-09-06 20:14:44 +090054using android::netdutils::StatusOr;
Joel Scherpelzde937962017-06-01 13:20:21 +090055using android::netdutils::toString;
Erik Kline38e51f12018-09-06 20:14:44 +090056using android::netdutils::status::ok;
Dan Albert5407e142015-03-16 10:05:59 -070057
Luke Huangf7782042018-08-08 13:13:04 +080058#define RETURN_STATUS_IF_IFCERROR(exp) \
59 do { \
60 if ((exp) == -1) { \
61 return statusFromErrno(errno, "Failed to add addr"); \
62 } \
63 } while (0);
64
Erik Klinee1da4842015-05-12 15:56:06 +090065namespace {
66
Hugo Benichic4b3a0c2018-05-22 08:48:40 +090067const char ipv4_proc_path[] = "/proc/sys/net/ipv4/conf";
Lorenzo Colitti37f2e372013-04-12 00:44:06 +090068const char ipv6_proc_path[] = "/proc/sys/net/ipv6/conf";
69
Erik Kline145fd252015-05-12 15:58:49 +090070const char ipv4_neigh_conf_dir[] = "/proc/sys/net/ipv4/neigh";
Erik Kline145fd252015-05-12 15:58:49 +090071const char ipv6_neigh_conf_dir[] = "/proc/sys/net/ipv6/neigh";
72
Erik Klineb218a872016-07-04 09:57:18 +090073const char proc_net_path[] = "/proc/sys/net";
Dmitry Shmidt6d6c0e62013-06-11 16:18:06 -070074const char sys_net_path[] = "/sys/class/net";
75
Joel Scherpelz31e25992017-03-24 12:40:00 +090076constexpr int kRouteInfoMinPrefixLen = 48;
77
78// RFC 7421 prefix length.
79constexpr int kRouteInfoMaxPrefixLen = 64;
80
Joel Scherpelzde937962017-06-01 13:20:21 +090081// Property used to persist RFC 7217 stable secret. Protected by SELinux policy.
82const char kStableSecretProperty[] = "persist.netd.stable_secret";
83
84// RFC 7217 stable secret on linux is formatted as an IPv6 address.
85// This function uses 128 bits of high quality entropy to generate an
86// address for this purpose. This function should be not be called
87// frequently.
88StatusOr<std::string> randomIPv6Address() {
89 in6_addr addr = {};
90 const auto& sys = sSyscalls.get();
91 ASSIGN_OR_RETURN(auto fd, sys.open("/dev/random", O_RDONLY));
92 RETURN_IF_NOT_OK(sys.read(fd, makeSlice(addr)));
93 return toString(addr);
94}
95
Erik Klineb218a872016-07-04 09:57:18 +090096inline bool isNormalPathComponent(const char *component) {
97 return (strcmp(component, ".") != 0) &&
98 (strcmp(component, "..") != 0) &&
99 (strchr(component, '/') == nullptr);
100}
101
102inline bool isAddressFamilyPathComponent(const char *component) {
103 return strcmp(component, "ipv4") == 0 || strcmp(component, "ipv6") == 0;
104}
105
106inline bool isInterfaceName(const char *name) {
107 return isNormalPathComponent(name) &&
108 (strcmp(name, "default") != 0) &&
109 (strcmp(name, "all") != 0);
Erik Klinee1da4842015-05-12 15:56:06 +0900110}
111
112int writeValueToPath(
113 const char* dirname, const char* subdirname, const char* basename,
114 const char* value) {
115 std::string path(StringPrintf("%s/%s/%s", dirname, subdirname, basename));
Luke Huangf7782042018-08-08 13:13:04 +0800116 return WriteStringToFile(value, path) ? 0 : -EREMOTEIO;
Erik Klinee1da4842015-05-12 15:56:06 +0900117}
118
Joel Scherpelz31e25992017-03-24 12:40:00 +0900119// Run @fn on each interface as well as 'default' in the path @dirname.
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900120void forEachInterface(
121 const std::string& dirname,
122 const std::function<void(const std::string& path, const std::string& iface)>& fn) {
Joel Scherpelz31e25992017-03-24 12:40:00 +0900123 // Run on default, which controls the behavior of any interfaces that are created in the future.
124 fn(dirname, "default");
125 DIR* dir = opendir(dirname.c_str());
Erik Klinee1da4842015-05-12 15:56:06 +0900126 if (!dir) {
Joel Scherpelz31e25992017-03-24 12:40:00 +0900127 ALOGE("Can't list %s: %s", dirname.c_str(), strerror(errno));
Erik Klinee1da4842015-05-12 15:56:06 +0900128 return;
129 }
Joel Scherpelz31e25992017-03-24 12:40:00 +0900130 while (true) {
131 const dirent *ent = readdir(dir);
132 if (!ent) {
133 break;
134 }
135 if ((ent->d_type != DT_DIR) || !isInterfaceName(ent->d_name)) {
Erik Klinee1da4842015-05-12 15:56:06 +0900136 continue;
137 }
Joel Scherpelz31e25992017-03-24 12:40:00 +0900138 fn(dirname, ent->d_name);
Erik Klinee1da4842015-05-12 15:56:06 +0900139 }
140 closedir(dir);
141}
142
Joel Scherpelz31e25992017-03-24 12:40:00 +0900143void setOnAllInterfaces(const char* dirname, const char* basename, const char* value) {
144 auto fn = [basename, value](const std::string& path, const std::string& iface) {
145 writeValueToPath(path.c_str(), iface.c_str(), basename, value);
146 };
147 forEachInterface(dirname, fn);
148}
149
Erik Kline7adf8d72015-07-28 18:51:01 +0900150void setIPv6UseOutgoingInterfaceAddrsOnly(const char *value) {
151 setOnAllInterfaces(ipv6_proc_path, "use_oif_addrs_only", value);
152}
153
Erik Klineb218a872016-07-04 09:57:18 +0900154std::string getParameterPathname(
155 const char *family, const char *which, const char *interface, const char *parameter) {
156 if (!isAddressFamilyPathComponent(family)) {
157 errno = EAFNOSUPPORT;
158 return "";
159 } else if (!isNormalPathComponent(which) ||
160 !isInterfaceName(interface) ||
161 !isNormalPathComponent(parameter)) {
162 errno = EINVAL;
163 return "";
164 }
165
166 return StringPrintf("%s/%s/%s/%s/%s", proc_net_path, family, which, interface, parameter);
167}
168
Joel Scherpelz31e25992017-03-24 12:40:00 +0900169void setAcceptIPv6RIO(int min, int max) {
170 auto fn = [min, max](const std::string& prefix, const std::string& iface) {
171 int rv = writeValueToPath(prefix.c_str(), iface.c_str(), "accept_ra_rt_info_min_plen",
172 std::to_string(min).c_str());
173 if (rv != 0) {
174 // Only update max_plen if the write to min_plen succeeded. This ordering will prevent
175 // RIOs from being accepted unless both min and max are written successfully.
176 return;
177 }
178 writeValueToPath(prefix.c_str(), iface.c_str(), "accept_ra_rt_info_max_plen",
179 std::to_string(max).c_str());
180 };
181 forEachInterface(ipv6_proc_path, fn);
182}
183
Joel Scherpelzde937962017-06-01 13:20:21 +0900184// Ideally this function would return StatusOr<std::string>, however
185// there is no safe value for dflt that will always differ from the
186// stored property. Bugs code could conceivably end up persisting the
187// reserved value resulting in surprising behavior.
188std::string getProperty(const std::string& key, const std::string& dflt) {
189 return android::base::GetProperty(key, dflt);
190};
191
192Status setProperty(const std::string& key, const std::string& val) {
Lorenzo Colitti516764f2017-07-10 19:13:23 +0900193 // SetProperty does not dependably set errno to a meaningful value. Use our own error code so
194 // callers don't get confused.
Joel Scherpelzde937962017-06-01 13:20:21 +0900195 return android::base::SetProperty(key, val)
196 ? ok
Lorenzo Colitti516764f2017-07-10 19:13:23 +0900197 : statusFromErrno(EREMOTEIO, "SetProperty failed, see libc logs");
Joel Scherpelzde937962017-06-01 13:20:21 +0900198};
199
200
Erik Klinee1da4842015-05-12 15:56:06 +0900201} // namespace
202
Bernie Innocenti4debf3b2018-09-12 13:54:50 +0900203namespace android {
204namespace net {
Luke Huangf7782042018-08-08 13:13:04 +0800205std::mutex InterfaceController::mutex;
Bernie Innocenti4debf3b2018-09-12 13:54:50 +0900206
Joel Scherpelzde937962017-06-01 13:20:21 +0900207android::netdutils::Status InterfaceController::enableStablePrivacyAddresses(
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900208 const std::string& iface,
209 const GetPropertyFn& getProperty,
210 const SetPropertyFn& setProperty) {
Joel Scherpelzde937962017-06-01 13:20:21 +0900211 const auto& sys = sSyscalls.get();
212 const std::string procTarget = std::string(ipv6_proc_path) + "/" + iface + "/stable_secret";
213 auto procFd = sys.open(procTarget, O_CLOEXEC | O_WRONLY);
214
215 // Devices with old kernels (typically < 4.4) don't support
216 // RFC 7217 stable privacy addresses.
217 if (equalToErrno(procFd, ENOENT)) {
218 return statusFromErrno(EOPNOTSUPP,
219 "Failed to open stable_secret. Assuming unsupported kernel version");
220 }
221
222 // If stable_secret exists but we can't open it, something strange is going on.
223 RETURN_IF_NOT_OK(procFd);
224
225 const char kUninitialized[] = "uninitialized";
226 const auto oldSecret = getProperty(kStableSecretProperty, kUninitialized);
227 std::string secret = oldSecret;
228
229 // Generate a new secret if no persistent property existed.
230 if (oldSecret == kUninitialized) {
231 ASSIGN_OR_RETURN(secret, randomIPv6Address());
232 }
233
234 // Ask the OS to generate SLAAC addresses on iface using secret.
235 RETURN_IF_NOT_OK(sys.write(procFd.value(), makeSlice(secret)));
236
237 // Don't persist an existing secret.
238 if (oldSecret != kUninitialized) {
239 return ok;
240 }
241
242 return setProperty(kStableSecretProperty, secret);
243}
244
Erik Kline2c5aaa12016-06-08 13:24:45 +0900245void InterfaceController::initializeAll() {
246 // Initial IPv6 settings.
247 // By default, accept_ra is set to 1 (accept RAs unless forwarding is on) on all interfaces.
248 // This causes RAs to work or not work based on whether forwarding is on, and causes routes
249 // learned from RAs to go away when forwarding is turned on. Make this behaviour predictable
250 // by always setting accept_ra to 2.
251 setAcceptRA("2");
Lorenzo Colitti37f2e372013-04-12 00:44:06 +0900252
Joel Scherpelz31e25992017-03-24 12:40:00 +0900253 // Accept RIOs with prefix length in the closed interval [48, 64].
254 setAcceptIPv6RIO(kRouteInfoMinPrefixLen, kRouteInfoMaxPrefixLen);
255
Erik Kline2c5aaa12016-06-08 13:24:45 +0900256 setAcceptRARouteTable(-RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX);
Erik Kline59273ed2014-12-08 16:05:28 +0900257
Erik Kline2c5aaa12016-06-08 13:24:45 +0900258 // Enable optimistic DAD for IPv6 addresses on all interfaces.
259 setIPv6OptimisticMode("1");
Erik Kline145fd252015-05-12 15:58:49 +0900260
Erik Kline2c5aaa12016-06-08 13:24:45 +0900261 // Reduce the ARP/ND base reachable time from the default (30sec) to 15sec.
262 setBaseReachableTimeMs(15 * 1000);
Erik Kline7adf8d72015-07-28 18:51:01 +0900263
Erik Kline2c5aaa12016-06-08 13:24:45 +0900264 // When sending traffic via a given interface use only addresses configured
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900265 // on that interface as possible source addresses.
Erik Kline2c5aaa12016-06-08 13:24:45 +0900266 setIPv6UseOutgoingInterfaceAddrsOnly("1");
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900267
268 // Ensure that ICMP redirects are rejected globally on all interfaces.
269 disableIcmpRedirects();
Dmitry Shmidt2eab1f72012-07-26 16:08:02 -0700270}
Lorenzo Colitti70afde62013-03-04 17:58:40 +0900271
Lorenzo Colitti70afde62013-03-04 17:58:40 +0900272int InterfaceController::setEnableIPv6(const char *interface, const int on) {
Erik Klinee1da4842015-05-12 15:56:06 +0900273 if (!isIfaceName(interface)) {
Luke Huangf7782042018-08-08 13:13:04 +0800274 return -ENOENT;
Erik Klinee1da4842015-05-12 15:56:06 +0900275 }
276 // When disable_ipv6 changes from 1 to 0, the kernel starts autoconf.
277 // When disable_ipv6 changes from 0 to 1, the kernel clears all autoconf
278 // addresses and routes and disables IPv6 on the interface.
279 const char *disable_ipv6 = on ? "0" : "1";
280 return writeValueToPath(ipv6_proc_path, interface, "disable_ipv6", disable_ipv6);
Lorenzo Colitti70afde62013-03-04 17:58:40 +0900281}
282
Joel Scherpelzde937962017-06-01 13:20:21 +0900283// Changes to addrGenMode will not fully take effect until the next
284// time disable_ipv6 transitions from 1 to 0.
285Status InterfaceController::setIPv6AddrGenMode(const std::string& interface, int mode) {
286 if (!isIfaceName(interface)) {
287 return statusFromErrno(ENOENT, "invalid iface name: " + interface);
288 }
289
290 switch (mode) {
291 case INetd::IPV6_ADDR_GEN_MODE_EUI64:
Maciej Żenczykowski92424d52019-08-09 14:29:12 -0700292 // Ignore return value. If /proc/.../addr_gen_mode is
Joel Scherpelzde937962017-06-01 13:20:21 +0900293 // missing we're probably in EUI64 mode already.
Maciej Żenczykowski92424d52019-08-09 14:29:12 -0700294 writeValueToPath(ipv6_proc_path, interface.c_str(), "addr_gen_mode", "0");
Joel Scherpelzde937962017-06-01 13:20:21 +0900295 break;
296 case INetd::IPV6_ADDR_GEN_MODE_STABLE_PRIVACY: {
297 return enableStablePrivacyAddresses(interface, getProperty, setProperty);
298 }
299 case INetd::IPV6_ADDR_GEN_MODE_NONE:
300 case INetd::IPV6_ADDR_GEN_MODE_RANDOM:
301 default:
302 return statusFromErrno(EOPNOTSUPP, "unsupported addrGenMode");
303 }
304
305 return ok;
306}
307
Erik Kline2c5aaa12016-06-08 13:24:45 +0900308int InterfaceController::setAcceptIPv6Ra(const char *interface, const int on) {
309 if (!isIfaceName(interface)) {
310 errno = ENOENT;
311 return -1;
312 }
313 // Because forwarding can be enabled even when tethering is off, we always
314 // use mode "2" (accept RAs, even if forwarding is enabled).
315 const char *accept_ra = on ? "2" : "0";
316 return writeValueToPath(ipv6_proc_path, interface, "accept_ra", accept_ra);
317}
318
319int InterfaceController::setAcceptIPv6Dad(const char *interface, const int on) {
320 if (!isIfaceName(interface)) {
321 errno = ENOENT;
322 return -1;
323 }
324 const char *accept_dad = on ? "1" : "0";
325 return writeValueToPath(ipv6_proc_path, interface, "accept_dad", accept_dad);
326}
327
Erik Kline59d8c482016-08-09 15:28:42 +0900328int InterfaceController::setIPv6DadTransmits(const char *interface, const char *value) {
329 if (!isIfaceName(interface)) {
330 errno = ENOENT;
331 return -1;
332 }
333 return writeValueToPath(ipv6_proc_path, interface, "dad_transmits", value);
334}
335
Lorenzo Colitti70afde62013-03-04 17:58:40 +0900336int InterfaceController::setIPv6PrivacyExtensions(const char *interface, const int on) {
Erik Klinee1da4842015-05-12 15:56:06 +0900337 if (!isIfaceName(interface)) {
338 errno = ENOENT;
Luke Huangf7782042018-08-08 13:13:04 +0800339 return -errno;
Erik Klinee1da4842015-05-12 15:56:06 +0900340 }
341 // 0: disable IPv6 privacy addresses
Joel Scherpelzde937962017-06-01 13:20:21 +0900342 // 2: enable IPv6 privacy addresses and prefer them over non-privacy ones.
Erik Klinee1da4842015-05-12 15:56:06 +0900343 return writeValueToPath(ipv6_proc_path, interface, "use_tempaddr", on ? "2" : "0");
Lorenzo Colitti70afde62013-03-04 17:58:40 +0900344}
Lorenzo Colitti37f2e372013-04-12 00:44:06 +0900345
Sreeram Ramachandrana4811802014-04-10 12:10:24 -0700346void InterfaceController::setAcceptRA(const char *value) {
Erik Klinee1da4842015-05-12 15:56:06 +0900347 setOnAllInterfaces(ipv6_proc_path, "accept_ra", value);
Sreeram Ramachandrana4811802014-04-10 12:10:24 -0700348}
349
Sreeram Ramachandrana01d6ef2014-04-10 19:37:59 -0700350// |tableOrOffset| is interpreted as:
Sreeram Ramachandrana4811802014-04-10 12:10:24 -0700351// If == 0: default. Routes go into RT6_TABLE_MAIN.
352// If > 0: user set. Routes go into the specified table.
353// If < 0: automatic. The absolute value is intepreted as an offset and added to the interface
354// ID to get the table. If it's set to -1000, routes from interface ID 5 will go into
355// table 1005, etc.
Sreeram Ramachandrana01d6ef2014-04-10 19:37:59 -0700356void InterfaceController::setAcceptRARouteTable(int tableOrOffset) {
Erik Klinee1da4842015-05-12 15:56:06 +0900357 std::string value(StringPrintf("%d", tableOrOffset));
358 setOnAllInterfaces(ipv6_proc_path, "accept_ra_rt_table", value.c_str());
Lorenzo Colitti37f2e372013-04-12 00:44:06 +0900359}
Dmitry Shmidt6d6c0e62013-06-11 16:18:06 -0700360
Dmitry Shmidt6d6c0e62013-06-11 16:18:06 -0700361int InterfaceController::setMtu(const char *interface, const char *mtu)
362{
Erik Klinee1da4842015-05-12 15:56:06 +0900363 if (!isIfaceName(interface)) {
364 errno = ENOENT;
Luke Huangf7782042018-08-08 13:13:04 +0800365 return -errno;
Erik Klinee1da4842015-05-12 15:56:06 +0900366 }
367 return writeValueToPath(sys_net_path, interface, "mtu", mtu);
Dmitry Shmidt6d6c0e62013-06-11 16:18:06 -0700368}
Erik Kline59273ed2014-12-08 16:05:28 +0900369
Erik Klinec296f092016-08-02 15:22:53 +0900370int InterfaceController::addAddress(const char *interface,
371 const char *addrString, int prefixLength) {
372 return ifc_add_address(interface, addrString, prefixLength);
373}
374
375int InterfaceController::delAddress(const char *interface,
376 const char *addrString, int prefixLength) {
377 return ifc_del_address(interface, addrString, prefixLength);
378}
379
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900380int InterfaceController::disableIcmpRedirects() {
381 int rv = 0;
382 rv |= writeValueToPath(ipv4_proc_path, "all", "accept_redirects", "0");
383 rv |= writeValueToPath(ipv6_proc_path, "all", "accept_redirects", "0");
384 setOnAllInterfaces(ipv4_proc_path, "accept_redirects", "0");
385 setOnAllInterfaces(ipv6_proc_path, "accept_redirects", "0");
386 return rv;
387}
388
Erik Klineb218a872016-07-04 09:57:18 +0900389int InterfaceController::getParameter(
390 const char *family, const char *which, const char *interface, const char *parameter,
391 std::string *value) {
392 const std::string path(getParameterPathname(family, which, interface, parameter));
393 if (path.empty()) {
394 return -errno;
395 }
Erik Kline38e51f12018-09-06 20:14:44 +0900396 if (ReadFileToString(path, value)) {
397 *value = Trim(*value);
398 return 0;
399 }
400 return -errno;
Erik Klineb218a872016-07-04 09:57:18 +0900401}
402
403int InterfaceController::setParameter(
404 const char *family, const char *which, const char *interface, const char *parameter,
405 const char *value) {
406 const std::string path(getParameterPathname(family, which, interface, parameter));
407 if (path.empty()) {
408 return -errno;
409 }
410 return WriteStringToFile(value, path) ? 0 : -errno;
411}
412
Erik Kline145fd252015-05-12 15:58:49 +0900413void InterfaceController::setBaseReachableTimeMs(unsigned int millis) {
414 std::string value(StringPrintf("%u", millis));
415 setOnAllInterfaces(ipv4_neigh_conf_dir, "base_reachable_time_ms", value.c_str());
416 setOnAllInterfaces(ipv6_neigh_conf_dir, "base_reachable_time_ms", value.c_str());
417}
418
Erik Kline59273ed2014-12-08 16:05:28 +0900419void InterfaceController::setIPv6OptimisticMode(const char *value) {
Erik Klinee1da4842015-05-12 15:56:06 +0900420 setOnAllInterfaces(ipv6_proc_path, "optimistic_dad", value);
421 setOnAllInterfaces(ipv6_proc_path, "use_optimistic", value);
Erik Kline59273ed2014-12-08 16:05:28 +0900422}
Chenbo Feng7e974052018-02-28 22:57:21 -0800423
Nathan Harold172f8e42018-04-19 13:10:19 -0700424StatusOr<std::vector<std::string>> InterfaceController::getIfaceNames() {
425 std::vector<std::string> ifaceNames;
Chenbo Feng7e974052018-02-28 22:57:21 -0800426 DIR* d;
427 struct dirent* de;
428
429 if (!(d = opendir("/sys/class/net"))) {
430 return statusFromErrno(errno, "Cannot open iface directory");
431 }
432 while ((de = readdir(d))) {
Maciej Żenczykowskiee0f48d2019-04-16 13:00:53 -0700433 if ((de->d_type != DT_DIR) && (de->d_type != DT_LNK)) continue;
Chenbo Feng7e974052018-02-28 22:57:21 -0800434 if (de->d_name[0] == '.') continue;
Nathan Harold172f8e42018-04-19 13:10:19 -0700435 ifaceNames.push_back(std::string(de->d_name));
Chenbo Feng7e974052018-02-28 22:57:21 -0800436 }
437 closedir(d);
Nathan Harold172f8e42018-04-19 13:10:19 -0700438 return ifaceNames;
439}
440
441StatusOr<std::map<std::string, uint32_t>> InterfaceController::getIfaceList() {
442 std::map<std::string, uint32_t> ifacePairs;
443
444 ASSIGN_OR_RETURN(auto ifaceNames, getIfaceNames());
445
446 for (const auto& name : ifaceNames) {
447 uint32_t ifaceIndex = if_nametoindex(name.c_str());
448 if (ifaceIndex) {
449 ifacePairs.insert(std::pair<std::string, uint32_t>(name, ifaceIndex));
450 }
451 }
Chenbo Feng7e974052018-02-28 22:57:21 -0800452 return ifacePairs;
453}
Bernie Innocenti4debf3b2018-09-12 13:54:50 +0900454
Luke Huangf7782042018-08-08 13:13:04 +0800455namespace {
456
457std::string hwAddrToStr(unsigned char* hwaddr) {
458 return StringPrintf("%02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3],
459 hwaddr[4], hwaddr[5]);
460}
461
462int ipv4NetmaskToPrefixLength(in_addr_t mask) {
463 int prefixLength = 0;
464 uint32_t m = ntohl(mask);
465 while (m & (1 << 31)) {
466 prefixLength++;
467 m = m << 1;
468 }
469 return prefixLength;
470}
471
472std::string toStdString(const String16& s) {
473 return std::string(String8(s.string()));
474}
475
476} // namespace
477
478Status InterfaceController::setCfg(const InterfaceConfigurationParcel& cfg) {
479 const auto& sys = sSyscalls.get();
480 ASSIGN_OR_RETURN(auto fd, sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
481 struct ifreq ifr = {
482 .ifr_addr = {.sa_family = AF_INET}, // Clear the IPv4 address.
483 };
484 strlcpy(ifr.ifr_name, cfg.ifName.c_str(), IFNAMSIZ);
485
486 // Make sure that clear IPv4 address before set flag
487 // SIOCGIFFLAGS might override ifr and caused clear IPv4 addr ioctl error
488 RETURN_IF_NOT_OK(sys.ioctl(fd, SIOCSIFADDR, &ifr));
489
490 if (!cfg.flags.empty()) {
491 RETURN_IF_NOT_OK(sys.ioctl(fd, SIOCGIFFLAGS, &ifr));
492 uint16_t flags = ifr.ifr_flags;
493
494 for (const auto& flag : cfg.flags) {
495 if (flag == toStdString(INetd::IF_STATE_UP())) {
496 ifr.ifr_flags = ifr.ifr_flags | IFF_UP;
497 } else if (flag == toStdString(INetd::IF_STATE_DOWN())) {
498 ifr.ifr_flags = (ifr.ifr_flags & (~IFF_UP));
499 }
500 }
501
502 if (ifr.ifr_flags != flags) {
503 RETURN_IF_NOT_OK(sys.ioctl(fd, SIOCSIFFLAGS, &ifr));
504 }
505 }
506
507 RETURN_STATUS_IF_IFCERROR(
508 ifc_add_address(cfg.ifName.c_str(), cfg.ipv4Addr.c_str(), cfg.prefixLength));
509
510 return ok;
511}
512
513StatusOr<InterfaceConfigurationParcel> InterfaceController::getCfg(const std::string& ifName) {
514 struct in_addr addr = {};
515 int prefixLength = 0;
516 unsigned char hwaddr[ETH_ALEN] = {};
517 unsigned flags = 0;
518 InterfaceConfigurationParcel cfgResult;
519
520 const auto& sys = sSyscalls.get();
521 ASSIGN_OR_RETURN(auto fd, sys.socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0));
522
523 struct ifreq ifr = {};
524 strlcpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ);
525
526 if (isOk(sys.ioctl(fd, SIOCGIFADDR, &ifr))) {
527 addr.s_addr = ((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr.s_addr;
528 }
529
530 if (isOk(sys.ioctl(fd, SIOCGIFNETMASK, &ifr))) {
531 prefixLength =
532 ipv4NetmaskToPrefixLength(((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr.s_addr);
533 }
534
535 if (isOk(sys.ioctl(fd, SIOCGIFFLAGS, &ifr))) {
536 flags = ifr.ifr_flags;
537 }
538
539 // ETH_ALEN is for ARPHRD_ETHER, it is better to check the sa_family.
540 // However, we keep old design for the consistency.
541 if (isOk(sys.ioctl(fd, SIOCGIFHWADDR, &ifr))) {
542 memcpy((void*) hwaddr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
543 } else {
544 ALOGW("Failed to retrieve HW addr for %s (%s)", ifName.c_str(), strerror(errno));
545 }
546
547 cfgResult.ifName = ifName;
548 cfgResult.hwAddr = hwAddrToStr(hwaddr);
549 cfgResult.ipv4Addr = std::string(inet_ntoa(addr));
550 cfgResult.prefixLength = prefixLength;
551 cfgResult.flags.push_back(flags & IFF_UP ? toStdString(INetd::IF_STATE_UP())
552 : toStdString(INetd::IF_STATE_DOWN()));
553
554 if (flags & IFF_BROADCAST) cfgResult.flags.push_back(toStdString(INetd::IF_FLAG_BROADCAST()));
555 if (flags & IFF_LOOPBACK) cfgResult.flags.push_back(toStdString(INetd::IF_FLAG_LOOPBACK()));
556 if (flags & IFF_POINTOPOINT)
557 cfgResult.flags.push_back(toStdString(INetd::IF_FLAG_POINTOPOINT()));
558 if (flags & IFF_RUNNING) cfgResult.flags.push_back(toStdString(INetd::IF_FLAG_RUNNING()));
559 if (flags & IFF_MULTICAST) cfgResult.flags.push_back(toStdString(INetd::IF_FLAG_MULTICAST()));
560
561 return cfgResult;
562}
563
564int InterfaceController::clearAddrs(const std::string& ifName) {
565 return ifc_clear_addresses(ifName.c_str());
566}
567
Bernie Innocenti4debf3b2018-09-12 13:54:50 +0900568} // namespace net
569} // namespace android