blob: daa07b47238f022548a18e3cebc0ed4971d3690b [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
Luke Huang94c43a12019-02-14 19:51:38 +0800116pid_t vfork_and_exec(const char* path, char* const argv[], int pipefd[2]) {
117 auto pid = vfork();
118 if (pid) {
119 // Parent process, or vfork() failed. Let caller deal with it.
120 return pid;
121 }
122
123 // Don't modify any memory between vfork and execv.
124 // Changing state of file descriptors would be fine.
125 // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
126 // duplicated fd.
127 if (dup2(pipefd[0], STDIN_FILENO) != STDIN_FILENO) {
128 // dup2 failed
129 _exit(EXIT_FAILURE);
130 }
131 execv(path, argv);
132 // Should never get here!
133 _exit(EXIT_FAILURE);
134 return pid;
135}
136
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900137} // namespace
138
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900139auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
140
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900141const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
142 "*filter\n"
143 "-nvx -L %s\n"
144 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
145
Erik Kline15079dd2018-05-18 23:10:56 +0900146int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
147 if (cmd.empty()) return 0;
148
Erik Klineb31fd692018-06-06 20:50:11 +0900149 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900150 // Send the trailing \0 as well.
151 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900152 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900153 errno = EREMOTEIO;
154 return -1;
155 }
156 return 0;
157}
158
159void TetherController::DnsmasqState::clear() {
160 update_ifaces_cmd.clear();
161 update_dns_cmd.clear();
162}
163
164int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
165 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
166}
167
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700168TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900169 if (inBpToolsMode()) {
170 enableForwarding(BP_TOOLS_MODE);
171 } else {
172 setIpFwdEnabled();
173 }
San Mehat9d10b342010-01-18 09:51:02 -0800174}
175
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900176bool TetherController::setIpFwdEnabled() {
177 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900178 bool disable = mForwardingRequests.empty();
179 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900180 ALOGD("Setting IP forward enable = %s", value);
181 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
182 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900183 if (disable) {
184 // Turning off the forwarding sysconf in the kernel has the side effect
185 // of turning on ICMP redirect, which is a security hazard.
186 // Turn ICMP redirect back off immediately.
187 int rv = InterfaceController::disableIcmpRedirects();
188 success &= (rv == 0);
189 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900190 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800191}
192
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900193bool TetherController::enableForwarding(const char* requester) {
194 // Don't return an error if this requester already requested forwarding. Only return errors for
195 // things that the caller caller needs to care about, such as "couldn't write to the file to
196 // enable forwarding".
197 mForwardingRequests.insert(requester);
198 return setIpFwdEnabled();
199}
San Mehat9d10b342010-01-18 09:51:02 -0800200
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900201bool TetherController::disableForwarding(const char* requester) {
202 mForwardingRequests.erase(requester);
203 return setIpFwdEnabled();
204}
San Mehat9d10b342010-01-18 09:51:02 -0800205
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900206size_t TetherController::forwardingRequestCount() {
207 return mForwardingRequests.size();
San Mehat9d10b342010-01-18 09:51:02 -0800208}
209
Erik Kline13fa01f2015-11-12 17:49:23 +0900210int TetherController::startTethering(int num_addrs, char **dhcp_ranges) {
San Mehat9d10b342010-01-18 09:51:02 -0800211 if (mDaemonPid != 0) {
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
San Mehat9d10b342010-01-18 09:51:02 -0800219 int pipefd[2];
220
Luke Huang94c43a12019-02-14 19:51:38 +0800221 if (pipe2(pipefd, O_CLOEXEC) < 0) {
Luke Huangb5733d72018-08-21 17:17:19 +0800222 int res = errno;
Luke Huang94c43a12019-02-14 19:51:38 +0800223 ALOGE("pipe2() failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800224 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800225 }
226
Luke Huang94c43a12019-02-14 19:51:38 +0800227 // Set parameters
228 Fwmark fwmark;
229 fwmark.netId = NetworkController::LOCAL_NET_ID;
230 fwmark.explicitlySelected = true;
231 fwmark.protectedFromVpn = true;
232 fwmark.permission = PERMISSION_SYSTEM;
233 char markStr[UINT32_HEX_STRLEN];
234 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800235
Luke Huang94c43a12019-02-14 19:51:38 +0800236 std::vector<const std::string> argVector = {
Erik Kline5f0358b2018-02-16 15:08:09 +0900237 "/system/bin/dnsmasq",
238 "--keep-in-foreground",
239 "--no-resolv",
240 "--no-poll",
241 "--dhcp-authoritative",
242 // TODO: pipe through metered status from ConnService
243 "--dhcp-option-force=43,ANDROID_METERED",
244 "--pid-file",
Luke Huang94c43a12019-02-14 19:51:38 +0800245 "--listen-mark",
246 markStr,
247 "--user",
248 kDnsmasqUsername,
249 };
San Mehat9d10b342010-01-18 09:51:02 -0800250
Luke Huang94c43a12019-02-14 19:51:38 +0800251 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is
252 // passed.
253 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
254 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
255 dhcp_ranges[addrIndex + 1]));
San Mehat9d10b342010-01-18 09:51:02 -0800256 }
257
Luke Huang94c43a12019-02-14 19:51:38 +0800258 auto args = (char**)std::calloc(argVector.size() + 1, sizeof(char*));
259 for (unsigned i = 0; i < argVector.size(); i++) {
260 args[i] = (char*)argVector[i].c_str();
261 }
262
263 /*
264 * TODO: Create a monitoring thread to handle and restart
265 * the daemon if it exits prematurely
266 */
267 pid_t pid = vfork_and_exec(args[0], args, pipefd);
268 int res = errno;
269 close(pipefd[0]);
270 free(args);
271 if (pid < 0) {
272 ALOGE("vfork & exec failed (%s)", strerror(errno));
273 close(pipefd[1]);
274 return -res;
275 }
276
277 mDaemonPid = pid;
278 mDaemonFd = pipefd[1];
279 configureForTethering(true);
280 applyDnsInterfaces();
281 ALOGD("Tethering services running");
282
San Mehat9d10b342010-01-18 09:51:02 -0800283 return 0;
284}
285
Luke Huangb5733d72018-08-21 17:17:19 +0800286std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
287 std::vector<char*> addrsCstrVec{};
288 addrsCstrVec.reserve(addrs.size());
289 for (const auto& addr : addrs) {
290 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
291 }
292 return addrsCstrVec;
293}
294
295int TetherController::startTethering(const std::vector<std::string>& dhcpRanges) {
296 struct in_addr v4_addr;
297 for (const auto& dhcpRange : dhcpRanges) {
298 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
299 return -EINVAL;
300 }
301 }
302 auto dhcp_ranges = toCstrVec(dhcpRanges);
303 return startTethering(dhcp_ranges.size(), dhcp_ranges.data());
304}
305
San Mehat9d10b342010-01-18 09:51:02 -0800306int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900307 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800308
309 if (mDaemonPid == 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000310 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800311 return 0;
312 }
313
Steve Block7b984e32011-12-20 16:22:42 +0000314 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800315
316 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700317 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800318 mDaemonPid = 0;
319 close(mDaemonFd);
320 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900321 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000322 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800323 return 0;
324}
Matthew Xie19944102012-07-12 16:42:07 -0700325
San Mehat9d10b342010-01-18 09:51:02 -0800326bool TetherController::isTetheringStarted() {
327 return (mDaemonPid == 0 ? false : true);
328}
329
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900330// dnsmasq can't parse commands larger than this due to the fixed-size buffer
331// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
332// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900333const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800334
Bernie Innocenti45238a12018-12-04 14:57:48 +0900335// TODO: convert callers to the overload taking a vector<string>
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700336int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700337 Fwmark fwmark;
338 fwmark.netId = netId;
339 fwmark.explicitlySelected = true;
340 fwmark.protectedFromVpn = true;
341 fwmark.permission = PERMISSION_SYSTEM;
342
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900343 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800344
Erik Kline1d065ba2016-06-08 13:24:45 +0900345 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900346 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700347 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800348
Lorenzo Colittic2841282015-11-25 22:13:57 +0900349 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700350 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900351 freeaddrinfo(res);
352 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000353 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900354 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900355 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800356 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800357 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800358
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900359 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
360 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800361 break;
362 }
363
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900364 daemonCmd += SEPARATOR;
365 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900366 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800367 }
368
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700369 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900370 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800371 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900372 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900373 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900374 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800375 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800376 }
377 }
378 return 0;
379}
380
Luke Huangb5733d72018-08-21 17:17:19 +0800381int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
382 struct in_addr v4_addr;
383 struct in6_addr v6_addr;
384 for (const auto& server : servers) {
385 if (!inet_pton(AF_INET, server.c_str(), &v4_addr) &&
386 !inet_pton(AF_INET6, server.c_str(), &v6_addr)) {
387 return -EINVAL;
388 }
389 }
390 auto dnsServers = toCstrVec(servers);
391 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
392}
393
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700394unsigned TetherController::getDnsNetId() {
395 return mDnsNetId;
396}
397
Erik Kline1d065ba2016-06-08 13:24:45 +0900398const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800399 return mDnsForwarders;
400}
401
Erik Kline1d065ba2016-06-08 13:24:45 +0900402bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900403 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800404 bool haveInterfaces = false;
405
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900406 for (const auto& ifname : mInterfaces) {
407 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
408 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800409 break;
410 }
411
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900412 daemonCmd += SEPARATOR;
413 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800414 haveInterfaces = true;
415 }
416
Erik Kline15079dd2018-05-18 23:10:56 +0900417 if (!haveInterfaces) {
418 mDnsmasqState.update_ifaces_cmd.clear();
419 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900420 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900421 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800422 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900423 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800424}
425
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800426int TetherController::tetherInterface(const char *interface) {
427 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700428 if (!isIfaceName(interface)) {
429 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800430 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700431 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800432
Erik Kline1d065ba2016-06-08 13:24:45 +0900433 if (!configureForIPv6Router(interface)) {
434 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800435 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900436 }
437 mInterfaces.push_back(interface);
438
439 if (!applyDnsInterfaces()) {
440 mInterfaces.pop_back();
441 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800442 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800443 } else {
444 return 0;
445 }
446}
447
San Mehat9d10b342010-01-18 09:51:02 -0800448int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800449 ALOGD("untetherInterface(%s)", interface);
450
Erik Kline1d065ba2016-06-08 13:24:45 +0900451 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
452 if (!strcmp(interface, it->c_str())) {
453 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800454
Erik Kline1d065ba2016-06-08 13:24:45 +0900455 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800456 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800457 }
458 }
459 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800460 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800461}
462
Erik Kline1d065ba2016-06-08 13:24:45 +0900463const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800464 return mInterfaces;
465}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900466
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900467int TetherController::setupIptablesHooks() {
468 int res;
469 res = setDefaults();
470 if (res < 0) {
471 return res;
472 }
473
474 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
475 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
476 // This is no longer optional and tethering will fail to start if it fails.
477 std::string mssRewriteCommand = StringPrintf(
478 "*mangle\n"
479 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
480 "COMMIT\n", LOCAL_MANGLE_FORWARD);
481
482 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
483 std::string defaultCommands = StringPrintf(
484 "*filter\n"
485 ":%s -\n"
486 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
487
488 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
489 if (res < 0) {
490 return res;
491 }
492
493 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
494 if (res < 0) {
495 return res;
496 }
497
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900498 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900499
500 return 0;
501}
502
503int TetherController::setDefaults() {
504 std::string v4Cmd = StringPrintf(
505 "*filter\n"
506 ":%s -\n"
507 "-A %s -j DROP\n"
508 "COMMIT\n"
509 "*nat\n"
510 ":%s -\n"
511 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
512
513 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900514 "*filter\n"
515 ":%s -\n"
516 "COMMIT\n"
517 "*raw\n"
518 ":%s -\n"
519 "COMMIT\n",
520 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900521
522 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
523 if (res < 0) {
524 return res;
525 }
526
527 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
528 if (res < 0) {
529 return res;
530 }
531
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900532 return 0;
533}
534
535int TetherController::enableNat(const char* intIface, const char* extIface) {
536 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
537
538 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900539 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900540 }
541
542 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
543 if (!strcmp(intIface, extIface)) {
544 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900545 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900546 }
547
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900548 if (isForwardingPairEnabled(intIface, extIface)) {
549 return 0;
550 }
551
552 // add this if we are the first enabled nat for this upstream
553 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900554 std::vector<std::string> v4Cmds = {
555 "*nat",
556 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
557 "COMMIT\n"
558 };
559
Luke Huangae038f82018-11-05 11:17:31 +0900560 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
561 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900562 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900563 if (!isAnyForwardingPairEnabled()) {
564 // unwind what's been done, but don't care about success - what more could we do?
565 setDefaults();
566 }
Luke Huang19b49c52018-10-22 12:12:05 +0900567 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900568 }
569 }
570
571 if (setForwardRules(true, intIface, extIface) != 0) {
572 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900573 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900574 setDefaults();
575 }
Luke Huang19b49c52018-10-22 12:12:05 +0900576 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900577 }
578
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900579 return 0;
580}
581
Luke Huangae038f82018-11-05 11:17:31 +0900582int TetherController::setTetherGlobalAlertRule() {
583 // Only add this if we are the first enabled nat
584 if (isAnyForwardingPairEnabled()) {
585 return 0;
586 }
587 const std::string cmds =
588 "*filter\n" +
589 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
590 "COMMIT\n";
591
592 return iptablesRestoreFunction(V4V6, cmds, nullptr);
593}
594
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900595int TetherController::setupIPv6CountersChain() {
596 // Only add this if we are the first enabled nat
597 if (isAnyForwardingPairEnabled()) {
598 return 0;
599 }
600
601 /*
602 * IPv6 tethering doesn't need the state-based conntrack rules, so
603 * it unconditionally jumps to the tether counters chain all the time.
604 */
Luke Huangae038f82018-11-05 11:17:31 +0900605 const std::string v6Cmds =
606 "*filter\n" +
607 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900608
Luke Huangae038f82018-11-05 11:17:31 +0900609 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900610}
611
612// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
613TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
614 const std::string& intIface, const std::string& extIface) {
615 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
616 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
617 if (it->second.iface == intIface) {
618 return &(it->second);
619 }
620 }
621 return nullptr;
622}
623
624void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
625 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
626 if (existingEntry != nullptr) {
627 existingEntry->active = true;
628 return;
629 }
630
631 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
632 .iface = intIface,
633 .active = true
634 }));
635}
636
637void TetherController::markForwardingPairDisabled(
638 const std::string& intIface, const std::string& extIface) {
639 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
640 if (existingEntry == nullptr) {
641 return;
642 }
643
644 existingEntry->active = false;
645}
646
647bool TetherController::isForwardingPairEnabled(
648 const std::string& intIface, const std::string& extIface) {
649 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
650 return existingEntry != nullptr && existingEntry->active;
651}
652
653bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
654 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
655 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
656 if (it->second.active) {
657 return true;
658 }
659 }
660 return false;
661}
662
663bool TetherController::isAnyForwardingPairEnabled() {
664 for (auto& it : mFwdIfaces) {
665 if (it.second.active) {
666 return true;
667 }
668 }
669 return false;
670}
671
672bool TetherController::tetherCountingRuleExists(
673 const std::string& iface1, const std::string& iface2) {
674 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
675 // is in the map regardless of its active status. Rules are added both ways so we check with
676 // the 2 combinations.
677 return findForwardingDownstream(iface1, iface2) != nullptr
678 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900679}
680
681/* static */
682std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
683 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
684}
685
686int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
687 const char *op = add ? "-A" : "-D";
688
689 std::string rpfilterCmd = StringPrintf(
690 "*raw\n"
691 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
692 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
693 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900694 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900695 }
696
697 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900698 "*raw",
699 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
700 LOCAL_RAW_PREROUTING, intIface),
701 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
702 LOCAL_RAW_PREROUTING, intIface),
703 "COMMIT",
704 "*filter",
705 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
706 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
707 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
708 intIface, extIface),
709 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
710 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900711 };
712
713 std::vector<std::string> v6 = {
714 "*filter",
715 };
716
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900717 // We only ever add tethering quota rules so that they stick.
718 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900719 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900720 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900721 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900722 v6.push_back(makeTetherCountingRule(extIface, intIface));
723 }
724
725 // Always make sure the drop rule is at the end.
726 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900727 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900728 if (add) {
729 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
730 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
731 }
732
733 v4.push_back("COMMIT\n");
734 v6.push_back("COMMIT\n");
735
736 // We only add IPv6 rules here, never remove them.
737 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
738 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
739 // unwind what's been done, but don't care about success - what more could we do?
740 if (add) {
741 setForwardRules(false, intIface, extIface);
742 }
Luke Huang19b49c52018-10-22 12:12:05 +0900743 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900744 }
745
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900746 if (add) {
747 addForwardingPair(intIface, extIface);
748 } else {
749 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900750 }
751
752 return 0;
753}
754
755int TetherController::disableNat(const char* intIface, const char* extIface) {
756 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900757 errno = ENODEV;
758 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900759 }
760
761 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900762 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900763 setDefaults();
764 }
765 return 0;
766}
767
768void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
769 for (TetherStats& existing : statsList) {
770 if (existing.addStatsIfMatch(stats)) {
771 return;
772 }
773 }
774 // No match. Insert a new interface pair.
775 statsList.push_back(stats);
776}
777
778/*
779 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900780 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900781 * pkts bytes target prot opt in out source destination
782 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
783 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
784 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
785 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
786 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900787 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900788 * pkts bytes target prot opt in out source destination
789 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
790 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
791 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900792 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900793int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900794 const std::string& statsOutput,
795 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800796 enum IndexOfIptChain {
797 ORIG_LINE,
798 PACKET_COUNTS,
799 BYTE_COUNTS,
800 HYPHEN,
801 IFACE0_NAME,
802 IFACE1_NAME,
803 SOURCE,
804 DESTINATION
805 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900806 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900807 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900808
waynema71a0b592018-11-21 13:31:34 +0800809 static const std::string NUM = "(\\d+)";
810 static const std::string IFACE = "([^\\s]+)";
811 static const std::string DST = "(0.0.0.0/0|::/0)";
812 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
813 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
814 "\\s+" + DST + "\\s+" + DST;
815 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900816
waynema71a0b592018-11-21 13:31:34 +0800817 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
818 int headerLine = 0;
819 for (const std::string& line : lines) {
820 // Skip headers.
821 if (headerLine < 2) {
822 if (line.empty()) {
823 ALOGV("Empty header while parsing tethering stats");
824 return -EREMOTEIO;
825 }
826 headerLine++;
827 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900828 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900829
waynema71a0b592018-11-21 13:31:34 +0800830 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900831
waynema71a0b592018-11-21 13:31:34 +0800832 extraProcessingInfo = line;
833 std::smatch matches;
834 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
835 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
836 // IPv4 has "--" indicating what to do with fragments...
837 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
838 // ... but IPv6 does not.
839 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
840 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
841 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
842 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
843 std::string iface0 = matches[IFACE0_NAME].str();
844 std::string iface1 = matches[IFACE1_NAME].str();
845 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900846
waynema71a0b592018-11-21 13:31:34 +0800847 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
848 " rest=<%s> orig line=<%s>",
849 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900850 /*
851 * The following assumes that the 1st rule has in:extIface out:intIface,
852 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900853 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900854 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900855 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800856 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
857 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900858 stats.intIface = iface0;
859 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900860 stats.txPackets = packets;
861 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900862 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800863 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
864 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900865 stats.rxPackets = packets;
866 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900867 }
868 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900869 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900870 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900871 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900872 }
873 }
874
875 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900876 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900877 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900878 }
879 return 0;
880}
881
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900882StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900883 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900884 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900885
886 for (const IptablesTarget target : {V4, V6}) {
887 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900888 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900889 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
890 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900891 }
892
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900893 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900894 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
895 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900896 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900897 }
898 }
899
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900900 return statsList;
901}
902
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900903} // namespace net
904} // namespace android