blob: 779426fdfc41b5e798e8db26704173cf60f70d88 [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>
Olivier Baillyff2c0d82010-11-17 11:45:07 -080021#include <string.h>
San Mehat18737842010-01-21 09:22:43 -080022
San Mehat9d10b342010-01-18 09:51:02 -080023#include <sys/socket.h>
24#include <sys/stat.h>
San Mehat18737842010-01-21 09:22:43 -080025#include <sys/types.h>
26#include <sys/wait.h>
27
San Mehat9d10b342010-01-18 09:51:02 -080028#include <netinet/in.h>
29#include <arpa/inet.h>
30
Erik Kline5f0358b2018-02-16 15:08:09 +090031#include <array>
32#include <cstdlib>
33#include <string>
34#include <vector>
35
San Mehat9d10b342010-01-18 09:51:02 -080036#define LOG_TAG "TetherController"
Lorenzo Colittia93126d2017-08-24 13:28:19 +090037#include <android-base/strings.h>
38#include <android-base/stringprintf.h>
Kazuhiro Ondo6b858eb2011-06-24 20:31:03 -050039#include <cutils/properties.h>
Logan Chien3f461482018-04-23 14:31:32 +080040#include <log/log.h>
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090041#include <netdutils/StatusOr.h>
San Mehat9d10b342010-01-18 09:51:02 -080042
Lorenzo Colitti667c4772014-08-26 14:13:07 -070043#include "Fwmark.h"
JP Abgrall69261cb2014-06-19 18:35:24 -070044#include "NetdConstants.h"
Lorenzo Colitti667c4772014-08-26 14:13:07 -070045#include "Permission.h"
Erik Kline1d065ba2016-06-08 13:24:45 +090046#include "InterfaceController.h"
Lorenzo Colittie20a5262017-05-09 18:30:44 +090047#include "NetworkController.h"
Lorenzo Colittia93126d2017-08-24 13:28:19 +090048#include "ResponseCode.h"
San Mehat9d10b342010-01-18 09:51:02 -080049#include "TetherController.h"
50
Lorenzo Colittia93126d2017-08-24 13:28:19 +090051using android::base::Join;
52using android::base::StringPrintf;
53using android::base::StringAppendF;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090054using android::netdutils::StatusOr;
55using android::netdutils::statusFromErrno;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090056
Lorenzo Colitti799625c2015-02-25 12:52:00 +090057namespace {
58
Erik Kline1d065ba2016-06-08 13:24:45 +090059const char BP_TOOLS_MODE[] = "bp-tools";
60const char IPV4_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv4/ip_forward";
61const char IPV6_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv6/conf/all/forwarding";
62const char SEPARATOR[] = "|";
Erik Kline93f9b222017-10-22 21:24:58 +090063constexpr const char kTcpBeLiberal[] = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
Lorenzo Colitti799625c2015-02-25 12:52:00 +090064
Erik Kline5f0358b2018-02-16 15:08:09 +090065// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
66constexpr const char kDnsmasqUsername[] = "dns_tether";
67
Lorenzo Colitti799625c2015-02-25 12:52:00 +090068bool writeToFile(const char* filename, const char* value) {
Nick Kralevichb95c60c2016-11-19 09:09:16 -080069 int fd = open(filename, O_WRONLY | O_CLOEXEC);
Nicolas Geoffrayafd40372015-03-16 11:58:06 +000070 if (fd < 0) {
71 ALOGE("Failed to open %s: %s", filename, strerror(errno));
72 return false;
73 }
74
75 const ssize_t len = strlen(value);
76 if (write(fd, value, len) != len) {
77 ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
78 close(fd);
79 return false;
80 }
81 close(fd);
82 return true;
Lorenzo Colitti799625c2015-02-25 12:52:00 +090083}
84
Erik Kline93f9b222017-10-22 21:24:58 +090085// TODO: Consider altering TCP and UDP timeouts as well.
86void configureForTethering(bool enabled) {
87 writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
88}
89
Erik Kline1d065ba2016-06-08 13:24:45 +090090bool configureForIPv6Router(const char *interface) {
91 return (InterfaceController::setEnableIPv6(interface, 0) == 0)
92 && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
Erik Kline6cddf512016-08-09 15:28:42 +090093 && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
94 && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
Erik Kline1d065ba2016-06-08 13:24:45 +090095 && (InterfaceController::setEnableIPv6(interface, 1) == 0);
96}
97
98void configureForIPv6Client(const char *interface) {
99 InterfaceController::setAcceptIPv6Ra(interface, 1);
Erik Kline6cddf512016-08-09 15:28:42 +0900100 InterfaceController::setAcceptIPv6Dad(interface, 1);
101 InterfaceController::setIPv6DadTransmits(interface, "1");
Erik Kline1d065ba2016-06-08 13:24:45 +0900102 InterfaceController::setEnableIPv6(interface, 0);
103}
104
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900105bool inBpToolsMode() {
106 // In BP tools mode, do not disable IP forwarding
107 char bootmode[PROPERTY_VALUE_MAX] = {0};
108 property_get("ro.bootmode", bootmode, "unknown");
109 return !strcmp(BP_TOOLS_MODE, bootmode);
110}
111
112} // namespace
113
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900114namespace android {
115namespace net {
116
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900117auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
118
119const int MAX_IPT_OUTPUT_LINE_LEN = 256;
120
121const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
122 "*filter\n"
123 "-nvx -L %s\n"
124 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
125
Erik Kline15079dd2018-05-18 23:10:56 +0900126int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
127 if (cmd.empty()) return 0;
128
129 ALOGD("Sending update msg to dnsmasq [%s]", cmd.c_str());
130 // Send the trailing \0 as well.
131 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
132 ALOGE("Failed to send update command to dnsmasq (%s)", strerror(errno));
133 errno = EREMOTEIO;
134 return -1;
135 }
136 return 0;
137}
138
139void TetherController::DnsmasqState::clear() {
140 update_ifaces_cmd.clear();
141 update_dns_cmd.clear();
142}
143
144int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
145 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
146}
147
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700148TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900149 if (inBpToolsMode()) {
150 enableForwarding(BP_TOOLS_MODE);
151 } else {
152 setIpFwdEnabled();
153 }
San Mehat9d10b342010-01-18 09:51:02 -0800154}
155
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900156bool TetherController::setIpFwdEnabled() {
157 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900158 bool disable = mForwardingRequests.empty();
159 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900160 ALOGD("Setting IP forward enable = %s", value);
161 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
162 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900163 if (disable) {
164 // Turning off the forwarding sysconf in the kernel has the side effect
165 // of turning on ICMP redirect, which is a security hazard.
166 // Turn ICMP redirect back off immediately.
167 int rv = InterfaceController::disableIcmpRedirects();
168 success &= (rv == 0);
169 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900170 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800171}
172
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900173bool TetherController::enableForwarding(const char* requester) {
174 // Don't return an error if this requester already requested forwarding. Only return errors for
175 // things that the caller caller needs to care about, such as "couldn't write to the file to
176 // enable forwarding".
177 mForwardingRequests.insert(requester);
178 return setIpFwdEnabled();
179}
San Mehat9d10b342010-01-18 09:51:02 -0800180
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900181bool TetherController::disableForwarding(const char* requester) {
182 mForwardingRequests.erase(requester);
183 return setIpFwdEnabled();
184}
San Mehat9d10b342010-01-18 09:51:02 -0800185
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900186size_t TetherController::forwardingRequestCount() {
187 return mForwardingRequests.size();
San Mehat9d10b342010-01-18 09:51:02 -0800188}
189
Erik Kline13fa01f2015-11-12 17:49:23 +0900190int TetherController::startTethering(int num_addrs, char **dhcp_ranges) {
San Mehat9d10b342010-01-18 09:51:02 -0800191 if (mDaemonPid != 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000192 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800193 errno = EBUSY;
194 return -1;
195 }
196
Steve Block7b984e32011-12-20 16:22:42 +0000197 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800198
199 pid_t pid;
200 int pipefd[2];
201
202 if (pipe(pipefd) < 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000203 ALOGE("pipe failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800204 return -1;
205 }
206
207 /*
208 * TODO: Create a monitoring thread to handle and restart
209 * the daemon if it exits prematurely
210 */
211 if ((pid = fork()) < 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000212 ALOGE("fork failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800213 close(pipefd[0]);
214 close(pipefd[1]);
215 return -1;
216 }
217
218 if (!pid) {
219 close(pipefd[1]);
220 if (pipefd[0] != STDIN_FILENO) {
221 if (dup2(pipefd[0], STDIN_FILENO) != STDIN_FILENO) {
Steve Block5ea0c052012-01-06 19:18:11 +0000222 ALOGE("dup2 failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800223 return -1;
224 }
225 close(pipefd[0]);
226 }
San Mehat9d10b342010-01-18 09:51:02 -0800227
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900228 Fwmark fwmark;
229 fwmark.netId = NetworkController::LOCAL_NET_ID;
230 fwmark.explicitlySelected = true;
231 fwmark.protectedFromVpn = true;
232 fwmark.permission = PERMISSION_SYSTEM;
233 char markStr[UINT32_HEX_STRLEN];
234 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
235
Erik Kline5f0358b2018-02-16 15:08:09 +0900236 std::vector<const std::string> argVector = {
237 "/system/bin/dnsmasq",
238 "--keep-in-foreground",
239 "--no-resolv",
240 "--no-poll",
241 "--dhcp-authoritative",
242 // TODO: pipe through metered status from ConnService
243 "--dhcp-option-force=43,ANDROID_METERED",
244 "--pid-file",
245 "--listen-mark", markStr,
246 "--user", kDnsmasqUsername,
247 };
San Mehat9d10b342010-01-18 09:51:02 -0800248
Erik Kline13fa01f2015-11-12 17:49:23 +0900249 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
Erik Kline5f0358b2018-02-16 15:08:09 +0900250 argVector.push_back(
251 StringPrintf("--dhcp-range=%s,%s,1h",
252 dhcp_ranges[addrIndex], dhcp_ranges[addrIndex+1]));
253 }
254
255 auto args = (char**)std::calloc(argVector.size() + 1, sizeof(char*));
256 for (unsigned i = 0; i < argVector.size(); i++) {
257 args[i] = (char*)argVector[i].c_str();
Robert Greenwalt3208ea02010-03-24 16:32:55 -0700258 }
259
260 if (execv(args[0], args)) {
Erik Kline5f0358b2018-02-16 15:08:09 +0900261 ALOGE("execv failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800262 }
Steve Block5ea0c052012-01-06 19:18:11 +0000263 ALOGE("Should never get here!");
JP Abgrallce4f3792012-08-06 13:44:44 -0700264 _exit(-1);
San Mehat9d10b342010-01-18 09:51:02 -0800265 } else {
266 close(pipefd[0]);
267 mDaemonPid = pid;
268 mDaemonFd = pipefd[1];
Erik Kline93f9b222017-10-22 21:24:58 +0900269 configureForTethering(true);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800270 applyDnsInterfaces();
Steve Block7b984e32011-12-20 16:22:42 +0000271 ALOGD("Tethering services running");
San Mehat9d10b342010-01-18 09:51:02 -0800272 }
273
274 return 0;
275}
276
277int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900278 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800279
280 if (mDaemonPid == 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000281 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800282 return 0;
283 }
284
Steve Block7b984e32011-12-20 16:22:42 +0000285 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800286
287 kill(mDaemonPid, SIGTERM);
San Mehat18737842010-01-21 09:22:43 -0800288 waitpid(mDaemonPid, NULL, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800289 mDaemonPid = 0;
290 close(mDaemonFd);
291 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900292 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000293 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800294 return 0;
295}
Matthew Xie19944102012-07-12 16:42:07 -0700296
San Mehat9d10b342010-01-18 09:51:02 -0800297bool TetherController::isTetheringStarted() {
298 return (mDaemonPid == 0 ? false : true);
299}
300
Kenny Rootcf52faf2010-02-18 09:59:55 -0800301#define MAX_CMD_SIZE 1024
302
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700303int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
San Mehat9d10b342010-01-18 09:51:02 -0800304 int i;
Erik Kline15079dd2018-05-18 23:10:56 +0900305 char daemonCmd[MAX_CMD_SIZE] = {};
San Mehat9d10b342010-01-18 09:51:02 -0800306
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700307 Fwmark fwmark;
308 fwmark.netId = netId;
309 fwmark.explicitlySelected = true;
310 fwmark.protectedFromVpn = true;
311 fwmark.permission = PERMISSION_SYSTEM;
312
Erik Kline13fa01f2015-11-12 17:49:23 +0900313 snprintf(daemonCmd, sizeof(daemonCmd), "update_dns%s0x%x", SEPARATOR, fwmark.intValue);
Kenny Rootcf52faf2010-02-18 09:59:55 -0800314 int cmdLen = strlen(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800315
Erik Kline1d065ba2016-06-08 13:24:45 +0900316 mDnsForwarders.clear();
San Mehat9d10b342010-01-18 09:51:02 -0800317 for (i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700318 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800319
Lorenzo Colittic2841282015-11-25 22:13:57 +0900320 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
321 int ret = getaddrinfo(servers[i], NULL, &hints, &res);
322 freeaddrinfo(res);
323 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000324 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900325 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900326 errno = EINVAL;
San Mehat9d10b342010-01-18 09:51:02 -0800327 return -1;
328 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800329
Nick Kralevichad5b41f2012-07-19 18:48:05 -0700330 cmdLen += (strlen(servers[i]) + 1);
331 if (cmdLen + 1 >= MAX_CMD_SIZE) {
Steve Block7b984e32011-12-20 16:22:42 +0000332 ALOGD("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800333 break;
334 }
335
Erik Kline13fa01f2015-11-12 17:49:23 +0900336 strcat(daemonCmd, SEPARATOR);
San Mehat9d10b342010-01-18 09:51:02 -0800337 strcat(daemonCmd, servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900338 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800339 }
340
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700341 mDnsNetId = netId;
Erik Kline15079dd2018-05-18 23:10:56 +0900342 mDnsmasqState.update_dns_cmd = std::string(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800343 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900344 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900345 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900346 errno = EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800347 return -1;
348 }
349 }
350 return 0;
351}
352
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700353unsigned TetherController::getDnsNetId() {
354 return mDnsNetId;
355}
356
Erik Kline1d065ba2016-06-08 13:24:45 +0900357const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800358 return mDnsForwarders;
359}
360
Erik Kline1d065ba2016-06-08 13:24:45 +0900361bool TetherController::applyDnsInterfaces() {
Erik Kline15079dd2018-05-18 23:10:56 +0900362 char daemonCmd[MAX_CMD_SIZE] = {};
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800363
364 strcpy(daemonCmd, "update_ifaces");
365 int cmdLen = strlen(daemonCmd);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800366 bool haveInterfaces = false;
367
Erik Kline1d065ba2016-06-08 13:24:45 +0900368 for (const auto &ifname : mInterfaces) {
369 cmdLen += (ifname.size() + 1);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800370 if (cmdLen + 1 >= MAX_CMD_SIZE) {
371 ALOGD("Too many DNS ifaces listed");
372 break;
373 }
374
Erik Kline13fa01f2015-11-12 17:49:23 +0900375 strcat(daemonCmd, SEPARATOR);
Erik Kline1d065ba2016-06-08 13:24:45 +0900376 strcat(daemonCmd, ifname.c_str());
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800377 haveInterfaces = true;
378 }
379
Erik Kline15079dd2018-05-18 23:10:56 +0900380 if (!haveInterfaces) {
381 mDnsmasqState.update_ifaces_cmd.clear();
382 } else {
383 mDnsmasqState.update_ifaces_cmd = std::string(daemonCmd);
384 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800385 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900386 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800387}
388
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800389int TetherController::tetherInterface(const char *interface) {
390 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700391 if (!isIfaceName(interface)) {
392 errno = ENOENT;
393 return -1;
394 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800395
Erik Kline1d065ba2016-06-08 13:24:45 +0900396 if (!configureForIPv6Router(interface)) {
397 configureForIPv6Client(interface);
398 return -1;
399 }
400 mInterfaces.push_back(interface);
401
402 if (!applyDnsInterfaces()) {
403 mInterfaces.pop_back();
404 configureForIPv6Client(interface);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800405 return -1;
406 } else {
407 return 0;
408 }
409}
410
San Mehat9d10b342010-01-18 09:51:02 -0800411int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800412 ALOGD("untetherInterface(%s)", interface);
413
Erik Kline1d065ba2016-06-08 13:24:45 +0900414 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
415 if (!strcmp(interface, it->c_str())) {
416 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800417
Erik Kline1d065ba2016-06-08 13:24:45 +0900418 configureForIPv6Client(interface);
419 return applyDnsInterfaces() ? 0 : -1;
San Mehat9d10b342010-01-18 09:51:02 -0800420 }
421 }
422 errno = ENOENT;
423 return -1;
424}
425
Erik Kline1d065ba2016-06-08 13:24:45 +0900426const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800427 return mInterfaces;
428}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900429
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900430int TetherController::setupIptablesHooks() {
431 int res;
432 res = setDefaults();
433 if (res < 0) {
434 return res;
435 }
436
437 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
438 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
439 // This is no longer optional and tethering will fail to start if it fails.
440 std::string mssRewriteCommand = StringPrintf(
441 "*mangle\n"
442 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
443 "COMMIT\n", LOCAL_MANGLE_FORWARD);
444
445 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
446 std::string defaultCommands = StringPrintf(
447 "*filter\n"
448 ":%s -\n"
449 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
450
451 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
452 if (res < 0) {
453 return res;
454 }
455
456 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
457 if (res < 0) {
458 return res;
459 }
460
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900461 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900462
463 return 0;
464}
465
466int TetherController::setDefaults() {
467 std::string v4Cmd = StringPrintf(
468 "*filter\n"
469 ":%s -\n"
470 "-A %s -j DROP\n"
471 "COMMIT\n"
472 "*nat\n"
473 ":%s -\n"
474 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
475
476 std::string v6Cmd = StringPrintf(
477 "*filter\n"
478 ":%s -\n"
479 "COMMIT\n"
480 "*raw\n"
481 ":%s -\n"
482 "COMMIT\n", LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
483
484 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
485 if (res < 0) {
486 return res;
487 }
488
489 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
490 if (res < 0) {
491 return res;
492 }
493
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900494 return 0;
495}
496
497int TetherController::enableNat(const char* intIface, const char* extIface) {
498 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
499
500 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
501 errno = ENODEV;
502 return -1;
503 }
504
505 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
506 if (!strcmp(intIface, extIface)) {
507 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
508 errno = EINVAL;
509 return -1;
510 }
511
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900512 if (isForwardingPairEnabled(intIface, extIface)) {
513 return 0;
514 }
515
516 // add this if we are the first enabled nat for this upstream
517 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900518 std::vector<std::string> v4Cmds = {
519 "*nat",
520 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
521 "COMMIT\n"
522 };
523
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900524 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) ||
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900525 setupIPv6CountersChain()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900526 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900527 if (!isAnyForwardingPairEnabled()) {
528 // unwind what's been done, but don't care about success - what more could we do?
529 setDefaults();
530 }
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900531 return -1;
532 }
533 }
534
535 if (setForwardRules(true, intIface, extIface) != 0) {
536 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900537 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900538 setDefaults();
539 }
540 errno = ENODEV;
541 return -1;
542 }
543
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900544 return 0;
545}
546
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900547int TetherController::setupIPv6CountersChain() {
548 // Only add this if we are the first enabled nat
549 if (isAnyForwardingPairEnabled()) {
550 return 0;
551 }
552
553 /*
554 * IPv6 tethering doesn't need the state-based conntrack rules, so
555 * it unconditionally jumps to the tether counters chain all the time.
556 */
557 std::vector<std::string> v6Cmds = {
558 "*filter",
559 StringPrintf("-A %s -g %s", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN),
560 "COMMIT\n"
561 };
562
563 return iptablesRestoreFunction(V6, Join(v6Cmds, '\n'), nullptr);
564}
565
566// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
567TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
568 const std::string& intIface, const std::string& extIface) {
569 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
570 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
571 if (it->second.iface == intIface) {
572 return &(it->second);
573 }
574 }
575 return nullptr;
576}
577
578void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
579 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
580 if (existingEntry != nullptr) {
581 existingEntry->active = true;
582 return;
583 }
584
585 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
586 .iface = intIface,
587 .active = true
588 }));
589}
590
591void TetherController::markForwardingPairDisabled(
592 const std::string& intIface, const std::string& extIface) {
593 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
594 if (existingEntry == nullptr) {
595 return;
596 }
597
598 existingEntry->active = false;
599}
600
601bool TetherController::isForwardingPairEnabled(
602 const std::string& intIface, const std::string& extIface) {
603 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
604 return existingEntry != nullptr && existingEntry->active;
605}
606
607bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
608 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
609 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
610 if (it->second.active) {
611 return true;
612 }
613 }
614 return false;
615}
616
617bool TetherController::isAnyForwardingPairEnabled() {
618 for (auto& it : mFwdIfaces) {
619 if (it.second.active) {
620 return true;
621 }
622 }
623 return false;
624}
625
626bool TetherController::tetherCountingRuleExists(
627 const std::string& iface1, const std::string& iface2) {
628 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
629 // is in the map regardless of its active status. Rules are added both ways so we check with
630 // the 2 combinations.
631 return findForwardingDownstream(iface1, iface2) != nullptr
632 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900633}
634
635/* static */
636std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
637 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
638}
639
640int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
641 const char *op = add ? "-A" : "-D";
642
643 std::string rpfilterCmd = StringPrintf(
644 "*raw\n"
645 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
646 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
647 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
648 return -1;
649 }
650
651 std::vector<std::string> v4 = {
652 "*filter",
653 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s",
654 op, LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
655 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP",
656 op, LOCAL_FORWARD, intIface, extIface),
657 StringPrintf("%s %s -i %s -o %s -g %s",
658 op, LOCAL_FORWARD, intIface, extIface, LOCAL_TETHER_COUNTERS_CHAIN),
659 };
660
661 std::vector<std::string> v6 = {
662 "*filter",
663 };
664
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900665 // We only ever add tethering quota rules so that they stick.
666 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900667 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900668 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900669 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900670 v6.push_back(makeTetherCountingRule(extIface, intIface));
671 }
672
673 // Always make sure the drop rule is at the end.
674 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900675 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900676 if (add) {
677 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
678 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
679 }
680
681 v4.push_back("COMMIT\n");
682 v6.push_back("COMMIT\n");
683
684 // We only add IPv6 rules here, never remove them.
685 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
686 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
687 // unwind what's been done, but don't care about success - what more could we do?
688 if (add) {
689 setForwardRules(false, intIface, extIface);
690 }
691 return -1;
692 }
693
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900694 if (add) {
695 addForwardingPair(intIface, extIface);
696 } else {
697 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900698 }
699
700 return 0;
701}
702
703int TetherController::disableNat(const char* intIface, const char* extIface) {
704 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
705 errno = ENODEV;
706 return -1;
707 }
708
709 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900710 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900711 setDefaults();
712 }
713 return 0;
714}
715
716void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
717 for (TetherStats& existing : statsList) {
718 if (existing.addStatsIfMatch(stats)) {
719 return;
720 }
721 }
722 // No match. Insert a new interface pair.
723 statsList.push_back(stats);
724}
725
726/*
727 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900728 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900729 * pkts bytes target prot opt in out source destination
730 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
731 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
732 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
733 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
734 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900735 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900736 * pkts bytes target prot opt in out source destination
737 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
738 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
739 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900740 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900741int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900742 const std::string& statsOutput,
743 std::string &extraProcessingInfo) {
744 int res;
745 std::string statsLine;
746 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
747 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
748 char rest[MAX_IPT_OUTPUT_LINE_LEN];
749
750 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900751 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900752 const char *buffPtr;
753 int64_t packets, bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900754
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900755 std::stringstream stream(statsOutput);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900756
757 // Skip headers.
758 for (int i = 0; i < 2; i++) {
759 std::getline(stream, statsLine, '\n');
760 extraProcessingInfo += statsLine + "\n";
761 if (statsLine.empty()) {
762 ALOGE("Empty header while parsing tethering stats");
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900763 return -EREMOTEIO;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900764 }
765 }
766
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900767 while (std::getline(stream, statsLine, '\n')) {
768 buffPtr = statsLine.c_str();
769
770 /* Clean up, so a failed parse can still print info */
771 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
772 if (strstr(buffPtr, "0.0.0.0")) {
773 // IPv4 has -- indicating what to do with fragments...
774 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
775 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
776 &packets, &bytes, iface0, iface1, rest);
777 } else {
778 // ... but IPv6 does not.
779 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
780 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all %s %s ::/%s",
781 &packets, &bytes, iface0, iface1, rest);
782 }
783 ALOGV("parse res=%d iface0=<%s> iface1=<%s> pkts=%" PRId64" bytes=%" PRId64" rest=<%s> orig line=<%s>", res,
784 iface0, iface1, packets, bytes, rest, buffPtr);
785 extraProcessingInfo += buffPtr;
786 extraProcessingInfo += "\n";
787
788 if (res != 5) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900789 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900790 }
791 /*
792 * The following assumes that the 1st rule has in:extIface out:intIface,
793 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900794 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900795 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900796 if (!stats.intIface[0]) {
797 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
798 stats.intIface = iface0;
799 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900800 stats.txPackets = packets;
801 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900802 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
803 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
804 stats.rxPackets = packets;
805 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900806 }
807 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900808 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900809 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900810 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900811 }
812 }
813
814 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900815 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900816 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900817 }
818 return 0;
819}
820
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900821StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900822 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900823 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900824
825 for (const IptablesTarget target : {V4, V6}) {
826 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900827 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900828 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
829 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900830 }
831
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900832 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900833 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
834 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900835 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900836 }
837 }
838
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900839 return statsList;
840}
841
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900842} // namespace net
843} // namespace android