blob: c1d73081fcacdc114a5b9813a8a1d6ae79fb52d3 [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();
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900141 ifacePairList.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",
220 "--no-poll",
221 "--dhcp-authoritative",
222 // TODO: pipe through metered status from ConnService
223 "--dhcp-option-force=43,ANDROID_METERED",
224 "--pid-file",
225 "--listen-mark", markStr,
226 "--user", kDnsmasqUsername,
227 };
San Mehat9d10b342010-01-18 09:51:02 -0800228
Erik Kline13fa01f2015-11-12 17:49:23 +0900229 for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
Erik Kline5f0358b2018-02-16 15:08:09 +0900230 argVector.push_back(
231 StringPrintf("--dhcp-range=%s,%s,1h",
232 dhcp_ranges[addrIndex], dhcp_ranges[addrIndex+1]));
233 }
234
235 auto args = (char**)std::calloc(argVector.size() + 1, sizeof(char*));
236 for (unsigned i = 0; i < argVector.size(); i++) {
237 args[i] = (char*)argVector[i].c_str();
Robert Greenwalt3208ea02010-03-24 16:32:55 -0700238 }
239
240 if (execv(args[0], args)) {
Erik Kline5f0358b2018-02-16 15:08:09 +0900241 ALOGE("execv failed (%s)", strerror(errno));
San Mehat9d10b342010-01-18 09:51:02 -0800242 }
Steve Block5ea0c052012-01-06 19:18:11 +0000243 ALOGE("Should never get here!");
JP Abgrallce4f3792012-08-06 13:44:44 -0700244 _exit(-1);
San Mehat9d10b342010-01-18 09:51:02 -0800245 } else {
246 close(pipefd[0]);
247 mDaemonPid = pid;
248 mDaemonFd = pipefd[1];
Erik Kline93f9b222017-10-22 21:24:58 +0900249 configureForTethering(true);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800250 applyDnsInterfaces();
Steve Block7b984e32011-12-20 16:22:42 +0000251 ALOGD("Tethering services running");
San Mehat9d10b342010-01-18 09:51:02 -0800252 }
253
254 return 0;
255}
256
257int TetherController::stopTethering() {
Erik Kline93f9b222017-10-22 21:24:58 +0900258 configureForTethering(false);
San Mehat9d10b342010-01-18 09:51:02 -0800259
260 if (mDaemonPid == 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000261 ALOGE("Tethering already stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800262 return 0;
263 }
264
Steve Block7b984e32011-12-20 16:22:42 +0000265 ALOGD("Stopping tethering services");
San Mehat9d10b342010-01-18 09:51:02 -0800266
267 kill(mDaemonPid, SIGTERM);
San Mehat18737842010-01-21 09:22:43 -0800268 waitpid(mDaemonPid, NULL, 0);
San Mehat9d10b342010-01-18 09:51:02 -0800269 mDaemonPid = 0;
270 close(mDaemonFd);
271 mDaemonFd = -1;
Steve Block7b984e32011-12-20 16:22:42 +0000272 ALOGD("Tethering services stopped");
San Mehat9d10b342010-01-18 09:51:02 -0800273 return 0;
274}
Matthew Xie19944102012-07-12 16:42:07 -0700275
San Mehat9d10b342010-01-18 09:51:02 -0800276bool TetherController::isTetheringStarted() {
277 return (mDaemonPid == 0 ? false : true);
278}
279
Kenny Rootcf52faf2010-02-18 09:59:55 -0800280#define MAX_CMD_SIZE 1024
281
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700282int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
San Mehat9d10b342010-01-18 09:51:02 -0800283 int i;
Kenny Rootcf52faf2010-02-18 09:59:55 -0800284 char daemonCmd[MAX_CMD_SIZE];
San Mehat9d10b342010-01-18 09:51:02 -0800285
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700286 Fwmark fwmark;
287 fwmark.netId = netId;
288 fwmark.explicitlySelected = true;
289 fwmark.protectedFromVpn = true;
290 fwmark.permission = PERMISSION_SYSTEM;
291
Erik Kline13fa01f2015-11-12 17:49:23 +0900292 snprintf(daemonCmd, sizeof(daemonCmd), "update_dns%s0x%x", SEPARATOR, fwmark.intValue);
Kenny Rootcf52faf2010-02-18 09:59:55 -0800293 int cmdLen = strlen(daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800294
Erik Kline1d065ba2016-06-08 13:24:45 +0900295 mDnsForwarders.clear();
San Mehat9d10b342010-01-18 09:51:02 -0800296 for (i = 0; i < numServers; i++) {
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700297 ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800298
Lorenzo Colittic2841282015-11-25 22:13:57 +0900299 addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
300 int ret = getaddrinfo(servers[i], NULL, &hints, &res);
301 freeaddrinfo(res);
302 if (ret) {
Steve Block5ea0c052012-01-06 19:18:11 +0000303 ALOGE("Failed to parse DNS server '%s'", servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900304 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900305 errno = EINVAL;
San Mehat9d10b342010-01-18 09:51:02 -0800306 return -1;
307 }
Kenny Rootcf52faf2010-02-18 09:59:55 -0800308
Nick Kralevichad5b41f2012-07-19 18:48:05 -0700309 cmdLen += (strlen(servers[i]) + 1);
310 if (cmdLen + 1 >= MAX_CMD_SIZE) {
Steve Block7b984e32011-12-20 16:22:42 +0000311 ALOGD("Too many DNS servers listed");
Kenny Rootcf52faf2010-02-18 09:59:55 -0800312 break;
313 }
314
Erik Kline13fa01f2015-11-12 17:49:23 +0900315 strcat(daemonCmd, SEPARATOR);
San Mehat9d10b342010-01-18 09:51:02 -0800316 strcat(daemonCmd, servers[i]);
Erik Kline1d065ba2016-06-08 13:24:45 +0900317 mDnsForwarders.push_back(servers[i]);
San Mehat9d10b342010-01-18 09:51:02 -0800318 }
319
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700320 mDnsNetId = netId;
San Mehat9d10b342010-01-18 09:51:02 -0800321 if (mDaemonFd != -1) {
Steve Block7b984e32011-12-20 16:22:42 +0000322 ALOGD("Sending update msg to dnsmasq [%s]", daemonCmd);
San Mehat9d10b342010-01-18 09:51:02 -0800323 if (write(mDaemonFd, daemonCmd, strlen(daemonCmd) +1) < 0) {
Steve Block5ea0c052012-01-06 19:18:11 +0000324 ALOGE("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline1d065ba2016-06-08 13:24:45 +0900325 mDnsForwarders.clear();
Lorenzo Colittic2841282015-11-25 22:13:57 +0900326 errno = EREMOTEIO;
San Mehat9d10b342010-01-18 09:51:02 -0800327 return -1;
328 }
329 }
330 return 0;
331}
332
Lorenzo Colitti667c4772014-08-26 14:13:07 -0700333unsigned TetherController::getDnsNetId() {
334 return mDnsNetId;
335}
336
Erik Kline1d065ba2016-06-08 13:24:45 +0900337const std::list<std::string> &TetherController::getDnsForwarders() const {
San Mehat9d10b342010-01-18 09:51:02 -0800338 return mDnsForwarders;
339}
340
Erik Kline1d065ba2016-06-08 13:24:45 +0900341bool TetherController::applyDnsInterfaces() {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800342 char daemonCmd[MAX_CMD_SIZE];
343
344 strcpy(daemonCmd, "update_ifaces");
345 int cmdLen = strlen(daemonCmd);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800346 bool haveInterfaces = false;
347
Erik Kline1d065ba2016-06-08 13:24:45 +0900348 for (const auto &ifname : mInterfaces) {
349 cmdLen += (ifname.size() + 1);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800350 if (cmdLen + 1 >= MAX_CMD_SIZE) {
351 ALOGD("Too many DNS ifaces listed");
352 break;
353 }
354
Erik Kline13fa01f2015-11-12 17:49:23 +0900355 strcat(daemonCmd, SEPARATOR);
Erik Kline1d065ba2016-06-08 13:24:45 +0900356 strcat(daemonCmd, ifname.c_str());
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800357 haveInterfaces = true;
358 }
359
360 if ((mDaemonFd != -1) && haveInterfaces) {
361 ALOGD("Sending update msg to dnsmasq [%s]", daemonCmd);
362 if (write(mDaemonFd, daemonCmd, strlen(daemonCmd) +1) < 0) {
363 ALOGE("Failed to send update command to dnsmasq (%s)", strerror(errno));
Erik Kline1d065ba2016-06-08 13:24:45 +0900364 return false;
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800365 }
366 }
Erik Kline1d065ba2016-06-08 13:24:45 +0900367 return true;
San Mehat9d10b342010-01-18 09:51:02 -0800368}
369
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800370int TetherController::tetherInterface(const char *interface) {
371 ALOGD("tetherInterface(%s)", interface);
JP Abgrall69261cb2014-06-19 18:35:24 -0700372 if (!isIfaceName(interface)) {
373 errno = ENOENT;
374 return -1;
375 }
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800376
Erik Kline1d065ba2016-06-08 13:24:45 +0900377 if (!configureForIPv6Router(interface)) {
378 configureForIPv6Client(interface);
379 return -1;
380 }
381 mInterfaces.push_back(interface);
382
383 if (!applyDnsInterfaces()) {
384 mInterfaces.pop_back();
385 configureForIPv6Client(interface);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800386 return -1;
387 } else {
388 return 0;
389 }
390}
391
San Mehat9d10b342010-01-18 09:51:02 -0800392int TetherController::untetherInterface(const char *interface) {
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800393 ALOGD("untetherInterface(%s)", interface);
394
Erik Kline1d065ba2016-06-08 13:24:45 +0900395 for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
396 if (!strcmp(interface, it->c_str())) {
397 mInterfaces.erase(it);
Robert Greenwalt3d4c7582012-12-11 12:33:37 -0800398
Erik Kline1d065ba2016-06-08 13:24:45 +0900399 configureForIPv6Client(interface);
400 return applyDnsInterfaces() ? 0 : -1;
San Mehat9d10b342010-01-18 09:51:02 -0800401 }
402 }
403 errno = ENOENT;
404 return -1;
405}
406
Erik Kline1d065ba2016-06-08 13:24:45 +0900407const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
San Mehat9d10b342010-01-18 09:51:02 -0800408 return mInterfaces;
409}
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900410
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900411int TetherController::setupIptablesHooks() {
412 int res;
413 res = setDefaults();
414 if (res < 0) {
415 return res;
416 }
417
418 // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
419 // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
420 // This is no longer optional and tethering will fail to start if it fails.
421 std::string mssRewriteCommand = StringPrintf(
422 "*mangle\n"
423 "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
424 "COMMIT\n", LOCAL_MANGLE_FORWARD);
425
426 // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
427 std::string defaultCommands = StringPrintf(
428 "*filter\n"
429 ":%s -\n"
430 "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
431
432 res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
433 if (res < 0) {
434 return res;
435 }
436
437 res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
438 if (res < 0) {
439 return res;
440 }
441
442 ifacePairList.clear();
443
444 return 0;
445}
446
447int TetherController::setDefaults() {
448 std::string v4Cmd = StringPrintf(
449 "*filter\n"
450 ":%s -\n"
451 "-A %s -j DROP\n"
452 "COMMIT\n"
453 "*nat\n"
454 ":%s -\n"
455 "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
456
457 std::string v6Cmd = StringPrintf(
458 "*filter\n"
459 ":%s -\n"
460 "COMMIT\n"
461 "*raw\n"
462 ":%s -\n"
463 "COMMIT\n", LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
464
465 int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
466 if (res < 0) {
467 return res;
468 }
469
470 res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
471 if (res < 0) {
472 return res;
473 }
474
475 natCount = 0;
476
477 return 0;
478}
479
480int TetherController::enableNat(const char* intIface, const char* extIface) {
481 ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
482
483 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
484 errno = ENODEV;
485 return -1;
486 }
487
488 /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
489 if (!strcmp(intIface, extIface)) {
490 ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
491 errno = EINVAL;
492 return -1;
493 }
494
495 // add this if we are the first added nat
496 if (natCount == 0) {
497 std::vector<std::string> v4Cmds = {
498 "*nat",
499 StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
500 "COMMIT\n"
501 };
502
503 /*
504 * IPv6 tethering doesn't need the state-based conntrack rules, so
505 * it unconditionally jumps to the tether counters chain all the time.
506 */
507 std::vector<std::string> v6Cmds = {
508 "*filter",
509 StringPrintf("-A %s -g %s", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN),
510 "COMMIT\n"
511 };
512
513 if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) ||
514 iptablesRestoreFunction(V6, Join(v6Cmds, '\n'), nullptr)) {
515 ALOGE("Error setting postroute rule: iface=%s", extIface);
516 // unwind what's been done, but don't care about success - what more could we do?
517 setDefaults();
518 return -1;
519 }
520 }
521
522 if (setForwardRules(true, intIface, extIface) != 0) {
523 ALOGE("Error setting forward rules");
524 if (natCount == 0) {
525 setDefaults();
526 }
527 errno = ENODEV;
528 return -1;
529 }
530
531 natCount++;
532 return 0;
533}
534
535bool TetherController::checkTetherCountingRuleExist(const std::string& pair_name) {
536 return std::find(ifacePairList.begin(), ifacePairList.end(), pair_name) != ifacePairList.end();
537}
538
539/* static */
540std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
541 return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
542}
543
544int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
545 const char *op = add ? "-A" : "-D";
546
547 std::string rpfilterCmd = StringPrintf(
548 "*raw\n"
549 "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
550 "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
551 if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
552 return -1;
553 }
554
555 std::vector<std::string> v4 = {
556 "*filter",
557 StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s",
558 op, LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
559 StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP",
560 op, LOCAL_FORWARD, intIface, extIface),
561 StringPrintf("%s %s -i %s -o %s -g %s",
562 op, LOCAL_FORWARD, intIface, extIface, LOCAL_TETHER_COUNTERS_CHAIN),
563 };
564
565 std::vector<std::string> v6 = {
566 "*filter",
567 };
568
569 /* We only ever add tethering quota rules so that they stick. */
570 std::string pair1 = StringPrintf("%s_%s", intIface, extIface);
571 if (add && !checkTetherCountingRuleExist(pair1)) {
572 v4.push_back(makeTetherCountingRule(intIface, extIface));
573 v6.push_back(makeTetherCountingRule(intIface, extIface));
574 }
575 std::string pair2 = StringPrintf("%s_%s", extIface, intIface);
576 if (add && !checkTetherCountingRuleExist(pair2)) {
577 v4.push_back(makeTetherCountingRule(extIface, intIface));
578 v6.push_back(makeTetherCountingRule(extIface, intIface));
579 }
580
581 // Always make sure the drop rule is at the end.
582 // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900583 // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900584 if (add) {
585 v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
586 v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
587 }
588
589 v4.push_back("COMMIT\n");
590 v6.push_back("COMMIT\n");
591
592 // We only add IPv6 rules here, never remove them.
593 if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
594 (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
595 // unwind what's been done, but don't care about success - what more could we do?
596 if (add) {
597 setForwardRules(false, intIface, extIface);
598 }
599 return -1;
600 }
601
602 if (add && !checkTetherCountingRuleExist(pair1)) {
603 ifacePairList.push_front(pair1);
604 }
605 if (add && !checkTetherCountingRuleExist(pair2)) {
606 ifacePairList.push_front(pair2);
607 }
608
609 return 0;
610}
611
612int TetherController::disableNat(const char* intIface, const char* extIface) {
613 if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
614 errno = ENODEV;
615 return -1;
616 }
617
618 setForwardRules(false, intIface, extIface);
619 if (--natCount <= 0) {
620 // handle decrement to 0 case (do reset to defaults) and erroneous dec below 0
621 setDefaults();
622 }
623 return 0;
624}
625
626void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
627 for (TetherStats& existing : statsList) {
628 if (existing.addStatsIfMatch(stats)) {
629 return;
630 }
631 }
632 // No match. Insert a new interface pair.
633 statsList.push_back(stats);
634}
635
636/*
637 * Parse the ptks and bytes out of:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900638 * Chain tetherctrl_counters (4 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900639 * pkts bytes target prot opt in out source destination
640 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
641 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
642 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
643 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
644 * or:
Lorenzo Colitti4604b4a2017-08-24 19:21:50 +0900645 * Chain tetherctrl_counters (0 references)
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900646 * pkts bytes target prot opt in out source destination
647 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
648 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
649 *
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900650 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900651int TetherController::addForwardChainStats(TetherStatsList& statsList,
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900652 const std::string& statsOutput,
653 std::string &extraProcessingInfo) {
654 int res;
655 std::string statsLine;
656 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
657 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
658 char rest[MAX_IPT_OUTPUT_LINE_LEN];
659
660 TetherStats stats;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900661 const TetherStats empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900662 const char *buffPtr;
663 int64_t packets, bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900664
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900665 std::stringstream stream(statsOutput);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900666
667 // Skip headers.
668 for (int i = 0; i < 2; i++) {
669 std::getline(stream, statsLine, '\n');
670 extraProcessingInfo += statsLine + "\n";
671 if (statsLine.empty()) {
672 ALOGE("Empty header while parsing tethering stats");
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900673 return -EREMOTEIO;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900674 }
675 }
676
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900677 while (std::getline(stream, statsLine, '\n')) {
678 buffPtr = statsLine.c_str();
679
680 /* Clean up, so a failed parse can still print info */
681 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
682 if (strstr(buffPtr, "0.0.0.0")) {
683 // IPv4 has -- indicating what to do with fragments...
684 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
685 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
686 &packets, &bytes, iface0, iface1, rest);
687 } else {
688 // ... but IPv6 does not.
689 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
690 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all %s %s ::/%s",
691 &packets, &bytes, iface0, iface1, rest);
692 }
693 ALOGV("parse res=%d iface0=<%s> iface1=<%s> pkts=%" PRId64" bytes=%" PRId64" rest=<%s> orig line=<%s>", res,
694 iface0, iface1, packets, bytes, rest, buffPtr);
695 extraProcessingInfo += buffPtr;
696 extraProcessingInfo += "\n";
697
698 if (res != 5) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900699 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900700 }
701 /*
702 * The following assumes that the 1st rule has in:extIface out:intIface,
703 * which is what TetherController sets up.
Lorenzo Colitti09353392017-08-24 14:20:32 +0900704 * The 1st matches rx, and sets up the pair for the tx side.
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900705 */
Lorenzo Colitti09353392017-08-24 14:20:32 +0900706 if (!stats.intIface[0]) {
707 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
708 stats.intIface = iface0;
709 stats.extIface = iface1;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900710 stats.txPackets = packets;
711 stats.txBytes = bytes;
Lorenzo Colitti9a65ac62017-09-04 18:07:56 +0900712 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
713 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
714 stats.rxPackets = packets;
715 stats.rxBytes = bytes;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900716 }
717 if (stats.rxBytes != -1 && stats.txBytes != -1) {
Lorenzo Colitti09353392017-08-24 14:20:32 +0900718 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900719 addStats(statsList, stats);
Lorenzo Colitti09353392017-08-24 14:20:32 +0900720 stats = empty;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900721 }
722 }
723
724 /* It is always an error to find only one side of the stats. */
Lorenzo Colitti38fd1362017-09-15 11:40:01 +0900725 if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900726 return -EREMOTEIO;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900727 }
728 return 0;
729}
730
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900731StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900732 TetherStatsList statsList;
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900733 std::string parsedIptablesOutput;
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900734
735 for (const IptablesTarget target : {V4, V6}) {
736 std::string statsString;
Lorenzo Colitti09353392017-08-24 14:20:32 +0900737 if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900738 return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
739 target, ret));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900740 }
741
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900742 if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900743 return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
744 target == V4 ? "IPv4": "IPv6",
Lorenzo Colitti5192bf72017-09-04 13:30:59 +0900745 parsedIptablesOutput.c_str()));
Lorenzo Colittia93126d2017-08-24 13:28:19 +0900746 }
747 }
748
Lorenzo Colitti9a8a9ff2017-01-31 19:06:59 +0900749 return statsList;
750}
751
Lorenzo Colittie20a5262017-05-09 18:30:44 +0900752} // namespace net
753} // namespace android