blob: 4fc603a99c668783efe735bfec24f5d78a4102d1 [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/strings.h>
40#include <android-base/stringprintf.h>
Kazuhiro Ondo6b858eb2011-06-24 20:31:03 -050041#include <cutils/properties.h>
Logan Chien3f461482018-04-23 14:31:32 +080042#include <log/log.h>
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090043#include <netdutils/StatusOr.h>
San Mehat9d10b342010-01-18 09:51:02 -080044
Erik Klineb31fd692018-06-06 20:50:11 +090045#include "Controllers.h"
Lorenzo Colitti667c4772014-08-26 14:13:07 -070046#include "Fwmark.h"
JP Abgrall69261cb2014-06-19 18:35:24 -070047#include "NetdConstants.h"
Lorenzo Colitti667c4772014-08-26 14:13:07 -070048#include "Permission.h"
Erik Kline1d065ba2016-06-08 13:24:45 +090049#include "InterfaceController.h"
Lorenzo Colittie20a5262017-05-09 18:30:44 +090050#include "NetworkController.h"
Lorenzo Colittia93126d2017-08-24 13:28:19 +090051#include "ResponseCode.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;
Erik Klineb31fd692018-06-06 20:50:11 +090058using android::base::StringPrintf;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090059using android::netdutils::statusFromErrno;
Erik Klineb31fd692018-06-06 20:50:11 +090060using android::netdutils::StatusOr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090061
Lorenzo Colitti799625c2015-02-25 12:52:00 +090062namespace {
63
Erik Kline1d065ba2016-06-08 13:24:45 +090064const char BP_TOOLS_MODE[] = "bp-tools";
65const char IPV4_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv4/ip_forward";
66const char IPV6_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv6/conf/all/forwarding";
67const char SEPARATOR[] = "|";
Erik Kline93f9b222017-10-22 21:24:58 +090068constexpr const char kTcpBeLiberal[] = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
Lorenzo Colitti799625c2015-02-25 12:52:00 +090069
Erik Kline5f0358b2018-02-16 15:08:09 +090070// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
71constexpr const char kDnsmasqUsername[] = "dns_tether";
72
Lorenzo Colitti799625c2015-02-25 12:52:00 +090073bool writeToFile(const char* filename, const char* value) {
Nick Kralevichb95c60c2016-11-19 09:09:16 -080074 int fd = open(filename, O_WRONLY | O_CLOEXEC);
Nicolas Geoffrayafd40372015-03-16 11:58:06 +000075 if (fd < 0) {
76 ALOGE("Failed to open %s: %s", filename, strerror(errno));
77 return false;
78 }
79
80 const ssize_t len = strlen(value);
81 if (write(fd, value, len) != len) {
82 ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
83 close(fd);
84 return false;
85 }
86 close(fd);
87 return true;
Lorenzo Colitti799625c2015-02-25 12:52:00 +090088}
89
Erik Kline93f9b222017-10-22 21:24:58 +090090// TODO: Consider altering TCP and UDP timeouts as well.
91void configureForTethering(bool enabled) {
92 writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
93}
94
Erik Kline1d065ba2016-06-08 13:24:45 +090095bool configureForIPv6Router(const char *interface) {
96 return (InterfaceController::setEnableIPv6(interface, 0) == 0)
97 && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
Erik Kline6cddf512016-08-09 15:28:42 +090098 && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
99 && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
Erik Kline1d065ba2016-06-08 13:24:45 +0900100 && (InterfaceController::setEnableIPv6(interface, 1) == 0);
101}
102
103void configureForIPv6Client(const char *interface) {
104 InterfaceController::setAcceptIPv6Ra(interface, 1);
Erik Kline6cddf512016-08-09 15:28:42 +0900105 InterfaceController::setAcceptIPv6Dad(interface, 1);
106 InterfaceController::setIPv6DadTransmits(interface, "1");
Erik Kline1d065ba2016-06-08 13:24:45 +0900107 InterfaceController::setEnableIPv6(interface, 0);
108}
109
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900110bool inBpToolsMode() {
111 // In BP tools mode, do not disable IP forwarding
112 char bootmode[PROPERTY_VALUE_MAX] = {0};
113 property_get("ro.bootmode", bootmode, "unknown");
114 return !strcmp(BP_TOOLS_MODE, bootmode);
115}
116
Luke Huang40962442019-02-26 11:46:10 +0800117int setPosixSpawnFileActionsAddDup2(posix_spawn_file_actions_t* fa, int fd, int new_fd) {
118 int res = posix_spawn_file_actions_init(fa);
119 if (res) {
120 return res;
Luke Huang94c43a12019-02-14 19:51:38 +0800121 }
Luke Huang40962442019-02-26 11:46:10 +0800122 return posix_spawn_file_actions_adddup2(fa, fd, new_fd);
123}
Luke Huang94c43a12019-02-14 19:51:38 +0800124
Luke Huang40962442019-02-26 11:46:10 +0800125int setPosixSpawnAttrFlags(posix_spawnattr_t* attr, short flags) {
126 int res = posix_spawnattr_init(attr);
127 if (res) {
128 return res;
Luke Huang94c43a12019-02-14 19:51:38 +0800129 }
Luke Huang40962442019-02-26 11:46:10 +0800130 return posix_spawnattr_setflags(attr, flags);
Luke Huang94c43a12019-02-14 19:51:38 +0800131}
132
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900133} // namespace
134
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900135auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
136
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900137const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
138 "*filter\n"
139 "-nvx -L %s\n"
140 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
141
Erik Kline15079dd2018-05-18 23:10:56 +0900142int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
143 if (cmd.empty()) return 0;
144
Erik Klineb31fd692018-06-06 20:50:11 +0900145 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900146 // Send the trailing \0 as well.
147 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900148 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900149 errno = EREMOTEIO;
150 return -1;
151 }
152 return 0;
153}
154
155void TetherController::DnsmasqState::clear() {
156 update_ifaces_cmd.clear();
157 update_dns_cmd.clear();
158}
159
160int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
161 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
162}
163
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700164TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900165 if (inBpToolsMode()) {
166 enableForwarding(BP_TOOLS_MODE);
167 } else {
168 setIpFwdEnabled();
169 }
San Mehat9d10b342010-01-18 09:51:02 -0800170}
171
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900172bool TetherController::setIpFwdEnabled() {
173 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900174 bool disable = mForwardingRequests.empty();
175 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900176 ALOGD("Setting IP forward enable = %s", value);
177 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
178 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900179 if (disable) {
180 // Turning off the forwarding sysconf in the kernel has the side effect
181 // of turning on ICMP redirect, which is a security hazard.
182 // Turn ICMP redirect back off immediately.
183 int rv = InterfaceController::disableIcmpRedirects();
184 success &= (rv == 0);
185 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900186 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800187}
188
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900189bool TetherController::enableForwarding(const char* requester) {
190 // Don't return an error if this requester already requested forwarding. Only return errors for
191 // things that the caller caller needs to care about, such as "couldn't write to the file to
192 // enable forwarding".
193 mForwardingRequests.insert(requester);
194 return setIpFwdEnabled();
195}
San Mehat9d10b342010-01-18 09:51:02 -0800196
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900197bool TetherController::disableForwarding(const char* requester) {
198 mForwardingRequests.erase(requester);
199 return setIpFwdEnabled();
200}
San Mehat9d10b342010-01-18 09:51:02 -0800201
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900202size_t TetherController::forwardingRequestCount() {
203 return mForwardingRequests.size();
San Mehat9d10b342010-01-18 09:51:02 -0800204}
205
Erik Kline13fa01f2015-11-12 17:49:23 +0900206int TetherController::startTethering(int num_addrs, char **dhcp_ranges) {
San Mehat9d10b342010-01-18 09:51:02 -0800207 if (mDaemonPid != 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000208 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800209 errno = EBUSY;
Luke Huangb5733d72018-08-21 17:17:19 +0800210 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800211 }
212
Steve Block7b984e32011-12-20 16:22:42 +0000213 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800214
San Mehat9d10b342010-01-18 09:51:02 -0800215 int pipefd[2];
216
Luke Huang94c43a12019-02-14 19:51:38 +0800217 if (pipe2(pipefd, O_CLOEXEC) < 0) {
Luke Huangb5733d72018-08-21 17:17:19 +0800218 int res = errno;
Luke Huang94c43a12019-02-14 19:51:38 +0800219 ALOGE("pipe2() failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800220 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800221 }
222
Luke Huang94c43a12019-02-14 19:51:38 +0800223 // Set parameters
224 Fwmark fwmark;
225 fwmark.netId = NetworkController::LOCAL_NET_ID;
226 fwmark.explicitlySelected = true;
227 fwmark.protectedFromVpn = true;
228 fwmark.permission = PERMISSION_SYSTEM;
229 char markStr[UINT32_HEX_STRLEN];
230 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800231
Luke Huang94c43a12019-02-14 19:51:38 +0800232 std::vector<const std::string> argVector = {
Erik Kline5f0358b2018-02-16 15:08:09 +0900233 "/system/bin/dnsmasq",
234 "--keep-in-foreground",
235 "--no-resolv",
236 "--no-poll",
237 "--dhcp-authoritative",
238 // TODO: pipe through metered status from ConnService
239 "--dhcp-option-force=43,ANDROID_METERED",
240 "--pid-file",
Luke Huang94c43a12019-02-14 19:51:38 +0800241 "--listen-mark",
242 markStr,
243 "--user",
244 kDnsmasqUsername,
245 };
San Mehat9d10b342010-01-18 09:51:02 -0800246
Luke Huang94c43a12019-02-14 19:51:38 +0800247 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is
248 // passed.
249 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
250 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
251 dhcp_ranges[addrIndex + 1]));
San Mehat9d10b342010-01-18 09:51:02 -0800252 }
253
Luke Huang94c43a12019-02-14 19:51:38 +0800254 auto args = (char**)std::calloc(argVector.size() + 1, sizeof(char*));
255 for (unsigned i = 0; i < argVector.size(); i++) {
256 args[i] = (char*)argVector[i].c_str();
257 }
258
259 /*
260 * TODO: Create a monitoring thread to handle and restart
261 * the daemon if it exits prematurely
262 */
Luke Huang40962442019-02-26 11:46:10 +0800263
264 // Note that don't modify any memory between vfork and execv.
265 // Changing state of file descriptors would be fine. See posix_spawn_file_actions_add*
266 // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
267 // duplicated fd.
268 posix_spawn_file_actions_t fa;
269 int res = setPosixSpawnFileActionsAddDup2(&fa, pipefd[0], STDIN_FILENO);
270 if (res) {
271 ALOGE("posix_spawn set fa failed (%s)", strerror(res));
Luke Huang94c43a12019-02-14 19:51:38 +0800272 return -res;
273 }
274
Luke Huang40962442019-02-26 11:46:10 +0800275 posix_spawnattr_t attr;
276 res = setPosixSpawnAttrFlags(&attr, POSIX_SPAWN_USEVFORK);
277 if (res) {
278 ALOGE("posix_spawn set attr flag failed (%s)", strerror(res));
279 return -res;
280 }
281
282 pid_t pid;
283 res = posix_spawn(&pid, args[0], &fa, &attr, args, nullptr);
284 close(pipefd[0]);
285 free(args);
286 posix_spawnattr_destroy(&attr);
287 posix_spawn_file_actions_destroy(&fa);
288 if (res) {
289 ALOGE("posix_spawn failed (%s)", strerror(res));
290 close(pipefd[1]);
291 return -res;
292 }
Luke Huang94c43a12019-02-14 19:51:38 +0800293 mDaemonPid = pid;
294 mDaemonFd = pipefd[1];
295 configureForTethering(true);
296 applyDnsInterfaces();
297 ALOGD("Tethering services running");
298
San Mehat9d10b342010-01-18 09:51:02 -0800299 return 0;
300}
301
Luke Huangb5733d72018-08-21 17:17:19 +0800302std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
303 std::vector<char*> addrsCstrVec{};
304 addrsCstrVec.reserve(addrs.size());
305 for (const auto& addr : addrs) {
306 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
307 }
308 return addrsCstrVec;
309}
310
311int TetherController::startTethering(const std::vector<std::string>& dhcpRanges) {
312 struct in_addr v4_addr;
313 for (const auto& dhcpRange : dhcpRanges) {
314 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
315 return -EINVAL;
316 }
317 }
318 auto dhcp_ranges = toCstrVec(dhcpRanges);
319 return startTethering(dhcp_ranges.size(), dhcp_ranges.data());
320}
321
San Mehat9d10b342010-01-18 09:51:02 -0800322int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900323 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800324
325 if (mDaemonPid == 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000326 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800327 return 0;
328 }
329
Steve Block7b984e32011-12-20 16:22:42 +0000330 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800331
332 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700333 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800334 mDaemonPid = 0;
335 close(mDaemonFd);
336 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900337 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000338 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800339 return 0;
340}
Matthew Xie19944102012-07-12 16:42:07 -0700341
San Mehat9d10b342010-01-18 09:51:02 -0800342bool TetherController::isTetheringStarted() {
343 return (mDaemonPid == 0 ? false : true);
344}
345
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900346// dnsmasq can't parse commands larger than this due to the fixed-size buffer
347// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
348// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900349const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800350
Bernie Innocenti45238a12018-12-04 14:57:48 +0900351// TODO: convert callers to the overload taking a vector<string>
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700352int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700353 Fwmark fwmark;
354 fwmark.netId = netId;
355 fwmark.explicitlySelected = true;
356 fwmark.protectedFromVpn = true;
357 fwmark.permission = PERMISSION_SYSTEM;
358
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900359 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800360
Erik Kline1d065ba2016-06-08 13:24:45 +0900361 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900362 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700363 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800364
Lorenzo Colittic2841282015-11-25 22:13:57 +0900365 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700366 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900367 freeaddrinfo(res);
368 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000369 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900370 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900371 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800372 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800373 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800374
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900375 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
376 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800377 break;
378 }
379
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900380 daemonCmd += SEPARATOR;
381 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900382 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800383 }
384
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700385 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900386 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800387 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900388 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900389 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900390 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800391 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800392 }
393 }
394 return 0;
395}
396
Luke Huangb5733d72018-08-21 17:17:19 +0800397int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
398 struct in_addr v4_addr;
399 struct in6_addr v6_addr;
400 for (const auto& server : servers) {
401 if (!inet_pton(AF_INET, server.c_str(), &v4_addr) &&
402 !inet_pton(AF_INET6, server.c_str(), &v6_addr)) {
403 return -EINVAL;
404 }
405 }
406 auto dnsServers = toCstrVec(servers);
407 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
408}
409
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700410unsigned TetherController::getDnsNetId() {
411 return mDnsNetId;
412}
413
Erik Kline1d065ba2016-06-08 13:24:45 +0900414const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800415 return mDnsForwarders;
416}
417
Erik Kline1d065ba2016-06-08 13:24:45 +0900418bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900419 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800420 bool haveInterfaces = false;
421
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900422 for (const auto& ifname : mInterfaces) {
423 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
424 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800425 break;
426 }
427
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900428 daemonCmd += SEPARATOR;
429 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800430 haveInterfaces = true;
431 }
432
Erik Kline15079dd2018-05-18 23:10:56 +0900433 if (!haveInterfaces) {
434 mDnsmasqState.update_ifaces_cmd.clear();
435 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900436 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900437 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800438 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900439 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800440}
441
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800442int TetherController::tetherInterface(const char *interface) {
443 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700444 if (!isIfaceName(interface)) {
445 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800446 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700447 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800448
Erik Kline1d065ba2016-06-08 13:24:45 +0900449 if (!configureForIPv6Router(interface)) {
450 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800451 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900452 }
453 mInterfaces.push_back(interface);
454
455 if (!applyDnsInterfaces()) {
456 mInterfaces.pop_back();
457 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800458 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800459 } else {
460 return 0;
461 }
462}
463
San Mehat9d10b342010-01-18 09:51:02 -0800464int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800465 ALOGD("untetherInterface(%s)", interface);
466
Erik Kline1d065ba2016-06-08 13:24:45 +0900467 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
468 if (!strcmp(interface, it->c_str())) {
469 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800470
Erik Kline1d065ba2016-06-08 13:24:45 +0900471 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800472 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800473 }
474 }
475 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800476 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800477}
478
Erik Kline1d065ba2016-06-08 13:24:45 +0900479const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800480 return mInterfaces;
481}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900482
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900483int TetherController::setupIptablesHooks() {
484 int res;
485 res = setDefaults();
486 if (res < 0) {
487 return res;
488 }
489
490 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
491 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
492 // This is no longer optional and tethering will fail to start if it fails.
493 std::string mssRewriteCommand = StringPrintf(
494 "*mangle\n"
495 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
496 "COMMIT\n", LOCAL_MANGLE_FORWARD);
497
498 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
499 std::string defaultCommands = StringPrintf(
500 "*filter\n"
501 ":%s -\n"
502 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
503
504 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
505 if (res < 0) {
506 return res;
507 }
508
509 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
510 if (res < 0) {
511 return res;
512 }
513
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900514 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900515
516 return 0;
517}
518
519int TetherController::setDefaults() {
520 std::string v4Cmd = StringPrintf(
521 "*filter\n"
522 ":%s -\n"
523 "-A %s -j DROP\n"
524 "COMMIT\n"
525 "*nat\n"
526 ":%s -\n"
527 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
528
529 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900530 "*filter\n"
531 ":%s -\n"
532 "COMMIT\n"
533 "*raw\n"
534 ":%s -\n"
535 "COMMIT\n",
536 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900537
538 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
539 if (res < 0) {
540 return res;
541 }
542
543 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
544 if (res < 0) {
545 return res;
546 }
547
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900548 return 0;
549}
550
551int TetherController::enableNat(const char* intIface, const char* extIface) {
552 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
553
554 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900555 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900556 }
557
558 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
559 if (!strcmp(intIface, extIface)) {
560 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900561 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900562 }
563
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900564 if (isForwardingPairEnabled(intIface, extIface)) {
565 return 0;
566 }
567
568 // add this if we are the first enabled nat for this upstream
569 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900570 std::vector<std::string> v4Cmds = {
571 "*nat",
572 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
573 "COMMIT\n"
574 };
575
Luke Huangae038f82018-11-05 11:17:31 +0900576 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
577 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900578 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900579 if (!isAnyForwardingPairEnabled()) {
580 // unwind what's been done, but don't care about success - what more could we do?
581 setDefaults();
582 }
Luke Huang19b49c52018-10-22 12:12:05 +0900583 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900584 }
585 }
586
587 if (setForwardRules(true, intIface, extIface) != 0) {
588 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900589 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900590 setDefaults();
591 }
Luke Huang19b49c52018-10-22 12:12:05 +0900592 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900593 }
594
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900595 return 0;
596}
597
Luke Huangae038f82018-11-05 11:17:31 +0900598int TetherController::setTetherGlobalAlertRule() {
599 // Only add this if we are the first enabled nat
600 if (isAnyForwardingPairEnabled()) {
601 return 0;
602 }
603 const std::string cmds =
604 "*filter\n" +
605 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
606 "COMMIT\n";
607
608 return iptablesRestoreFunction(V4V6, cmds, nullptr);
609}
610
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900611int TetherController::setupIPv6CountersChain() {
612 // Only add this if we are the first enabled nat
613 if (isAnyForwardingPairEnabled()) {
614 return 0;
615 }
616
617 /*
618 * IPv6 tethering doesn't need the state-based conntrack rules, so
619 * it unconditionally jumps to the tether counters chain all the time.
620 */
Luke Huangae038f82018-11-05 11:17:31 +0900621 const std::string v6Cmds =
622 "*filter\n" +
623 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900624
Luke Huangae038f82018-11-05 11:17:31 +0900625 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900626}
627
628// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
629TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
630 const std::string& intIface, const std::string& extIface) {
631 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
632 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
633 if (it->second.iface == intIface) {
634 return &(it->second);
635 }
636 }
637 return nullptr;
638}
639
640void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
641 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
642 if (existingEntry != nullptr) {
643 existingEntry->active = true;
644 return;
645 }
646
647 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
648 .iface = intIface,
649 .active = true
650 }));
651}
652
653void TetherController::markForwardingPairDisabled(
654 const std::string& intIface, const std::string& extIface) {
655 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
656 if (existingEntry == nullptr) {
657 return;
658 }
659
660 existingEntry->active = false;
661}
662
663bool TetherController::isForwardingPairEnabled(
664 const std::string& intIface, const std::string& extIface) {
665 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
666 return existingEntry != nullptr && existingEntry->active;
667}
668
669bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
670 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
671 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
672 if (it->second.active) {
673 return true;
674 }
675 }
676 return false;
677}
678
679bool TetherController::isAnyForwardingPairEnabled() {
680 for (auto& it : mFwdIfaces) {
681 if (it.second.active) {
682 return true;
683 }
684 }
685 return false;
686}
687
688bool TetherController::tetherCountingRuleExists(
689 const std::string& iface1, const std::string& iface2) {
690 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
691 // is in the map regardless of its active status. Rules are added both ways so we check with
692 // the 2 combinations.
693 return findForwardingDownstream(iface1, iface2) != nullptr
694 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900695}
696
697/* static */
698std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
699 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
700}
701
702int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
703 const char *op = add ? "-A" : "-D";
704
705 std::string rpfilterCmd = StringPrintf(
706 "*raw\n"
707 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
708 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
709 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900710 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900711 }
712
713 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900714 "*raw",
715 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
716 LOCAL_RAW_PREROUTING, intIface),
717 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
718 LOCAL_RAW_PREROUTING, intIface),
719 "COMMIT",
720 "*filter",
721 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
722 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
723 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
724 intIface, extIface),
725 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
726 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900727 };
728
729 std::vector<std::string> v6 = {
730 "*filter",
731 };
732
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900733 // We only ever add tethering quota rules so that they stick.
734 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900735 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900736 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900737 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900738 v6.push_back(makeTetherCountingRule(extIface, intIface));
739 }
740
741 // Always make sure the drop rule is at the end.
742 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900743 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900744 if (add) {
745 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
746 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
747 }
748
749 v4.push_back("COMMIT\n");
750 v6.push_back("COMMIT\n");
751
752 // We only add IPv6 rules here, never remove them.
753 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
754 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
755 // unwind what's been done, but don't care about success - what more could we do?
756 if (add) {
757 setForwardRules(false, intIface, extIface);
758 }
Luke Huang19b49c52018-10-22 12:12:05 +0900759 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900760 }
761
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900762 if (add) {
763 addForwardingPair(intIface, extIface);
764 } else {
765 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900766 }
767
768 return 0;
769}
770
771int TetherController::disableNat(const char* intIface, const char* extIface) {
772 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900773 errno = ENODEV;
774 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900775 }
776
777 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900778 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900779 setDefaults();
780 }
781 return 0;
782}
783
784void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
785 for (TetherStats& existing : statsList) {
786 if (existing.addStatsIfMatch(stats)) {
787 return;
788 }
789 }
790 // No match. Insert a new interface pair.
791 statsList.push_back(stats);
792}
793
794/*
795 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900796 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900797 * pkts bytes target prot opt in out source destination
798 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
799 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
800 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
801 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
802 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900803 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900804 * pkts bytes target prot opt in out source destination
805 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
806 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
807 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900808 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900809int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900810 const std::string& statsOutput,
811 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800812 enum IndexOfIptChain {
813 ORIG_LINE,
814 PACKET_COUNTS,
815 BYTE_COUNTS,
816 HYPHEN,
817 IFACE0_NAME,
818 IFACE1_NAME,
819 SOURCE,
820 DESTINATION
821 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900822 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900823 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900824
waynema71a0b592018-11-21 13:31:34 +0800825 static const std::string NUM = "(\\d+)";
826 static const std::string IFACE = "([^\\s]+)";
827 static const std::string DST = "(0.0.0.0/0|::/0)";
828 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
829 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
830 "\\s+" + DST + "\\s+" + DST;
831 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900832
waynema71a0b592018-11-21 13:31:34 +0800833 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
834 int headerLine = 0;
835 for (const std::string& line : lines) {
836 // Skip headers.
837 if (headerLine < 2) {
838 if (line.empty()) {
839 ALOGV("Empty header while parsing tethering stats");
840 return -EREMOTEIO;
841 }
842 headerLine++;
843 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900844 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900845
waynema71a0b592018-11-21 13:31:34 +0800846 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900847
waynema71a0b592018-11-21 13:31:34 +0800848 extraProcessingInfo = line;
849 std::smatch matches;
850 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
851 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
852 // IPv4 has "--" indicating what to do with fragments...
853 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
854 // ... but IPv6 does not.
855 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
856 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
857 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
858 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
859 std::string iface0 = matches[IFACE0_NAME].str();
860 std::string iface1 = matches[IFACE1_NAME].str();
861 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900862
waynema71a0b592018-11-21 13:31:34 +0800863 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
864 " rest=<%s> orig line=<%s>",
865 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900866 /*
867 * The following assumes that the 1st rule has in:extIface out:intIface,
868 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900869 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900870 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900871 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800872 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
873 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900874 stats.intIface = iface0;
875 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900876 stats.txPackets = packets;
877 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900878 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800879 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
880 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900881 stats.rxPackets = packets;
882 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900883 }
884 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900885 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900886 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900887 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900888 }
889 }
890
891 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900892 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900893 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900894 }
895 return 0;
896}
897
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900898StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900899 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900900 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900901
902 for (const IptablesTarget target : {V4, V6}) {
903 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900904 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900905 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
906 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900907 }
908
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900909 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900910 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
911 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900912 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900913 }
914 }
915
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900916 return statsList;
917}
918
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900919} // namespace net
920} // namespace android