blob: a62d7746767a4af3bed6ad3ee0d6cea82f50fb71 [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>
Hungming Chen1da90082020-02-14 20:24:16 +080045#include <net/if.h>
Lorenzo Colitti52db3912020-02-17 23:59:45 +090046#include <netdutils/DumpWriter.h>
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090047#include <netdutils/StatusOr.h>
San Mehat9d10b342010-01-18 09:51:02 -080048
Erik Klineb31fd692018-06-06 20:50:11 +090049#include "Controllers.h"
Lorenzo Colitti667c4772014-08-26 14:13:07 -070050#include "Fwmark.h"
Erik Kline1d065ba2016-06-08 13:24:45 +090051#include "InterfaceController.h"
Mike Yuf0e019f2019-03-13 14:43:39 +080052#include "NetdConstants.h"
Lorenzo Colittie20a5262017-05-09 18:30:44 +090053#include "NetworkController.h"
Hungming Chen1da90082020-02-14 20:24:16 +080054#include "OffloadUtils.h"
Mike Yuf0e019f2019-03-13 14:43:39 +080055#include "Permission.h"
San Mehat9d10b342010-01-18 09:51:02 -080056#include "TetherController.h"
57
Bernie Innocenti4debf3b2018-09-12 13:54:50 +090058namespace android {
59namespace net {
60
Lorenzo Colittia93126d2017-08-24 13:28:19 +090061using android::base::Join;
George Burgess IVe3dc1312019-02-28 11:27:04 -080062using android::base::Pipe;
Erik Klineb31fd692018-06-06 20:50:11 +090063using android::base::StringPrintf;
George Burgess IVe3dc1312019-02-28 11:27:04 -080064using android::base::unique_fd;
Lorenzo Colitti52db3912020-02-17 23:59:45 +090065using android::netdutils::DumpWriter;
66using android::netdutils::ScopedIndent;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090067using android::netdutils::statusFromErrno;
Erik Klineb31fd692018-06-06 20:50:11 +090068using android::netdutils::StatusOr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090069
Lorenzo Colitti799625c2015-02-25 12:52:00 +090070namespace {
71
Erik Kline1d065ba2016-06-08 13:24:45 +090072const char BP_TOOLS_MODE[] = "bp-tools";
73const char IPV4_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv4/ip_forward";
74const char IPV6_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv6/conf/all/forwarding";
75const char SEPARATOR[] = "|";
Erik Kline93f9b222017-10-22 21:24:58 +090076constexpr const char kTcpBeLiberal[] = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
Lorenzo Colitti799625c2015-02-25 12:52:00 +090077
Erik Kline5f0358b2018-02-16 15:08:09 +090078// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
79constexpr const char kDnsmasqUsername[] = "dns_tether";
80
Lorenzo Colitti799625c2015-02-25 12:52:00 +090081bool writeToFile(const char* filename, const char* value) {
Nick Kralevichb95c60c2016-11-19 09:09:16 -080082 int fd = open(filename, O_WRONLY | O_CLOEXEC);
Nicolas Geoffrayafd40372015-03-16 11:58:06 +000083 if (fd < 0) {
84 ALOGE("Failed to open %s: %s", filename, strerror(errno));
85 return false;
86 }
87
88 const ssize_t len = strlen(value);
89 if (write(fd, value, len) != len) {
90 ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
91 close(fd);
92 return false;
93 }
94 close(fd);
95 return true;
Lorenzo Colitti799625c2015-02-25 12:52:00 +090096}
97
Erik Kline93f9b222017-10-22 21:24:58 +090098// TODO: Consider altering TCP and UDP timeouts as well.
99void configureForTethering(bool enabled) {
100 writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
101}
102
Erik Kline1d065ba2016-06-08 13:24:45 +0900103bool configureForIPv6Router(const char *interface) {
104 return (InterfaceController::setEnableIPv6(interface, 0) == 0)
105 && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
Erik Kline6cddf512016-08-09 15:28:42 +0900106 && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
107 && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
Erik Kline1d065ba2016-06-08 13:24:45 +0900108 && (InterfaceController::setEnableIPv6(interface, 1) == 0);
109}
110
111void configureForIPv6Client(const char *interface) {
112 InterfaceController::setAcceptIPv6Ra(interface, 1);
Erik Kline6cddf512016-08-09 15:28:42 +0900113 InterfaceController::setAcceptIPv6Dad(interface, 1);
114 InterfaceController::setIPv6DadTransmits(interface, "1");
Erik Kline1d065ba2016-06-08 13:24:45 +0900115 InterfaceController::setEnableIPv6(interface, 0);
116}
117
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900118bool inBpToolsMode() {
119 // In BP tools mode, do not disable IP forwarding
120 char bootmode[PROPERTY_VALUE_MAX] = {0};
121 property_get("ro.bootmode", bootmode, "unknown");
122 return !strcmp(BP_TOOLS_MODE, bootmode);
123}
124
125} // namespace
126
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900127auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
128
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900129const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
130 "*filter\n"
131 "-nvx -L %s\n"
132 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
133
Erik Kline15079dd2018-05-18 23:10:56 +0900134int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
135 if (cmd.empty()) return 0;
136
Erik Klineb31fd692018-06-06 20:50:11 +0900137 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900138 // Send the trailing \0 as well.
139 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900140 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900141 errno = EREMOTEIO;
142 return -1;
143 }
144 return 0;
145}
146
147void TetherController::DnsmasqState::clear() {
148 update_ifaces_cmd.clear();
149 update_dns_cmd.clear();
150}
151
152int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
153 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
154}
155
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700156TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900157 if (inBpToolsMode()) {
158 enableForwarding(BP_TOOLS_MODE);
159 } else {
160 setIpFwdEnabled();
161 }
San Mehat9d10b342010-01-18 09:51:02 -0800162}
163
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900164bool TetherController::setIpFwdEnabled() {
165 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900166 bool disable = mForwardingRequests.empty();
167 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900168 ALOGD("Setting IP forward enable = %s", value);
169 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
170 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900171 if (disable) {
172 // Turning off the forwarding sysconf in the kernel has the side effect
173 // of turning on ICMP redirect, which is a security hazard.
174 // Turn ICMP redirect back off immediately.
175 int rv = InterfaceController::disableIcmpRedirects();
176 success &= (rv == 0);
177 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900178 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800179}
180
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900181bool TetherController::enableForwarding(const char* requester) {
182 // Don't return an error if this requester already requested forwarding. Only return errors for
183 // things that the caller caller needs to care about, such as "couldn't write to the file to
184 // enable forwarding".
185 mForwardingRequests.insert(requester);
186 return setIpFwdEnabled();
187}
San Mehat9d10b342010-01-18 09:51:02 -0800188
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900189bool TetherController::disableForwarding(const char* requester) {
190 mForwardingRequests.erase(requester);
191 return setIpFwdEnabled();
192}
San Mehat9d10b342010-01-18 09:51:02 -0800193
Luke Huang728cf4c2019-03-14 19:43:02 +0800194const std::set<std::string>& TetherController::getIpfwdRequesterList() const {
195 return mForwardingRequests;
San Mehat9d10b342010-01-18 09:51:02 -0800196}
197
Luke Huang91bd3e12019-08-20 11:33:52 +0800198int TetherController::startTethering(bool usingLegacyDnsProxy, int num_addrs, char** dhcp_ranges) {
199 if (!usingLegacyDnsProxy && num_addrs == 0) {
200 // Both DHCP and DnsProxy are disabled, we don't need to start dnsmasq
201 configureForTethering(true);
202 mIsTetheringStarted = true;
203 return 0;
204 }
205
206 if (mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000207 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800208 errno = EBUSY;
Luke Huangb5733d72018-08-21 17:17:19 +0800209 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800210 }
211
Steve Block7b984e32011-12-20 16:22:42 +0000212 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800213
George Burgess IVe3dc1312019-02-28 11:27:04 -0800214 unique_fd pipeRead, pipeWrite;
215 if (!Pipe(&pipeRead, &pipeWrite, O_CLOEXEC)) {
Luke Huangb5733d72018-08-21 17:17:19 +0800216 int res = errno;
Luke Huang94c43a12019-02-14 19:51:38 +0800217 ALOGE("pipe2() failed (%s)", strerror(errno));
Luke Huangb5733d72018-08-21 17:17:19 +0800218 return -res;
San Mehat9d10b342010-01-18 09:51:02 -0800219 }
220
Luke Huang94c43a12019-02-14 19:51:38 +0800221 // Set parameters
222 Fwmark fwmark;
223 fwmark.netId = NetworkController::LOCAL_NET_ID;
224 fwmark.explicitlySelected = true;
225 fwmark.protectedFromVpn = true;
226 fwmark.permission = PERMISSION_SYSTEM;
227 char markStr[UINT32_HEX_STRLEN];
228 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800229
Luke Huang94c43a12019-02-14 19:51:38 +0800230 std::vector<const std::string> argVector = {
Erik Kline5f0358b2018-02-16 15:08:09 +0900231 "/system/bin/dnsmasq",
232 "--keep-in-foreground",
233 "--no-resolv",
234 "--no-poll",
235 "--dhcp-authoritative",
236 // TODO: pipe through metered status from ConnService
237 "--dhcp-option-force=43,ANDROID_METERED",
238 "--pid-file",
Luke Huang94c43a12019-02-14 19:51:38 +0800239 "--listen-mark",
240 markStr,
241 "--user",
242 kDnsmasqUsername,
243 };
San Mehat9d10b342010-01-18 09:51:02 -0800244
Luke Huang91bd3e12019-08-20 11:33:52 +0800245 if (!usingLegacyDnsProxy) {
246 argVector.push_back("--port=0");
247 }
248
249 // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is passed.
Luke Huang94c43a12019-02-14 19:51:38 +0800250 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
251 argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
252 dhcp_ranges[addrIndex + 1]));
San Mehat9d10b342010-01-18 09:51:02 -0800253 }
254
George Burgess IVe3dc1312019-02-28 11:27:04 -0800255 std::vector<char*> args(argVector.size() + 1);
Luke Huang94c43a12019-02-14 19:51:38 +0800256 for (unsigned i = 0; i < argVector.size(); i++) {
257 args[i] = (char*)argVector[i].c_str();
258 }
259
260 /*
261 * TODO: Create a monitoring thread to handle and restart
262 * the daemon if it exits prematurely
263 */
Luke Huang40962442019-02-26 11:46:10 +0800264
265 // Note that don't modify any memory between vfork and execv.
266 // Changing state of file descriptors would be fine. See posix_spawn_file_actions_add*
267 // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
268 // duplicated fd.
269 posix_spawn_file_actions_t fa;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700270 int res = posix_spawn_file_actions_init(&fa);
Luke Huang40962442019-02-26 11:46:10 +0800271 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700272 ALOGE("posix_spawn_file_actions_init failed (%s)", strerror(res));
273 return -res;
274 }
275 const android::base::ScopeGuard faGuard = [&] { posix_spawn_file_actions_destroy(&fa); };
276 res = posix_spawn_file_actions_adddup2(&fa, pipeRead.get(), STDIN_FILENO);
277 if (res) {
278 ALOGE("posix_spawn_file_actions_adddup2 failed (%s)", strerror(res));
Luke Huang94c43a12019-02-14 19:51:38 +0800279 return -res;
280 }
281
Luke Huang40962442019-02-26 11:46:10 +0800282 posix_spawnattr_t attr;
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700283 res = posix_spawnattr_init(&attr);
Luke Huang40962442019-02-26 11:46:10 +0800284 if (res) {
Maciej Żenczykowski2cffd942019-05-05 13:40:35 -0700285 ALOGE("posix_spawnattr_init failed (%s)", strerror(res));
286 return -res;
287 }
288 const android::base::ScopeGuard attrGuard = [&] { posix_spawnattr_destroy(&attr); };
289 res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK);
290 if (res) {
291 ALOGE("posix_spawnattr_setflags failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800292 return -res;
293 }
294
295 pid_t pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800296 res = posix_spawn(&pid, args[0], &fa, &attr, &args[0], nullptr);
Luke Huang40962442019-02-26 11:46:10 +0800297 if (res) {
298 ALOGE("posix_spawn failed (%s)", strerror(res));
Luke Huang40962442019-02-26 11:46:10 +0800299 return -res;
300 }
Luke Huang94c43a12019-02-14 19:51:38 +0800301 mDaemonPid = pid;
George Burgess IVe3dc1312019-02-28 11:27:04 -0800302 mDaemonFd = pipeWrite.release();
Luke Huang94c43a12019-02-14 19:51:38 +0800303 configureForTethering(true);
Luke Huang91bd3e12019-08-20 11:33:52 +0800304 mIsTetheringStarted = true;
Luke Huang94c43a12019-02-14 19:51:38 +0800305 applyDnsInterfaces();
306 ALOGD("Tethering services running");
307
San Mehat9d10b342010-01-18 09:51:02 -0800308 return 0;
309}
310
Luke Huangb5733d72018-08-21 17:17:19 +0800311std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
312 std::vector<char*> addrsCstrVec{};
313 addrsCstrVec.reserve(addrs.size());
314 for (const auto& addr : addrs) {
315 addrsCstrVec.push_back(const_cast<char*>(addr.data()));
316 }
317 return addrsCstrVec;
318}
319
Luke Huang91bd3e12019-08-20 11:33:52 +0800320int TetherController::startTethering(bool usingLegacyDnsProxy,
321 const std::vector<std::string>& dhcpRanges) {
Luke Huangb5733d72018-08-21 17:17:19 +0800322 struct in_addr v4_addr;
323 for (const auto& dhcpRange : dhcpRanges) {
324 if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
325 return -EINVAL;
326 }
327 }
328 auto dhcp_ranges = toCstrVec(dhcpRanges);
Luke Huang91bd3e12019-08-20 11:33:52 +0800329 return startTethering(usingLegacyDnsProxy, dhcp_ranges.size(), dhcp_ranges.data());
Luke Huangb5733d72018-08-21 17:17:19 +0800330}
331
San Mehat9d10b342010-01-18 09:51:02 -0800332int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900333 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800334
Luke Huang91bd3e12019-08-20 11:33:52 +0800335 if (!mIsTetheringStarted) {
Steve Block5ea0c052012-01-06 19:18:11 +0000336 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800337 return 0;
338 }
339
Luke Huang91bd3e12019-08-20 11:33:52 +0800340 mIsTetheringStarted = false;
341 // dnsmasq is not started
342 if (mDaemonPid == 0) {
343 return 0;
344 }
345
Steve Block7b984e32011-12-20 16:22:42 +0000346 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800347
348 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700349 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800350 mDaemonPid = 0;
351 close(mDaemonFd);
352 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900353 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000354 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800355 return 0;
356}
Matthew Xie19944102012-07-12 16:42:07 -0700357
San Mehat9d10b342010-01-18 09:51:02 -0800358bool TetherController::isTetheringStarted() {
Luke Huang91bd3e12019-08-20 11:33:52 +0800359 return mIsTetheringStarted;
San Mehat9d10b342010-01-18 09:51:02 -0800360}
361
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900362// dnsmasq can't parse commands larger than this due to the fixed-size buffer
363// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
364// dnsmasq reads up to 1023 bytes.
Bernie Innocenti45238a12018-12-04 14:57:48 +0900365const size_t MAX_CMD_SIZE = 1023;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800366
Luke Huang8dc1cac2019-03-30 16:12:31 +0800367// TODO: Remove overload function and update this after NDC migration.
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700368int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700369 Fwmark fwmark;
370 fwmark.netId = netId;
371 fwmark.explicitlySelected = true;
372 fwmark.protectedFromVpn = true;
373 fwmark.permission = PERMISSION_SYSTEM;
374
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900375 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800376
Erik Kline1d065ba2016-06-08 13:24:45 +0900377 mDnsForwarders.clear();
Bernie Innocenti45238a12018-12-04 14:57:48 +0900378 for (int i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700379 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800380
Lorenzo Colittic2841282015-11-25 22:13:57 +0900381 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700382 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900383 freeaddrinfo(res);
384 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000385 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900386 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900387 errno = EINVAL;
Luke Huangb5733d72018-08-21 17:17:19 +0800388 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800389 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800390
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900391 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
392 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800393 break;
394 }
395
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900396 daemonCmd += SEPARATOR;
397 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900398 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800399 }
400
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700401 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900402 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800403 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900404 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900405 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900406 errno = EREMOTEIO;
Luke Huangb5733d72018-08-21 17:17:19 +0800407 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800408 }
409 }
410 return 0;
411}
412
Luke Huangb5733d72018-08-21 17:17:19 +0800413int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
Luke Huangb5733d72018-08-21 17:17:19 +0800414 auto dnsServers = toCstrVec(servers);
415 return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
416}
417
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700418unsigned TetherController::getDnsNetId() {
419 return mDnsNetId;
420}
421
Erik Kline1d065ba2016-06-08 13:24:45 +0900422const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800423 return mDnsForwarders;
424}
425
Erik Kline1d065ba2016-06-08 13:24:45 +0900426bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900427 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800428 bool haveInterfaces = false;
429
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900430 for (const auto& ifname : mInterfaces) {
431 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
432 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800433 break;
434 }
435
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900436 daemonCmd += SEPARATOR;
437 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800438 haveInterfaces = true;
439 }
440
Erik Kline15079dd2018-05-18 23:10:56 +0900441 if (!haveInterfaces) {
442 mDnsmasqState.update_ifaces_cmd.clear();
443 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900444 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900445 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800446 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900447 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800448}
449
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800450int TetherController::tetherInterface(const char *interface) {
451 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700452 if (!isIfaceName(interface)) {
453 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800454 return -errno;
JP Abgrall69261cb2014-06-19 18:35:24 -0700455 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800456
Erik Kline1d065ba2016-06-08 13:24:45 +0900457 if (!configureForIPv6Router(interface)) {
458 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800459 return -EREMOTEIO;
Erik Kline1d065ba2016-06-08 13:24:45 +0900460 }
461 mInterfaces.push_back(interface);
462
463 if (!applyDnsInterfaces()) {
464 mInterfaces.pop_back();
465 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800466 return -EREMOTEIO;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800467 } else {
468 return 0;
469 }
470}
471
San Mehat9d10b342010-01-18 09:51:02 -0800472int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800473 ALOGD("untetherInterface(%s)", interface);
474
Erik Kline1d065ba2016-06-08 13:24:45 +0900475 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
476 if (!strcmp(interface, it->c_str())) {
477 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800478
Erik Kline1d065ba2016-06-08 13:24:45 +0900479 configureForIPv6Client(interface);
Luke Huangb5733d72018-08-21 17:17:19 +0800480 return applyDnsInterfaces() ? 0 : -EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800481 }
482 }
483 errno = ENOENT;
Luke Huangb5733d72018-08-21 17:17:19 +0800484 return -errno;
San Mehat9d10b342010-01-18 09:51:02 -0800485}
486
Erik Kline1d065ba2016-06-08 13:24:45 +0900487const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800488 return mInterfaces;
489}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900490
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900491int TetherController::setupIptablesHooks() {
492 int res;
493 res = setDefaults();
494 if (res < 0) {
495 return res;
496 }
497
498 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
499 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
500 // This is no longer optional and tethering will fail to start if it fails.
501 std::string mssRewriteCommand = StringPrintf(
502 "*mangle\n"
503 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
504 "COMMIT\n", LOCAL_MANGLE_FORWARD);
505
506 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
507 std::string defaultCommands = StringPrintf(
508 "*filter\n"
509 ":%s -\n"
510 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
511
512 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
513 if (res < 0) {
514 return res;
515 }
516
517 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
518 if (res < 0) {
519 return res;
520 }
521
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900522 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900523
524 return 0;
525}
526
527int TetherController::setDefaults() {
528 std::string v4Cmd = StringPrintf(
529 "*filter\n"
530 ":%s -\n"
531 "-A %s -j DROP\n"
532 "COMMIT\n"
533 "*nat\n"
534 ":%s -\n"
535 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
536
537 std::string v6Cmd = StringPrintf(
Luke Huangae038f82018-11-05 11:17:31 +0900538 "*filter\n"
539 ":%s -\n"
540 "COMMIT\n"
541 "*raw\n"
542 ":%s -\n"
543 "COMMIT\n",
544 LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900545
546 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
547 if (res < 0) {
548 return res;
549 }
550
551 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
552 if (res < 0) {
553 return res;
554 }
555
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900556 return 0;
557}
558
559int TetherController::enableNat(const char* intIface, const char* extIface) {
560 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
561
562 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huang19b49c52018-10-22 12:12:05 +0900563 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900564 }
565
566 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
567 if (!strcmp(intIface, extIface)) {
568 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
Luke Huang19b49c52018-10-22 12:12:05 +0900569 return -EINVAL;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900570 }
571
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900572 if (isForwardingPairEnabled(intIface, extIface)) {
573 return 0;
574 }
575
576 // add this if we are the first enabled nat for this upstream
577 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900578 std::vector<std::string> v4Cmds = {
579 "*nat",
580 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
581 "COMMIT\n"
582 };
583
Luke Huangae038f82018-11-05 11:17:31 +0900584 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
585 setTetherGlobalAlertRule()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900586 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900587 if (!isAnyForwardingPairEnabled()) {
588 // unwind what's been done, but don't care about success - what more could we do?
589 setDefaults();
590 }
Luke Huang19b49c52018-10-22 12:12:05 +0900591 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900592 }
593 }
594
595 if (setForwardRules(true, intIface, extIface) != 0) {
596 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900597 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900598 setDefaults();
599 }
Luke Huang19b49c52018-10-22 12:12:05 +0900600 return -ENODEV;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900601 }
602
Hungming Chen1da90082020-02-14 20:24:16 +0800603 maybeStartBpf(extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900604 return 0;
605}
606
Luke Huangae038f82018-11-05 11:17:31 +0900607int TetherController::setTetherGlobalAlertRule() {
608 // Only add this if we are the first enabled nat
609 if (isAnyForwardingPairEnabled()) {
610 return 0;
611 }
612 const std::string cmds =
613 "*filter\n" +
614 StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
615 "COMMIT\n";
616
617 return iptablesRestoreFunction(V4V6, cmds, nullptr);
618}
619
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900620int TetherController::setupIPv6CountersChain() {
621 // Only add this if we are the first enabled nat
622 if (isAnyForwardingPairEnabled()) {
623 return 0;
624 }
625
626 /*
627 * IPv6 tethering doesn't need the state-based conntrack rules, so
628 * it unconditionally jumps to the tether counters chain all the time.
629 */
Luke Huangae038f82018-11-05 11:17:31 +0900630 const std::string v6Cmds =
631 "*filter\n" +
632 StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900633
Luke Huangae038f82018-11-05 11:17:31 +0900634 return iptablesRestoreFunction(V6, v6Cmds, nullptr);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900635}
636
637// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
638TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
639 const std::string& intIface, const std::string& extIface) {
640 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
641 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
642 if (it->second.iface == intIface) {
643 return &(it->second);
644 }
645 }
646 return nullptr;
647}
648
649void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
650 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
651 if (existingEntry != nullptr) {
652 existingEntry->active = true;
653 return;
654 }
655
656 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
657 .iface = intIface,
658 .active = true
659 }));
660}
661
662void TetherController::markForwardingPairDisabled(
663 const std::string& intIface, const std::string& extIface) {
664 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
665 if (existingEntry == nullptr) {
666 return;
667 }
668
669 existingEntry->active = false;
670}
671
672bool TetherController::isForwardingPairEnabled(
673 const std::string& intIface, const std::string& extIface) {
674 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
675 return existingEntry != nullptr && existingEntry->active;
676}
677
678bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
679 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
680 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
681 if (it->second.active) {
682 return true;
683 }
684 }
685 return false;
686}
687
688bool TetherController::isAnyForwardingPairEnabled() {
689 for (auto& it : mFwdIfaces) {
690 if (it.second.active) {
691 return true;
692 }
693 }
694 return false;
695}
696
697bool TetherController::tetherCountingRuleExists(
698 const std::string& iface1, const std::string& iface2) {
699 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
700 // is in the map regardless of its active status. Rules are added both ways so we check with
701 // the 2 combinations.
702 return findForwardingDownstream(iface1, iface2) != nullptr
703 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900704}
705
706/* static */
707std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
708 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
709}
710
711int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
712 const char *op = add ? "-A" : "-D";
713
714 std::string rpfilterCmd = StringPrintf(
715 "*raw\n"
716 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
717 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
718 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
Luke Huang19b49c52018-10-22 12:12:05 +0900719 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900720 }
721
722 std::vector<std::string> v4 = {
hiroaki.yokoyama04f2cb52018-06-13 18:47:30 +0900723 "*raw",
724 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
725 LOCAL_RAW_PREROUTING, intIface),
726 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
727 LOCAL_RAW_PREROUTING, intIface),
728 "COMMIT",
729 "*filter",
730 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
731 LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
732 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
733 intIface, extIface),
734 StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
735 LOCAL_TETHER_COUNTERS_CHAIN),
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900736 };
737
738 std::vector<std::string> v6 = {
739 "*filter",
740 };
741
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900742 // We only ever add tethering quota rules so that they stick.
743 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900744 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900745 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900746 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900747 v6.push_back(makeTetherCountingRule(extIface, intIface));
748 }
749
750 // Always make sure the drop rule is at the end.
751 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900752 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900753 if (add) {
754 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
755 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
756 }
757
758 v4.push_back("COMMIT\n");
759 v6.push_back("COMMIT\n");
760
761 // We only add IPv6 rules here, never remove them.
762 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
763 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
764 // unwind what's been done, but don't care about success - what more could we do?
765 if (add) {
766 setForwardRules(false, intIface, extIface);
767 }
Luke Huang19b49c52018-10-22 12:12:05 +0900768 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900769 }
770
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900771 if (add) {
772 addForwardingPair(intIface, extIface);
773 } else {
774 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900775 }
776
777 return 0;
778}
779
780int TetherController::disableNat(const char* intIface, const char* extIface) {
781 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
Luke Huangae038f82018-11-05 11:17:31 +0900782 errno = ENODEV;
783 return -errno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900784 }
785
786 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900787 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900788 setDefaults();
789 }
Hungming Chen1da90082020-02-14 20:24:16 +0800790
791 maybeStopBpf(extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900792 return 0;
793}
794
795void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
796 for (TetherStats& existing : statsList) {
797 if (existing.addStatsIfMatch(stats)) {
798 return;
799 }
800 }
801 // No match. Insert a new interface pair.
802 statsList.push_back(stats);
803}
804
805/*
806 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900807 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900808 * pkts bytes target prot opt in out source destination
809 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
810 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
811 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
812 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
813 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900814 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900815 * pkts bytes target prot opt in out source destination
816 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
817 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
818 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900819 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900820int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900821 const std::string& statsOutput,
822 std::string &extraProcessingInfo) {
waynema71a0b592018-11-21 13:31:34 +0800823 enum IndexOfIptChain {
824 ORIG_LINE,
825 PACKET_COUNTS,
826 BYTE_COUNTS,
827 HYPHEN,
828 IFACE0_NAME,
829 IFACE1_NAME,
830 SOURCE,
831 DESTINATION
832 };
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900833 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900834 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900835
waynema71a0b592018-11-21 13:31:34 +0800836 static const std::string NUM = "(\\d+)";
837 static const std::string IFACE = "([^\\s]+)";
838 static const std::string DST = "(0.0.0.0/0|::/0)";
839 static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
840 " RETURN all( -- | )" + IFACE + "\\s+" + IFACE +
841 "\\s+" + DST + "\\s+" + DST;
842 static const std::regex IP_RE(COUNTERS);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900843
waynema71a0b592018-11-21 13:31:34 +0800844 const std::vector<std::string> lines = base::Split(statsOutput, "\n");
845 int headerLine = 0;
846 for (const std::string& line : lines) {
847 // Skip headers.
848 if (headerLine < 2) {
849 if (line.empty()) {
850 ALOGV("Empty header while parsing tethering stats");
851 return -EREMOTEIO;
852 }
853 headerLine++;
854 continue;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900855 }
Lorenzo Colitti09353392017-08-24 14:20:32 +0900856
waynema71a0b592018-11-21 13:31:34 +0800857 if (line.empty()) continue;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900858
waynema71a0b592018-11-21 13:31:34 +0800859 extraProcessingInfo = line;
860 std::smatch matches;
861 if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
862 // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
863 // IPv4 has "--" indicating what to do with fragments...
864 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
865 // ... but IPv6 does not.
866 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
867 // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
868 int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
869 int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
870 std::string iface0 = matches[IFACE0_NAME].str();
871 std::string iface1 = matches[IFACE1_NAME].str();
872 std::string rest = matches[SOURCE].str();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900873
waynema71a0b592018-11-21 13:31:34 +0800874 ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
875 " rest=<%s> orig line=<%s>",
876 iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900877 /*
878 * The following assumes that the 1st rule has in:extIface out:intIface,
879 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900880 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900881 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900882 if (!stats.intIface[0]) {
waynema71a0b592018-11-21 13:31:34 +0800883 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
884 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900885 stats.intIface = iface0;
886 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900887 stats.txPackets = packets;
888 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900889 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
waynema71a0b592018-11-21 13:31:34 +0800890 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
891 " ", iface0.c_str(), iface1.c_str(), bytes, packets);
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900892 stats.rxPackets = packets;
893 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900894 }
895 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900896 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900897 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900898 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900899 }
900 }
901
902 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900903 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900904 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900905 }
906 return 0;
907}
908
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900909StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900910 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900911 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900912
913 for (const IptablesTarget target : {V4, V6}) {
914 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900915 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900916 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
917 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900918 }
919
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900920 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900921 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
922 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900923 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900924 }
925 }
926
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900927 return statsList;
928}
929
Hungming Chen1da90082020-02-14 20:24:16 +0800930void TetherController::maybeStartBpf(const char* extIface) {
931 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
932 int ifIndex = if_nametoindex(extIface);
933 if (!ifIndex) {
934 ALOGE("Fail to get index for interface %s", extIface);
935 return;
936 }
937
938 auto isEthernet = android::net::isEthernet(extIface);
939 if (!isEthernet.ok()) {
940 ALOGE("isEthernet(%s[%d]) failure: %s", extIface, ifIndex,
941 isEthernet.error().message().c_str());
942 return;
943 }
944
945 int rv = getTetherIngressProgFd(isEthernet.value());
946 if (rv < 0) {
947 ALOGE("getTetherIngressProgFd(%d) failure: %s", isEthernet.value(), strerror(-rv));
948 return;
949 }
950 unique_fd tetherProgFd(rv);
951
952 rv = tcFilterAddDevIngressTether(ifIndex, tetherProgFd, isEthernet.value());
953 if (rv) {
954 ALOGE("tcFilterAddDevIngressTether(%d[%s], %d) failure: %s", ifIndex, extIface,
955 isEthernet.value(), strerror(-rv));
956 return;
957 }
958}
959
960void TetherController::maybeStopBpf(const char* extIface) {
961 // TODO: perhaps ignore IPv4-only interface because IPv4 traffic downstream is not supported.
962 int ifIndex = if_nametoindex(extIface);
963 if (!ifIndex) {
964 ALOGE("Fail to get index for interface %s", extIface);
965 return;
966 }
967
968 int rv = tcFilterDelDevIngressTether(ifIndex);
969 if (rv < 0) {
970 ALOGE("tcFilterDelDevIngressTether(%d[%s]) failure: %s", ifIndex, extIface, strerror(-rv));
971 }
972}
973
Lorenzo Colitti52db3912020-02-17 23:59:45 +0900974void TetherController::dumpIfaces(DumpWriter& dw) {
975 dw.println("Interface pairs:");
976
977 ScopedIndent ifaceIndent(dw);
978 for (const auto& it : mFwdIfaces) {
979 dw.println("%s -> %s %s", it.first.c_str(), it.second.iface.c_str(),
980 (it.second.active ? "ACTIVE" : "DISABLED"));
981 }
982}
983
984void TetherController::dump(DumpWriter& dw) {
985 std::lock_guard guard(lock);
986
987 ScopedIndent tetherControllerIndent(dw);
988 dw.println("TetherController");
989 dw.incIndent();
990
991 dw.println("Forwarding requests: " + Join(mForwardingRequests, ' '));
992 if (mDnsNetId != 0) {
993 dw.println(StringPrintf("DNS: netId %d servers [%s]", mDnsNetId,
994 Join(mDnsForwarders, ", ").c_str()));
995 }
996 if (mDaemonPid != 0) {
997 dw.println("dnsmasq PID: %d", mDaemonPid);
998 }
999
1000 dumpIfaces(dw);
1001}
1002
Lorenzo Colittie20a5262017-05-09 18:30:44 +09001003} // namespace net
1004} // namespace android