blob: 47fb8230f1e921793e2178bd2e0c854539526cbd [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;
JP Abgrall26e0d492011-06-24 19:21:51 -0700232
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700233 switch (jumpHandling) {
234 case IptJumpReject:
JP Abgrall340d5cc2013-06-28 17:06:00 -0700235 /*
236 * Must be carefull what one rejects with, as uper layer protocols will just
237 * keep on hammering the device until the number of retries are done.
238 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
239 */
240 fullCmd += " --jump REJECT";
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700241 break;
242 case IptJumpReturn:
243 fullCmd += " --jump RETURN";
244 break;
245 case IptJumpNoAdd:
246 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700247 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700248
Paul Jensen94b2ab92015-08-04 10:35:05 -0400249 fullCmd.insert(0, " -w ");
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700250 fullCmd.insert(0, iptVer == IptIpV4 ? IPTABLES_PATH : IP6TABLES_PATH);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700251
Rom Lemarchand14150212013-01-24 10:01:04 -0800252 if (StrncpyAndCheck(buffer, fullCmd.c_str(), sizeof(buffer))) {
253 ALOGE("iptables command too long");
254 return -1;
255 }
256
257 argc = 0;
258 while ((tmp = strsep(&next, " "))) {
259 argv[argc++] = tmp;
260 if (argc >= MAX_CMD_ARGS) {
261 ALOGE("iptables argument overflow");
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700262 return -1;
263 }
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700264 }
Rom Lemarchand14150212013-01-24 10:01:04 -0800265
266 argv[argc] = NULL;
Lorenzo Colitti86a47982016-03-18 17:52:25 +0900267 res = execFunction(argc, (char **)argv, &status, false,
Rom Lemarchand14150212013-01-24 10:01:04 -0800268 failureHandling == IptFailShow);
JP Abgrallc8dc63b2013-02-13 16:30:00 -0800269 res = res || !WIFEXITED(status) || WEXITSTATUS(status);
270 if (res && failureHandling == IptFailShow) {
271 ALOGE("runIptablesCmd(): res=%d status=%d failed %s", res, status,
272 fullCmd.c_str());
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700273 }
274 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700275}
276
JP Abgrall0e540ec2013-08-26 15:13:10 -0700277void BandwidthController::flushCleanTables(bool doClean) {
278 /* Flush and remove the bw_costly_<iface> tables */
279 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700280
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900281 std::string commands = android::base::Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900282 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700283}
JP Abgrall0031cea2012-04-17 16:38:23 -0700284
JP Abgrall0e540ec2013-08-26 15:13:10 -0700285int BandwidthController::setupIptablesHooks(void) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700286 /* flush+clean is allowed to fail */
287 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700288 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700289}
290
291int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrall0031cea2012-04-17 16:38:23 -0700292 char value[PROPERTY_VALUE_MAX];
293
294 if (!force) {
295 property_get("persist.bandwidth.enable", value, "1");
296 if (!strcmp(value, "0"))
297 return 0;
298 }
JP Abgrall8a932722011-07-13 19:17:35 -0700299
JP Abgralldb7da582011-09-18 12:57:32 -0700300 /* Let's pretend we started from scratch ... */
JP Abgrall8a932722011-07-13 19:17:35 -0700301 sharedQuotaIfaces.clear();
302 quotaIfaces.clear();
JP Abgralldb7da582011-09-18 12:57:32 -0700303 globalAlertBytes = 0;
JP Abgrallc6c67342011-10-07 16:28:54 -0700304 globalAlertTetherCount = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700305 sharedQuotaBytes = sharedAlertBytes = 0;
306
JP Abgrall0e540ec2013-08-26 15:13:10 -0700307 flushCleanTables(false);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900308 std::string commands = android::base::Join(IPT_BASIC_ACCOUNTING_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900309 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700310}
311
312int BandwidthController::disableBandwidthControl(void) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700313
314 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700315 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700316}
317
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900318int BandwidthController::enableDataSaver(bool enable) {
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900319 return runIpxtablesCmd(DATA_SAVER_ENABLE_COMMAND.c_str(),
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900320 enable ? IptJumpReject : IptJumpReturn, IptFailShow);
321}
322
JP Abgrall8a932722011-07-13 19:17:35 -0700323int BandwidthController::runCommands(int numCommands, const char *commands[],
324 RunCmdErrHandling cmdErrHandling) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700325 int res = 0;
JP Abgrallad729ac2012-04-24 23:27:44 -0700326 IptFailureLog failureLogging = IptFailShow;
327 if (cmdErrHandling == RunCmdFailureOk) {
328 failureLogging = IptFailHide;
329 }
Steve Block3fb42e02011-10-20 11:55:56 +0100330 ALOGV("runCommands(): %d commands", numCommands);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700331 for (int cmdNum = 0; cmdNum < numCommands; cmdNum++) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700332 res = runIpxtablesCmd(commands[cmdNum], IptJumpNoAdd, failureLogging);
JP Abgrall0031cea2012-04-17 16:38:23 -0700333 if (res && cmdErrHandling != RunCmdFailureOk)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700334 return res;
335 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700336 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700337}
338
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700339std::string BandwidthController::makeIptablesSpecialAppCmd(IptOp op, int uid, const char *chain) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700340 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700341 char *buff;
342 const char *opFlag;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700343
344 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700345 case IptOpInsert:
346 opFlag = "-I";
347 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800348 case IptOpAppend:
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700349 ALOGE("Append op not supported for %s uids", chain);
350 res = "";
351 return res;
JP Abgrall109899b2013-02-12 19:20:13 -0800352 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700353 case IptOpReplace:
354 opFlag = "-R";
355 break;
356 default:
357 case IptOpDelete:
358 opFlag = "-D";
359 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700360 }
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700361 asprintf(&buff, "%s %s -m owner --uid-owner %d", opFlag, chain, uid);
JP Abgrall8a932722011-07-13 19:17:35 -0700362 res = buff;
363 free(buff);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700364 return res;
365}
366
367int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700368 return manipulateNaughtyApps(numUids, appUids, SpecialAppOpAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700369}
370
371int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700372 return manipulateNaughtyApps(numUids, appUids, SpecialAppOpRemove);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700373}
374
JP Abgralle4788732013-07-02 20:28:45 -0700375int BandwidthController::addNiceApps(int numUids, char *appUids[]) {
376 return manipulateNiceApps(numUids, appUids, SpecialAppOpAdd);
377}
378
379int BandwidthController::removeNiceApps(int numUids, char *appUids[]) {
380 return manipulateNiceApps(numUids, appUids, SpecialAppOpRemove);
381}
382
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700383int BandwidthController::manipulateNaughtyApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
Lorenzo Colittib1f05572016-03-18 11:55:56 +0900384 return manipulateSpecialApps(numUids, appStrUids, "bw_penalty_box", IptJumpReject, appOp);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700385}
386
JP Abgralle4788732013-07-02 20:28:45 -0700387int BandwidthController::manipulateNiceApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
Lorenzo Colittib1f05572016-03-18 11:55:56 +0900388 return manipulateSpecialApps(numUids, appStrUids, "bw_happy_box", IptJumpReturn, appOp);
JP Abgralle4788732013-07-02 20:28:45 -0700389}
390
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700391
392int BandwidthController::manipulateSpecialApps(int numUids, char *appStrUids[],
393 const char *chain,
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700394 IptJumpOp jumpHandling, SpecialAppOp appOp) {
395
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700396 int uidNum;
JP Abgrall26e0d492011-06-24 19:21:51 -0700397 const char *failLogTemplate;
398 IptOp op;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700399 int appUids[numUids];
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700400 std::string iptCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700401
JP Abgrall26e0d492011-06-24 19:21:51 -0700402 switch (appOp) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700403 case SpecialAppOpAdd:
JP Abgrall8a932722011-07-13 19:17:35 -0700404 op = IptOpInsert;
JP Abgrallaf476f72013-07-03 12:23:55 -0700405 failLogTemplate = "Failed to add app uid %s(%d) to %s.";
JP Abgrall8a932722011-07-13 19:17:35 -0700406 break;
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700407 case SpecialAppOpRemove:
JP Abgrall8a932722011-07-13 19:17:35 -0700408 op = IptOpDelete;
JP Abgrallaf476f72013-07-03 12:23:55 -0700409 failLogTemplate = "Failed to delete app uid %s(%d) from %s box.";
JP Abgrall8a932722011-07-13 19:17:35 -0700410 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700411 default:
412 ALOGE("Unexpected app Op %d", appOp);
413 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700414 }
415
416 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrallaf476f72013-07-03 12:23:55 -0700417 char *end;
418 appUids[uidNum] = strtoul(appStrUids[uidNum], &end, 0);
419 if (*end || !*appStrUids[uidNum]) {
420 ALOGE(failLogTemplate, appStrUids[uidNum], appUids[uidNum], chain);
JP Abgrall26e0d492011-06-24 19:21:51 -0700421 goto fail_parse;
422 }
423 }
JP Abgrall26e0d492011-06-24 19:21:51 -0700424
425 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrallb1d24092012-04-27 01:02:31 -0700426 int uid = appUids[uidNum];
JP Abgrallb1d24092012-04-27 01:02:31 -0700427
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700428 iptCmd = makeIptablesSpecialAppCmd(op, uid, chain);
429 if (runIpxtablesCmd(iptCmd.c_str(), jumpHandling)) {
JP Abgrallaf476f72013-07-03 12:23:55 -0700430 ALOGE(failLogTemplate, appStrUids[uidNum], uid, chain);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700431 goto fail_with_uidNum;
432 }
433 }
434 return 0;
435
JP Abgrall26e0d492011-06-24 19:21:51 -0700436fail_with_uidNum:
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700437 /* Try to remove the uid that failed in any case*/
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700438 iptCmd = makeIptablesSpecialAppCmd(IptOpDelete, appUids[uidNum], chain);
439 runIpxtablesCmd(iptCmd.c_str(), jumpHandling);
JP Abgrall26e0d492011-06-24 19:21:51 -0700440fail_parse:
441 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700442}
443
JP Abgrall26e0d492011-06-24 19:21:51 -0700444std::string BandwidthController::makeIptablesQuotaCmd(IptOp op, const char *costName, int64_t quota) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700445 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700446 char *buff;
447 const char *opFlag;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700448
SynergyDev7776cea2014-03-16 15:48:51 -0700449 ALOGV("makeIptablesQuotaCmd(%d, %" PRId64")", op, quota);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700450
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700451 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700452 case IptOpInsert:
453 opFlag = "-I";
454 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800455 case IptOpAppend:
456 opFlag = "-A";
457 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700458 case IptOpReplace:
459 opFlag = "-R";
460 break;
461 default:
462 case IptOpDelete:
463 opFlag = "-D";
464 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700465 }
JP Abgrall8a932722011-07-13 19:17:35 -0700466
JP Abgrallbfa74662011-06-29 19:23:04 -0700467 // The requried IP version specific --jump REJECT ... will be added later.
SynergyDev7776cea2014-03-16 15:48:51 -0700468 asprintf(&buff, "%s bw_costly_%s -m quota2 ! --quota %" PRId64" --name %s", opFlag, costName, quota,
JP Abgrall8a932722011-07-13 19:17:35 -0700469 costName);
470 res = buff;
471 free(buff);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700472 return res;
473}
474
JP Abgrall26e0d492011-06-24 19:21:51 -0700475int BandwidthController::prepCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700476 char cmd[MAX_CMD_LEN];
JP Abgrall0031cea2012-04-17 16:38:23 -0700477 int res = 0, res1, res2;
JP Abgrall8a932722011-07-13 19:17:35 -0700478 int ruleInsertPos = 1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700479 std::string costString;
480 const char *costCString;
481
JP Abgrall0dad7c22011-06-24 11:58:14 -0700482 /* The "-N costly" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700483 switch (quotaType) {
484 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700485 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700486 costString += ifn;
487 costCString = costString.c_str();
JP Abgrall0031cea2012-04-17 16:38:23 -0700488 /*
JP Abgrall7e51cde2013-07-03 13:33:05 -0700489 * Flush the bw_costly_<iface> is allowed to fail in case it didn't exist.
JP Abgrall0031cea2012-04-17 16:38:23 -0700490 * Creating a new one is allowed to fail in case it existed.
491 * This helps with netd restarts.
492 */
493 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700494 res1 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700495 snprintf(cmd, sizeof(cmd), "-N %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700496 res2 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700497 res = (res1 && res2) || (!res1 && !res2);
498
JP Abgrall7e51cde2013-07-03 13:33:05 -0700499 snprintf(cmd, sizeof(cmd), "-A %s -j bw_penalty_box", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700500 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall26e0d492011-06-24 19:21:51 -0700501 break;
502 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700503 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700504 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700505 default:
506 ALOGE("Unexpected quotatype %d", quotaType);
507 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700508 }
509
JP Abgrall8a932722011-07-13 19:17:35 -0700510 if (globalAlertBytes) {
511 /* The alert rule comes 1st */
512 ruleInsertPos = 2;
513 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700514
515 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700516 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700517
518 snprintf(cmd, sizeof(cmd), "-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700519 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall0031cea2012-04-17 16:38:23 -0700520
521 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700522 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700523
524 snprintf(cmd, sizeof(cmd), "-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700525 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900526
527 snprintf(cmd, sizeof(cmd), "-D bw_FORWARD -o %s --jump %s", ifn, costCString);
528 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
529 snprintf(cmd, sizeof(cmd), "-A bw_FORWARD -o %s --jump %s", ifn, costCString);
530 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
531
JP Abgrall0dad7c22011-06-24 11:58:14 -0700532 return res;
533}
534
JP Abgrall26e0d492011-06-24 19:21:51 -0700535int BandwidthController::cleanupCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700536 char cmd[MAX_CMD_LEN];
537 int res = 0;
538 std::string costString;
539 const char *costCString;
540
JP Abgrall26e0d492011-06-24 19:21:51 -0700541 switch (quotaType) {
542 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700543 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700544 costString += ifn;
545 costCString = costString.c_str();
JP Abgrall26e0d492011-06-24 19:21:51 -0700546 break;
547 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700548 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700549 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700550 default:
551 ALOGE("Unexpected quotatype %d", quotaType);
552 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700553 }
554
JP Abgrall0031cea2012-04-17 16:38:23 -0700555 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700556 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900557 for (const auto tableName : {LOCAL_OUTPUT, LOCAL_FORWARD}) {
558 snprintf(cmd, sizeof(cmd), "-D %s -o %s --jump %s", tableName, ifn, costCString);
559 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
560 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700561
JP Abgrall7e51cde2013-07-03 13:33:05 -0700562 /* The "-N bw_costly_shared" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700563 if (quotaType == QuotaUnique) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700564 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700565 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgralla9f802c2011-06-29 15:46:45 -0700566 snprintf(cmd, sizeof(cmd), "-X %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700567 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700568 }
569 return res;
570}
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700571
JP Abgrall0dad7c22011-06-24 11:58:14 -0700572int BandwidthController::setInterfaceSharedQuota(const char *iface, int64_t maxBytes) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700573 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700574 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700575 std::string quotaCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700576 std::string ifaceName;
577 ;
JP Abgrallbfa74662011-06-29 19:23:04 -0700578 const char *costName = "shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700579 std::list<std::string>::iterator it;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700580
JP Abgrall8a932722011-07-13 19:17:35 -0700581 if (!maxBytes) {
582 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000583 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700584 return -1;
585 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700586 if (!isIfaceName(iface))
587 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700588 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000589 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700590 return -1;
591 }
592 ifaceName = ifn;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700593
594 if (maxBytes == -1) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700595 return removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700596 }
597
598 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700599 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
600 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700601 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700602 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700603
JP Abgrall0dad7c22011-06-24 11:58:14 -0700604 if (it == sharedQuotaIfaces.end()) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700605 res |= prepCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700606 if (sharedQuotaIfaces.empty()) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700607 quotaCmd = makeIptablesQuotaCmd(IptOpInsert, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700608 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700609 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000610 ALOGE("Failed set quota rule");
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700611 goto fail;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700612 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700613 sharedQuotaBytes = maxBytes;
614 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700615 sharedQuotaIfaces.push_front(ifaceName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700616
617 }
618
619 if (maxBytes != sharedQuotaBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700620 res |= updateQuota(costName, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700621 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000622 ALOGE("Failed update quota for %s", costName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700623 goto fail;
624 }
625 sharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700626 }
627 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700628
629 fail:
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700630 /*
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700631 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
632 * rules in the kernel to see which ones need cleaning up.
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700633 * For now callers needs to choose if they want to "ndc bandwidth enable"
634 * which resets everything.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700635 */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700636 removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700637 return -1;
638}
639
JP Abgrall8a932722011-07-13 19:17:35 -0700640/* It will also cleanup any shared alerts */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700641int BandwidthController::removeInterfaceSharedQuota(const char *iface) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700642 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700643 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700644 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700645 std::list<std::string>::iterator it;
JP Abgrallbfa74662011-06-29 19:23:04 -0700646 const char *costName = "shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700647
JP Abgrall69261cb2014-06-19 18:35:24 -0700648 if (!isIfaceName(iface))
649 return -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700650 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000651 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700652 return -1;
653 }
JP Abgrall8a932722011-07-13 19:17:35 -0700654 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700655
JP Abgrall0dad7c22011-06-24 11:58:14 -0700656 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
657 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700658 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700659 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700660 if (it == sharedQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000661 ALOGE("No such iface %s to delete", ifn);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700662 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700663 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700664
JP Abgrall26e0d492011-06-24 19:21:51 -0700665 res |= cleanupCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700666 sharedQuotaIfaces.erase(it);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700667
JP Abgrall0dad7c22011-06-24 11:58:14 -0700668 if (sharedQuotaIfaces.empty()) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700669 std::string quotaCmd;
JP Abgrallbfa74662011-06-29 19:23:04 -0700670 quotaCmd = makeIptablesQuotaCmd(IptOpDelete, costName, sharedQuotaBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700671 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall8a932722011-07-13 19:17:35 -0700672 sharedQuotaBytes = 0;
673 if (sharedAlertBytes) {
674 removeSharedAlert();
675 sharedAlertBytes = 0;
676 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700677 }
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700678 return res;
679}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700680
681int BandwidthController::setInterfaceQuota(const char *iface, int64_t maxBytes) {
682 char ifn[MAX_IFACENAME_LEN];
683 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700684 std::string ifaceName;
685 const char *costName;
686 std::list<QuotaInfo>::iterator it;
687 std::string quotaCmd;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700688
JP Abgrall69261cb2014-06-19 18:35:24 -0700689 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700690 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700691
JP Abgrall8a932722011-07-13 19:17:35 -0700692 if (!maxBytes) {
693 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000694 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700695 return -1;
696 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700697 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700698 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700699 }
700
JP Abgrall8a932722011-07-13 19:17:35 -0700701 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000702 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700703 return -1;
704 }
705 ifaceName = ifn;
706 costName = iface;
707
JP Abgrall0dad7c22011-06-24 11:58:14 -0700708 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700709 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700710 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700711 break;
712 }
713
714 if (it == quotaIfaces.end()) {
JP Abgralle4788732013-07-02 20:28:45 -0700715 /* Preparing the iface adds a penalty/happy box check */
JP Abgrall26e0d492011-06-24 19:21:51 -0700716 res |= prepCostlyIface(ifn, QuotaUnique);
JP Abgrallbaeccc42013-06-25 09:44:10 -0700717 /*
JP Abgralle4788732013-07-02 20:28:45 -0700718 * The rejecting quota limit should go after the penalty/happy box checks
JP Abgrallbaeccc42013-06-25 09:44:10 -0700719 * or else a naughty app could just eat up the quota.
720 * So we append here.
721 */
JP Abgrall109899b2013-02-12 19:20:13 -0800722 quotaCmd = makeIptablesQuotaCmd(IptOpAppend, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700723 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700724 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000725 ALOGE("Failed set quota rule");
JP Abgrall0dad7c22011-06-24 11:58:14 -0700726 goto fail;
727 }
728
JP Abgrall8a932722011-07-13 19:17:35 -0700729 quotaIfaces.push_front(QuotaInfo(ifaceName, maxBytes, 0));
JP Abgrall0dad7c22011-06-24 11:58:14 -0700730
731 } else {
JP Abgrall8a932722011-07-13 19:17:35 -0700732 res |= updateQuota(costName, maxBytes);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700733 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000734 ALOGE("Failed update quota for %s", iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700735 goto fail;
736 }
JP Abgrall8a932722011-07-13 19:17:35 -0700737 it->quota = maxBytes;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700738 }
739 return 0;
740
741 fail:
742 /*
743 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
744 * rules in the kernel to see which ones need cleaning up.
745 * For now callers needs to choose if they want to "ndc bandwidth enable"
746 * which resets everything.
747 */
748 removeInterfaceSharedQuota(ifn);
749 return -1;
750}
751
JP Abgrall8a932722011-07-13 19:17:35 -0700752int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
753 return getInterfaceQuota("shared", bytes);
754}
755
756int BandwidthController::getInterfaceQuota(const char *costName, int64_t *bytes) {
757 FILE *fp;
758 char *fname;
759 int scanRes;
760
JP Abgrall69261cb2014-06-19 18:35:24 -0700761 if (!isIfaceName(costName))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700762 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700763
JP Abgrall8a932722011-07-13 19:17:35 -0700764 asprintf(&fname, "/proc/net/xt_quota/%s", costName);
Nick Kralevich53ea9ca2015-01-31 13:54:00 -0800765 fp = fopen(fname, "re");
JP Abgrall8a932722011-07-13 19:17:35 -0700766 free(fname);
767 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000768 ALOGE("Reading quota %s failed (%s)", costName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700769 return -1;
770 }
Mark Salyzynca0b5e22014-03-26 14:15:03 -0700771 scanRes = fscanf(fp, "%" SCNd64, bytes);
SynergyDev7776cea2014-03-16 15:48:51 -0700772 ALOGV("Read quota res=%d bytes=%" PRId64, scanRes, *bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700773 fclose(fp);
774 return scanRes == 1 ? 0 : -1;
775}
776
JP Abgrall0dad7c22011-06-24 11:58:14 -0700777int BandwidthController::removeInterfaceQuota(const char *iface) {
778
779 char ifn[MAX_IFACENAME_LEN];
780 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700781 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700782 std::list<QuotaInfo>::iterator it;
JP Abgrall26e0d492011-06-24 19:21:51 -0700783
JP Abgrall69261cb2014-06-19 18:35:24 -0700784 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700785 return -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700786 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000787 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700788 return -1;
789 }
790 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700791
JP Abgrall0dad7c22011-06-24 11:58:14 -0700792 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700793 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700794 break;
795 }
796
797 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000798 ALOGE("No such iface %s to delete", ifn);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700799 return -1;
800 }
801
802 /* This also removes the quota command of CostlyIface chain. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700803 res |= cleanupCostlyIface(ifn, QuotaUnique);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700804
805 quotaIfaces.erase(it);
806
807 return res;
808}
JP Abgrall8a932722011-07-13 19:17:35 -0700809
810int BandwidthController::updateQuota(const char *quotaName, int64_t bytes) {
811 FILE *fp;
812 char *fname;
813
JP Abgrall69261cb2014-06-19 18:35:24 -0700814 if (!isIfaceName(quotaName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700815 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName);
816 return -1;
817 }
818
JP Abgrall8a932722011-07-13 19:17:35 -0700819 asprintf(&fname, "/proc/net/xt_quota/%s", quotaName);
Nick Kralevich53ea9ca2015-01-31 13:54:00 -0800820 fp = fopen(fname, "we");
JP Abgrall8a932722011-07-13 19:17:35 -0700821 free(fname);
822 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000823 ALOGE("Updating quota %s failed (%s)", quotaName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700824 return -1;
825 }
SynergyDev7776cea2014-03-16 15:48:51 -0700826 fprintf(fp, "%" PRId64"\n", bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700827 fclose(fp);
828 return 0;
829}
830
831int BandwidthController::runIptablesAlertCmd(IptOp op, const char *alertName, int64_t bytes) {
832 int res = 0;
833 const char *opFlag;
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900834 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700835
836 switch (op) {
837 case IptOpInsert:
838 opFlag = "-I";
839 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700840 default:
841 case IptOpDelete:
842 opFlag = "-D";
843 break;
844 }
845
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900846 // TODO: consider using an alternate template for the delete that does not include the --quota
847 // value. This code works because the --quota value is ignored by deletes
848 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT", bytes, alertName);
849 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT", bytes, alertName);
850 StringAppendF(&alertQuotaCmd, "COMMIT\n");
851
852 iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrall8a932722011-07-13 19:17:35 -0700853 return res;
854}
855
JP Abgrallc6c67342011-10-07 16:28:54 -0700856int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700857 const char *opFlag;
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900858 std::string alertQuotaCmd = "*filter\n";
JP Abgrallc6c67342011-10-07 16:28:54 -0700859
860 switch (op) {
861 case IptOpInsert:
862 opFlag = "-I";
863 break;
JP Abgrallc6c67342011-10-07 16:28:54 -0700864 default:
865 case IptOpDelete:
866 opFlag = "-D";
867 break;
868 }
869
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900870 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD", bytes, alertName);
871 StringAppendF(&alertQuotaCmd, "COMMIT\n");
872
873 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700874}
875
876int BandwidthController::setGlobalAlert(int64_t bytes) {
877 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700878 int res = 0;
879
880 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000881 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700882 return -1;
883 }
884 if (globalAlertBytes) {
885 res = updateQuota(alertName, bytes);
886 } else {
887 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700888 if (globalAlertTetherCount) {
Steve Block3fb42e02011-10-20 11:55:56 +0100889 ALOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700890 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
891 }
JP Abgrall8a932722011-07-13 19:17:35 -0700892 }
893 globalAlertBytes = bytes;
894 return res;
895}
896
JP Abgrallc6c67342011-10-07 16:28:54 -0700897int BandwidthController::setGlobalAlertInForwardChain(void) {
898 const char *alertName = ALERT_GLOBAL_NAME;
899 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700900
JP Abgrallc6c67342011-10-07 16:28:54 -0700901 globalAlertTetherCount++;
Steve Block3fb42e02011-10-20 11:55:56 +0100902 ALOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700903
904 /*
905 * If there is no globalAlert active we are done.
906 * If there is an active globalAlert but this is not the 1st
907 * tether, we are also done.
908 */
909 if (!globalAlertBytes || globalAlertTetherCount != 1) {
910 return 0;
911 }
912
913 /* We only add the rule if this was the 1st tether added. */
914 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
915 return res;
916}
917
918int BandwidthController::removeGlobalAlert(void) {
919
920 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700921 int res = 0;
922
923 if (!globalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000924 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700925 return -1;
926 }
927 res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700928 if (globalAlertTetherCount) {
929 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
930 }
JP Abgrall8a932722011-07-13 19:17:35 -0700931 globalAlertBytes = 0;
932 return res;
933}
934
JP Abgrallc6c67342011-10-07 16:28:54 -0700935int BandwidthController::removeGlobalAlertInForwardChain(void) {
936 int res = 0;
937 const char *alertName = ALERT_GLOBAL_NAME;
938
939 if (!globalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000940 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700941 return -1;
942 }
943
944 globalAlertTetherCount--;
945 /*
946 * If there is no globalAlert active we are done.
947 * If there is an active globalAlert but there are more
948 * tethers, we are also done.
949 */
950 if (!globalAlertBytes || globalAlertTetherCount >= 1) {
951 return 0;
952 }
953
954 /* We only detete the rule if this was the last tether removed. */
955 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
956 return res;
957}
958
JP Abgrall8a932722011-07-13 19:17:35 -0700959int BandwidthController::setSharedAlert(int64_t bytes) {
960 if (!sharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000961 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700962 return -1;
963 }
964 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000965 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700966 return -1;
967 }
968 return setCostlyAlert("shared", bytes, &sharedAlertBytes);
969}
970
971int BandwidthController::removeSharedAlert(void) {
972 return removeCostlyAlert("shared", &sharedAlertBytes);
973}
974
975int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
976 std::list<QuotaInfo>::iterator it;
977
JP Abgrall69261cb2014-06-19 18:35:24 -0700978 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700979 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface);
980 return -1;
981 }
982
JP Abgrall8a932722011-07-13 19:17:35 -0700983 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000984 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700985 return -1;
986 }
987 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
988 if (it->ifaceName == iface)
989 break;
990 }
991
992 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000993 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700994 return -1;
995 }
996
997 return setCostlyAlert(iface, bytes, &it->alert);
998}
999
1000int BandwidthController::removeInterfaceAlert(const char *iface) {
1001 std::list<QuotaInfo>::iterator it;
1002
JP Abgrall69261cb2014-06-19 18:35:24 -07001003 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001004 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface);
1005 return -1;
1006 }
1007
JP Abgrall8a932722011-07-13 19:17:35 -07001008 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
1009 if (it->ifaceName == iface)
1010 break;
1011 }
1012
1013 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +00001014 ALOGE("No prior alert set for interface %s", iface);
JP Abgrall8a932722011-07-13 19:17:35 -07001015 return -1;
1016 }
1017
1018 return removeCostlyAlert(iface, &it->alert);
1019}
1020
1021int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
1022 char *alertQuotaCmd;
JP Abgrall109899b2013-02-12 19:20:13 -08001023 char *chainName;
JP Abgrall8a932722011-07-13 19:17:35 -07001024 int res = 0;
1025 char *alertName;
1026
JP Abgrall69261cb2014-06-19 18:35:24 -07001027 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001028 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName);
1029 return -1;
1030 }
1031
JP Abgrall8a932722011-07-13 19:17:35 -07001032 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001033 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -07001034 return -1;
1035 }
1036 asprintf(&alertName, "%sAlert", costName);
1037 if (*alertBytes) {
1038 res = updateQuota(alertName, *alertBytes);
1039 } else {
JP Abgrall7e51cde2013-07-03 13:33:05 -07001040 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall109899b2013-02-12 19:20:13 -08001041 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-A", chainName, bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001042 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001043 free(alertQuotaCmd);
JP Abgrall109899b2013-02-12 19:20:13 -08001044 free(chainName);
JP Abgrall8a932722011-07-13 19:17:35 -07001045 }
1046 *alertBytes = bytes;
1047 free(alertName);
1048 return res;
1049}
1050
1051int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
1052 char *alertQuotaCmd;
1053 char *chainName;
1054 char *alertName;
1055 int res = 0;
1056
JP Abgrall69261cb2014-06-19 18:35:24 -07001057 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001058 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName);
1059 return -1;
1060 }
1061
JP Abgrall8a932722011-07-13 19:17:35 -07001062 if (!*alertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001063 ALOGE("No prior alert set for %s alert", costName);
JP Abgrall8a932722011-07-13 19:17:35 -07001064 return -1;
1065 }
1066
Jesper Hanssona9d791f2012-04-27 13:54:27 +02001067 asprintf(&alertName, "%sAlert", costName);
JP Abgrall7e51cde2013-07-03 13:33:05 -07001068 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall92009c82013-02-06 18:01:24 -08001069 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001070 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001071 free(alertQuotaCmd);
1072 free(chainName);
1073
1074 *alertBytes = 0;
1075 free(alertName);
1076 return res;
1077}
JP Abgralldb7da582011-09-18 12:57:32 -07001078
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001079void BandwidthController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
1080 for (TetherStats& existing : statsList) {
1081 if (existing.addStatsIfMatch(stats)) {
1082 return;
1083 }
1084 }
1085 // No match. Insert a new interface pair.
1086 statsList.push_back(stats);
1087}
1088
JP Abgralldb7da582011-09-18 12:57:32 -07001089/*
1090 * Parse the ptks and bytes out of:
JP Abgrallbaeccc42013-06-25 09:44:10 -07001091 * Chain natctrl_tether_counters (4 references)
1092 * pkts bytes target prot opt in out source destination
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001093 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1094 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
1095 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
1096 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001097 * or:
1098 * Chain natctrl_tether_counters (0 references)
1099 * pkts bytes target prot opt in out source destination
1100 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
1101 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
1102 *
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001103 * It results in an error if invoked and no tethering counter rules exist. The constraint
1104 * helps detect complete parsing failure.
JP Abgralldb7da582011-09-18 12:57:32 -07001105 */
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001106int BandwidthController::addForwardChainStats(const TetherStats& filter,
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001107 TetherStatsList& statsList,
1108 const std::string& statsOutput,
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001109 std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -07001110 int res;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001111 std::string statsLine;
JP Abgralldb7da582011-09-18 12:57:32 -07001112 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
1113 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
1114 char rest[MAX_IPT_OUTPUT_LINE_LEN];
1115
JP Abgrallbaeccc42013-06-25 09:44:10 -07001116 TetherStats stats;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001117 const char *buffPtr;
JP Abgralldb7da582011-09-18 12:57:32 -07001118 int64_t packets, bytes;
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001119 int statsFound = 0;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001120
1121 bool filterPair = filter.intIface[0] && filter.extIface[0];
1122
1123 char *filterMsg = filter.getStatsLine();
1124 ALOGV("filter: %s", filterMsg);
1125 free(filterMsg);
1126
1127 stats = filter;
JP Abgralldb7da582011-09-18 12:57:32 -07001128
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001129 std::stringstream stream(statsOutput);
1130 while (std::getline(stream, statsLine, '\n')) {
1131 buffPtr = statsLine.c_str();
1132
JP Abgralldb7da582011-09-18 12:57:32 -07001133 /* Clean up, so a failed parse can still print info */
1134 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001135 if (strstr(buffPtr, "0.0.0.0")) {
1136 // IPv4 has -- indicating what to do with fragments...
1137 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1138 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
1139 &packets, &bytes, iface0, iface1, rest);
1140 } else {
1141 // ... but IPv6 does not.
1142 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
1143 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all %s %s ::/%s",
1144 &packets, &bytes, iface0, iface1, rest);
1145 }
SynergyDev7776cea2014-03-16 15:48:51 -07001146 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 -07001147 iface0, iface1, packets, bytes, rest, buffPtr);
JP Abgralla2a64f02011-11-11 20:36:16 -08001148 extraProcessingInfo += buffPtr;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001149 extraProcessingInfo += "\n";
JP Abgralla2a64f02011-11-11 20:36:16 -08001150
JP Abgralldb7da582011-09-18 12:57:32 -07001151 if (res != 5) {
1152 continue;
1153 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001154 /*
1155 * The following assumes that the 1st rule has in:extIface out:intIface,
1156 * which is what NatController sets up.
1157 * If not filtering, the 1st match rx, and sets up the pair for the tx side.
1158 */
1159 if (filter.intIface[0] && filter.extIface[0]) {
1160 if (filter.intIface == iface0 && filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001161 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 -07001162 stats.rxPackets = packets;
1163 stats.rxBytes = bytes;
1164 } else if (filter.intIface == iface1 && filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001165 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 -07001166 stats.txPackets = packets;
1167 stats.txBytes = bytes;
1168 }
1169 } else if (filter.intIface[0] || filter.extIface[0]) {
1170 if (filter.intIface == iface0 || filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001171 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 -07001172 stats.intIface = iface0;
1173 stats.extIface = iface1;
1174 stats.rxPackets = packets;
1175 stats.rxBytes = bytes;
1176 } else if (filter.intIface == iface1 || filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001177 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 -07001178 stats.intIface = iface1;
1179 stats.extIface = iface0;
1180 stats.txPackets = packets;
1181 stats.txBytes = bytes;
1182 }
1183 } else /* if (!filter.intFace[0] && !filter.extIface[0]) */ {
1184 if (!stats.intIface[0]) {
SynergyDev7776cea2014-03-16 15:48:51 -07001185 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 -07001186 stats.intIface = iface0;
1187 stats.extIface = iface1;
1188 stats.rxPackets = packets;
1189 stats.rxBytes = bytes;
1190 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001191 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 -07001192 stats.txPackets = packets;
1193 stats.txBytes = bytes;
1194 }
1195 }
1196 if (stats.rxBytes != -1 && stats.txBytes != -1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001197 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64" filterPair=%d", stats.rxBytes, stats.txBytes, filterPair);
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001198 addStats(statsList, stats);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001199 if (filterPair) {
JP Abgrallbaeccc42013-06-25 09:44:10 -07001200 return 0;
1201 } else {
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001202 statsFound++;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001203 stats = filter;
1204 }
JP Abgralldb7da582011-09-18 12:57:32 -07001205 }
1206 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001207
1208 /* It is always an error to find only one side of the stats. */
1209 /* It is an error to find nothing when not filtering. */
1210 if (((stats.rxBytes == -1) != (stats.txBytes == -1)) ||
1211 (!statsFound && !filterPair)) {
1212 return -1;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001213 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001214 return 0;
JP Abgralldb7da582011-09-18 12:57:32 -07001215}
1216
JP Abgrallbaeccc42013-06-25 09:44:10 -07001217char *BandwidthController::TetherStats::getStatsLine(void) const {
JP Abgralldb7da582011-09-18 12:57:32 -07001218 char *msg;
SynergyDev7776cea2014-03-16 15:48:51 -07001219 asprintf(&msg, "%s %s %" PRId64" %" PRId64" %" PRId64" %" PRId64, intIface.c_str(), extIface.c_str(),
JP Abgralldb7da582011-09-18 12:57:32 -07001220 rxBytes, rxPackets, txBytes, txPackets);
1221 return msg;
1222}
1223
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001224int BandwidthController::getTetherStats(SocketClient *cli, TetherStats& filter,
1225 std::string &extraProcessingInfo) {
1226 int res = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001227
1228 TetherStatsList statsList;
1229
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001230 for (const IptablesTarget target : {V4, V6}) {
1231 std::string statsString;
1232 res = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString);
1233 if (res != 0) {
1234 ALOGE("Failed to run %s err=%d", GET_TETHER_STATS_COMMAND.c_str(), res);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001235 return -1;
1236 }
1237
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001238 res = addForwardChainStats(filter, statsList, statsString, extraProcessingInfo);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001239 if (res != 0) {
1240 return res;
1241 }
1242 }
JP Abgralldb7da582011-09-18 12:57:32 -07001243
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001244 if (filter.intIface[0] && filter.extIface[0] && statsList.size() == 1) {
1245 cli->sendMsg(ResponseCode::TetheringStatsResult, statsList[0].getStatsLine(), false);
1246 } else {
1247 for (const auto& stats: statsList) {
1248 cli->sendMsg(ResponseCode::TetheringStatsListResult, stats.getStatsLine(), false);
1249 }
1250 if (res == 0) {
1251 cli->sendMsg(ResponseCode::CommandOkay, "Tethering stats list completed", false);
1252 }
1253 }
1254
JP Abgralldb7da582011-09-18 12:57:32 -07001255 return res;
1256}
JP Abgrall0e540ec2013-08-26 15:13:10 -07001257
1258void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001259 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
1260 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001261
1262 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001263 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
1264 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001265 return;
1266 }
1267 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001268 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001269}
1270
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001271void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
1272 std::stringstream stream(ruleList);
1273 std::string rule;
1274 std::vector<std::string> clearCommands = { "*filter" };
1275 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001276
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001277 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
1278 while (std::getline(stream, rule, '\n')) {
1279 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
1280 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
1281 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
1282
1283 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -07001284 continue;
1285 }
1286
Lorenzo Colitti3c272702017-04-26 15:48:13 +09001287 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001288 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +09001289 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001290 }
1291 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001292
1293 if (clearCommands.size() == 1) {
1294 // No rules found.
1295 return;
1296 }
1297
1298 clearCommands.push_back("COMMIT\n");
1299 iptablesRestoreFunction(V4V6, android::base::Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001300}