blob: a1e2ea4e71d47f610e03c8c40e9264fad90ac204 [file] [log] [blame]
San Mehat9d10b342010-01-18 09:51:02 -08001/*
2 * Copyright (C) 2008 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 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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
San Mehat9d10b342010-01-18 09:51:02 -080017#include <errno.h>
San Mehat18737842010-01-21 09:22:43 -080018#include <fcntl.h>
Lorenzo Colittia93126d2017-08-24 13:28:19 +090019#include <inttypes.h>
Lorenzo Colittic2841282015-11-25 22:13:57 +090020#include <netdb.h>
Luke Huang40962442019-02-26 11:46:10 +080021#include <spawn.h>
Olivier Baillyff2c0d82010-11-17 11:45:07 -080022#include <string.h>
San Mehat18737842010-01-21 09:22:43 -080023
San Mehat9d10b342010-01-18 09:51:02 -080024#include <sys/socket.h>
25#include <sys/stat.h>
San Mehat18737842010-01-21 09:22:43 -080026#include <sys/types.h>
27#include <sys/wait.h>
28
San Mehat9d10b342010-01-18 09:51:02 -080029#include <netinet/in.h>
30#include <arpa/inet.h>
31
Erik Kline5f0358b2018-02-16 15:08:09 +090032#include <array>
33#include <cstdlib>
waynema71a0b592018-11-21 13:31:34 +080034#include <regex>
Erik Kline5f0358b2018-02-16 15:08:09 +090035#include <string>
36#include <vector>
37
San Mehat9d10b342010-01-18 09:51:02 -080038#define LOG_TAG "TetherController"
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -070039#include <android-base/scopeguard.h>
Lorenzo Colittia93126d2017-08-24 13:28:19 +090040#include <android-base/stringprintf.h>
George Burgess IVe3dc1312019-02-28 11:27:04 -080041#include <android-base/strings.h>
42#include <android-base/unique_fd.h>
Kazuhiro Ondo6b858eb2011-06-24 20:31:03 -050043#include <cutils/properties.h>
Logan Chien3f461482018-04-23 14:31:32 +080044#include <log/log.h>
Hungming Chen1da90082020-02-14 20:24:16 +080045#include <net/if.h>
Lorenzo Colitti52db3912020-02-17 23:59:45 +090046#include <netdutils/DumpWriter.h>
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090047#include <netdutils/StatusOr.h>
San Mehat9d10b342010-01-18 09:51:02 -080048
Erik Klineb31fd692018-06-06 20:50:11 +090049#include "Controllers.h"
Lorenzo Colitti667c4772014-08-26 14:13:07 -070050#include "Fwmark.h"
Erik Kline1d065ba2016-06-08 13:24:45 +090051#include "InterfaceController.h"
Mike Yuf0e019f2019-03-13 14:43:39 +080052#include "NetdConstants.h"
Lorenzo Colittie20a5262017-05-09 18:30:44 +090053#include "NetworkController.h"
Hungming Chen1da90082020-02-14 20:24:16 +080054#include "OffloadUtils.h"
Mike Yuf0e019f2019-03-13 14:43:39 +080055#include "Permission.h"
San Mehat9d10b342010-01-18 09:51:02 -080056#include "TetherController.h"
57
Bernie Innocenti4debf3b2018-09-12 13:54:50 +090058namespace android {
59namespace net {
60
Lorenzo Colittie801d3c2020-02-18 00:00:35 +090061using android::base::Error;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090062using android::base::Join;
George Burgess IVe3dc1312019-02-28 11:27:04 -080063using android::base::Pipe;
Lorenzo Colittie801d3c2020-02-18 00:00:35 +090064using android::base::Result;
65using android::base::StringAppendF;
Erik Klineb31fd692018-06-06 20:50:11 +090066using android::base::StringPrintf;
George Burgess IVe3dc1312019-02-28 11:27:04 -080067using android::base::unique_fd;
Lorenzo Colitti52db3912020-02-17 23:59:45 +090068using android::netdutils::DumpWriter;
69using android::netdutils::ScopedIndent;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090070using android::netdutils::statusFromErrno;
Erik Klineb31fd692018-06-06 20:50:11 +090071using android::netdutils::StatusOr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090072
Lorenzo Colitti799625c2015-02-25 12:52:00 +090073namespace {
74
Erik Kline1d065ba2016-06-08 13:24:45 +090075const char BP_TOOLS_MODE[] = "bp-tools";
76const char IPV4_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv4/ip_forward";
77const char IPV6_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv6/conf/all/forwarding";
78const char SEPARATOR[] = "|";
Erik Kline93f9b222017-10-22 21:24:58 +090079constexpr const char kTcpBeLiberal[] = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
Lorenzo Colitti799625c2015-02-25 12:52:00 +090080
Erik Kline5f0358b2018-02-16 15:08:09 +090081// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
82constexpr const char kDnsmasqUsername[] = "dns_tether";
83
Lorenzo Colitti799625c2015-02-25 12:52:00 +090084bool writeToFile(const char* filename, const char* value) {
Nick Kralevichb95c60c2016-11-19 09:09:16 -080085 int fd = open(filename, O_WRONLY | O_CLOEXEC);
Nicolas Geoffrayafd40372015-03-16 11:58:06 +000086 if (fd < 0) {
87 ALOGE("Failed to open %s: %s", filename, strerror(errno));
88 return false;
89 }
90
91 const ssize_t len = strlen(value);
92 if (write(fd, value, len) != len) {
93 ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
94 close(fd);
95 return false;
96 }
97 close(fd);
98 return true;
Lorenzo Colitti799625c2015-02-25 12:52:00 +090099}
100
Erik Kline93f9b222017-10-22 21:24:58 +0900101// TODO: Consider altering TCP and UDP timeouts as well.
102void configureForTethering(bool enabled) {
103 writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
104}
105
Erik Kline1d065ba2016-06-08 13:24:45 +0900106bool configureForIPv6Router(const char *interface) {
107 return (InterfaceController::setEnableIPv6(interface, 0) == 0)
108 && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
Erik Kline6cddf512016-08-09 15:28:42 +0900109 && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
110 && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
Erik Kline1d065ba2016-06-08 13:24:45 +0900111 && (InterfaceController::setEnableIPv6(interface, 1) == 0);
112}
113
114void configureForIPv6Client(const char *interface) {
115 InterfaceController::setAcceptIPv6Ra(interface, 1);
Erik Kline6cddf512016-08-09 15:28:42 +0900116 InterfaceController::setAcceptIPv6Dad(interface, 1);
117 InterfaceController::setIPv6DadTransmits(interface, "1");
Erik Kline1d065ba2016-06-08 13:24:45 +0900118 InterfaceController::setEnableIPv6(interface, 0);
119}
120
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900121bool inBpToolsMode() {
122 // In BP tools mode, do not disable IP forwarding
123 char bootmode[PROPERTY_VALUE_MAX] = {0};
124 property_get("ro.bootmode", bootmode, "unknown");
125 return !strcmp(BP_TOOLS_MODE, bootmode);
126}
127
128} // namespace
129
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900130auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
131
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900132const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
133 "*filter\n"
134 "-nvx -L %s\n"
135 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
136
Erik Kline15079dd2018-05-18 23:10:56 +0900137int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
138 if (cmd.empty()) return 0;
139
Erik Klineb31fd692018-06-06 20:50:11 +0900140 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900141 // Send the trailing \0 as well.
142 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900143 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900144 errno = EREMOTEIO;
145 return -1;
146 }
147 return 0;
148}
149
150void TetherController::DnsmasqState::clear() {
151 update_ifaces_cmd.clear();
152 update_dns_cmd.clear();
153}
154
155int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
156 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
157}
158
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700159TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900160 if (inBpToolsMode()) {
161 enableForwarding(BP_TOOLS_MODE);
162 } else {
163 setIpFwdEnabled();
164 }
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900165
166 // Open BPF maps, ignoring errors because the device might not support BPF offload.
167 int fd = getTetherIngressMapFd();
168 if (fd != -1) {
169 mBpfIngressMap.reset(fd);
170 }
171 fd = getTetherStatsMapFd();
172 if (fd != -1) {
173 mBpfStatsMap.reset(fd);
174 }
San Mehat9d10b342010-01-18 09:51:02 -0800175}
176
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900177bool TetherController::setIpFwdEnabled() {
178 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900179 bool disable = mForwardingRequests.empty();
180 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900181 ALOGD("Setting IP forward enable = %s", value);
182 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
183 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900184 if (disable) {
185 // Turning off the forwarding sysconf in the kernel has the side effect
186 // of turning on ICMP redirect, which is a security hazard.
187 // Turn ICMP redirect back off immediately.
188 int rv = InterfaceController::disableIcmpRedirects();
189 success &= (rv == 0);
190 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900191 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800192}
193
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900194bool TetherController::enableForwarding(const char* requester) {
195 // Don't return an error if this requester already requested forwarding. Only return errors for
196 // things that the caller caller needs to care about, such as "couldn't write to the file to
197 // enable forwarding".
198 mForwardingRequests.insert(requester);
199 return setIpFwdEnabled();
200}
San Mehat9d10b342010-01-18 09:51:02 -0800201
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900202bool TetherController::disableForwarding(const char* requester) {
203 mForwardingRequests.erase(requester);
204 return setIpFwdEnabled();
205}
San Mehat9d10b342010-01-18 09:51:02 -0800206
Luke Huang728cf4c2019-03-14 19:43:02 +0800207const std::set<std::string>& TetherController::getIpfwdRequesterList() const {
208 return mForwardingRequests;
San Mehat9d10b342010-01-18 09:51:02 -0800209}
210
Luke Huang91bd3e12019-08-20 11:33:52 +0800211int TetherController::startTethering(bool usingLegacyDnsProxy, int num_addrs, char** dhcp_ranges) {
212 if (!usingLegacyDnsProxy && num_addrs == 0) {
213 // Both DHCP and DnsProxy are disabled, we don't need to start dnsmasq
214 configureForTethering(true);
215 mIsTetheringStarted = true;
216 return 0;
217 }
218
219 if (mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000220 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800221 errno = EBUSY;
Luke Huangb5733d72018-08-21 17:17:19 +0800222 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800223 }
224
Steve Block7b984e32011-12-20 16:22:42 +0000225 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800226
George Burgess IVe3dc1312019-02-28 11:27:04 -0800227 unique_fd pipeRead, pipeWrite;
228 if (!Pipe(&pipeRead, &pipeWrite, O_CLOEXEC)) {
Luke Huangb5733d72018-08-21 17:17:19 +0800229 int res = errno;
Luke Huang94c43a12019-02-14 19:51:38 +0800230 ALOGE("pipe2() failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800231 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800232 }
233
Luke Huang94c43a12019-02-14 19:51:38 +0800234 // Set parameters
235 Fwmark fwmark;
236 fwmark.netId = NetworkController::LOCAL_NET_ID;
237 fwmark.explicitlySelected = true;
238 fwmark.protectedFromVpn = true;
239 fwmark.permission = PERMISSION_SYSTEM;
240 char markStr[UINT32_HEX_STRLEN];
241 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800242
Luke Huang94c43a12019-02-14 19:51:38 +0800243 std::vector<const std::string> argVector = {
Erik Kline5f0358b2018-02-16 15:08:09 +0900244 "/system/bin/dnsmasq",
245 "--keep-in-foreground",
246 "--no-resolv",
247 "--no-poll",
248 "--dhcp-authoritative",
249 // TODO: pipe through metered status from ConnService
250 "--dhcp-option-force=43,ANDROID_METERED",
251 "--pid-file",
Luke Huang94c43a12019-02-14 19:51:38 +0800252 "--listen-mark",
253 markStr,
254 "--user",
255 kDnsmasqUsername,
256 };
San Mehat9d10b342010-01-18 09:51:02 -0800257
Luke Huang91bd3e12019-08-20 11:33:52 +0800258 if (!usingLegacyDnsProxy) {
259 argVector.push_back("--port=0");
260 }
261
262 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is passed.
Luke Huang94c43a12019-02-14 19:51:38 +0800263 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
264 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
265 dhcp_ranges[addrIndex + 1]));
San Mehat9d10b342010-01-18 09:51:02 -0800266 }
267
George Burgess IVe3dc1312019-02-28 11:27:04 -0800268 std::vector<char*> args(argVector.size() + 1);
Luke Huang94c43a12019-02-14 19:51:38 +0800269 for (unsigned i = 0; i < argVector.size(); i++) {
270 args[i] = (char*)argVector[i].c_str();
271 }
272
273 /*
274 * TODO: Create a monitoring thread to handle and restart
275 * the daemon if it exits prematurely
276 */
Luke Huang40962442019-02-26 11:46:10 +0800277
278 // Note that don't modify any memory between vfork and execv.
279 // Changing state of file descriptors would be fine. See posix_spawn_file_actions_add*
280 // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
281 // duplicated fd.
282 posix_spawn_file_actions_t fa;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700283 int res = posix_spawn_file_actions_init(&fa);
Luke Huang40962442019-02-26 11:46:10 +0800284 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700285 ALOGE("posix_spawn_file_actions_init failed (%s)", strerror(res));
286 return -res;
287 }
288 const android::base::ScopeGuard faGuard = [&] { posix_spawn_file_actions_destroy(&fa); };
289 res = posix_spawn_file_actions_adddup2(&fa, pipeRead.get(), STDIN_FILENO);
290 if (res) {
291 ALOGE("posix_spawn_file_actions_adddup2 failed (%s)", strerror(res));
Luke Huang94c43a12019-02-14 19:51:38 +0800292 return -res;
293 }
294
Luke Huang40962442019-02-26 11:46:10 +0800295 posix_spawnattr_t attr;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700296 res = posix_spawnattr_init(&attr);
Luke Huang40962442019-02-26 11:46:10 +0800297 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700298 ALOGE("posix_spawnattr_init failed (%s)", strerror(res));
299 return -res;
300 }
301 const android::base::ScopeGuard attrGuard = [&] { posix_spawnattr_destroy(&attr); };
302 res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK);
303 if (res) {
304 ALOGE("posix_spawnattr_setflags failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800305 return -res;
306 }
307
308 pid_t pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800309 res = posix_spawn(&pid, args[0], &fa, &attr, &args[0], nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800310 if (res) {
311 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800312 return -res;
313 }
Luke Huang94c43a12019-02-14 19:51:38 +0800314 mDaemonPid = pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800315 mDaemonFd = pipeWrite.release();
Luke Huang94c43a12019-02-14 19:51:38 +0800316 configureForTethering(true);
Luke Huang91bd3e12019-08-20 11:33:52 +0800317 mIsTetheringStarted = true;
Luke Huang94c43a12019-02-14 19:51:38 +0800318 applyDnsInterfaces();
319 ALOGD("Tethering services running");
320
San Mehat9d10b342010-01-18 09:51:02 -0800321 return 0;
322}
323
Luke Huangb5733d72018-08-21 17:17:19 +0800324std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
325 std::vector<char*> addrsCstrVec{};
326 addrsCstrVec.reserve(addrs.size());
327 for (const auto& addr : addrs) {
328 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
329 }
330 return addrsCstrVec;
331}
332
Luke Huang91bd3e12019-08-20 11:33:52 +0800333int TetherController::startTethering(bool usingLegacyDnsProxy,
334 const std::vector<std::string>& dhcpRanges) {
Luke Huangb5733d72018-08-21 17:17:19 +0800335 struct in_addr v4_addr;
336 for (const auto& dhcpRange : dhcpRanges) {
337 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
338 return -EINVAL;
339 }
340 }
341 auto dhcp_ranges = toCstrVec(dhcpRanges);
Luke Huang91bd3e12019-08-20 11:33:52 +0800342 return startTethering(usingLegacyDnsProxy, dhcp_ranges.size(), dhcp_ranges.data());
Luke Huangb5733d72018-08-21 17:17:19 +0800343}
344
San Mehat9d10b342010-01-18 09:51:02 -0800345int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900346 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800347
Luke Huang91bd3e12019-08-20 11:33:52 +0800348 if (!mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000349 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800350 return 0;
351 }
352
Luke Huang91bd3e12019-08-20 11:33:52 +0800353 mIsTetheringStarted = false;
354 // dnsmasq is not started
355 if (mDaemonPid == 0) {
356 return 0;
357 }
358
Steve Block7b984e32011-12-20 16:22:42 +0000359 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800360
361 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700362 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800363 mDaemonPid = 0;
364 close(mDaemonFd);
365 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900366 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000367 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800368 return 0;
369}
Matthew Xie19944102012-07-12 16:42:07 -0700370
San Mehat9d10b342010-01-18 09:51:02 -0800371bool TetherController::isTetheringStarted() {
Luke Huang91bd3e12019-08-20 11:33:52 +0800372 return mIsTetheringStarted;
San Mehat9d10b342010-01-18 09:51:02 -0800373}
374
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900375// dnsmasq can't parse commands larger than this due to the fixed-size buffer
376// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
377// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900378const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800379
Luke Huang8dc1cac2019-03-30 16:12:31 +0800380// TODO: Remove overload function and update this after NDC migration.
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700381int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700382 Fwmark fwmark;
383 fwmark.netId = netId;
384 fwmark.explicitlySelected = true;
385 fwmark.protectedFromVpn = true;
386 fwmark.permission = PERMISSION_SYSTEM;
387
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900388 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800389
Erik Kline1d065ba2016-06-08 13:24:45 +0900390 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900391 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700392 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800393
Lorenzo Colittic2841282015-11-25 22:13:57 +0900394 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700395 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900396 freeaddrinfo(res);
397 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000398 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900399 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900400 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800401 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800402 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800403
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900404 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
405 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800406 break;
407 }
408
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900409 daemonCmd += SEPARATOR;
410 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900411 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800412 }
413
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700414 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900415 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800416 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900417 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900418 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900419 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800420 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800421 }
422 }
423 return 0;
424}
425
Luke Huangb5733d72018-08-21 17:17:19 +0800426int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
Luke Huangb5733d72018-08-21 17:17:19 +0800427 auto dnsServers = toCstrVec(servers);
428 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
429}
430
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700431unsigned TetherController::getDnsNetId() {
432 return mDnsNetId;
433}
434
Erik Kline1d065ba2016-06-08 13:24:45 +0900435const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800436 return mDnsForwarders;
437}
438
Erik Kline1d065ba2016-06-08 13:24:45 +0900439bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900440 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800441 bool haveInterfaces = false;
442
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900443 for (const auto& ifname : mInterfaces) {
444 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
445 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800446 break;
447 }
448
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900449 daemonCmd += SEPARATOR;
450 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800451 haveInterfaces = true;
452 }
453
Erik Kline15079dd2018-05-18 23:10:56 +0900454 if (!haveInterfaces) {
455 mDnsmasqState.update_ifaces_cmd.clear();
456 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900457 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900458 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800459 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900460 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800461}
462
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800463int TetherController::tetherInterface(const char *interface) {
464 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700465 if (!isIfaceName(interface)) {
466 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800467 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700468 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800469
Erik Kline1d065ba2016-06-08 13:24:45 +0900470 if (!configureForIPv6Router(interface)) {
471 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800472 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900473 }
474 mInterfaces.push_back(interface);
475
476 if (!applyDnsInterfaces()) {
477 mInterfaces.pop_back();
478 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800479 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800480 } else {
481 return 0;
482 }
483}
484
San Mehat9d10b342010-01-18 09:51:02 -0800485int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800486 ALOGD("untetherInterface(%s)", interface);
487
Erik Kline1d065ba2016-06-08 13:24:45 +0900488 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
489 if (!strcmp(interface, it->c_str())) {
490 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800491
Erik Kline1d065ba2016-06-08 13:24:45 +0900492 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800493 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800494 }
495 }
496 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800497 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800498}
499
Erik Kline1d065ba2016-06-08 13:24:45 +0900500const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800501 return mInterfaces;
502}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900503
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900504int TetherController::setupIptablesHooks() {
505 int res;
506 res = setDefaults();
507 if (res < 0) {
508 return res;
509 }
510
511 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
512 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
513 // This is no longer optional and tethering will fail to start if it fails.
514 std::string mssRewriteCommand = StringPrintf(
515 "*mangle\n"
516 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
517 "COMMIT\n", LOCAL_MANGLE_FORWARD);
518
519 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
520 std::string defaultCommands = StringPrintf(
521 "*filter\n"
522 ":%s -\n"
523 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
524
525 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
526 if (res < 0) {
527 return res;
528 }
529
530 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
531 if (res < 0) {
532 return res;
533 }
534
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900535 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900536
537 return 0;
538}
539
540int TetherController::setDefaults() {
541 std::string v4Cmd = StringPrintf(
542 "*filter\n"
543 ":%s -\n"
544 "-A %s -j DROP\n"
545 "COMMIT\n"
546 "*nat\n"
547 ":%s -\n"
548 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
549
550 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900551 "*filter\n"
552 ":%s -\n"
553 "COMMIT\n"
554 "*raw\n"
555 ":%s -\n"
556 "COMMIT\n",
557 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900558
559 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
560 if (res < 0) {
561 return res;
562 }
563
564 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
565 if (res < 0) {
566 return res;
567 }
568
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900569 return 0;
570}
571
572int TetherController::enableNat(const char* intIface, const char* extIface) {
573 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
574
575 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900576 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900577 }
578
579 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
580 if (!strcmp(intIface, extIface)) {
581 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900582 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900583 }
584
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900585 if (isForwardingPairEnabled(intIface, extIface)) {
586 return 0;
587 }
588
589 // add this if we are the first enabled nat for this upstream
590 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900591 std::vector<std::string> v4Cmds = {
592 "*nat",
593 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
594 "COMMIT\n"
595 };
596
Luke Huangae038f82018-11-05 11:17:31 +0900597 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
598 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900599 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900600 if (!isAnyForwardingPairEnabled()) {
601 // unwind what's been done, but don't care about success - what more could we do?
602 setDefaults();
603 }
Luke Huang19b49c52018-10-22 12:12:05 +0900604 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900605 }
606 }
607
608 if (setForwardRules(true, intIface, extIface) != 0) {
609 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900610 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900611 setDefaults();
612 }
Luke Huang19b49c52018-10-22 12:12:05 +0900613 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900614 }
615
Hungming Chen1da90082020-02-14 20:24:16 +0800616 maybeStartBpf(extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900617 return 0;
618}
619
Luke Huangae038f82018-11-05 11:17:31 +0900620int TetherController::setTetherGlobalAlertRule() {
621 // Only add this if we are the first enabled nat
622 if (isAnyForwardingPairEnabled()) {
623 return 0;
624 }
625 const std::string cmds =
626 "*filter\n" +
627 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
628 "COMMIT\n";
629
630 return iptablesRestoreFunction(V4V6, cmds, nullptr);
631}
632
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900633int TetherController::setupIPv6CountersChain() {
634 // Only add this if we are the first enabled nat
635 if (isAnyForwardingPairEnabled()) {
636 return 0;
637 }
638
639 /*
640 * IPv6 tethering doesn't need the state-based conntrack rules, so
641 * it unconditionally jumps to the tether counters chain all the time.
642 */
Luke Huangae038f82018-11-05 11:17:31 +0900643 const std::string v6Cmds =
644 "*filter\n" +
645 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900646
Luke Huangae038f82018-11-05 11:17:31 +0900647 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900648}
649
650// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
651TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
652 const std::string& intIface, const std::string& extIface) {
653 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
654 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
655 if (it->second.iface == intIface) {
656 return &(it->second);
657 }
658 }
659 return nullptr;
660}
661
662void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
663 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
664 if (existingEntry != nullptr) {
665 existingEntry->active = true;
666 return;
667 }
668
669 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
670 .iface = intIface,
671 .active = true
672 }));
673}
674
675void TetherController::markForwardingPairDisabled(
676 const std::string& intIface, const std::string& extIface) {
677 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
678 if (existingEntry == nullptr) {
679 return;
680 }
681
682 existingEntry->active = false;
683}
684
685bool TetherController::isForwardingPairEnabled(
686 const std::string& intIface, const std::string& extIface) {
687 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
688 return existingEntry != nullptr && existingEntry->active;
689}
690
691bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
692 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
693 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
694 if (it->second.active) {
695 return true;
696 }
697 }
698 return false;
699}
700
701bool TetherController::isAnyForwardingPairEnabled() {
702 for (auto& it : mFwdIfaces) {
703 if (it.second.active) {
704 return true;
705 }
706 }
707 return false;
708}
709
710bool TetherController::tetherCountingRuleExists(
711 const std::string& iface1, const std::string& iface2) {
712 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
713 // is in the map regardless of its active status. Rules are added both ways so we check with
714 // the 2 combinations.
715 return findForwardingDownstream(iface1, iface2) != nullptr
716 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900717}
718
719/* static */
720std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
721 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
722}
723
724int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
725 const char *op = add ? "-A" : "-D";
726
727 std::string rpfilterCmd = StringPrintf(
728 "*raw\n"
729 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
730 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
731 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900732 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900733 }
734
735 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900736 "*raw",
737 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
738 LOCAL_RAW_PREROUTING, intIface),
739 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
740 LOCAL_RAW_PREROUTING, intIface),
741 "COMMIT",
742 "*filter",
743 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
744 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
745 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
746 intIface, extIface),
747 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
748 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900749 };
750
751 std::vector<std::string> v6 = {
752 "*filter",
753 };
754
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900755 // We only ever add tethering quota rules so that they stick.
756 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900757 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900758 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900759 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900760 v6.push_back(makeTetherCountingRule(extIface, intIface));
761 }
762
763 // Always make sure the drop rule is at the end.
764 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900765 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900766 if (add) {
767 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
768 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
769 }
770
771 v4.push_back("COMMIT\n");
772 v6.push_back("COMMIT\n");
773
774 // We only add IPv6 rules here, never remove them.
775 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
776 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
777 // unwind what's been done, but don't care about success - what more could we do?
778 if (add) {
779 setForwardRules(false, intIface, extIface);
780 }
Luke Huang19b49c52018-10-22 12:12:05 +0900781 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900782 }
783
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900784 if (add) {
785 addForwardingPair(intIface, extIface);
786 } else {
787 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900788 }
789
790 return 0;
791}
792
793int TetherController::disableNat(const char* intIface, const char* extIface) {
794 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900795 errno = ENODEV;
796 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900797 }
798
799 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900800 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900801 setDefaults();
802 }
Hungming Chen1da90082020-02-14 20:24:16 +0800803
804 maybeStopBpf(extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900805 return 0;
806}
807
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900808Result<void> TetherController::addDownstreamIpv6Rule(int intIfaceIndex, int extIfaceIndex,
809 const std::vector<uint8_t>& ipAddress,
810 const std::vector<uint8_t>& srcL2Address,
811 const std::vector<uint8_t>& dstL2Address) {
812 ethhdr hdr = {
813 .h_proto = htons(ETH_P_IPV6),
814 };
815 if (ipAddress.size() != sizeof(in6_addr)) {
816 return Error(EINVAL) << "Invalid IP address length " << ipAddress.size();
817 }
818 if (srcL2Address.size() != sizeof(hdr.h_source)) {
819 return Error(EINVAL) << "Invalid L2 src address length " << srcL2Address.size();
820 }
821 if (dstL2Address.size() != sizeof(hdr.h_dest)) {
822 return Error(EINVAL) << "Invalid L2 dst address length " << dstL2Address.size();
823 }
824 memcpy(&hdr.h_dest, dstL2Address.data(), sizeof(hdr.h_dest));
825 memcpy(&hdr.h_source, srcL2Address.data(), sizeof(hdr.h_source));
826
827 TetherIngressKey key = {
828 .iif = static_cast<uint32_t>(extIfaceIndex),
829 .neigh6 = *(const in6_addr*)ipAddress.data(),
830 };
831
832 TetherIngressValue value = {
833 static_cast<uint32_t>(intIfaceIndex),
834 hdr,
835 };
836
837 return mBpfIngressMap.writeValue(key, value, BPF_ANY);
838}
839
840Result<void> TetherController::removeDownstreamIpv6Rule(int extIfaceIndex,
841 const std::vector<uint8_t>& ipAddress) {
842 if (ipAddress.size() != sizeof(in6_addr)) {
843 return Error(EINVAL) << "Invalid IP address length " << ipAddress.size();
844 }
845
846 TetherIngressKey key = {
847 .iif = static_cast<uint32_t>(extIfaceIndex),
848 .neigh6 = *(const in6_addr*)ipAddress.data(),
849 };
850
851 Result<void> ret = mBpfIngressMap.deleteValue(key);
852
853 // Silently return success if the rule did not exist.
854 if (!ret.ok() && ret.error().code() == ENOENT) return {};
855
856 return ret;
857}
858
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900859void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
860 for (TetherStats& existing : statsList) {
861 if (existing.addStatsIfMatch(stats)) {
862 return;
863 }
864 }
865 // No match. Insert a new interface pair.
866 statsList.push_back(stats);
867}
868
869/*
870 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900871 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900872 * pkts bytes target prot opt in out source destination
873 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
874 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
875 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
876 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
877 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900878 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900879 * pkts bytes target prot opt in out source destination
880 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
881 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
882 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900883 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900884int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900885 const std::string& statsOutput,
886 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800887 enum IndexOfIptChain {
888 ORIG_LINE,
889 PACKET_COUNTS,
890 BYTE_COUNTS,
891 HYPHEN,
892 IFACE0_NAME,
893 IFACE1_NAME,
894 SOURCE,
895 DESTINATION
896 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900897 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900898 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900899
waynema71a0b592018-11-21 13:31:34 +0800900 static const std::string NUM = "(\\d+)";
901 static const std::string IFACE = "([^\\s]+)";
902 static const std::string DST = "(0.0.0.0/0|::/0)";
903 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
904 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
905 "\\s+" + DST + "\\s+" + DST;
906 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900907
waynema71a0b592018-11-21 13:31:34 +0800908 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
909 int headerLine = 0;
910 for (const std::string& line : lines) {
911 // Skip headers.
912 if (headerLine < 2) {
913 if (line.empty()) {
914 ALOGV("Empty header while parsing tethering stats");
915 return -EREMOTEIO;
916 }
917 headerLine++;
918 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900919 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900920
waynema71a0b592018-11-21 13:31:34 +0800921 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900922
waynema71a0b592018-11-21 13:31:34 +0800923 extraProcessingInfo = line;
924 std::smatch matches;
925 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
926 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
927 // IPv4 has "--" indicating what to do with fragments...
928 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
929 // ... but IPv6 does not.
930 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
931 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
932 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
933 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
934 std::string iface0 = matches[IFACE0_NAME].str();
935 std::string iface1 = matches[IFACE1_NAME].str();
936 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900937
waynema71a0b592018-11-21 13:31:34 +0800938 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
939 " rest=<%s> orig line=<%s>",
940 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900941 /*
942 * The following assumes that the 1st rule has in:extIface out:intIface,
943 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900944 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900945 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900946 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800947 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
948 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900949 stats.intIface = iface0;
950 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900951 stats.txPackets = packets;
952 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900953 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800954 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
955 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900956 stats.rxPackets = packets;
957 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900958 }
959 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900960 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900961 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900962 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900963 }
964 }
965
966 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900967 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900968 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900969 }
970 return 0;
971}
972
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900973StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900974 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900975 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900976
977 for (const IptablesTarget target : {V4, V6}) {
978 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900979 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900980 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
981 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900982 }
983
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900984 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900985 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
986 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900987 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900988 }
989 }
990
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900991 return statsList;
992}
993
Hungming Chen1da90082020-02-14 20:24:16 +0800994void TetherController::maybeStartBpf(const char* extIface) {
Maciej Żenczykowskiaef13012020-02-18 17:13:09 -0800995 if (!bpf::isBpfSupported()) return;
996
Hungming Chen1da90082020-02-14 20:24:16 +0800997 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
998 int ifIndex = if_nametoindex(extIface);
999 if (!ifIndex) {
1000 ALOGE("Fail to get index for interface %s", extIface);
1001 return;
1002 }
1003
1004 auto isEthernet = android::net::isEthernet(extIface);
1005 if (!isEthernet.ok()) {
1006 ALOGE("isEthernet(%s[%d]) failure: %s", extIface, ifIndex,
1007 isEthernet.error().message().c_str());
1008 return;
1009 }
1010
1011 int rv = getTetherIngressProgFd(isEthernet.value());
1012 if (rv < 0) {
1013 ALOGE("getTetherIngressProgFd(%d) failure: %s", isEthernet.value(), strerror(-rv));
1014 return;
1015 }
1016 unique_fd tetherProgFd(rv);
1017
1018 rv = tcFilterAddDevIngressTether(ifIndex, tetherProgFd, isEthernet.value());
1019 if (rv) {
1020 ALOGE("tcFilterAddDevIngressTether(%d[%s], %d) failure: %s", ifIndex, extIface,
1021 isEthernet.value(), strerror(-rv));
1022 return;
1023 }
1024}
1025
1026void TetherController::maybeStopBpf(const char* extIface) {
Maciej Żenczykowskiaef13012020-02-18 17:13:09 -08001027 if (!bpf::isBpfSupported()) return;
1028
Hungming Chen1da90082020-02-14 20:24:16 +08001029 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
1030 int ifIndex = if_nametoindex(extIface);
1031 if (!ifIndex) {
1032 ALOGE("Fail to get index for interface %s", extIface);
1033 return;
1034 }
1035
1036 int rv = tcFilterDelDevIngressTether(ifIndex);
1037 if (rv < 0) {
1038 ALOGE("tcFilterDelDevIngressTether(%d[%s]) failure: %s", ifIndex, extIface, strerror(-rv));
1039 }
1040}
1041
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001042void TetherController::dumpIfaces(DumpWriter& dw) {
1043 dw.println("Interface pairs:");
1044
1045 ScopedIndent ifaceIndent(dw);
1046 for (const auto& it : mFwdIfaces) {
1047 dw.println("%s -> %s %s", it.first.c_str(), it.second.iface.c_str(),
1048 (it.second.active ? "ACTIVE" : "DISABLED"));
1049 }
1050}
1051
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001052namespace {
1053
1054std::string l2ToString(const uint8_t* addr, size_t len) {
1055 std::string str;
1056
1057 if (len == 0) return str;
1058
1059 StringAppendF(&str, "%02x", addr[0]);
1060 for (size_t i = 1; i < len; i++) {
1061 StringAppendF(&str, ":%02x", addr[i]);
1062 }
1063
1064 return str;
1065}
1066
1067} // namespace
1068
1069void TetherController::dumpBpf(DumpWriter& dw) {
1070 if (!mBpfIngressMap.isValid() || !mBpfStatsMap.isValid()) {
1071 dw.println("BPF not supported");
1072 return;
1073 }
1074
1075 dw.println("BPF ingress map: iif v6addr -> oif srcmac dstmac ethertype");
1076 const auto printIngressMap = [&dw](const TetherIngressKey& key, const TetherIngressValue& value,
1077 const BpfMap<TetherIngressKey, TetherIngressValue>&) {
1078 char addr[INET6_ADDRSTRLEN];
1079 std::string src = l2ToString(value.macHeader.h_source, sizeof(value.macHeader.h_source));
1080 std::string dst = l2ToString(value.macHeader.h_dest, sizeof(value.macHeader.h_dest));
1081 inet_ntop(AF_INET6, &key.neigh6, addr, sizeof(addr));
1082
1083 dw.println("%d %s -> %d %s %s %04x", key.iif, addr, value.oif, src.c_str(), dst.c_str(),
1084 ntohs(value.macHeader.h_proto));
1085
1086 return Result<void>();
1087 };
1088
1089 dw.incIndent();
1090 auto ret = mBpfIngressMap.iterateWithValue(printIngressMap);
1091 if (!ret.ok()) {
1092 dw.println("Error printing BPF ingress map: %s", ret.error().message().c_str());
1093 }
1094 dw.decIndent();
1095
1096 dw.println("BPF stats (downlink): iif -> packets bytes errors");
1097 const auto printStatsMap = [&dw](const uint32_t& key, const TetherStatsValue& value,
1098 const BpfMap<uint32_t, TetherStatsValue>&) {
1099 dw.println("%d -> %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxPackets, value.rxBytes,
1100 value.rxErrors);
1101
1102 return Result<void>();
1103 };
1104
1105 dw.incIndent();
1106 ret = mBpfStatsMap.iterateWithValue(printStatsMap);
1107 if (!ret.ok()) {
1108 dw.println("Error printing BPF stats map: %s", ret.error().message().c_str());
1109 }
1110 dw.decIndent();
1111}
1112
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001113void TetherController::dump(DumpWriter& dw) {
1114 std::lock_guard guard(lock);
1115
1116 ScopedIndent tetherControllerIndent(dw);
1117 dw.println("TetherController");
1118 dw.incIndent();
1119
1120 dw.println("Forwarding requests: " + Join(mForwardingRequests, ' '));
1121 if (mDnsNetId != 0) {
1122 dw.println(StringPrintf("DNS: netId %d servers [%s]", mDnsNetId,
1123 Join(mDnsForwarders, ", ").c_str()));
1124 }
1125 if (mDaemonPid != 0) {
1126 dw.println("dnsmasq PID: %d", mDaemonPid);
1127 }
1128
1129 dumpIfaces(dw);
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001130 dw.println("");
1131 dumpBpf(dw);
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001132}
1133
Lorenzo Colittie20a5262017-05-09 18:30:44 +09001134} // namespace net
1135} // namespace android