blob: 30a048aa9cd382d9cba9103c504eb6a8dae0e0e4 [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) {
JP Abgrall8a932722011-07-13 19:17:35 -0700832 const char *opFlag;
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900833 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700834
835 switch (op) {
836 case IptOpInsert:
837 opFlag = "-I";
838 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700839 default:
840 case IptOpDelete:
841 opFlag = "-D";
842 break;
843 }
844
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900845 // TODO: consider using an alternate template for the delete that does not include the --quota
846 // value. This code works because the --quota value is ignored by deletes
847 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT", bytes, alertName);
848 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT", bytes, alertName);
849 StringAppendF(&alertQuotaCmd, "COMMIT\n");
850
Lorenzo Colitti4773cb42017-04-27 14:03:25 +0900851 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrall8a932722011-07-13 19:17:35 -0700852}
853
JP Abgrallc6c67342011-10-07 16:28:54 -0700854int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700855 const char *opFlag;
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900856 std::string alertQuotaCmd = "*filter\n";
JP Abgrallc6c67342011-10-07 16:28:54 -0700857
858 switch (op) {
859 case IptOpInsert:
860 opFlag = "-I";
861 break;
JP Abgrallc6c67342011-10-07 16:28:54 -0700862 default:
863 case IptOpDelete:
864 opFlag = "-D";
865 break;
866 }
867
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900868 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD", bytes, alertName);
869 StringAppendF(&alertQuotaCmd, "COMMIT\n");
870
871 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700872}
873
874int BandwidthController::setGlobalAlert(int64_t bytes) {
875 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700876 int res = 0;
877
878 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000879 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700880 return -1;
881 }
882 if (globalAlertBytes) {
883 res = updateQuota(alertName, bytes);
884 } else {
885 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700886 if (globalAlertTetherCount) {
Steve Block3fb42e02011-10-20 11:55:56 +0100887 ALOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700888 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
889 }
JP Abgrall8a932722011-07-13 19:17:35 -0700890 }
891 globalAlertBytes = bytes;
892 return res;
893}
894
JP Abgrallc6c67342011-10-07 16:28:54 -0700895int BandwidthController::setGlobalAlertInForwardChain(void) {
896 const char *alertName = ALERT_GLOBAL_NAME;
897 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700898
JP Abgrallc6c67342011-10-07 16:28:54 -0700899 globalAlertTetherCount++;
Steve Block3fb42e02011-10-20 11:55:56 +0100900 ALOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700901
902 /*
903 * If there is no globalAlert active we are done.
904 * If there is an active globalAlert but this is not the 1st
905 * tether, we are also done.
906 */
907 if (!globalAlertBytes || globalAlertTetherCount != 1) {
908 return 0;
909 }
910
911 /* We only add the rule if this was the 1st tether added. */
912 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
913 return res;
914}
915
916int BandwidthController::removeGlobalAlert(void) {
917
918 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700919 int res = 0;
920
921 if (!globalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000922 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700923 return -1;
924 }
925 res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700926 if (globalAlertTetherCount) {
927 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
928 }
JP Abgrall8a932722011-07-13 19:17:35 -0700929 globalAlertBytes = 0;
930 return res;
931}
932
JP Abgrallc6c67342011-10-07 16:28:54 -0700933int BandwidthController::removeGlobalAlertInForwardChain(void) {
934 int res = 0;
935 const char *alertName = ALERT_GLOBAL_NAME;
936
937 if (!globalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000938 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700939 return -1;
940 }
941
942 globalAlertTetherCount--;
943 /*
944 * If there is no globalAlert active we are done.
945 * If there is an active globalAlert but there are more
946 * tethers, we are also done.
947 */
948 if (!globalAlertBytes || globalAlertTetherCount >= 1) {
949 return 0;
950 }
951
952 /* We only detete the rule if this was the last tether removed. */
953 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
954 return res;
955}
956
JP Abgrall8a932722011-07-13 19:17:35 -0700957int BandwidthController::setSharedAlert(int64_t bytes) {
958 if (!sharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000959 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700960 return -1;
961 }
962 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000963 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700964 return -1;
965 }
966 return setCostlyAlert("shared", bytes, &sharedAlertBytes);
967}
968
969int BandwidthController::removeSharedAlert(void) {
970 return removeCostlyAlert("shared", &sharedAlertBytes);
971}
972
973int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
974 std::list<QuotaInfo>::iterator it;
975
JP Abgrall69261cb2014-06-19 18:35:24 -0700976 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700977 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface);
978 return -1;
979 }
980
JP Abgrall8a932722011-07-13 19:17:35 -0700981 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000982 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700983 return -1;
984 }
985 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
986 if (it->ifaceName == iface)
987 break;
988 }
989
990 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000991 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700992 return -1;
993 }
994
995 return setCostlyAlert(iface, bytes, &it->alert);
996}
997
998int BandwidthController::removeInterfaceAlert(const char *iface) {
999 std::list<QuotaInfo>::iterator it;
1000
JP Abgrall69261cb2014-06-19 18:35:24 -07001001 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001002 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface);
1003 return -1;
1004 }
1005
JP Abgrall8a932722011-07-13 19:17:35 -07001006 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
1007 if (it->ifaceName == iface)
1008 break;
1009 }
1010
1011 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +00001012 ALOGE("No prior alert set for interface %s", iface);
JP Abgrall8a932722011-07-13 19:17:35 -07001013 return -1;
1014 }
1015
1016 return removeCostlyAlert(iface, &it->alert);
1017}
1018
1019int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
1020 char *alertQuotaCmd;
JP Abgrall109899b2013-02-12 19:20:13 -08001021 char *chainName;
JP Abgrall8a932722011-07-13 19:17:35 -07001022 int res = 0;
1023 char *alertName;
1024
JP Abgrall69261cb2014-06-19 18:35:24 -07001025 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001026 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName);
1027 return -1;
1028 }
1029
JP Abgrall8a932722011-07-13 19:17:35 -07001030 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001031 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -07001032 return -1;
1033 }
1034 asprintf(&alertName, "%sAlert", costName);
1035 if (*alertBytes) {
1036 res = updateQuota(alertName, *alertBytes);
1037 } else {
JP Abgrall7e51cde2013-07-03 13:33:05 -07001038 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall109899b2013-02-12 19:20:13 -08001039 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-A", chainName, bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001040 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001041 free(alertQuotaCmd);
JP Abgrall109899b2013-02-12 19:20:13 -08001042 free(chainName);
JP Abgrall8a932722011-07-13 19:17:35 -07001043 }
1044 *alertBytes = bytes;
1045 free(alertName);
1046 return res;
1047}
1048
1049int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
1050 char *alertQuotaCmd;
1051 char *chainName;
1052 char *alertName;
1053 int res = 0;
1054
JP Abgrall69261cb2014-06-19 18:35:24 -07001055 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001056 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName);
1057 return -1;
1058 }
1059
JP Abgrall8a932722011-07-13 19:17:35 -07001060 if (!*alertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001061 ALOGE("No prior alert set for %s alert", costName);
JP Abgrall8a932722011-07-13 19:17:35 -07001062 return -1;
1063 }
1064
Jesper Hanssona9d791f2012-04-27 13:54:27 +02001065 asprintf(&alertName, "%sAlert", costName);
JP Abgrall7e51cde2013-07-03 13:33:05 -07001066 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall92009c82013-02-06 18:01:24 -08001067 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001068 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001069 free(alertQuotaCmd);
1070 free(chainName);
1071
1072 *alertBytes = 0;
1073 free(alertName);
1074 return res;
1075}
JP Abgralldb7da582011-09-18 12:57:32 -07001076
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001077void BandwidthController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
1078 for (TetherStats& existing : statsList) {
1079 if (existing.addStatsIfMatch(stats)) {
1080 return;
1081 }
1082 }
1083 // No match. Insert a new interface pair.
1084 statsList.push_back(stats);
1085}
1086
JP Abgralldb7da582011-09-18 12:57:32 -07001087/*
1088 * Parse the ptks and bytes out of:
JP Abgrallbaeccc42013-06-25 09:44:10 -07001089 * Chain natctrl_tether_counters (4 references)
1090 * pkts bytes target prot opt in out source destination
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001091 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1092 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
1093 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
1094 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001095 * or:
1096 * Chain natctrl_tether_counters (0 references)
1097 * pkts bytes target prot opt in out source destination
1098 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
1099 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
1100 *
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001101 * It results in an error if invoked and no tethering counter rules exist. The constraint
1102 * helps detect complete parsing failure.
JP Abgralldb7da582011-09-18 12:57:32 -07001103 */
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001104int BandwidthController::addForwardChainStats(const TetherStats& filter,
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001105 TetherStatsList& statsList,
1106 const std::string& statsOutput,
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001107 std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -07001108 int res;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001109 std::string statsLine;
JP Abgralldb7da582011-09-18 12:57:32 -07001110 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
1111 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
1112 char rest[MAX_IPT_OUTPUT_LINE_LEN];
1113
JP Abgrallbaeccc42013-06-25 09:44:10 -07001114 TetherStats stats;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001115 const char *buffPtr;
JP Abgralldb7da582011-09-18 12:57:32 -07001116 int64_t packets, bytes;
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001117 int statsFound = 0;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001118
1119 bool filterPair = filter.intIface[0] && filter.extIface[0];
1120
1121 char *filterMsg = filter.getStatsLine();
1122 ALOGV("filter: %s", filterMsg);
1123 free(filterMsg);
1124
1125 stats = filter;
JP Abgralldb7da582011-09-18 12:57:32 -07001126
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001127 std::stringstream stream(statsOutput);
1128 while (std::getline(stream, statsLine, '\n')) {
1129 buffPtr = statsLine.c_str();
1130
JP Abgralldb7da582011-09-18 12:57:32 -07001131 /* Clean up, so a failed parse can still print info */
1132 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001133 if (strstr(buffPtr, "0.0.0.0")) {
1134 // IPv4 has -- indicating what to do with fragments...
1135 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1136 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
1137 &packets, &bytes, iface0, iface1, rest);
1138 } else {
1139 // ... but IPv6 does not.
1140 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
1141 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all %s %s ::/%s",
1142 &packets, &bytes, iface0, iface1, rest);
1143 }
SynergyDev7776cea2014-03-16 15:48:51 -07001144 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 -07001145 iface0, iface1, packets, bytes, rest, buffPtr);
JP Abgralla2a64f02011-11-11 20:36:16 -08001146 extraProcessingInfo += buffPtr;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001147 extraProcessingInfo += "\n";
JP Abgralla2a64f02011-11-11 20:36:16 -08001148
JP Abgralldb7da582011-09-18 12:57:32 -07001149 if (res != 5) {
1150 continue;
1151 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001152 /*
1153 * The following assumes that the 1st rule has in:extIface out:intIface,
1154 * which is what NatController sets up.
1155 * If not filtering, the 1st match rx, and sets up the pair for the tx side.
1156 */
1157 if (filter.intIface[0] && filter.extIface[0]) {
1158 if (filter.intIface == iface0 && filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001159 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 -07001160 stats.rxPackets = packets;
1161 stats.rxBytes = bytes;
1162 } else if (filter.intIface == iface1 && filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001163 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 -07001164 stats.txPackets = packets;
1165 stats.txBytes = bytes;
1166 }
1167 } else if (filter.intIface[0] || filter.extIface[0]) {
1168 if (filter.intIface == iface0 || filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001169 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 -07001170 stats.intIface = iface0;
1171 stats.extIface = iface1;
1172 stats.rxPackets = packets;
1173 stats.rxBytes = bytes;
1174 } else if (filter.intIface == iface1 || filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001175 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 -07001176 stats.intIface = iface1;
1177 stats.extIface = iface0;
1178 stats.txPackets = packets;
1179 stats.txBytes = bytes;
1180 }
1181 } else /* if (!filter.intFace[0] && !filter.extIface[0]) */ {
1182 if (!stats.intIface[0]) {
SynergyDev7776cea2014-03-16 15:48:51 -07001183 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 -07001184 stats.intIface = iface0;
1185 stats.extIface = iface1;
1186 stats.rxPackets = packets;
1187 stats.rxBytes = bytes;
1188 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001189 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 -07001190 stats.txPackets = packets;
1191 stats.txBytes = bytes;
1192 }
1193 }
1194 if (stats.rxBytes != -1 && stats.txBytes != -1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001195 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64" filterPair=%d", stats.rxBytes, stats.txBytes, filterPair);
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001196 addStats(statsList, stats);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001197 if (filterPair) {
JP Abgrallbaeccc42013-06-25 09:44:10 -07001198 return 0;
1199 } else {
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001200 statsFound++;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001201 stats = filter;
1202 }
JP Abgralldb7da582011-09-18 12:57:32 -07001203 }
1204 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001205
1206 /* It is always an error to find only one side of the stats. */
1207 /* It is an error to find nothing when not filtering. */
1208 if (((stats.rxBytes == -1) != (stats.txBytes == -1)) ||
1209 (!statsFound && !filterPair)) {
1210 return -1;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001211 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001212 return 0;
JP Abgralldb7da582011-09-18 12:57:32 -07001213}
1214
JP Abgrallbaeccc42013-06-25 09:44:10 -07001215char *BandwidthController::TetherStats::getStatsLine(void) const {
JP Abgralldb7da582011-09-18 12:57:32 -07001216 char *msg;
SynergyDev7776cea2014-03-16 15:48:51 -07001217 asprintf(&msg, "%s %s %" PRId64" %" PRId64" %" PRId64" %" PRId64, intIface.c_str(), extIface.c_str(),
JP Abgralldb7da582011-09-18 12:57:32 -07001218 rxBytes, rxPackets, txBytes, txPackets);
1219 return msg;
1220}
1221
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001222int BandwidthController::getTetherStats(SocketClient *cli, TetherStats& filter,
1223 std::string &extraProcessingInfo) {
1224 int res = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001225
1226 TetherStatsList statsList;
1227
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001228 for (const IptablesTarget target : {V4, V6}) {
1229 std::string statsString;
1230 res = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString);
1231 if (res != 0) {
1232 ALOGE("Failed to run %s err=%d", GET_TETHER_STATS_COMMAND.c_str(), res);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001233 return -1;
1234 }
1235
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001236 res = addForwardChainStats(filter, statsList, statsString, extraProcessingInfo);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001237 if (res != 0) {
1238 return res;
1239 }
1240 }
JP Abgralldb7da582011-09-18 12:57:32 -07001241
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001242 if (filter.intIface[0] && filter.extIface[0] && statsList.size() == 1) {
1243 cli->sendMsg(ResponseCode::TetheringStatsResult, statsList[0].getStatsLine(), false);
1244 } else {
1245 for (const auto& stats: statsList) {
1246 cli->sendMsg(ResponseCode::TetheringStatsListResult, stats.getStatsLine(), false);
1247 }
1248 if (res == 0) {
1249 cli->sendMsg(ResponseCode::CommandOkay, "Tethering stats list completed", false);
1250 }
1251 }
1252
JP Abgralldb7da582011-09-18 12:57:32 -07001253 return res;
1254}
JP Abgrall0e540ec2013-08-26 15:13:10 -07001255
1256void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001257 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
1258 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001259
1260 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001261 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
1262 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001263 return;
1264 }
1265 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001266 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001267}
1268
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001269void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
1270 std::stringstream stream(ruleList);
1271 std::string rule;
1272 std::vector<std::string> clearCommands = { "*filter" };
1273 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001274
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001275 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
1276 while (std::getline(stream, rule, '\n')) {
1277 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
1278 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
1279 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
1280
1281 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -07001282 continue;
1283 }
1284
Lorenzo Colitti3c272702017-04-26 15:48:13 +09001285 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001286 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +09001287 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001288 }
1289 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001290
1291 if (clearCommands.size() == 1) {
1292 // No rules found.
1293 return;
1294 }
1295
1296 clearCommands.push_back("COMMIT\n");
1297 iptablesRestoreFunction(V4V6, android::base::Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001298}