blob: 75cda7db0d4acefdfddbddc17ea2a8685f9984b0 [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>
Olivier Baillyff2c0d82010-11-17 11:45:07 -080021#include <string.h>
San Mehat18737842010-01-21 09:22:43 -080022
San Mehat9d10b342010-01-18 09:51:02 -080023#include <sys/socket.h>
24#include <sys/stat.h>
San Mehat18737842010-01-21 09:22:43 -080025#include <sys/types.h>
26#include <sys/wait.h>
27
San Mehat9d10b342010-01-18 09:51:02 -080028#include <netinet/in.h>
29#include <arpa/inet.h>
30
Erik Kline5f0358b2018-02-16 15:08:09 +090031#include <array>
32#include <cstdlib>
waynema71a0b592018-11-21 13:31:34 +080033#include <regex>
Erik Kline5f0358b2018-02-16 15:08:09 +090034#include <string>
35#include <vector>
36
San Mehat9d10b342010-01-18 09:51:02 -080037#define LOG_TAG "TetherController"
Lorenzo Colittia93126d2017-08-24 13:28:19 +090038#include <android-base/strings.h>
39#include <android-base/stringprintf.h>
Kazuhiro Ondo6b858eb2011-06-24 20:31:03 -050040#include <cutils/properties.h>
Logan Chien3f461482018-04-23 14:31:32 +080041#include <log/log.h>
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090042#include <netdutils/StatusOr.h>
San Mehat9d10b342010-01-18 09:51:02 -080043
Erik Klineb31fd692018-06-06 20:50:11 +090044#include "Controllers.h"
Lorenzo Colitti667c4772014-08-26 14:13:07 -070045#include "Fwmark.h"
JP Abgrall69261cb2014-06-19 18:35:24 -070046#include "NetdConstants.h"
Lorenzo Colitti667c4772014-08-26 14:13:07 -070047#include "Permission.h"
Erik Kline1d065ba2016-06-08 13:24:45 +090048#include "InterfaceController.h"
Lorenzo Colittie20a5262017-05-09 18:30:44 +090049#include "NetworkController.h"
Lorenzo Colittia93126d2017-08-24 13:28:19 +090050#include "ResponseCode.h"
San Mehat9d10b342010-01-18 09:51:02 -080051#include "TetherController.h"
52
Bernie Innocenti4debf3b2018-09-12 13:54:50 +090053namespace android {
54namespace net {
55
Lorenzo Colittia93126d2017-08-24 13:28:19 +090056using android::base::Join;
Erik Klineb31fd692018-06-06 20:50:11 +090057using android::base::StringPrintf;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090058using android::netdutils::statusFromErrno;
Erik Klineb31fd692018-06-06 20:50:11 +090059using android::netdutils::StatusOr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090060
Lorenzo Colitti799625c2015-02-25 12:52:00 +090061namespace {
62
Erik Kline1d065ba2016-06-08 13:24:45 +090063const char BP_TOOLS_MODE[] = "bp-tools";
64const char IPV4_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv4/ip_forward";
65const char IPV6_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv6/conf/all/forwarding";
66const char SEPARATOR[] = "|";
Erik Kline93f9b222017-10-22 21:24:58 +090067constexpr const char kTcpBeLiberal[] = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
Lorenzo Colitti799625c2015-02-25 12:52:00 +090068
Erik Kline5f0358b2018-02-16 15:08:09 +090069// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
70constexpr const char kDnsmasqUsername[] = "dns_tether";
71
Lorenzo Colitti799625c2015-02-25 12:52:00 +090072bool writeToFile(const char* filename, const char* value) {
Nick Kralevichb95c60c2016-11-19 09:09:16 -080073 int fd = open(filename, O_WRONLY | O_CLOEXEC);
Nicolas Geoffrayafd40372015-03-16 11:58:06 +000074 if (fd < 0) {
75 ALOGE("Failed to open %s: %s", filename, strerror(errno));
76 return false;
77 }
78
79 const ssize_t len = strlen(value);
80 if (write(fd, value, len) != len) {
81 ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
82 close(fd);
83 return false;
84 }
85 close(fd);
86 return true;
Lorenzo Colitti799625c2015-02-25 12:52:00 +090087}
88
Erik Kline93f9b222017-10-22 21:24:58 +090089// TODO: Consider altering TCP and UDP timeouts as well.
90void configureForTethering(bool enabled) {
91 writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
92}
93
Erik Kline1d065ba2016-06-08 13:24:45 +090094bool configureForIPv6Router(const char *interface) {
95 return (InterfaceController::setEnableIPv6(interface, 0) == 0)
96 && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
Erik Kline6cddf512016-08-09 15:28:42 +090097 && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
98 && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
Erik Kline1d065ba2016-06-08 13:24:45 +090099 && (InterfaceController::setEnableIPv6(interface, 1) == 0);
100}
101
102void configureForIPv6Client(const char *interface) {
103 InterfaceController::setAcceptIPv6Ra(interface, 1);
Erik Kline6cddf512016-08-09 15:28:42 +0900104 InterfaceController::setAcceptIPv6Dad(interface, 1);
105 InterfaceController::setIPv6DadTransmits(interface, "1");
Erik Kline1d065ba2016-06-08 13:24:45 +0900106 InterfaceController::setEnableIPv6(interface, 0);
107}
108
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900109bool inBpToolsMode() {
110 // In BP tools mode, do not disable IP forwarding
111 char bootmode[PROPERTY_VALUE_MAX] = {0};
112 property_get("ro.bootmode", bootmode, "unknown");
113 return !strcmp(BP_TOOLS_MODE, bootmode);
114}
115
116} // namespace
117
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900118auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
119
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900120const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
121 "*filter\n"
122 "-nvx -L %s\n"
123 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
124
Erik Kline15079dd2018-05-18 23:10:56 +0900125int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
126 if (cmd.empty()) return 0;
127
Erik Klineb31fd692018-06-06 20:50:11 +0900128 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900129 // Send the trailing \0 as well.
130 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900131 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900132 errno = EREMOTEIO;
133 return -1;
134 }
135 return 0;
136}
137
138void TetherController::DnsmasqState::clear() {
139 update_ifaces_cmd.clear();
140 update_dns_cmd.clear();
141}
142
143int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
144 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
145}
146
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700147TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900148 if (inBpToolsMode()) {
149 enableForwarding(BP_TOOLS_MODE);
150 } else {
151 setIpFwdEnabled();
152 }
San Mehat9d10b342010-01-18 09:51:02 -0800153}
154
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900155bool TetherController::setIpFwdEnabled() {
156 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900157 bool disable = mForwardingRequests.empty();
158 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900159 ALOGD("Setting IP forward enable = %s", value);
160 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
161 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900162 if (disable) {
163 // Turning off the forwarding sysconf in the kernel has the side effect
164 // of turning on ICMP redirect, which is a security hazard.
165 // Turn ICMP redirect back off immediately.
166 int rv = InterfaceController::disableIcmpRedirects();
167 success &= (rv == 0);
168 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900169 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800170}
171
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900172bool TetherController::enableForwarding(const char* requester) {
173 // Don't return an error if this requester already requested forwarding. Only return errors for
174 // things that the caller caller needs to care about, such as "couldn't write to the file to
175 // enable forwarding".
176 mForwardingRequests.insert(requester);
177 return setIpFwdEnabled();
178}
San Mehat9d10b342010-01-18 09:51:02 -0800179
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900180bool TetherController::disableForwarding(const char* requester) {
181 mForwardingRequests.erase(requester);
182 return setIpFwdEnabled();
183}
San Mehat9d10b342010-01-18 09:51:02 -0800184
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900185size_t TetherController::forwardingRequestCount() {
186 return mForwardingRequests.size();
San Mehat9d10b342010-01-18 09:51:02 -0800187}
188
Erik Kline13fa01f2015-11-12 17:49:23 +0900189int TetherController::startTethering(int num_addrs, char **dhcp_ranges) {
San Mehat9d10b342010-01-18 09:51:02 -0800190 if (mDaemonPid != 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000191 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800192 errno = EBUSY;
Luke Huangb5733d72018-08-21 17:17:19 +0800193 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800194 }
195
Steve Block7b984e32011-12-20 16:22:42 +0000196 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800197
198 pid_t pid;
199 int pipefd[2];
200
201 if (pipe(pipefd) < 0) {
Luke Huangb5733d72018-08-21 17:17:19 +0800202 int res = errno;
Steve Block5ea0c052012-01-06 19:18:11 +0000203 ALOGE("pipe failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800204 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800205 }
206
207 /*
208 * TODO: Create a monitoring thread to handle and restart
209 * the daemon if it exits prematurely
210 */
211 if ((pid = fork()) < 0) {
Luke Huangb5733d72018-08-21 17:17:19 +0800212 int res = errno;
Steve Block5ea0c052012-01-06 19:18:11 +0000213 ALOGE("fork failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800214 close(pipefd[0]);
215 close(pipefd[1]);
Luke Huangb5733d72018-08-21 17:17:19 +0800216 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800217 }
218
219 if (!pid) {
220 close(pipefd[1]);
221 if (pipefd[0] != STDIN_FILENO) {
222 if (dup2(pipefd[0], STDIN_FILENO) != STDIN_FILENO) {
Luke Huangb5733d72018-08-21 17:17:19 +0800223 int res = errno;
Steve Block5ea0c052012-01-06 19:18:11 +0000224 ALOGE("dup2 failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800225 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800226 }
227 close(pipefd[0]);
228 }
San Mehat9d10b342010-01-18 09:51:02 -0800229
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900230 Fwmark fwmark;
231 fwmark.netId = NetworkController::LOCAL_NET_ID;
232 fwmark.explicitlySelected = true;
233 fwmark.protectedFromVpn = true;
234 fwmark.permission = PERMISSION_SYSTEM;
235 char markStr[UINT32_HEX_STRLEN];
236 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
237
Erik Kline5f0358b2018-02-16 15:08:09 +0900238 std::vector<const std::string> argVector = {
239 "/system/bin/dnsmasq",
240 "--keep-in-foreground",
241 "--no-resolv",
242 "--no-poll",
243 "--dhcp-authoritative",
244 // TODO: pipe through metered status from ConnService
245 "--dhcp-option-force=43,ANDROID_METERED",
246 "--pid-file",
247 "--listen-mark", markStr,
248 "--user", kDnsmasqUsername,
249 };
San Mehat9d10b342010-01-18 09:51:02 -0800250
Remi NGUYEN VANedbf5f62018-08-06 15:03:18 +0900251 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is passed.
Erik Kline13fa01f2015-11-12 17:49:23 +0900252 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
Remi NGUYEN VANedbf5f62018-08-06 15:03:18 +0900253 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
254 dhcp_ranges[addrIndex + 1]));
Erik Kline5f0358b2018-02-16 15:08:09 +0900255 }
256
257 auto args = (char**)std::calloc(argVector.size() + 1, sizeof(char*));
258 for (unsigned i = 0; i < argVector.size(); i++) {
259 args[i] = (char*)argVector[i].c_str();
Robert Greenwalt3208ea02010-03-24 16:32:55 -0700260 }
261
262 if (execv(args[0], args)) {
Erik Kline5f0358b2018-02-16 15:08:09 +0900263 ALOGE("execv failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800264 }
Steve Block5ea0c052012-01-06 19:18:11 +0000265 ALOGE("Should never get here!");
JP Abgrallce4f3792012-08-06 13:44:44 -0700266 _exit(-1);
San Mehat9d10b342010-01-18 09:51:02 -0800267 } else {
268 close(pipefd[0]);
269 mDaemonPid = pid;
270 mDaemonFd = pipefd[1];
Erik Kline93f9b222017-10-22 21:24:58 +0900271 configureForTethering(true);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800272 applyDnsInterfaces();
Steve Block7b984e32011-12-20 16:22:42 +0000273 ALOGD("Tethering services running");
San Mehat9d10b342010-01-18 09:51:02 -0800274 }
275
276 return 0;
277}
278
Luke Huangb5733d72018-08-21 17:17:19 +0800279std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
280 std::vector<char*> addrsCstrVec{};
281 addrsCstrVec.reserve(addrs.size());
282 for (const auto& addr : addrs) {
283 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
284 }
285 return addrsCstrVec;
286}
287
288int TetherController::startTethering(const std::vector<std::string>& dhcpRanges) {
289 struct in_addr v4_addr;
290 for (const auto& dhcpRange : dhcpRanges) {
291 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
292 return -EINVAL;
293 }
294 }
295 auto dhcp_ranges = toCstrVec(dhcpRanges);
296 return startTethering(dhcp_ranges.size(), dhcp_ranges.data());
297}
298
San Mehat9d10b342010-01-18 09:51:02 -0800299int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900300 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800301
302 if (mDaemonPid == 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000303 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800304 return 0;
305 }
306
Steve Block7b984e32011-12-20 16:22:42 +0000307 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800308
309 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700310 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800311 mDaemonPid = 0;
312 close(mDaemonFd);
313 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900314 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000315 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800316 return 0;
317}
Matthew Xie19944102012-07-12 16:42:07 -0700318
San Mehat9d10b342010-01-18 09:51:02 -0800319bool TetherController::isTetheringStarted() {
320 return (mDaemonPid == 0 ? false : true);
321}
322
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900323// dnsmasq can't parse commands larger than this due to the fixed-size buffer
324// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
325// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900326const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800327
Bernie Innocenti45238a12018-12-04 14:57:48 +0900328// TODO: convert callers to the overload taking a vector<string>
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700329int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700330 Fwmark fwmark;
331 fwmark.netId = netId;
332 fwmark.explicitlySelected = true;
333 fwmark.protectedFromVpn = true;
334 fwmark.permission = PERMISSION_SYSTEM;
335
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900336 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800337
Erik Kline1d065ba2016-06-08 13:24:45 +0900338 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900339 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700340 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800341
Lorenzo Colittic2841282015-11-25 22:13:57 +0900342 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700343 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900344 freeaddrinfo(res);
345 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000346 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900347 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900348 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800349 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800350 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800351
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900352 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
353 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800354 break;
355 }
356
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900357 daemonCmd += SEPARATOR;
358 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900359 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800360 }
361
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700362 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900363 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800364 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900365 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900366 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900367 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800368 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800369 }
370 }
371 return 0;
372}
373
Luke Huangb5733d72018-08-21 17:17:19 +0800374int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
375 struct in_addr v4_addr;
376 struct in6_addr v6_addr;
377 for (const auto& server : servers) {
378 if (!inet_pton(AF_INET, server.c_str(), &v4_addr) &&
379 !inet_pton(AF_INET6, server.c_str(), &v6_addr)) {
380 return -EINVAL;
381 }
382 }
383 auto dnsServers = toCstrVec(servers);
384 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
385}
386
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700387unsigned TetherController::getDnsNetId() {
388 return mDnsNetId;
389}
390
Erik Kline1d065ba2016-06-08 13:24:45 +0900391const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800392 return mDnsForwarders;
393}
394
Erik Kline1d065ba2016-06-08 13:24:45 +0900395bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900396 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800397 bool haveInterfaces = false;
398
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900399 for (const auto& ifname : mInterfaces) {
400 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
401 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800402 break;
403 }
404
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900405 daemonCmd += SEPARATOR;
406 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800407 haveInterfaces = true;
408 }
409
Erik Kline15079dd2018-05-18 23:10:56 +0900410 if (!haveInterfaces) {
411 mDnsmasqState.update_ifaces_cmd.clear();
412 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900413 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900414 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800415 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900416 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800417}
418
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800419int TetherController::tetherInterface(const char *interface) {
420 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700421 if (!isIfaceName(interface)) {
422 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800423 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700424 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800425
Erik Kline1d065ba2016-06-08 13:24:45 +0900426 if (!configureForIPv6Router(interface)) {
427 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800428 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900429 }
430 mInterfaces.push_back(interface);
431
432 if (!applyDnsInterfaces()) {
433 mInterfaces.pop_back();
434 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800435 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800436 } else {
437 return 0;
438 }
439}
440
San Mehat9d10b342010-01-18 09:51:02 -0800441int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800442 ALOGD("untetherInterface(%s)", interface);
443
Erik Kline1d065ba2016-06-08 13:24:45 +0900444 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
445 if (!strcmp(interface, it->c_str())) {
446 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800447
Erik Kline1d065ba2016-06-08 13:24:45 +0900448 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800449 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800450 }
451 }
452 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800453 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800454}
455
Erik Kline1d065ba2016-06-08 13:24:45 +0900456const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800457 return mInterfaces;
458}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900459
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900460int TetherController::setupIptablesHooks() {
461 int res;
462 res = setDefaults();
463 if (res < 0) {
464 return res;
465 }
466
467 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
468 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
469 // This is no longer optional and tethering will fail to start if it fails.
470 std::string mssRewriteCommand = StringPrintf(
471 "*mangle\n"
472 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
473 "COMMIT\n", LOCAL_MANGLE_FORWARD);
474
475 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
476 std::string defaultCommands = StringPrintf(
477 "*filter\n"
478 ":%s -\n"
479 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
480
481 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
482 if (res < 0) {
483 return res;
484 }
485
486 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
487 if (res < 0) {
488 return res;
489 }
490
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900491 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900492
493 return 0;
494}
495
496int TetherController::setDefaults() {
497 std::string v4Cmd = StringPrintf(
498 "*filter\n"
499 ":%s -\n"
500 "-A %s -j DROP\n"
501 "COMMIT\n"
502 "*nat\n"
503 ":%s -\n"
504 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
505
506 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900507 "*filter\n"
508 ":%s -\n"
509 "COMMIT\n"
510 "*raw\n"
511 ":%s -\n"
512 "COMMIT\n",
513 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900514
515 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
516 if (res < 0) {
517 return res;
518 }
519
520 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
521 if (res < 0) {
522 return res;
523 }
524
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900525 return 0;
526}
527
528int TetherController::enableNat(const char* intIface, const char* extIface) {
529 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
530
531 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900532 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900533 }
534
535 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
536 if (!strcmp(intIface, extIface)) {
537 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900538 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900539 }
540
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900541 if (isForwardingPairEnabled(intIface, extIface)) {
542 return 0;
543 }
544
545 // add this if we are the first enabled nat for this upstream
546 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900547 std::vector<std::string> v4Cmds = {
548 "*nat",
549 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
550 "COMMIT\n"
551 };
552
Luke Huangae038f82018-11-05 11:17:31 +0900553 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
554 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900555 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900556 if (!isAnyForwardingPairEnabled()) {
557 // unwind what's been done, but don't care about success - what more could we do?
558 setDefaults();
559 }
Luke Huang19b49c52018-10-22 12:12:05 +0900560 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900561 }
562 }
563
564 if (setForwardRules(true, intIface, extIface) != 0) {
565 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900566 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900567 setDefaults();
568 }
Luke Huang19b49c52018-10-22 12:12:05 +0900569 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900570 }
571
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900572 return 0;
573}
574
Luke Huangae038f82018-11-05 11:17:31 +0900575int TetherController::setTetherGlobalAlertRule() {
576 // Only add this if we are the first enabled nat
577 if (isAnyForwardingPairEnabled()) {
578 return 0;
579 }
580 const std::string cmds =
581 "*filter\n" +
582 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
583 "COMMIT\n";
584
585 return iptablesRestoreFunction(V4V6, cmds, nullptr);
586}
587
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900588int TetherController::setupIPv6CountersChain() {
589 // Only add this if we are the first enabled nat
590 if (isAnyForwardingPairEnabled()) {
591 return 0;
592 }
593
594 /*
595 * IPv6 tethering doesn't need the state-based conntrack rules, so
596 * it unconditionally jumps to the tether counters chain all the time.
597 */
Luke Huangae038f82018-11-05 11:17:31 +0900598 const std::string v6Cmds =
599 "*filter\n" +
600 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900601
Luke Huangae038f82018-11-05 11:17:31 +0900602 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900603}
604
605// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
606TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
607 const std::string& intIface, const std::string& extIface) {
608 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
609 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
610 if (it->second.iface == intIface) {
611 return &(it->second);
612 }
613 }
614 return nullptr;
615}
616
617void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
618 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
619 if (existingEntry != nullptr) {
620 existingEntry->active = true;
621 return;
622 }
623
624 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
625 .iface = intIface,
626 .active = true
627 }));
628}
629
630void TetherController::markForwardingPairDisabled(
631 const std::string& intIface, const std::string& extIface) {
632 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
633 if (existingEntry == nullptr) {
634 return;
635 }
636
637 existingEntry->active = false;
638}
639
640bool TetherController::isForwardingPairEnabled(
641 const std::string& intIface, const std::string& extIface) {
642 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
643 return existingEntry != nullptr && existingEntry->active;
644}
645
646bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
647 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
648 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
649 if (it->second.active) {
650 return true;
651 }
652 }
653 return false;
654}
655
656bool TetherController::isAnyForwardingPairEnabled() {
657 for (auto& it : mFwdIfaces) {
658 if (it.second.active) {
659 return true;
660 }
661 }
662 return false;
663}
664
665bool TetherController::tetherCountingRuleExists(
666 const std::string& iface1, const std::string& iface2) {
667 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
668 // is in the map regardless of its active status. Rules are added both ways so we check with
669 // the 2 combinations.
670 return findForwardingDownstream(iface1, iface2) != nullptr
671 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900672}
673
674/* static */
675std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
676 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
677}
678
679int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
680 const char *op = add ? "-A" : "-D";
681
682 std::string rpfilterCmd = StringPrintf(
683 "*raw\n"
684 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
685 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
686 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900687 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900688 }
689
690 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900691 "*raw",
692 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
693 LOCAL_RAW_PREROUTING, intIface),
694 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
695 LOCAL_RAW_PREROUTING, intIface),
696 "COMMIT",
697 "*filter",
698 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
699 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
700 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
701 intIface, extIface),
702 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
703 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900704 };
705
706 std::vector<std::string> v6 = {
707 "*filter",
708 };
709
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900710 // We only ever add tethering quota rules so that they stick.
711 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900712 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900713 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900714 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900715 v6.push_back(makeTetherCountingRule(extIface, intIface));
716 }
717
718 // Always make sure the drop rule is at the end.
719 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900720 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900721 if (add) {
722 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
723 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
724 }
725
726 v4.push_back("COMMIT\n");
727 v6.push_back("COMMIT\n");
728
729 // We only add IPv6 rules here, never remove them.
730 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
731 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
732 // unwind what's been done, but don't care about success - what more could we do?
733 if (add) {
734 setForwardRules(false, intIface, extIface);
735 }
Luke Huang19b49c52018-10-22 12:12:05 +0900736 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900737 }
738
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900739 if (add) {
740 addForwardingPair(intIface, extIface);
741 } else {
742 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900743 }
744
745 return 0;
746}
747
748int TetherController::disableNat(const char* intIface, const char* extIface) {
749 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900750 errno = ENODEV;
751 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900752 }
753
754 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900755 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900756 setDefaults();
757 }
758 return 0;
759}
760
761void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
762 for (TetherStats& existing : statsList) {
763 if (existing.addStatsIfMatch(stats)) {
764 return;
765 }
766 }
767 // No match. Insert a new interface pair.
768 statsList.push_back(stats);
769}
770
771/*
772 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900773 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900774 * pkts bytes target prot opt in out source destination
775 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
776 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
777 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
778 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
779 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900780 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900781 * pkts bytes target prot opt in out source destination
782 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
783 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
784 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900785 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900786int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900787 const std::string& statsOutput,
788 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800789 enum IndexOfIptChain {
790 ORIG_LINE,
791 PACKET_COUNTS,
792 BYTE_COUNTS,
793 HYPHEN,
794 IFACE0_NAME,
795 IFACE1_NAME,
796 SOURCE,
797 DESTINATION
798 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900799 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900800 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900801
waynema71a0b592018-11-21 13:31:34 +0800802 static const std::string NUM = "(\\d+)";
803 static const std::string IFACE = "([^\\s]+)";
804 static const std::string DST = "(0.0.0.0/0|::/0)";
805 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
806 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
807 "\\s+" + DST + "\\s+" + DST;
808 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900809
waynema71a0b592018-11-21 13:31:34 +0800810 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
811 int headerLine = 0;
812 for (const std::string& line : lines) {
813 // Skip headers.
814 if (headerLine < 2) {
815 if (line.empty()) {
816 ALOGV("Empty header while parsing tethering stats");
817 return -EREMOTEIO;
818 }
819 headerLine++;
820 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900821 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900822
waynema71a0b592018-11-21 13:31:34 +0800823 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900824
waynema71a0b592018-11-21 13:31:34 +0800825 extraProcessingInfo = line;
826 std::smatch matches;
827 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
828 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
829 // IPv4 has "--" indicating what to do with fragments...
830 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
831 // ... but IPv6 does not.
832 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
833 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
834 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
835 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
836 std::string iface0 = matches[IFACE0_NAME].str();
837 std::string iface1 = matches[IFACE1_NAME].str();
838 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900839
waynema71a0b592018-11-21 13:31:34 +0800840 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
841 " rest=<%s> orig line=<%s>",
842 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900843 /*
844 * The following assumes that the 1st rule has in:extIface out:intIface,
845 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900846 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900847 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900848 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800849 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
850 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900851 stats.intIface = iface0;
852 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900853 stats.txPackets = packets;
854 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900855 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800856 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
857 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900858 stats.rxPackets = packets;
859 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900860 }
861 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900862 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900863 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900864 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900865 }
866 }
867
868 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900869 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900870 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900871 }
872 return 0;
873}
874
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900875StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900876 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900877 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900878
879 for (const IptablesTarget target : {V4, V6}) {
880 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900881 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900882 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
883 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900884 }
885
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900886 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900887 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
888 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900889 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900890 }
891 }
892
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900893 return statsList;
894}
895
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900896} // namespace net
897} // namespace android