blob: c684a1adf56372bc93240f3927ad73380c5e4cef [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"
Lorenzo Colittia93126d2017-08-24 13:28:19 +090039#include <android-base/stringprintf.h>
George Burgess IVe3dc1312019-02-28 11:27:04 -080040#include <android-base/strings.h>
41#include <android-base/unique_fd.h>
Kazuhiro Ondo6b858eb2011-06-24 20:31:03 -050042#include <cutils/properties.h>
Logan Chien3f461482018-04-23 14:31:32 +080043#include <log/log.h>
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090044#include <netdutils/StatusOr.h>
San Mehat9d10b342010-01-18 09:51:02 -080045
Erik Klineb31fd692018-06-06 20:50:11 +090046#include "Controllers.h"
Lorenzo Colitti667c4772014-08-26 14:13:07 -070047#include "Fwmark.h"
JP Abgrall69261cb2014-06-19 18:35:24 -070048#include "NetdConstants.h"
Lorenzo Colitti667c4772014-08-26 14:13:07 -070049#include "Permission.h"
Erik Kline1d065ba2016-06-08 13:24:45 +090050#include "InterfaceController.h"
Lorenzo Colittie20a5262017-05-09 18:30:44 +090051#include "NetworkController.h"
Lorenzo Colittia93126d2017-08-24 13:28:19 +090052#include "ResponseCode.h"
San Mehat9d10b342010-01-18 09:51:02 -080053#include "TetherController.h"
54
Bernie Innocenti4debf3b2018-09-12 13:54:50 +090055namespace android {
56namespace net {
57
Lorenzo Colittia93126d2017-08-24 13:28:19 +090058using android::base::Join;
George Burgess IVe3dc1312019-02-28 11:27:04 -080059using android::base::Pipe;
Erik Klineb31fd692018-06-06 20:50:11 +090060using android::base::StringPrintf;
George Burgess IVe3dc1312019-02-28 11:27:04 -080061using android::base::unique_fd;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090062using android::netdutils::statusFromErrno;
Erik Klineb31fd692018-06-06 20:50:11 +090063using android::netdutils::StatusOr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090064
Lorenzo Colitti799625c2015-02-25 12:52:00 +090065namespace {
66
Erik Kline1d065ba2016-06-08 13:24:45 +090067const char BP_TOOLS_MODE[] = "bp-tools";
68const char IPV4_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv4/ip_forward";
69const char IPV6_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv6/conf/all/forwarding";
70const char SEPARATOR[] = "|";
Erik Kline93f9b222017-10-22 21:24:58 +090071constexpr const char kTcpBeLiberal[] = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
Lorenzo Colitti799625c2015-02-25 12:52:00 +090072
Erik Kline5f0358b2018-02-16 15:08:09 +090073// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
74constexpr const char kDnsmasqUsername[] = "dns_tether";
75
Lorenzo Colitti799625c2015-02-25 12:52:00 +090076bool writeToFile(const char* filename, const char* value) {
Nick Kralevichb95c60c2016-11-19 09:09:16 -080077 int fd = open(filename, O_WRONLY | O_CLOEXEC);
Nicolas Geoffrayafd40372015-03-16 11:58:06 +000078 if (fd < 0) {
79 ALOGE("Failed to open %s: %s", filename, strerror(errno));
80 return false;
81 }
82
83 const ssize_t len = strlen(value);
84 if (write(fd, value, len) != len) {
85 ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
86 close(fd);
87 return false;
88 }
89 close(fd);
90 return true;
Lorenzo Colitti799625c2015-02-25 12:52:00 +090091}
92
Erik Kline93f9b222017-10-22 21:24:58 +090093// TODO: Consider altering TCP and UDP timeouts as well.
94void configureForTethering(bool enabled) {
95 writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
96}
97
Erik Kline1d065ba2016-06-08 13:24:45 +090098bool configureForIPv6Router(const char *interface) {
99 return (InterfaceController::setEnableIPv6(interface, 0) == 0)
100 && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
Erik Kline6cddf512016-08-09 15:28:42 +0900101 && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
102 && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
Erik Kline1d065ba2016-06-08 13:24:45 +0900103 && (InterfaceController::setEnableIPv6(interface, 1) == 0);
104}
105
106void configureForIPv6Client(const char *interface) {
107 InterfaceController::setAcceptIPv6Ra(interface, 1);
Erik Kline6cddf512016-08-09 15:28:42 +0900108 InterfaceController::setAcceptIPv6Dad(interface, 1);
109 InterfaceController::setIPv6DadTransmits(interface, "1");
Erik Kline1d065ba2016-06-08 13:24:45 +0900110 InterfaceController::setEnableIPv6(interface, 0);
111}
112
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900113bool inBpToolsMode() {
114 // In BP tools mode, do not disable IP forwarding
115 char bootmode[PROPERTY_VALUE_MAX] = {0};
116 property_get("ro.bootmode", bootmode, "unknown");
117 return !strcmp(BP_TOOLS_MODE, bootmode);
118}
119
Luke Huang40962442019-02-26 11:46:10 +0800120int setPosixSpawnFileActionsAddDup2(posix_spawn_file_actions_t* fa, int fd, int new_fd) {
121 int res = posix_spawn_file_actions_init(fa);
122 if (res) {
123 return res;
Luke Huang94c43a12019-02-14 19:51:38 +0800124 }
Luke Huang40962442019-02-26 11:46:10 +0800125 return posix_spawn_file_actions_adddup2(fa, fd, new_fd);
126}
Luke Huang94c43a12019-02-14 19:51:38 +0800127
Luke Huang40962442019-02-26 11:46:10 +0800128int setPosixSpawnAttrFlags(posix_spawnattr_t* attr, short flags) {
129 int res = posix_spawnattr_init(attr);
130 if (res) {
131 return res;
Luke Huang94c43a12019-02-14 19:51:38 +0800132 }
Luke Huang40962442019-02-26 11:46:10 +0800133 return posix_spawnattr_setflags(attr, flags);
Luke Huang94c43a12019-02-14 19:51:38 +0800134}
135
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900136} // namespace
137
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900138auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
139
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900140const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
141 "*filter\n"
142 "-nvx -L %s\n"
143 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
144
Erik Kline15079dd2018-05-18 23:10:56 +0900145int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
146 if (cmd.empty()) return 0;
147
Erik Klineb31fd692018-06-06 20:50:11 +0900148 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900149 // Send the trailing \0 as well.
150 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900151 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900152 errno = EREMOTEIO;
153 return -1;
154 }
155 return 0;
156}
157
158void TetherController::DnsmasqState::clear() {
159 update_ifaces_cmd.clear();
160 update_dns_cmd.clear();
161}
162
163int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
164 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
165}
166
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700167TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900168 if (inBpToolsMode()) {
169 enableForwarding(BP_TOOLS_MODE);
170 } else {
171 setIpFwdEnabled();
172 }
San Mehat9d10b342010-01-18 09:51:02 -0800173}
174
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900175bool TetherController::setIpFwdEnabled() {
176 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900177 bool disable = mForwardingRequests.empty();
178 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900179 ALOGD("Setting IP forward enable = %s", value);
180 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
181 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900182 if (disable) {
183 // Turning off the forwarding sysconf in the kernel has the side effect
184 // of turning on ICMP redirect, which is a security hazard.
185 // Turn ICMP redirect back off immediately.
186 int rv = InterfaceController::disableIcmpRedirects();
187 success &= (rv == 0);
188 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900189 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800190}
191
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900192bool TetherController::enableForwarding(const char* requester) {
193 // Don't return an error if this requester already requested forwarding. Only return errors for
194 // things that the caller caller needs to care about, such as "couldn't write to the file to
195 // enable forwarding".
196 mForwardingRequests.insert(requester);
197 return setIpFwdEnabled();
198}
San Mehat9d10b342010-01-18 09:51:02 -0800199
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900200bool TetherController::disableForwarding(const char* requester) {
201 mForwardingRequests.erase(requester);
202 return setIpFwdEnabled();
203}
San Mehat9d10b342010-01-18 09:51:02 -0800204
Luke Huang728cf4c2019-03-14 19:43:02 +0800205const std::set<std::string>& TetherController::getIpfwdRequesterList() const {
206 return mForwardingRequests;
San Mehat9d10b342010-01-18 09:51:02 -0800207}
208
Erik Kline13fa01f2015-11-12 17:49:23 +0900209int TetherController::startTethering(int num_addrs, char **dhcp_ranges) {
San Mehat9d10b342010-01-18 09:51:02 -0800210 if (mDaemonPid != 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000211 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800212 errno = EBUSY;
Luke Huangb5733d72018-08-21 17:17:19 +0800213 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800214 }
215
Steve Block7b984e32011-12-20 16:22:42 +0000216 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800217
George Burgess IVe3dc1312019-02-28 11:27:04 -0800218 unique_fd pipeRead, pipeWrite;
219 if (!Pipe(&pipeRead, &pipeWrite, O_CLOEXEC)) {
Luke Huangb5733d72018-08-21 17:17:19 +0800220 int res = errno;
Luke Huang94c43a12019-02-14 19:51:38 +0800221 ALOGE("pipe2() failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800222 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800223 }
224
Luke Huang94c43a12019-02-14 19:51:38 +0800225 // Set parameters
226 Fwmark fwmark;
227 fwmark.netId = NetworkController::LOCAL_NET_ID;
228 fwmark.explicitlySelected = true;
229 fwmark.protectedFromVpn = true;
230 fwmark.permission = PERMISSION_SYSTEM;
231 char markStr[UINT32_HEX_STRLEN];
232 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800233
Luke Huang94c43a12019-02-14 19:51:38 +0800234 std::vector<const std::string> argVector = {
Erik Kline5f0358b2018-02-16 15:08:09 +0900235 "/system/bin/dnsmasq",
236 "--keep-in-foreground",
237 "--no-resolv",
238 "--no-poll",
239 "--dhcp-authoritative",
240 // TODO: pipe through metered status from ConnService
241 "--dhcp-option-force=43,ANDROID_METERED",
242 "--pid-file",
Luke Huang94c43a12019-02-14 19:51:38 +0800243 "--listen-mark",
244 markStr,
245 "--user",
246 kDnsmasqUsername,
247 };
San Mehat9d10b342010-01-18 09:51:02 -0800248
Luke Huang94c43a12019-02-14 19:51:38 +0800249 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is
250 // passed.
251 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
252 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
253 dhcp_ranges[addrIndex + 1]));
San Mehat9d10b342010-01-18 09:51:02 -0800254 }
255
George Burgess IVe3dc1312019-02-28 11:27:04 -0800256 std::vector<char*> args(argVector.size() + 1);
Luke Huang94c43a12019-02-14 19:51:38 +0800257 for (unsigned i = 0; i < argVector.size(); i++) {
258 args[i] = (char*)argVector[i].c_str();
259 }
260
261 /*
262 * TODO: Create a monitoring thread to handle and restart
263 * the daemon if it exits prematurely
264 */
Luke Huang40962442019-02-26 11:46:10 +0800265
266 // Note that don't modify any memory between vfork and execv.
267 // Changing state of file descriptors would be fine. See posix_spawn_file_actions_add*
268 // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
269 // duplicated fd.
270 posix_spawn_file_actions_t fa;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800271 int res = setPosixSpawnFileActionsAddDup2(&fa, pipeRead.get(), STDIN_FILENO);
Luke Huang40962442019-02-26 11:46:10 +0800272 if (res) {
273 ALOGE("posix_spawn set fa failed (%s)", strerror(res));
Luke Huang94c43a12019-02-14 19:51:38 +0800274 return -res;
275 }
276
Luke Huang40962442019-02-26 11:46:10 +0800277 posix_spawnattr_t attr;
278 res = setPosixSpawnAttrFlags(&attr, POSIX_SPAWN_USEVFORK);
279 if (res) {
280 ALOGE("posix_spawn set attr flag failed (%s)", strerror(res));
281 return -res;
282 }
283
284 pid_t pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800285 res = posix_spawn(&pid, args[0], &fa, &attr, &args[0], nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800286 posix_spawnattr_destroy(&attr);
287 posix_spawn_file_actions_destroy(&fa);
288 if (res) {
289 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800290 return -res;
291 }
Luke Huang94c43a12019-02-14 19:51:38 +0800292 mDaemonPid = pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800293 mDaemonFd = pipeWrite.release();
Luke Huang94c43a12019-02-14 19:51:38 +0800294 configureForTethering(true);
295 applyDnsInterfaces();
296 ALOGD("Tethering services running");
297
San Mehat9d10b342010-01-18 09:51:02 -0800298 return 0;
299}
300
Luke Huangb5733d72018-08-21 17:17:19 +0800301std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
302 std::vector<char*> addrsCstrVec{};
303 addrsCstrVec.reserve(addrs.size());
304 for (const auto& addr : addrs) {
305 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
306 }
307 return addrsCstrVec;
308}
309
310int TetherController::startTethering(const std::vector<std::string>& dhcpRanges) {
311 struct in_addr v4_addr;
312 for (const auto& dhcpRange : dhcpRanges) {
313 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
314 return -EINVAL;
315 }
316 }
317 auto dhcp_ranges = toCstrVec(dhcpRanges);
318 return startTethering(dhcp_ranges.size(), dhcp_ranges.data());
319}
320
San Mehat9d10b342010-01-18 09:51:02 -0800321int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900322 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800323
324 if (mDaemonPid == 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000325 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800326 return 0;
327 }
328
Steve Block7b984e32011-12-20 16:22:42 +0000329 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800330
331 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700332 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800333 mDaemonPid = 0;
334 close(mDaemonFd);
335 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900336 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000337 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800338 return 0;
339}
Matthew Xie19944102012-07-12 16:42:07 -0700340
San Mehat9d10b342010-01-18 09:51:02 -0800341bool TetherController::isTetheringStarted() {
342 return (mDaemonPid == 0 ? false : true);
343}
344
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900345// dnsmasq can't parse commands larger than this due to the fixed-size buffer
346// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
347// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900348const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800349
Luke Huang8dc1cac2019-03-30 16:12:31 +0800350// TODO: Remove overload function and update this after NDC migration.
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700351int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700352 Fwmark fwmark;
353 fwmark.netId = netId;
354 fwmark.explicitlySelected = true;
355 fwmark.protectedFromVpn = true;
356 fwmark.permission = PERMISSION_SYSTEM;
357
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900358 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800359
Erik Kline1d065ba2016-06-08 13:24:45 +0900360 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900361 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700362 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800363
Lorenzo Colittic2841282015-11-25 22:13:57 +0900364 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700365 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900366 freeaddrinfo(res);
367 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000368 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900369 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900370 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800371 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800372 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800373
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900374 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
375 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800376 break;
377 }
378
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900379 daemonCmd += SEPARATOR;
380 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900381 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800382 }
383
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700384 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900385 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800386 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900387 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900388 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900389 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800390 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800391 }
392 }
393 return 0;
394}
395
Luke Huangb5733d72018-08-21 17:17:19 +0800396int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
Luke Huangb5733d72018-08-21 17:17:19 +0800397 auto dnsServers = toCstrVec(servers);
398 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
399}
400
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700401unsigned TetherController::getDnsNetId() {
402 return mDnsNetId;
403}
404
Erik Kline1d065ba2016-06-08 13:24:45 +0900405const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800406 return mDnsForwarders;
407}
408
Erik Kline1d065ba2016-06-08 13:24:45 +0900409bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900410 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800411 bool haveInterfaces = false;
412
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900413 for (const auto& ifname : mInterfaces) {
414 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
415 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800416 break;
417 }
418
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900419 daemonCmd += SEPARATOR;
420 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800421 haveInterfaces = true;
422 }
423
Erik Kline15079dd2018-05-18 23:10:56 +0900424 if (!haveInterfaces) {
425 mDnsmasqState.update_ifaces_cmd.clear();
426 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900427 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900428 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800429 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900430 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800431}
432
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800433int TetherController::tetherInterface(const char *interface) {
434 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700435 if (!isIfaceName(interface)) {
436 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800437 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700438 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800439
Erik Kline1d065ba2016-06-08 13:24:45 +0900440 if (!configureForIPv6Router(interface)) {
441 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800442 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900443 }
444 mInterfaces.push_back(interface);
445
446 if (!applyDnsInterfaces()) {
447 mInterfaces.pop_back();
448 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800449 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800450 } else {
451 return 0;
452 }
453}
454
San Mehat9d10b342010-01-18 09:51:02 -0800455int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800456 ALOGD("untetherInterface(%s)", interface);
457
Erik Kline1d065ba2016-06-08 13:24:45 +0900458 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
459 if (!strcmp(interface, it->c_str())) {
460 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800461
Erik Kline1d065ba2016-06-08 13:24:45 +0900462 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800463 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800464 }
465 }
466 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800467 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800468}
469
Erik Kline1d065ba2016-06-08 13:24:45 +0900470const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800471 return mInterfaces;
472}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900473
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900474int TetherController::setupIptablesHooks() {
475 int res;
476 res = setDefaults();
477 if (res < 0) {
478 return res;
479 }
480
481 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
482 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
483 // This is no longer optional and tethering will fail to start if it fails.
484 std::string mssRewriteCommand = StringPrintf(
485 "*mangle\n"
486 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
487 "COMMIT\n", LOCAL_MANGLE_FORWARD);
488
489 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
490 std::string defaultCommands = StringPrintf(
491 "*filter\n"
492 ":%s -\n"
493 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
494
495 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
496 if (res < 0) {
497 return res;
498 }
499
500 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
501 if (res < 0) {
502 return res;
503 }
504
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900505 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900506
507 return 0;
508}
509
510int TetherController::setDefaults() {
511 std::string v4Cmd = StringPrintf(
512 "*filter\n"
513 ":%s -\n"
514 "-A %s -j DROP\n"
515 "COMMIT\n"
516 "*nat\n"
517 ":%s -\n"
518 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
519
520 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900521 "*filter\n"
522 ":%s -\n"
523 "COMMIT\n"
524 "*raw\n"
525 ":%s -\n"
526 "COMMIT\n",
527 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900528
529 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
530 if (res < 0) {
531 return res;
532 }
533
534 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
535 if (res < 0) {
536 return res;
537 }
538
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900539 return 0;
540}
541
542int TetherController::enableNat(const char* intIface, const char* extIface) {
543 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
544
545 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900546 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900547 }
548
549 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
550 if (!strcmp(intIface, extIface)) {
551 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900552 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900553 }
554
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900555 if (isForwardingPairEnabled(intIface, extIface)) {
556 return 0;
557 }
558
559 // add this if we are the first enabled nat for this upstream
560 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900561 std::vector<std::string> v4Cmds = {
562 "*nat",
563 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
564 "COMMIT\n"
565 };
566
Luke Huangae038f82018-11-05 11:17:31 +0900567 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
568 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900569 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900570 if (!isAnyForwardingPairEnabled()) {
571 // unwind what's been done, but don't care about success - what more could we do?
572 setDefaults();
573 }
Luke Huang19b49c52018-10-22 12:12:05 +0900574 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900575 }
576 }
577
578 if (setForwardRules(true, intIface, extIface) != 0) {
579 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900580 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900581 setDefaults();
582 }
Luke Huang19b49c52018-10-22 12:12:05 +0900583 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900584 }
585
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900586 return 0;
587}
588
Luke Huangae038f82018-11-05 11:17:31 +0900589int TetherController::setTetherGlobalAlertRule() {
590 // Only add this if we are the first enabled nat
591 if (isAnyForwardingPairEnabled()) {
592 return 0;
593 }
594 const std::string cmds =
595 "*filter\n" +
596 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
597 "COMMIT\n";
598
599 return iptablesRestoreFunction(V4V6, cmds, nullptr);
600}
601
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900602int TetherController::setupIPv6CountersChain() {
603 // Only add this if we are the first enabled nat
604 if (isAnyForwardingPairEnabled()) {
605 return 0;
606 }
607
608 /*
609 * IPv6 tethering doesn't need the state-based conntrack rules, so
610 * it unconditionally jumps to the tether counters chain all the time.
611 */
Luke Huangae038f82018-11-05 11:17:31 +0900612 const std::string v6Cmds =
613 "*filter\n" +
614 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900615
Luke Huangae038f82018-11-05 11:17:31 +0900616 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900617}
618
619// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
620TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
621 const std::string& intIface, const std::string& extIface) {
622 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
623 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
624 if (it->second.iface == intIface) {
625 return &(it->second);
626 }
627 }
628 return nullptr;
629}
630
631void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
632 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
633 if (existingEntry != nullptr) {
634 existingEntry->active = true;
635 return;
636 }
637
638 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
639 .iface = intIface,
640 .active = true
641 }));
642}
643
644void TetherController::markForwardingPairDisabled(
645 const std::string& intIface, const std::string& extIface) {
646 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
647 if (existingEntry == nullptr) {
648 return;
649 }
650
651 existingEntry->active = false;
652}
653
654bool TetherController::isForwardingPairEnabled(
655 const std::string& intIface, const std::string& extIface) {
656 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
657 return existingEntry != nullptr && existingEntry->active;
658}
659
660bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
661 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
662 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
663 if (it->second.active) {
664 return true;
665 }
666 }
667 return false;
668}
669
670bool TetherController::isAnyForwardingPairEnabled() {
671 for (auto& it : mFwdIfaces) {
672 if (it.second.active) {
673 return true;
674 }
675 }
676 return false;
677}
678
679bool TetherController::tetherCountingRuleExists(
680 const std::string& iface1, const std::string& iface2) {
681 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
682 // is in the map regardless of its active status. Rules are added both ways so we check with
683 // the 2 combinations.
684 return findForwardingDownstream(iface1, iface2) != nullptr
685 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900686}
687
688/* static */
689std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
690 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
691}
692
693int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
694 const char *op = add ? "-A" : "-D";
695
696 std::string rpfilterCmd = StringPrintf(
697 "*raw\n"
698 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
699 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
700 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900701 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900702 }
703
704 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900705 "*raw",
706 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
707 LOCAL_RAW_PREROUTING, intIface),
708 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
709 LOCAL_RAW_PREROUTING, intIface),
710 "COMMIT",
711 "*filter",
712 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
713 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
714 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
715 intIface, extIface),
716 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
717 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900718 };
719
720 std::vector<std::string> v6 = {
721 "*filter",
722 };
723
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900724 // We only ever add tethering quota rules so that they stick.
725 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900726 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900727 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900728 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900729 v6.push_back(makeTetherCountingRule(extIface, intIface));
730 }
731
732 // Always make sure the drop rule is at the end.
733 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900734 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900735 if (add) {
736 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
737 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
738 }
739
740 v4.push_back("COMMIT\n");
741 v6.push_back("COMMIT\n");
742
743 // We only add IPv6 rules here, never remove them.
744 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
745 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
746 // unwind what's been done, but don't care about success - what more could we do?
747 if (add) {
748 setForwardRules(false, intIface, extIface);
749 }
Luke Huang19b49c52018-10-22 12:12:05 +0900750 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900751 }
752
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900753 if (add) {
754 addForwardingPair(intIface, extIface);
755 } else {
756 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900757 }
758
759 return 0;
760}
761
762int TetherController::disableNat(const char* intIface, const char* extIface) {
763 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900764 errno = ENODEV;
765 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900766 }
767
768 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900769 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900770 setDefaults();
771 }
772 return 0;
773}
774
775void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
776 for (TetherStats& existing : statsList) {
777 if (existing.addStatsIfMatch(stats)) {
778 return;
779 }
780 }
781 // No match. Insert a new interface pair.
782 statsList.push_back(stats);
783}
784
785/*
786 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900787 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900788 * pkts bytes target prot opt in out source destination
789 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
790 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
791 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
792 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
793 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900794 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900795 * pkts bytes target prot opt in out source destination
796 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
797 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
798 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900799 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900800int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900801 const std::string& statsOutput,
802 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800803 enum IndexOfIptChain {
804 ORIG_LINE,
805 PACKET_COUNTS,
806 BYTE_COUNTS,
807 HYPHEN,
808 IFACE0_NAME,
809 IFACE1_NAME,
810 SOURCE,
811 DESTINATION
812 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900813 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900814 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900815
waynema71a0b592018-11-21 13:31:34 +0800816 static const std::string NUM = "(\\d+)";
817 static const std::string IFACE = "([^\\s]+)";
818 static const std::string DST = "(0.0.0.0/0|::/0)";
819 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
820 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
821 "\\s+" + DST + "\\s+" + DST;
822 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900823
waynema71a0b592018-11-21 13:31:34 +0800824 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
825 int headerLine = 0;
826 for (const std::string& line : lines) {
827 // Skip headers.
828 if (headerLine < 2) {
829 if (line.empty()) {
830 ALOGV("Empty header while parsing tethering stats");
831 return -EREMOTEIO;
832 }
833 headerLine++;
834 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900835 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900836
waynema71a0b592018-11-21 13:31:34 +0800837 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900838
waynema71a0b592018-11-21 13:31:34 +0800839 extraProcessingInfo = line;
840 std::smatch matches;
841 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
842 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
843 // IPv4 has "--" indicating what to do with fragments...
844 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
845 // ... but IPv6 does not.
846 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
847 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
848 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
849 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
850 std::string iface0 = matches[IFACE0_NAME].str();
851 std::string iface1 = matches[IFACE1_NAME].str();
852 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900853
waynema71a0b592018-11-21 13:31:34 +0800854 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
855 " rest=<%s> orig line=<%s>",
856 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900857 /*
858 * The following assumes that the 1st rule has in:extIface out:intIface,
859 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900860 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900861 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900862 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800863 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
864 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900865 stats.intIface = iface0;
866 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900867 stats.txPackets = packets;
868 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900869 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800870 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
871 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900872 stats.rxPackets = packets;
873 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900874 }
875 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900876 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900877 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900878 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900879 }
880 }
881
882 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900883 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900884 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900885 }
886 return 0;
887}
888
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900889StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900890 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900891 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900892
893 for (const IptablesTarget target : {V4, V6}) {
894 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900895 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900896 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
897 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900898 }
899
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900900 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900901 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
902 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900903 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900904 }
905 }
906
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900907 return statsList;
908}
909
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900910} // namespace net
911} // namespace android