blob: cc3b49c0b0e5c51255d2394bebd5811e6fe5149d [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 Chen68dade32020-02-20 13:50:56 +080080
81// Dummy interface name, the name needs to be longer than 16 characters so it can never conflict
82// with a real interface name. See also IFNAMSIZ.
Hungming Chenc2e95fb2020-02-19 17:41:30 +080083constexpr const char kBpfOffloadInterface[] = "BPFOffloadInterface";
Lorenzo Colitti799625c2015-02-25 12:52:00 +090084
Erik Kline5f0358b2018-02-16 15:08:09 +090085// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
86constexpr const char kDnsmasqUsername[] = "dns_tether";
87
Lorenzo Colitti799625c2015-02-25 12:52:00 +090088bool writeToFile(const char* filename, const char* value) {
Nick Kralevichb95c60c2016-11-19 09:09:16 -080089 int fd = open(filename, O_WRONLY | O_CLOEXEC);
Nicolas Geoffrayafd40372015-03-16 11:58:06 +000090 if (fd < 0) {
91 ALOGE("Failed to open %s: %s", filename, strerror(errno));
92 return false;
93 }
94
95 const ssize_t len = strlen(value);
96 if (write(fd, value, len) != len) {
97 ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
98 close(fd);
99 return false;
100 }
101 close(fd);
102 return true;
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900103}
104
Erik Kline93f9b222017-10-22 21:24:58 +0900105// TODO: Consider altering TCP and UDP timeouts as well.
106void configureForTethering(bool enabled) {
107 writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
108}
109
Erik Kline1d065ba2016-06-08 13:24:45 +0900110bool configureForIPv6Router(const char *interface) {
111 return (InterfaceController::setEnableIPv6(interface, 0) == 0)
112 && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
Erik Kline6cddf512016-08-09 15:28:42 +0900113 && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
114 && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
Erik Kline1d065ba2016-06-08 13:24:45 +0900115 && (InterfaceController::setEnableIPv6(interface, 1) == 0);
116}
117
118void configureForIPv6Client(const char *interface) {
119 InterfaceController::setAcceptIPv6Ra(interface, 1);
Erik Kline6cddf512016-08-09 15:28:42 +0900120 InterfaceController::setAcceptIPv6Dad(interface, 1);
121 InterfaceController::setIPv6DadTransmits(interface, "1");
Erik Kline1d065ba2016-06-08 13:24:45 +0900122 InterfaceController::setEnableIPv6(interface, 0);
123}
124
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900125bool inBpToolsMode() {
126 // In BP tools mode, do not disable IP forwarding
127 char bootmode[PROPERTY_VALUE_MAX] = {0};
128 property_get("ro.bootmode", bootmode, "unknown");
129 return !strcmp(BP_TOOLS_MODE, bootmode);
130}
131
132} // namespace
133
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900134auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
135
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900136const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
137 "*filter\n"
138 "-nvx -L %s\n"
139 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
140
Erik Kline15079dd2018-05-18 23:10:56 +0900141int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
142 if (cmd.empty()) return 0;
143
Erik Klineb31fd692018-06-06 20:50:11 +0900144 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900145 // Send the trailing \0 as well.
146 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900147 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900148 errno = EREMOTEIO;
149 return -1;
150 }
151 return 0;
152}
153
154void TetherController::DnsmasqState::clear() {
155 update_ifaces_cmd.clear();
156 update_dns_cmd.clear();
157}
158
159int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
160 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
161}
162
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700163TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900164 if (inBpToolsMode()) {
165 enableForwarding(BP_TOOLS_MODE);
166 } else {
167 setIpFwdEnabled();
168 }
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800169 maybeInitMaps();
San Mehat9d10b342010-01-18 09:51:02 -0800170}
171
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900172bool TetherController::setIpFwdEnabled() {
173 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900174 bool disable = mForwardingRequests.empty();
175 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900176 ALOGD("Setting IP forward enable = %s", value);
177 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
178 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900179 if (disable) {
180 // Turning off the forwarding sysconf in the kernel has the side effect
181 // of turning on ICMP redirect, which is a security hazard.
182 // Turn ICMP redirect back off immediately.
183 int rv = InterfaceController::disableIcmpRedirects();
184 success &= (rv == 0);
185 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900186 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800187}
188
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900189bool TetherController::enableForwarding(const char* requester) {
190 // Don't return an error if this requester already requested forwarding. Only return errors for
191 // things that the caller caller needs to care about, such as "couldn't write to the file to
192 // enable forwarding".
193 mForwardingRequests.insert(requester);
194 return setIpFwdEnabled();
195}
San Mehat9d10b342010-01-18 09:51:02 -0800196
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900197bool TetherController::disableForwarding(const char* requester) {
198 mForwardingRequests.erase(requester);
199 return setIpFwdEnabled();
200}
San Mehat9d10b342010-01-18 09:51:02 -0800201
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800202void TetherController::maybeInitMaps() {
203 if (!bpf::isBpfSupported()) return;
204
205 // Used for parsing tether stats from BPF maps. If open the map failed, skip to open
206 // tether BPF offload maps.
207 mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH);
208 if (!mIfaceIndexNameMap.isValid()) return;
209
210 // Open BPF maps, ignoring errors because the device might not support BPF offload.
211 int fd = getTetherIngressMapFd();
Maciej Żenczykowski109ac532020-02-19 10:36:44 -0800212 if (fd >= 0) {
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800213 mBpfIngressMap.reset(fd);
Maciej Żenczykowski109ac532020-02-19 10:36:44 -0800214 mBpfIngressMap.clear();
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800215 }
216 fd = getTetherStatsMapFd();
Maciej Żenczykowski109ac532020-02-19 10:36:44 -0800217 if (fd >= 0) {
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800218 mBpfStatsMap.reset(fd);
Maciej Żenczykowski109ac532020-02-19 10:36:44 -0800219 mBpfStatsMap.clear();
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800220 }
221}
222
Luke Huang728cf4c2019-03-14 19:43:02 +0800223const std::set<std::string>& TetherController::getIpfwdRequesterList() const {
224 return mForwardingRequests;
San Mehat9d10b342010-01-18 09:51:02 -0800225}
226
Luke Huang91bd3e12019-08-20 11:33:52 +0800227int TetherController::startTethering(bool usingLegacyDnsProxy, int num_addrs, char** dhcp_ranges) {
228 if (!usingLegacyDnsProxy && num_addrs == 0) {
229 // Both DHCP and DnsProxy are disabled, we don't need to start dnsmasq
230 configureForTethering(true);
231 mIsTetheringStarted = true;
232 return 0;
233 }
234
235 if (mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000236 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800237 errno = EBUSY;
Luke Huangb5733d72018-08-21 17:17:19 +0800238 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800239 }
240
Steve Block7b984e32011-12-20 16:22:42 +0000241 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800242
George Burgess IVe3dc1312019-02-28 11:27:04 -0800243 unique_fd pipeRead, pipeWrite;
244 if (!Pipe(&pipeRead, &pipeWrite, O_CLOEXEC)) {
Luke Huangb5733d72018-08-21 17:17:19 +0800245 int res = errno;
Luke Huang94c43a12019-02-14 19:51:38 +0800246 ALOGE("pipe2() failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800247 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800248 }
249
Luke Huang94c43a12019-02-14 19:51:38 +0800250 // Set parameters
251 Fwmark fwmark;
252 fwmark.netId = NetworkController::LOCAL_NET_ID;
253 fwmark.explicitlySelected = true;
254 fwmark.protectedFromVpn = true;
255 fwmark.permission = PERMISSION_SYSTEM;
256 char markStr[UINT32_HEX_STRLEN];
257 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800258
Luke Huang94c43a12019-02-14 19:51:38 +0800259 std::vector<const std::string> argVector = {
Erik Kline5f0358b2018-02-16 15:08:09 +0900260 "/system/bin/dnsmasq",
261 "--keep-in-foreground",
262 "--no-resolv",
263 "--no-poll",
264 "--dhcp-authoritative",
265 // TODO: pipe through metered status from ConnService
266 "--dhcp-option-force=43,ANDROID_METERED",
267 "--pid-file",
Luke Huang94c43a12019-02-14 19:51:38 +0800268 "--listen-mark",
269 markStr,
270 "--user",
271 kDnsmasqUsername,
272 };
San Mehat9d10b342010-01-18 09:51:02 -0800273
Luke Huang91bd3e12019-08-20 11:33:52 +0800274 if (!usingLegacyDnsProxy) {
275 argVector.push_back("--port=0");
276 }
277
278 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is passed.
Luke Huang94c43a12019-02-14 19:51:38 +0800279 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
280 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
281 dhcp_ranges[addrIndex + 1]));
San Mehat9d10b342010-01-18 09:51:02 -0800282 }
283
George Burgess IVe3dc1312019-02-28 11:27:04 -0800284 std::vector<char*> args(argVector.size() + 1);
Luke Huang94c43a12019-02-14 19:51:38 +0800285 for (unsigned i = 0; i < argVector.size(); i++) {
286 args[i] = (char*)argVector[i].c_str();
287 }
288
289 /*
290 * TODO: Create a monitoring thread to handle and restart
291 * the daemon if it exits prematurely
292 */
Luke Huang40962442019-02-26 11:46:10 +0800293
294 // Note that don't modify any memory between vfork and execv.
295 // Changing state of file descriptors would be fine. See posix_spawn_file_actions_add*
296 // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
297 // duplicated fd.
298 posix_spawn_file_actions_t fa;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700299 int res = posix_spawn_file_actions_init(&fa);
Luke Huang40962442019-02-26 11:46:10 +0800300 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700301 ALOGE("posix_spawn_file_actions_init failed (%s)", strerror(res));
302 return -res;
303 }
304 const android::base::ScopeGuard faGuard = [&] { posix_spawn_file_actions_destroy(&fa); };
305 res = posix_spawn_file_actions_adddup2(&fa, pipeRead.get(), STDIN_FILENO);
306 if (res) {
307 ALOGE("posix_spawn_file_actions_adddup2 failed (%s)", strerror(res));
Luke Huang94c43a12019-02-14 19:51:38 +0800308 return -res;
309 }
310
Luke Huang40962442019-02-26 11:46:10 +0800311 posix_spawnattr_t attr;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700312 res = posix_spawnattr_init(&attr);
Luke Huang40962442019-02-26 11:46:10 +0800313 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700314 ALOGE("posix_spawnattr_init failed (%s)", strerror(res));
315 return -res;
316 }
317 const android::base::ScopeGuard attrGuard = [&] { posix_spawnattr_destroy(&attr); };
318 res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK);
319 if (res) {
320 ALOGE("posix_spawnattr_setflags failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800321 return -res;
322 }
323
324 pid_t pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800325 res = posix_spawn(&pid, args[0], &fa, &attr, &args[0], nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800326 if (res) {
327 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800328 return -res;
329 }
Luke Huang94c43a12019-02-14 19:51:38 +0800330 mDaemonPid = pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800331 mDaemonFd = pipeWrite.release();
Luke Huang94c43a12019-02-14 19:51:38 +0800332 configureForTethering(true);
Luke Huang91bd3e12019-08-20 11:33:52 +0800333 mIsTetheringStarted = true;
Luke Huang94c43a12019-02-14 19:51:38 +0800334 applyDnsInterfaces();
335 ALOGD("Tethering services running");
336
San Mehat9d10b342010-01-18 09:51:02 -0800337 return 0;
338}
339
Luke Huangb5733d72018-08-21 17:17:19 +0800340std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
341 std::vector<char*> addrsCstrVec{};
342 addrsCstrVec.reserve(addrs.size());
343 for (const auto& addr : addrs) {
344 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
345 }
346 return addrsCstrVec;
347}
348
Luke Huang91bd3e12019-08-20 11:33:52 +0800349int TetherController::startTethering(bool usingLegacyDnsProxy,
350 const std::vector<std::string>& dhcpRanges) {
Luke Huangb5733d72018-08-21 17:17:19 +0800351 struct in_addr v4_addr;
352 for (const auto& dhcpRange : dhcpRanges) {
353 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
354 return -EINVAL;
355 }
356 }
357 auto dhcp_ranges = toCstrVec(dhcpRanges);
Luke Huang91bd3e12019-08-20 11:33:52 +0800358 return startTethering(usingLegacyDnsProxy, dhcp_ranges.size(), dhcp_ranges.data());
Luke Huangb5733d72018-08-21 17:17:19 +0800359}
360
San Mehat9d10b342010-01-18 09:51:02 -0800361int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900362 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800363
Luke Huang91bd3e12019-08-20 11:33:52 +0800364 if (!mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000365 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800366 return 0;
367 }
368
Luke Huang91bd3e12019-08-20 11:33:52 +0800369 mIsTetheringStarted = false;
370 // dnsmasq is not started
371 if (mDaemonPid == 0) {
372 return 0;
373 }
374
Steve Block7b984e32011-12-20 16:22:42 +0000375 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800376
377 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700378 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800379 mDaemonPid = 0;
380 close(mDaemonFd);
381 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900382 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000383 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800384 return 0;
385}
Matthew Xie19944102012-07-12 16:42:07 -0700386
San Mehat9d10b342010-01-18 09:51:02 -0800387bool TetherController::isTetheringStarted() {
Luke Huang91bd3e12019-08-20 11:33:52 +0800388 return mIsTetheringStarted;
San Mehat9d10b342010-01-18 09:51:02 -0800389}
390
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900391// dnsmasq can't parse commands larger than this due to the fixed-size buffer
392// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
393// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900394const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800395
Luke Huang8dc1cac2019-03-30 16:12:31 +0800396// TODO: Remove overload function and update this after NDC migration.
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700397int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700398 Fwmark fwmark;
399 fwmark.netId = netId;
400 fwmark.explicitlySelected = true;
401 fwmark.protectedFromVpn = true;
402 fwmark.permission = PERMISSION_SYSTEM;
403
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900404 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800405
Erik Kline1d065ba2016-06-08 13:24:45 +0900406 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900407 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700408 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800409
Lorenzo Colittic2841282015-11-25 22:13:57 +0900410 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700411 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900412 freeaddrinfo(res);
413 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000414 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900415 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900416 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800417 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800418 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800419
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900420 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
421 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800422 break;
423 }
424
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900425 daemonCmd += SEPARATOR;
426 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900427 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800428 }
429
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700430 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900431 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800432 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900433 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900434 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900435 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800436 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800437 }
438 }
439 return 0;
440}
441
Luke Huangb5733d72018-08-21 17:17:19 +0800442int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
Luke Huangb5733d72018-08-21 17:17:19 +0800443 auto dnsServers = toCstrVec(servers);
444 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
445}
446
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700447unsigned TetherController::getDnsNetId() {
448 return mDnsNetId;
449}
450
Erik Kline1d065ba2016-06-08 13:24:45 +0900451const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800452 return mDnsForwarders;
453}
454
Erik Kline1d065ba2016-06-08 13:24:45 +0900455bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900456 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800457 bool haveInterfaces = false;
458
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900459 for (const auto& ifname : mInterfaces) {
460 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
461 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800462 break;
463 }
464
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900465 daemonCmd += SEPARATOR;
466 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800467 haveInterfaces = true;
468 }
469
Erik Kline15079dd2018-05-18 23:10:56 +0900470 if (!haveInterfaces) {
471 mDnsmasqState.update_ifaces_cmd.clear();
472 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900473 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900474 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800475 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900476 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800477}
478
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800479int TetherController::tetherInterface(const char *interface) {
480 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700481 if (!isIfaceName(interface)) {
482 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800483 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700484 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800485
Erik Kline1d065ba2016-06-08 13:24:45 +0900486 if (!configureForIPv6Router(interface)) {
487 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800488 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900489 }
490 mInterfaces.push_back(interface);
491
492 if (!applyDnsInterfaces()) {
493 mInterfaces.pop_back();
494 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800495 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800496 } else {
497 return 0;
498 }
499}
500
San Mehat9d10b342010-01-18 09:51:02 -0800501int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800502 ALOGD("untetherInterface(%s)", interface);
503
Erik Kline1d065ba2016-06-08 13:24:45 +0900504 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
505 if (!strcmp(interface, it->c_str())) {
506 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800507
Erik Kline1d065ba2016-06-08 13:24:45 +0900508 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800509 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800510 }
511 }
512 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800513 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800514}
515
Erik Kline1d065ba2016-06-08 13:24:45 +0900516const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800517 return mInterfaces;
518}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900519
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900520int TetherController::setupIptablesHooks() {
521 int res;
522 res = setDefaults();
523 if (res < 0) {
524 return res;
525 }
526
527 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
528 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
529 // This is no longer optional and tethering will fail to start if it fails.
530 std::string mssRewriteCommand = StringPrintf(
531 "*mangle\n"
532 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
533 "COMMIT\n", LOCAL_MANGLE_FORWARD);
534
535 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
536 std::string defaultCommands = StringPrintf(
537 "*filter\n"
538 ":%s -\n"
539 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
540
541 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
542 if (res < 0) {
543 return res;
544 }
545
546 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
547 if (res < 0) {
548 return res;
549 }
550
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900551 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900552
553 return 0;
554}
555
556int TetherController::setDefaults() {
557 std::string v4Cmd = StringPrintf(
558 "*filter\n"
559 ":%s -\n"
560 "-A %s -j DROP\n"
561 "COMMIT\n"
562 "*nat\n"
563 ":%s -\n"
564 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
565
566 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900567 "*filter\n"
568 ":%s -\n"
569 "COMMIT\n"
570 "*raw\n"
571 ":%s -\n"
572 "COMMIT\n",
573 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900574
575 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
576 if (res < 0) {
577 return res;
578 }
579
580 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
581 if (res < 0) {
582 return res;
583 }
584
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900585 return 0;
586}
587
588int TetherController::enableNat(const char* intIface, const char* extIface) {
589 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
590
591 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900592 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900593 }
594
595 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
596 if (!strcmp(intIface, extIface)) {
597 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900598 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900599 }
600
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900601 if (isForwardingPairEnabled(intIface, extIface)) {
602 return 0;
603 }
604
605 // add this if we are the first enabled nat for this upstream
606 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900607 std::vector<std::string> v4Cmds = {
608 "*nat",
609 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
610 "COMMIT\n"
611 };
612
Luke Huangae038f82018-11-05 11:17:31 +0900613 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
614 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900615 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900616 if (!isAnyForwardingPairEnabled()) {
617 // unwind what's been done, but don't care about success - what more could we do?
618 setDefaults();
619 }
Luke Huang19b49c52018-10-22 12:12:05 +0900620 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900621 }
622 }
623
624 if (setForwardRules(true, intIface, extIface) != 0) {
625 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900626 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900627 setDefaults();
628 }
Luke Huang19b49c52018-10-22 12:12:05 +0900629 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900630 }
631
Hungming Chen1da90082020-02-14 20:24:16 +0800632 maybeStartBpf(extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900633 return 0;
634}
635
Luke Huangae038f82018-11-05 11:17:31 +0900636int TetherController::setTetherGlobalAlertRule() {
637 // Only add this if we are the first enabled nat
638 if (isAnyForwardingPairEnabled()) {
639 return 0;
640 }
641 const std::string cmds =
642 "*filter\n" +
643 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
644 "COMMIT\n";
645
646 return iptablesRestoreFunction(V4V6, cmds, nullptr);
647}
648
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900649int TetherController::setupIPv6CountersChain() {
650 // Only add this if we are the first enabled nat
651 if (isAnyForwardingPairEnabled()) {
652 return 0;
653 }
654
655 /*
656 * IPv6 tethering doesn't need the state-based conntrack rules, so
657 * it unconditionally jumps to the tether counters chain all the time.
658 */
Luke Huangae038f82018-11-05 11:17:31 +0900659 const std::string v6Cmds =
660 "*filter\n" +
661 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900662
Luke Huangae038f82018-11-05 11:17:31 +0900663 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900664}
665
666// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
667TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
668 const std::string& intIface, const std::string& extIface) {
669 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
670 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
671 if (it->second.iface == intIface) {
672 return &(it->second);
673 }
674 }
675 return nullptr;
676}
677
678void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
679 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
680 if (existingEntry != nullptr) {
681 existingEntry->active = true;
682 return;
683 }
684
685 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
686 .iface = intIface,
687 .active = true
688 }));
689}
690
691void TetherController::markForwardingPairDisabled(
692 const std::string& intIface, const std::string& extIface) {
693 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
694 if (existingEntry == nullptr) {
695 return;
696 }
697
698 existingEntry->active = false;
699}
700
701bool TetherController::isForwardingPairEnabled(
702 const std::string& intIface, const std::string& extIface) {
703 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
704 return existingEntry != nullptr && existingEntry->active;
705}
706
707bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
708 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
709 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
710 if (it->second.active) {
711 return true;
712 }
713 }
714 return false;
715}
716
717bool TetherController::isAnyForwardingPairEnabled() {
718 for (auto& it : mFwdIfaces) {
719 if (it.second.active) {
720 return true;
721 }
722 }
723 return false;
724}
725
726bool TetherController::tetherCountingRuleExists(
727 const std::string& iface1, const std::string& iface2) {
728 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
729 // is in the map regardless of its active status. Rules are added both ways so we check with
730 // the 2 combinations.
731 return findForwardingDownstream(iface1, iface2) != nullptr
732 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900733}
734
735/* static */
736std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
737 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
738}
739
740int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
741 const char *op = add ? "-A" : "-D";
742
743 std::string rpfilterCmd = StringPrintf(
744 "*raw\n"
745 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
746 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
747 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900748 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900749 }
750
751 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900752 "*raw",
753 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
754 LOCAL_RAW_PREROUTING, intIface),
755 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
756 LOCAL_RAW_PREROUTING, intIface),
757 "COMMIT",
758 "*filter",
759 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
760 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
761 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
762 intIface, extIface),
763 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
764 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900765 };
766
767 std::vector<std::string> v6 = {
768 "*filter",
769 };
770
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900771 // We only ever add tethering quota rules so that they stick.
772 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900773 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900774 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900775 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900776 v6.push_back(makeTetherCountingRule(extIface, intIface));
777 }
778
779 // Always make sure the drop rule is at the end.
780 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900781 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900782 if (add) {
783 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
784 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
785 }
786
787 v4.push_back("COMMIT\n");
788 v6.push_back("COMMIT\n");
789
790 // We only add IPv6 rules here, never remove them.
791 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
792 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
793 // unwind what's been done, but don't care about success - what more could we do?
794 if (add) {
795 setForwardRules(false, intIface, extIface);
796 }
Luke Huang19b49c52018-10-22 12:12:05 +0900797 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900798 }
799
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900800 if (add) {
801 addForwardingPair(intIface, extIface);
802 } else {
803 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900804 }
805
806 return 0;
807}
808
809int TetherController::disableNat(const char* intIface, const char* extIface) {
810 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900811 errno = ENODEV;
812 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900813 }
814
815 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900816 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900817 setDefaults();
818 }
Hungming Chen1da90082020-02-14 20:24:16 +0800819
820 maybeStopBpf(extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900821 return 0;
822}
823
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900824Result<void> TetherController::addDownstreamIpv6Rule(int intIfaceIndex, int extIfaceIndex,
825 const std::vector<uint8_t>& ipAddress,
826 const std::vector<uint8_t>& srcL2Address,
827 const std::vector<uint8_t>& dstL2Address) {
828 ethhdr hdr = {
829 .h_proto = htons(ETH_P_IPV6),
830 };
831 if (ipAddress.size() != sizeof(in6_addr)) {
832 return Error(EINVAL) << "Invalid IP address length " << ipAddress.size();
833 }
834 if (srcL2Address.size() != sizeof(hdr.h_source)) {
835 return Error(EINVAL) << "Invalid L2 src address length " << srcL2Address.size();
836 }
837 if (dstL2Address.size() != sizeof(hdr.h_dest)) {
838 return Error(EINVAL) << "Invalid L2 dst address length " << dstL2Address.size();
839 }
840 memcpy(&hdr.h_dest, dstL2Address.data(), sizeof(hdr.h_dest));
841 memcpy(&hdr.h_source, srcL2Address.data(), sizeof(hdr.h_source));
842
843 TetherIngressKey key = {
844 .iif = static_cast<uint32_t>(extIfaceIndex),
845 .neigh6 = *(const in6_addr*)ipAddress.data(),
846 };
847
848 TetherIngressValue value = {
849 static_cast<uint32_t>(intIfaceIndex),
850 hdr,
851 };
852
853 return mBpfIngressMap.writeValue(key, value, BPF_ANY);
854}
855
856Result<void> TetherController::removeDownstreamIpv6Rule(int extIfaceIndex,
857 const std::vector<uint8_t>& ipAddress) {
858 if (ipAddress.size() != sizeof(in6_addr)) {
859 return Error(EINVAL) << "Invalid IP address length " << ipAddress.size();
860 }
861
862 TetherIngressKey key = {
863 .iif = static_cast<uint32_t>(extIfaceIndex),
864 .neigh6 = *(const in6_addr*)ipAddress.data(),
865 };
866
867 Result<void> ret = mBpfIngressMap.deleteValue(key);
868
869 // Silently return success if the rule did not exist.
870 if (!ret.ok() && ret.error().code() == ENOENT) return {};
871
872 return ret;
873}
874
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900875void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
876 for (TetherStats& existing : statsList) {
877 if (existing.addStatsIfMatch(stats)) {
878 return;
879 }
880 }
881 // No match. Insert a new interface pair.
882 statsList.push_back(stats);
883}
884
885/*
886 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900887 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900888 * pkts bytes target prot opt in out source destination
889 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
890 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
891 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
892 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
893 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900894 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900895 * pkts bytes target prot opt in out source destination
896 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
897 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
898 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900899 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900900int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900901 const std::string& statsOutput,
902 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800903 enum IndexOfIptChain {
904 ORIG_LINE,
905 PACKET_COUNTS,
906 BYTE_COUNTS,
907 HYPHEN,
908 IFACE0_NAME,
909 IFACE1_NAME,
910 SOURCE,
911 DESTINATION
912 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900913 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900914 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900915
waynema71a0b592018-11-21 13:31:34 +0800916 static const std::string NUM = "(\\d+)";
917 static const std::string IFACE = "([^\\s]+)";
918 static const std::string DST = "(0.0.0.0/0|::/0)";
919 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
920 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
921 "\\s+" + DST + "\\s+" + DST;
922 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900923
waynema71a0b592018-11-21 13:31:34 +0800924 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
925 int headerLine = 0;
926 for (const std::string& line : lines) {
927 // Skip headers.
928 if (headerLine < 2) {
929 if (line.empty()) {
930 ALOGV("Empty header while parsing tethering stats");
931 return -EREMOTEIO;
932 }
933 headerLine++;
934 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900935 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900936
waynema71a0b592018-11-21 13:31:34 +0800937 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900938
waynema71a0b592018-11-21 13:31:34 +0800939 extraProcessingInfo = line;
940 std::smatch matches;
941 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
942 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
943 // IPv4 has "--" indicating what to do with fragments...
944 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
945 // ... but IPv6 does not.
946 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
947 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
948 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
949 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
950 std::string iface0 = matches[IFACE0_NAME].str();
951 std::string iface1 = matches[IFACE1_NAME].str();
952 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900953
waynema71a0b592018-11-21 13:31:34 +0800954 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
955 " rest=<%s> orig line=<%s>",
956 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900957 /*
958 * The following assumes that the 1st rule has in:extIface out:intIface,
959 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900960 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900961 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900962 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800963 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
964 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900965 stats.intIface = iface0;
966 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900967 stats.txPackets = packets;
968 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900969 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800970 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
971 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900972 stats.rxPackets = packets;
973 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900974 }
975 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900976 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900977 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900978 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900979 }
980 }
981
982 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900983 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900984 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900985 }
986 return 0;
987}
988
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900989StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900990 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900991 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900992
993 for (const IptablesTarget target : {V4, V6}) {
994 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900995 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900996 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
997 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900998 }
999
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001000 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001001 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
1002 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001003 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001004 }
1005 }
1006
Hungming Chen68dade32020-02-20 13:50:56 +08001007 if (!mBpfStatsMap.isValid()) {
1008 return statsList;
1009 }
Hungming Chenc2e95fb2020-02-19 17:41:30 +08001010
Hungming Chen68dade32020-02-20 13:50:56 +08001011 const auto processTetherStats = [this, &statsList](const uint32_t& key,
1012 const TetherStatsValue& value,
1013 const BpfMap<uint32_t, TetherStatsValue>&) {
1014 auto ifname = mIfaceIndexNameMap.readValue(key);
1015 if (!ifname.ok()) {
1016 // Keep on going regardless to parse as much as possible.
1017 return Result<void>();
Hungming Chenc2e95fb2020-02-19 17:41:30 +08001018 }
Hungming Chen68dade32020-02-20 13:50:56 +08001019 // Because the same interface name can have different interface IDs over time, there might
1020 // already be a TetherStats in the list with this interface name. This is fine because
1021 // addStats will increment an existing TetherStats if there is one in the list already,
1022 // and add a new TetherStats to the list if there isn't.
1023 addStats(statsList,
1024 {kBpfOffloadInterface, ifname.value().name, static_cast<int64_t>(value.rxBytes),
1025 static_cast<int64_t>(value.rxPackets), static_cast<int64_t>(value.txBytes),
1026 static_cast<int64_t>(value.txPackets)});
1027 return Result<void>();
1028 };
1029
1030 auto ret = mBpfStatsMap.iterateWithValue(processTetherStats);
1031 if (!ret.ok()) {
1032 // Ignore error to return the non-BPF tether stats result.
1033 ALOGE("Error processing tether stats from BPF maps: %s", ret.error().message().c_str());
Hungming Chenc2e95fb2020-02-19 17:41:30 +08001034 }
1035
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001036 return statsList;
1037}
1038
Hungming Chen1da90082020-02-14 20:24:16 +08001039void TetherController::maybeStartBpf(const char* extIface) {
Maciej Żenczykowskiaef13012020-02-18 17:13:09 -08001040 if (!bpf::isBpfSupported()) return;
1041
Hungming Chen1da90082020-02-14 20:24:16 +08001042 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
1043 int ifIndex = if_nametoindex(extIface);
1044 if (!ifIndex) {
1045 ALOGE("Fail to get index for interface %s", extIface);
1046 return;
1047 }
1048
1049 auto isEthernet = android::net::isEthernet(extIface);
1050 if (!isEthernet.ok()) {
1051 ALOGE("isEthernet(%s[%d]) failure: %s", extIface, ifIndex,
1052 isEthernet.error().message().c_str());
1053 return;
1054 }
1055
1056 int rv = getTetherIngressProgFd(isEthernet.value());
1057 if (rv < 0) {
1058 ALOGE("getTetherIngressProgFd(%d) failure: %s", isEthernet.value(), strerror(-rv));
1059 return;
1060 }
1061 unique_fd tetherProgFd(rv);
1062
1063 rv = tcFilterAddDevIngressTether(ifIndex, tetherProgFd, isEthernet.value());
1064 if (rv) {
1065 ALOGE("tcFilterAddDevIngressTether(%d[%s], %d) failure: %s", ifIndex, extIface,
1066 isEthernet.value(), strerror(-rv));
1067 return;
1068 }
1069}
1070
1071void TetherController::maybeStopBpf(const char* extIface) {
Maciej Żenczykowskiaef13012020-02-18 17:13:09 -08001072 if (!bpf::isBpfSupported()) return;
1073
Hungming Chen1da90082020-02-14 20:24:16 +08001074 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
1075 int ifIndex = if_nametoindex(extIface);
1076 if (!ifIndex) {
1077 ALOGE("Fail to get index for interface %s", extIface);
1078 return;
1079 }
1080
1081 int rv = tcFilterDelDevIngressTether(ifIndex);
1082 if (rv < 0) {
1083 ALOGE("tcFilterDelDevIngressTether(%d[%s]) failure: %s", ifIndex, extIface, strerror(-rv));
1084 }
1085}
1086
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001087void TetherController::dumpIfaces(DumpWriter& dw) {
1088 dw.println("Interface pairs:");
1089
1090 ScopedIndent ifaceIndent(dw);
1091 for (const auto& it : mFwdIfaces) {
1092 dw.println("%s -> %s %s", it.first.c_str(), it.second.iface.c_str(),
1093 (it.second.active ? "ACTIVE" : "DISABLED"));
1094 }
1095}
1096
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001097namespace {
1098
1099std::string l2ToString(const uint8_t* addr, size_t len) {
1100 std::string str;
1101
1102 if (len == 0) return str;
1103
1104 StringAppendF(&str, "%02x", addr[0]);
1105 for (size_t i = 1; i < len; i++) {
1106 StringAppendF(&str, ":%02x", addr[i]);
1107 }
1108
1109 return str;
1110}
1111
1112} // namespace
1113
1114void TetherController::dumpBpf(DumpWriter& dw) {
1115 if (!mBpfIngressMap.isValid() || !mBpfStatsMap.isValid()) {
1116 dw.println("BPF not supported");
1117 return;
1118 }
1119
1120 dw.println("BPF ingress map: iif v6addr -> oif srcmac dstmac ethertype");
1121 const auto printIngressMap = [&dw](const TetherIngressKey& key, const TetherIngressValue& value,
1122 const BpfMap<TetherIngressKey, TetherIngressValue>&) {
1123 char addr[INET6_ADDRSTRLEN];
1124 std::string src = l2ToString(value.macHeader.h_source, sizeof(value.macHeader.h_source));
1125 std::string dst = l2ToString(value.macHeader.h_dest, sizeof(value.macHeader.h_dest));
1126 inet_ntop(AF_INET6, &key.neigh6, addr, sizeof(addr));
1127
1128 dw.println("%d %s -> %d %s %s %04x", key.iif, addr, value.oif, src.c_str(), dst.c_str(),
1129 ntohs(value.macHeader.h_proto));
1130
1131 return Result<void>();
1132 };
1133
1134 dw.incIndent();
1135 auto ret = mBpfIngressMap.iterateWithValue(printIngressMap);
1136 if (!ret.ok()) {
1137 dw.println("Error printing BPF ingress map: %s", ret.error().message().c_str());
1138 }
1139 dw.decIndent();
1140
1141 dw.println("BPF stats (downlink): iif -> packets bytes errors");
1142 const auto printStatsMap = [&dw](const uint32_t& key, const TetherStatsValue& value,
1143 const BpfMap<uint32_t, TetherStatsValue>&) {
1144 dw.println("%d -> %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxPackets, value.rxBytes,
1145 value.rxErrors);
1146
1147 return Result<void>();
1148 };
1149
1150 dw.incIndent();
1151 ret = mBpfStatsMap.iterateWithValue(printStatsMap);
1152 if (!ret.ok()) {
1153 dw.println("Error printing BPF stats map: %s", ret.error().message().c_str());
1154 }
1155 dw.decIndent();
1156}
1157
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001158void TetherController::dump(DumpWriter& dw) {
1159 std::lock_guard guard(lock);
1160
1161 ScopedIndent tetherControllerIndent(dw);
1162 dw.println("TetherController");
1163 dw.incIndent();
1164
1165 dw.println("Forwarding requests: " + Join(mForwardingRequests, ' '));
1166 if (mDnsNetId != 0) {
1167 dw.println(StringPrintf("DNS: netId %d servers [%s]", mDnsNetId,
1168 Join(mDnsForwarders, ", ").c_str()));
1169 }
1170 if (mDaemonPid != 0) {
1171 dw.println("dnsmasq PID: %d", mDaemonPid);
1172 }
1173
1174 dumpIfaces(dw);
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001175 dw.println("");
1176 dumpBpf(dw);
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001177}
1178
Lorenzo Colittie20a5262017-05-09 18:30:44 +09001179} // namespace net
1180} // namespace android