blob: c987d634e655b1bb2daee3a12a4e5a5f7026378b [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"
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -070039#include <android-base/scopeguard.h>
Lorenzo Colittia93126d2017-08-24 13:28:19 +090040#include <android-base/stringprintf.h>
George Burgess IVe3dc1312019-02-28 11:27:04 -080041#include <android-base/strings.h>
42#include <android-base/unique_fd.h>
Kazuhiro Ondo6b858eb2011-06-24 20:31:03 -050043#include <cutils/properties.h>
Logan Chien3f461482018-04-23 14:31:32 +080044#include <log/log.h>
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090045#include <netdutils/StatusOr.h>
San Mehat9d10b342010-01-18 09:51:02 -080046
Erik Klineb31fd692018-06-06 20:50:11 +090047#include "Controllers.h"
Lorenzo Colitti667c4772014-08-26 14:13:07 -070048#include "Fwmark.h"
Erik Kline1d065ba2016-06-08 13:24:45 +090049#include "InterfaceController.h"
Mike Yuf0e019f2019-03-13 14:43:39 +080050#include "NetdConstants.h"
Lorenzo Colittie20a5262017-05-09 18:30:44 +090051#include "NetworkController.h"
Mike Yuf0e019f2019-03-13 14:43:39 +080052#include "Permission.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
120} // namespace
121
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900122auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
123
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900124const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
125 "*filter\n"
126 "-nvx -L %s\n"
127 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
128
Erik Kline15079dd2018-05-18 23:10:56 +0900129int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
130 if (cmd.empty()) return 0;
131
Erik Klineb31fd692018-06-06 20:50:11 +0900132 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900133 // Send the trailing \0 as well.
134 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900135 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900136 errno = EREMOTEIO;
137 return -1;
138 }
139 return 0;
140}
141
142void TetherController::DnsmasqState::clear() {
143 update_ifaces_cmd.clear();
144 update_dns_cmd.clear();
145}
146
147int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
148 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
149}
150
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700151TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900152 if (inBpToolsMode()) {
153 enableForwarding(BP_TOOLS_MODE);
154 } else {
155 setIpFwdEnabled();
156 }
San Mehat9d10b342010-01-18 09:51:02 -0800157}
158
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900159bool TetherController::setIpFwdEnabled() {
160 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900161 bool disable = mForwardingRequests.empty();
162 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900163 ALOGD("Setting IP forward enable = %s", value);
164 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
165 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900166 if (disable) {
167 // Turning off the forwarding sysconf in the kernel has the side effect
168 // of turning on ICMP redirect, which is a security hazard.
169 // Turn ICMP redirect back off immediately.
170 int rv = InterfaceController::disableIcmpRedirects();
171 success &= (rv == 0);
172 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900173 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800174}
175
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900176bool TetherController::enableForwarding(const char* requester) {
177 // Don't return an error if this requester already requested forwarding. Only return errors for
178 // things that the caller caller needs to care about, such as "couldn't write to the file to
179 // enable forwarding".
180 mForwardingRequests.insert(requester);
181 return setIpFwdEnabled();
182}
San Mehat9d10b342010-01-18 09:51:02 -0800183
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900184bool TetherController::disableForwarding(const char* requester) {
185 mForwardingRequests.erase(requester);
186 return setIpFwdEnabled();
187}
San Mehat9d10b342010-01-18 09:51:02 -0800188
Luke Huang728cf4c2019-03-14 19:43:02 +0800189const std::set<std::string>& TetherController::getIpfwdRequesterList() const {
190 return mForwardingRequests;
San Mehat9d10b342010-01-18 09:51:02 -0800191}
192
Luke Huang91bd3e12019-08-20 11:33:52 +0800193int TetherController::startTethering(bool usingLegacyDnsProxy, int num_addrs, char** dhcp_ranges) {
194 if (!usingLegacyDnsProxy && num_addrs == 0) {
195 // Both DHCP and DnsProxy are disabled, we don't need to start dnsmasq
196 configureForTethering(true);
197 mIsTetheringStarted = true;
198 return 0;
199 }
200
201 if (mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000202 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800203 errno = EBUSY;
Luke Huangb5733d72018-08-21 17:17:19 +0800204 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800205 }
206
Steve Block7b984e32011-12-20 16:22:42 +0000207 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800208
George Burgess IVe3dc1312019-02-28 11:27:04 -0800209 unique_fd pipeRead, pipeWrite;
210 if (!Pipe(&pipeRead, &pipeWrite, O_CLOEXEC)) {
Luke Huangb5733d72018-08-21 17:17:19 +0800211 int res = errno;
Luke Huang94c43a12019-02-14 19:51:38 +0800212 ALOGE("pipe2() failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800213 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800214 }
215
Luke Huang94c43a12019-02-14 19:51:38 +0800216 // Set parameters
217 Fwmark fwmark;
218 fwmark.netId = NetworkController::LOCAL_NET_ID;
219 fwmark.explicitlySelected = true;
220 fwmark.protectedFromVpn = true;
221 fwmark.permission = PERMISSION_SYSTEM;
222 char markStr[UINT32_HEX_STRLEN];
223 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800224
Luke Huang94c43a12019-02-14 19:51:38 +0800225 std::vector<const std::string> argVector = {
Erik Kline5f0358b2018-02-16 15:08:09 +0900226 "/system/bin/dnsmasq",
227 "--keep-in-foreground",
228 "--no-resolv",
229 "--no-poll",
230 "--dhcp-authoritative",
231 // TODO: pipe through metered status from ConnService
232 "--dhcp-option-force=43,ANDROID_METERED",
233 "--pid-file",
Luke Huang94c43a12019-02-14 19:51:38 +0800234 "--listen-mark",
235 markStr,
236 "--user",
237 kDnsmasqUsername,
238 };
San Mehat9d10b342010-01-18 09:51:02 -0800239
Luke Huang91bd3e12019-08-20 11:33:52 +0800240 if (!usingLegacyDnsProxy) {
241 argVector.push_back("--port=0");
242 }
243
244 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is passed.
Luke Huang94c43a12019-02-14 19:51:38 +0800245 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
246 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
247 dhcp_ranges[addrIndex + 1]));
San Mehat9d10b342010-01-18 09:51:02 -0800248 }
249
George Burgess IVe3dc1312019-02-28 11:27:04 -0800250 std::vector<char*> args(argVector.size() + 1);
Luke Huang94c43a12019-02-14 19:51:38 +0800251 for (unsigned i = 0; i < argVector.size(); i++) {
252 args[i] = (char*)argVector[i].c_str();
253 }
254
255 /*
256 * TODO: Create a monitoring thread to handle and restart
257 * the daemon if it exits prematurely
258 */
Luke Huang40962442019-02-26 11:46:10 +0800259
260 // Note that don't modify any memory between vfork and execv.
261 // Changing state of file descriptors would be fine. See posix_spawn_file_actions_add*
262 // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
263 // duplicated fd.
264 posix_spawn_file_actions_t fa;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700265 int res = posix_spawn_file_actions_init(&fa);
Luke Huang40962442019-02-26 11:46:10 +0800266 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700267 ALOGE("posix_spawn_file_actions_init failed (%s)", strerror(res));
268 return -res;
269 }
270 const android::base::ScopeGuard faGuard = [&] { posix_spawn_file_actions_destroy(&fa); };
271 res = posix_spawn_file_actions_adddup2(&fa, pipeRead.get(), STDIN_FILENO);
272 if (res) {
273 ALOGE("posix_spawn_file_actions_adddup2 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;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700278 res = posix_spawnattr_init(&attr);
Luke Huang40962442019-02-26 11:46:10 +0800279 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700280 ALOGE("posix_spawnattr_init failed (%s)", strerror(res));
281 return -res;
282 }
283 const android::base::ScopeGuard attrGuard = [&] { posix_spawnattr_destroy(&attr); };
284 res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK);
285 if (res) {
286 ALOGE("posix_spawnattr_setflags failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800287 return -res;
288 }
289
290 pid_t pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800291 res = posix_spawn(&pid, args[0], &fa, &attr, &args[0], nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800292 if (res) {
293 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800294 return -res;
295 }
Luke Huang94c43a12019-02-14 19:51:38 +0800296 mDaemonPid = pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800297 mDaemonFd = pipeWrite.release();
Luke Huang94c43a12019-02-14 19:51:38 +0800298 configureForTethering(true);
Luke Huang91bd3e12019-08-20 11:33:52 +0800299 mIsTetheringStarted = true;
Luke Huang94c43a12019-02-14 19:51:38 +0800300 applyDnsInterfaces();
301 ALOGD("Tethering services running");
302
San Mehat9d10b342010-01-18 09:51:02 -0800303 return 0;
304}
305
Luke Huangb5733d72018-08-21 17:17:19 +0800306std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
307 std::vector<char*> addrsCstrVec{};
308 addrsCstrVec.reserve(addrs.size());
309 for (const auto& addr : addrs) {
310 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
311 }
312 return addrsCstrVec;
313}
314
Luke Huang91bd3e12019-08-20 11:33:52 +0800315int TetherController::startTethering(bool usingLegacyDnsProxy,
316 const std::vector<std::string>& dhcpRanges) {
Luke Huangb5733d72018-08-21 17:17:19 +0800317 struct in_addr v4_addr;
318 for (const auto& dhcpRange : dhcpRanges) {
319 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
320 return -EINVAL;
321 }
322 }
323 auto dhcp_ranges = toCstrVec(dhcpRanges);
Luke Huang91bd3e12019-08-20 11:33:52 +0800324 return startTethering(usingLegacyDnsProxy, dhcp_ranges.size(), dhcp_ranges.data());
Luke Huangb5733d72018-08-21 17:17:19 +0800325}
326
San Mehat9d10b342010-01-18 09:51:02 -0800327int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900328 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800329
Luke Huang91bd3e12019-08-20 11:33:52 +0800330 if (!mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000331 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800332 return 0;
333 }
334
Luke Huang91bd3e12019-08-20 11:33:52 +0800335 mIsTetheringStarted = false;
336 // dnsmasq is not started
337 if (mDaemonPid == 0) {
338 return 0;
339 }
340
Steve Block7b984e32011-12-20 16:22:42 +0000341 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800342
343 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700344 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800345 mDaemonPid = 0;
346 close(mDaemonFd);
347 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900348 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000349 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800350 return 0;
351}
Matthew Xie19944102012-07-12 16:42:07 -0700352
San Mehat9d10b342010-01-18 09:51:02 -0800353bool TetherController::isTetheringStarted() {
Luke Huang91bd3e12019-08-20 11:33:52 +0800354 return mIsTetheringStarted;
San Mehat9d10b342010-01-18 09:51:02 -0800355}
356
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900357// dnsmasq can't parse commands larger than this due to the fixed-size buffer
358// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
359// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900360const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800361
Luke Huang8dc1cac2019-03-30 16:12:31 +0800362// TODO: Remove overload function and update this after NDC migration.
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700363int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700364 Fwmark fwmark;
365 fwmark.netId = netId;
366 fwmark.explicitlySelected = true;
367 fwmark.protectedFromVpn = true;
368 fwmark.permission = PERMISSION_SYSTEM;
369
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900370 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800371
Erik Kline1d065ba2016-06-08 13:24:45 +0900372 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900373 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700374 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800375
Lorenzo Colittic2841282015-11-25 22:13:57 +0900376 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700377 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900378 freeaddrinfo(res);
379 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000380 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900381 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900382 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800383 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800384 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800385
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900386 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
387 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800388 break;
389 }
390
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900391 daemonCmd += SEPARATOR;
392 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900393 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800394 }
395
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700396 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900397 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800398 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900399 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900400 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900401 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800402 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800403 }
404 }
405 return 0;
406}
407
Luke Huangb5733d72018-08-21 17:17:19 +0800408int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
Luke Huangb5733d72018-08-21 17:17:19 +0800409 auto dnsServers = toCstrVec(servers);
410 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
411}
412
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700413unsigned TetherController::getDnsNetId() {
414 return mDnsNetId;
415}
416
Erik Kline1d065ba2016-06-08 13:24:45 +0900417const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800418 return mDnsForwarders;
419}
420
Erik Kline1d065ba2016-06-08 13:24:45 +0900421bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900422 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800423 bool haveInterfaces = false;
424
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900425 for (const auto& ifname : mInterfaces) {
426 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
427 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800428 break;
429 }
430
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900431 daemonCmd += SEPARATOR;
432 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800433 haveInterfaces = true;
434 }
435
Erik Kline15079dd2018-05-18 23:10:56 +0900436 if (!haveInterfaces) {
437 mDnsmasqState.update_ifaces_cmd.clear();
438 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900439 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900440 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800441 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900442 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800443}
444
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800445int TetherController::tetherInterface(const char *interface) {
446 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700447 if (!isIfaceName(interface)) {
448 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800449 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700450 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800451
Erik Kline1d065ba2016-06-08 13:24:45 +0900452 if (!configureForIPv6Router(interface)) {
453 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800454 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900455 }
456 mInterfaces.push_back(interface);
457
458 if (!applyDnsInterfaces()) {
459 mInterfaces.pop_back();
460 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800461 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800462 } else {
463 return 0;
464 }
465}
466
San Mehat9d10b342010-01-18 09:51:02 -0800467int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800468 ALOGD("untetherInterface(%s)", interface);
469
Erik Kline1d065ba2016-06-08 13:24:45 +0900470 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
471 if (!strcmp(interface, it->c_str())) {
472 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800473
Erik Kline1d065ba2016-06-08 13:24:45 +0900474 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800475 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800476 }
477 }
478 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800479 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800480}
481
Erik Kline1d065ba2016-06-08 13:24:45 +0900482const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800483 return mInterfaces;
484}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900485
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900486int TetherController::setupIptablesHooks() {
487 int res;
488 res = setDefaults();
489 if (res < 0) {
490 return res;
491 }
492
493 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
494 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
495 // This is no longer optional and tethering will fail to start if it fails.
496 std::string mssRewriteCommand = StringPrintf(
497 "*mangle\n"
498 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
499 "COMMIT\n", LOCAL_MANGLE_FORWARD);
500
501 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
502 std::string defaultCommands = StringPrintf(
503 "*filter\n"
504 ":%s -\n"
505 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
506
507 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
508 if (res < 0) {
509 return res;
510 }
511
512 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
513 if (res < 0) {
514 return res;
515 }
516
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900517 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900518
519 return 0;
520}
521
522int TetherController::setDefaults() {
523 std::string v4Cmd = StringPrintf(
524 "*filter\n"
525 ":%s -\n"
526 "-A %s -j DROP\n"
527 "COMMIT\n"
528 "*nat\n"
529 ":%s -\n"
530 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
531
532 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900533 "*filter\n"
534 ":%s -\n"
535 "COMMIT\n"
536 "*raw\n"
537 ":%s -\n"
538 "COMMIT\n",
539 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900540
541 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
542 if (res < 0) {
543 return res;
544 }
545
546 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
547 if (res < 0) {
548 return res;
549 }
550
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900551 return 0;
552}
553
554int TetherController::enableNat(const char* intIface, const char* extIface) {
555 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
556
557 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900558 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900559 }
560
561 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
562 if (!strcmp(intIface, extIface)) {
563 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900564 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900565 }
566
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900567 if (isForwardingPairEnabled(intIface, extIface)) {
568 return 0;
569 }
570
571 // add this if we are the first enabled nat for this upstream
572 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900573 std::vector<std::string> v4Cmds = {
574 "*nat",
575 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
576 "COMMIT\n"
577 };
578
Luke Huangae038f82018-11-05 11:17:31 +0900579 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
580 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900581 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900582 if (!isAnyForwardingPairEnabled()) {
583 // unwind what's been done, but don't care about success - what more could we do?
584 setDefaults();
585 }
Luke Huang19b49c52018-10-22 12:12:05 +0900586 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900587 }
588 }
589
590 if (setForwardRules(true, intIface, extIface) != 0) {
591 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900592 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900593 setDefaults();
594 }
Luke Huang19b49c52018-10-22 12:12:05 +0900595 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900596 }
597
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900598 return 0;
599}
600
Luke Huangae038f82018-11-05 11:17:31 +0900601int TetherController::setTetherGlobalAlertRule() {
602 // Only add this if we are the first enabled nat
603 if (isAnyForwardingPairEnabled()) {
604 return 0;
605 }
606 const std::string cmds =
607 "*filter\n" +
608 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
609 "COMMIT\n";
610
611 return iptablesRestoreFunction(V4V6, cmds, nullptr);
612}
613
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900614int TetherController::setupIPv6CountersChain() {
615 // Only add this if we are the first enabled nat
616 if (isAnyForwardingPairEnabled()) {
617 return 0;
618 }
619
620 /*
621 * IPv6 tethering doesn't need the state-based conntrack rules, so
622 * it unconditionally jumps to the tether counters chain all the time.
623 */
Luke Huangae038f82018-11-05 11:17:31 +0900624 const std::string v6Cmds =
625 "*filter\n" +
626 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900627
Luke Huangae038f82018-11-05 11:17:31 +0900628 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900629}
630
631// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
632TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
633 const std::string& intIface, const std::string& extIface) {
634 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
635 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
636 if (it->second.iface == intIface) {
637 return &(it->second);
638 }
639 }
640 return nullptr;
641}
642
643void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
644 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
645 if (existingEntry != nullptr) {
646 existingEntry->active = true;
647 return;
648 }
649
650 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
651 .iface = intIface,
652 .active = true
653 }));
654}
655
656void TetherController::markForwardingPairDisabled(
657 const std::string& intIface, const std::string& extIface) {
658 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
659 if (existingEntry == nullptr) {
660 return;
661 }
662
663 existingEntry->active = false;
664}
665
666bool TetherController::isForwardingPairEnabled(
667 const std::string& intIface, const std::string& extIface) {
668 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
669 return existingEntry != nullptr && existingEntry->active;
670}
671
672bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
673 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
674 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
675 if (it->second.active) {
676 return true;
677 }
678 }
679 return false;
680}
681
682bool TetherController::isAnyForwardingPairEnabled() {
683 for (auto& it : mFwdIfaces) {
684 if (it.second.active) {
685 return true;
686 }
687 }
688 return false;
689}
690
691bool TetherController::tetherCountingRuleExists(
692 const std::string& iface1, const std::string& iface2) {
693 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
694 // is in the map regardless of its active status. Rules are added both ways so we check with
695 // the 2 combinations.
696 return findForwardingDownstream(iface1, iface2) != nullptr
697 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900698}
699
700/* static */
701std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
702 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
703}
704
705int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
706 const char *op = add ? "-A" : "-D";
707
708 std::string rpfilterCmd = StringPrintf(
709 "*raw\n"
710 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
711 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
712 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900713 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900714 }
715
716 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900717 "*raw",
718 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
719 LOCAL_RAW_PREROUTING, intIface),
720 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
721 LOCAL_RAW_PREROUTING, intIface),
722 "COMMIT",
723 "*filter",
724 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
725 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
726 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
727 intIface, extIface),
728 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
729 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900730 };
731
732 std::vector<std::string> v6 = {
733 "*filter",
734 };
735
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900736 // We only ever add tethering quota rules so that they stick.
737 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900738 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900739 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900740 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900741 v6.push_back(makeTetherCountingRule(extIface, intIface));
742 }
743
744 // Always make sure the drop rule is at the end.
745 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900746 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900747 if (add) {
748 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
749 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
750 }
751
752 v4.push_back("COMMIT\n");
753 v6.push_back("COMMIT\n");
754
755 // We only add IPv6 rules here, never remove them.
756 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
757 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
758 // unwind what's been done, but don't care about success - what more could we do?
759 if (add) {
760 setForwardRules(false, intIface, extIface);
761 }
Luke Huang19b49c52018-10-22 12:12:05 +0900762 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900763 }
764
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900765 if (add) {
766 addForwardingPair(intIface, extIface);
767 } else {
768 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900769 }
770
771 return 0;
772}
773
774int TetherController::disableNat(const char* intIface, const char* extIface) {
775 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900776 errno = ENODEV;
777 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900778 }
779
780 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900781 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900782 setDefaults();
783 }
784 return 0;
785}
786
787void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
788 for (TetherStats& existing : statsList) {
789 if (existing.addStatsIfMatch(stats)) {
790 return;
791 }
792 }
793 // No match. Insert a new interface pair.
794 statsList.push_back(stats);
795}
796
797/*
798 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900799 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900800 * pkts bytes target prot opt in out source destination
801 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
802 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
803 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
804 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
805 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900806 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900807 * pkts bytes target prot opt in out source destination
808 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
809 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
810 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900811 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900812int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900813 const std::string& statsOutput,
814 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800815 enum IndexOfIptChain {
816 ORIG_LINE,
817 PACKET_COUNTS,
818 BYTE_COUNTS,
819 HYPHEN,
820 IFACE0_NAME,
821 IFACE1_NAME,
822 SOURCE,
823 DESTINATION
824 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900825 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900826 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900827
waynema71a0b592018-11-21 13:31:34 +0800828 static const std::string NUM = "(\\d+)";
829 static const std::string IFACE = "([^\\s]+)";
830 static const std::string DST = "(0.0.0.0/0|::/0)";
831 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
832 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
833 "\\s+" + DST + "\\s+" + DST;
834 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900835
waynema71a0b592018-11-21 13:31:34 +0800836 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
837 int headerLine = 0;
838 for (const std::string& line : lines) {
839 // Skip headers.
840 if (headerLine < 2) {
841 if (line.empty()) {
842 ALOGV("Empty header while parsing tethering stats");
843 return -EREMOTEIO;
844 }
845 headerLine++;
846 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900847 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900848
waynema71a0b592018-11-21 13:31:34 +0800849 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900850
waynema71a0b592018-11-21 13:31:34 +0800851 extraProcessingInfo = line;
852 std::smatch matches;
853 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
854 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
855 // IPv4 has "--" indicating what to do with fragments...
856 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
857 // ... but IPv6 does not.
858 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
859 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
860 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
861 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
862 std::string iface0 = matches[IFACE0_NAME].str();
863 std::string iface1 = matches[IFACE1_NAME].str();
864 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900865
waynema71a0b592018-11-21 13:31:34 +0800866 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
867 " rest=<%s> orig line=<%s>",
868 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900869 /*
870 * The following assumes that the 1st rule has in:extIface out:intIface,
871 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900872 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900873 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900874 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800875 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
876 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900877 stats.intIface = iface0;
878 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900879 stats.txPackets = packets;
880 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900881 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800882 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
883 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900884 stats.rxPackets = packets;
885 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900886 }
887 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900888 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900889 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900890 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900891 }
892 }
893
894 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900895 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900896 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900897 }
898 return 0;
899}
900
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900901StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900902 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900903 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900904
905 for (const IptablesTarget target : {V4, V6}) {
906 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900907 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900908 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
909 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900910 }
911
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900912 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900913 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
914 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900915 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900916 }
917 }
918
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900919 return statsList;
920}
921
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900922} // namespace net
923} // namespace android