blob: 144d24f4649fbd3a957bc64a07021d5ef765fa83 [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
Lorenzo Colittif0e051c2020-04-06 09:19:57 +000058#include "android/net/TetherOffloadRuleParcel.h"
59
Bernie Innocenti4debf3b2018-09-12 13:54:50 +090060namespace android {
61namespace net {
62
Lorenzo Colittie801d3c2020-02-18 00:00:35 +090063using android::base::Error;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090064using android::base::Join;
George Burgess IVe3dc1312019-02-28 11:27:04 -080065using android::base::Pipe;
Lorenzo Colittie801d3c2020-02-18 00:00:35 +090066using android::base::Result;
67using android::base::StringAppendF;
Erik Klineb31fd692018-06-06 20:50:11 +090068using android::base::StringPrintf;
George Burgess IVe3dc1312019-02-28 11:27:04 -080069using android::base::unique_fd;
Lorenzo Colittif0e051c2020-04-06 09:19:57 +000070using android::net::TetherOffloadRuleParcel;
Lorenzo Colitti52db3912020-02-17 23:59:45 +090071using android::netdutils::DumpWriter;
72using android::netdutils::ScopedIndent;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090073using android::netdutils::statusFromErrno;
Erik Klineb31fd692018-06-06 20:50:11 +090074using android::netdutils::StatusOr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090075
Lorenzo Colitti799625c2015-02-25 12:52:00 +090076namespace {
77
Erik Kline1d065ba2016-06-08 13:24:45 +090078const char BP_TOOLS_MODE[] = "bp-tools";
79const char IPV4_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv4/ip_forward";
80const char IPV6_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv6/conf/all/forwarding";
81const char SEPARATOR[] = "|";
Erik Kline93f9b222017-10-22 21:24:58 +090082constexpr const char kTcpBeLiberal[] = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
Hungming Chen68dade32020-02-20 13:50:56 +080083
84// Dummy interface name, the name needs to be longer than 16 characters so it can never conflict
85// with a real interface name. See also IFNAMSIZ.
Hungming Chenc2e95fb2020-02-19 17:41:30 +080086constexpr const char kBpfOffloadInterface[] = "BPFOffloadInterface";
Lorenzo Colitti799625c2015-02-25 12:52:00 +090087
Erik Kline5f0358b2018-02-16 15:08:09 +090088// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
89constexpr const char kDnsmasqUsername[] = "dns_tether";
90
Lorenzo Colitti799625c2015-02-25 12:52:00 +090091bool writeToFile(const char* filename, const char* value) {
Nick Kralevichb95c60c2016-11-19 09:09:16 -080092 int fd = open(filename, O_WRONLY | O_CLOEXEC);
Nicolas Geoffrayafd40372015-03-16 11:58:06 +000093 if (fd < 0) {
94 ALOGE("Failed to open %s: %s", filename, strerror(errno));
95 return false;
96 }
97
98 const ssize_t len = strlen(value);
99 if (write(fd, value, len) != len) {
100 ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
101 close(fd);
102 return false;
103 }
104 close(fd);
105 return true;
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900106}
107
Erik Kline93f9b222017-10-22 21:24:58 +0900108// TODO: Consider altering TCP and UDP timeouts as well.
109void configureForTethering(bool enabled) {
110 writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
111}
112
Erik Kline1d065ba2016-06-08 13:24:45 +0900113bool configureForIPv6Router(const char *interface) {
114 return (InterfaceController::setEnableIPv6(interface, 0) == 0)
115 && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
Erik Kline6cddf512016-08-09 15:28:42 +0900116 && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
117 && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
Erik Kline1d065ba2016-06-08 13:24:45 +0900118 && (InterfaceController::setEnableIPv6(interface, 1) == 0);
119}
120
121void configureForIPv6Client(const char *interface) {
122 InterfaceController::setAcceptIPv6Ra(interface, 1);
Erik Kline6cddf512016-08-09 15:28:42 +0900123 InterfaceController::setAcceptIPv6Dad(interface, 1);
124 InterfaceController::setIPv6DadTransmits(interface, "1");
Erik Kline1d065ba2016-06-08 13:24:45 +0900125 InterfaceController::setEnableIPv6(interface, 0);
126}
127
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900128bool inBpToolsMode() {
129 // In BP tools mode, do not disable IP forwarding
130 char bootmode[PROPERTY_VALUE_MAX] = {0};
131 property_get("ro.bootmode", bootmode, "unknown");
132 return !strcmp(BP_TOOLS_MODE, bootmode);
133}
134
135} // namespace
136
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900137auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
138
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900139const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
140 "*filter\n"
141 "-nvx -L %s\n"
142 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
143
Erik Kline15079dd2018-05-18 23:10:56 +0900144int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
145 if (cmd.empty()) return 0;
146
Erik Klineb31fd692018-06-06 20:50:11 +0900147 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900148 // Send the trailing \0 as well.
149 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900150 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900151 errno = EREMOTEIO;
152 return -1;
153 }
154 return 0;
155}
156
157void TetherController::DnsmasqState::clear() {
158 update_ifaces_cmd.clear();
159 update_dns_cmd.clear();
160}
161
162int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
163 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
164}
165
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700166TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900167 if (inBpToolsMode()) {
168 enableForwarding(BP_TOOLS_MODE);
169 } else {
170 setIpFwdEnabled();
171 }
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800172 maybeInitMaps();
San Mehat9d10b342010-01-18 09:51:02 -0800173}
174
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900175bool TetherController::setIpFwdEnabled() {
176 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900177 bool disable = mForwardingRequests.empty();
178 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900179 ALOGD("Setting IP forward enable = %s", value);
180 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
181 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900182 if (disable) {
183 // Turning off the forwarding sysconf in the kernel has the side effect
184 // of turning on ICMP redirect, which is a security hazard.
185 // Turn ICMP redirect back off immediately.
186 int rv = InterfaceController::disableIcmpRedirects();
187 success &= (rv == 0);
188 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900189 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800190}
191
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900192bool TetherController::enableForwarding(const char* requester) {
193 // Don't return an error if this requester already requested forwarding. Only return errors for
194 // things that the caller caller needs to care about, such as "couldn't write to the file to
195 // enable forwarding".
196 mForwardingRequests.insert(requester);
197 return setIpFwdEnabled();
198}
San Mehat9d10b342010-01-18 09:51:02 -0800199
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900200bool TetherController::disableForwarding(const char* requester) {
201 mForwardingRequests.erase(requester);
202 return setIpFwdEnabled();
203}
San Mehat9d10b342010-01-18 09:51:02 -0800204
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800205void TetherController::maybeInitMaps() {
206 if (!bpf::isBpfSupported()) return;
207
208 // Used for parsing tether stats from BPF maps. If open the map failed, skip to open
209 // tether BPF offload maps.
210 mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH);
211 if (!mIfaceIndexNameMap.isValid()) return;
212
213 // Open BPF maps, ignoring errors because the device might not support BPF offload.
214 int fd = getTetherIngressMapFd();
Maciej Żenczykowski109ac532020-02-19 10:36:44 -0800215 if (fd >= 0) {
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800216 mBpfIngressMap.reset(fd);
Maciej Żenczykowski109ac532020-02-19 10:36:44 -0800217 mBpfIngressMap.clear();
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800218 }
219 fd = getTetherStatsMapFd();
Maciej Żenczykowski109ac532020-02-19 10:36:44 -0800220 if (fd >= 0) {
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800221 mBpfStatsMap.reset(fd);
Maciej Żenczykowski109ac532020-02-19 10:36:44 -0800222 mBpfStatsMap.clear();
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800223 }
224}
225
Luke Huang728cf4c2019-03-14 19:43:02 +0800226const std::set<std::string>& TetherController::getIpfwdRequesterList() const {
227 return mForwardingRequests;
San Mehat9d10b342010-01-18 09:51:02 -0800228}
229
Luke Huang91bd3e12019-08-20 11:33:52 +0800230int TetherController::startTethering(bool usingLegacyDnsProxy, int num_addrs, char** dhcp_ranges) {
231 if (!usingLegacyDnsProxy && num_addrs == 0) {
232 // Both DHCP and DnsProxy are disabled, we don't need to start dnsmasq
233 configureForTethering(true);
234 mIsTetheringStarted = true;
235 return 0;
236 }
237
238 if (mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000239 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800240 errno = EBUSY;
Luke Huangb5733d72018-08-21 17:17:19 +0800241 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800242 }
243
Steve Block7b984e32011-12-20 16:22:42 +0000244 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800245
George Burgess IVe3dc1312019-02-28 11:27:04 -0800246 unique_fd pipeRead, pipeWrite;
247 if (!Pipe(&pipeRead, &pipeWrite, O_CLOEXEC)) {
Luke Huangb5733d72018-08-21 17:17:19 +0800248 int res = errno;
Luke Huang94c43a12019-02-14 19:51:38 +0800249 ALOGE("pipe2() failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800250 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800251 }
252
Luke Huang94c43a12019-02-14 19:51:38 +0800253 // Set parameters
254 Fwmark fwmark;
255 fwmark.netId = NetworkController::LOCAL_NET_ID;
256 fwmark.explicitlySelected = true;
257 fwmark.protectedFromVpn = true;
258 fwmark.permission = PERMISSION_SYSTEM;
259 char markStr[UINT32_HEX_STRLEN];
260 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800261
Luke Huang94c43a12019-02-14 19:51:38 +0800262 std::vector<const std::string> argVector = {
Erik Kline5f0358b2018-02-16 15:08:09 +0900263 "/system/bin/dnsmasq",
264 "--keep-in-foreground",
265 "--no-resolv",
266 "--no-poll",
267 "--dhcp-authoritative",
268 // TODO: pipe through metered status from ConnService
269 "--dhcp-option-force=43,ANDROID_METERED",
270 "--pid-file",
Luke Huang94c43a12019-02-14 19:51:38 +0800271 "--listen-mark",
272 markStr,
273 "--user",
274 kDnsmasqUsername,
275 };
San Mehat9d10b342010-01-18 09:51:02 -0800276
Luke Huang91bd3e12019-08-20 11:33:52 +0800277 if (!usingLegacyDnsProxy) {
278 argVector.push_back("--port=0");
279 }
280
281 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is passed.
Luke Huang94c43a12019-02-14 19:51:38 +0800282 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
283 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
284 dhcp_ranges[addrIndex + 1]));
San Mehat9d10b342010-01-18 09:51:02 -0800285 }
286
George Burgess IVe3dc1312019-02-28 11:27:04 -0800287 std::vector<char*> args(argVector.size() + 1);
Luke Huang94c43a12019-02-14 19:51:38 +0800288 for (unsigned i = 0; i < argVector.size(); i++) {
289 args[i] = (char*)argVector[i].c_str();
290 }
291
292 /*
293 * TODO: Create a monitoring thread to handle and restart
294 * the daemon if it exits prematurely
295 */
Luke Huang40962442019-02-26 11:46:10 +0800296
297 // Note that don't modify any memory between vfork and execv.
298 // Changing state of file descriptors would be fine. See posix_spawn_file_actions_add*
299 // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
300 // duplicated fd.
301 posix_spawn_file_actions_t fa;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700302 int res = posix_spawn_file_actions_init(&fa);
Luke Huang40962442019-02-26 11:46:10 +0800303 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700304 ALOGE("posix_spawn_file_actions_init failed (%s)", strerror(res));
305 return -res;
306 }
307 const android::base::ScopeGuard faGuard = [&] { posix_spawn_file_actions_destroy(&fa); };
308 res = posix_spawn_file_actions_adddup2(&fa, pipeRead.get(), STDIN_FILENO);
309 if (res) {
310 ALOGE("posix_spawn_file_actions_adddup2 failed (%s)", strerror(res));
Luke Huang94c43a12019-02-14 19:51:38 +0800311 return -res;
312 }
313
Luke Huang40962442019-02-26 11:46:10 +0800314 posix_spawnattr_t attr;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700315 res = posix_spawnattr_init(&attr);
Luke Huang40962442019-02-26 11:46:10 +0800316 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700317 ALOGE("posix_spawnattr_init failed (%s)", strerror(res));
318 return -res;
319 }
320 const android::base::ScopeGuard attrGuard = [&] { posix_spawnattr_destroy(&attr); };
321 res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK);
322 if (res) {
323 ALOGE("posix_spawnattr_setflags failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800324 return -res;
325 }
326
327 pid_t pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800328 res = posix_spawn(&pid, args[0], &fa, &attr, &args[0], nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800329 if (res) {
330 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800331 return -res;
332 }
Luke Huang94c43a12019-02-14 19:51:38 +0800333 mDaemonPid = pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800334 mDaemonFd = pipeWrite.release();
Luke Huang94c43a12019-02-14 19:51:38 +0800335 configureForTethering(true);
Luke Huang91bd3e12019-08-20 11:33:52 +0800336 mIsTetheringStarted = true;
Luke Huang94c43a12019-02-14 19:51:38 +0800337 applyDnsInterfaces();
338 ALOGD("Tethering services running");
339
San Mehat9d10b342010-01-18 09:51:02 -0800340 return 0;
341}
342
Luke Huangb5733d72018-08-21 17:17:19 +0800343std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
344 std::vector<char*> addrsCstrVec{};
345 addrsCstrVec.reserve(addrs.size());
346 for (const auto& addr : addrs) {
347 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
348 }
349 return addrsCstrVec;
350}
351
Luke Huang91bd3e12019-08-20 11:33:52 +0800352int TetherController::startTethering(bool usingLegacyDnsProxy,
353 const std::vector<std::string>& dhcpRanges) {
Luke Huangb5733d72018-08-21 17:17:19 +0800354 struct in_addr v4_addr;
355 for (const auto& dhcpRange : dhcpRanges) {
356 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
357 return -EINVAL;
358 }
359 }
360 auto dhcp_ranges = toCstrVec(dhcpRanges);
Luke Huang91bd3e12019-08-20 11:33:52 +0800361 return startTethering(usingLegacyDnsProxy, dhcp_ranges.size(), dhcp_ranges.data());
Luke Huangb5733d72018-08-21 17:17:19 +0800362}
363
San Mehat9d10b342010-01-18 09:51:02 -0800364int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900365 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800366
Luke Huang91bd3e12019-08-20 11:33:52 +0800367 if (!mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000368 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800369 return 0;
370 }
371
Luke Huang91bd3e12019-08-20 11:33:52 +0800372 mIsTetheringStarted = false;
373 // dnsmasq is not started
374 if (mDaemonPid == 0) {
375 return 0;
376 }
377
Steve Block7b984e32011-12-20 16:22:42 +0000378 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800379
380 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700381 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800382 mDaemonPid = 0;
383 close(mDaemonFd);
384 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900385 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000386 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800387 return 0;
388}
Matthew Xie19944102012-07-12 16:42:07 -0700389
San Mehat9d10b342010-01-18 09:51:02 -0800390bool TetherController::isTetheringStarted() {
Luke Huang91bd3e12019-08-20 11:33:52 +0800391 return mIsTetheringStarted;
San Mehat9d10b342010-01-18 09:51:02 -0800392}
393
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900394// dnsmasq can't parse commands larger than this due to the fixed-size buffer
395// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
396// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900397const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800398
Luke Huang8dc1cac2019-03-30 16:12:31 +0800399// TODO: Remove overload function and update this after NDC migration.
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700400int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700401 Fwmark fwmark;
402 fwmark.netId = netId;
403 fwmark.explicitlySelected = true;
404 fwmark.protectedFromVpn = true;
405 fwmark.permission = PERMISSION_SYSTEM;
406
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900407 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800408
Erik Kline1d065ba2016-06-08 13:24:45 +0900409 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900410 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700411 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800412
Lorenzo Colittic2841282015-11-25 22:13:57 +0900413 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700414 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900415 freeaddrinfo(res);
416 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000417 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900418 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900419 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800420 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800421 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800422
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900423 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
424 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800425 break;
426 }
427
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900428 daemonCmd += SEPARATOR;
429 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900430 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800431 }
432
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700433 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900434 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800435 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900436 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900437 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900438 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800439 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800440 }
441 }
442 return 0;
443}
444
Luke Huangb5733d72018-08-21 17:17:19 +0800445int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
Luke Huangb5733d72018-08-21 17:17:19 +0800446 auto dnsServers = toCstrVec(servers);
447 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
448}
449
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700450unsigned TetherController::getDnsNetId() {
451 return mDnsNetId;
452}
453
Erik Kline1d065ba2016-06-08 13:24:45 +0900454const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800455 return mDnsForwarders;
456}
457
Erik Kline1d065ba2016-06-08 13:24:45 +0900458bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900459 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800460 bool haveInterfaces = false;
461
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900462 for (const auto& ifname : mInterfaces) {
463 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
464 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800465 break;
466 }
467
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900468 daemonCmd += SEPARATOR;
469 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800470 haveInterfaces = true;
471 }
472
Erik Kline15079dd2018-05-18 23:10:56 +0900473 if (!haveInterfaces) {
474 mDnsmasqState.update_ifaces_cmd.clear();
475 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900476 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900477 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800478 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900479 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800480}
481
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800482int TetherController::tetherInterface(const char *interface) {
483 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700484 if (!isIfaceName(interface)) {
485 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800486 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700487 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800488
Erik Kline1d065ba2016-06-08 13:24:45 +0900489 if (!configureForIPv6Router(interface)) {
490 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800491 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900492 }
493 mInterfaces.push_back(interface);
494
495 if (!applyDnsInterfaces()) {
496 mInterfaces.pop_back();
497 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800498 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800499 } else {
500 return 0;
501 }
502}
503
San Mehat9d10b342010-01-18 09:51:02 -0800504int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800505 ALOGD("untetherInterface(%s)", interface);
506
Erik Kline1d065ba2016-06-08 13:24:45 +0900507 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
508 if (!strcmp(interface, it->c_str())) {
509 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800510
Erik Kline1d065ba2016-06-08 13:24:45 +0900511 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800512 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800513 }
514 }
515 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800516 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800517}
518
Erik Kline1d065ba2016-06-08 13:24:45 +0900519const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800520 return mInterfaces;
521}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900522
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900523int TetherController::setupIptablesHooks() {
524 int res;
525 res = setDefaults();
526 if (res < 0) {
527 return res;
528 }
529
530 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
531 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
532 // This is no longer optional and tethering will fail to start if it fails.
533 std::string mssRewriteCommand = StringPrintf(
534 "*mangle\n"
535 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
536 "COMMIT\n", LOCAL_MANGLE_FORWARD);
537
538 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
539 std::string defaultCommands = StringPrintf(
540 "*filter\n"
541 ":%s -\n"
542 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
543
544 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
545 if (res < 0) {
546 return res;
547 }
548
549 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
550 if (res < 0) {
551 return res;
552 }
553
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900554 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900555
556 return 0;
557}
558
559int TetherController::setDefaults() {
560 std::string v4Cmd = StringPrintf(
561 "*filter\n"
562 ":%s -\n"
563 "-A %s -j DROP\n"
564 "COMMIT\n"
565 "*nat\n"
566 ":%s -\n"
567 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
568
569 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900570 "*filter\n"
571 ":%s -\n"
572 "COMMIT\n"
573 "*raw\n"
574 ":%s -\n"
575 "COMMIT\n",
576 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900577
578 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
579 if (res < 0) {
580 return res;
581 }
582
583 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
584 if (res < 0) {
585 return res;
586 }
587
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900588 return 0;
589}
590
591int TetherController::enableNat(const char* intIface, const char* extIface) {
592 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
593
594 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900595 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900596 }
597
598 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
599 if (!strcmp(intIface, extIface)) {
600 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900601 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900602 }
603
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900604 if (isForwardingPairEnabled(intIface, extIface)) {
605 return 0;
606 }
607
608 // add this if we are the first enabled nat for this upstream
609 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900610 std::vector<std::string> v4Cmds = {
611 "*nat",
612 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
613 "COMMIT\n"
614 };
615
Luke Huangae038f82018-11-05 11:17:31 +0900616 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
617 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900618 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900619 if (!isAnyForwardingPairEnabled()) {
620 // unwind what's been done, but don't care about success - what more could we do?
621 setDefaults();
622 }
Luke Huang19b49c52018-10-22 12:12:05 +0900623 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900624 }
625 }
626
627 if (setForwardRules(true, intIface, extIface) != 0) {
628 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900629 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900630 setDefaults();
631 }
Luke Huang19b49c52018-10-22 12:12:05 +0900632 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900633 }
634
Hungming Chen1da90082020-02-14 20:24:16 +0800635 maybeStartBpf(extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900636 return 0;
637}
638
Luke Huangae038f82018-11-05 11:17:31 +0900639int TetherController::setTetherGlobalAlertRule() {
640 // Only add this if we are the first enabled nat
641 if (isAnyForwardingPairEnabled()) {
642 return 0;
643 }
644 const std::string cmds =
645 "*filter\n" +
646 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
647 "COMMIT\n";
648
649 return iptablesRestoreFunction(V4V6, cmds, nullptr);
650}
651
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900652int TetherController::setupIPv6CountersChain() {
653 // Only add this if we are the first enabled nat
654 if (isAnyForwardingPairEnabled()) {
655 return 0;
656 }
657
658 /*
659 * IPv6 tethering doesn't need the state-based conntrack rules, so
660 * it unconditionally jumps to the tether counters chain all the time.
661 */
Luke Huangae038f82018-11-05 11:17:31 +0900662 const std::string v6Cmds =
663 "*filter\n" +
664 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900665
Luke Huangae038f82018-11-05 11:17:31 +0900666 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900667}
668
669// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
670TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
671 const std::string& intIface, const std::string& extIface) {
672 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
673 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
674 if (it->second.iface == intIface) {
675 return &(it->second);
676 }
677 }
678 return nullptr;
679}
680
681void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
682 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
683 if (existingEntry != nullptr) {
684 existingEntry->active = true;
685 return;
686 }
687
688 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
689 .iface = intIface,
690 .active = true
691 }));
692}
693
694void TetherController::markForwardingPairDisabled(
695 const std::string& intIface, const std::string& extIface) {
696 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
697 if (existingEntry == nullptr) {
698 return;
699 }
700
701 existingEntry->active = false;
702}
703
704bool TetherController::isForwardingPairEnabled(
705 const std::string& intIface, const std::string& extIface) {
706 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
707 return existingEntry != nullptr && existingEntry->active;
708}
709
710bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
711 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
712 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
713 if (it->second.active) {
714 return true;
715 }
716 }
717 return false;
718}
719
720bool TetherController::isAnyForwardingPairEnabled() {
721 for (auto& it : mFwdIfaces) {
722 if (it.second.active) {
723 return true;
724 }
725 }
726 return false;
727}
728
729bool TetherController::tetherCountingRuleExists(
730 const std::string& iface1, const std::string& iface2) {
731 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
732 // is in the map regardless of its active status. Rules are added both ways so we check with
733 // the 2 combinations.
734 return findForwardingDownstream(iface1, iface2) != nullptr
735 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900736}
737
738/* static */
739std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
740 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
741}
742
743int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
744 const char *op = add ? "-A" : "-D";
745
746 std::string rpfilterCmd = StringPrintf(
747 "*raw\n"
748 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
749 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
750 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900751 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900752 }
753
754 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900755 "*raw",
756 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
757 LOCAL_RAW_PREROUTING, intIface),
758 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
759 LOCAL_RAW_PREROUTING, intIface),
760 "COMMIT",
761 "*filter",
762 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
763 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
764 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
765 intIface, extIface),
766 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
767 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900768 };
769
770 std::vector<std::string> v6 = {
771 "*filter",
772 };
773
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900774 // We only ever add tethering quota rules so that they stick.
775 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900776 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900777 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900778 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900779 v6.push_back(makeTetherCountingRule(extIface, intIface));
780 }
781
782 // Always make sure the drop rule is at the end.
783 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900784 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900785 if (add) {
786 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
787 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
788 }
789
790 v4.push_back("COMMIT\n");
791 v6.push_back("COMMIT\n");
792
793 // We only add IPv6 rules here, never remove them.
794 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
795 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
796 // unwind what's been done, but don't care about success - what more could we do?
797 if (add) {
798 setForwardRules(false, intIface, extIface);
799 }
Luke Huang19b49c52018-10-22 12:12:05 +0900800 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900801 }
802
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900803 if (add) {
804 addForwardingPair(intIface, extIface);
805 } else {
806 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900807 }
808
809 return 0;
810}
811
812int TetherController::disableNat(const char* intIface, const char* extIface) {
813 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900814 errno = ENODEV;
815 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900816 }
817
818 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900819 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900820 setDefaults();
821 }
Hungming Chen1da90082020-02-14 20:24:16 +0800822
823 maybeStopBpf(extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900824 return 0;
825}
826
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000827namespace {
828Result<void> validateOffloadRule(const TetherOffloadRuleParcel& rule) {
829 struct ethhdr hdr;
830
831 if (rule.inputInterfaceIndex <= 0) {
832 return Error(ENODEV) << "Invalid input interface " << rule.inputInterfaceIndex;
833 }
834 if (rule.outputInterfaceIndex <= 0) {
835 return Error(ENODEV) << "Invalid output interface " << rule.inputInterfaceIndex;
836 }
837 if (rule.prefixLength != 128) {
838 return Error(EINVAL) << "Prefix length must be 128, not " << rule.prefixLength;
839 }
840 if (rule.destination.size() != sizeof(in6_addr)) {
841 return Error(EAFNOSUPPORT) << "Invalid IP address length " << rule.destination.size();
842 }
843 if (rule.srcL2Address.size() != sizeof(hdr.h_source)) {
844 return Error(ENXIO) << "Invalid L2 src address length " << rule.srcL2Address.size();
845 }
846 if (rule.dstL2Address.size() != sizeof(hdr.h_dest)) {
847 return Error(ENXIO) << "Invalid L2 dst address length " << rule.dstL2Address.size();
848 }
849 return Result<void>();
850}
851} // namespace
852
853Result<void> TetherController::addOffloadRule(const TetherOffloadRuleParcel& rule) {
854 Result<void> res = validateOffloadRule(rule);
855 if (!res.ok()) return res;
856
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900857 ethhdr hdr = {
858 .h_proto = htons(ETH_P_IPV6),
859 };
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000860 memcpy(&hdr.h_dest, rule.dstL2Address.data(), sizeof(hdr.h_dest));
861 memcpy(&hdr.h_source, rule.srcL2Address.data(), sizeof(hdr.h_source));
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900862
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000863 // Only downstream supported for now.
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900864 TetherIngressKey key = {
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000865 .iif = static_cast<uint32_t>(rule.inputInterfaceIndex),
866 .neigh6 = *(const in6_addr*)rule.destination.data(),
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900867 };
868
869 TetherIngressValue value = {
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000870 static_cast<uint32_t>(rule.outputInterfaceIndex),
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900871 hdr,
872 };
873
874 return mBpfIngressMap.writeValue(key, value, BPF_ANY);
875}
876
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000877Result<void> TetherController::removeOffloadRule(const TetherOffloadRuleParcel& rule) {
878 Result<void> res = validateOffloadRule(rule);
879 if (!res.ok()) return res;
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900880
881 TetherIngressKey key = {
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000882 .iif = static_cast<uint32_t>(rule.inputInterfaceIndex),
883 .neigh6 = *(const in6_addr*)rule.destination.data(),
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900884 };
885
886 Result<void> ret = mBpfIngressMap.deleteValue(key);
887
888 // Silently return success if the rule did not exist.
889 if (!ret.ok() && ret.error().code() == ENOENT) return {};
890
891 return ret;
892}
893
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900894void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
895 for (TetherStats& existing : statsList) {
896 if (existing.addStatsIfMatch(stats)) {
897 return;
898 }
899 }
900 // No match. Insert a new interface pair.
901 statsList.push_back(stats);
902}
903
904/*
905 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900906 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900907 * pkts bytes target prot opt in out source destination
908 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
909 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
910 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
911 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
912 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900913 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900914 * pkts bytes target prot opt in out source destination
915 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
916 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
917 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900918 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900919int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900920 const std::string& statsOutput,
921 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800922 enum IndexOfIptChain {
923 ORIG_LINE,
924 PACKET_COUNTS,
925 BYTE_COUNTS,
926 HYPHEN,
927 IFACE0_NAME,
928 IFACE1_NAME,
929 SOURCE,
930 DESTINATION
931 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900932 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900933 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900934
waynema71a0b592018-11-21 13:31:34 +0800935 static const std::string NUM = "(\\d+)";
936 static const std::string IFACE = "([^\\s]+)";
937 static const std::string DST = "(0.0.0.0/0|::/0)";
938 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
939 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
940 "\\s+" + DST + "\\s+" + DST;
941 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900942
waynema71a0b592018-11-21 13:31:34 +0800943 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
944 int headerLine = 0;
945 for (const std::string& line : lines) {
946 // Skip headers.
947 if (headerLine < 2) {
948 if (line.empty()) {
949 ALOGV("Empty header while parsing tethering stats");
950 return -EREMOTEIO;
951 }
952 headerLine++;
953 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900954 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900955
waynema71a0b592018-11-21 13:31:34 +0800956 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900957
waynema71a0b592018-11-21 13:31:34 +0800958 extraProcessingInfo = line;
959 std::smatch matches;
960 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
961 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
962 // IPv4 has "--" indicating what to do with fragments...
963 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
964 // ... but IPv6 does not.
965 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
966 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
967 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
968 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
969 std::string iface0 = matches[IFACE0_NAME].str();
970 std::string iface1 = matches[IFACE1_NAME].str();
971 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900972
waynema71a0b592018-11-21 13:31:34 +0800973 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
974 " rest=<%s> orig line=<%s>",
975 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900976 /*
977 * The following assumes that the 1st rule has in:extIface out:intIface,
978 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900979 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900980 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900981 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800982 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
983 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900984 stats.intIface = iface0;
985 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900986 stats.txPackets = packets;
987 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900988 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800989 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
990 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900991 stats.rxPackets = packets;
992 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900993 }
994 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900995 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900996 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900997 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900998 }
999 }
1000
1001 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +09001002 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001003 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001004 }
1005 return 0;
1006}
1007
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001008StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001009 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001010 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001011
1012 for (const IptablesTarget target : {V4, V6}) {
1013 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +09001014 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001015 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
1016 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001017 }
1018
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001019 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001020 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
1021 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001022 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001023 }
1024 }
1025
Hungming Chen68dade32020-02-20 13:50:56 +08001026 if (!mBpfStatsMap.isValid()) {
1027 return statsList;
1028 }
Hungming Chenc2e95fb2020-02-19 17:41:30 +08001029
Hungming Chen68dade32020-02-20 13:50:56 +08001030 const auto processTetherStats = [this, &statsList](const uint32_t& key,
1031 const TetherStatsValue& value,
1032 const BpfMap<uint32_t, TetherStatsValue>&) {
1033 auto ifname = mIfaceIndexNameMap.readValue(key);
1034 if (!ifname.ok()) {
1035 // Keep on going regardless to parse as much as possible.
1036 return Result<void>();
Hungming Chenc2e95fb2020-02-19 17:41:30 +08001037 }
Hungming Chen68dade32020-02-20 13:50:56 +08001038 // Because the same interface name can have different interface IDs over time, there might
1039 // already be a TetherStats in the list with this interface name. This is fine because
1040 // addStats will increment an existing TetherStats if there is one in the list already,
1041 // and add a new TetherStats to the list if there isn't.
1042 addStats(statsList,
1043 {kBpfOffloadInterface, ifname.value().name, static_cast<int64_t>(value.rxBytes),
1044 static_cast<int64_t>(value.rxPackets), static_cast<int64_t>(value.txBytes),
1045 static_cast<int64_t>(value.txPackets)});
1046 return Result<void>();
1047 };
1048
1049 auto ret = mBpfStatsMap.iterateWithValue(processTetherStats);
1050 if (!ret.ok()) {
1051 // Ignore error to return the non-BPF tether stats result.
1052 ALOGE("Error processing tether stats from BPF maps: %s", ret.error().message().c_str());
Hungming Chenc2e95fb2020-02-19 17:41:30 +08001053 }
1054
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001055 return statsList;
1056}
1057
Hungming Chen1da90082020-02-14 20:24:16 +08001058void TetherController::maybeStartBpf(const char* extIface) {
Maciej Żenczykowskiaef13012020-02-18 17:13:09 -08001059 if (!bpf::isBpfSupported()) return;
1060
Hungming Chen1da90082020-02-14 20:24:16 +08001061 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
1062 int ifIndex = if_nametoindex(extIface);
1063 if (!ifIndex) {
1064 ALOGE("Fail to get index for interface %s", extIface);
1065 return;
1066 }
1067
1068 auto isEthernet = android::net::isEthernet(extIface);
1069 if (!isEthernet.ok()) {
1070 ALOGE("isEthernet(%s[%d]) failure: %s", extIface, ifIndex,
1071 isEthernet.error().message().c_str());
1072 return;
1073 }
1074
1075 int rv = getTetherIngressProgFd(isEthernet.value());
1076 if (rv < 0) {
1077 ALOGE("getTetherIngressProgFd(%d) failure: %s", isEthernet.value(), strerror(-rv));
1078 return;
1079 }
1080 unique_fd tetherProgFd(rv);
1081
1082 rv = tcFilterAddDevIngressTether(ifIndex, tetherProgFd, isEthernet.value());
1083 if (rv) {
1084 ALOGE("tcFilterAddDevIngressTether(%d[%s], %d) failure: %s", ifIndex, extIface,
1085 isEthernet.value(), strerror(-rv));
1086 return;
1087 }
1088}
1089
1090void TetherController::maybeStopBpf(const char* extIface) {
Maciej Żenczykowskiaef13012020-02-18 17:13:09 -08001091 if (!bpf::isBpfSupported()) return;
1092
Hungming Chen1da90082020-02-14 20:24:16 +08001093 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
1094 int ifIndex = if_nametoindex(extIface);
1095 if (!ifIndex) {
1096 ALOGE("Fail to get index for interface %s", extIface);
1097 return;
1098 }
1099
1100 int rv = tcFilterDelDevIngressTether(ifIndex);
1101 if (rv < 0) {
1102 ALOGE("tcFilterDelDevIngressTether(%d[%s]) failure: %s", ifIndex, extIface, strerror(-rv));
1103 }
1104}
1105
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001106void TetherController::dumpIfaces(DumpWriter& dw) {
1107 dw.println("Interface pairs:");
1108
1109 ScopedIndent ifaceIndent(dw);
1110 for (const auto& it : mFwdIfaces) {
1111 dw.println("%s -> %s %s", it.first.c_str(), it.second.iface.c_str(),
1112 (it.second.active ? "ACTIVE" : "DISABLED"));
1113 }
1114}
1115
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001116namespace {
1117
1118std::string l2ToString(const uint8_t* addr, size_t len) {
1119 std::string str;
1120
1121 if (len == 0) return str;
1122
1123 StringAppendF(&str, "%02x", addr[0]);
1124 for (size_t i = 1; i < len; i++) {
1125 StringAppendF(&str, ":%02x", addr[i]);
1126 }
1127
1128 return str;
1129}
1130
1131} // namespace
1132
1133void TetherController::dumpBpf(DumpWriter& dw) {
1134 if (!mBpfIngressMap.isValid() || !mBpfStatsMap.isValid()) {
1135 dw.println("BPF not supported");
1136 return;
1137 }
1138
1139 dw.println("BPF ingress map: iif v6addr -> oif srcmac dstmac ethertype");
1140 const auto printIngressMap = [&dw](const TetherIngressKey& key, const TetherIngressValue& value,
1141 const BpfMap<TetherIngressKey, TetherIngressValue>&) {
1142 char addr[INET6_ADDRSTRLEN];
1143 std::string src = l2ToString(value.macHeader.h_source, sizeof(value.macHeader.h_source));
1144 std::string dst = l2ToString(value.macHeader.h_dest, sizeof(value.macHeader.h_dest));
1145 inet_ntop(AF_INET6, &key.neigh6, addr, sizeof(addr));
1146
1147 dw.println("%d %s -> %d %s %s %04x", key.iif, addr, value.oif, src.c_str(), dst.c_str(),
1148 ntohs(value.macHeader.h_proto));
1149
1150 return Result<void>();
1151 };
1152
1153 dw.incIndent();
1154 auto ret = mBpfIngressMap.iterateWithValue(printIngressMap);
1155 if (!ret.ok()) {
1156 dw.println("Error printing BPF ingress map: %s", ret.error().message().c_str());
1157 }
1158 dw.decIndent();
1159
1160 dw.println("BPF stats (downlink): iif -> packets bytes errors");
1161 const auto printStatsMap = [&dw](const uint32_t& key, const TetherStatsValue& value,
1162 const BpfMap<uint32_t, TetherStatsValue>&) {
1163 dw.println("%d -> %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxPackets, value.rxBytes,
1164 value.rxErrors);
1165
1166 return Result<void>();
1167 };
1168
1169 dw.incIndent();
1170 ret = mBpfStatsMap.iterateWithValue(printStatsMap);
1171 if (!ret.ok()) {
1172 dw.println("Error printing BPF stats map: %s", ret.error().message().c_str());
1173 }
1174 dw.decIndent();
1175}
1176
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001177void TetherController::dump(DumpWriter& dw) {
1178 std::lock_guard guard(lock);
1179
1180 ScopedIndent tetherControllerIndent(dw);
1181 dw.println("TetherController");
1182 dw.incIndent();
1183
1184 dw.println("Forwarding requests: " + Join(mForwardingRequests, ' '));
1185 if (mDnsNetId != 0) {
1186 dw.println(StringPrintf("DNS: netId %d servers [%s]", mDnsNetId,
1187 Join(mDnsForwarders, ", ").c_str()));
1188 }
1189 if (mDaemonPid != 0) {
1190 dw.println("dnsmasq PID: %d", mDaemonPid);
1191 }
1192
1193 dumpIfaces(dw);
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001194 dw.println("");
1195 dumpBpf(dw);
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001196}
1197
Lorenzo Colittie20a5262017-05-09 18:30:44 +09001198} // namespace net
1199} // namespace android