blob: b159d9587a79db7076e8afaaef9b9fef65ad6b4b [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"
Mike Yuf0e019f2019-03-13 14:43:39 +080054#include "Permission.h"
Patrick Rohr70d42502021-10-12 18:24:10 +020055#include "TcUtils.h"
San Mehat9d10b342010-01-18 09:51:02 -080056#include "TetherController.h"
57
Lorenzo Colitti182cd3c2020-04-04 00:44:01 +090058#include "android/net/TetherOffloadRuleParcel.h"
59
Bernie Innocenti4debf3b2018-09-12 13:54:50 +090060namespace android {
61namespace net {
62
Lorenzo Colittia93126d2017-08-24 13:28:19 +090063using android::base::Join;
George Burgess IVe3dc1312019-02-28 11:27:04 -080064using android::base::Pipe;
Lorenzo Colittie801d3c2020-02-18 00:00:35 +090065using android::base::Result;
Erik Klineb31fd692018-06-06 20:50:11 +090066using android::base::StringPrintf;
George Burgess IVe3dc1312019-02-28 11:27:04 -080067using android::base::unique_fd;
Lorenzo Colitti52db3912020-02-17 23:59:45 +090068using android::netdutils::DumpWriter;
69using android::netdutils::ScopedIndent;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090070using android::netdutils::statusFromErrno;
Erik Klineb31fd692018-06-06 20:50:11 +090071using android::netdutils::StatusOr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090072
Lorenzo Colitti799625c2015-02-25 12:52:00 +090073namespace {
74
Erik Kline1d065ba2016-06-08 13:24:45 +090075const char BP_TOOLS_MODE[] = "bp-tools";
76const char IPV4_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv4/ip_forward";
77const char IPV6_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv6/conf/all/forwarding";
78const char SEPARATOR[] = "|";
Erik Kline93f9b222017-10-22 21:24:58 +090079constexpr const char kTcpBeLiberal[] = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
Hungming Chen68dade32020-02-20 13:50:56 +080080
Erik Kline5f0358b2018-02-16 15:08:09 +090081// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
82constexpr const char kDnsmasqUsername[] = "dns_tether";
83
Lorenzo Colitti799625c2015-02-25 12:52:00 +090084bool writeToFile(const char* filename, const char* value) {
Nick Kralevichb95c60c2016-11-19 09:09:16 -080085 int fd = open(filename, O_WRONLY | O_CLOEXEC);
Nicolas Geoffrayafd40372015-03-16 11:58:06 +000086 if (fd < 0) {
87 ALOGE("Failed to open %s: %s", filename, strerror(errno));
88 return false;
89 }
90
91 const ssize_t len = strlen(value);
92 if (write(fd, value, len) != len) {
93 ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
94 close(fd);
95 return false;
96 }
97 close(fd);
98 return true;
Lorenzo Colitti799625c2015-02-25 12:52:00 +090099}
100
Erik Kline93f9b222017-10-22 21:24:58 +0900101// TODO: Consider altering TCP and UDP timeouts as well.
102void configureForTethering(bool enabled) {
103 writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
104}
105
Erik Kline1d065ba2016-06-08 13:24:45 +0900106bool configureForIPv6Router(const char *interface) {
107 return (InterfaceController::setEnableIPv6(interface, 0) == 0)
108 && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
Erik Kline6cddf512016-08-09 15:28:42 +0900109 && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
110 && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
Erik Kline1d065ba2016-06-08 13:24:45 +0900111 && (InterfaceController::setEnableIPv6(interface, 1) == 0);
112}
113
114void configureForIPv6Client(const char *interface) {
115 InterfaceController::setAcceptIPv6Ra(interface, 1);
Erik Kline6cddf512016-08-09 15:28:42 +0900116 InterfaceController::setAcceptIPv6Dad(interface, 1);
117 InterfaceController::setIPv6DadTransmits(interface, "1");
Erik Kline1d065ba2016-06-08 13:24:45 +0900118 InterfaceController::setEnableIPv6(interface, 0);
119}
120
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900121bool inBpToolsMode() {
122 // In BP tools mode, do not disable IP forwarding
123 char bootmode[PROPERTY_VALUE_MAX] = {0};
124 property_get("ro.bootmode", bootmode, "unknown");
125 return !strcmp(BP_TOOLS_MODE, bootmode);
126}
127
128} // namespace
129
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900130auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
131
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900132const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
133 "*filter\n"
134 "-nvx -L %s\n"
135 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
136
Erik Kline15079dd2018-05-18 23:10:56 +0900137int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
138 if (cmd.empty()) return 0;
139
Erik Klineb31fd692018-06-06 20:50:11 +0900140 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900141 // Send the trailing \0 as well.
142 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900143 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900144 errno = EREMOTEIO;
145 return -1;
146 }
147 return 0;
148}
149
150void TetherController::DnsmasqState::clear() {
151 update_ifaces_cmd.clear();
152 update_dns_cmd.clear();
153}
154
155int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
156 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
157}
158
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700159TetherController::TetherController() {
Ken Chen66e860f2021-04-01 15:50:28 +0800160 gLog.info("enter TetherController ctor");
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900161 if (inBpToolsMode()) {
162 enableForwarding(BP_TOOLS_MODE);
163 } else {
164 setIpFwdEnabled();
165 }
Ken Chen66e860f2021-04-01 15:50:28 +0800166 gLog.info("leave TetherController ctor");
San Mehat9d10b342010-01-18 09:51:02 -0800167}
168
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900169bool TetherController::setIpFwdEnabled() {
170 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900171 bool disable = mForwardingRequests.empty();
172 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900173 ALOGD("Setting IP forward enable = %s", value);
174 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
175 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900176 if (disable) {
177 // Turning off the forwarding sysconf in the kernel has the side effect
178 // of turning on ICMP redirect, which is a security hazard.
179 // Turn ICMP redirect back off immediately.
180 int rv = InterfaceController::disableIcmpRedirects();
181 success &= (rv == 0);
182 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900183 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800184}
185
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900186bool TetherController::enableForwarding(const char* requester) {
187 // Don't return an error if this requester already requested forwarding. Only return errors for
188 // things that the caller caller needs to care about, such as "couldn't write to the file to
189 // enable forwarding".
190 mForwardingRequests.insert(requester);
191 return setIpFwdEnabled();
192}
San Mehat9d10b342010-01-18 09:51:02 -0800193
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900194bool TetherController::disableForwarding(const char* requester) {
195 mForwardingRequests.erase(requester);
196 return setIpFwdEnabled();
197}
San Mehat9d10b342010-01-18 09:51:02 -0800198
Luke Huang728cf4c2019-03-14 19:43:02 +0800199const std::set<std::string>& TetherController::getIpfwdRequesterList() const {
200 return mForwardingRequests;
San Mehat9d10b342010-01-18 09:51:02 -0800201}
202
Luke Huang91bd3e12019-08-20 11:33:52 +0800203int TetherController::startTethering(bool usingLegacyDnsProxy, int num_addrs, char** dhcp_ranges) {
204 if (!usingLegacyDnsProxy && num_addrs == 0) {
205 // Both DHCP and DnsProxy are disabled, we don't need to start dnsmasq
206 configureForTethering(true);
207 mIsTetheringStarted = true;
208 return 0;
209 }
210
211 if (mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000212 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800213 errno = EBUSY;
Luke Huangb5733d72018-08-21 17:17:19 +0800214 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800215 }
216
Steve Block7b984e32011-12-20 16:22:42 +0000217 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800218
George Burgess IVe3dc1312019-02-28 11:27:04 -0800219 unique_fd pipeRead, pipeWrite;
220 if (!Pipe(&pipeRead, &pipeWrite, O_CLOEXEC)) {
Luke Huangb5733d72018-08-21 17:17:19 +0800221 int res = errno;
Luke Huang94c43a12019-02-14 19:51:38 +0800222 ALOGE("pipe2() failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800223 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800224 }
225
Luke Huang94c43a12019-02-14 19:51:38 +0800226 // Set parameters
227 Fwmark fwmark;
228 fwmark.netId = NetworkController::LOCAL_NET_ID;
229 fwmark.explicitlySelected = true;
230 fwmark.protectedFromVpn = true;
231 fwmark.permission = PERMISSION_SYSTEM;
232 char markStr[UINT32_HEX_STRLEN];
233 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800234
Ryan Prichard61214652024-06-27 23:11:42 -0700235 std::vector<std::string> argVector = {
Erik Kline5f0358b2018-02-16 15:08:09 +0900236 "/system/bin/dnsmasq",
237 "--keep-in-foreground",
238 "--no-resolv",
239 "--no-poll",
240 "--dhcp-authoritative",
241 // TODO: pipe through metered status from ConnService
242 "--dhcp-option-force=43,ANDROID_METERED",
243 "--pid-file",
Luke Huang94c43a12019-02-14 19:51:38 +0800244 "--listen-mark",
245 markStr,
246 "--user",
247 kDnsmasqUsername,
248 };
San Mehat9d10b342010-01-18 09:51:02 -0800249
Luke Huang91bd3e12019-08-20 11:33:52 +0800250 if (!usingLegacyDnsProxy) {
251 argVector.push_back("--port=0");
252 }
253
254 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is passed.
Luke Huang94c43a12019-02-14 19:51:38 +0800255 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
256 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
257 dhcp_ranges[addrIndex + 1]));
San Mehat9d10b342010-01-18 09:51:02 -0800258 }
259
George Burgess IVe3dc1312019-02-28 11:27:04 -0800260 std::vector<char*> args(argVector.size() + 1);
Luke Huang94c43a12019-02-14 19:51:38 +0800261 for (unsigned i = 0; i < argVector.size(); i++) {
262 args[i] = (char*)argVector[i].c_str();
263 }
264
265 /*
266 * TODO: Create a monitoring thread to handle and restart
267 * the daemon if it exits prematurely
268 */
Luke Huang40962442019-02-26 11:46:10 +0800269
270 // Note that don't modify any memory between vfork and execv.
271 // Changing state of file descriptors would be fine. See posix_spawn_file_actions_add*
272 // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
273 // duplicated fd.
274 posix_spawn_file_actions_t fa;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700275 int res = posix_spawn_file_actions_init(&fa);
Luke Huang40962442019-02-26 11:46:10 +0800276 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700277 ALOGE("posix_spawn_file_actions_init failed (%s)", strerror(res));
278 return -res;
279 }
280 const android::base::ScopeGuard faGuard = [&] { posix_spawn_file_actions_destroy(&fa); };
281 res = posix_spawn_file_actions_adddup2(&fa, pipeRead.get(), STDIN_FILENO);
282 if (res) {
283 ALOGE("posix_spawn_file_actions_adddup2 failed (%s)", strerror(res));
Luke Huang94c43a12019-02-14 19:51:38 +0800284 return -res;
285 }
286
Luke Huang40962442019-02-26 11:46:10 +0800287 posix_spawnattr_t attr;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700288 res = posix_spawnattr_init(&attr);
Luke Huang40962442019-02-26 11:46:10 +0800289 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700290 ALOGE("posix_spawnattr_init failed (%s)", strerror(res));
291 return -res;
292 }
293 const android::base::ScopeGuard attrGuard = [&] { posix_spawnattr_destroy(&attr); };
Patrick Rohr62b90202024-08-28 21:28:48 +0000294 res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK | POSIX_SPAWN_CLOEXEC_DEFAULT);
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700295 if (res) {
296 ALOGE("posix_spawnattr_setflags failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800297 return -res;
298 }
299
300 pid_t pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800301 res = posix_spawn(&pid, args[0], &fa, &attr, &args[0], nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800302 if (res) {
303 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800304 return -res;
305 }
Luke Huang94c43a12019-02-14 19:51:38 +0800306 mDaemonPid = pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800307 mDaemonFd = pipeWrite.release();
Luke Huang94c43a12019-02-14 19:51:38 +0800308 configureForTethering(true);
Luke Huang91bd3e12019-08-20 11:33:52 +0800309 mIsTetheringStarted = true;
Luke Huang94c43a12019-02-14 19:51:38 +0800310 applyDnsInterfaces();
311 ALOGD("Tethering services running");
312
San Mehat9d10b342010-01-18 09:51:02 -0800313 return 0;
314}
315
Luke Huangb5733d72018-08-21 17:17:19 +0800316std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
317 std::vector<char*> addrsCstrVec{};
318 addrsCstrVec.reserve(addrs.size());
319 for (const auto& addr : addrs) {
320 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
321 }
322 return addrsCstrVec;
323}
324
Luke Huang91bd3e12019-08-20 11:33:52 +0800325int TetherController::startTethering(bool usingLegacyDnsProxy,
326 const std::vector<std::string>& dhcpRanges) {
Luke Huangb5733d72018-08-21 17:17:19 +0800327 struct in_addr v4_addr;
328 for (const auto& dhcpRange : dhcpRanges) {
329 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
330 return -EINVAL;
331 }
332 }
333 auto dhcp_ranges = toCstrVec(dhcpRanges);
Luke Huang91bd3e12019-08-20 11:33:52 +0800334 return startTethering(usingLegacyDnsProxy, dhcp_ranges.size(), dhcp_ranges.data());
Luke Huangb5733d72018-08-21 17:17:19 +0800335}
336
San Mehat9d10b342010-01-18 09:51:02 -0800337int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900338 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800339
Luke Huang91bd3e12019-08-20 11:33:52 +0800340 if (!mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000341 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800342 return 0;
343 }
344
Luke Huang91bd3e12019-08-20 11:33:52 +0800345 mIsTetheringStarted = false;
346 // dnsmasq is not started
347 if (mDaemonPid == 0) {
348 return 0;
349 }
350
Steve Block7b984e32011-12-20 16:22:42 +0000351 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800352
WeiZhang4f3dffb2021-11-30 00:32:46 -0600353 ::stopProcess(mDaemonPid, "tethering(dnsmasq)");
San Mehat9d10b342010-01-18 09:51:02 -0800354 mDaemonPid = 0;
355 close(mDaemonFd);
356 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900357 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000358 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800359 return 0;
360}
Matthew Xie19944102012-07-12 16:42:07 -0700361
San Mehat9d10b342010-01-18 09:51:02 -0800362bool TetherController::isTetheringStarted() {
Luke Huang91bd3e12019-08-20 11:33:52 +0800363 return mIsTetheringStarted;
San Mehat9d10b342010-01-18 09:51:02 -0800364}
365
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900366// dnsmasq can't parse commands larger than this due to the fixed-size buffer
367// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
368// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900369const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800370
Luke Huang8dc1cac2019-03-30 16:12:31 +0800371// TODO: Remove overload function and update this after NDC migration.
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700372int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700373 Fwmark fwmark;
374 fwmark.netId = netId;
375 fwmark.explicitlySelected = true;
376 fwmark.protectedFromVpn = true;
377 fwmark.permission = PERMISSION_SYSTEM;
378
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900379 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800380
Erik Kline1d065ba2016-06-08 13:24:45 +0900381 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900382 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700383 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800384
Lorenzo Colittic2841282015-11-25 22:13:57 +0900385 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700386 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900387 freeaddrinfo(res);
388 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000389 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900390 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900391 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800392 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800393 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800394
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900395 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
396 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800397 break;
398 }
399
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900400 daemonCmd += SEPARATOR;
401 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900402 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800403 }
404
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700405 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900406 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800407 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900408 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900409 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900410 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800411 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800412 }
413 }
414 return 0;
415}
416
Luke Huangb5733d72018-08-21 17:17:19 +0800417int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
Luke Huangb5733d72018-08-21 17:17:19 +0800418 auto dnsServers = toCstrVec(servers);
419 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
420}
421
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700422unsigned TetherController::getDnsNetId() {
423 return mDnsNetId;
424}
425
Erik Kline1d065ba2016-06-08 13:24:45 +0900426const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800427 return mDnsForwarders;
428}
429
Erik Kline1d065ba2016-06-08 13:24:45 +0900430bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900431 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800432 bool haveInterfaces = false;
433
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900434 for (const auto& ifname : mInterfaces) {
435 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
436 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800437 break;
438 }
439
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900440 daemonCmd += SEPARATOR;
441 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800442 haveInterfaces = true;
443 }
444
Erik Kline15079dd2018-05-18 23:10:56 +0900445 if (!haveInterfaces) {
446 mDnsmasqState.update_ifaces_cmd.clear();
447 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900448 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900449 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800450 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900451 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800452}
453
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800454int TetherController::tetherInterface(const char *interface) {
455 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700456 if (!isIfaceName(interface)) {
457 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800458 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700459 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800460
Erik Kline1d065ba2016-06-08 13:24:45 +0900461 if (!configureForIPv6Router(interface)) {
462 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800463 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900464 }
465 mInterfaces.push_back(interface);
466
467 if (!applyDnsInterfaces()) {
468 mInterfaces.pop_back();
469 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800470 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800471 } else {
472 return 0;
473 }
474}
475
San Mehat9d10b342010-01-18 09:51:02 -0800476int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800477 ALOGD("untetherInterface(%s)", interface);
478
Erik Kline1d065ba2016-06-08 13:24:45 +0900479 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
480 if (!strcmp(interface, it->c_str())) {
481 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800482
Erik Kline1d065ba2016-06-08 13:24:45 +0900483 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800484 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800485 }
486 }
487 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800488 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800489}
490
Erik Kline1d065ba2016-06-08 13:24:45 +0900491const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800492 return mInterfaces;
493}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900494
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900495int TetherController::setupIptablesHooks() {
496 int res;
497 res = setDefaults();
498 if (res < 0) {
499 return res;
500 }
501
502 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
503 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
504 // This is no longer optional and tethering will fail to start if it fails.
505 std::string mssRewriteCommand = StringPrintf(
506 "*mangle\n"
507 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
508 "COMMIT\n", LOCAL_MANGLE_FORWARD);
509
510 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
511 std::string defaultCommands = StringPrintf(
512 "*filter\n"
513 ":%s -\n"
514 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
515
516 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
517 if (res < 0) {
518 return res;
519 }
520
521 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
522 if (res < 0) {
523 return res;
524 }
525
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900526 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900527
528 return 0;
529}
530
531int TetherController::setDefaults() {
532 std::string v4Cmd = StringPrintf(
533 "*filter\n"
534 ":%s -\n"
535 "-A %s -j DROP\n"
536 "COMMIT\n"
537 "*nat\n"
538 ":%s -\n"
539 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
540
541 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900542 "*filter\n"
543 ":%s -\n"
544 "COMMIT\n"
545 "*raw\n"
546 ":%s -\n"
547 "COMMIT\n",
548 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900549
550 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
551 if (res < 0) {
552 return res;
553 }
554
555 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
556 if (res < 0) {
557 return res;
558 }
559
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900560 return 0;
561}
562
563int TetherController::enableNat(const char* intIface, const char* extIface) {
564 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
565
566 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900567 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900568 }
569
570 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
571 if (!strcmp(intIface, extIface)) {
572 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900573 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900574 }
575
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900576 if (isForwardingPairEnabled(intIface, extIface)) {
577 return 0;
578 }
579
580 // add this if we are the first enabled nat for this upstream
Hungming Chen99cf5702021-03-04 17:23:05 +0800581 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900582 std::vector<std::string> v4Cmds = {
583 "*nat",
584 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
585 "COMMIT\n"
586 };
587
Luke Huangae038f82018-11-05 11:17:31 +0900588 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
589 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900590 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900591 if (!isAnyForwardingPairEnabled()) {
592 // unwind what's been done, but don't care about success - what more could we do?
593 setDefaults();
594 }
Luke Huang19b49c52018-10-22 12:12:05 +0900595 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900596 }
597 }
598
599 if (setForwardRules(true, intIface, extIface) != 0) {
600 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900601 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900602 setDefaults();
603 }
Luke Huang19b49c52018-10-22 12:12:05 +0900604 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900605 }
606
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900607 return 0;
608}
609
Luke Huangae038f82018-11-05 11:17:31 +0900610int TetherController::setTetherGlobalAlertRule() {
611 // Only add this if we are the first enabled nat
612 if (isAnyForwardingPairEnabled()) {
613 return 0;
614 }
615 const std::string cmds =
616 "*filter\n" +
617 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
618 "COMMIT\n";
619
620 return iptablesRestoreFunction(V4V6, cmds, nullptr);
621}
622
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900623int TetherController::setupIPv6CountersChain() {
624 // Only add this if we are the first enabled nat
625 if (isAnyForwardingPairEnabled()) {
626 return 0;
627 }
628
629 /*
630 * IPv6 tethering doesn't need the state-based conntrack rules, so
631 * it unconditionally jumps to the tether counters chain all the time.
632 */
Luke Huangae038f82018-11-05 11:17:31 +0900633 const std::string v6Cmds =
634 "*filter\n" +
635 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900636
Luke Huangae038f82018-11-05 11:17:31 +0900637 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900638}
639
640// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
641TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
642 const std::string& intIface, const std::string& extIface) {
643 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
644 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
645 if (it->second.iface == intIface) {
646 return &(it->second);
647 }
648 }
649 return nullptr;
650}
651
652void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
653 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
654 if (existingEntry != nullptr) {
655 existingEntry->active = true;
656 return;
657 }
658
659 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
660 .iface = intIface,
661 .active = true
662 }));
663}
664
665void TetherController::markForwardingPairDisabled(
666 const std::string& intIface, const std::string& extIface) {
667 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
668 if (existingEntry == nullptr) {
669 return;
670 }
671
672 existingEntry->active = false;
673}
674
675bool TetherController::isForwardingPairEnabled(
676 const std::string& intIface, const std::string& extIface) {
677 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
678 return existingEntry != nullptr && existingEntry->active;
679}
680
681bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
682 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
683 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
684 if (it->second.active) {
685 return true;
686 }
687 }
688 return false;
689}
690
691bool TetherController::isAnyForwardingPairEnabled() {
692 for (auto& it : mFwdIfaces) {
693 if (it.second.active) {
694 return true;
695 }
696 }
697 return false;
698}
699
700bool TetherController::tetherCountingRuleExists(
701 const std::string& iface1, const std::string& iface2) {
702 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
703 // is in the map regardless of its active status. Rules are added both ways so we check with
704 // the 2 combinations.
705 return findForwardingDownstream(iface1, iface2) != nullptr
706 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900707}
708
709/* static */
710std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
711 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
712}
713
714int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
715 const char *op = add ? "-A" : "-D";
716
717 std::string rpfilterCmd = StringPrintf(
718 "*raw\n"
719 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
720 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
721 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900722 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900723 }
724
725 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900726 "*raw",
727 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
728 LOCAL_RAW_PREROUTING, intIface),
729 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
730 LOCAL_RAW_PREROUTING, intIface),
731 "COMMIT",
732 "*filter",
733 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
734 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
735 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
736 intIface, extIface),
737 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
738 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900739 };
740
741 std::vector<std::string> v6 = {
742 "*filter",
743 };
744
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900745 // We only ever add tethering quota rules so that they stick.
746 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900747 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900748 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900749 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900750 v6.push_back(makeTetherCountingRule(extIface, intIface));
751 }
752
753 // Always make sure the drop rule is at the end.
754 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900755 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900756 if (add) {
757 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
758 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
759 }
760
761 v4.push_back("COMMIT\n");
762 v6.push_back("COMMIT\n");
763
764 // We only add IPv6 rules here, never remove them.
765 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
766 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
767 // unwind what's been done, but don't care about success - what more could we do?
768 if (add) {
769 setForwardRules(false, intIface, extIface);
770 }
Luke Huang19b49c52018-10-22 12:12:05 +0900771 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900772 }
773
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900774 if (add) {
775 addForwardingPair(intIface, extIface);
776 } else {
777 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900778 }
779
780 return 0;
781}
782
783int TetherController::disableNat(const char* intIface, const char* extIface) {
784 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900785 errno = ENODEV;
786 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900787 }
788
789 setForwardRules(false, intIface, extIface);
Maciej Żenczykowskidde0c022020-04-06 21:09:53 -0700790 if (!isAnyForwardingPairEnabled()) setDefaults();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900791 return 0;
792}
793
794void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
795 for (TetherStats& existing : statsList) {
796 if (existing.addStatsIfMatch(stats)) {
797 return;
798 }
799 }
800 // No match. Insert a new interface pair.
801 statsList.push_back(stats);
802}
803
804/*
805 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900806 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900807 * pkts bytes target prot opt in out source destination
808 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
809 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
810 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
811 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
812 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900813 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900814 * pkts bytes target prot opt in out source destination
Maciej Żenczykowski392f6d72023-10-21 21:06:56 -0700815 * 0 0 RETURN all -- wlan0 rmnet_data0 ::/0 ::/0
816 * 0 0 RETURN all -- rmnet_data0 wlan0 ::/0 ::/0
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900817 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900818 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900819int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900820 const std::string& statsOutput,
821 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800822 enum IndexOfIptChain {
823 ORIG_LINE,
824 PACKET_COUNTS,
825 BYTE_COUNTS,
waynema71a0b592018-11-21 13:31:34 +0800826 IFACE0_NAME,
827 IFACE1_NAME,
828 SOURCE,
829 DESTINATION
830 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900831 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900832 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900833
waynema71a0b592018-11-21 13:31:34 +0800834 static const std::string NUM = "(\\d+)";
835 static const std::string IFACE = "([^\\s]+)";
836 static const std::string DST = "(0.0.0.0/0|::/0)";
837 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
Maciej Żenczykowski392f6d72023-10-21 21:06:56 -0700838 " RETURN all -- " + IFACE + "\\s+" + IFACE +
waynema71a0b592018-11-21 13:31:34 +0800839 "\\s+" + DST + "\\s+" + DST;
840 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900841
waynema71a0b592018-11-21 13:31:34 +0800842 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
843 int headerLine = 0;
844 for (const std::string& line : lines) {
845 // Skip headers.
846 if (headerLine < 2) {
847 if (line.empty()) {
848 ALOGV("Empty header while parsing tethering stats");
849 return -EREMOTEIO;
850 }
851 headerLine++;
852 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900853 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900854
waynema71a0b592018-11-21 13:31:34 +0800855 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900856
waynema71a0b592018-11-21 13:31:34 +0800857 extraProcessingInfo = line;
858 std::smatch matches;
859 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
waynema71a0b592018-11-21 13:31:34 +0800860 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
Maciej Żenczykowski392f6d72023-10-21 21:06:56 -0700861 // 26 2373 RETURN all -- wlan0 rmnet0 ::/0 ::/0
waynema71a0b592018-11-21 13:31:34 +0800862 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
863 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
864 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
865 std::string iface0 = matches[IFACE0_NAME].str();
866 std::string iface1 = matches[IFACE1_NAME].str();
867 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900868
waynema71a0b592018-11-21 13:31:34 +0800869 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
870 " rest=<%s> orig line=<%s>",
871 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900872 /*
873 * The following assumes that the 1st rule has in:extIface out:intIface,
874 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900875 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900876 */
Maciej Żenczykowskif4f22b22021-11-18 10:50:36 -0800877 if (stats.intIface.empty()) {
waynema71a0b592018-11-21 13:31:34 +0800878 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
879 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900880 stats.intIface = iface0;
881 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900882 stats.txPackets = packets;
883 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900884 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800885 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
886 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900887 stats.rxPackets = packets;
888 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900889 }
890 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900891 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900892 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900893 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900894 }
895 }
896
897 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900898 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900899 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900900 }
901 return 0;
902}
903
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900904StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900905 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900906 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900907
908 for (const IptablesTarget target : {V4, V6}) {
909 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900910 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900911 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
912 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900913 }
914
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900915 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900916 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
917 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900918 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900919 }
920 }
921
Hungming Chenf40dc092020-03-12 16:21:03 +0800922 return statsList;
923}
Hungming Chenc2e95fb2020-02-19 17:41:30 +0800924
Lorenzo Colitti52db3912020-02-17 23:59:45 +0900925void TetherController::dumpIfaces(DumpWriter& dw) {
926 dw.println("Interface pairs:");
927
928 ScopedIndent ifaceIndent(dw);
929 for (const auto& it : mFwdIfaces) {
930 dw.println("%s -> %s %s", it.first.c_str(), it.second.iface.c_str(),
931 (it.second.active ? "ACTIVE" : "DISABLED"));
932 }
933}
934
935void TetherController::dump(DumpWriter& dw) {
936 std::lock_guard guard(lock);
937
938 ScopedIndent tetherControllerIndent(dw);
939 dw.println("TetherController");
940 dw.incIndent();
941
942 dw.println("Forwarding requests: " + Join(mForwardingRequests, ' '));
943 if (mDnsNetId != 0) {
944 dw.println(StringPrintf("DNS: netId %d servers [%s]", mDnsNetId,
945 Join(mDnsForwarders, ", ").c_str()));
946 }
947 if (mDaemonPid != 0) {
948 dw.println("dnsmasq PID: %d", mDaemonPid);
949 }
950
951 dumpIfaces(dw);
952}
953
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900954} // namespace net
955} // namespace android