blob: 0c5b6bfe217b38c158963b8c60e4d0df0acabb4a [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"
Erik Kline1d065ba2016-06-08 13:24:45 +090048#include "InterfaceController.h"
Mike Yuf0e019f2019-03-13 14:43:39 +080049#include "NetdConstants.h"
Lorenzo Colittie20a5262017-05-09 18:30:44 +090050#include "NetworkController.h"
Mike Yuf0e019f2019-03-13 14:43:39 +080051#include "Permission.h"
San Mehat9d10b342010-01-18 09:51:02 -080052#include "TetherController.h"
53
Bernie Innocenti4debf3b2018-09-12 13:54:50 +090054namespace android {
55namespace net {
56
Lorenzo Colittia93126d2017-08-24 13:28:19 +090057using android::base::Join;
George Burgess IVe3dc1312019-02-28 11:27:04 -080058using android::base::Pipe;
Erik Klineb31fd692018-06-06 20:50:11 +090059using android::base::StringPrintf;
George Burgess IVe3dc1312019-02-28 11:27:04 -080060using android::base::unique_fd;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090061using android::netdutils::statusFromErrno;
Erik Klineb31fd692018-06-06 20:50:11 +090062using android::netdutils::StatusOr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090063
Lorenzo Colitti799625c2015-02-25 12:52:00 +090064namespace {
65
Erik Kline1d065ba2016-06-08 13:24:45 +090066const char BP_TOOLS_MODE[] = "bp-tools";
67const char IPV4_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv4/ip_forward";
68const char IPV6_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv6/conf/all/forwarding";
69const char SEPARATOR[] = "|";
Erik Kline93f9b222017-10-22 21:24:58 +090070constexpr const char kTcpBeLiberal[] = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
Lorenzo Colitti799625c2015-02-25 12:52:00 +090071
Erik Kline5f0358b2018-02-16 15:08:09 +090072// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
73constexpr const char kDnsmasqUsername[] = "dns_tether";
74
Lorenzo Colitti799625c2015-02-25 12:52:00 +090075bool writeToFile(const char* filename, const char* value) {
Nick Kralevichb95c60c2016-11-19 09:09:16 -080076 int fd = open(filename, O_WRONLY | O_CLOEXEC);
Nicolas Geoffrayafd40372015-03-16 11:58:06 +000077 if (fd < 0) {
78 ALOGE("Failed to open %s: %s", filename, strerror(errno));
79 return false;
80 }
81
82 const ssize_t len = strlen(value);
83 if (write(fd, value, len) != len) {
84 ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
85 close(fd);
86 return false;
87 }
88 close(fd);
89 return true;
Lorenzo Colitti799625c2015-02-25 12:52:00 +090090}
91
Erik Kline93f9b222017-10-22 21:24:58 +090092// TODO: Consider altering TCP and UDP timeouts as well.
93void configureForTethering(bool enabled) {
94 writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
95}
96
Erik Kline1d065ba2016-06-08 13:24:45 +090097bool configureForIPv6Router(const char *interface) {
98 return (InterfaceController::setEnableIPv6(interface, 0) == 0)
99 && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
Erik Kline6cddf512016-08-09 15:28:42 +0900100 && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
101 && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
Erik Kline1d065ba2016-06-08 13:24:45 +0900102 && (InterfaceController::setEnableIPv6(interface, 1) == 0);
103}
104
105void configureForIPv6Client(const char *interface) {
106 InterfaceController::setAcceptIPv6Ra(interface, 1);
Erik Kline6cddf512016-08-09 15:28:42 +0900107 InterfaceController::setAcceptIPv6Dad(interface, 1);
108 InterfaceController::setIPv6DadTransmits(interface, "1");
Erik Kline1d065ba2016-06-08 13:24:45 +0900109 InterfaceController::setEnableIPv6(interface, 0);
110}
111
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900112bool inBpToolsMode() {
113 // In BP tools mode, do not disable IP forwarding
114 char bootmode[PROPERTY_VALUE_MAX] = {0};
115 property_get("ro.bootmode", bootmode, "unknown");
116 return !strcmp(BP_TOOLS_MODE, bootmode);
117}
118
Luke Huang40962442019-02-26 11:46:10 +0800119int setPosixSpawnFileActionsAddDup2(posix_spawn_file_actions_t* fa, int fd, int new_fd) {
120 int res = posix_spawn_file_actions_init(fa);
121 if (res) {
122 return res;
Luke Huang94c43a12019-02-14 19:51:38 +0800123 }
Luke Huang40962442019-02-26 11:46:10 +0800124 return posix_spawn_file_actions_adddup2(fa, fd, new_fd);
125}
Luke Huang94c43a12019-02-14 19:51:38 +0800126
Luke Huang40962442019-02-26 11:46:10 +0800127int setPosixSpawnAttrFlags(posix_spawnattr_t* attr, short flags) {
128 int res = posix_spawnattr_init(attr);
129 if (res) {
130 return res;
Luke Huang94c43a12019-02-14 19:51:38 +0800131 }
Luke Huang40962442019-02-26 11:46:10 +0800132 return posix_spawnattr_setflags(attr, flags);
Luke Huang94c43a12019-02-14 19:51:38 +0800133}
134
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900135} // namespace
136
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900137auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
138
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900139const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
140 "*filter\n"
141 "-nvx -L %s\n"
142 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
143
Erik Kline15079dd2018-05-18 23:10:56 +0900144int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
145 if (cmd.empty()) return 0;
146
Erik Klineb31fd692018-06-06 20:50:11 +0900147 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900148 // Send the trailing \0 as well.
149 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900150 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900151 errno = EREMOTEIO;
152 return -1;
153 }
154 return 0;
155}
156
157void TetherController::DnsmasqState::clear() {
158 update_ifaces_cmd.clear();
159 update_dns_cmd.clear();
160}
161
162int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
163 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
164}
165
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700166TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900167 if (inBpToolsMode()) {
168 enableForwarding(BP_TOOLS_MODE);
169 } else {
170 setIpFwdEnabled();
171 }
San Mehat9d10b342010-01-18 09:51:02 -0800172}
173
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900174bool TetherController::setIpFwdEnabled() {
175 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900176 bool disable = mForwardingRequests.empty();
177 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900178 ALOGD("Setting IP forward enable = %s", value);
179 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
180 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900181 if (disable) {
182 // Turning off the forwarding sysconf in the kernel has the side effect
183 // of turning on ICMP redirect, which is a security hazard.
184 // Turn ICMP redirect back off immediately.
185 int rv = InterfaceController::disableIcmpRedirects();
186 success &= (rv == 0);
187 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900188 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800189}
190
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900191bool TetherController::enableForwarding(const char* requester) {
192 // Don't return an error if this requester already requested forwarding. Only return errors for
193 // things that the caller caller needs to care about, such as "couldn't write to the file to
194 // enable forwarding".
195 mForwardingRequests.insert(requester);
196 return setIpFwdEnabled();
197}
San Mehat9d10b342010-01-18 09:51:02 -0800198
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900199bool TetherController::disableForwarding(const char* requester) {
200 mForwardingRequests.erase(requester);
201 return setIpFwdEnabled();
202}
San Mehat9d10b342010-01-18 09:51:02 -0800203
Luke Huang728cf4c2019-03-14 19:43:02 +0800204const std::set<std::string>& TetherController::getIpfwdRequesterList() const {
205 return mForwardingRequests;
San Mehat9d10b342010-01-18 09:51:02 -0800206}
207
Erik Kline13fa01f2015-11-12 17:49:23 +0900208int TetherController::startTethering(int num_addrs, char **dhcp_ranges) {
San Mehat9d10b342010-01-18 09:51:02 -0800209 if (mDaemonPid != 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000210 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800211 errno = EBUSY;
Luke Huangb5733d72018-08-21 17:17:19 +0800212 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800213 }
214
Steve Block7b984e32011-12-20 16:22:42 +0000215 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800216
George Burgess IVe3dc1312019-02-28 11:27:04 -0800217 unique_fd pipeRead, pipeWrite;
218 if (!Pipe(&pipeRead, &pipeWrite, O_CLOEXEC)) {
Luke Huangb5733d72018-08-21 17:17:19 +0800219 int res = errno;
Luke Huang94c43a12019-02-14 19:51:38 +0800220 ALOGE("pipe2() failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800221 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800222 }
223
Luke Huang94c43a12019-02-14 19:51:38 +0800224 // Set parameters
225 Fwmark fwmark;
226 fwmark.netId = NetworkController::LOCAL_NET_ID;
227 fwmark.explicitlySelected = true;
228 fwmark.protectedFromVpn = true;
229 fwmark.permission = PERMISSION_SYSTEM;
230 char markStr[UINT32_HEX_STRLEN];
231 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800232
Luke Huang94c43a12019-02-14 19:51:38 +0800233 std::vector<const std::string> argVector = {
Erik Kline5f0358b2018-02-16 15:08:09 +0900234 "/system/bin/dnsmasq",
235 "--keep-in-foreground",
236 "--no-resolv",
237 "--no-poll",
238 "--dhcp-authoritative",
239 // TODO: pipe through metered status from ConnService
240 "--dhcp-option-force=43,ANDROID_METERED",
241 "--pid-file",
Luke Huang94c43a12019-02-14 19:51:38 +0800242 "--listen-mark",
243 markStr,
244 "--user",
245 kDnsmasqUsername,
246 };
San Mehat9d10b342010-01-18 09:51:02 -0800247
Luke Huang94c43a12019-02-14 19:51:38 +0800248 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is
249 // passed.
250 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
251 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
252 dhcp_ranges[addrIndex + 1]));
San Mehat9d10b342010-01-18 09:51:02 -0800253 }
254
George Burgess IVe3dc1312019-02-28 11:27:04 -0800255 std::vector<char*> args(argVector.size() + 1);
Luke Huang94c43a12019-02-14 19:51:38 +0800256 for (unsigned i = 0; i < argVector.size(); i++) {
257 args[i] = (char*)argVector[i].c_str();
258 }
259
260 /*
261 * TODO: Create a monitoring thread to handle and restart
262 * the daemon if it exits prematurely
263 */
Luke Huang40962442019-02-26 11:46:10 +0800264
265 // Note that don't modify any memory between vfork and execv.
266 // Changing state of file descriptors would be fine. See posix_spawn_file_actions_add*
267 // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
268 // duplicated fd.
269 posix_spawn_file_actions_t fa;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800270 int res = setPosixSpawnFileActionsAddDup2(&fa, pipeRead.get(), STDIN_FILENO);
Luke Huang40962442019-02-26 11:46:10 +0800271 if (res) {
272 ALOGE("posix_spawn set fa failed (%s)", strerror(res));
Luke Huang94c43a12019-02-14 19:51:38 +0800273 return -res;
274 }
275
Luke Huang40962442019-02-26 11:46:10 +0800276 posix_spawnattr_t attr;
277 res = setPosixSpawnAttrFlags(&attr, POSIX_SPAWN_USEVFORK);
278 if (res) {
279 ALOGE("posix_spawn set attr flag failed (%s)", strerror(res));
280 return -res;
281 }
282
283 pid_t pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800284 res = posix_spawn(&pid, args[0], &fa, &attr, &args[0], nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800285 posix_spawnattr_destroy(&attr);
286 posix_spawn_file_actions_destroy(&fa);
287 if (res) {
288 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800289 return -res;
290 }
Luke Huang94c43a12019-02-14 19:51:38 +0800291 mDaemonPid = pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800292 mDaemonFd = pipeWrite.release();
Luke Huang94c43a12019-02-14 19:51:38 +0800293 configureForTethering(true);
294 applyDnsInterfaces();
295 ALOGD("Tethering services running");
296
San Mehat9d10b342010-01-18 09:51:02 -0800297 return 0;
298}
299
Luke Huangb5733d72018-08-21 17:17:19 +0800300std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
301 std::vector<char*> addrsCstrVec{};
302 addrsCstrVec.reserve(addrs.size());
303 for (const auto& addr : addrs) {
304 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
305 }
306 return addrsCstrVec;
307}
308
309int TetherController::startTethering(const std::vector<std::string>& dhcpRanges) {
310 struct in_addr v4_addr;
311 for (const auto& dhcpRange : dhcpRanges) {
312 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
313 return -EINVAL;
314 }
315 }
316 auto dhcp_ranges = toCstrVec(dhcpRanges);
317 return startTethering(dhcp_ranges.size(), dhcp_ranges.data());
318}
319
San Mehat9d10b342010-01-18 09:51:02 -0800320int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900321 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800322
323 if (mDaemonPid == 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000324 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800325 return 0;
326 }
327
Steve Block7b984e32011-12-20 16:22:42 +0000328 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800329
330 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700331 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800332 mDaemonPid = 0;
333 close(mDaemonFd);
334 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900335 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000336 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800337 return 0;
338}
Matthew Xie19944102012-07-12 16:42:07 -0700339
San Mehat9d10b342010-01-18 09:51:02 -0800340bool TetherController::isTetheringStarted() {
341 return (mDaemonPid == 0 ? false : true);
342}
343
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900344// dnsmasq can't parse commands larger than this due to the fixed-size buffer
345// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
346// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900347const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800348
Luke Huang8dc1cac2019-03-30 16:12:31 +0800349// TODO: Remove overload function and update this after NDC migration.
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700350int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700351 Fwmark fwmark;
352 fwmark.netId = netId;
353 fwmark.explicitlySelected = true;
354 fwmark.protectedFromVpn = true;
355 fwmark.permission = PERMISSION_SYSTEM;
356
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900357 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800358
Erik Kline1d065ba2016-06-08 13:24:45 +0900359 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900360 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700361 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800362
Lorenzo Colittic2841282015-11-25 22:13:57 +0900363 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700364 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900365 freeaddrinfo(res);
366 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000367 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900368 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900369 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800370 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800371 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800372
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900373 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
374 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800375 break;
376 }
377
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900378 daemonCmd += SEPARATOR;
379 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900380 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800381 }
382
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700383 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900384 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800385 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900386 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900387 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900388 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800389 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800390 }
391 }
392 return 0;
393}
394
Luke Huangb5733d72018-08-21 17:17:19 +0800395int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
Luke Huangb5733d72018-08-21 17:17:19 +0800396 auto dnsServers = toCstrVec(servers);
397 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
398}
399
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700400unsigned TetherController::getDnsNetId() {
401 return mDnsNetId;
402}
403
Erik Kline1d065ba2016-06-08 13:24:45 +0900404const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800405 return mDnsForwarders;
406}
407
Erik Kline1d065ba2016-06-08 13:24:45 +0900408bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900409 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800410 bool haveInterfaces = false;
411
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900412 for (const auto& ifname : mInterfaces) {
413 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
414 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800415 break;
416 }
417
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900418 daemonCmd += SEPARATOR;
419 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800420 haveInterfaces = true;
421 }
422
Erik Kline15079dd2018-05-18 23:10:56 +0900423 if (!haveInterfaces) {
424 mDnsmasqState.update_ifaces_cmd.clear();
425 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900426 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900427 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800428 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900429 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800430}
431
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800432int TetherController::tetherInterface(const char *interface) {
433 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700434 if (!isIfaceName(interface)) {
435 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800436 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700437 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800438
Erik Kline1d065ba2016-06-08 13:24:45 +0900439 if (!configureForIPv6Router(interface)) {
440 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800441 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900442 }
443 mInterfaces.push_back(interface);
444
445 if (!applyDnsInterfaces()) {
446 mInterfaces.pop_back();
447 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800448 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800449 } else {
450 return 0;
451 }
452}
453
San Mehat9d10b342010-01-18 09:51:02 -0800454int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800455 ALOGD("untetherInterface(%s)", interface);
456
Erik Kline1d065ba2016-06-08 13:24:45 +0900457 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
458 if (!strcmp(interface, it->c_str())) {
459 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800460
Erik Kline1d065ba2016-06-08 13:24:45 +0900461 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800462 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800463 }
464 }
465 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800466 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800467}
468
Erik Kline1d065ba2016-06-08 13:24:45 +0900469const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800470 return mInterfaces;
471}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900472
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900473int TetherController::setupIptablesHooks() {
474 int res;
475 res = setDefaults();
476 if (res < 0) {
477 return res;
478 }
479
480 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
481 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
482 // This is no longer optional and tethering will fail to start if it fails.
483 std::string mssRewriteCommand = StringPrintf(
484 "*mangle\n"
485 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
486 "COMMIT\n", LOCAL_MANGLE_FORWARD);
487
488 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
489 std::string defaultCommands = StringPrintf(
490 "*filter\n"
491 ":%s -\n"
492 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
493
494 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
495 if (res < 0) {
496 return res;
497 }
498
499 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
500 if (res < 0) {
501 return res;
502 }
503
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900504 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900505
506 return 0;
507}
508
509int TetherController::setDefaults() {
510 std::string v4Cmd = StringPrintf(
511 "*filter\n"
512 ":%s -\n"
513 "-A %s -j DROP\n"
514 "COMMIT\n"
515 "*nat\n"
516 ":%s -\n"
517 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
518
519 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900520 "*filter\n"
521 ":%s -\n"
522 "COMMIT\n"
523 "*raw\n"
524 ":%s -\n"
525 "COMMIT\n",
526 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900527
528 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
529 if (res < 0) {
530 return res;
531 }
532
533 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
534 if (res < 0) {
535 return res;
536 }
537
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900538 return 0;
539}
540
541int TetherController::enableNat(const char* intIface, const char* extIface) {
542 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
543
544 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900545 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900546 }
547
548 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
549 if (!strcmp(intIface, extIface)) {
550 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900551 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900552 }
553
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900554 if (isForwardingPairEnabled(intIface, extIface)) {
555 return 0;
556 }
557
558 // add this if we are the first enabled nat for this upstream
559 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900560 std::vector<std::string> v4Cmds = {
561 "*nat",
562 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
563 "COMMIT\n"
564 };
565
Luke Huangae038f82018-11-05 11:17:31 +0900566 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
567 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900568 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900569 if (!isAnyForwardingPairEnabled()) {
570 // unwind what's been done, but don't care about success - what more could we do?
571 setDefaults();
572 }
Luke Huang19b49c52018-10-22 12:12:05 +0900573 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900574 }
575 }
576
577 if (setForwardRules(true, intIface, extIface) != 0) {
578 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900579 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900580 setDefaults();
581 }
Luke Huang19b49c52018-10-22 12:12:05 +0900582 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900583 }
584
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900585 return 0;
586}
587
Luke Huangae038f82018-11-05 11:17:31 +0900588int TetherController::setTetherGlobalAlertRule() {
589 // Only add this if we are the first enabled nat
590 if (isAnyForwardingPairEnabled()) {
591 return 0;
592 }
593 const std::string cmds =
594 "*filter\n" +
595 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
596 "COMMIT\n";
597
598 return iptablesRestoreFunction(V4V6, cmds, nullptr);
599}
600
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900601int TetherController::setupIPv6CountersChain() {
602 // Only add this if we are the first enabled nat
603 if (isAnyForwardingPairEnabled()) {
604 return 0;
605 }
606
607 /*
608 * IPv6 tethering doesn't need the state-based conntrack rules, so
609 * it unconditionally jumps to the tether counters chain all the time.
610 */
Luke Huangae038f82018-11-05 11:17:31 +0900611 const std::string v6Cmds =
612 "*filter\n" +
613 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900614
Luke Huangae038f82018-11-05 11:17:31 +0900615 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900616}
617
618// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
619TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
620 const std::string& intIface, const std::string& extIface) {
621 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
622 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
623 if (it->second.iface == intIface) {
624 return &(it->second);
625 }
626 }
627 return nullptr;
628}
629
630void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
631 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
632 if (existingEntry != nullptr) {
633 existingEntry->active = true;
634 return;
635 }
636
637 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
638 .iface = intIface,
639 .active = true
640 }));
641}
642
643void TetherController::markForwardingPairDisabled(
644 const std::string& intIface, const std::string& extIface) {
645 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
646 if (existingEntry == nullptr) {
647 return;
648 }
649
650 existingEntry->active = false;
651}
652
653bool TetherController::isForwardingPairEnabled(
654 const std::string& intIface, const std::string& extIface) {
655 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
656 return existingEntry != nullptr && existingEntry->active;
657}
658
659bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
660 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
661 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
662 if (it->second.active) {
663 return true;
664 }
665 }
666 return false;
667}
668
669bool TetherController::isAnyForwardingPairEnabled() {
670 for (auto& it : mFwdIfaces) {
671 if (it.second.active) {
672 return true;
673 }
674 }
675 return false;
676}
677
678bool TetherController::tetherCountingRuleExists(
679 const std::string& iface1, const std::string& iface2) {
680 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
681 // is in the map regardless of its active status. Rules are added both ways so we check with
682 // the 2 combinations.
683 return findForwardingDownstream(iface1, iface2) != nullptr
684 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900685}
686
687/* static */
688std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
689 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
690}
691
692int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
693 const char *op = add ? "-A" : "-D";
694
695 std::string rpfilterCmd = StringPrintf(
696 "*raw\n"
697 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
698 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
699 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900700 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900701 }
702
703 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900704 "*raw",
705 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
706 LOCAL_RAW_PREROUTING, intIface),
707 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
708 LOCAL_RAW_PREROUTING, intIface),
709 "COMMIT",
710 "*filter",
711 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
712 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
713 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
714 intIface, extIface),
715 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
716 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900717 };
718
719 std::vector<std::string> v6 = {
720 "*filter",
721 };
722
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900723 // We only ever add tethering quota rules so that they stick.
724 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900725 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900726 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900727 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900728 v6.push_back(makeTetherCountingRule(extIface, intIface));
729 }
730
731 // Always make sure the drop rule is at the end.
732 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900733 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900734 if (add) {
735 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
736 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
737 }
738
739 v4.push_back("COMMIT\n");
740 v6.push_back("COMMIT\n");
741
742 // We only add IPv6 rules here, never remove them.
743 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
744 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
745 // unwind what's been done, but don't care about success - what more could we do?
746 if (add) {
747 setForwardRules(false, intIface, extIface);
748 }
Luke Huang19b49c52018-10-22 12:12:05 +0900749 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900750 }
751
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900752 if (add) {
753 addForwardingPair(intIface, extIface);
754 } else {
755 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900756 }
757
758 return 0;
759}
760
761int TetherController::disableNat(const char* intIface, const char* extIface) {
762 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900763 errno = ENODEV;
764 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900765 }
766
767 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900768 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900769 setDefaults();
770 }
771 return 0;
772}
773
774void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
775 for (TetherStats& existing : statsList) {
776 if (existing.addStatsIfMatch(stats)) {
777 return;
778 }
779 }
780 // No match. Insert a new interface pair.
781 statsList.push_back(stats);
782}
783
784/*
785 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900786 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900787 * pkts bytes target prot opt in out source destination
788 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
789 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
790 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
791 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
792 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900793 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900794 * pkts bytes target prot opt in out source destination
795 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
796 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
797 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900798 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900799int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900800 const std::string& statsOutput,
801 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800802 enum IndexOfIptChain {
803 ORIG_LINE,
804 PACKET_COUNTS,
805 BYTE_COUNTS,
806 HYPHEN,
807 IFACE0_NAME,
808 IFACE1_NAME,
809 SOURCE,
810 DESTINATION
811 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900812 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900813 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900814
waynema71a0b592018-11-21 13:31:34 +0800815 static const std::string NUM = "(\\d+)";
816 static const std::string IFACE = "([^\\s]+)";
817 static const std::string DST = "(0.0.0.0/0|::/0)";
818 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
819 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
820 "\\s+" + DST + "\\s+" + DST;
821 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900822
waynema71a0b592018-11-21 13:31:34 +0800823 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
824 int headerLine = 0;
825 for (const std::string& line : lines) {
826 // Skip headers.
827 if (headerLine < 2) {
828 if (line.empty()) {
829 ALOGV("Empty header while parsing tethering stats");
830 return -EREMOTEIO;
831 }
832 headerLine++;
833 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900834 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900835
waynema71a0b592018-11-21 13:31:34 +0800836 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900837
waynema71a0b592018-11-21 13:31:34 +0800838 extraProcessingInfo = line;
839 std::smatch matches;
840 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
841 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
842 // IPv4 has "--" indicating what to do with fragments...
843 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
844 // ... but IPv6 does not.
845 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
846 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
847 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
848 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
849 std::string iface0 = matches[IFACE0_NAME].str();
850 std::string iface1 = matches[IFACE1_NAME].str();
851 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900852
waynema71a0b592018-11-21 13:31:34 +0800853 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
854 " rest=<%s> orig line=<%s>",
855 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900856 /*
857 * The following assumes that the 1st rule has in:extIface out:intIface,
858 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900859 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900860 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900861 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800862 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
863 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900864 stats.intIface = iface0;
865 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900866 stats.txPackets = packets;
867 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900868 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800869 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
870 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900871 stats.rxPackets = packets;
872 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900873 }
874 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900875 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900876 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900877 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900878 }
879 }
880
881 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900882 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900883 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900884 }
885 return 0;
886}
887
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900888StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900889 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900890 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900891
892 for (const IptablesTarget target : {V4, V6}) {
893 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900894 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900895 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
896 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900897 }
898
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900899 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900900 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
901 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900902 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900903 }
904 }
905
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900906 return statsList;
907}
908
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900909} // namespace net
910} // namespace android