blob: 828ef3ad12701819d4e563b752339cf768472bda [file] [log] [blame]
JP Abgrall4a5f5ca2011-06-15 18:37:39 -07001/*
2 * Copyright (C) 2011 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
JP Abgralle4788732013-07-02 20:28:45 -070017// #define LOG_NDEBUG 0
JP Abgralldb7da582011-09-18 12:57:32 -070018
19/*
20 * The CommandListener, FrameworkListener don't allow for
21 * multiple calls in parallel to reach the BandwidthController.
22 * If they ever were to allow it, then netd/ would need some tweaking.
23 */
24
Lorenzo Colitti13debb82016-03-27 17:46:30 +090025#include <string>
26#include <vector>
27
JP Abgrall8a932722011-07-13 19:17:35 -070028#include <errno.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070029#include <fcntl.h>
JP Abgralldb7da582011-09-18 12:57:32 -070030#include <stdio.h>
JP Abgrall8a932722011-07-13 19:17:35 -070031#include <stdlib.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070032#include <string.h>
Nick Kralevich0b2b9022014-05-01 13:10:45 -070033#include <ctype.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070034
Matthew Leach2a54d962013-01-14 15:07:12 +000035#define __STDC_FORMAT_MACROS 1
36#include <inttypes.h>
37
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070038#include <sys/socket.h>
39#include <sys/stat.h>
40#include <sys/types.h>
41#include <sys/wait.h>
42
43#include <linux/netlink.h>
44#include <linux/rtnetlink.h>
45#include <linux/pkt_sched.h>
46
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090047#include "android-base/stringprintf.h"
Lorenzo Colitti13debb82016-03-27 17:46:30 +090048#include "android-base/strings.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070049#define LOG_TAG "BandwidthController"
50#include <cutils/log.h>
51#include <cutils/properties.h>
Rom Lemarchand14150212013-01-24 10:01:04 -080052#include <logwrap/logwrap.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070053
JP Abgrall0031cea2012-04-17 16:38:23 -070054#include "NetdConstants.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070055#include "BandwidthController.h"
JP Abgrallbaeccc42013-06-25 09:44:10 -070056#include "NatController.h" /* For LOCAL_TETHER_COUNTERS_CHAIN */
57#include "ResponseCode.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070058
JP Abgralldb7da582011-09-18 12:57:32 -070059/* Alphabetical */
Lorenzo Colitti3c272702017-04-26 15:48:13 +090060#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s\n"
Jeff Sharkey8e188ed2012-07-12 18:32:03 -070061const char* BandwidthController::LOCAL_INPUT = "bw_INPUT";
62const char* BandwidthController::LOCAL_FORWARD = "bw_FORWARD";
63const char* BandwidthController::LOCAL_OUTPUT = "bw_OUTPUT";
64const char* BandwidthController::LOCAL_RAW_PREROUTING = "bw_raw_PREROUTING";
65const char* BandwidthController::LOCAL_MANGLE_POSTROUTING = "bw_mangle_POSTROUTING";
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090066
Lorenzo Colitti86a47982016-03-18 17:52:25 +090067auto BandwidthController::execFunction = android_fork_execvp;
68auto BandwidthController::popenFunction = popen;
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090069auto BandwidthController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
Lorenzo Colitti86a47982016-03-18 17:52:25 +090070
Lorenzo Colitti3c272702017-04-26 15:48:13 +090071using android::base::StringAppendF;
72using android::base::StringPrintf;
73
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090074namespace {
75
76const char ALERT_GLOBAL_NAME[] = "globalAlert";
77const int MAX_CMD_ARGS = 32;
78const int MAX_CMD_LEN = 1024;
79const int MAX_IFACENAME_LEN = 64;
80const int MAX_IPT_OUTPUT_LINE_LEN = 256;
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090081const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colitti3c272702017-04-26 15:48:13 +090082const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
Lorenzo Colittice6748a2017-02-02 01:34:33 +090083 "*filter\n"
84 "-nvx -L %s\n"
85 "COMMIT\n", NatController::LOCAL_TETHER_COUNTERS_CHAIN);
86
JP Abgralldb7da582011-09-18 12:57:32 -070087
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070088/**
89 * Some comments about the rules:
90 * * Ordering
91 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070092 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070093 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070094 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070095 *
96 * * global quota vs per interface quota
97 * - global quota for all costly interfaces uses a single costly chain:
98 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -070099 * iptables -N bw_costly_shared
100 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
101 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
102 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -0700103 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -0700104 * iptables -A bw_costly_shared --jump bw_penalty_box
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900105 * iptables -A bw_penalty_box --jump bw_happy_box
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900106 * iptables -A bw_happy_box --jump bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700107 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700108 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700109 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
110 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700111 *
112 * - quota per interface. This is achieve by having "costly" chains per quota.
113 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700114 * iptables -N bw_costly_iface0
115 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
116 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
117 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -0700118 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -0700119 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700120 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900121 * * Penalty box, happy box and data saver.
122 * - bw_penalty box is a blacklist of apps that are rejected.
123 * - bw_happy_box is a whitelist of apps. It always includes all system apps
124 * - bw_data_saver implements data usage restrictions.
125 * - Via the UI the user can add and remove apps from the whitelist and
126 * blacklist, and turn on/off data saver.
127 * - The blacklist takes precedence over the whitelist and the whitelist
128 * takes precedence over data saver.
129 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700130 * * bw_penalty_box handling:
131 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900132 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700133 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700134 * --jump REJECT --reject-with icmp-port-unreachable
135 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700136 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900137 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700138 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700139 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700140 * --jump RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900141 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900142 * * bw_data_saver handling:
143 * - The bw_data_saver comes after the happy box.
144 * Enable data saver:
145 * iptables -R 1 bw_data_saver --jump REJECT --reject-with icmp-port-unreachable
146 * Disable data saver:
147 * iptables -R 1 bw_data_saver --jump RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700148 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900149
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900150const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900151const std::string DATA_SAVER_ENABLE_COMMAND = "-R bw_data_saver 1";
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900152const std::string HAPPY_BOX_WHITELIST_COMMAND = StringPrintf(
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900153 "-I bw_happy_box -m owner --uid-owner %d-%d --jump RETURN", 0, MAX_SYSTEM_UID);
154
155static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700156 /*
157 * Cleanup rules.
JP Abgrall7e51cde2013-07-03 13:33:05 -0700158 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
JP Abgrall0031cea2012-04-17 16:38:23 -0700159 * to allow coexistance.
JP Abgrall39f8f242011-06-29 19:21:58 -0700160 */
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900161 "*filter",
162 ":bw_INPUT -",
163 ":bw_OUTPUT -",
164 ":bw_FORWARD -",
165 ":bw_happy_box -",
166 ":bw_penalty_box -",
167 ":bw_data_saver -",
168 ":bw_costly_shared -",
169 "COMMIT",
170 "*raw",
171 ":bw_raw_PREROUTING -",
172 "COMMIT",
173 "*mangle",
174 ":bw_mangle_POSTROUTING -",
175 COMMIT_AND_CLOSE
JP Abgrall0031cea2012-04-17 16:38:23 -0700176};
177
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900178static const std::vector<std::string> IPT_BASIC_ACCOUNTING_COMMANDS = {
179 "*filter",
JP Abgrall0031cea2012-04-17 16:38:23 -0700180 "-A bw_INPUT -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall0031cea2012-04-17 16:38:23 -0700181 "-A bw_OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900182 "-A bw_costly_shared --jump bw_penalty_box",
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900183 "-A bw_penalty_box --jump bw_happy_box",
184 "-A bw_happy_box --jump bw_data_saver",
185 "-A bw_data_saver -j RETURN",
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900186 HAPPY_BOX_WHITELIST_COMMAND,
187 "COMMIT",
188
189 "*raw",
190 "-A bw_raw_PREROUTING -m owner --socket-exists", /* This is a tracking rule. */
191 "COMMIT",
192
193 "*mangle",
194 "-A bw_mangle_POSTROUTING -m owner --socket-exists", /* This is a tracking rule. */
195 COMMIT_AND_CLOSE
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900196};
197
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900198
199} // namespace
200
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700201BandwidthController::BandwidthController(void) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700202}
203
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700204int BandwidthController::runIpxtablesCmd(const char *cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700205 IptFailureLog failureHandling) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700206 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700207
Steve Block3fb42e02011-10-20 11:55:56 +0100208 ALOGV("runIpxtablesCmd(cmd=%s)", cmd);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700209 res |= runIptablesCmd(cmd, jumpHandling, IptIpV4, failureHandling);
210 res |= runIptablesCmd(cmd, jumpHandling, IptIpV6, failureHandling);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700211 return res;
212}
213
JP Abgrall26e0d492011-06-24 19:21:51 -0700214int BandwidthController::StrncpyAndCheck(char *buffer, const char *src, size_t buffSize) {
215
216 memset(buffer, '\0', buffSize); // strncpy() is not filling leftover with '\0'
217 strncpy(buffer, src, buffSize);
218 return buffer[buffSize - 1];
219}
220
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700221int BandwidthController::runIptablesCmd(const char *cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700222 IptIpVer iptVer, IptFailureLog failureHandling) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700223 char buffer[MAX_CMD_LEN];
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700224 const char *argv[MAX_CMD_ARGS];
JP Abgrall26e0d492011-06-24 19:21:51 -0700225 int argc = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700226 char *next = buffer;
227 char *tmp;
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700228 int res;
Rom Lemarchand14150212013-01-24 10:01:04 -0800229 int status = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700230
JP Abgrall0dad7c22011-06-24 11:58:14 -0700231 std::string fullCmd = cmd;
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900232 fullCmd += jumpToString(jumpHandling);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700233
Paul Jensen94b2ab92015-08-04 10:35:05 -0400234 fullCmd.insert(0, " -w ");
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700235 fullCmd.insert(0, iptVer == IptIpV4 ? IPTABLES_PATH : IP6TABLES_PATH);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700236
Rom Lemarchand14150212013-01-24 10:01:04 -0800237 if (StrncpyAndCheck(buffer, fullCmd.c_str(), sizeof(buffer))) {
238 ALOGE("iptables command too long");
239 return -1;
240 }
241
242 argc = 0;
243 while ((tmp = strsep(&next, " "))) {
244 argv[argc++] = tmp;
245 if (argc >= MAX_CMD_ARGS) {
246 ALOGE("iptables argument overflow");
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700247 return -1;
248 }
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700249 }
Rom Lemarchand14150212013-01-24 10:01:04 -0800250
251 argv[argc] = NULL;
Lorenzo Colitti86a47982016-03-18 17:52:25 +0900252 res = execFunction(argc, (char **)argv, &status, false,
Rom Lemarchand14150212013-01-24 10:01:04 -0800253 failureHandling == IptFailShow);
JP Abgrallc8dc63b2013-02-13 16:30:00 -0800254 res = res || !WIFEXITED(status) || WEXITSTATUS(status);
255 if (res && failureHandling == IptFailShow) {
256 ALOGE("runIptablesCmd(): res=%d status=%d failed %s", res, status,
257 fullCmd.c_str());
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700258 }
259 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700260}
261
JP Abgrall0e540ec2013-08-26 15:13:10 -0700262void BandwidthController::flushCleanTables(bool doClean) {
263 /* Flush and remove the bw_costly_<iface> tables */
264 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700265
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900266 std::string commands = android::base::Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900267 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700268}
JP Abgrall0031cea2012-04-17 16:38:23 -0700269
JP Abgrall0e540ec2013-08-26 15:13:10 -0700270int BandwidthController::setupIptablesHooks(void) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700271 /* flush+clean is allowed to fail */
272 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700273 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700274}
275
276int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrall0031cea2012-04-17 16:38:23 -0700277 char value[PROPERTY_VALUE_MAX];
278
279 if (!force) {
280 property_get("persist.bandwidth.enable", value, "1");
281 if (!strcmp(value, "0"))
282 return 0;
283 }
JP Abgrall8a932722011-07-13 19:17:35 -0700284
JP Abgralldb7da582011-09-18 12:57:32 -0700285 /* Let's pretend we started from scratch ... */
JP Abgrall8a932722011-07-13 19:17:35 -0700286 sharedQuotaIfaces.clear();
287 quotaIfaces.clear();
JP Abgralldb7da582011-09-18 12:57:32 -0700288 globalAlertBytes = 0;
JP Abgrallc6c67342011-10-07 16:28:54 -0700289 globalAlertTetherCount = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700290 sharedQuotaBytes = sharedAlertBytes = 0;
291
JP Abgrall0e540ec2013-08-26 15:13:10 -0700292 flushCleanTables(false);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900293 std::string commands = android::base::Join(IPT_BASIC_ACCOUNTING_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900294 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700295}
296
297int BandwidthController::disableBandwidthControl(void) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700298
299 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700300 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700301}
302
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900303int BandwidthController::enableDataSaver(bool enable) {
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900304 return runIpxtablesCmd(DATA_SAVER_ENABLE_COMMAND.c_str(),
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900305 enable ? IptJumpReject : IptJumpReturn, IptFailShow);
306}
307
JP Abgrall8a932722011-07-13 19:17:35 -0700308int BandwidthController::runCommands(int numCommands, const char *commands[],
309 RunCmdErrHandling cmdErrHandling) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700310 int res = 0;
JP Abgrallad729ac2012-04-24 23:27:44 -0700311 IptFailureLog failureLogging = IptFailShow;
312 if (cmdErrHandling == RunCmdFailureOk) {
313 failureLogging = IptFailHide;
314 }
Steve Block3fb42e02011-10-20 11:55:56 +0100315 ALOGV("runCommands(): %d commands", numCommands);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700316 for (int cmdNum = 0; cmdNum < numCommands; cmdNum++) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700317 res = runIpxtablesCmd(commands[cmdNum], IptJumpNoAdd, failureLogging);
JP Abgrall0031cea2012-04-17 16:38:23 -0700318 if (res && cmdErrHandling != RunCmdFailureOk)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700319 return res;
320 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700321 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700322}
323
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700324std::string BandwidthController::makeIptablesSpecialAppCmd(IptOp op, int uid, const char *chain) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700325 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700326 char *buff;
327 const char *opFlag;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700328
329 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700330 case IptOpInsert:
331 opFlag = "-I";
332 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700333 case IptOpDelete:
334 opFlag = "-D";
335 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700336 }
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700337 asprintf(&buff, "%s %s -m owner --uid-owner %d", opFlag, chain, uid);
JP Abgrall8a932722011-07-13 19:17:35 -0700338 res = buff;
339 free(buff);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700340 return res;
341}
342
343int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900344 return manipulateNaughtyApps(numUids, appUids, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700345}
346
347int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900348 return manipulateNaughtyApps(numUids, appUids, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700349}
350
JP Abgralle4788732013-07-02 20:28:45 -0700351int BandwidthController::addNiceApps(int numUids, char *appUids[]) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900352 return manipulateNiceApps(numUids, appUids, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700353}
354
355int BandwidthController::removeNiceApps(int numUids, char *appUids[]) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900356 return manipulateNiceApps(numUids, appUids, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700357}
358
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900359int BandwidthController::manipulateNaughtyApps(int numUids, char *appStrUids[], IptOp op) {
360 return manipulateSpecialApps(numUids, appStrUids, "bw_penalty_box", IptJumpReject, op);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700361}
362
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900363int BandwidthController::manipulateNiceApps(int numUids, char *appStrUids[], IptOp op) {
364 return manipulateSpecialApps(numUids, appStrUids, "bw_happy_box", IptJumpReturn, op);
JP Abgralle4788732013-07-02 20:28:45 -0700365}
366
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700367
368int BandwidthController::manipulateSpecialApps(int numUids, char *appStrUids[],
369 const char *chain,
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900370 IptJumpOp jumpHandling, IptOp op) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700371
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700372 int uidNum;
JP Abgrall26e0d492011-06-24 19:21:51 -0700373 const char *failLogTemplate;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700374 int appUids[numUids];
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700375 std::string iptCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700376
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900377 switch (op) {
378 case IptOpInsert:
JP Abgrallaf476f72013-07-03 12:23:55 -0700379 failLogTemplate = "Failed to add app uid %s(%d) to %s.";
JP Abgrall8a932722011-07-13 19:17:35 -0700380 break;
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900381 case IptOpDelete:
JP Abgrallaf476f72013-07-03 12:23:55 -0700382 failLogTemplate = "Failed to delete app uid %s(%d) from %s box.";
JP Abgrall8a932722011-07-13 19:17:35 -0700383 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700384 }
385
386 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrallaf476f72013-07-03 12:23:55 -0700387 char *end;
388 appUids[uidNum] = strtoul(appStrUids[uidNum], &end, 0);
389 if (*end || !*appStrUids[uidNum]) {
390 ALOGE(failLogTemplate, appStrUids[uidNum], appUids[uidNum], chain);
JP Abgrall26e0d492011-06-24 19:21:51 -0700391 goto fail_parse;
392 }
393 }
JP Abgrall26e0d492011-06-24 19:21:51 -0700394
395 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrallb1d24092012-04-27 01:02:31 -0700396 int uid = appUids[uidNum];
JP Abgrallb1d24092012-04-27 01:02:31 -0700397
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700398 iptCmd = makeIptablesSpecialAppCmd(op, uid, chain);
399 if (runIpxtablesCmd(iptCmd.c_str(), jumpHandling)) {
JP Abgrallaf476f72013-07-03 12:23:55 -0700400 ALOGE(failLogTemplate, appStrUids[uidNum], uid, chain);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700401 goto fail_with_uidNum;
402 }
403 }
404 return 0;
405
JP Abgrall26e0d492011-06-24 19:21:51 -0700406fail_with_uidNum:
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700407 /* Try to remove the uid that failed in any case*/
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700408 iptCmd = makeIptablesSpecialAppCmd(IptOpDelete, appUids[uidNum], chain);
409 runIpxtablesCmd(iptCmd.c_str(), jumpHandling);
JP Abgrall26e0d492011-06-24 19:21:51 -0700410fail_parse:
411 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700412}
413
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900414std::string BandwidthController::makeIptablesQuotaCmd(IptFullOp op, const char *costName, int64_t quota) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700415 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700416 char *buff;
417 const char *opFlag;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700418
SynergyDev7776cea2014-03-16 15:48:51 -0700419 ALOGV("makeIptablesQuotaCmd(%d, %" PRId64")", op, quota);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700420
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700421 switch (op) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900422 case IptFullOpInsert:
JP Abgrall8a932722011-07-13 19:17:35 -0700423 opFlag = "-I";
424 break;
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900425 case IptFullOpAppend:
JP Abgrall109899b2013-02-12 19:20:13 -0800426 opFlag = "-A";
427 break;
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900428 case IptFullOpDelete:
JP Abgrall8a932722011-07-13 19:17:35 -0700429 opFlag = "-D";
430 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700431 }
JP Abgrall8a932722011-07-13 19:17:35 -0700432
JP Abgrallbfa74662011-06-29 19:23:04 -0700433 // The requried IP version specific --jump REJECT ... will be added later.
SynergyDev7776cea2014-03-16 15:48:51 -0700434 asprintf(&buff, "%s bw_costly_%s -m quota2 ! --quota %" PRId64" --name %s", opFlag, costName, quota,
JP Abgrall8a932722011-07-13 19:17:35 -0700435 costName);
436 res = buff;
437 free(buff);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700438 return res;
439}
440
JP Abgrall26e0d492011-06-24 19:21:51 -0700441int BandwidthController::prepCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700442 char cmd[MAX_CMD_LEN];
JP Abgrall0031cea2012-04-17 16:38:23 -0700443 int res = 0, res1, res2;
JP Abgrall8a932722011-07-13 19:17:35 -0700444 int ruleInsertPos = 1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700445 std::string costString;
446 const char *costCString;
447
JP Abgrall0dad7c22011-06-24 11:58:14 -0700448 /* The "-N costly" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700449 switch (quotaType) {
450 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700451 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700452 costString += ifn;
453 costCString = costString.c_str();
JP Abgrall0031cea2012-04-17 16:38:23 -0700454 /*
JP Abgrall7e51cde2013-07-03 13:33:05 -0700455 * Flush the bw_costly_<iface> is allowed to fail in case it didn't exist.
JP Abgrall0031cea2012-04-17 16:38:23 -0700456 * Creating a new one is allowed to fail in case it existed.
457 * This helps with netd restarts.
458 */
459 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700460 res1 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700461 snprintf(cmd, sizeof(cmd), "-N %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700462 res2 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700463 res = (res1 && res2) || (!res1 && !res2);
464
JP Abgrall7e51cde2013-07-03 13:33:05 -0700465 snprintf(cmd, sizeof(cmd), "-A %s -j bw_penalty_box", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700466 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall26e0d492011-06-24 19:21:51 -0700467 break;
468 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700469 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700470 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700471 }
472
JP Abgrall8a932722011-07-13 19:17:35 -0700473 if (globalAlertBytes) {
474 /* The alert rule comes 1st */
475 ruleInsertPos = 2;
476 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700477
478 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700479 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700480
481 snprintf(cmd, sizeof(cmd), "-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700482 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall0031cea2012-04-17 16:38:23 -0700483
484 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700485 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700486
487 snprintf(cmd, sizeof(cmd), "-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700488 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900489
490 snprintf(cmd, sizeof(cmd), "-D bw_FORWARD -o %s --jump %s", ifn, costCString);
491 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
492 snprintf(cmd, sizeof(cmd), "-A bw_FORWARD -o %s --jump %s", ifn, costCString);
493 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
494
JP Abgrall0dad7c22011-06-24 11:58:14 -0700495 return res;
496}
497
JP Abgrall26e0d492011-06-24 19:21:51 -0700498int BandwidthController::cleanupCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700499 char cmd[MAX_CMD_LEN];
500 int res = 0;
501 std::string costString;
502 const char *costCString;
503
JP Abgrall26e0d492011-06-24 19:21:51 -0700504 switch (quotaType) {
505 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700506 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700507 costString += ifn;
508 costCString = costString.c_str();
JP Abgrall26e0d492011-06-24 19:21:51 -0700509 break;
510 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700511 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700512 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700513 }
514
JP Abgrall0031cea2012-04-17 16:38:23 -0700515 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700516 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900517 for (const auto tableName : {LOCAL_OUTPUT, LOCAL_FORWARD}) {
518 snprintf(cmd, sizeof(cmd), "-D %s -o %s --jump %s", tableName, ifn, costCString);
519 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
520 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700521
JP Abgrall7e51cde2013-07-03 13:33:05 -0700522 /* The "-N bw_costly_shared" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700523 if (quotaType == QuotaUnique) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700524 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700525 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgralla9f802c2011-06-29 15:46:45 -0700526 snprintf(cmd, sizeof(cmd), "-X %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700527 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700528 }
529 return res;
530}
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700531
JP Abgrall0dad7c22011-06-24 11:58:14 -0700532int BandwidthController::setInterfaceSharedQuota(const char *iface, int64_t maxBytes) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700533 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700534 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700535 std::string quotaCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700536 std::string ifaceName;
537 ;
JP Abgrallbfa74662011-06-29 19:23:04 -0700538 const char *costName = "shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700539 std::list<std::string>::iterator it;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700540
JP Abgrall8a932722011-07-13 19:17:35 -0700541 if (!maxBytes) {
542 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000543 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700544 return -1;
545 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700546 if (!isIfaceName(iface))
547 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700548 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000549 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700550 return -1;
551 }
552 ifaceName = ifn;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700553
554 if (maxBytes == -1) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700555 return removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700556 }
557
558 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700559 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
560 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700561 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700562 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700563
JP Abgrall0dad7c22011-06-24 11:58:14 -0700564 if (it == sharedQuotaIfaces.end()) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700565 res |= prepCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700566 if (sharedQuotaIfaces.empty()) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900567 quotaCmd = makeIptablesQuotaCmd(IptFullOpInsert, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700568 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700569 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000570 ALOGE("Failed set quota rule");
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700571 goto fail;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700572 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700573 sharedQuotaBytes = maxBytes;
574 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700575 sharedQuotaIfaces.push_front(ifaceName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700576
577 }
578
579 if (maxBytes != sharedQuotaBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700580 res |= updateQuota(costName, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700581 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000582 ALOGE("Failed update quota for %s", costName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700583 goto fail;
584 }
585 sharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700586 }
587 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700588
589 fail:
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700590 /*
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700591 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
592 * rules in the kernel to see which ones need cleaning up.
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700593 * For now callers needs to choose if they want to "ndc bandwidth enable"
594 * which resets everything.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700595 */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700596 removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700597 return -1;
598}
599
JP Abgrall8a932722011-07-13 19:17:35 -0700600/* It will also cleanup any shared alerts */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700601int BandwidthController::removeInterfaceSharedQuota(const char *iface) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700602 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700603 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700604 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700605 std::list<std::string>::iterator it;
JP Abgrallbfa74662011-06-29 19:23:04 -0700606 const char *costName = "shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700607
JP Abgrall69261cb2014-06-19 18:35:24 -0700608 if (!isIfaceName(iface))
609 return -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700610 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000611 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700612 return -1;
613 }
JP Abgrall8a932722011-07-13 19:17:35 -0700614 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700615
JP Abgrall0dad7c22011-06-24 11:58:14 -0700616 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
617 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700618 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700619 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700620 if (it == sharedQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000621 ALOGE("No such iface %s to delete", ifn);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700622 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700623 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700624
JP Abgrall26e0d492011-06-24 19:21:51 -0700625 res |= cleanupCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700626 sharedQuotaIfaces.erase(it);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700627
JP Abgrall0dad7c22011-06-24 11:58:14 -0700628 if (sharedQuotaIfaces.empty()) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700629 std::string quotaCmd;
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900630 quotaCmd = makeIptablesQuotaCmd(IptFullOpDelete, costName, sharedQuotaBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700631 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall8a932722011-07-13 19:17:35 -0700632 sharedQuotaBytes = 0;
633 if (sharedAlertBytes) {
634 removeSharedAlert();
635 sharedAlertBytes = 0;
636 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700637 }
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700638 return res;
639}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700640
641int BandwidthController::setInterfaceQuota(const char *iface, int64_t maxBytes) {
642 char ifn[MAX_IFACENAME_LEN];
643 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700644 std::string ifaceName;
645 const char *costName;
646 std::list<QuotaInfo>::iterator it;
647 std::string quotaCmd;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700648
JP Abgrall69261cb2014-06-19 18:35:24 -0700649 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700650 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700651
JP Abgrall8a932722011-07-13 19:17:35 -0700652 if (!maxBytes) {
653 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000654 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700655 return -1;
656 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700657 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700658 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700659 }
660
JP Abgrall8a932722011-07-13 19:17:35 -0700661 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000662 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700663 return -1;
664 }
665 ifaceName = ifn;
666 costName = iface;
667
JP Abgrall0dad7c22011-06-24 11:58:14 -0700668 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700669 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700670 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700671 break;
672 }
673
674 if (it == quotaIfaces.end()) {
JP Abgralle4788732013-07-02 20:28:45 -0700675 /* Preparing the iface adds a penalty/happy box check */
JP Abgrall26e0d492011-06-24 19:21:51 -0700676 res |= prepCostlyIface(ifn, QuotaUnique);
JP Abgrallbaeccc42013-06-25 09:44:10 -0700677 /*
JP Abgralle4788732013-07-02 20:28:45 -0700678 * The rejecting quota limit should go after the penalty/happy box checks
JP Abgrallbaeccc42013-06-25 09:44:10 -0700679 * or else a naughty app could just eat up the quota.
680 * So we append here.
681 */
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900682 quotaCmd = makeIptablesQuotaCmd(IptFullOpAppend, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700683 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700684 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000685 ALOGE("Failed set quota rule");
JP Abgrall0dad7c22011-06-24 11:58:14 -0700686 goto fail;
687 }
688
JP Abgrall8a932722011-07-13 19:17:35 -0700689 quotaIfaces.push_front(QuotaInfo(ifaceName, maxBytes, 0));
JP Abgrall0dad7c22011-06-24 11:58:14 -0700690
691 } else {
JP Abgrall8a932722011-07-13 19:17:35 -0700692 res |= updateQuota(costName, maxBytes);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700693 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000694 ALOGE("Failed update quota for %s", iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700695 goto fail;
696 }
JP Abgrall8a932722011-07-13 19:17:35 -0700697 it->quota = maxBytes;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700698 }
699 return 0;
700
701 fail:
702 /*
703 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
704 * rules in the kernel to see which ones need cleaning up.
705 * For now callers needs to choose if they want to "ndc bandwidth enable"
706 * which resets everything.
707 */
708 removeInterfaceSharedQuota(ifn);
709 return -1;
710}
711
JP Abgrall8a932722011-07-13 19:17:35 -0700712int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
713 return getInterfaceQuota("shared", bytes);
714}
715
716int BandwidthController::getInterfaceQuota(const char *costName, int64_t *bytes) {
717 FILE *fp;
718 char *fname;
719 int scanRes;
720
JP Abgrall69261cb2014-06-19 18:35:24 -0700721 if (!isIfaceName(costName))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700722 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700723
JP Abgrall8a932722011-07-13 19:17:35 -0700724 asprintf(&fname, "/proc/net/xt_quota/%s", costName);
Nick Kralevich53ea9ca2015-01-31 13:54:00 -0800725 fp = fopen(fname, "re");
JP Abgrall8a932722011-07-13 19:17:35 -0700726 free(fname);
727 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000728 ALOGE("Reading quota %s failed (%s)", costName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700729 return -1;
730 }
Mark Salyzynca0b5e22014-03-26 14:15:03 -0700731 scanRes = fscanf(fp, "%" SCNd64, bytes);
SynergyDev7776cea2014-03-16 15:48:51 -0700732 ALOGV("Read quota res=%d bytes=%" PRId64, scanRes, *bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700733 fclose(fp);
734 return scanRes == 1 ? 0 : -1;
735}
736
JP Abgrall0dad7c22011-06-24 11:58:14 -0700737int BandwidthController::removeInterfaceQuota(const char *iface) {
738
739 char ifn[MAX_IFACENAME_LEN];
740 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700741 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700742 std::list<QuotaInfo>::iterator it;
JP Abgrall26e0d492011-06-24 19:21:51 -0700743
JP Abgrall69261cb2014-06-19 18:35:24 -0700744 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700745 return -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700746 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000747 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700748 return -1;
749 }
750 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700751
JP Abgrall0dad7c22011-06-24 11:58:14 -0700752 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700753 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700754 break;
755 }
756
757 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000758 ALOGE("No such iface %s to delete", ifn);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700759 return -1;
760 }
761
762 /* This also removes the quota command of CostlyIface chain. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700763 res |= cleanupCostlyIface(ifn, QuotaUnique);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700764
765 quotaIfaces.erase(it);
766
767 return res;
768}
JP Abgrall8a932722011-07-13 19:17:35 -0700769
770int BandwidthController::updateQuota(const char *quotaName, int64_t bytes) {
771 FILE *fp;
772 char *fname;
773
JP Abgrall69261cb2014-06-19 18:35:24 -0700774 if (!isIfaceName(quotaName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700775 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName);
776 return -1;
777 }
778
JP Abgrall8a932722011-07-13 19:17:35 -0700779 asprintf(&fname, "/proc/net/xt_quota/%s", quotaName);
Nick Kralevich53ea9ca2015-01-31 13:54:00 -0800780 fp = fopen(fname, "we");
JP Abgrall8a932722011-07-13 19:17:35 -0700781 free(fname);
782 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000783 ALOGE("Updating quota %s failed (%s)", quotaName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700784 return -1;
785 }
SynergyDev7776cea2014-03-16 15:48:51 -0700786 fprintf(fp, "%" PRId64"\n", bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700787 fclose(fp);
788 return 0;
789}
790
791int BandwidthController::runIptablesAlertCmd(IptOp op, const char *alertName, int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900792 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900793 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700794
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900795 // TODO: consider using an alternate template for the delete that does not include the --quota
796 // value. This code works because the --quota value is ignored by deletes
797 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT", bytes, alertName);
798 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT", bytes, alertName);
799 StringAppendF(&alertQuotaCmd, "COMMIT\n");
800
Lorenzo Colitti4773cb42017-04-27 14:03:25 +0900801 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrall8a932722011-07-13 19:17:35 -0700802}
803
JP Abgrallc6c67342011-10-07 16:28:54 -0700804int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900805 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900806 std::string alertQuotaCmd = "*filter\n";
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900807 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD", bytes, alertName);
808 StringAppendF(&alertQuotaCmd, "COMMIT\n");
809
810 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700811}
812
813int BandwidthController::setGlobalAlert(int64_t bytes) {
814 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700815 int res = 0;
816
817 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000818 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700819 return -1;
820 }
821 if (globalAlertBytes) {
822 res = updateQuota(alertName, bytes);
823 } else {
824 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700825 if (globalAlertTetherCount) {
Steve Block3fb42e02011-10-20 11:55:56 +0100826 ALOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700827 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
828 }
JP Abgrall8a932722011-07-13 19:17:35 -0700829 }
830 globalAlertBytes = bytes;
831 return res;
832}
833
JP Abgrallc6c67342011-10-07 16:28:54 -0700834int BandwidthController::setGlobalAlertInForwardChain(void) {
835 const char *alertName = ALERT_GLOBAL_NAME;
836 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700837
JP Abgrallc6c67342011-10-07 16:28:54 -0700838 globalAlertTetherCount++;
Steve Block3fb42e02011-10-20 11:55:56 +0100839 ALOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700840
841 /*
842 * If there is no globalAlert active we are done.
843 * If there is an active globalAlert but this is not the 1st
844 * tether, we are also done.
845 */
846 if (!globalAlertBytes || globalAlertTetherCount != 1) {
847 return 0;
848 }
849
850 /* We only add the rule if this was the 1st tether added. */
851 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
852 return res;
853}
854
855int BandwidthController::removeGlobalAlert(void) {
856
857 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700858 int res = 0;
859
860 if (!globalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000861 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700862 return -1;
863 }
864 res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700865 if (globalAlertTetherCount) {
866 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
867 }
JP Abgrall8a932722011-07-13 19:17:35 -0700868 globalAlertBytes = 0;
869 return res;
870}
871
JP Abgrallc6c67342011-10-07 16:28:54 -0700872int BandwidthController::removeGlobalAlertInForwardChain(void) {
873 int res = 0;
874 const char *alertName = ALERT_GLOBAL_NAME;
875
876 if (!globalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000877 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700878 return -1;
879 }
880
881 globalAlertTetherCount--;
882 /*
883 * If there is no globalAlert active we are done.
884 * If there is an active globalAlert but there are more
885 * tethers, we are also done.
886 */
887 if (!globalAlertBytes || globalAlertTetherCount >= 1) {
888 return 0;
889 }
890
891 /* We only detete the rule if this was the last tether removed. */
892 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
893 return res;
894}
895
JP Abgrall8a932722011-07-13 19:17:35 -0700896int BandwidthController::setSharedAlert(int64_t bytes) {
897 if (!sharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000898 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700899 return -1;
900 }
901 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000902 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700903 return -1;
904 }
905 return setCostlyAlert("shared", bytes, &sharedAlertBytes);
906}
907
908int BandwidthController::removeSharedAlert(void) {
909 return removeCostlyAlert("shared", &sharedAlertBytes);
910}
911
912int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
913 std::list<QuotaInfo>::iterator it;
914
JP Abgrall69261cb2014-06-19 18:35:24 -0700915 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700916 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface);
917 return -1;
918 }
919
JP Abgrall8a932722011-07-13 19:17:35 -0700920 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000921 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700922 return -1;
923 }
924 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
925 if (it->ifaceName == iface)
926 break;
927 }
928
929 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000930 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700931 return -1;
932 }
933
934 return setCostlyAlert(iface, bytes, &it->alert);
935}
936
937int BandwidthController::removeInterfaceAlert(const char *iface) {
938 std::list<QuotaInfo>::iterator it;
939
JP Abgrall69261cb2014-06-19 18:35:24 -0700940 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700941 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface);
942 return -1;
943 }
944
JP Abgrall8a932722011-07-13 19:17:35 -0700945 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
946 if (it->ifaceName == iface)
947 break;
948 }
949
950 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000951 ALOGE("No prior alert set for interface %s", iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700952 return -1;
953 }
954
955 return removeCostlyAlert(iface, &it->alert);
956}
957
958int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
959 char *alertQuotaCmd;
JP Abgrall109899b2013-02-12 19:20:13 -0800960 char *chainName;
JP Abgrall8a932722011-07-13 19:17:35 -0700961 int res = 0;
962 char *alertName;
963
JP Abgrall69261cb2014-06-19 18:35:24 -0700964 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700965 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName);
966 return -1;
967 }
968
JP Abgrall8a932722011-07-13 19:17:35 -0700969 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000970 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700971 return -1;
972 }
973 asprintf(&alertName, "%sAlert", costName);
974 if (*alertBytes) {
975 res = updateQuota(alertName, *alertBytes);
976 } else {
JP Abgrall7e51cde2013-07-03 13:33:05 -0700977 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall109899b2013-02-12 19:20:13 -0800978 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-A", chainName, bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700979 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700980 free(alertQuotaCmd);
JP Abgrall109899b2013-02-12 19:20:13 -0800981 free(chainName);
JP Abgrall8a932722011-07-13 19:17:35 -0700982 }
983 *alertBytes = bytes;
984 free(alertName);
985 return res;
986}
987
988int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
989 char *alertQuotaCmd;
990 char *chainName;
991 char *alertName;
992 int res = 0;
993
JP Abgrall69261cb2014-06-19 18:35:24 -0700994 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700995 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName);
996 return -1;
997 }
998
JP Abgrall8a932722011-07-13 19:17:35 -0700999 if (!*alertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001000 ALOGE("No prior alert set for %s alert", costName);
JP Abgrall8a932722011-07-13 19:17:35 -07001001 return -1;
1002 }
1003
Jesper Hanssona9d791f2012-04-27 13:54:27 +02001004 asprintf(&alertName, "%sAlert", costName);
JP Abgrall7e51cde2013-07-03 13:33:05 -07001005 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall92009c82013-02-06 18:01:24 -08001006 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001007 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001008 free(alertQuotaCmd);
1009 free(chainName);
1010
1011 *alertBytes = 0;
1012 free(alertName);
1013 return res;
1014}
JP Abgralldb7da582011-09-18 12:57:32 -07001015
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001016void BandwidthController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
1017 for (TetherStats& existing : statsList) {
1018 if (existing.addStatsIfMatch(stats)) {
1019 return;
1020 }
1021 }
1022 // No match. Insert a new interface pair.
1023 statsList.push_back(stats);
1024}
1025
JP Abgralldb7da582011-09-18 12:57:32 -07001026/*
1027 * Parse the ptks and bytes out of:
JP Abgrallbaeccc42013-06-25 09:44:10 -07001028 * Chain natctrl_tether_counters (4 references)
1029 * pkts bytes target prot opt in out source destination
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001030 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1031 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
1032 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
1033 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001034 * or:
1035 * Chain natctrl_tether_counters (0 references)
1036 * pkts bytes target prot opt in out source destination
1037 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
1038 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
1039 *
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001040 * It results in an error if invoked and no tethering counter rules exist. The constraint
1041 * helps detect complete parsing failure.
JP Abgralldb7da582011-09-18 12:57:32 -07001042 */
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001043int BandwidthController::addForwardChainStats(const TetherStats& filter,
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001044 TetherStatsList& statsList,
1045 const std::string& statsOutput,
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001046 std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -07001047 int res;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001048 std::string statsLine;
JP Abgralldb7da582011-09-18 12:57:32 -07001049 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
1050 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
1051 char rest[MAX_IPT_OUTPUT_LINE_LEN];
1052
JP Abgrallbaeccc42013-06-25 09:44:10 -07001053 TetherStats stats;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001054 const char *buffPtr;
JP Abgralldb7da582011-09-18 12:57:32 -07001055 int64_t packets, bytes;
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001056 int statsFound = 0;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001057
1058 bool filterPair = filter.intIface[0] && filter.extIface[0];
1059
1060 char *filterMsg = filter.getStatsLine();
1061 ALOGV("filter: %s", filterMsg);
1062 free(filterMsg);
1063
1064 stats = filter;
JP Abgralldb7da582011-09-18 12:57:32 -07001065
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001066 std::stringstream stream(statsOutput);
1067 while (std::getline(stream, statsLine, '\n')) {
1068 buffPtr = statsLine.c_str();
1069
JP Abgralldb7da582011-09-18 12:57:32 -07001070 /* Clean up, so a failed parse can still print info */
1071 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001072 if (strstr(buffPtr, "0.0.0.0")) {
1073 // IPv4 has -- indicating what to do with fragments...
1074 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1075 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
1076 &packets, &bytes, iface0, iface1, rest);
1077 } else {
1078 // ... but IPv6 does not.
1079 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
1080 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all %s %s ::/%s",
1081 &packets, &bytes, iface0, iface1, rest);
1082 }
SynergyDev7776cea2014-03-16 15:48:51 -07001083 ALOGV("parse res=%d iface0=<%s> iface1=<%s> pkts=%" PRId64" bytes=%" PRId64" rest=<%s> orig line=<%s>", res,
JP Abgralldb7da582011-09-18 12:57:32 -07001084 iface0, iface1, packets, bytes, rest, buffPtr);
JP Abgralla2a64f02011-11-11 20:36:16 -08001085 extraProcessingInfo += buffPtr;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001086 extraProcessingInfo += "\n";
JP Abgralla2a64f02011-11-11 20:36:16 -08001087
JP Abgralldb7da582011-09-18 12:57:32 -07001088 if (res != 5) {
1089 continue;
1090 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001091 /*
1092 * The following assumes that the 1st rule has in:extIface out:intIface,
1093 * which is what NatController sets up.
1094 * If not filtering, the 1st match rx, and sets up the pair for the tx side.
1095 */
1096 if (filter.intIface[0] && filter.extIface[0]) {
1097 if (filter.intIface == iface0 && filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001098 ALOGV("2Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001099 stats.rxPackets = packets;
1100 stats.rxBytes = bytes;
1101 } else if (filter.intIface == iface1 && filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001102 ALOGV("2Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001103 stats.txPackets = packets;
1104 stats.txBytes = bytes;
1105 }
1106 } else if (filter.intIface[0] || filter.extIface[0]) {
1107 if (filter.intIface == iface0 || filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001108 ALOGV("1Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001109 stats.intIface = iface0;
1110 stats.extIface = iface1;
1111 stats.rxPackets = packets;
1112 stats.rxBytes = bytes;
1113 } else if (filter.intIface == iface1 || filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001114 ALOGV("1Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001115 stats.intIface = iface1;
1116 stats.extIface = iface0;
1117 stats.txPackets = packets;
1118 stats.txBytes = bytes;
1119 }
1120 } else /* if (!filter.intFace[0] && !filter.extIface[0]) */ {
1121 if (!stats.intIface[0]) {
SynergyDev7776cea2014-03-16 15:48:51 -07001122 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001123 stats.intIface = iface0;
1124 stats.extIface = iface1;
1125 stats.rxPackets = packets;
1126 stats.rxBytes = bytes;
1127 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001128 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001129 stats.txPackets = packets;
1130 stats.txBytes = bytes;
1131 }
1132 }
1133 if (stats.rxBytes != -1 && stats.txBytes != -1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001134 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64" filterPair=%d", stats.rxBytes, stats.txBytes, filterPair);
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001135 addStats(statsList, stats);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001136 if (filterPair) {
JP Abgrallbaeccc42013-06-25 09:44:10 -07001137 return 0;
1138 } else {
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001139 statsFound++;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001140 stats = filter;
1141 }
JP Abgralldb7da582011-09-18 12:57:32 -07001142 }
1143 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001144
1145 /* It is always an error to find only one side of the stats. */
1146 /* It is an error to find nothing when not filtering. */
1147 if (((stats.rxBytes == -1) != (stats.txBytes == -1)) ||
1148 (!statsFound && !filterPair)) {
1149 return -1;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001150 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001151 return 0;
JP Abgralldb7da582011-09-18 12:57:32 -07001152}
1153
JP Abgrallbaeccc42013-06-25 09:44:10 -07001154char *BandwidthController::TetherStats::getStatsLine(void) const {
JP Abgralldb7da582011-09-18 12:57:32 -07001155 char *msg;
SynergyDev7776cea2014-03-16 15:48:51 -07001156 asprintf(&msg, "%s %s %" PRId64" %" PRId64" %" PRId64" %" PRId64, intIface.c_str(), extIface.c_str(),
JP Abgralldb7da582011-09-18 12:57:32 -07001157 rxBytes, rxPackets, txBytes, txPackets);
1158 return msg;
1159}
1160
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001161int BandwidthController::getTetherStats(SocketClient *cli, TetherStats& filter,
1162 std::string &extraProcessingInfo) {
1163 int res = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001164
1165 TetherStatsList statsList;
1166
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001167 for (const IptablesTarget target : {V4, V6}) {
1168 std::string statsString;
1169 res = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString);
1170 if (res != 0) {
1171 ALOGE("Failed to run %s err=%d", GET_TETHER_STATS_COMMAND.c_str(), res);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001172 return -1;
1173 }
1174
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001175 res = addForwardChainStats(filter, statsList, statsString, extraProcessingInfo);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001176 if (res != 0) {
1177 return res;
1178 }
1179 }
JP Abgralldb7da582011-09-18 12:57:32 -07001180
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001181 if (filter.intIface[0] && filter.extIface[0] && statsList.size() == 1) {
1182 cli->sendMsg(ResponseCode::TetheringStatsResult, statsList[0].getStatsLine(), false);
1183 } else {
1184 for (const auto& stats: statsList) {
1185 cli->sendMsg(ResponseCode::TetheringStatsListResult, stats.getStatsLine(), false);
1186 }
1187 if (res == 0) {
1188 cli->sendMsg(ResponseCode::CommandOkay, "Tethering stats list completed", false);
1189 }
1190 }
1191
JP Abgralldb7da582011-09-18 12:57:32 -07001192 return res;
1193}
JP Abgrall0e540ec2013-08-26 15:13:10 -07001194
1195void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001196 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
1197 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001198
1199 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001200 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
1201 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001202 return;
1203 }
1204 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001205 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001206}
1207
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001208void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
1209 std::stringstream stream(ruleList);
1210 std::string rule;
1211 std::vector<std::string> clearCommands = { "*filter" };
1212 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001213
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001214 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
1215 while (std::getline(stream, rule, '\n')) {
1216 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
1217 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
1218 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
1219
1220 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -07001221 continue;
1222 }
1223
Lorenzo Colitti3c272702017-04-26 15:48:13 +09001224 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001225 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +09001226 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001227 }
1228 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001229
1230 if (clearCommands.size() == 1) {
1231 // No rules found.
1232 return;
1233 }
1234
1235 clearCommands.push_back("COMMIT\n");
1236 iptablesRestoreFunction(V4V6, android::base::Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001237}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +09001238
1239inline const char *BandwidthController::opToString(IptOp op) {
1240 switch (op) {
1241 case IptOpInsert:
1242 return "-I";
1243 case IptOpDelete:
1244 return "-D";
1245 }
1246}
1247
1248inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
1249 /*
1250 * Must be careful what one rejects with, as upper layer protocols will just
1251 * keep on hammering the device until the number of retries are done.
1252 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
1253 */
1254 switch (jumpHandling) {
1255 case IptJumpNoAdd:
1256 return "";
1257 case IptJumpReject:
1258 return " --jump REJECT";
1259 case IptJumpReturn:
1260 return " --jump RETURN";
1261 }
1262}