blob: b56480a97b59eb72bdf0af1578e94880a96b3520 [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 Colitti52db3912020-02-17 23:59:45 +090045#include <netdutils/DumpWriter.h>
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090046#include <netdutils/StatusOr.h>
San Mehat9d10b342010-01-18 09:51:02 -080047
Erik Klineb31fd692018-06-06 20:50:11 +090048#include "Controllers.h"
Lorenzo Colitti667c4772014-08-26 14:13:07 -070049#include "Fwmark.h"
Erik Kline1d065ba2016-06-08 13:24:45 +090050#include "InterfaceController.h"
Mike Yuf0e019f2019-03-13 14:43:39 +080051#include "NetdConstants.h"
Lorenzo Colittie20a5262017-05-09 18:30:44 +090052#include "NetworkController.h"
Mike Yuf0e019f2019-03-13 14:43:39 +080053#include "Permission.h"
San Mehat9d10b342010-01-18 09:51:02 -080054#include "TetherController.h"
55
Bernie Innocenti4debf3b2018-09-12 13:54:50 +090056namespace android {
57namespace net {
58
Lorenzo Colittia93126d2017-08-24 13:28:19 +090059using android::base::Join;
George Burgess IVe3dc1312019-02-28 11:27:04 -080060using android::base::Pipe;
Erik Klineb31fd692018-06-06 20:50:11 +090061using android::base::StringPrintf;
George Burgess IVe3dc1312019-02-28 11:27:04 -080062using android::base::unique_fd;
Lorenzo Colitti52db3912020-02-17 23:59:45 +090063using android::netdutils::DumpWriter;
64using android::netdutils::ScopedIndent;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090065using android::netdutils::statusFromErrno;
Erik Klineb31fd692018-06-06 20:50:11 +090066using android::netdutils::StatusOr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090067
Lorenzo Colitti799625c2015-02-25 12:52:00 +090068namespace {
69
Erik Kline1d065ba2016-06-08 13:24:45 +090070const char BP_TOOLS_MODE[] = "bp-tools";
71const char IPV4_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv4/ip_forward";
72const char IPV6_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv6/conf/all/forwarding";
73const char SEPARATOR[] = "|";
Erik Kline93f9b222017-10-22 21:24:58 +090074constexpr const char kTcpBeLiberal[] = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
Lorenzo Colitti799625c2015-02-25 12:52:00 +090075
Erik Kline5f0358b2018-02-16 15:08:09 +090076// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
77constexpr const char kDnsmasqUsername[] = "dns_tether";
78
Lorenzo Colitti799625c2015-02-25 12:52:00 +090079bool writeToFile(const char* filename, const char* value) {
Nick Kralevichb95c60c2016-11-19 09:09:16 -080080 int fd = open(filename, O_WRONLY | O_CLOEXEC);
Nicolas Geoffrayafd40372015-03-16 11:58:06 +000081 if (fd < 0) {
82 ALOGE("Failed to open %s: %s", filename, strerror(errno));
83 return false;
84 }
85
86 const ssize_t len = strlen(value);
87 if (write(fd, value, len) != len) {
88 ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
89 close(fd);
90 return false;
91 }
92 close(fd);
93 return true;
Lorenzo Colitti799625c2015-02-25 12:52:00 +090094}
95
Erik Kline93f9b222017-10-22 21:24:58 +090096// TODO: Consider altering TCP and UDP timeouts as well.
97void configureForTethering(bool enabled) {
98 writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
99}
100
Erik Kline1d065ba2016-06-08 13:24:45 +0900101bool configureForIPv6Router(const char *interface) {
102 return (InterfaceController::setEnableIPv6(interface, 0) == 0)
103 && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
Erik Kline6cddf512016-08-09 15:28:42 +0900104 && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
105 && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
Erik Kline1d065ba2016-06-08 13:24:45 +0900106 && (InterfaceController::setEnableIPv6(interface, 1) == 0);
107}
108
109void configureForIPv6Client(const char *interface) {
110 InterfaceController::setAcceptIPv6Ra(interface, 1);
Erik Kline6cddf512016-08-09 15:28:42 +0900111 InterfaceController::setAcceptIPv6Dad(interface, 1);
112 InterfaceController::setIPv6DadTransmits(interface, "1");
Erik Kline1d065ba2016-06-08 13:24:45 +0900113 InterfaceController::setEnableIPv6(interface, 0);
114}
115
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900116bool inBpToolsMode() {
117 // In BP tools mode, do not disable IP forwarding
118 char bootmode[PROPERTY_VALUE_MAX] = {0};
119 property_get("ro.bootmode", bootmode, "unknown");
120 return !strcmp(BP_TOOLS_MODE, bootmode);
121}
122
123} // namespace
124
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900125auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
126
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900127const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
128 "*filter\n"
129 "-nvx -L %s\n"
130 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
131
Erik Kline15079dd2018-05-18 23:10:56 +0900132int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
133 if (cmd.empty()) return 0;
134
Erik Klineb31fd692018-06-06 20:50:11 +0900135 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900136 // Send the trailing \0 as well.
137 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900138 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900139 errno = EREMOTEIO;
140 return -1;
141 }
142 return 0;
143}
144
145void TetherController::DnsmasqState::clear() {
146 update_ifaces_cmd.clear();
147 update_dns_cmd.clear();
148}
149
150int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
151 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
152}
153
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700154TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900155 if (inBpToolsMode()) {
156 enableForwarding(BP_TOOLS_MODE);
157 } else {
158 setIpFwdEnabled();
159 }
San Mehat9d10b342010-01-18 09:51:02 -0800160}
161
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900162bool TetherController::setIpFwdEnabled() {
163 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900164 bool disable = mForwardingRequests.empty();
165 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900166 ALOGD("Setting IP forward enable = %s", value);
167 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
168 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900169 if (disable) {
170 // Turning off the forwarding sysconf in the kernel has the side effect
171 // of turning on ICMP redirect, which is a security hazard.
172 // Turn ICMP redirect back off immediately.
173 int rv = InterfaceController::disableIcmpRedirects();
174 success &= (rv == 0);
175 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900176 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800177}
178
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900179bool TetherController::enableForwarding(const char* requester) {
180 // Don't return an error if this requester already requested forwarding. Only return errors for
181 // things that the caller caller needs to care about, such as "couldn't write to the file to
182 // enable forwarding".
183 mForwardingRequests.insert(requester);
184 return setIpFwdEnabled();
185}
San Mehat9d10b342010-01-18 09:51:02 -0800186
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900187bool TetherController::disableForwarding(const char* requester) {
188 mForwardingRequests.erase(requester);
189 return setIpFwdEnabled();
190}
San Mehat9d10b342010-01-18 09:51:02 -0800191
Luke Huang728cf4c2019-03-14 19:43:02 +0800192const std::set<std::string>& TetherController::getIpfwdRequesterList() const {
193 return mForwardingRequests;
San Mehat9d10b342010-01-18 09:51:02 -0800194}
195
Luke Huang91bd3e12019-08-20 11:33:52 +0800196int TetherController::startTethering(bool usingLegacyDnsProxy, int num_addrs, char** dhcp_ranges) {
197 if (!usingLegacyDnsProxy && num_addrs == 0) {
198 // Both DHCP and DnsProxy are disabled, we don't need to start dnsmasq
199 configureForTethering(true);
200 mIsTetheringStarted = true;
201 return 0;
202 }
203
204 if (mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000205 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800206 errno = EBUSY;
Luke Huangb5733d72018-08-21 17:17:19 +0800207 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800208 }
209
Steve Block7b984e32011-12-20 16:22:42 +0000210 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800211
George Burgess IVe3dc1312019-02-28 11:27:04 -0800212 unique_fd pipeRead, pipeWrite;
213 if (!Pipe(&pipeRead, &pipeWrite, O_CLOEXEC)) {
Luke Huangb5733d72018-08-21 17:17:19 +0800214 int res = errno;
Luke Huang94c43a12019-02-14 19:51:38 +0800215 ALOGE("pipe2() failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800216 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800217 }
218
Luke Huang94c43a12019-02-14 19:51:38 +0800219 // Set parameters
220 Fwmark fwmark;
221 fwmark.netId = NetworkController::LOCAL_NET_ID;
222 fwmark.explicitlySelected = true;
223 fwmark.protectedFromVpn = true;
224 fwmark.permission = PERMISSION_SYSTEM;
225 char markStr[UINT32_HEX_STRLEN];
226 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800227
Luke Huang94c43a12019-02-14 19:51:38 +0800228 std::vector<const std::string> argVector = {
Erik Kline5f0358b2018-02-16 15:08:09 +0900229 "/system/bin/dnsmasq",
230 "--keep-in-foreground",
231 "--no-resolv",
232 "--no-poll",
233 "--dhcp-authoritative",
234 // TODO: pipe through metered status from ConnService
235 "--dhcp-option-force=43,ANDROID_METERED",
236 "--pid-file",
Luke Huang94c43a12019-02-14 19:51:38 +0800237 "--listen-mark",
238 markStr,
239 "--user",
240 kDnsmasqUsername,
241 };
San Mehat9d10b342010-01-18 09:51:02 -0800242
Luke Huang91bd3e12019-08-20 11:33:52 +0800243 if (!usingLegacyDnsProxy) {
244 argVector.push_back("--port=0");
245 }
246
247 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is passed.
Luke Huang94c43a12019-02-14 19:51:38 +0800248 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
249 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
250 dhcp_ranges[addrIndex + 1]));
San Mehat9d10b342010-01-18 09:51:02 -0800251 }
252
George Burgess IVe3dc1312019-02-28 11:27:04 -0800253 std::vector<char*> args(argVector.size() + 1);
Luke Huang94c43a12019-02-14 19:51:38 +0800254 for (unsigned i = 0; i < argVector.size(); i++) {
255 args[i] = (char*)argVector[i].c_str();
256 }
257
258 /*
259 * TODO: Create a monitoring thread to handle and restart
260 * the daemon if it exits prematurely
261 */
Luke Huang40962442019-02-26 11:46:10 +0800262
263 // Note that don't modify any memory between vfork and execv.
264 // Changing state of file descriptors would be fine. See posix_spawn_file_actions_add*
265 // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
266 // duplicated fd.
267 posix_spawn_file_actions_t fa;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700268 int res = posix_spawn_file_actions_init(&fa);
Luke Huang40962442019-02-26 11:46:10 +0800269 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700270 ALOGE("posix_spawn_file_actions_init failed (%s)", strerror(res));
271 return -res;
272 }
273 const android::base::ScopeGuard faGuard = [&] { posix_spawn_file_actions_destroy(&fa); };
274 res = posix_spawn_file_actions_adddup2(&fa, pipeRead.get(), STDIN_FILENO);
275 if (res) {
276 ALOGE("posix_spawn_file_actions_adddup2 failed (%s)", strerror(res));
Luke Huang94c43a12019-02-14 19:51:38 +0800277 return -res;
278 }
279
Luke Huang40962442019-02-26 11:46:10 +0800280 posix_spawnattr_t attr;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700281 res = posix_spawnattr_init(&attr);
Luke Huang40962442019-02-26 11:46:10 +0800282 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700283 ALOGE("posix_spawnattr_init failed (%s)", strerror(res));
284 return -res;
285 }
286 const android::base::ScopeGuard attrGuard = [&] { posix_spawnattr_destroy(&attr); };
287 res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK);
288 if (res) {
289 ALOGE("posix_spawnattr_setflags failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800290 return -res;
291 }
292
293 pid_t pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800294 res = posix_spawn(&pid, args[0], &fa, &attr, &args[0], nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800295 if (res) {
296 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800297 return -res;
298 }
Luke Huang94c43a12019-02-14 19:51:38 +0800299 mDaemonPid = pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800300 mDaemonFd = pipeWrite.release();
Luke Huang94c43a12019-02-14 19:51:38 +0800301 configureForTethering(true);
Luke Huang91bd3e12019-08-20 11:33:52 +0800302 mIsTetheringStarted = true;
Luke Huang94c43a12019-02-14 19:51:38 +0800303 applyDnsInterfaces();
304 ALOGD("Tethering services running");
305
San Mehat9d10b342010-01-18 09:51:02 -0800306 return 0;
307}
308
Luke Huangb5733d72018-08-21 17:17:19 +0800309std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
310 std::vector<char*> addrsCstrVec{};
311 addrsCstrVec.reserve(addrs.size());
312 for (const auto& addr : addrs) {
313 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
314 }
315 return addrsCstrVec;
316}
317
Luke Huang91bd3e12019-08-20 11:33:52 +0800318int TetherController::startTethering(bool usingLegacyDnsProxy,
319 const std::vector<std::string>& dhcpRanges) {
Luke Huangb5733d72018-08-21 17:17:19 +0800320 struct in_addr v4_addr;
321 for (const auto& dhcpRange : dhcpRanges) {
322 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
323 return -EINVAL;
324 }
325 }
326 auto dhcp_ranges = toCstrVec(dhcpRanges);
Luke Huang91bd3e12019-08-20 11:33:52 +0800327 return startTethering(usingLegacyDnsProxy, dhcp_ranges.size(), dhcp_ranges.data());
Luke Huangb5733d72018-08-21 17:17:19 +0800328}
329
San Mehat9d10b342010-01-18 09:51:02 -0800330int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900331 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800332
Luke Huang91bd3e12019-08-20 11:33:52 +0800333 if (!mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000334 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800335 return 0;
336 }
337
Luke Huang91bd3e12019-08-20 11:33:52 +0800338 mIsTetheringStarted = false;
339 // dnsmasq is not started
340 if (mDaemonPid == 0) {
341 return 0;
342 }
343
Steve Block7b984e32011-12-20 16:22:42 +0000344 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800345
346 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700347 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800348 mDaemonPid = 0;
349 close(mDaemonFd);
350 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900351 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000352 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800353 return 0;
354}
Matthew Xie19944102012-07-12 16:42:07 -0700355
San Mehat9d10b342010-01-18 09:51:02 -0800356bool TetherController::isTetheringStarted() {
Luke Huang91bd3e12019-08-20 11:33:52 +0800357 return mIsTetheringStarted;
San Mehat9d10b342010-01-18 09:51:02 -0800358}
359
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900360// dnsmasq can't parse commands larger than this due to the fixed-size buffer
361// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
362// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900363const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800364
Luke Huang8dc1cac2019-03-30 16:12:31 +0800365// TODO: Remove overload function and update this after NDC migration.
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700366int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700367 Fwmark fwmark;
368 fwmark.netId = netId;
369 fwmark.explicitlySelected = true;
370 fwmark.protectedFromVpn = true;
371 fwmark.permission = PERMISSION_SYSTEM;
372
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900373 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800374
Erik Kline1d065ba2016-06-08 13:24:45 +0900375 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900376 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700377 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800378
Lorenzo Colittic2841282015-11-25 22:13:57 +0900379 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700380 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900381 freeaddrinfo(res);
382 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000383 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900384 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900385 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800386 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800387 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800388
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900389 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
390 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800391 break;
392 }
393
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900394 daemonCmd += SEPARATOR;
395 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900396 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800397 }
398
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700399 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900400 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800401 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900402 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900403 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900404 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800405 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800406 }
407 }
408 return 0;
409}
410
Luke Huangb5733d72018-08-21 17:17:19 +0800411int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
Luke Huangb5733d72018-08-21 17:17:19 +0800412 auto dnsServers = toCstrVec(servers);
413 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
414}
415
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700416unsigned TetherController::getDnsNetId() {
417 return mDnsNetId;
418}
419
Erik Kline1d065ba2016-06-08 13:24:45 +0900420const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800421 return mDnsForwarders;
422}
423
Erik Kline1d065ba2016-06-08 13:24:45 +0900424bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900425 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800426 bool haveInterfaces = false;
427
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900428 for (const auto& ifname : mInterfaces) {
429 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
430 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800431 break;
432 }
433
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900434 daemonCmd += SEPARATOR;
435 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800436 haveInterfaces = true;
437 }
438
Erik Kline15079dd2018-05-18 23:10:56 +0900439 if (!haveInterfaces) {
440 mDnsmasqState.update_ifaces_cmd.clear();
441 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900442 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900443 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800444 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900445 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800446}
447
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800448int TetherController::tetherInterface(const char *interface) {
449 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700450 if (!isIfaceName(interface)) {
451 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800452 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700453 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800454
Erik Kline1d065ba2016-06-08 13:24:45 +0900455 if (!configureForIPv6Router(interface)) {
456 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800457 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900458 }
459 mInterfaces.push_back(interface);
460
461 if (!applyDnsInterfaces()) {
462 mInterfaces.pop_back();
463 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800464 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800465 } else {
466 return 0;
467 }
468}
469
San Mehat9d10b342010-01-18 09:51:02 -0800470int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800471 ALOGD("untetherInterface(%s)", interface);
472
Erik Kline1d065ba2016-06-08 13:24:45 +0900473 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
474 if (!strcmp(interface, it->c_str())) {
475 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800476
Erik Kline1d065ba2016-06-08 13:24:45 +0900477 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800478 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800479 }
480 }
481 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800482 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800483}
484
Erik Kline1d065ba2016-06-08 13:24:45 +0900485const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800486 return mInterfaces;
487}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900488
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900489int TetherController::setupIptablesHooks() {
490 int res;
491 res = setDefaults();
492 if (res < 0) {
493 return res;
494 }
495
496 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
497 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
498 // This is no longer optional and tethering will fail to start if it fails.
499 std::string mssRewriteCommand = StringPrintf(
500 "*mangle\n"
501 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
502 "COMMIT\n", LOCAL_MANGLE_FORWARD);
503
504 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
505 std::string defaultCommands = StringPrintf(
506 "*filter\n"
507 ":%s -\n"
508 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
509
510 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
511 if (res < 0) {
512 return res;
513 }
514
515 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
516 if (res < 0) {
517 return res;
518 }
519
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900520 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900521
522 return 0;
523}
524
525int TetherController::setDefaults() {
526 std::string v4Cmd = StringPrintf(
527 "*filter\n"
528 ":%s -\n"
529 "-A %s -j DROP\n"
530 "COMMIT\n"
531 "*nat\n"
532 ":%s -\n"
533 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
534
535 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900536 "*filter\n"
537 ":%s -\n"
538 "COMMIT\n"
539 "*raw\n"
540 ":%s -\n"
541 "COMMIT\n",
542 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900543
544 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
545 if (res < 0) {
546 return res;
547 }
548
549 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
550 if (res < 0) {
551 return res;
552 }
553
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900554 return 0;
555}
556
557int TetherController::enableNat(const char* intIface, const char* extIface) {
558 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
559
560 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900561 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900562 }
563
564 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
565 if (!strcmp(intIface, extIface)) {
566 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900567 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900568 }
569
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900570 if (isForwardingPairEnabled(intIface, extIface)) {
571 return 0;
572 }
573
574 // add this if we are the first enabled nat for this upstream
575 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900576 std::vector<std::string> v4Cmds = {
577 "*nat",
578 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
579 "COMMIT\n"
580 };
581
Luke Huangae038f82018-11-05 11:17:31 +0900582 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
583 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900584 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900585 if (!isAnyForwardingPairEnabled()) {
586 // unwind what's been done, but don't care about success - what more could we do?
587 setDefaults();
588 }
Luke Huang19b49c52018-10-22 12:12:05 +0900589 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900590 }
591 }
592
593 if (setForwardRules(true, intIface, extIface) != 0) {
594 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900595 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900596 setDefaults();
597 }
Luke Huang19b49c52018-10-22 12:12:05 +0900598 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900599 }
600
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900601 return 0;
602}
603
Luke Huangae038f82018-11-05 11:17:31 +0900604int TetherController::setTetherGlobalAlertRule() {
605 // Only add this if we are the first enabled nat
606 if (isAnyForwardingPairEnabled()) {
607 return 0;
608 }
609 const std::string cmds =
610 "*filter\n" +
611 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
612 "COMMIT\n";
613
614 return iptablesRestoreFunction(V4V6, cmds, nullptr);
615}
616
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900617int TetherController::setupIPv6CountersChain() {
618 // Only add this if we are the first enabled nat
619 if (isAnyForwardingPairEnabled()) {
620 return 0;
621 }
622
623 /*
624 * IPv6 tethering doesn't need the state-based conntrack rules, so
625 * it unconditionally jumps to the tether counters chain all the time.
626 */
Luke Huangae038f82018-11-05 11:17:31 +0900627 const std::string v6Cmds =
628 "*filter\n" +
629 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900630
Luke Huangae038f82018-11-05 11:17:31 +0900631 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900632}
633
634// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
635TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
636 const std::string& intIface, const std::string& extIface) {
637 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
638 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
639 if (it->second.iface == intIface) {
640 return &(it->second);
641 }
642 }
643 return nullptr;
644}
645
646void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
647 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
648 if (existingEntry != nullptr) {
649 existingEntry->active = true;
650 return;
651 }
652
653 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
654 .iface = intIface,
655 .active = true
656 }));
657}
658
659void TetherController::markForwardingPairDisabled(
660 const std::string& intIface, const std::string& extIface) {
661 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
662 if (existingEntry == nullptr) {
663 return;
664 }
665
666 existingEntry->active = false;
667}
668
669bool TetherController::isForwardingPairEnabled(
670 const std::string& intIface, const std::string& extIface) {
671 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
672 return existingEntry != nullptr && existingEntry->active;
673}
674
675bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
676 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
677 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
678 if (it->second.active) {
679 return true;
680 }
681 }
682 return false;
683}
684
685bool TetherController::isAnyForwardingPairEnabled() {
686 for (auto& it : mFwdIfaces) {
687 if (it.second.active) {
688 return true;
689 }
690 }
691 return false;
692}
693
694bool TetherController::tetherCountingRuleExists(
695 const std::string& iface1, const std::string& iface2) {
696 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
697 // is in the map regardless of its active status. Rules are added both ways so we check with
698 // the 2 combinations.
699 return findForwardingDownstream(iface1, iface2) != nullptr
700 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900701}
702
703/* static */
704std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
705 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
706}
707
708int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
709 const char *op = add ? "-A" : "-D";
710
711 std::string rpfilterCmd = StringPrintf(
712 "*raw\n"
713 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
714 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
715 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900716 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900717 }
718
719 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900720 "*raw",
721 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
722 LOCAL_RAW_PREROUTING, intIface),
723 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
724 LOCAL_RAW_PREROUTING, intIface),
725 "COMMIT",
726 "*filter",
727 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
728 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
729 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
730 intIface, extIface),
731 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
732 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900733 };
734
735 std::vector<std::string> v6 = {
736 "*filter",
737 };
738
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900739 // We only ever add tethering quota rules so that they stick.
740 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900741 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900742 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900743 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900744 v6.push_back(makeTetherCountingRule(extIface, intIface));
745 }
746
747 // Always make sure the drop rule is at the end.
748 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900749 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900750 if (add) {
751 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
752 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
753 }
754
755 v4.push_back("COMMIT\n");
756 v6.push_back("COMMIT\n");
757
758 // We only add IPv6 rules here, never remove them.
759 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
760 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
761 // unwind what's been done, but don't care about success - what more could we do?
762 if (add) {
763 setForwardRules(false, intIface, extIface);
764 }
Luke Huang19b49c52018-10-22 12:12:05 +0900765 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900766 }
767
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900768 if (add) {
769 addForwardingPair(intIface, extIface);
770 } else {
771 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900772 }
773
774 return 0;
775}
776
777int TetherController::disableNat(const char* intIface, const char* extIface) {
778 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900779 errno = ENODEV;
780 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900781 }
782
783 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900784 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900785 setDefaults();
786 }
787 return 0;
788}
789
790void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
791 for (TetherStats& existing : statsList) {
792 if (existing.addStatsIfMatch(stats)) {
793 return;
794 }
795 }
796 // No match. Insert a new interface pair.
797 statsList.push_back(stats);
798}
799
800/*
801 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900802 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900803 * pkts bytes target prot opt in out source destination
804 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
805 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
806 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
807 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
808 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900809 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900810 * pkts bytes target prot opt in out source destination
811 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
812 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
813 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900814 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900815int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900816 const std::string& statsOutput,
817 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800818 enum IndexOfIptChain {
819 ORIG_LINE,
820 PACKET_COUNTS,
821 BYTE_COUNTS,
822 HYPHEN,
823 IFACE0_NAME,
824 IFACE1_NAME,
825 SOURCE,
826 DESTINATION
827 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900828 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900829 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900830
waynema71a0b592018-11-21 13:31:34 +0800831 static const std::string NUM = "(\\d+)";
832 static const std::string IFACE = "([^\\s]+)";
833 static const std::string DST = "(0.0.0.0/0|::/0)";
834 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
835 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
836 "\\s+" + DST + "\\s+" + DST;
837 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900838
waynema71a0b592018-11-21 13:31:34 +0800839 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
840 int headerLine = 0;
841 for (const std::string& line : lines) {
842 // Skip headers.
843 if (headerLine < 2) {
844 if (line.empty()) {
845 ALOGV("Empty header while parsing tethering stats");
846 return -EREMOTEIO;
847 }
848 headerLine++;
849 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900850 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900851
waynema71a0b592018-11-21 13:31:34 +0800852 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900853
waynema71a0b592018-11-21 13:31:34 +0800854 extraProcessingInfo = line;
855 std::smatch matches;
856 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
857 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
858 // IPv4 has "--" indicating what to do with fragments...
859 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
860 // ... but IPv6 does not.
861 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
862 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
863 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
864 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
865 std::string iface0 = matches[IFACE0_NAME].str();
866 std::string iface1 = matches[IFACE1_NAME].str();
867 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900868
waynema71a0b592018-11-21 13:31:34 +0800869 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
870 " rest=<%s> orig line=<%s>",
871 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900872 /*
873 * The following assumes that the 1st rule has in:extIface out:intIface,
874 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900875 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900876 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900877 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800878 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
879 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900880 stats.intIface = iface0;
881 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900882 stats.txPackets = packets;
883 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900884 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800885 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
886 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900887 stats.rxPackets = packets;
888 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900889 }
890 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900891 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900892 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900893 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900894 }
895 }
896
897 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900898 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900899 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900900 }
901 return 0;
902}
903
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900904StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900905 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900906 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900907
908 for (const IptablesTarget target : {V4, V6}) {
909 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900910 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900911 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
912 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900913 }
914
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900915 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900916 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
917 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900918 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900919 }
920 }
921
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900922 return statsList;
923}
924
Lorenzo Colitti52db3912020-02-17 23:59:45 +0900925void TetherController::dumpIfaces(DumpWriter& dw) {
926 dw.println("Interface pairs:");
927
928 ScopedIndent ifaceIndent(dw);
929 for (const auto& it : mFwdIfaces) {
930 dw.println("%s -> %s %s", it.first.c_str(), it.second.iface.c_str(),
931 (it.second.active ? "ACTIVE" : "DISABLED"));
932 }
933}
934
935void TetherController::dump(DumpWriter& dw) {
936 std::lock_guard guard(lock);
937
938 ScopedIndent tetherControllerIndent(dw);
939 dw.println("TetherController");
940 dw.incIndent();
941
942 dw.println("Forwarding requests: " + Join(mForwardingRequests, ' '));
943 if (mDnsNetId != 0) {
944 dw.println(StringPrintf("DNS: netId %d servers [%s]", mDnsNetId,
945 Join(mDnsForwarders, ", ").c_str()));
946 }
947 if (mDaemonPid != 0) {
948 dw.println("dnsmasq PID: %d", mDaemonPid);
949 }
950
951 dumpIfaces(dw);
952}
953
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900954} // namespace net
955} // namespace android