blob: 6b5b060e387ee0e691838173913c9a64242ca752 [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
Erik Kline5f0358b2018-02-16 15:08:09 +090084// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
85constexpr const char kDnsmasqUsername[] = "dns_tether";
86
Hungming Chen93a39d22020-03-16 13:53:19 +080087// A value used by interface quota indicates there is no limit.
88// Sync from frameworks/base/core/java/android/net/netstats/provider/NetworkStatsProvider.java
89constexpr int64_t QUOTA_UNLIMITED = -1;
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
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800208 // Open BPF maps, ignoring errors because the device might not support BPF offload.
209 int fd = getTetherIngressMapFd();
Maciej Żenczykowski109ac532020-02-19 10:36:44 -0800210 if (fd >= 0) {
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800211 mBpfIngressMap.reset(fd);
Maciej Żenczykowski109ac532020-02-19 10:36:44 -0800212 mBpfIngressMap.clear();
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800213 }
214 fd = getTetherStatsMapFd();
Maciej Żenczykowski109ac532020-02-19 10:36:44 -0800215 if (fd >= 0) {
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800216 mBpfStatsMap.reset(fd);
Maciej Żenczykowski109ac532020-02-19 10:36:44 -0800217 mBpfStatsMap.clear();
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800218 }
Maciej Żenczykowskid25a7342020-05-04 18:18:38 -0700219 fd = getTetherLimitMapFd();
220 if (fd >= 0) {
221 mBpfLimitMap.reset(fd);
222 mBpfLimitMap.clear();
223 }
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800224}
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
Maciej Żenczykowski99665c32020-04-09 10:50:42 +0000609 bool firstDownstreamForThisUpstream = !isAnyForwardingEnabledOnUpstream(extIface);
610 if (firstDownstreamForThisUpstream) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900611 std::vector<std::string> v4Cmds = {
612 "*nat",
613 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
614 "COMMIT\n"
615 };
616
Luke Huangae038f82018-11-05 11:17:31 +0900617 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
618 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900619 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900620 if (!isAnyForwardingPairEnabled()) {
621 // unwind what's been done, but don't care about success - what more could we do?
622 setDefaults();
623 }
Luke Huang19b49c52018-10-22 12:12:05 +0900624 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900625 }
626 }
627
628 if (setForwardRules(true, intIface, extIface) != 0) {
629 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900630 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900631 setDefaults();
632 }
Luke Huang19b49c52018-10-22 12:12:05 +0900633 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900634 }
635
Maciej Żenczykowski99665c32020-04-09 10:50:42 +0000636 if (firstDownstreamForThisUpstream) maybeStartBpf(extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900637 return 0;
638}
639
Luke Huangae038f82018-11-05 11:17:31 +0900640int TetherController::setTetherGlobalAlertRule() {
641 // Only add this if we are the first enabled nat
642 if (isAnyForwardingPairEnabled()) {
643 return 0;
644 }
645 const std::string cmds =
646 "*filter\n" +
647 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
648 "COMMIT\n";
649
650 return iptablesRestoreFunction(V4V6, cmds, nullptr);
651}
652
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900653int TetherController::setupIPv6CountersChain() {
654 // Only add this if we are the first enabled nat
655 if (isAnyForwardingPairEnabled()) {
656 return 0;
657 }
658
659 /*
660 * IPv6 tethering doesn't need the state-based conntrack rules, so
661 * it unconditionally jumps to the tether counters chain all the time.
662 */
Luke Huangae038f82018-11-05 11:17:31 +0900663 const std::string v6Cmds =
664 "*filter\n" +
665 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900666
Luke Huangae038f82018-11-05 11:17:31 +0900667 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900668}
669
670// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
671TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
672 const std::string& intIface, const std::string& extIface) {
673 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
674 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
675 if (it->second.iface == intIface) {
676 return &(it->second);
677 }
678 }
679 return nullptr;
680}
681
682void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
683 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
684 if (existingEntry != nullptr) {
685 existingEntry->active = true;
686 return;
687 }
688
689 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
690 .iface = intIface,
691 .active = true
692 }));
693}
694
695void TetherController::markForwardingPairDisabled(
696 const std::string& intIface, const std::string& extIface) {
697 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
698 if (existingEntry == nullptr) {
699 return;
700 }
701
702 existingEntry->active = false;
703}
704
705bool TetherController::isForwardingPairEnabled(
706 const std::string& intIface, const std::string& extIface) {
707 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
708 return existingEntry != nullptr && existingEntry->active;
709}
710
711bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
712 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
713 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
714 if (it->second.active) {
715 return true;
716 }
717 }
718 return false;
719}
720
721bool TetherController::isAnyForwardingPairEnabled() {
722 for (auto& it : mFwdIfaces) {
723 if (it.second.active) {
724 return true;
725 }
726 }
727 return false;
728}
729
730bool TetherController::tetherCountingRuleExists(
731 const std::string& iface1, const std::string& iface2) {
732 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
733 // is in the map regardless of its active status. Rules are added both ways so we check with
734 // the 2 combinations.
735 return findForwardingDownstream(iface1, iface2) != nullptr
736 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900737}
738
739/* static */
740std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
741 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
742}
743
744int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
745 const char *op = add ? "-A" : "-D";
746
747 std::string rpfilterCmd = StringPrintf(
748 "*raw\n"
749 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
750 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
751 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900752 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900753 }
754
755 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900756 "*raw",
757 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
758 LOCAL_RAW_PREROUTING, intIface),
759 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
760 LOCAL_RAW_PREROUTING, intIface),
761 "COMMIT",
762 "*filter",
763 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
764 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
765 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
766 intIface, extIface),
767 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
768 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900769 };
770
771 std::vector<std::string> v6 = {
772 "*filter",
773 };
774
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900775 // We only ever add tethering quota rules so that they stick.
776 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900777 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900778 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900779 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900780 v6.push_back(makeTetherCountingRule(extIface, intIface));
781 }
782
783 // Always make sure the drop rule is at the end.
784 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900785 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900786 if (add) {
787 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
788 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
789 }
790
791 v4.push_back("COMMIT\n");
792 v6.push_back("COMMIT\n");
793
794 // We only add IPv6 rules here, never remove them.
795 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
796 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
797 // unwind what's been done, but don't care about success - what more could we do?
798 if (add) {
799 setForwardRules(false, intIface, extIface);
800 }
Luke Huang19b49c52018-10-22 12:12:05 +0900801 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900802 }
803
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900804 if (add) {
805 addForwardingPair(intIface, extIface);
806 } else {
807 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900808 }
809
810 return 0;
811}
812
813int TetherController::disableNat(const char* intIface, const char* extIface) {
814 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900815 errno = ENODEV;
816 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900817 }
818
819 setForwardRules(false, intIface, extIface);
Maciej Żenczykowski99665c32020-04-09 10:50:42 +0000820 if (!isAnyForwardingEnabledOnUpstream(extIface)) maybeStopBpf(extIface);
821 if (!isAnyForwardingPairEnabled()) setDefaults();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900822 return 0;
823}
824
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000825namespace {
826Result<void> validateOffloadRule(const TetherOffloadRuleParcel& rule) {
827 struct ethhdr hdr;
828
829 if (rule.inputInterfaceIndex <= 0) {
830 return Error(ENODEV) << "Invalid input interface " << rule.inputInterfaceIndex;
831 }
832 if (rule.outputInterfaceIndex <= 0) {
833 return Error(ENODEV) << "Invalid output interface " << rule.inputInterfaceIndex;
834 }
835 if (rule.prefixLength != 128) {
836 return Error(EINVAL) << "Prefix length must be 128, not " << rule.prefixLength;
837 }
838 if (rule.destination.size() != sizeof(in6_addr)) {
839 return Error(EAFNOSUPPORT) << "Invalid IP address length " << rule.destination.size();
840 }
841 if (rule.srcL2Address.size() != sizeof(hdr.h_source)) {
842 return Error(ENXIO) << "Invalid L2 src address length " << rule.srcL2Address.size();
843 }
844 if (rule.dstL2Address.size() != sizeof(hdr.h_dest)) {
845 return Error(ENXIO) << "Invalid L2 dst address length " << rule.dstL2Address.size();
846 }
847 return Result<void>();
848}
849} // namespace
850
851Result<void> TetherController::addOffloadRule(const TetherOffloadRuleParcel& rule) {
852 Result<void> res = validateOffloadRule(rule);
853 if (!res.ok()) return res;
854
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900855 ethhdr hdr = {
856 .h_proto = htons(ETH_P_IPV6),
857 };
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000858 memcpy(&hdr.h_dest, rule.dstL2Address.data(), sizeof(hdr.h_dest));
859 memcpy(&hdr.h_source, rule.srcL2Address.data(), sizeof(hdr.h_source));
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900860
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000861 // Only downstream supported for now.
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900862 TetherIngressKey key = {
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000863 .iif = static_cast<uint32_t>(rule.inputInterfaceIndex),
864 .neigh6 = *(const in6_addr*)rule.destination.data(),
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900865 };
866
867 TetherIngressValue value = {
Maciej Żenczykowski1ec24532020-05-23 22:07:00 +0000868 .oif = static_cast<uint32_t>(rule.outputInterfaceIndex),
869 .macHeader = hdr,
870 .pmtu = 1500, // TODO: don't just blindly use this default
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900871 };
872
873 return mBpfIngressMap.writeValue(key, value, BPF_ANY);
874}
875
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000876Result<void> TetherController::removeOffloadRule(const TetherOffloadRuleParcel& rule) {
877 Result<void> res = validateOffloadRule(rule);
878 if (!res.ok()) return res;
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900879
880 TetherIngressKey key = {
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000881 .iif = static_cast<uint32_t>(rule.inputInterfaceIndex),
882 .neigh6 = *(const in6_addr*)rule.destination.data(),
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900883 };
884
885 Result<void> ret = mBpfIngressMap.deleteValue(key);
886
887 // Silently return success if the rule did not exist.
888 if (!ret.ok() && ret.error().code() == ENOENT) return {};
889
890 return ret;
891}
892
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900893void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
894 for (TetherStats& existing : statsList) {
895 if (existing.addStatsIfMatch(stats)) {
896 return;
897 }
898 }
899 // No match. Insert a new interface pair.
900 statsList.push_back(stats);
901}
902
903/*
904 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900905 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900906 * pkts bytes target prot opt in out source destination
907 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
908 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
909 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
910 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
911 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900912 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900913 * pkts bytes target prot opt in out source destination
914 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
915 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
916 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900917 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900918int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900919 const std::string& statsOutput,
920 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800921 enum IndexOfIptChain {
922 ORIG_LINE,
923 PACKET_COUNTS,
924 BYTE_COUNTS,
925 HYPHEN,
926 IFACE0_NAME,
927 IFACE1_NAME,
928 SOURCE,
929 DESTINATION
930 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900931 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900932 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900933
waynema71a0b592018-11-21 13:31:34 +0800934 static const std::string NUM = "(\\d+)";
935 static const std::string IFACE = "([^\\s]+)";
936 static const std::string DST = "(0.0.0.0/0|::/0)";
937 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
938 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
939 "\\s+" + DST + "\\s+" + DST;
940 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900941
waynema71a0b592018-11-21 13:31:34 +0800942 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
943 int headerLine = 0;
944 for (const std::string& line : lines) {
945 // Skip headers.
946 if (headerLine < 2) {
947 if (line.empty()) {
948 ALOGV("Empty header while parsing tethering stats");
949 return -EREMOTEIO;
950 }
951 headerLine++;
952 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900953 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900954
waynema71a0b592018-11-21 13:31:34 +0800955 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900956
waynema71a0b592018-11-21 13:31:34 +0800957 extraProcessingInfo = line;
958 std::smatch matches;
959 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
960 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
961 // IPv4 has "--" indicating what to do with fragments...
962 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
963 // ... but IPv6 does not.
964 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
965 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
966 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
967 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
968 std::string iface0 = matches[IFACE0_NAME].str();
969 std::string iface1 = matches[IFACE1_NAME].str();
970 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900971
waynema71a0b592018-11-21 13:31:34 +0800972 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
973 " rest=<%s> orig line=<%s>",
974 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900975 /*
976 * The following assumes that the 1st rule has in:extIface out:intIface,
977 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900978 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900979 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900980 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800981 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
982 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900983 stats.intIface = iface0;
984 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900985 stats.txPackets = packets;
986 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900987 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800988 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
989 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900990 stats.rxPackets = packets;
991 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900992 }
993 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900994 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900995 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900996 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900997 }
998 }
999
1000 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +09001001 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001002 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001003 }
1004 return 0;
1005}
1006
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001007StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001008 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001009 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001010
1011 for (const IptablesTarget target : {V4, V6}) {
1012 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +09001013 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001014 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
1015 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001016 }
1017
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001018 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001019 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
1020 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001021 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001022 }
1023 }
1024
Hungming Chen41b0ed92020-06-02 00:13:20 +00001025 return statsList;
1026}
Hungming Chenc2e95fb2020-02-19 17:41:30 +08001027
Hungming Chen41b0ed92020-06-02 00:13:20 +00001028StatusOr<TetherController::TetherOffloadStatsList> TetherController::getTetherOffloadStats() {
1029 TetherOffloadStatsList statsList;
1030
1031 const auto processTetherStats = [&statsList](const uint32_t& key, const TetherStatsValue& value,
1032 const BpfMap<uint32_t, TetherStatsValue>&) {
1033 statsList.push_back({.ifIndex = static_cast<int>(key),
1034 .rxBytes = static_cast<int64_t>(value.rxBytes),
1035 .rxPackets = static_cast<int64_t>(value.rxPackets),
1036 .txBytes = static_cast<int64_t>(value.txBytes),
1037 .txPackets = static_cast<int64_t>(value.txPackets)});
Hungming Chen68dade32020-02-20 13:50:56 +08001038 return Result<void>();
1039 };
1040
1041 auto ret = mBpfStatsMap.iterateWithValue(processTetherStats);
1042 if (!ret.ok()) {
Hungming Chen41b0ed92020-06-02 00:13:20 +00001043 // Ignore error to return the remaining tether stats result.
Hungming Chen68dade32020-02-20 13:50:56 +08001044 ALOGE("Error processing tether stats from BPF maps: %s", ret.error().message().c_str());
Hungming Chenc2e95fb2020-02-19 17:41:30 +08001045 }
1046
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001047 return statsList;
1048}
1049
Maciej Żenczykowskiac14cb52020-05-23 20:48:00 +00001050// Use UINT64_MAX (~0uLL) for unlimited.
1051Result<void> TetherController::setBpfLimit(uint32_t ifIndex, uint64_t limit) {
1052 // The common case is an update, where the stats already exist,
1053 // hence we read first, even though writing with BPF_NOEXIST
1054 // first would make the code simpler.
1055 uint64_t rxBytes, txBytes;
1056 auto statsEntry = mBpfStatsMap.readValue(ifIndex);
1057
1058 if (statsEntry.ok()) {
1059 // Ok, there was a stats entry.
1060 rxBytes = statsEntry.value().rxBytes;
1061 txBytes = statsEntry.value().txBytes;
1062 } else if (statsEntry.error().code() == ENOENT) {
1063 // No stats entry - create one with zeroes.
1064 TetherStatsValue stats = {};
1065 // This function is the *only* thing that can create entries.
1066 auto ret = mBpfStatsMap.writeValue(ifIndex, stats, BPF_NOEXIST);
1067 if (!ret.ok()) {
1068 ALOGE("mBpfStatsMap.writeValue failure: %s", strerror(ret.error().code()));
1069 return ret;
1070 }
1071 rxBytes = 0;
1072 txBytes = 0;
1073 } else {
1074 // Other error while trying to get stats entry.
1075 return statsEntry.error();
1076 }
1077
1078 // rxBytes + txBytes won't overflow even at 5gbps for ~936 years.
1079 uint64_t newLimit = rxBytes + txBytes + limit;
1080
1081 // if adding limit (e.g., if limit is UINT64_MAX) caused overflow: clamp to 'infinity'
1082 if (newLimit < rxBytes + txBytes) newLimit = ~0uLL;
1083
1084 auto ret = mBpfLimitMap.writeValue(ifIndex, newLimit, BPF_ANY);
1085 if (!ret.ok()) {
1086 ALOGE("mBpfLimitMap.writeValue failure: %s", strerror(ret.error().code()));
1087 return ret;
1088 }
1089
1090 return {};
1091}
1092
Hungming Chen1da90082020-02-14 20:24:16 +08001093void TetherController::maybeStartBpf(const char* extIface) {
Maciej Żenczykowskiaef13012020-02-18 17:13:09 -08001094 if (!bpf::isBpfSupported()) return;
1095
Hungming Chen1da90082020-02-14 20:24:16 +08001096 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
1097 int ifIndex = if_nametoindex(extIface);
1098 if (!ifIndex) {
1099 ALOGE("Fail to get index for interface %s", extIface);
1100 return;
1101 }
1102
1103 auto isEthernet = android::net::isEthernet(extIface);
1104 if (!isEthernet.ok()) {
1105 ALOGE("isEthernet(%s[%d]) failure: %s", extIface, ifIndex,
1106 isEthernet.error().message().c_str());
1107 return;
1108 }
1109
1110 int rv = getTetherIngressProgFd(isEthernet.value());
1111 if (rv < 0) {
1112 ALOGE("getTetherIngressProgFd(%d) failure: %s", isEthernet.value(), strerror(-rv));
1113 return;
1114 }
1115 unique_fd tetherProgFd(rv);
1116
1117 rv = tcFilterAddDevIngressTether(ifIndex, tetherProgFd, isEthernet.value());
1118 if (rv) {
1119 ALOGE("tcFilterAddDevIngressTether(%d[%s], %d) failure: %s", ifIndex, extIface,
1120 isEthernet.value(), strerror(-rv));
1121 return;
1122 }
Maciej Żenczykowskiac14cb52020-05-23 20:48:00 +00001123
1124 // For now we just set data limit to 'infinity' ie. unlimited.
1125 setBpfLimit(ifIndex, ~0uLL);
Hungming Chen1da90082020-02-14 20:24:16 +08001126}
1127
1128void TetherController::maybeStopBpf(const char* extIface) {
Maciej Żenczykowskiaef13012020-02-18 17:13:09 -08001129 if (!bpf::isBpfSupported()) return;
1130
Hungming Chen1da90082020-02-14 20:24:16 +08001131 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
1132 int ifIndex = if_nametoindex(extIface);
1133 if (!ifIndex) {
1134 ALOGE("Fail to get index for interface %s", extIface);
1135 return;
1136 }
1137
1138 int rv = tcFilterDelDevIngressTether(ifIndex);
1139 if (rv < 0) {
1140 ALOGE("tcFilterDelDevIngressTether(%d[%s]) failure: %s", ifIndex, extIface, strerror(-rv));
1141 }
1142}
1143
Hungming Chen93a39d22020-03-16 13:53:19 +08001144int TetherController::setTetherOffloadInterfaceQuota(int ifIndex, int64_t maxBytes) {
1145 if (!mBpfStatsMap.isValid() || !mBpfLimitMap.isValid()) return -ENOTSUP;
1146
1147 if (ifIndex <= 0) return -ENODEV;
1148
1149 if (maxBytes < QUOTA_UNLIMITED) {
1150 ALOGE("Invalid bytes value. Must be -1 (unlimited) or 0..max_int64.");
1151 return -ERANGE;
1152 }
1153
1154 // Note that a value of unlimited quota (-1) indicates simply max_uint64.
1155 const auto res = setBpfLimit(static_cast<uint32_t>(ifIndex), static_cast<uint64_t>(maxBytes));
1156 if (!res.ok()) {
1157 ALOGE("Fail to set quota %" PRId64 " for interface index %d: %s", maxBytes, ifIndex,
1158 strerror(res.error().code()));
1159 return -res.error().code();
1160 }
1161
1162 return 0;
1163}
1164
Hungming Chenaf0dbed2020-04-17 20:00:27 +08001165Result<TetherController::TetherOffloadStats> TetherController::getAndClearTetherOffloadStats(
1166 int ifIndex) {
1167 if (!mBpfStatsMap.isValid() || !mBpfLimitMap.isValid()) return Error(ENOTSUP);
1168
1169 if (ifIndex <= 0) {
1170 return Error(ENODEV) << "Invalid interface " << ifIndex;
1171 }
1172
1173 // getAndClearTetherOffloadStats is called after all offload rules have already been deleted
1174 // for the given upstream interface. Before starting to do cleanup stuff in this function, use
1175 // synchronizeKernelRCU to make sure that all the current running eBPF programs are finished
1176 // on all CPUs, especially the unfinished packet processing. After synchronizeKernelRCU
1177 // returned, we can safely read or delete on the stats map or the limit map.
1178 if (int res = bpf::synchronizeKernelRCU()) {
1179 // Error log but don't return error. Do as much cleanup as possible.
1180 ALOGE("synchronize_rcu() failed: %s", strerror(-res));
1181 }
1182
1183 const auto stats = mBpfStatsMap.readValue(ifIndex);
1184 if (!stats.ok()) {
1185 return Error(stats.error().code()) << "Fail to get stats for interface index " << ifIndex;
1186 }
1187
1188 auto res = mBpfStatsMap.deleteValue(ifIndex);
1189 if (!res.ok()) {
1190 return Error(res.error().code()) << "Fail to delete stats for interface index " << ifIndex;
1191 }
1192
1193 res = mBpfLimitMap.deleteValue(ifIndex);
1194 if (!res.ok()) {
1195 return Error(res.error().code()) << "Fail to delete limit for interface index " << ifIndex;
1196 }
1197
1198 return TetherOffloadStats{.ifIndex = static_cast<int>(ifIndex),
1199 .rxBytes = static_cast<int64_t>(stats.value().rxBytes),
1200 .rxPackets = static_cast<int64_t>(stats.value().rxPackets),
1201 .txBytes = static_cast<int64_t>(stats.value().txBytes),
1202 .txPackets = static_cast<int64_t>(stats.value().txPackets)};
1203}
1204
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001205void TetherController::dumpIfaces(DumpWriter& dw) {
1206 dw.println("Interface pairs:");
1207
1208 ScopedIndent ifaceIndent(dw);
1209 for (const auto& it : mFwdIfaces) {
1210 dw.println("%s -> %s %s", it.first.c_str(), it.second.iface.c_str(),
1211 (it.second.active ? "ACTIVE" : "DISABLED"));
1212 }
1213}
1214
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001215namespace {
1216
1217std::string l2ToString(const uint8_t* addr, size_t len) {
1218 std::string str;
1219
1220 if (len == 0) return str;
1221
1222 StringAppendF(&str, "%02x", addr[0]);
1223 for (size_t i = 1; i < len; i++) {
1224 StringAppendF(&str, ":%02x", addr[i]);
1225 }
1226
1227 return str;
1228}
1229
1230} // namespace
1231
1232void TetherController::dumpBpf(DumpWriter& dw) {
Maciej Żenczykowskid25a7342020-05-04 18:18:38 -07001233 if (!mBpfIngressMap.isValid() || !mBpfStatsMap.isValid() || !mBpfLimitMap.isValid()) {
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001234 dw.println("BPF not supported");
1235 return;
1236 }
1237
Maciej Żenczykowski1ec24532020-05-23 22:07:00 +00001238 dw.println("BPF ingress map: iif v6addr -> oif srcmac dstmac ethertype [pmtu]");
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001239 const auto printIngressMap = [&dw](const TetherIngressKey& key, const TetherIngressValue& value,
1240 const BpfMap<TetherIngressKey, TetherIngressValue>&) {
1241 char addr[INET6_ADDRSTRLEN];
1242 std::string src = l2ToString(value.macHeader.h_source, sizeof(value.macHeader.h_source));
1243 std::string dst = l2ToString(value.macHeader.h_dest, sizeof(value.macHeader.h_dest));
1244 inet_ntop(AF_INET6, &key.neigh6, addr, sizeof(addr));
1245
Maciej Żenczykowski1ec24532020-05-23 22:07:00 +00001246 dw.println("%u %s -> %u %s %s %04x [%u]", key.iif, addr, value.oif, src.c_str(),
1247 dst.c_str(), ntohs(value.macHeader.h_proto), value.pmtu);
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001248
1249 return Result<void>();
1250 };
1251
1252 dw.incIndent();
1253 auto ret = mBpfIngressMap.iterateWithValue(printIngressMap);
1254 if (!ret.ok()) {
1255 dw.println("Error printing BPF ingress map: %s", ret.error().message().c_str());
1256 }
1257 dw.decIndent();
1258
1259 dw.println("BPF stats (downlink): iif -> packets bytes errors");
1260 const auto printStatsMap = [&dw](const uint32_t& key, const TetherStatsValue& value,
1261 const BpfMap<uint32_t, TetherStatsValue>&) {
Treehugger Robot15b21b72020-05-13 09:24:07 +00001262 dw.println("%u -> %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxPackets, value.rxBytes,
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001263 value.rxErrors);
1264
1265 return Result<void>();
1266 };
1267
1268 dw.incIndent();
1269 ret = mBpfStatsMap.iterateWithValue(printStatsMap);
1270 if (!ret.ok()) {
1271 dw.println("Error printing BPF stats map: %s", ret.error().message().c_str());
1272 }
1273 dw.decIndent();
Maciej Żenczykowskid25a7342020-05-04 18:18:38 -07001274
1275 dw.println("BPF limit: iif -> bytes");
1276 const auto printLimitMap = [&dw](const uint32_t& key, const uint64_t& value,
1277 const BpfMap<uint32_t, uint64_t>&) {
1278 dw.println("%u -> %" PRIu64, key, value);
1279
1280 return Result<void>();
1281 };
1282
1283 dw.incIndent();
1284 ret = mBpfLimitMap.iterateWithValue(printLimitMap);
1285 if (!ret.ok()) {
1286 dw.println("Error printing BPF limit map: %s", ret.error().message().c_str());
1287 }
1288 dw.decIndent();
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001289}
1290
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001291void TetherController::dump(DumpWriter& dw) {
1292 std::lock_guard guard(lock);
1293
1294 ScopedIndent tetherControllerIndent(dw);
1295 dw.println("TetherController");
1296 dw.incIndent();
1297
1298 dw.println("Forwarding requests: " + Join(mForwardingRequests, ' '));
1299 if (mDnsNetId != 0) {
1300 dw.println(StringPrintf("DNS: netId %d servers [%s]", mDnsNetId,
1301 Join(mDnsForwarders, ", ").c_str()));
1302 }
1303 if (mDaemonPid != 0) {
1304 dw.println("dnsmasq PID: %d", mDaemonPid);
1305 }
1306
1307 dumpIfaces(dw);
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001308 dw.println("");
1309 dumpBpf(dw);
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001310}
1311
Lorenzo Colittie20a5262017-05-09 18:30:44 +09001312} // namespace net
1313} // namespace android