blob: 16f272cdcafa453fe2b5fb5e9cd6445bca2633a5 [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";
Hungming Chenc2e95fb2020-02-19 17:41:30 +080080constexpr const char kBpfOffloadInterface[] = "BPFOffloadInterface";
Lorenzo Colitti799625c2015-02-25 12:52:00 +090081
Erik Kline5f0358b2018-02-16 15:08:09 +090082// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
83constexpr const char kDnsmasqUsername[] = "dns_tether";
84
Lorenzo Colitti799625c2015-02-25 12:52:00 +090085bool writeToFile(const char* filename, const char* value) {
Nick Kralevichb95c60c2016-11-19 09:09:16 -080086 int fd = open(filename, O_WRONLY | O_CLOEXEC);
Nicolas Geoffrayafd40372015-03-16 11:58:06 +000087 if (fd < 0) {
88 ALOGE("Failed to open %s: %s", filename, strerror(errno));
89 return false;
90 }
91
92 const ssize_t len = strlen(value);
93 if (write(fd, value, len) != len) {
94 ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
95 close(fd);
96 return false;
97 }
98 close(fd);
99 return true;
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900100}
101
Erik Kline93f9b222017-10-22 21:24:58 +0900102// TODO: Consider altering TCP and UDP timeouts as well.
103void configureForTethering(bool enabled) {
104 writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
105}
106
Erik Kline1d065ba2016-06-08 13:24:45 +0900107bool configureForIPv6Router(const char *interface) {
108 return (InterfaceController::setEnableIPv6(interface, 0) == 0)
109 && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
Erik Kline6cddf512016-08-09 15:28:42 +0900110 && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
111 && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
Erik Kline1d065ba2016-06-08 13:24:45 +0900112 && (InterfaceController::setEnableIPv6(interface, 1) == 0);
113}
114
115void configureForIPv6Client(const char *interface) {
116 InterfaceController::setAcceptIPv6Ra(interface, 1);
Erik Kline6cddf512016-08-09 15:28:42 +0900117 InterfaceController::setAcceptIPv6Dad(interface, 1);
118 InterfaceController::setIPv6DadTransmits(interface, "1");
Erik Kline1d065ba2016-06-08 13:24:45 +0900119 InterfaceController::setEnableIPv6(interface, 0);
120}
121
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900122bool inBpToolsMode() {
123 // In BP tools mode, do not disable IP forwarding
124 char bootmode[PROPERTY_VALUE_MAX] = {0};
125 property_get("ro.bootmode", bootmode, "unknown");
126 return !strcmp(BP_TOOLS_MODE, bootmode);
127}
128
129} // namespace
130
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900131auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
132
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900133const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
134 "*filter\n"
135 "-nvx -L %s\n"
136 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
137
Erik Kline15079dd2018-05-18 23:10:56 +0900138int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
139 if (cmd.empty()) return 0;
140
Erik Klineb31fd692018-06-06 20:50:11 +0900141 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900142 // Send the trailing \0 as well.
143 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900144 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900145 errno = EREMOTEIO;
146 return -1;
147 }
148 return 0;
149}
150
151void TetherController::DnsmasqState::clear() {
152 update_ifaces_cmd.clear();
153 update_dns_cmd.clear();
154}
155
156int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
157 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
158}
159
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700160TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900161 if (inBpToolsMode()) {
162 enableForwarding(BP_TOOLS_MODE);
163 } else {
164 setIpFwdEnabled();
165 }
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800166 maybeInitMaps();
San Mehat9d10b342010-01-18 09:51:02 -0800167}
168
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900169bool TetherController::setIpFwdEnabled() {
170 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900171 bool disable = mForwardingRequests.empty();
172 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900173 ALOGD("Setting IP forward enable = %s", value);
174 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
175 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900176 if (disable) {
177 // Turning off the forwarding sysconf in the kernel has the side effect
178 // of turning on ICMP redirect, which is a security hazard.
179 // Turn ICMP redirect back off immediately.
180 int rv = InterfaceController::disableIcmpRedirects();
181 success &= (rv == 0);
182 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900183 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800184}
185
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900186bool TetherController::enableForwarding(const char* requester) {
187 // Don't return an error if this requester already requested forwarding. Only return errors for
188 // things that the caller caller needs to care about, such as "couldn't write to the file to
189 // enable forwarding".
190 mForwardingRequests.insert(requester);
191 return setIpFwdEnabled();
192}
San Mehat9d10b342010-01-18 09:51:02 -0800193
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900194bool TetherController::disableForwarding(const char* requester) {
195 mForwardingRequests.erase(requester);
196 return setIpFwdEnabled();
197}
San Mehat9d10b342010-01-18 09:51:02 -0800198
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800199void TetherController::maybeInitMaps() {
200 if (!bpf::isBpfSupported()) return;
201
202 // Used for parsing tether stats from BPF maps. If open the map failed, skip to open
203 // tether BPF offload maps.
204 mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH);
205 if (!mIfaceIndexNameMap.isValid()) return;
206
207 // Open BPF maps, ignoring errors because the device might not support BPF offload.
208 int fd = getTetherIngressMapFd();
209 if (fd != -1) {
210 mBpfIngressMap.reset(fd);
211 }
212 fd = getTetherStatsMapFd();
213 if (fd != -1) {
214 mBpfStatsMap.reset(fd);
215 }
216}
217
Luke Huang728cf4c2019-03-14 19:43:02 +0800218const std::set<std::string>& TetherController::getIpfwdRequesterList() const {
219 return mForwardingRequests;
San Mehat9d10b342010-01-18 09:51:02 -0800220}
221
Luke Huang91bd3e12019-08-20 11:33:52 +0800222int TetherController::startTethering(bool usingLegacyDnsProxy, int num_addrs, char** dhcp_ranges) {
223 if (!usingLegacyDnsProxy && num_addrs == 0) {
224 // Both DHCP and DnsProxy are disabled, we don't need to start dnsmasq
225 configureForTethering(true);
226 mIsTetheringStarted = true;
227 return 0;
228 }
229
230 if (mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000231 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800232 errno = EBUSY;
Luke Huangb5733d72018-08-21 17:17:19 +0800233 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800234 }
235
Steve Block7b984e32011-12-20 16:22:42 +0000236 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800237
George Burgess IVe3dc1312019-02-28 11:27:04 -0800238 unique_fd pipeRead, pipeWrite;
239 if (!Pipe(&pipeRead, &pipeWrite, O_CLOEXEC)) {
Luke Huangb5733d72018-08-21 17:17:19 +0800240 int res = errno;
Luke Huang94c43a12019-02-14 19:51:38 +0800241 ALOGE("pipe2() failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800242 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800243 }
244
Luke Huang94c43a12019-02-14 19:51:38 +0800245 // Set parameters
246 Fwmark fwmark;
247 fwmark.netId = NetworkController::LOCAL_NET_ID;
248 fwmark.explicitlySelected = true;
249 fwmark.protectedFromVpn = true;
250 fwmark.permission = PERMISSION_SYSTEM;
251 char markStr[UINT32_HEX_STRLEN];
252 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800253
Luke Huang94c43a12019-02-14 19:51:38 +0800254 std::vector<const std::string> argVector = {
Erik Kline5f0358b2018-02-16 15:08:09 +0900255 "/system/bin/dnsmasq",
256 "--keep-in-foreground",
257 "--no-resolv",
258 "--no-poll",
259 "--dhcp-authoritative",
260 // TODO: pipe through metered status from ConnService
261 "--dhcp-option-force=43,ANDROID_METERED",
262 "--pid-file",
Luke Huang94c43a12019-02-14 19:51:38 +0800263 "--listen-mark",
264 markStr,
265 "--user",
266 kDnsmasqUsername,
267 };
San Mehat9d10b342010-01-18 09:51:02 -0800268
Luke Huang91bd3e12019-08-20 11:33:52 +0800269 if (!usingLegacyDnsProxy) {
270 argVector.push_back("--port=0");
271 }
272
273 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is passed.
Luke Huang94c43a12019-02-14 19:51:38 +0800274 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
275 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
276 dhcp_ranges[addrIndex + 1]));
San Mehat9d10b342010-01-18 09:51:02 -0800277 }
278
George Burgess IVe3dc1312019-02-28 11:27:04 -0800279 std::vector<char*> args(argVector.size() + 1);
Luke Huang94c43a12019-02-14 19:51:38 +0800280 for (unsigned i = 0; i < argVector.size(); i++) {
281 args[i] = (char*)argVector[i].c_str();
282 }
283
284 /*
285 * TODO: Create a monitoring thread to handle and restart
286 * the daemon if it exits prematurely
287 */
Luke Huang40962442019-02-26 11:46:10 +0800288
289 // Note that don't modify any memory between vfork and execv.
290 // Changing state of file descriptors would be fine. See posix_spawn_file_actions_add*
291 // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
292 // duplicated fd.
293 posix_spawn_file_actions_t fa;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700294 int res = posix_spawn_file_actions_init(&fa);
Luke Huang40962442019-02-26 11:46:10 +0800295 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700296 ALOGE("posix_spawn_file_actions_init failed (%s)", strerror(res));
297 return -res;
298 }
299 const android::base::ScopeGuard faGuard = [&] { posix_spawn_file_actions_destroy(&fa); };
300 res = posix_spawn_file_actions_adddup2(&fa, pipeRead.get(), STDIN_FILENO);
301 if (res) {
302 ALOGE("posix_spawn_file_actions_adddup2 failed (%s)", strerror(res));
Luke Huang94c43a12019-02-14 19:51:38 +0800303 return -res;
304 }
305
Luke Huang40962442019-02-26 11:46:10 +0800306 posix_spawnattr_t attr;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700307 res = posix_spawnattr_init(&attr);
Luke Huang40962442019-02-26 11:46:10 +0800308 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700309 ALOGE("posix_spawnattr_init failed (%s)", strerror(res));
310 return -res;
311 }
312 const android::base::ScopeGuard attrGuard = [&] { posix_spawnattr_destroy(&attr); };
313 res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK);
314 if (res) {
315 ALOGE("posix_spawnattr_setflags failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800316 return -res;
317 }
318
319 pid_t pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800320 res = posix_spawn(&pid, args[0], &fa, &attr, &args[0], nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800321 if (res) {
322 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800323 return -res;
324 }
Luke Huang94c43a12019-02-14 19:51:38 +0800325 mDaemonPid = pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800326 mDaemonFd = pipeWrite.release();
Luke Huang94c43a12019-02-14 19:51:38 +0800327 configureForTethering(true);
Luke Huang91bd3e12019-08-20 11:33:52 +0800328 mIsTetheringStarted = true;
Luke Huang94c43a12019-02-14 19:51:38 +0800329 applyDnsInterfaces();
330 ALOGD("Tethering services running");
331
San Mehat9d10b342010-01-18 09:51:02 -0800332 return 0;
333}
334
Luke Huangb5733d72018-08-21 17:17:19 +0800335std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
336 std::vector<char*> addrsCstrVec{};
337 addrsCstrVec.reserve(addrs.size());
338 for (const auto& addr : addrs) {
339 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
340 }
341 return addrsCstrVec;
342}
343
Luke Huang91bd3e12019-08-20 11:33:52 +0800344int TetherController::startTethering(bool usingLegacyDnsProxy,
345 const std::vector<std::string>& dhcpRanges) {
Luke Huangb5733d72018-08-21 17:17:19 +0800346 struct in_addr v4_addr;
347 for (const auto& dhcpRange : dhcpRanges) {
348 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
349 return -EINVAL;
350 }
351 }
352 auto dhcp_ranges = toCstrVec(dhcpRanges);
Luke Huang91bd3e12019-08-20 11:33:52 +0800353 return startTethering(usingLegacyDnsProxy, dhcp_ranges.size(), dhcp_ranges.data());
Luke Huangb5733d72018-08-21 17:17:19 +0800354}
355
San Mehat9d10b342010-01-18 09:51:02 -0800356int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900357 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800358
Luke Huang91bd3e12019-08-20 11:33:52 +0800359 if (!mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000360 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800361 return 0;
362 }
363
Luke Huang91bd3e12019-08-20 11:33:52 +0800364 mIsTetheringStarted = false;
365 // dnsmasq is not started
366 if (mDaemonPid == 0) {
367 return 0;
368 }
369
Steve Block7b984e32011-12-20 16:22:42 +0000370 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800371
372 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700373 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800374 mDaemonPid = 0;
375 close(mDaemonFd);
376 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900377 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000378 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800379 return 0;
380}
Matthew Xie19944102012-07-12 16:42:07 -0700381
San Mehat9d10b342010-01-18 09:51:02 -0800382bool TetherController::isTetheringStarted() {
Luke Huang91bd3e12019-08-20 11:33:52 +0800383 return mIsTetheringStarted;
San Mehat9d10b342010-01-18 09:51:02 -0800384}
385
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900386// dnsmasq can't parse commands larger than this due to the fixed-size buffer
387// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
388// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900389const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800390
Luke Huang8dc1cac2019-03-30 16:12:31 +0800391// TODO: Remove overload function and update this after NDC migration.
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700392int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700393 Fwmark fwmark;
394 fwmark.netId = netId;
395 fwmark.explicitlySelected = true;
396 fwmark.protectedFromVpn = true;
397 fwmark.permission = PERMISSION_SYSTEM;
398
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900399 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800400
Erik Kline1d065ba2016-06-08 13:24:45 +0900401 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900402 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700403 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800404
Lorenzo Colittic2841282015-11-25 22:13:57 +0900405 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700406 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900407 freeaddrinfo(res);
408 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000409 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900410 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900411 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800412 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800413 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800414
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900415 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
416 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800417 break;
418 }
419
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900420 daemonCmd += SEPARATOR;
421 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900422 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800423 }
424
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700425 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900426 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800427 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900428 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900429 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900430 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800431 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800432 }
433 }
434 return 0;
435}
436
Luke Huangb5733d72018-08-21 17:17:19 +0800437int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
Luke Huangb5733d72018-08-21 17:17:19 +0800438 auto dnsServers = toCstrVec(servers);
439 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
440}
441
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700442unsigned TetherController::getDnsNetId() {
443 return mDnsNetId;
444}
445
Erik Kline1d065ba2016-06-08 13:24:45 +0900446const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800447 return mDnsForwarders;
448}
449
Erik Kline1d065ba2016-06-08 13:24:45 +0900450bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900451 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800452 bool haveInterfaces = false;
453
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900454 for (const auto& ifname : mInterfaces) {
455 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
456 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800457 break;
458 }
459
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900460 daemonCmd += SEPARATOR;
461 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800462 haveInterfaces = true;
463 }
464
Erik Kline15079dd2018-05-18 23:10:56 +0900465 if (!haveInterfaces) {
466 mDnsmasqState.update_ifaces_cmd.clear();
467 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900468 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900469 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800470 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900471 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800472}
473
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800474int TetherController::tetherInterface(const char *interface) {
475 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700476 if (!isIfaceName(interface)) {
477 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800478 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700479 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800480
Erik Kline1d065ba2016-06-08 13:24:45 +0900481 if (!configureForIPv6Router(interface)) {
482 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800483 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900484 }
485 mInterfaces.push_back(interface);
486
487 if (!applyDnsInterfaces()) {
488 mInterfaces.pop_back();
489 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800490 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800491 } else {
492 return 0;
493 }
494}
495
San Mehat9d10b342010-01-18 09:51:02 -0800496int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800497 ALOGD("untetherInterface(%s)", interface);
498
Erik Kline1d065ba2016-06-08 13:24:45 +0900499 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
500 if (!strcmp(interface, it->c_str())) {
501 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800502
Erik Kline1d065ba2016-06-08 13:24:45 +0900503 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800504 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800505 }
506 }
507 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800508 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800509}
510
Erik Kline1d065ba2016-06-08 13:24:45 +0900511const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800512 return mInterfaces;
513}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900514
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900515int TetherController::setupIptablesHooks() {
516 int res;
517 res = setDefaults();
518 if (res < 0) {
519 return res;
520 }
521
522 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
523 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
524 // This is no longer optional and tethering will fail to start if it fails.
525 std::string mssRewriteCommand = StringPrintf(
526 "*mangle\n"
527 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
528 "COMMIT\n", LOCAL_MANGLE_FORWARD);
529
530 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
531 std::string defaultCommands = StringPrintf(
532 "*filter\n"
533 ":%s -\n"
534 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
535
536 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
537 if (res < 0) {
538 return res;
539 }
540
541 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
542 if (res < 0) {
543 return res;
544 }
545
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900546 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900547
548 return 0;
549}
550
551int TetherController::setDefaults() {
552 std::string v4Cmd = StringPrintf(
553 "*filter\n"
554 ":%s -\n"
555 "-A %s -j DROP\n"
556 "COMMIT\n"
557 "*nat\n"
558 ":%s -\n"
559 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
560
561 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900562 "*filter\n"
563 ":%s -\n"
564 "COMMIT\n"
565 "*raw\n"
566 ":%s -\n"
567 "COMMIT\n",
568 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900569
570 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
571 if (res < 0) {
572 return res;
573 }
574
575 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
576 if (res < 0) {
577 return res;
578 }
579
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900580 return 0;
581}
582
583int TetherController::enableNat(const char* intIface, const char* extIface) {
584 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
585
586 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900587 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900588 }
589
590 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
591 if (!strcmp(intIface, extIface)) {
592 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900593 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900594 }
595
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900596 if (isForwardingPairEnabled(intIface, extIface)) {
597 return 0;
598 }
599
600 // add this if we are the first enabled nat for this upstream
601 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900602 std::vector<std::string> v4Cmds = {
603 "*nat",
604 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
605 "COMMIT\n"
606 };
607
Luke Huangae038f82018-11-05 11:17:31 +0900608 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
609 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900610 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900611 if (!isAnyForwardingPairEnabled()) {
612 // unwind what's been done, but don't care about success - what more could we do?
613 setDefaults();
614 }
Luke Huang19b49c52018-10-22 12:12:05 +0900615 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900616 }
617 }
618
619 if (setForwardRules(true, intIface, extIface) != 0) {
620 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900621 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900622 setDefaults();
623 }
Luke Huang19b49c52018-10-22 12:12:05 +0900624 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900625 }
626
Hungming Chen1da90082020-02-14 20:24:16 +0800627 maybeStartBpf(extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900628 return 0;
629}
630
Luke Huangae038f82018-11-05 11:17:31 +0900631int TetherController::setTetherGlobalAlertRule() {
632 // Only add this if we are the first enabled nat
633 if (isAnyForwardingPairEnabled()) {
634 return 0;
635 }
636 const std::string cmds =
637 "*filter\n" +
638 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
639 "COMMIT\n";
640
641 return iptablesRestoreFunction(V4V6, cmds, nullptr);
642}
643
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900644int TetherController::setupIPv6CountersChain() {
645 // Only add this if we are the first enabled nat
646 if (isAnyForwardingPairEnabled()) {
647 return 0;
648 }
649
650 /*
651 * IPv6 tethering doesn't need the state-based conntrack rules, so
652 * it unconditionally jumps to the tether counters chain all the time.
653 */
Luke Huangae038f82018-11-05 11:17:31 +0900654 const std::string v6Cmds =
655 "*filter\n" +
656 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900657
Luke Huangae038f82018-11-05 11:17:31 +0900658 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900659}
660
661// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
662TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
663 const std::string& intIface, const std::string& extIface) {
664 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
665 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
666 if (it->second.iface == intIface) {
667 return &(it->second);
668 }
669 }
670 return nullptr;
671}
672
673void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
674 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
675 if (existingEntry != nullptr) {
676 existingEntry->active = true;
677 return;
678 }
679
680 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
681 .iface = intIface,
682 .active = true
683 }));
684}
685
686void TetherController::markForwardingPairDisabled(
687 const std::string& intIface, const std::string& extIface) {
688 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
689 if (existingEntry == nullptr) {
690 return;
691 }
692
693 existingEntry->active = false;
694}
695
696bool TetherController::isForwardingPairEnabled(
697 const std::string& intIface, const std::string& extIface) {
698 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
699 return existingEntry != nullptr && existingEntry->active;
700}
701
702bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
703 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
704 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
705 if (it->second.active) {
706 return true;
707 }
708 }
709 return false;
710}
711
712bool TetherController::isAnyForwardingPairEnabled() {
713 for (auto& it : mFwdIfaces) {
714 if (it.second.active) {
715 return true;
716 }
717 }
718 return false;
719}
720
721bool TetherController::tetherCountingRuleExists(
722 const std::string& iface1, const std::string& iface2) {
723 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
724 // is in the map regardless of its active status. Rules are added both ways so we check with
725 // the 2 combinations.
726 return findForwardingDownstream(iface1, iface2) != nullptr
727 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900728}
729
730/* static */
731std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
732 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
733}
734
735int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
736 const char *op = add ? "-A" : "-D";
737
738 std::string rpfilterCmd = StringPrintf(
739 "*raw\n"
740 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
741 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
742 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900743 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900744 }
745
746 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900747 "*raw",
748 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
749 LOCAL_RAW_PREROUTING, intIface),
750 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
751 LOCAL_RAW_PREROUTING, intIface),
752 "COMMIT",
753 "*filter",
754 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
755 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
756 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
757 intIface, extIface),
758 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
759 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900760 };
761
762 std::vector<std::string> v6 = {
763 "*filter",
764 };
765
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900766 // We only ever add tethering quota rules so that they stick.
767 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900768 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900769 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900770 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900771 v6.push_back(makeTetherCountingRule(extIface, intIface));
772 }
773
774 // Always make sure the drop rule is at the end.
775 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900776 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900777 if (add) {
778 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
779 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
780 }
781
782 v4.push_back("COMMIT\n");
783 v6.push_back("COMMIT\n");
784
785 // We only add IPv6 rules here, never remove them.
786 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
787 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
788 // unwind what's been done, but don't care about success - what more could we do?
789 if (add) {
790 setForwardRules(false, intIface, extIface);
791 }
Luke Huang19b49c52018-10-22 12:12:05 +0900792 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900793 }
794
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900795 if (add) {
796 addForwardingPair(intIface, extIface);
797 } else {
798 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900799 }
800
801 return 0;
802}
803
804int TetherController::disableNat(const char* intIface, const char* extIface) {
805 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900806 errno = ENODEV;
807 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900808 }
809
810 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900811 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900812 setDefaults();
813 }
Hungming Chen1da90082020-02-14 20:24:16 +0800814
815 maybeStopBpf(extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900816 return 0;
817}
818
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900819Result<void> TetherController::addDownstreamIpv6Rule(int intIfaceIndex, int extIfaceIndex,
820 const std::vector<uint8_t>& ipAddress,
821 const std::vector<uint8_t>& srcL2Address,
822 const std::vector<uint8_t>& dstL2Address) {
823 ethhdr hdr = {
824 .h_proto = htons(ETH_P_IPV6),
825 };
826 if (ipAddress.size() != sizeof(in6_addr)) {
827 return Error(EINVAL) << "Invalid IP address length " << ipAddress.size();
828 }
829 if (srcL2Address.size() != sizeof(hdr.h_source)) {
830 return Error(EINVAL) << "Invalid L2 src address length " << srcL2Address.size();
831 }
832 if (dstL2Address.size() != sizeof(hdr.h_dest)) {
833 return Error(EINVAL) << "Invalid L2 dst address length " << dstL2Address.size();
834 }
835 memcpy(&hdr.h_dest, dstL2Address.data(), sizeof(hdr.h_dest));
836 memcpy(&hdr.h_source, srcL2Address.data(), sizeof(hdr.h_source));
837
838 TetherIngressKey key = {
839 .iif = static_cast<uint32_t>(extIfaceIndex),
840 .neigh6 = *(const in6_addr*)ipAddress.data(),
841 };
842
843 TetherIngressValue value = {
844 static_cast<uint32_t>(intIfaceIndex),
845 hdr,
846 };
847
848 return mBpfIngressMap.writeValue(key, value, BPF_ANY);
849}
850
851Result<void> TetherController::removeDownstreamIpv6Rule(int extIfaceIndex,
852 const std::vector<uint8_t>& ipAddress) {
853 if (ipAddress.size() != sizeof(in6_addr)) {
854 return Error(EINVAL) << "Invalid IP address length " << ipAddress.size();
855 }
856
857 TetherIngressKey key = {
858 .iif = static_cast<uint32_t>(extIfaceIndex),
859 .neigh6 = *(const in6_addr*)ipAddress.data(),
860 };
861
862 Result<void> ret = mBpfIngressMap.deleteValue(key);
863
864 // Silently return success if the rule did not exist.
865 if (!ret.ok() && ret.error().code() == ENOENT) return {};
866
867 return ret;
868}
869
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900870void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
871 for (TetherStats& existing : statsList) {
872 if (existing.addStatsIfMatch(stats)) {
873 return;
874 }
875 }
876 // No match. Insert a new interface pair.
877 statsList.push_back(stats);
878}
879
880/*
881 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900882 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900883 * pkts bytes target prot opt in out source destination
884 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
885 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
886 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
887 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
888 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900889 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900890 * pkts bytes target prot opt in out source destination
891 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
892 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
893 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900894 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900895int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900896 const std::string& statsOutput,
897 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800898 enum IndexOfIptChain {
899 ORIG_LINE,
900 PACKET_COUNTS,
901 BYTE_COUNTS,
902 HYPHEN,
903 IFACE0_NAME,
904 IFACE1_NAME,
905 SOURCE,
906 DESTINATION
907 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900908 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900909 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900910
waynema71a0b592018-11-21 13:31:34 +0800911 static const std::string NUM = "(\\d+)";
912 static const std::string IFACE = "([^\\s]+)";
913 static const std::string DST = "(0.0.0.0/0|::/0)";
914 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
915 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
916 "\\s+" + DST + "\\s+" + DST;
917 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900918
waynema71a0b592018-11-21 13:31:34 +0800919 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
920 int headerLine = 0;
921 for (const std::string& line : lines) {
922 // Skip headers.
923 if (headerLine < 2) {
924 if (line.empty()) {
925 ALOGV("Empty header while parsing tethering stats");
926 return -EREMOTEIO;
927 }
928 headerLine++;
929 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900930 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900931
waynema71a0b592018-11-21 13:31:34 +0800932 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900933
waynema71a0b592018-11-21 13:31:34 +0800934 extraProcessingInfo = line;
935 std::smatch matches;
936 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
937 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
938 // IPv4 has "--" indicating what to do with fragments...
939 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
940 // ... but IPv6 does not.
941 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
942 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
943 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
944 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
945 std::string iface0 = matches[IFACE0_NAME].str();
946 std::string iface1 = matches[IFACE1_NAME].str();
947 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900948
waynema71a0b592018-11-21 13:31:34 +0800949 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
950 " rest=<%s> orig line=<%s>",
951 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900952 /*
953 * The following assumes that the 1st rule has in:extIface out:intIface,
954 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900955 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900956 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900957 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800958 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
959 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900960 stats.intIface = iface0;
961 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900962 stats.txPackets = packets;
963 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900964 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800965 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
966 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900967 stats.rxPackets = packets;
968 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900969 }
970 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900971 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900972 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900973 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900974 }
975 }
976
977 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900978 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900979 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900980 }
981 return 0;
982}
983
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900984StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900985 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900986 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900987
988 for (const IptablesTarget target : {V4, V6}) {
989 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900990 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900991 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
992 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900993 }
994
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900995 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900996 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
997 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900998 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900999 }
1000 }
1001
Hungming Chenc2e95fb2020-02-19 17:41:30 +08001002 if (mBpfStatsMap.isValid()) {
1003 const auto processTetherStats = [this, &statsList](
1004 const uint32_t& key, const TetherStatsValue& value,
1005 const BpfMap<uint32_t, TetherStatsValue>&) {
1006 auto ifname = mIfaceIndexNameMap.readValue(key);
1007 if (!ifname.ok()) {
1008 // Keep on going regardless to parse as much as possible.
1009 return Result<void>();
1010 }
1011 addStats(statsList,
1012 {kBpfOffloadInterface, ifname.value().name,
1013 static_cast<int64_t>(value.rxBytes), static_cast<int64_t>(value.rxPackets),
1014 static_cast<int64_t>(value.txBytes), static_cast<int64_t>(value.txPackets)});
1015 return Result<void>();
1016 };
1017
1018 auto ret = mBpfStatsMap.iterateWithValue(processTetherStats);
1019 if (!ret.ok()) {
1020 // Ignore error to return the non-BPF tether stats result.
1021 ALOGE("Error processing tether stats from BPF maps: %s", ret.error().message().c_str());
1022 }
1023 }
1024
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001025 return statsList;
1026}
1027
Hungming Chen1da90082020-02-14 20:24:16 +08001028void TetherController::maybeStartBpf(const char* extIface) {
Maciej Żenczykowskiaef13012020-02-18 17:13:09 -08001029 if (!bpf::isBpfSupported()) return;
1030
Hungming Chen1da90082020-02-14 20:24:16 +08001031 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
1032 int ifIndex = if_nametoindex(extIface);
1033 if (!ifIndex) {
1034 ALOGE("Fail to get index for interface %s", extIface);
1035 return;
1036 }
1037
1038 auto isEthernet = android::net::isEthernet(extIface);
1039 if (!isEthernet.ok()) {
1040 ALOGE("isEthernet(%s[%d]) failure: %s", extIface, ifIndex,
1041 isEthernet.error().message().c_str());
1042 return;
1043 }
1044
1045 int rv = getTetherIngressProgFd(isEthernet.value());
1046 if (rv < 0) {
1047 ALOGE("getTetherIngressProgFd(%d) failure: %s", isEthernet.value(), strerror(-rv));
1048 return;
1049 }
1050 unique_fd tetherProgFd(rv);
1051
1052 rv = tcFilterAddDevIngressTether(ifIndex, tetherProgFd, isEthernet.value());
1053 if (rv) {
1054 ALOGE("tcFilterAddDevIngressTether(%d[%s], %d) failure: %s", ifIndex, extIface,
1055 isEthernet.value(), strerror(-rv));
1056 return;
1057 }
1058}
1059
1060void TetherController::maybeStopBpf(const char* extIface) {
Maciej Żenczykowskiaef13012020-02-18 17:13:09 -08001061 if (!bpf::isBpfSupported()) return;
1062
Hungming Chen1da90082020-02-14 20:24:16 +08001063 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
1064 int ifIndex = if_nametoindex(extIface);
1065 if (!ifIndex) {
1066 ALOGE("Fail to get index for interface %s", extIface);
1067 return;
1068 }
1069
1070 int rv = tcFilterDelDevIngressTether(ifIndex);
1071 if (rv < 0) {
1072 ALOGE("tcFilterDelDevIngressTether(%d[%s]) failure: %s", ifIndex, extIface, strerror(-rv));
1073 }
1074}
1075
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001076void TetherController::dumpIfaces(DumpWriter& dw) {
1077 dw.println("Interface pairs:");
1078
1079 ScopedIndent ifaceIndent(dw);
1080 for (const auto& it : mFwdIfaces) {
1081 dw.println("%s -> %s %s", it.first.c_str(), it.second.iface.c_str(),
1082 (it.second.active ? "ACTIVE" : "DISABLED"));
1083 }
1084}
1085
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001086namespace {
1087
1088std::string l2ToString(const uint8_t* addr, size_t len) {
1089 std::string str;
1090
1091 if (len == 0) return str;
1092
1093 StringAppendF(&str, "%02x", addr[0]);
1094 for (size_t i = 1; i < len; i++) {
1095 StringAppendF(&str, ":%02x", addr[i]);
1096 }
1097
1098 return str;
1099}
1100
1101} // namespace
1102
1103void TetherController::dumpBpf(DumpWriter& dw) {
1104 if (!mBpfIngressMap.isValid() || !mBpfStatsMap.isValid()) {
1105 dw.println("BPF not supported");
1106 return;
1107 }
1108
1109 dw.println("BPF ingress map: iif v6addr -> oif srcmac dstmac ethertype");
1110 const auto printIngressMap = [&dw](const TetherIngressKey& key, const TetherIngressValue& value,
1111 const BpfMap<TetherIngressKey, TetherIngressValue>&) {
1112 char addr[INET6_ADDRSTRLEN];
1113 std::string src = l2ToString(value.macHeader.h_source, sizeof(value.macHeader.h_source));
1114 std::string dst = l2ToString(value.macHeader.h_dest, sizeof(value.macHeader.h_dest));
1115 inet_ntop(AF_INET6, &key.neigh6, addr, sizeof(addr));
1116
1117 dw.println("%d %s -> %d %s %s %04x", key.iif, addr, value.oif, src.c_str(), dst.c_str(),
1118 ntohs(value.macHeader.h_proto));
1119
1120 return Result<void>();
1121 };
1122
1123 dw.incIndent();
1124 auto ret = mBpfIngressMap.iterateWithValue(printIngressMap);
1125 if (!ret.ok()) {
1126 dw.println("Error printing BPF ingress map: %s", ret.error().message().c_str());
1127 }
1128 dw.decIndent();
1129
1130 dw.println("BPF stats (downlink): iif -> packets bytes errors");
1131 const auto printStatsMap = [&dw](const uint32_t& key, const TetherStatsValue& value,
1132 const BpfMap<uint32_t, TetherStatsValue>&) {
1133 dw.println("%d -> %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxPackets, value.rxBytes,
1134 value.rxErrors);
1135
1136 return Result<void>();
1137 };
1138
1139 dw.incIndent();
1140 ret = mBpfStatsMap.iterateWithValue(printStatsMap);
1141 if (!ret.ok()) {
1142 dw.println("Error printing BPF stats map: %s", ret.error().message().c_str());
1143 }
1144 dw.decIndent();
1145}
1146
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001147void TetherController::dump(DumpWriter& dw) {
1148 std::lock_guard guard(lock);
1149
1150 ScopedIndent tetherControllerIndent(dw);
1151 dw.println("TetherController");
1152 dw.incIndent();
1153
1154 dw.println("Forwarding requests: " + Join(mForwardingRequests, ' '));
1155 if (mDnsNetId != 0) {
1156 dw.println(StringPrintf("DNS: netId %d servers [%s]", mDnsNetId,
1157 Join(mDnsForwarders, ", ").c_str()));
1158 }
1159 if (mDaemonPid != 0) {
1160 dw.println("dnsmasq PID: %d", mDaemonPid);
1161 }
1162
1163 dumpIfaces(dw);
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001164 dw.println("");
1165 dumpBpf(dw);
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001166}
1167
Lorenzo Colittie20a5262017-05-09 18:30:44 +09001168} // namespace net
1169} // namespace android