blob: 7567dd52e8d839ae39cce8015e649c050ebf0c75 [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";
Lorenzo Colitti799625c2015-02-25 12:52:00 +090083
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",
Eric Changa0787fe2018-08-03 14:34:32 -0700266 "--dhcp-ignore-names",
Erik Kline5f0358b2018-02-16 15:08:09 +0900267 "--no-poll",
268 "--dhcp-authoritative",
269 // TODO: pipe through metered status from ConnService
270 "--dhcp-option-force=43,ANDROID_METERED",
271 "--pid-file",
Luke Huang94c43a12019-02-14 19:51:38 +0800272 "--listen-mark",
273 markStr,
274 "--user",
275 kDnsmasqUsername,
276 };
San Mehat9d10b342010-01-18 09:51:02 -0800277
Luke Huang91bd3e12019-08-20 11:33:52 +0800278 if (!usingLegacyDnsProxy) {
279 argVector.push_back("--port=0");
280 }
281
282 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is passed.
Luke Huang94c43a12019-02-14 19:51:38 +0800283 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
284 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
285 dhcp_ranges[addrIndex + 1]));
San Mehat9d10b342010-01-18 09:51:02 -0800286 }
287
George Burgess IVe3dc1312019-02-28 11:27:04 -0800288 std::vector<char*> args(argVector.size() + 1);
Luke Huang94c43a12019-02-14 19:51:38 +0800289 for (unsigned i = 0; i < argVector.size(); i++) {
290 args[i] = (char*)argVector[i].c_str();
291 }
292
293 /*
294 * TODO: Create a monitoring thread to handle and restart
295 * the daemon if it exits prematurely
296 */
Luke Huang40962442019-02-26 11:46:10 +0800297
298 // Note that don't modify any memory between vfork and execv.
299 // Changing state of file descriptors would be fine. See posix_spawn_file_actions_add*
300 // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
301 // duplicated fd.
302 posix_spawn_file_actions_t fa;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700303 int res = posix_spawn_file_actions_init(&fa);
Luke Huang40962442019-02-26 11:46:10 +0800304 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700305 ALOGE("posix_spawn_file_actions_init failed (%s)", strerror(res));
306 return -res;
307 }
308 const android::base::ScopeGuard faGuard = [&] { posix_spawn_file_actions_destroy(&fa); };
309 res = posix_spawn_file_actions_adddup2(&fa, pipeRead.get(), STDIN_FILENO);
310 if (res) {
311 ALOGE("posix_spawn_file_actions_adddup2 failed (%s)", strerror(res));
Luke Huang94c43a12019-02-14 19:51:38 +0800312 return -res;
313 }
314
Luke Huang40962442019-02-26 11:46:10 +0800315 posix_spawnattr_t attr;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700316 res = posix_spawnattr_init(&attr);
Luke Huang40962442019-02-26 11:46:10 +0800317 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700318 ALOGE("posix_spawnattr_init failed (%s)", strerror(res));
319 return -res;
320 }
321 const android::base::ScopeGuard attrGuard = [&] { posix_spawnattr_destroy(&attr); };
322 res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK);
323 if (res) {
324 ALOGE("posix_spawnattr_setflags failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800325 return -res;
326 }
327
328 pid_t pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800329 res = posix_spawn(&pid, args[0], &fa, &attr, &args[0], nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800330 if (res) {
331 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800332 return -res;
333 }
Luke Huang94c43a12019-02-14 19:51:38 +0800334 mDaemonPid = pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800335 mDaemonFd = pipeWrite.release();
Luke Huang94c43a12019-02-14 19:51:38 +0800336 configureForTethering(true);
Luke Huang91bd3e12019-08-20 11:33:52 +0800337 mIsTetheringStarted = true;
Luke Huang94c43a12019-02-14 19:51:38 +0800338 applyDnsInterfaces();
339 ALOGD("Tethering services running");
340
San Mehat9d10b342010-01-18 09:51:02 -0800341 return 0;
342}
343
Luke Huangb5733d72018-08-21 17:17:19 +0800344std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
345 std::vector<char*> addrsCstrVec{};
346 addrsCstrVec.reserve(addrs.size());
347 for (const auto& addr : addrs) {
348 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
349 }
350 return addrsCstrVec;
351}
352
Luke Huang91bd3e12019-08-20 11:33:52 +0800353int TetherController::startTethering(bool usingLegacyDnsProxy,
354 const std::vector<std::string>& dhcpRanges) {
Luke Huangb5733d72018-08-21 17:17:19 +0800355 struct in_addr v4_addr;
356 for (const auto& dhcpRange : dhcpRanges) {
357 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
358 return -EINVAL;
359 }
360 }
361 auto dhcp_ranges = toCstrVec(dhcpRanges);
Luke Huang91bd3e12019-08-20 11:33:52 +0800362 return startTethering(usingLegacyDnsProxy, dhcp_ranges.size(), dhcp_ranges.data());
Luke Huangb5733d72018-08-21 17:17:19 +0800363}
364
San Mehat9d10b342010-01-18 09:51:02 -0800365int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900366 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800367
Luke Huang91bd3e12019-08-20 11:33:52 +0800368 if (!mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000369 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800370 return 0;
371 }
372
Luke Huang91bd3e12019-08-20 11:33:52 +0800373 mIsTetheringStarted = false;
374 // dnsmasq is not started
375 if (mDaemonPid == 0) {
376 return 0;
377 }
378
Steve Block7b984e32011-12-20 16:22:42 +0000379 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800380
381 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700382 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800383 mDaemonPid = 0;
384 close(mDaemonFd);
385 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900386 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000387 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800388 return 0;
389}
Matthew Xie19944102012-07-12 16:42:07 -0700390
San Mehat9d10b342010-01-18 09:51:02 -0800391bool TetherController::isTetheringStarted() {
Luke Huang91bd3e12019-08-20 11:33:52 +0800392 return mIsTetheringStarted;
San Mehat9d10b342010-01-18 09:51:02 -0800393}
394
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900395// dnsmasq can't parse commands larger than this due to the fixed-size buffer
396// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
397// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900398const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800399
Luke Huang8dc1cac2019-03-30 16:12:31 +0800400// TODO: Remove overload function and update this after NDC migration.
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700401int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700402 Fwmark fwmark;
403 fwmark.netId = netId;
404 fwmark.explicitlySelected = true;
405 fwmark.protectedFromVpn = true;
406 fwmark.permission = PERMISSION_SYSTEM;
407
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900408 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800409
Erik Kline1d065ba2016-06-08 13:24:45 +0900410 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900411 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700412 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800413
Lorenzo Colittic2841282015-11-25 22:13:57 +0900414 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700415 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900416 freeaddrinfo(res);
417 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000418 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900419 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900420 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800421 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800422 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800423
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900424 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
425 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800426 break;
427 }
428
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900429 daemonCmd += SEPARATOR;
430 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900431 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800432 }
433
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700434 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900435 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800436 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900437 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900438 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900439 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800440 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800441 }
442 }
443 return 0;
444}
445
Luke Huangb5733d72018-08-21 17:17:19 +0800446int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
Luke Huangb5733d72018-08-21 17:17:19 +0800447 auto dnsServers = toCstrVec(servers);
448 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
449}
450
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700451unsigned TetherController::getDnsNetId() {
452 return mDnsNetId;
453}
454
Erik Kline1d065ba2016-06-08 13:24:45 +0900455const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800456 return mDnsForwarders;
457}
458
Erik Kline1d065ba2016-06-08 13:24:45 +0900459bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900460 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800461 bool haveInterfaces = false;
462
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900463 for (const auto& ifname : mInterfaces) {
464 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
465 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800466 break;
467 }
468
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900469 daemonCmd += SEPARATOR;
470 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800471 haveInterfaces = true;
472 }
473
Erik Kline15079dd2018-05-18 23:10:56 +0900474 if (!haveInterfaces) {
475 mDnsmasqState.update_ifaces_cmd.clear();
476 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900477 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900478 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800479 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900480 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800481}
482
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800483int TetherController::tetherInterface(const char *interface) {
484 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700485 if (!isIfaceName(interface)) {
486 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800487 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700488 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800489
Erik Kline1d065ba2016-06-08 13:24:45 +0900490 if (!configureForIPv6Router(interface)) {
491 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800492 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900493 }
494 mInterfaces.push_back(interface);
495
496 if (!applyDnsInterfaces()) {
497 mInterfaces.pop_back();
498 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800499 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800500 } else {
501 return 0;
502 }
503}
504
San Mehat9d10b342010-01-18 09:51:02 -0800505int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800506 ALOGD("untetherInterface(%s)", interface);
507
Erik Kline1d065ba2016-06-08 13:24:45 +0900508 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
509 if (!strcmp(interface, it->c_str())) {
510 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800511
Erik Kline1d065ba2016-06-08 13:24:45 +0900512 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800513 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800514 }
515 }
516 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800517 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800518}
519
Erik Kline1d065ba2016-06-08 13:24:45 +0900520const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800521 return mInterfaces;
522}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900523
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900524int TetherController::setupIptablesHooks() {
525 int res;
526 res = setDefaults();
527 if (res < 0) {
528 return res;
529 }
530
531 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
532 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
533 // This is no longer optional and tethering will fail to start if it fails.
534 std::string mssRewriteCommand = StringPrintf(
535 "*mangle\n"
536 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
537 "COMMIT\n", LOCAL_MANGLE_FORWARD);
538
539 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
540 std::string defaultCommands = StringPrintf(
541 "*filter\n"
542 ":%s -\n"
543 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
544
545 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
546 if (res < 0) {
547 return res;
548 }
549
550 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
551 if (res < 0) {
552 return res;
553 }
554
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900555 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900556
557 return 0;
558}
559
560int TetherController::setDefaults() {
561 std::string v4Cmd = StringPrintf(
562 "*filter\n"
563 ":%s -\n"
564 "-A %s -j DROP\n"
565 "COMMIT\n"
566 "*nat\n"
567 ":%s -\n"
568 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
569
570 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900571 "*filter\n"
572 ":%s -\n"
573 "COMMIT\n"
574 "*raw\n"
575 ":%s -\n"
576 "COMMIT\n",
577 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900578
579 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
580 if (res < 0) {
581 return res;
582 }
583
584 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
585 if (res < 0) {
586 return res;
587 }
588
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900589 return 0;
590}
591
592int TetherController::enableNat(const char* intIface, const char* extIface) {
593 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
594
595 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900596 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900597 }
598
599 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
600 if (!strcmp(intIface, extIface)) {
601 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900602 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900603 }
604
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900605 if (isForwardingPairEnabled(intIface, extIface)) {
606 return 0;
607 }
608
609 // add this if we are the first enabled nat for this upstream
Maciej Żenczykowski99665c32020-04-09 10:50:42 +0000610 bool firstDownstreamForThisUpstream = !isAnyForwardingEnabledOnUpstream(extIface);
611 if (firstDownstreamForThisUpstream) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900612 std::vector<std::string> v4Cmds = {
613 "*nat",
614 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
615 "COMMIT\n"
616 };
617
Luke Huangae038f82018-11-05 11:17:31 +0900618 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
619 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900620 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900621 if (!isAnyForwardingPairEnabled()) {
622 // unwind what's been done, but don't care about success - what more could we do?
623 setDefaults();
624 }
Luke Huang19b49c52018-10-22 12:12:05 +0900625 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900626 }
627 }
628
629 if (setForwardRules(true, intIface, extIface) != 0) {
630 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900631 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900632 setDefaults();
633 }
Luke Huang19b49c52018-10-22 12:12:05 +0900634 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900635 }
636
Maciej Żenczykowski99665c32020-04-09 10:50:42 +0000637 if (firstDownstreamForThisUpstream) maybeStartBpf(extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900638 return 0;
639}
640
Luke Huangae038f82018-11-05 11:17:31 +0900641int TetherController::setTetherGlobalAlertRule() {
642 // Only add this if we are the first enabled nat
643 if (isAnyForwardingPairEnabled()) {
644 return 0;
645 }
646 const std::string cmds =
647 "*filter\n" +
648 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
649 "COMMIT\n";
650
651 return iptablesRestoreFunction(V4V6, cmds, nullptr);
652}
653
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900654int TetherController::setupIPv6CountersChain() {
655 // Only add this if we are the first enabled nat
656 if (isAnyForwardingPairEnabled()) {
657 return 0;
658 }
659
660 /*
661 * IPv6 tethering doesn't need the state-based conntrack rules, so
662 * it unconditionally jumps to the tether counters chain all the time.
663 */
Luke Huangae038f82018-11-05 11:17:31 +0900664 const std::string v6Cmds =
665 "*filter\n" +
666 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900667
Luke Huangae038f82018-11-05 11:17:31 +0900668 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900669}
670
671// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
672TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
673 const std::string& intIface, const std::string& extIface) {
674 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
675 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
676 if (it->second.iface == intIface) {
677 return &(it->second);
678 }
679 }
680 return nullptr;
681}
682
683void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
684 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
685 if (existingEntry != nullptr) {
686 existingEntry->active = true;
687 return;
688 }
689
690 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
691 .iface = intIface,
692 .active = true
693 }));
694}
695
696void TetherController::markForwardingPairDisabled(
697 const std::string& intIface, const std::string& extIface) {
698 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
699 if (existingEntry == nullptr) {
700 return;
701 }
702
703 existingEntry->active = false;
704}
705
706bool TetherController::isForwardingPairEnabled(
707 const std::string& intIface, const std::string& extIface) {
708 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
709 return existingEntry != nullptr && existingEntry->active;
710}
711
712bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
713 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
714 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
715 if (it->second.active) {
716 return true;
717 }
718 }
719 return false;
720}
721
722bool TetherController::isAnyForwardingPairEnabled() {
723 for (auto& it : mFwdIfaces) {
724 if (it.second.active) {
725 return true;
726 }
727 }
728 return false;
729}
730
731bool TetherController::tetherCountingRuleExists(
732 const std::string& iface1, const std::string& iface2) {
733 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
734 // is in the map regardless of its active status. Rules are added both ways so we check with
735 // the 2 combinations.
736 return findForwardingDownstream(iface1, iface2) != nullptr
737 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900738}
739
740/* static */
741std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
742 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
743}
744
745int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
746 const char *op = add ? "-A" : "-D";
747
748 std::string rpfilterCmd = StringPrintf(
749 "*raw\n"
750 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
751 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
752 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900753 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900754 }
755
756 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900757 "*raw",
758 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
759 LOCAL_RAW_PREROUTING, intIface),
760 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
761 LOCAL_RAW_PREROUTING, intIface),
762 "COMMIT",
763 "*filter",
764 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
765 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
766 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
767 intIface, extIface),
768 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
769 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900770 };
771
772 std::vector<std::string> v6 = {
773 "*filter",
774 };
775
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900776 // We only ever add tethering quota rules so that they stick.
777 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900778 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900779 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900780 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900781 v6.push_back(makeTetherCountingRule(extIface, intIface));
782 }
783
784 // Always make sure the drop rule is at the end.
785 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900786 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900787 if (add) {
788 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
789 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
790 }
791
792 v4.push_back("COMMIT\n");
793 v6.push_back("COMMIT\n");
794
795 // We only add IPv6 rules here, never remove them.
796 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
797 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
798 // unwind what's been done, but don't care about success - what more could we do?
799 if (add) {
800 setForwardRules(false, intIface, extIface);
801 }
Luke Huang19b49c52018-10-22 12:12:05 +0900802 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900803 }
804
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900805 if (add) {
806 addForwardingPair(intIface, extIface);
807 } else {
808 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900809 }
810
811 return 0;
812}
813
814int TetherController::disableNat(const char* intIface, const char* extIface) {
815 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
816 errno = ENODEV;
Luke Huangae038f82018-11-05 11:17:31 +0900817 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900818 }
819
820 setForwardRules(false, intIface, extIface);
Maciej Żenczykowski99665c32020-04-09 10:50:42 +0000821 if (!isAnyForwardingEnabledOnUpstream(extIface)) maybeStopBpf(extIface);
822 if (!isAnyForwardingPairEnabled()) setDefaults();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900823 return 0;
824}
825
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000826namespace {
827Result<void> validateOffloadRule(const TetherOffloadRuleParcel& rule) {
828 struct ethhdr hdr;
829
830 if (rule.inputInterfaceIndex <= 0) {
831 return Error(ENODEV) << "Invalid input interface " << rule.inputInterfaceIndex;
832 }
833 if (rule.outputInterfaceIndex <= 0) {
834 return Error(ENODEV) << "Invalid output interface " << rule.inputInterfaceIndex;
835 }
836 if (rule.prefixLength != 128) {
837 return Error(EINVAL) << "Prefix length must be 128, not " << rule.prefixLength;
838 }
839 if (rule.destination.size() != sizeof(in6_addr)) {
840 return Error(EAFNOSUPPORT) << "Invalid IP address length " << rule.destination.size();
841 }
842 if (rule.srcL2Address.size() != sizeof(hdr.h_source)) {
843 return Error(ENXIO) << "Invalid L2 src address length " << rule.srcL2Address.size();
844 }
845 if (rule.dstL2Address.size() != sizeof(hdr.h_dest)) {
846 return Error(ENXIO) << "Invalid L2 dst address length " << rule.dstL2Address.size();
847 }
Maciej Żenczykowski9c63b692020-05-23 16:10:31 -0700848 if (rule.pmtu < IPV6_MIN_MTU || rule.pmtu > 0xFFFF) {
849 return Error(EINVAL) << "Invalid IPv6 path mtu " << rule.pmtu;
850 }
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000851 return Result<void>();
852}
853} // namespace
854
855Result<void> TetherController::addOffloadRule(const TetherOffloadRuleParcel& rule) {
856 Result<void> res = validateOffloadRule(rule);
857 if (!res.ok()) return res;
858
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900859 ethhdr hdr = {
860 .h_proto = htons(ETH_P_IPV6),
861 };
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000862 memcpy(&hdr.h_dest, rule.dstL2Address.data(), sizeof(hdr.h_dest));
863 memcpy(&hdr.h_source, rule.srcL2Address.data(), sizeof(hdr.h_source));
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900864
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000865 // Only downstream supported for now.
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900866 TetherIngressKey key = {
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000867 .iif = static_cast<uint32_t>(rule.inputInterfaceIndex),
868 .neigh6 = *(const in6_addr*)rule.destination.data(),
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900869 };
870
871 TetherIngressValue value = {
Maciej Żenczykowski1ec24532020-05-23 22:07:00 +0000872 .oif = static_cast<uint32_t>(rule.outputInterfaceIndex),
873 .macHeader = hdr,
Maciej Żenczykowski9c63b692020-05-23 16:10:31 -0700874 .pmtu = static_cast<uint16_t>(rule.pmtu),
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900875 };
876
877 return mBpfIngressMap.writeValue(key, value, BPF_ANY);
878}
879
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000880Result<void> TetherController::removeOffloadRule(const TetherOffloadRuleParcel& rule) {
881 Result<void> res = validateOffloadRule(rule);
882 if (!res.ok()) return res;
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900883
884 TetherIngressKey key = {
Lorenzo Colittif0e051c2020-04-06 09:19:57 +0000885 .iif = static_cast<uint32_t>(rule.inputInterfaceIndex),
886 .neigh6 = *(const in6_addr*)rule.destination.data(),
Lorenzo Colittie801d3c2020-02-18 00:00:35 +0900887 };
888
889 Result<void> ret = mBpfIngressMap.deleteValue(key);
890
891 // Silently return success if the rule did not exist.
892 if (!ret.ok() && ret.error().code() == ENOENT) return {};
893
894 return ret;
895}
896
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900897void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
898 for (TetherStats& existing : statsList) {
899 if (existing.addStatsIfMatch(stats)) {
900 return;
901 }
902 }
903 // No match. Insert a new interface pair.
904 statsList.push_back(stats);
905}
906
907/*
908 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900909 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900910 * pkts bytes target prot opt in out source destination
911 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
912 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
913 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
914 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
915 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900916 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900917 * pkts bytes target prot opt in out source destination
918 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
919 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
920 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900921 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900922int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900923 const std::string& statsOutput,
924 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800925 enum IndexOfIptChain {
926 ORIG_LINE,
927 PACKET_COUNTS,
928 BYTE_COUNTS,
929 HYPHEN,
930 IFACE0_NAME,
931 IFACE1_NAME,
932 SOURCE,
933 DESTINATION
934 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900935 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900936 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900937
waynema71a0b592018-11-21 13:31:34 +0800938 static const std::string NUM = "(\\d+)";
939 static const std::string IFACE = "([^\\s]+)";
940 static const std::string DST = "(0.0.0.0/0|::/0)";
941 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
942 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
943 "\\s+" + DST + "\\s+" + DST;
944 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900945
waynema71a0b592018-11-21 13:31:34 +0800946 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
947 int headerLine = 0;
948 for (const std::string& line : lines) {
949 // Skip headers.
950 if (headerLine < 2) {
951 if (line.empty()) {
952 ALOGV("Empty header while parsing tethering stats");
953 return -EREMOTEIO;
954 }
955 headerLine++;
956 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900957 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900958
waynema71a0b592018-11-21 13:31:34 +0800959 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900960
waynema71a0b592018-11-21 13:31:34 +0800961 extraProcessingInfo = line;
962 std::smatch matches;
963 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
964 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
965 // IPv4 has "--" indicating what to do with fragments...
966 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
967 // ... but IPv6 does not.
968 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
969 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
970 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
971 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
972 std::string iface0 = matches[IFACE0_NAME].str();
973 std::string iface1 = matches[IFACE1_NAME].str();
974 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900975
waynema71a0b592018-11-21 13:31:34 +0800976 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
977 " rest=<%s> orig line=<%s>",
978 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900979 /*
980 * The following assumes that the 1st rule has in:extIface out:intIface,
981 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900982 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900983 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900984 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800985 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
986 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900987 stats.intIface = iface0;
988 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900989 stats.txPackets = packets;
990 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900991 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800992 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
993 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900994 stats.rxPackets = packets;
995 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900996 }
997 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900998 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900999 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +09001000 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001001 }
1002 }
1003
1004 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +09001005 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001006 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001007 }
1008 return 0;
1009}
1010
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001011StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001012 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001013 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001014
1015 for (const IptablesTarget target : {V4, V6}) {
1016 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +09001017 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001018 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
1019 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001020 }
1021
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001022 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001023 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
1024 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +09001025 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +09001026 }
1027 }
1028
Hungming Chen41b0ed92020-06-02 00:13:20 +00001029 return statsList;
1030}
Hungming Chenc2e95fb2020-02-19 17:41:30 +08001031
Hungming Chen41b0ed92020-06-02 00:13:20 +00001032StatusOr<TetherController::TetherOffloadStatsList> TetherController::getTetherOffloadStats() {
1033 TetherOffloadStatsList statsList;
1034
1035 const auto processTetherStats = [&statsList](const uint32_t& key, const TetherStatsValue& value,
1036 const BpfMap<uint32_t, TetherStatsValue>&) {
1037 statsList.push_back({.ifIndex = static_cast<int>(key),
1038 .rxBytes = static_cast<int64_t>(value.rxBytes),
1039 .rxPackets = static_cast<int64_t>(value.rxPackets),
1040 .txBytes = static_cast<int64_t>(value.txBytes),
1041 .txPackets = static_cast<int64_t>(value.txPackets)});
Hungming Chen68dade32020-02-20 13:50:56 +08001042 return Result<void>();
1043 };
1044
1045 auto ret = mBpfStatsMap.iterateWithValue(processTetherStats);
1046 if (!ret.ok()) {
Hungming Chen41b0ed92020-06-02 00:13:20 +00001047 // Ignore error to return the remaining tether stats result.
Hungming Chen68dade32020-02-20 13:50:56 +08001048 ALOGE("Error processing tether stats from BPF maps: %s", ret.error().message().c_str());
Hungming Chenc2e95fb2020-02-19 17:41:30 +08001049 }
1050
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +09001051 return statsList;
1052}
1053
Maciej Żenczykowskiac14cb52020-05-23 20:48:00 +00001054// Use UINT64_MAX (~0uLL) for unlimited.
1055Result<void> TetherController::setBpfLimit(uint32_t ifIndex, uint64_t limit) {
1056 // The common case is an update, where the stats already exist,
1057 // hence we read first, even though writing with BPF_NOEXIST
1058 // first would make the code simpler.
1059 uint64_t rxBytes, txBytes;
1060 auto statsEntry = mBpfStatsMap.readValue(ifIndex);
1061
1062 if (statsEntry.ok()) {
1063 // Ok, there was a stats entry.
1064 rxBytes = statsEntry.value().rxBytes;
1065 txBytes = statsEntry.value().txBytes;
1066 } else if (statsEntry.error().code() == ENOENT) {
1067 // No stats entry - create one with zeroes.
1068 TetherStatsValue stats = {};
1069 // This function is the *only* thing that can create entries.
1070 auto ret = mBpfStatsMap.writeValue(ifIndex, stats, BPF_NOEXIST);
1071 if (!ret.ok()) {
1072 ALOGE("mBpfStatsMap.writeValue failure: %s", strerror(ret.error().code()));
1073 return ret;
1074 }
1075 rxBytes = 0;
1076 txBytes = 0;
1077 } else {
1078 // Other error while trying to get stats entry.
1079 return statsEntry.error();
1080 }
1081
1082 // rxBytes + txBytes won't overflow even at 5gbps for ~936 years.
1083 uint64_t newLimit = rxBytes + txBytes + limit;
1084
1085 // if adding limit (e.g., if limit is UINT64_MAX) caused overflow: clamp to 'infinity'
1086 if (newLimit < rxBytes + txBytes) newLimit = ~0uLL;
1087
1088 auto ret = mBpfLimitMap.writeValue(ifIndex, newLimit, BPF_ANY);
1089 if (!ret.ok()) {
1090 ALOGE("mBpfLimitMap.writeValue failure: %s", strerror(ret.error().code()));
1091 return ret;
1092 }
1093
1094 return {};
1095}
1096
Hungming Chen1da90082020-02-14 20:24:16 +08001097void TetherController::maybeStartBpf(const char* extIface) {
Maciej Żenczykowskiaef13012020-02-18 17:13:09 -08001098 if (!bpf::isBpfSupported()) return;
1099
Hungming Chen1da90082020-02-14 20:24:16 +08001100 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
1101 int ifIndex = if_nametoindex(extIface);
1102 if (!ifIndex) {
1103 ALOGE("Fail to get index for interface %s", extIface);
1104 return;
1105 }
1106
1107 auto isEthernet = android::net::isEthernet(extIface);
1108 if (!isEthernet.ok()) {
1109 ALOGE("isEthernet(%s[%d]) failure: %s", extIface, ifIndex,
1110 isEthernet.error().message().c_str());
1111 return;
1112 }
1113
1114 int rv = getTetherIngressProgFd(isEthernet.value());
1115 if (rv < 0) {
1116 ALOGE("getTetherIngressProgFd(%d) failure: %s", isEthernet.value(), strerror(-rv));
1117 return;
1118 }
1119 unique_fd tetherProgFd(rv);
1120
1121 rv = tcFilterAddDevIngressTether(ifIndex, tetherProgFd, isEthernet.value());
1122 if (rv) {
1123 ALOGE("tcFilterAddDevIngressTether(%d[%s], %d) failure: %s", ifIndex, extIface,
1124 isEthernet.value(), strerror(-rv));
1125 return;
1126 }
1127}
1128
1129void TetherController::maybeStopBpf(const char* extIface) {
Maciej Żenczykowskiaef13012020-02-18 17:13:09 -08001130 if (!bpf::isBpfSupported()) return;
1131
Hungming Chen1da90082020-02-14 20:24:16 +08001132 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
1133 int ifIndex = if_nametoindex(extIface);
1134 if (!ifIndex) {
1135 ALOGE("Fail to get index for interface %s", extIface);
1136 return;
1137 }
1138
1139 int rv = tcFilterDelDevIngressTether(ifIndex);
1140 if (rv < 0) {
1141 ALOGE("tcFilterDelDevIngressTether(%d[%s]) failure: %s", ifIndex, extIface, strerror(-rv));
1142 }
1143}
1144
Hungming Chen93a39d22020-03-16 13:53:19 +08001145int TetherController::setTetherOffloadInterfaceQuota(int ifIndex, int64_t maxBytes) {
1146 if (!mBpfStatsMap.isValid() || !mBpfLimitMap.isValid()) return -ENOTSUP;
1147
1148 if (ifIndex <= 0) return -ENODEV;
1149
1150 if (maxBytes < QUOTA_UNLIMITED) {
1151 ALOGE("Invalid bytes value. Must be -1 (unlimited) or 0..max_int64.");
1152 return -ERANGE;
1153 }
1154
1155 // Note that a value of unlimited quota (-1) indicates simply max_uint64.
1156 const auto res = setBpfLimit(static_cast<uint32_t>(ifIndex), static_cast<uint64_t>(maxBytes));
1157 if (!res.ok()) {
1158 ALOGE("Fail to set quota %" PRId64 " for interface index %d: %s", maxBytes, ifIndex,
1159 strerror(res.error().code()));
1160 return -res.error().code();
1161 }
1162
1163 return 0;
1164}
1165
Hungming Chenaf0dbed2020-04-17 20:00:27 +08001166Result<TetherController::TetherOffloadStats> TetherController::getAndClearTetherOffloadStats(
1167 int ifIndex) {
1168 if (!mBpfStatsMap.isValid() || !mBpfLimitMap.isValid()) return Error(ENOTSUP);
1169
1170 if (ifIndex <= 0) {
1171 return Error(ENODEV) << "Invalid interface " << ifIndex;
1172 }
1173
1174 // getAndClearTetherOffloadStats is called after all offload rules have already been deleted
1175 // for the given upstream interface. Before starting to do cleanup stuff in this function, use
1176 // synchronizeKernelRCU to make sure that all the current running eBPF programs are finished
1177 // on all CPUs, especially the unfinished packet processing. After synchronizeKernelRCU
1178 // returned, we can safely read or delete on the stats map or the limit map.
1179 if (int res = bpf::synchronizeKernelRCU()) {
1180 // Error log but don't return error. Do as much cleanup as possible.
1181 ALOGE("synchronize_rcu() failed: %s", strerror(-res));
1182 }
1183
1184 const auto stats = mBpfStatsMap.readValue(ifIndex);
1185 if (!stats.ok()) {
1186 return Error(stats.error().code()) << "Fail to get stats for interface index " << ifIndex;
1187 }
1188
1189 auto res = mBpfStatsMap.deleteValue(ifIndex);
1190 if (!res.ok()) {
1191 return Error(res.error().code()) << "Fail to delete stats for interface index " << ifIndex;
1192 }
1193
1194 res = mBpfLimitMap.deleteValue(ifIndex);
1195 if (!res.ok()) {
1196 return Error(res.error().code()) << "Fail to delete limit for interface index " << ifIndex;
1197 }
1198
1199 return TetherOffloadStats{.ifIndex = static_cast<int>(ifIndex),
1200 .rxBytes = static_cast<int64_t>(stats.value().rxBytes),
1201 .rxPackets = static_cast<int64_t>(stats.value().rxPackets),
1202 .txBytes = static_cast<int64_t>(stats.value().txBytes),
1203 .txPackets = static_cast<int64_t>(stats.value().txPackets)};
1204}
1205
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001206void TetherController::dumpIfaces(DumpWriter& dw) {
1207 dw.println("Interface pairs:");
1208
1209 ScopedIndent ifaceIndent(dw);
1210 for (const auto& it : mFwdIfaces) {
1211 dw.println("%s -> %s %s", it.first.c_str(), it.second.iface.c_str(),
1212 (it.second.active ? "ACTIVE" : "DISABLED"));
1213 }
1214}
1215
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001216namespace {
1217
1218std::string l2ToString(const uint8_t* addr, size_t len) {
1219 std::string str;
1220
1221 if (len == 0) return str;
1222
1223 StringAppendF(&str, "%02x", addr[0]);
1224 for (size_t i = 1; i < len; i++) {
1225 StringAppendF(&str, ":%02x", addr[i]);
1226 }
1227
1228 return str;
1229}
1230
1231} // namespace
1232
1233void TetherController::dumpBpf(DumpWriter& dw) {
Maciej Żenczykowskid25a7342020-05-04 18:18:38 -07001234 if (!mBpfIngressMap.isValid() || !mBpfStatsMap.isValid() || !mBpfLimitMap.isValid()) {
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001235 dw.println("BPF not supported");
1236 return;
1237 }
1238
Maciej Żenczykowskie278f3a2020-06-11 03:26:46 +00001239 dw.println("BPF ingress map: iif(iface) v6addr -> oif(iface) srcmac dstmac ethertype [pmtu]");
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001240 const auto printIngressMap = [&dw](const TetherIngressKey& key, const TetherIngressValue& value,
1241 const BpfMap<TetherIngressKey, TetherIngressValue>&) {
1242 char addr[INET6_ADDRSTRLEN];
1243 std::string src = l2ToString(value.macHeader.h_source, sizeof(value.macHeader.h_source));
1244 std::string dst = l2ToString(value.macHeader.h_dest, sizeof(value.macHeader.h_dest));
1245 inet_ntop(AF_INET6, &key.neigh6, addr, sizeof(addr));
1246
Maciej Żenczykowskie278f3a2020-06-11 03:26:46 +00001247 char iifStr[IFNAMSIZ] = "?";
1248 char oifStr[IFNAMSIZ] = "?";
1249 if_indextoname(key.iif, iifStr);
1250 if_indextoname(value.oif, oifStr);
1251 dw.println("%u(%s) %s -> %u(%s) %s %s %04x [%u]", key.iif, iifStr, addr, value.oif, oifStr,
1252 src.c_str(), dst.c_str(), ntohs(value.macHeader.h_proto), value.pmtu);
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001253
1254 return Result<void>();
1255 };
1256
1257 dw.incIndent();
1258 auto ret = mBpfIngressMap.iterateWithValue(printIngressMap);
1259 if (!ret.ok()) {
1260 dw.println("Error printing BPF ingress map: %s", ret.error().message().c_str());
1261 }
1262 dw.decIndent();
1263
Maciej Żenczykowskie278f3a2020-06-11 03:26:46 +00001264 dw.println("BPF stats (downlink): iif(iface) -> packets bytes errors");
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001265 const auto printStatsMap = [&dw](const uint32_t& key, const TetherStatsValue& value,
1266 const BpfMap<uint32_t, TetherStatsValue>&) {
Maciej Żenczykowskie278f3a2020-06-11 03:26:46 +00001267 char iifStr[IFNAMSIZ] = "?";
1268 if_indextoname(key, iifStr);
1269 dw.println("%u(%s) -> %" PRIu64 " %" PRIu64 " %" PRIu64, key, iifStr, value.rxPackets,
1270 value.rxBytes, value.rxErrors);
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001271
1272 return Result<void>();
1273 };
1274
1275 dw.incIndent();
1276 ret = mBpfStatsMap.iterateWithValue(printStatsMap);
1277 if (!ret.ok()) {
1278 dw.println("Error printing BPF stats map: %s", ret.error().message().c_str());
1279 }
1280 dw.decIndent();
Maciej Żenczykowskid25a7342020-05-04 18:18:38 -07001281
Maciej Żenczykowskie278f3a2020-06-11 03:26:46 +00001282 dw.println("BPF limit: iif(iface) -> bytes");
Maciej Żenczykowskid25a7342020-05-04 18:18:38 -07001283 const auto printLimitMap = [&dw](const uint32_t& key, const uint64_t& value,
1284 const BpfMap<uint32_t, uint64_t>&) {
Maciej Żenczykowskie278f3a2020-06-11 03:26:46 +00001285 char iifStr[IFNAMSIZ] = "?";
1286 if_indextoname(key, iifStr);
1287 dw.println("%u(%s) -> %" PRIu64, key, iifStr, value);
Maciej Żenczykowskid25a7342020-05-04 18:18:38 -07001288
1289 return Result<void>();
1290 };
1291
1292 dw.incIndent();
1293 ret = mBpfLimitMap.iterateWithValue(printLimitMap);
1294 if (!ret.ok()) {
1295 dw.println("Error printing BPF limit map: %s", ret.error().message().c_str());
1296 }
1297 dw.decIndent();
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001298}
1299
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001300void TetherController::dump(DumpWriter& dw) {
1301 std::lock_guard guard(lock);
1302
1303 ScopedIndent tetherControllerIndent(dw);
1304 dw.println("TetherController");
1305 dw.incIndent();
1306
1307 dw.println("Forwarding requests: " + Join(mForwardingRequests, ' '));
1308 if (mDnsNetId != 0) {
1309 dw.println(StringPrintf("DNS: netId %d servers [%s]", mDnsNetId,
1310 Join(mDnsForwarders, ", ").c_str()));
1311 }
1312 if (mDaemonPid != 0) {
1313 dw.println("dnsmasq PID: %d", mDaemonPid);
1314 }
1315
1316 dumpIfaces(dw);
Lorenzo Colittie801d3c2020-02-18 00:00:35 +09001317 dw.println("");
1318 dumpBpf(dw);
Lorenzo Colitti52db3912020-02-17 23:59:45 +09001319}
1320
Lorenzo Colittie20a5262017-05-09 18:30:44 +09001321} // namespace net
1322} // namespace android