blob: 857ac99364c051365aafa233400a2e0aa43f8a9d [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
Erik Klineb31fd692018-06-06 20:50:11 +090043#include "Controllers.h"
Lorenzo Colitti667c4772014-08-26 14:13:07 -070044#include "Fwmark.h"
JP Abgrall69261cb2014-06-19 18:35:24 -070045#include "NetdConstants.h"
Lorenzo Colitti667c4772014-08-26 14:13:07 -070046#include "Permission.h"
Erik Kline1d065ba2016-06-08 13:24:45 +090047#include "InterfaceController.h"
Lorenzo Colittie20a5262017-05-09 18:30:44 +090048#include "NetworkController.h"
Lorenzo Colittia93126d2017-08-24 13:28:19 +090049#include "ResponseCode.h"
San Mehat9d10b342010-01-18 09:51:02 -080050#include "TetherController.h"
51
Lorenzo Colittia93126d2017-08-24 13:28:19 +090052using android::base::Join;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090053using android::base::StringAppendF;
Erik Klineb31fd692018-06-06 20:50:11 +090054using android::base::StringPrintf;
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +090055using android::netdutils::statusFromErrno;
Erik Klineb31fd692018-06-06 20:50:11 +090056using android::netdutils::StatusOr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +090057
Lorenzo Colitti799625c2015-02-25 12:52:00 +090058namespace {
59
Erik Kline1d065ba2016-06-08 13:24:45 +090060const char BP_TOOLS_MODE[] = "bp-tools";
61const char IPV4_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv4/ip_forward";
62const char IPV6_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv6/conf/all/forwarding";
63const char SEPARATOR[] = "|";
Erik Kline93f9b222017-10-22 21:24:58 +090064constexpr const char kTcpBeLiberal[] = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
Lorenzo Colitti799625c2015-02-25 12:52:00 +090065
Erik Kline5f0358b2018-02-16 15:08:09 +090066// Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
67constexpr const char kDnsmasqUsername[] = "dns_tether";
68
Lorenzo Colitti799625c2015-02-25 12:52:00 +090069bool writeToFile(const char* filename, const char* value) {
Nick Kralevichb95c60c2016-11-19 09:09:16 -080070 int fd = open(filename, O_WRONLY | O_CLOEXEC);
Nicolas Geoffrayafd40372015-03-16 11:58:06 +000071 if (fd < 0) {
72 ALOGE("Failed to open %s: %s", filename, strerror(errno));
73 return false;
74 }
75
76 const ssize_t len = strlen(value);
77 if (write(fd, value, len) != len) {
78 ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
79 close(fd);
80 return false;
81 }
82 close(fd);
83 return true;
Lorenzo Colitti799625c2015-02-25 12:52:00 +090084}
85
Erik Kline93f9b222017-10-22 21:24:58 +090086// TODO: Consider altering TCP and UDP timeouts as well.
87void configureForTethering(bool enabled) {
88 writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
89}
90
Erik Kline1d065ba2016-06-08 13:24:45 +090091bool configureForIPv6Router(const char *interface) {
92 return (InterfaceController::setEnableIPv6(interface, 0) == 0)
93 && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
Erik Kline6cddf512016-08-09 15:28:42 +090094 && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
95 && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
Erik Kline1d065ba2016-06-08 13:24:45 +090096 && (InterfaceController::setEnableIPv6(interface, 1) == 0);
97}
98
99void configureForIPv6Client(const char *interface) {
100 InterfaceController::setAcceptIPv6Ra(interface, 1);
Erik Kline6cddf512016-08-09 15:28:42 +0900101 InterfaceController::setAcceptIPv6Dad(interface, 1);
102 InterfaceController::setIPv6DadTransmits(interface, "1");
Erik Kline1d065ba2016-06-08 13:24:45 +0900103 InterfaceController::setEnableIPv6(interface, 0);
104}
105
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900106bool inBpToolsMode() {
107 // In BP tools mode, do not disable IP forwarding
108 char bootmode[PROPERTY_VALUE_MAX] = {0};
109 property_get("ro.bootmode", bootmode, "unknown");
110 return !strcmp(BP_TOOLS_MODE, bootmode);
111}
112
113} // namespace
114
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900115namespace android {
116namespace net {
117
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900118auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
119
120const int MAX_IPT_OUTPUT_LINE_LEN = 256;
121
122const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
123 "*filter\n"
124 "-nvx -L %s\n"
125 "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
126
Erik Kline15079dd2018-05-18 23:10:56 +0900127int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
128 if (cmd.empty()) return 0;
129
Erik Klineb31fd692018-06-06 20:50:11 +0900130 gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
Erik Kline15079dd2018-05-18 23:10:56 +0900131 // Send the trailing \0 as well.
132 if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
Erik Klineb31fd692018-06-06 20:50:11 +0900133 gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline15079dd2018-05-18 23:10:56 +0900134 errno = EREMOTEIO;
135 return -1;
136 }
137 return 0;
138}
139
140void TetherController::DnsmasqState::clear() {
141 update_ifaces_cmd.clear();
142 update_dns_cmd.clear();
143}
144
145int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
146 return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
147}
148
Sreeram Ramachandran87475a12014-07-15 16:20:28 -0700149TetherController::TetherController() {
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900150 if (inBpToolsMode()) {
151 enableForwarding(BP_TOOLS_MODE);
152 } else {
153 setIpFwdEnabled();
154 }
San Mehat9d10b342010-01-18 09:51:02 -0800155}
156
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900157bool TetherController::setIpFwdEnabled() {
158 bool success = true;
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900159 bool disable = mForwardingRequests.empty();
160 const char* value = disable ? "0" : "1";
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900161 ALOGD("Setting IP forward enable = %s", value);
162 success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
163 success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
Hugo Benichic4b3a0c2018-05-22 08:48:40 +0900164 if (disable) {
165 // Turning off the forwarding sysconf in the kernel has the side effect
166 // of turning on ICMP redirect, which is a security hazard.
167 // Turn ICMP redirect back off immediately.
168 int rv = InterfaceController::disableIcmpRedirects();
169 success &= (rv == 0);
170 }
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900171 return success;
San Mehat9d10b342010-01-18 09:51:02 -0800172}
173
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900174bool TetherController::enableForwarding(const char* requester) {
175 // Don't return an error if this requester already requested forwarding. Only return errors for
176 // things that the caller caller needs to care about, such as "couldn't write to the file to
177 // enable forwarding".
178 mForwardingRequests.insert(requester);
179 return setIpFwdEnabled();
180}
San Mehat9d10b342010-01-18 09:51:02 -0800181
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900182bool TetherController::disableForwarding(const char* requester) {
183 mForwardingRequests.erase(requester);
184 return setIpFwdEnabled();
185}
San Mehat9d10b342010-01-18 09:51:02 -0800186
Lorenzo Colitti799625c2015-02-25 12:52:00 +0900187size_t TetherController::forwardingRequestCount() {
188 return mForwardingRequests.size();
San Mehat9d10b342010-01-18 09:51:02 -0800189}
190
Erik Kline13fa01f2015-11-12 17:49:23 +0900191int TetherController::startTethering(int num_addrs, char **dhcp_ranges) {
San Mehat9d10b342010-01-18 09:51:02 -0800192 if (mDaemonPid != 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000193 ALOGE("Tethering already started");
San Mehat9d10b342010-01-18 09:51:02 -0800194 errno = EBUSY;
195 return -1;
196 }
197
Steve Block7b984e32011-12-20 16:22:42 +0000198 ALOGD("Starting tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800199
200 pid_t pid;
201 int pipefd[2];
202
203 if (pipe(pipefd) < 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000204 ALOGE("pipe failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800205 return -1;
206 }
207
208 /*
209 * TODO: Create a monitoring thread to handle and restart
210 * the daemon if it exits prematurely
211 */
212 if ((pid = fork()) < 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000213 ALOGE("fork failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800214 close(pipefd[0]);
215 close(pipefd[1]);
216 return -1;
217 }
218
219 if (!pid) {
220 close(pipefd[1]);
221 if (pipefd[0] != STDIN_FILENO) {
222 if (dup2(pipefd[0], STDIN_FILENO) != STDIN_FILENO) {
Steve Block5ea0c052012-01-06 19:18:11 +0000223 ALOGE("dup2 failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800224 return -1;
225 }
226 close(pipefd[0]);
227 }
San Mehat9d10b342010-01-18 09:51:02 -0800228
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900229 Fwmark fwmark;
230 fwmark.netId = NetworkController::LOCAL_NET_ID;
231 fwmark.explicitlySelected = true;
232 fwmark.protectedFromVpn = true;
233 fwmark.permission = PERMISSION_SYSTEM;
234 char markStr[UINT32_HEX_STRLEN];
235 snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
236
Erik Kline5f0358b2018-02-16 15:08:09 +0900237 std::vector<const std::string> argVector = {
238 "/system/bin/dnsmasq",
239 "--keep-in-foreground",
240 "--no-resolv",
241 "--no-poll",
242 "--dhcp-authoritative",
243 // TODO: pipe through metered status from ConnService
244 "--dhcp-option-force=43,ANDROID_METERED",
245 "--pid-file",
246 "--listen-mark", markStr,
247 "--user", kDnsmasqUsername,
248 };
San Mehat9d10b342010-01-18 09:51:02 -0800249
Erik Kline13fa01f2015-11-12 17:49:23 +0900250 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
Erik Kline5f0358b2018-02-16 15:08:09 +0900251 argVector.push_back(
252 StringPrintf("--dhcp-range=%s,%s,1h",
253 dhcp_ranges[addrIndex], dhcp_ranges[addrIndex+1]));
254 }
255
256 auto args = (char**)std::calloc(argVector.size() + 1, sizeof(char*));
257 for (unsigned i = 0; i < argVector.size(); i++) {
258 args[i] = (char*)argVector[i].c_str();
Robert Greenwalt3208ea02010-03-24 16:32:55 -0700259 }
260
261 if (execv(args[0], args)) {
Erik Kline5f0358b2018-02-16 15:08:09 +0900262 ALOGE("execv failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800263 }
Steve Block5ea0c052012-01-06 19:18:11 +0000264 ALOGE("Should never get here!");
JP Abgrallce4f3792012-08-06 13:44:44 -0700265 _exit(-1);
San Mehat9d10b342010-01-18 09:51:02 -0800266 } else {
267 close(pipefd[0]);
268 mDaemonPid = pid;
269 mDaemonFd = pipefd[1];
Erik Kline93f9b222017-10-22 21:24:58 +0900270 configureForTethering(true);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800271 applyDnsInterfaces();
Steve Block7b984e32011-12-20 16:22:42 +0000272 ALOGD("Tethering services running");
San Mehat9d10b342010-01-18 09:51:02 -0800273 }
274
275 return 0;
276}
277
278int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900279 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800280
281 if (mDaemonPid == 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000282 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800283 return 0;
284 }
285
Steve Block7b984e32011-12-20 16:22:42 +0000286 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800287
288 kill(mDaemonPid, SIGTERM);
Yi Kongbdfd57e2018-07-25 13:26:10 -0700289 waitpid(mDaemonPid, nullptr, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800290 mDaemonPid = 0;
291 close(mDaemonFd);
292 mDaemonFd = -1;
Erik Kline15079dd2018-05-18 23:10:56 +0900293 mDnsmasqState.clear();
Steve Block7b984e32011-12-20 16:22:42 +0000294 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800295 return 0;
296}
Matthew Xie19944102012-07-12 16:42:07 -0700297
San Mehat9d10b342010-01-18 09:51:02 -0800298bool TetherController::isTetheringStarted() {
299 return (mDaemonPid == 0 ? false : true);
300}
301
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900302// dnsmasq can't parse commands larger than this due to the fixed-size buffer
303// in check_android_listeners(). The receiving buffer is 1024 bytes long, but
304// dnsmasq reads up to 1023 bytes.
305#define MAX_CMD_SIZE 1023
Kenny Rootcf52faf2010-02-18 09:59:55 -0800306
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700307int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
San Mehat9d10b342010-01-18 09:51:02 -0800308 int i;
San Mehat9d10b342010-01-18 09:51:02 -0800309
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700310 Fwmark fwmark;
311 fwmark.netId = netId;
312 fwmark.explicitlySelected = true;
313 fwmark.protectedFromVpn = true;
314 fwmark.permission = PERMISSION_SYSTEM;
315
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900316 std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
San Mehat9d10b342010-01-18 09:51:02 -0800317
Erik Kline1d065ba2016-06-08 13:24:45 +0900318 mDnsForwarders.clear();
San Mehat9d10b342010-01-18 09:51:02 -0800319 for (i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700320 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800321
Lorenzo Colittic2841282015-11-25 22:13:57 +0900322 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
Yi Kongbdfd57e2018-07-25 13:26:10 -0700323 int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
Lorenzo Colittic2841282015-11-25 22:13:57 +0900324 freeaddrinfo(res);
325 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000326 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900327 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900328 errno = EINVAL;
San Mehat9d10b342010-01-18 09:51:02 -0800329 return -1;
330 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800331
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900332 if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
333 ALOGE("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800334 break;
335 }
336
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900337 daemonCmd += SEPARATOR;
338 daemonCmd += servers[i];
Erik Kline1d065ba2016-06-08 13:24:45 +0900339 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800340 }
341
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700342 mDnsNetId = netId;
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900343 mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800344 if (mDaemonFd != -1) {
Erik Kline15079dd2018-05-18 23:10:56 +0900345 if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
Erik Kline1d065ba2016-06-08 13:24:45 +0900346 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900347 errno = EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800348 return -1;
349 }
350 }
351 return 0;
352}
353
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700354unsigned TetherController::getDnsNetId() {
355 return mDnsNetId;
356}
357
Erik Kline1d065ba2016-06-08 13:24:45 +0900358const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800359 return mDnsForwarders;
360}
361
Erik Kline1d065ba2016-06-08 13:24:45 +0900362bool TetherController::applyDnsInterfaces() {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900363 std::string daemonCmd = "update_ifaces";
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800364 bool haveInterfaces = false;
365
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900366 for (const auto& ifname : mInterfaces) {
367 if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
368 ALOGE("Too many DNS servers listed");
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800369 break;
370 }
371
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900372 daemonCmd += SEPARATOR;
373 daemonCmd += ifname;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800374 haveInterfaces = true;
375 }
376
Erik Kline15079dd2018-05-18 23:10:56 +0900377 if (!haveInterfaces) {
378 mDnsmasqState.update_ifaces_cmd.clear();
379 } else {
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900380 mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
Erik Kline15079dd2018-05-18 23:10:56 +0900381 if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800382 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900383 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800384}
385
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800386int TetherController::tetherInterface(const char *interface) {
387 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700388 if (!isIfaceName(interface)) {
389 errno = ENOENT;
390 return -1;
391 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800392
Erik Kline1d065ba2016-06-08 13:24:45 +0900393 if (!configureForIPv6Router(interface)) {
394 configureForIPv6Client(interface);
395 return -1;
396 }
397 mInterfaces.push_back(interface);
398
399 if (!applyDnsInterfaces()) {
400 mInterfaces.pop_back();
401 configureForIPv6Client(interface);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800402 return -1;
403 } else {
404 return 0;
405 }
406}
407
San Mehat9d10b342010-01-18 09:51:02 -0800408int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800409 ALOGD("untetherInterface(%s)", interface);
410
Erik Kline1d065ba2016-06-08 13:24:45 +0900411 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
412 if (!strcmp(interface, it->c_str())) {
413 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800414
Erik Kline1d065ba2016-06-08 13:24:45 +0900415 configureForIPv6Client(interface);
416 return applyDnsInterfaces() ? 0 : -1;
San Mehat9d10b342010-01-18 09:51:02 -0800417 }
418 }
419 errno = ENOENT;
420 return -1;
421}
422
Erik Kline1d065ba2016-06-08 13:24:45 +0900423const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800424 return mInterfaces;
425}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900426
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900427int TetherController::setupIptablesHooks() {
428 int res;
429 res = setDefaults();
430 if (res < 0) {
431 return res;
432 }
433
434 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
435 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
436 // This is no longer optional and tethering will fail to start if it fails.
437 std::string mssRewriteCommand = StringPrintf(
438 "*mangle\n"
439 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
440 "COMMIT\n", LOCAL_MANGLE_FORWARD);
441
442 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
443 std::string defaultCommands = StringPrintf(
444 "*filter\n"
445 ":%s -\n"
446 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
447
448 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
449 if (res < 0) {
450 return res;
451 }
452
453 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
454 if (res < 0) {
455 return res;
456 }
457
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900458 mFwdIfaces.clear();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900459
460 return 0;
461}
462
463int TetherController::setDefaults() {
464 std::string v4Cmd = StringPrintf(
465 "*filter\n"
466 ":%s -\n"
467 "-A %s -j DROP\n"
468 "COMMIT\n"
469 "*nat\n"
470 ":%s -\n"
471 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
472
473 std::string v6Cmd = StringPrintf(
474 "*filter\n"
475 ":%s -\n"
476 "COMMIT\n"
477 "*raw\n"
478 ":%s -\n"
479 "COMMIT\n", LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
480
481 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
482 if (res < 0) {
483 return res;
484 }
485
486 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
487 if (res < 0) {
488 return res;
489 }
490
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900491 return 0;
492}
493
494int TetherController::enableNat(const char* intIface, const char* extIface) {
495 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
496
497 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
498 errno = ENODEV;
499 return -1;
500 }
501
502 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
503 if (!strcmp(intIface, extIface)) {
504 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
505 errno = EINVAL;
506 return -1;
507 }
508
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900509 if (isForwardingPairEnabled(intIface, extIface)) {
510 return 0;
511 }
512
513 // add this if we are the first enabled nat for this upstream
514 if (!isAnyForwardingEnabledOnUpstream(extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900515 std::vector<std::string> v4Cmds = {
516 "*nat",
517 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
518 "COMMIT\n"
519 };
520
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900521 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) ||
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900522 setupIPv6CountersChain()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900523 ALOGE("Error setting postroute rule: iface=%s", extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900524 if (!isAnyForwardingPairEnabled()) {
525 // unwind what's been done, but don't care about success - what more could we do?
526 setDefaults();
527 }
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900528 return -1;
529 }
530 }
531
532 if (setForwardRules(true, intIface, extIface) != 0) {
533 ALOGE("Error setting forward rules");
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900534 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900535 setDefaults();
536 }
537 errno = ENODEV;
538 return -1;
539 }
540
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900541 return 0;
542}
543
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900544int TetherController::setupIPv6CountersChain() {
545 // Only add this if we are the first enabled nat
546 if (isAnyForwardingPairEnabled()) {
547 return 0;
548 }
549
550 /*
551 * IPv6 tethering doesn't need the state-based conntrack rules, so
552 * it unconditionally jumps to the tether counters chain all the time.
553 */
554 std::vector<std::string> v6Cmds = {
555 "*filter",
556 StringPrintf("-A %s -g %s", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN),
557 "COMMIT\n"
558 };
559
560 return iptablesRestoreFunction(V6, Join(v6Cmds, '\n'), nullptr);
561}
562
563// Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
564TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
565 const std::string& intIface, const std::string& extIface) {
566 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
567 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
568 if (it->second.iface == intIface) {
569 return &(it->second);
570 }
571 }
572 return nullptr;
573}
574
575void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
576 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
577 if (existingEntry != nullptr) {
578 existingEntry->active = true;
579 return;
580 }
581
582 mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
583 .iface = intIface,
584 .active = true
585 }));
586}
587
588void TetherController::markForwardingPairDisabled(
589 const std::string& intIface, const std::string& extIface) {
590 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
591 if (existingEntry == nullptr) {
592 return;
593 }
594
595 existingEntry->active = false;
596}
597
598bool TetherController::isForwardingPairEnabled(
599 const std::string& intIface, const std::string& extIface) {
600 ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
601 return existingEntry != nullptr && existingEntry->active;
602}
603
604bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
605 auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
606 for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
607 if (it->second.active) {
608 return true;
609 }
610 }
611 return false;
612}
613
614bool TetherController::isAnyForwardingPairEnabled() {
615 for (auto& it : mFwdIfaces) {
616 if (it.second.active) {
617 return true;
618 }
619 }
620 return false;
621}
622
623bool TetherController::tetherCountingRuleExists(
624 const std::string& iface1, const std::string& iface2) {
625 // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
626 // is in the map regardless of its active status. Rules are added both ways so we check with
627 // the 2 combinations.
628 return findForwardingDownstream(iface1, iface2) != nullptr
629 || findForwardingDownstream(iface2, iface1) != nullptr;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900630}
631
632/* static */
633std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
634 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
635}
636
637int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
638 const char *op = add ? "-A" : "-D";
639
640 std::string rpfilterCmd = StringPrintf(
641 "*raw\n"
642 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
643 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
644 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
645 return -1;
646 }
647
648 std::vector<std::string> v4 = {
649 "*filter",
650 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s",
651 op, LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
652 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP",
653 op, LOCAL_FORWARD, intIface, extIface),
654 StringPrintf("%s %s -i %s -o %s -g %s",
655 op, LOCAL_FORWARD, intIface, extIface, LOCAL_TETHER_COUNTERS_CHAIN),
656 };
657
658 std::vector<std::string> v6 = {
659 "*filter",
660 };
661
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900662 // We only ever add tethering quota rules so that they stick.
663 if (add && !tetherCountingRuleExists(intIface, extIface)) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900664 v4.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900665 v4.push_back(makeTetherCountingRule(extIface, intIface));
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900666 v6.push_back(makeTetherCountingRule(intIface, extIface));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900667 v6.push_back(makeTetherCountingRule(extIface, intIface));
668 }
669
670 // Always make sure the drop rule is at the end.
671 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900672 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900673 if (add) {
674 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
675 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
676 }
677
678 v4.push_back("COMMIT\n");
679 v6.push_back("COMMIT\n");
680
681 // We only add IPv6 rules here, never remove them.
682 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
683 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
684 // unwind what's been done, but don't care about success - what more could we do?
685 if (add) {
686 setForwardRules(false, intIface, extIface);
687 }
688 return -1;
689 }
690
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900691 if (add) {
692 addForwardingPair(intIface, extIface);
693 } else {
694 markForwardingPairDisabled(intIface, extIface);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900695 }
696
697 return 0;
698}
699
700int TetherController::disableNat(const char* intIface, const char* extIface) {
701 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
702 errno = ENODEV;
703 return -1;
704 }
705
706 setForwardRules(false, intIface, extIface);
Remi NGUYEN VAN3b47c792018-03-20 14:44:12 +0900707 if (!isAnyForwardingPairEnabled()) {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900708 setDefaults();
709 }
710 return 0;
711}
712
713void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
714 for (TetherStats& existing : statsList) {
715 if (existing.addStatsIfMatch(stats)) {
716 return;
717 }
718 }
719 // No match. Insert a new interface pair.
720 statsList.push_back(stats);
721}
722
723/*
724 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900725 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900726 * pkts bytes target prot opt in out source destination
727 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
728 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
729 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
730 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
731 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900732 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900733 * pkts bytes target prot opt in out source destination
734 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
735 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
736 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900737 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900738int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900739 const std::string& statsOutput,
740 std::string &extraProcessingInfo) {
741 int res;
742 std::string statsLine;
743 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
744 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
745 char rest[MAX_IPT_OUTPUT_LINE_LEN];
746
747 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900748 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900749 const char *buffPtr;
750 int64_t packets, bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900751
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900752 std::stringstream stream(statsOutput);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900753
754 // Skip headers.
755 for (int i = 0; i < 2; i++) {
756 std::getline(stream, statsLine, '\n');
757 extraProcessingInfo += statsLine + "\n";
758 if (statsLine.empty()) {
759 ALOGE("Empty header while parsing tethering stats");
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900760 return -EREMOTEIO;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900761 }
762 }
763
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900764 while (std::getline(stream, statsLine, '\n')) {
765 buffPtr = statsLine.c_str();
766
767 /* Clean up, so a failed parse can still print info */
768 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
769 if (strstr(buffPtr, "0.0.0.0")) {
770 // IPv4 has -- indicating what to do with fragments...
771 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
772 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
773 &packets, &bytes, iface0, iface1, rest);
774 } else {
775 // ... but IPv6 does not.
776 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
777 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all %s %s ::/%s",
778 &packets, &bytes, iface0, iface1, rest);
779 }
780 ALOGV("parse res=%d iface0=<%s> iface1=<%s> pkts=%" PRId64" bytes=%" PRId64" rest=<%s> orig line=<%s>", res,
781 iface0, iface1, packets, bytes, rest, buffPtr);
782 extraProcessingInfo += buffPtr;
783 extraProcessingInfo += "\n";
784
785 if (res != 5) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900786 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900787 }
788 /*
789 * The following assumes that the 1st rule has in:extIface out:intIface,
790 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900791 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900792 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900793 if (!stats.intIface[0]) {
794 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
795 stats.intIface = iface0;
796 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900797 stats.txPackets = packets;
798 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900799 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
800 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
801 stats.rxPackets = packets;
802 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900803 }
804 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900805 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900806 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900807 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900808 }
809 }
810
811 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900812 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900813 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900814 }
815 return 0;
816}
817
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900818StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900819 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900820 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900821
822 for (const IptablesTarget target : {V4, V6}) {
823 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900824 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900825 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
826 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900827 }
828
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900829 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900830 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
831 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900832 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900833 }
834 }
835
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900836 return statsList;
837}
838
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900839} // namespace net
840} // namespace android