blob: c80ea801d17adadefbe317e6a90404e672ac4c83 [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>
San Mehat9d10b342010-01-18 09:51:02 -080039#include <cutils/log.h>
Kazuhiro Ondo6b858eb2011-06-24 20:31:03 -050040#include <cutils/properties.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
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700126TetherController::TetherController() {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700127 mDnsNetId = 0;
San Mehat9d10b342010-01-18 09:51:02 -0800128 mDaemonFd = -1;
129 mDaemonPid = 0;
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900130 if (inBpToolsMode()) {
131 enableForwarding(BP_TOOLS_MODE);
132 } else {
133 setIpFwdEnabled();
134 }
San Mehat9d10b342010-01-18 09:51:02 -0800135}
136
137TetherController::~TetherController() {
Erik Kline1d065ba2016-06-08 13:24:45 +0900138 mInterfaces.clear();
139 mDnsForwarders.clear();
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900140 mForwardingRequests.clear();
Remi NGUYEN VAN7e6f47c2018-03-20 14:44:12 +0900141 mFwdIfaces.clear();
San Mehat9d10b342010-01-18 09:51:02 -0800142}
143
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900144bool TetherController::setIpFwdEnabled() {
145 bool success = true;
146 const char* value = mForwardingRequests.empty() ? "0" : "1";
147 ALOGD("Setting IP forward enable = %s", value);
148 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
149 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
150 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800151}
152
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900153bool TetherController::enableForwarding(const char* requester) {
154 // Don't return an error if this requester already requested forwarding. Only return errors for
155 // things that the caller caller needs to care about, such as "couldn't write to the file to
156 // enable forwarding".
157 mForwardingRequests.insert(requester);
158 return setIpFwdEnabled();
159}
San Mehat9d10b342010-01-18 09:51:02 -0800160
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900161bool TetherController::disableForwarding(const char* requester) {
162 mForwardingRequests.erase(requester);
163 return setIpFwdEnabled();
164}
San Mehat9d10b342010-01-18 09:51:02 -0800165
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900166size_t TetherController::forwardingRequestCount() {
167 return mForwardingRequests.size();
San Mehat9d10b342010-01-18 09:51:02 -0800168}
169
Erik Kline13fa01f2015-11-12 17:49:23 +0900170int TetherController::startTethering(int num_addrs, char **dhcp_ranges) {
San Mehat9d10b342010-01-18 09:51:02 -0800171 if (mDaemonPid != 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000172 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800173 errno = EBUSY;
174 return -1;
175 }
176
Steve Block7b984e32011-12-20 16:22:42 +0000177 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800178
179 pid_t pid;
180 int pipefd[2];
181
182 if (pipe(pipefd) < 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000183 ALOGE("pipe failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800184 return -1;
185 }
186
187 /*
188 * TODO: Create a monitoring thread to handle and restart
189 * the daemon if it exits prematurely
190 */
191 if ((pid = fork()) < 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000192 ALOGE("fork failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800193 close(pipefd[0]);
194 close(pipefd[1]);
195 return -1;
196 }
197
198 if (!pid) {
199 close(pipefd[1]);
200 if (pipefd[0] != STDIN_FILENO) {
201 if (dup2(pipefd[0], STDIN_FILENO) != STDIN_FILENO) {
Steve Block5ea0c052012-01-06 19:18:11 +0000202 ALOGE("dup2 failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800203 return -1;
204 }
205 close(pipefd[0]);
206 }
San Mehat9d10b342010-01-18 09:51:02 -0800207
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900208 Fwmark fwmark;
209 fwmark.netId = NetworkController::LOCAL_NET_ID;
210 fwmark.explicitlySelected = true;
211 fwmark.protectedFromVpn = true;
212 fwmark.permission = PERMISSION_SYSTEM;
213 char markStr[UINT32_HEX_STRLEN];
214 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
215
Erik Kline5f0358b2018-02-16 15:08:09 +0900216 std::vector<const std::string> argVector = {
217 "/system/bin/dnsmasq",
218 "--keep-in-foreground",
219 "--no-resolv",
Eric Changa0787fe2018-08-03 14:34:32 -0700220 "--dhcp-ignore-names",
Erik Kline5f0358b2018-02-16 15:08:09 +0900221 "--no-poll",
222 "--dhcp-authoritative",
223 // TODO: pipe through metered status from ConnService
224 "--dhcp-option-force=43,ANDROID_METERED",
225 "--pid-file",
226 "--listen-mark", markStr,
227 "--user", kDnsmasqUsername,
228 };
San Mehat9d10b342010-01-18 09:51:02 -0800229
Erik Kline13fa01f2015-11-12 17:49:23 +0900230 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
Erik Kline5f0358b2018-02-16 15:08:09 +0900231 argVector.push_back(
232 StringPrintf("--dhcp-range=%s,%s,1h",
233 dhcp_ranges[addrIndex], dhcp_ranges[addrIndex+1]));
234 }
235
236 auto args = (char**)std::calloc(argVector.size() + 1, sizeof(char*));
237 for (unsigned i = 0; i < argVector.size(); i++) {
238 args[i] = (char*)argVector[i].c_str();
Robert Greenwalt3208ea02010-03-24 16:32:55 -0700239 }
240
241 if (execv(args[0], args)) {
Erik Kline5f0358b2018-02-16 15:08:09 +0900242 ALOGE("execv failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800243 }
Steve Block5ea0c052012-01-06 19:18:11 +0000244 ALOGE("Should never get here!");
JP Abgrallce4f3792012-08-06 13:44:44 -0700245 _exit(-1);
San Mehat9d10b342010-01-18 09:51:02 -0800246 } else {
247 close(pipefd[0]);
248 mDaemonPid = pid;
249 mDaemonFd = pipefd[1];
Erik Kline93f9b222017-10-22 21:24:58 +0900250 configureForTethering(true);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800251 applyDnsInterfaces();
Steve Block7b984e32011-12-20 16:22:42 +0000252 ALOGD("Tethering services running");
San Mehat9d10b342010-01-18 09:51:02 -0800253 }
254
255 return 0;
256}
257
258int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900259 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800260
261 if (mDaemonPid == 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000262 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800263 return 0;
264 }
265
Steve Block7b984e32011-12-20 16:22:42 +0000266 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800267
268 kill(mDaemonPid, SIGTERM);
San Mehat18737842010-01-21 09:22:43 -0800269 waitpid(mDaemonPid, NULL, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800270 mDaemonPid = 0;
271 close(mDaemonFd);
272 mDaemonFd = -1;
Steve Block7b984e32011-12-20 16:22:42 +0000273 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800274 return 0;
275}
Matthew Xie19944102012-07-12 16:42:07 -0700276
San Mehat9d10b342010-01-18 09:51:02 -0800277bool TetherController::isTetheringStarted() {
278 return (mDaemonPid == 0 ? false : true);
279}
280
Kenny Rootcf52faf2010-02-18 09:59:55 -0800281#define MAX_CMD_SIZE 1024
282
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700283int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
San Mehat9d10b342010-01-18 09:51:02 -0800284 int i;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800285 char daemonCmd[MAX_CMD_SIZE];
San Mehat9d10b342010-01-18 09:51:02 -0800286
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700287 Fwmark fwmark;
288 fwmark.netId = netId;
289 fwmark.explicitlySelected = true;
290 fwmark.protectedFromVpn = true;
291 fwmark.permission = PERMISSION_SYSTEM;
292
Erik Kline13fa01f2015-11-12 17:49:23 +0900293 snprintf(daemonCmd, sizeof(daemonCmd), "update_dns%s0x%x", SEPARATOR, fwmark.intValue);
Kenny Rootcf52faf2010-02-18 09:59:55 -0800294 int cmdLen = strlen(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800295
Erik Kline1d065ba2016-06-08 13:24:45 +0900296 mDnsForwarders.clear();
San Mehat9d10b342010-01-18 09:51:02 -0800297 for (i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700298 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800299
Lorenzo Colittic2841282015-11-25 22:13:57 +0900300 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
301 int ret = getaddrinfo(servers[i], NULL, &hints, &res);
302 freeaddrinfo(res);
303 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000304 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900305 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900306 errno = EINVAL;
San Mehat9d10b342010-01-18 09:51:02 -0800307 return -1;
308 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800309
Nick Kralevichad5b41f2012-07-19 18:48:05 -0700310 cmdLen += (strlen(servers[i]) + 1);
311 if (cmdLen + 1 >= MAX_CMD_SIZE) {
Steve Block7b984e32011-12-20 16:22:42 +0000312 ALOGD("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800313 break;
314 }
315
Erik Kline13fa01f2015-11-12 17:49:23 +0900316 strcat(daemonCmd, SEPARATOR);
San Mehat9d10b342010-01-18 09:51:02 -0800317 strcat(daemonCmd, servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900318 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800319 }
320
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700321 mDnsNetId = netId;
San Mehat9d10b342010-01-18 09:51:02 -0800322 if (mDaemonFd != -1) {
Steve Block7b984e32011-12-20 16:22:42 +0000323 ALOGD("Sending update msg to dnsmasq [%s]", daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800324 if (write(mDaemonFd, daemonCmd, strlen(daemonCmd) +1) < 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000325 ALOGE("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline1d065ba2016-06-08 13:24:45 +0900326 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900327 errno = EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800328 return -1;
329 }
330 }
331 return 0;
332}
333
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700334unsigned TetherController::getDnsNetId() {
335 return mDnsNetId;
336}
337
Erik Kline1d065ba2016-06-08 13:24:45 +0900338const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800339 return mDnsForwarders;
340}
341
Erik Kline1d065ba2016-06-08 13:24:45 +0900342bool TetherController::applyDnsInterfaces() {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800343 char daemonCmd[MAX_CMD_SIZE];
344
345 strcpy(daemonCmd, "update_ifaces");
346 int cmdLen = strlen(daemonCmd);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800347 bool haveInterfaces = false;
348
Erik Kline1d065ba2016-06-08 13:24:45 +0900349 for (const auto &ifname : mInterfaces) {
350 cmdLen += (ifname.size() + 1);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800351 if (cmdLen + 1 >= MAX_CMD_SIZE) {
352 ALOGD("Too many DNS ifaces listed");
353 break;
354 }
355
Erik Kline13fa01f2015-11-12 17:49:23 +0900356 strcat(daemonCmd, SEPARATOR);
Erik Kline1d065ba2016-06-08 13:24:45 +0900357 strcat(daemonCmd, ifname.c_str());
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800358 haveInterfaces = true;
359 }
360
361 if ((mDaemonFd != -1) && haveInterfaces) {
362 ALOGD("Sending update msg to dnsmasq [%s]", daemonCmd);
363 if (write(mDaemonFd, daemonCmd, strlen(daemonCmd) +1) < 0) {
364 ALOGE("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline1d065ba2016-06-08 13:24:45 +0900365 return false;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800366 }
367 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900368 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800369}
370
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800371int TetherController::tetherInterface(const char *interface) {
372 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700373 if (!isIfaceName(interface)) {
374 errno = ENOENT;
375 return -1;
376 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800377
Erik Kline1d065ba2016-06-08 13:24:45 +0900378 if (!configureForIPv6Router(interface)) {
379 configureForIPv6Client(interface);
380 return -1;
381 }
382 mInterfaces.push_back(interface);
383
384 if (!applyDnsInterfaces()) {
385 mInterfaces.pop_back();
386 configureForIPv6Client(interface);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800387 return -1;
388 } else {
389 return 0;
390 }
391}
392
San Mehat9d10b342010-01-18 09:51:02 -0800393int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800394 ALOGD("untetherInterface(%s)", interface);
395
Erik Kline1d065ba2016-06-08 13:24:45 +0900396 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
397 if (!strcmp(interface, it->c_str())) {
398 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800399
Erik Kline1d065ba2016-06-08 13:24:45 +0900400 configureForIPv6Client(interface);
401 return applyDnsInterfaces() ? 0 : -1;
San Mehat9d10b342010-01-18 09:51:02 -0800402 }
403 }
404 errno = ENOENT;
405 return -1;
406}
407
Erik Kline1d065ba2016-06-08 13:24:45 +0900408const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800409 return mInterfaces;
410}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900411
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900412int TetherController::setupIptablesHooks() {
413 int res;
414 res = setDefaults();
415 if (res < 0) {
416 return res;
417 }
418
419 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
420 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
421 // This is no longer optional and tethering will fail to start if it fails.
422 std::string mssRewriteCommand = StringPrintf(
423 "*mangle\n"
424 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
425 "COMMIT\n", LOCAL_MANGLE_FORWARD);
426
427 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
428 std::string defaultCommands = StringPrintf(
429 "*filter\n"
430 ":%s -\n"
431 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
432
433 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
434 if (res < 0) {
435 return res;
436 }
437
438 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
439 if (res < 0) {
440 return res;
441 }
442
Remi NGUYEN VAN7e6f47c2018-03-20 14:44:12 +0900443 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900444
445 return 0;
446}
447
448int TetherController::setDefaults() {
449 std::string v4Cmd = StringPrintf(
450 "*filter\n"
451 ":%s -\n"
452 "-A %s -j DROP\n"
453 "COMMIT\n"
454 "*nat\n"
455 ":%s -\n"
456 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
457
458 std::string v6Cmd = StringPrintf(
459 "*filter\n"
460 ":%s -\n"
461 "COMMIT\n"
462 "*raw\n"
463 ":%s -\n"
464 "COMMIT\n", LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
465
466 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
467 if (res < 0) {
468 return res;
469 }
470
471 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
472 if (res < 0) {
473 return res;
474 }
475
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900476 return 0;
477}
478
479int TetherController::enableNat(const char* intIface, const char* extIface) {
480 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
481
482 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
483 errno = ENODEV;
484 return -1;
485 }
486
487 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
488 if (!strcmp(intIface, extIface)) {
489 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
490 errno = EINVAL;
491 return -1;
492 }
493
Remi NGUYEN VAN7e6f47c2018-03-20 14:44:12 +0900494 if (isForwardingPairEnabled(intIface, extIface)) {
495 return 0;
496 }
497
498 // add this if we are the first enabled nat for this upstream
499 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900500 std::vector<std::string> v4Cmds = {
501 "*nat",
502 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
503 "COMMIT\n"
504 };
505
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900506 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) ||
Remi NGUYEN VAN7e6f47c2018-03-20 14:44:12 +0900507 setupIPv6CountersChain()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900508 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN7e6f47c2018-03-20 14:44:12 +0900509 if (!isAnyForwardingPairEnabled()) {
510 // unwind what's been done, but don't care about success - what more could we do?
511 setDefaults();
512 }
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900513 return -1;
514 }
515 }
516
517 if (setForwardRules(true, intIface, extIface) != 0) {
518 ALOGE("Error setting forward rules");
Remi NGUYEN VAN7e6f47c2018-03-20 14:44:12 +0900519 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900520 setDefaults();
521 }
522 errno = ENODEV;
523 return -1;
524 }
525
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900526 return 0;
527}
528
Remi NGUYEN VAN7e6f47c2018-03-20 14:44:12 +0900529int TetherController::setupIPv6CountersChain() {
530 // Only add this if we are the first enabled nat
531 if (isAnyForwardingPairEnabled()) {
532 return 0;
533 }
534
535 /*
536 * IPv6 tethering doesn't need the state-based conntrack rules, so
537 * it unconditionally jumps to the tether counters chain all the time.
538 */
539 std::vector<std::string> v6Cmds = {
540 "*filter",
541 StringPrintf("-A %s -g %s", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN),
542 "COMMIT\n"
543 };
544
545 return iptablesRestoreFunction(V6, Join(v6Cmds, '\n'), nullptr);
546}
547
548// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
549TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
550 const std::string& intIface, const std::string& extIface) {
551 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
552 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
553 if (it->second.iface == intIface) {
554 return &(it->second);
555 }
556 }
557 return nullptr;
558}
559
560void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
561 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
562 if (existingEntry != nullptr) {
563 existingEntry->active = true;
564 return;
565 }
566
567 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
568 .iface = intIface,
569 .active = true
570 }));
571}
572
573void TetherController::markForwardingPairDisabled(
574 const std::string& intIface, const std::string& extIface) {
575 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
576 if (existingEntry == nullptr) {
577 return;
578 }
579
580 existingEntry->active = false;
581}
582
583bool TetherController::isForwardingPairEnabled(
584 const std::string& intIface, const std::string& extIface) {
585 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
586 return existingEntry != nullptr && existingEntry->active;
587}
588
589bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
590 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
591 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
592 if (it->second.active) {
593 return true;
594 }
595 }
596 return false;
597}
598
599bool TetherController::isAnyForwardingPairEnabled() {
600 for (auto& it : mFwdIfaces) {
601 if (it.second.active) {
602 return true;
603 }
604 }
605 return false;
606}
607
608bool TetherController::tetherCountingRuleExists(
609 const std::string& iface1, const std::string& iface2) {
610 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
611 // is in the map regardless of its active status. Rules are added both ways so we check with
612 // the 2 combinations.
613 return findForwardingDownstream(iface1, iface2) != nullptr
614 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900615}
616
617/* static */
618std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
619 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
620}
621
622int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
623 const char *op = add ? "-A" : "-D";
624
625 std::string rpfilterCmd = StringPrintf(
626 "*raw\n"
627 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
628 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
629 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
630 return -1;
631 }
632
633 std::vector<std::string> v4 = {
Tyler Wearbbe2d302018-05-02 19:59:49 +0530634 "*raw",
635 StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp",
636 op, LOCAL_RAW_PREROUTING, intIface),
Sunmeet Gillb72bff32018-05-10 11:17:04 -0700637 StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp",
638 op, LOCAL_RAW_PREROUTING, intIface),
Tyler Wearbbe2d302018-05-02 19:59:49 +0530639 "COMMIT",
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900640 "*filter",
641 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s",
642 op, LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
643 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP",
644 op, LOCAL_FORWARD, intIface, extIface),
645 StringPrintf("%s %s -i %s -o %s -g %s",
646 op, LOCAL_FORWARD, intIface, extIface, LOCAL_TETHER_COUNTERS_CHAIN),
647 };
648
649 std::vector<std::string> v6 = {
650 "*filter",
651 };
652
Remi NGUYEN VAN7e6f47c2018-03-20 14:44:12 +0900653 // We only ever add tethering quota rules so that they stick.
654 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900655 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900656 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN7e6f47c2018-03-20 14:44:12 +0900657 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900658 v6.push_back(makeTetherCountingRule(extIface, intIface));
659 }
660
661 // Always make sure the drop rule is at the end.
662 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900663 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900664 if (add) {
665 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
666 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
667 }
668
669 v4.push_back("COMMIT\n");
670 v6.push_back("COMMIT\n");
671
672 // We only add IPv6 rules here, never remove them.
673 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
674 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
675 // unwind what's been done, but don't care about success - what more could we do?
676 if (add) {
677 setForwardRules(false, intIface, extIface);
678 }
679 return -1;
680 }
681
Remi NGUYEN VAN7e6f47c2018-03-20 14:44:12 +0900682 if (add) {
683 addForwardingPair(intIface, extIface);
684 } else {
685 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900686 }
687
688 return 0;
689}
690
691int TetherController::disableNat(const char* intIface, const char* extIface) {
692 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
693 errno = ENODEV;
694 return -1;
695 }
696
697 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN7e6f47c2018-03-20 14:44:12 +0900698 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900699 setDefaults();
700 }
701 return 0;
702}
703
704void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
705 for (TetherStats& existing : statsList) {
706 if (existing.addStatsIfMatch(stats)) {
707 return;
708 }
709 }
710 // No match. Insert a new interface pair.
711 statsList.push_back(stats);
712}
713
714/*
715 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900716 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900717 * pkts bytes target prot opt in out source destination
718 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
719 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
720 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
721 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
722 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900723 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900724 * pkts bytes target prot opt in out source destination
725 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
726 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
727 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900728 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900729int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900730 const std::string& statsOutput,
731 std::string &extraProcessingInfo) {
732 int res;
733 std::string statsLine;
734 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
735 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
736 char rest[MAX_IPT_OUTPUT_LINE_LEN];
737
738 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900739 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900740 const char *buffPtr;
741 int64_t packets, bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900742
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900743 std::stringstream stream(statsOutput);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900744
745 // Skip headers.
746 for (int i = 0; i < 2; i++) {
747 std::getline(stream, statsLine, '\n');
748 extraProcessingInfo += statsLine + "\n";
749 if (statsLine.empty()) {
750 ALOGE("Empty header while parsing tethering stats");
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900751 return -EREMOTEIO;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900752 }
753 }
754
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900755 while (std::getline(stream, statsLine, '\n')) {
756 buffPtr = statsLine.c_str();
757
758 /* Clean up, so a failed parse can still print info */
759 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
760 if (strstr(buffPtr, "0.0.0.0")) {
761 // IPv4 has -- indicating what to do with fragments...
762 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
763 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
764 &packets, &bytes, iface0, iface1, rest);
765 } else {
766 // ... but IPv6 does not.
767 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
768 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all %s %s ::/%s",
769 &packets, &bytes, iface0, iface1, rest);
770 }
771 ALOGV("parse res=%d iface0=<%s> iface1=<%s> pkts=%" PRId64" bytes=%" PRId64" rest=<%s> orig line=<%s>", res,
772 iface0, iface1, packets, bytes, rest, buffPtr);
773 extraProcessingInfo += buffPtr;
774 extraProcessingInfo += "\n";
775
776 if (res != 5) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900777 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900778 }
779 /*
780 * The following assumes that the 1st rule has in:extIface out:intIface,
781 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900782 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900783 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900784 if (!stats.intIface[0]) {
785 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
786 stats.intIface = iface0;
787 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900788 stats.txPackets = packets;
789 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900790 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
791 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
792 stats.rxPackets = packets;
793 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900794 }
795 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900796 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900797 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900798 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900799 }
800 }
801
802 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900803 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900804 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900805 }
806 return 0;
807}
808
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900809StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900810 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900811 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900812
813 for (const IptablesTarget target : {V4, V6}) {
814 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900815 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900816 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
817 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900818 }
819
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900820 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900821 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
822 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900823 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900824 }
825 }
826
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900827 return statsList;
828}
829
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900830} // namespace net
831} // namespace android