blob: c8e8d14c730b8dd7d59e8c7742e2af219fbcdb2e [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 */
SynergyDev7776cea2014-03-16 15:48:51 -070060#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s"
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 Colitti7618ccb2016-03-18 12:36:03 +090071namespace {
72
73const char ALERT_GLOBAL_NAME[] = "globalAlert";
74const int MAX_CMD_ARGS = 32;
75const int MAX_CMD_LEN = 1024;
76const int MAX_IFACENAME_LEN = 64;
77const int MAX_IPT_OUTPUT_LINE_LEN = 256;
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090078const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colittice6748a2017-02-02 01:34:33 +090079const std::string GET_TETHER_STATS_COMMAND = android::base::StringPrintf(
80 "*filter\n"
81 "-nvx -L %s\n"
82 "COMMIT\n", NatController::LOCAL_TETHER_COUNTERS_CHAIN);
83
JP Abgralldb7da582011-09-18 12:57:32 -070084
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070085/**
86 * Some comments about the rules:
87 * * Ordering
88 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070089 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070090 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070091 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070092 *
93 * * global quota vs per interface quota
94 * - global quota for all costly interfaces uses a single costly chain:
95 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -070096 * iptables -N bw_costly_shared
97 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
98 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
99 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -0700100 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -0700101 * iptables -A bw_costly_shared --jump bw_penalty_box
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900102 * iptables -A bw_penalty_box --jump bw_happy_box
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900103 * iptables -A bw_happy_box --jump bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700104 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700105 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700106 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
107 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700108 *
109 * - quota per interface. This is achieve by having "costly" chains per quota.
110 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700111 * iptables -N bw_costly_iface0
112 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
113 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
114 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -0700115 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -0700116 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700117 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900118 * * Penalty box, happy box and data saver.
119 * - bw_penalty box is a blacklist of apps that are rejected.
120 * - bw_happy_box is a whitelist of apps. It always includes all system apps
121 * - bw_data_saver implements data usage restrictions.
122 * - Via the UI the user can add and remove apps from the whitelist and
123 * blacklist, and turn on/off data saver.
124 * - The blacklist takes precedence over the whitelist and the whitelist
125 * takes precedence over data saver.
126 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700127 * * bw_penalty_box handling:
128 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900129 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700130 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700131 * --jump REJECT --reject-with icmp-port-unreachable
132 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700133 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900134 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700135 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700136 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700137 * --jump RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900138 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900139 * * bw_data_saver handling:
140 * - The bw_data_saver comes after the happy box.
141 * Enable data saver:
142 * iptables -R 1 bw_data_saver --jump REJECT --reject-with icmp-port-unreachable
143 * Disable data saver:
144 * iptables -R 1 bw_data_saver --jump RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700145 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900146
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900147const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900148const std::string DATA_SAVER_ENABLE_COMMAND = "-R bw_data_saver 1";
149const std::string HAPPY_BOX_WHITELIST_COMMAND = android::base::StringPrintf(
150 "-I bw_happy_box -m owner --uid-owner %d-%d --jump RETURN", 0, MAX_SYSTEM_UID);
151
152static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700153 /*
154 * Cleanup rules.
JP Abgrall7e51cde2013-07-03 13:33:05 -0700155 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
JP Abgrall0031cea2012-04-17 16:38:23 -0700156 * to allow coexistance.
JP Abgrall39f8f242011-06-29 19:21:58 -0700157 */
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900158 "*filter",
159 ":bw_INPUT -",
160 ":bw_OUTPUT -",
161 ":bw_FORWARD -",
162 ":bw_happy_box -",
163 ":bw_penalty_box -",
164 ":bw_data_saver -",
165 ":bw_costly_shared -",
166 "COMMIT",
167 "*raw",
168 ":bw_raw_PREROUTING -",
169 "COMMIT",
170 "*mangle",
171 ":bw_mangle_POSTROUTING -",
172 COMMIT_AND_CLOSE
JP Abgrall0031cea2012-04-17 16:38:23 -0700173};
174
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900175static const std::vector<std::string> IPT_BASIC_ACCOUNTING_COMMANDS = {
176 "*filter",
JP Abgrall0031cea2012-04-17 16:38:23 -0700177 "-A bw_INPUT -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall0031cea2012-04-17 16:38:23 -0700178 "-A bw_OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900179 "-A bw_costly_shared --jump bw_penalty_box",
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900180 "-A bw_penalty_box --jump bw_happy_box",
181 "-A bw_happy_box --jump bw_data_saver",
182 "-A bw_data_saver -j RETURN",
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900183 HAPPY_BOX_WHITELIST_COMMAND,
184 "COMMIT",
185
186 "*raw",
187 "-A bw_raw_PREROUTING -m owner --socket-exists", /* This is a tracking rule. */
188 "COMMIT",
189
190 "*mangle",
191 "-A bw_mangle_POSTROUTING -m owner --socket-exists", /* This is a tracking rule. */
192 COMMIT_AND_CLOSE
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900193};
194
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900195
196} // namespace
197
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700198BandwidthController::BandwidthController(void) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700199}
200
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700201int BandwidthController::runIpxtablesCmd(const char *cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700202 IptFailureLog failureHandling) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700203 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700204
Steve Block3fb42e02011-10-20 11:55:56 +0100205 ALOGV("runIpxtablesCmd(cmd=%s)", cmd);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700206 res |= runIptablesCmd(cmd, jumpHandling, IptIpV4, failureHandling);
207 res |= runIptablesCmd(cmd, jumpHandling, IptIpV6, failureHandling);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700208 return res;
209}
210
JP Abgrall26e0d492011-06-24 19:21:51 -0700211int BandwidthController::StrncpyAndCheck(char *buffer, const char *src, size_t buffSize) {
212
213 memset(buffer, '\0', buffSize); // strncpy() is not filling leftover with '\0'
214 strncpy(buffer, src, buffSize);
215 return buffer[buffSize - 1];
216}
217
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700218int BandwidthController::runIptablesCmd(const char *cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700219 IptIpVer iptVer, IptFailureLog failureHandling) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700220 char buffer[MAX_CMD_LEN];
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700221 const char *argv[MAX_CMD_ARGS];
JP Abgrall26e0d492011-06-24 19:21:51 -0700222 int argc = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700223 char *next = buffer;
224 char *tmp;
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700225 int res;
Rom Lemarchand14150212013-01-24 10:01:04 -0800226 int status = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700227
JP Abgrall0dad7c22011-06-24 11:58:14 -0700228 std::string fullCmd = cmd;
JP Abgrall26e0d492011-06-24 19:21:51 -0700229
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700230 switch (jumpHandling) {
231 case IptJumpReject:
JP Abgrall340d5cc2013-06-28 17:06:00 -0700232 /*
233 * Must be carefull what one rejects with, as uper layer protocols will just
234 * keep on hammering the device until the number of retries are done.
235 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
236 */
237 fullCmd += " --jump REJECT";
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700238 break;
239 case IptJumpReturn:
240 fullCmd += " --jump RETURN";
241 break;
242 case IptJumpNoAdd:
243 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700244 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700245
Paul Jensen94b2ab92015-08-04 10:35:05 -0400246 fullCmd.insert(0, " -w ");
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700247 fullCmd.insert(0, iptVer == IptIpV4 ? IPTABLES_PATH : IP6TABLES_PATH);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700248
Rom Lemarchand14150212013-01-24 10:01:04 -0800249 if (StrncpyAndCheck(buffer, fullCmd.c_str(), sizeof(buffer))) {
250 ALOGE("iptables command too long");
251 return -1;
252 }
253
254 argc = 0;
255 while ((tmp = strsep(&next, " "))) {
256 argv[argc++] = tmp;
257 if (argc >= MAX_CMD_ARGS) {
258 ALOGE("iptables argument overflow");
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700259 return -1;
260 }
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700261 }
Rom Lemarchand14150212013-01-24 10:01:04 -0800262
263 argv[argc] = NULL;
Lorenzo Colitti86a47982016-03-18 17:52:25 +0900264 res = execFunction(argc, (char **)argv, &status, false,
Rom Lemarchand14150212013-01-24 10:01:04 -0800265 failureHandling == IptFailShow);
JP Abgrallc8dc63b2013-02-13 16:30:00 -0800266 res = res || !WIFEXITED(status) || WEXITSTATUS(status);
267 if (res && failureHandling == IptFailShow) {
268 ALOGE("runIptablesCmd(): res=%d status=%d failed %s", res, status,
269 fullCmd.c_str());
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700270 }
271 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700272}
273
JP Abgrall0e540ec2013-08-26 15:13:10 -0700274void BandwidthController::flushCleanTables(bool doClean) {
275 /* Flush and remove the bw_costly_<iface> tables */
276 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700277
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900278 std::string commands = android::base::Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900279 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700280}
JP Abgrall0031cea2012-04-17 16:38:23 -0700281
JP Abgrall0e540ec2013-08-26 15:13:10 -0700282int BandwidthController::setupIptablesHooks(void) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700283 /* flush+clean is allowed to fail */
284 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700285 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700286}
287
288int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrall0031cea2012-04-17 16:38:23 -0700289 char value[PROPERTY_VALUE_MAX];
290
291 if (!force) {
292 property_get("persist.bandwidth.enable", value, "1");
293 if (!strcmp(value, "0"))
294 return 0;
295 }
JP Abgrall8a932722011-07-13 19:17:35 -0700296
JP Abgralldb7da582011-09-18 12:57:32 -0700297 /* Let's pretend we started from scratch ... */
JP Abgrall8a932722011-07-13 19:17:35 -0700298 sharedQuotaIfaces.clear();
299 quotaIfaces.clear();
JP Abgralldb7da582011-09-18 12:57:32 -0700300 globalAlertBytes = 0;
JP Abgrallc6c67342011-10-07 16:28:54 -0700301 globalAlertTetherCount = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700302 sharedQuotaBytes = sharedAlertBytes = 0;
303
JP Abgrall0e540ec2013-08-26 15:13:10 -0700304 flushCleanTables(false);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900305 std::string commands = android::base::Join(IPT_BASIC_ACCOUNTING_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900306 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700307}
308
309int BandwidthController::disableBandwidthControl(void) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700310
311 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700312 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700313}
314
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900315int BandwidthController::enableDataSaver(bool enable) {
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900316 return runIpxtablesCmd(DATA_SAVER_ENABLE_COMMAND.c_str(),
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900317 enable ? IptJumpReject : IptJumpReturn, IptFailShow);
318}
319
JP Abgrall8a932722011-07-13 19:17:35 -0700320int BandwidthController::runCommands(int numCommands, const char *commands[],
321 RunCmdErrHandling cmdErrHandling) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700322 int res = 0;
JP Abgrallad729ac2012-04-24 23:27:44 -0700323 IptFailureLog failureLogging = IptFailShow;
324 if (cmdErrHandling == RunCmdFailureOk) {
325 failureLogging = IptFailHide;
326 }
Steve Block3fb42e02011-10-20 11:55:56 +0100327 ALOGV("runCommands(): %d commands", numCommands);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700328 for (int cmdNum = 0; cmdNum < numCommands; cmdNum++) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700329 res = runIpxtablesCmd(commands[cmdNum], IptJumpNoAdd, failureLogging);
JP Abgrall0031cea2012-04-17 16:38:23 -0700330 if (res && cmdErrHandling != RunCmdFailureOk)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700331 return res;
332 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700333 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700334}
335
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700336std::string BandwidthController::makeIptablesSpecialAppCmd(IptOp op, int uid, const char *chain) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700337 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700338 char *buff;
339 const char *opFlag;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700340
341 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700342 case IptOpInsert:
343 opFlag = "-I";
344 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800345 case IptOpAppend:
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700346 ALOGE("Append op not supported for %s uids", chain);
347 res = "";
348 return res;
JP Abgrall109899b2013-02-12 19:20:13 -0800349 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700350 case IptOpReplace:
351 opFlag = "-R";
352 break;
353 default:
354 case IptOpDelete:
355 opFlag = "-D";
356 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700357 }
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700358 asprintf(&buff, "%s %s -m owner --uid-owner %d", opFlag, chain, uid);
JP Abgrall8a932722011-07-13 19:17:35 -0700359 res = buff;
360 free(buff);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700361 return res;
362}
363
364int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700365 return manipulateNaughtyApps(numUids, appUids, SpecialAppOpAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700366}
367
368int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700369 return manipulateNaughtyApps(numUids, appUids, SpecialAppOpRemove);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700370}
371
JP Abgralle4788732013-07-02 20:28:45 -0700372int BandwidthController::addNiceApps(int numUids, char *appUids[]) {
373 return manipulateNiceApps(numUids, appUids, SpecialAppOpAdd);
374}
375
376int BandwidthController::removeNiceApps(int numUids, char *appUids[]) {
377 return manipulateNiceApps(numUids, appUids, SpecialAppOpRemove);
378}
379
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700380int BandwidthController::manipulateNaughtyApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
Lorenzo Colittib1f05572016-03-18 11:55:56 +0900381 return manipulateSpecialApps(numUids, appStrUids, "bw_penalty_box", IptJumpReject, appOp);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700382}
383
JP Abgralle4788732013-07-02 20:28:45 -0700384int BandwidthController::manipulateNiceApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
Lorenzo Colittib1f05572016-03-18 11:55:56 +0900385 return manipulateSpecialApps(numUids, appStrUids, "bw_happy_box", IptJumpReturn, appOp);
JP Abgralle4788732013-07-02 20:28:45 -0700386}
387
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700388
389int BandwidthController::manipulateSpecialApps(int numUids, char *appStrUids[],
390 const char *chain,
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700391 IptJumpOp jumpHandling, SpecialAppOp appOp) {
392
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700393 int uidNum;
JP Abgrall26e0d492011-06-24 19:21:51 -0700394 const char *failLogTemplate;
395 IptOp op;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700396 int appUids[numUids];
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700397 std::string iptCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700398
JP Abgrall26e0d492011-06-24 19:21:51 -0700399 switch (appOp) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700400 case SpecialAppOpAdd:
JP Abgrall8a932722011-07-13 19:17:35 -0700401 op = IptOpInsert;
JP Abgrallaf476f72013-07-03 12:23:55 -0700402 failLogTemplate = "Failed to add app uid %s(%d) to %s.";
JP Abgrall8a932722011-07-13 19:17:35 -0700403 break;
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700404 case SpecialAppOpRemove:
JP Abgrall8a932722011-07-13 19:17:35 -0700405 op = IptOpDelete;
JP Abgrallaf476f72013-07-03 12:23:55 -0700406 failLogTemplate = "Failed to delete app uid %s(%d) from %s box.";
JP Abgrall8a932722011-07-13 19:17:35 -0700407 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700408 default:
409 ALOGE("Unexpected app Op %d", appOp);
410 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700411 }
412
413 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrallaf476f72013-07-03 12:23:55 -0700414 char *end;
415 appUids[uidNum] = strtoul(appStrUids[uidNum], &end, 0);
416 if (*end || !*appStrUids[uidNum]) {
417 ALOGE(failLogTemplate, appStrUids[uidNum], appUids[uidNum], chain);
JP Abgrall26e0d492011-06-24 19:21:51 -0700418 goto fail_parse;
419 }
420 }
JP Abgrall26e0d492011-06-24 19:21:51 -0700421
422 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrallb1d24092012-04-27 01:02:31 -0700423 int uid = appUids[uidNum];
JP Abgrallb1d24092012-04-27 01:02:31 -0700424
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700425 iptCmd = makeIptablesSpecialAppCmd(op, uid, chain);
426 if (runIpxtablesCmd(iptCmd.c_str(), jumpHandling)) {
JP Abgrallaf476f72013-07-03 12:23:55 -0700427 ALOGE(failLogTemplate, appStrUids[uidNum], uid, chain);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700428 goto fail_with_uidNum;
429 }
430 }
431 return 0;
432
JP Abgrall26e0d492011-06-24 19:21:51 -0700433fail_with_uidNum:
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700434 /* Try to remove the uid that failed in any case*/
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700435 iptCmd = makeIptablesSpecialAppCmd(IptOpDelete, appUids[uidNum], chain);
436 runIpxtablesCmd(iptCmd.c_str(), jumpHandling);
JP Abgrall26e0d492011-06-24 19:21:51 -0700437fail_parse:
438 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700439}
440
JP Abgrall26e0d492011-06-24 19:21:51 -0700441std::string BandwidthController::makeIptablesQuotaCmd(IptOp op, const char *costName, int64_t quota) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700442 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700443 char *buff;
444 const char *opFlag;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700445
SynergyDev7776cea2014-03-16 15:48:51 -0700446 ALOGV("makeIptablesQuotaCmd(%d, %" PRId64")", op, quota);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700447
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700448 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700449 case IptOpInsert:
450 opFlag = "-I";
451 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800452 case IptOpAppend:
453 opFlag = "-A";
454 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700455 case IptOpReplace:
456 opFlag = "-R";
457 break;
458 default:
459 case IptOpDelete:
460 opFlag = "-D";
461 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700462 }
JP Abgrall8a932722011-07-13 19:17:35 -0700463
JP Abgrallbfa74662011-06-29 19:23:04 -0700464 // The requried IP version specific --jump REJECT ... will be added later.
SynergyDev7776cea2014-03-16 15:48:51 -0700465 asprintf(&buff, "%s bw_costly_%s -m quota2 ! --quota %" PRId64" --name %s", opFlag, costName, quota,
JP Abgrall8a932722011-07-13 19:17:35 -0700466 costName);
467 res = buff;
468 free(buff);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700469 return res;
470}
471
JP Abgrall26e0d492011-06-24 19:21:51 -0700472int BandwidthController::prepCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700473 char cmd[MAX_CMD_LEN];
JP Abgrall0031cea2012-04-17 16:38:23 -0700474 int res = 0, res1, res2;
JP Abgrall8a932722011-07-13 19:17:35 -0700475 int ruleInsertPos = 1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700476 std::string costString;
477 const char *costCString;
478
JP Abgrall0dad7c22011-06-24 11:58:14 -0700479 /* The "-N costly" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700480 switch (quotaType) {
481 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700482 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700483 costString += ifn;
484 costCString = costString.c_str();
JP Abgrall0031cea2012-04-17 16:38:23 -0700485 /*
JP Abgrall7e51cde2013-07-03 13:33:05 -0700486 * Flush the bw_costly_<iface> is allowed to fail in case it didn't exist.
JP Abgrall0031cea2012-04-17 16:38:23 -0700487 * Creating a new one is allowed to fail in case it existed.
488 * This helps with netd restarts.
489 */
490 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700491 res1 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700492 snprintf(cmd, sizeof(cmd), "-N %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700493 res2 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700494 res = (res1 && res2) || (!res1 && !res2);
495
JP Abgrall7e51cde2013-07-03 13:33:05 -0700496 snprintf(cmd, sizeof(cmd), "-A %s -j bw_penalty_box", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700497 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall26e0d492011-06-24 19:21:51 -0700498 break;
499 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700500 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700501 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700502 default:
503 ALOGE("Unexpected quotatype %d", quotaType);
504 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700505 }
506
JP Abgrall8a932722011-07-13 19:17:35 -0700507 if (globalAlertBytes) {
508 /* The alert rule comes 1st */
509 ruleInsertPos = 2;
510 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700511
512 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700513 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700514
515 snprintf(cmd, sizeof(cmd), "-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700516 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall0031cea2012-04-17 16:38:23 -0700517
518 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700519 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700520
521 snprintf(cmd, sizeof(cmd), "-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700522 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900523
524 snprintf(cmd, sizeof(cmd), "-D bw_FORWARD -o %s --jump %s", ifn, costCString);
525 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
526 snprintf(cmd, sizeof(cmd), "-A bw_FORWARD -o %s --jump %s", ifn, costCString);
527 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
528
JP Abgrall0dad7c22011-06-24 11:58:14 -0700529 return res;
530}
531
JP Abgrall26e0d492011-06-24 19:21:51 -0700532int BandwidthController::cleanupCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700533 char cmd[MAX_CMD_LEN];
534 int res = 0;
535 std::string costString;
536 const char *costCString;
537
JP Abgrall26e0d492011-06-24 19:21:51 -0700538 switch (quotaType) {
539 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700540 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700541 costString += ifn;
542 costCString = costString.c_str();
JP Abgrall26e0d492011-06-24 19:21:51 -0700543 break;
544 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700545 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700546 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700547 default:
548 ALOGE("Unexpected quotatype %d", quotaType);
549 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700550 }
551
JP Abgrall0031cea2012-04-17 16:38:23 -0700552 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700553 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900554 for (const auto tableName : {LOCAL_OUTPUT, LOCAL_FORWARD}) {
555 snprintf(cmd, sizeof(cmd), "-D %s -o %s --jump %s", tableName, ifn, costCString);
556 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
557 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700558
JP Abgrall7e51cde2013-07-03 13:33:05 -0700559 /* The "-N bw_costly_shared" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700560 if (quotaType == QuotaUnique) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700561 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700562 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgralla9f802c2011-06-29 15:46:45 -0700563 snprintf(cmd, sizeof(cmd), "-X %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700564 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700565 }
566 return res;
567}
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700568
JP Abgrall0dad7c22011-06-24 11:58:14 -0700569int BandwidthController::setInterfaceSharedQuota(const char *iface, int64_t maxBytes) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700570 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700571 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700572 std::string quotaCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700573 std::string ifaceName;
574 ;
JP Abgrallbfa74662011-06-29 19:23:04 -0700575 const char *costName = "shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700576 std::list<std::string>::iterator it;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700577
JP Abgrall8a932722011-07-13 19:17:35 -0700578 if (!maxBytes) {
579 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000580 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700581 return -1;
582 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700583 if (!isIfaceName(iface))
584 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700585 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000586 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700587 return -1;
588 }
589 ifaceName = ifn;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700590
591 if (maxBytes == -1) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700592 return removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700593 }
594
595 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700596 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
597 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700598 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700599 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700600
JP Abgrall0dad7c22011-06-24 11:58:14 -0700601 if (it == sharedQuotaIfaces.end()) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700602 res |= prepCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700603 if (sharedQuotaIfaces.empty()) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700604 quotaCmd = makeIptablesQuotaCmd(IptOpInsert, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700605 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700606 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000607 ALOGE("Failed set quota rule");
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700608 goto fail;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700609 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700610 sharedQuotaBytes = maxBytes;
611 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700612 sharedQuotaIfaces.push_front(ifaceName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700613
614 }
615
616 if (maxBytes != sharedQuotaBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700617 res |= updateQuota(costName, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700618 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000619 ALOGE("Failed update quota for %s", costName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700620 goto fail;
621 }
622 sharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700623 }
624 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700625
626 fail:
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700627 /*
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700628 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
629 * rules in the kernel to see which ones need cleaning up.
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700630 * For now callers needs to choose if they want to "ndc bandwidth enable"
631 * which resets everything.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700632 */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700633 removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700634 return -1;
635}
636
JP Abgrall8a932722011-07-13 19:17:35 -0700637/* It will also cleanup any shared alerts */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700638int BandwidthController::removeInterfaceSharedQuota(const char *iface) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700639 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700640 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700641 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700642 std::list<std::string>::iterator it;
JP Abgrallbfa74662011-06-29 19:23:04 -0700643 const char *costName = "shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700644
JP Abgrall69261cb2014-06-19 18:35:24 -0700645 if (!isIfaceName(iface))
646 return -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700647 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000648 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700649 return -1;
650 }
JP Abgrall8a932722011-07-13 19:17:35 -0700651 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700652
JP Abgrall0dad7c22011-06-24 11:58:14 -0700653 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
654 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700655 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700656 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700657 if (it == sharedQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000658 ALOGE("No such iface %s to delete", ifn);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700659 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700660 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700661
JP Abgrall26e0d492011-06-24 19:21:51 -0700662 res |= cleanupCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700663 sharedQuotaIfaces.erase(it);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700664
JP Abgrall0dad7c22011-06-24 11:58:14 -0700665 if (sharedQuotaIfaces.empty()) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700666 std::string quotaCmd;
JP Abgrallbfa74662011-06-29 19:23:04 -0700667 quotaCmd = makeIptablesQuotaCmd(IptOpDelete, costName, sharedQuotaBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700668 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall8a932722011-07-13 19:17:35 -0700669 sharedQuotaBytes = 0;
670 if (sharedAlertBytes) {
671 removeSharedAlert();
672 sharedAlertBytes = 0;
673 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700674 }
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700675 return res;
676}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700677
678int BandwidthController::setInterfaceQuota(const char *iface, int64_t maxBytes) {
679 char ifn[MAX_IFACENAME_LEN];
680 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700681 std::string ifaceName;
682 const char *costName;
683 std::list<QuotaInfo>::iterator it;
684 std::string quotaCmd;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700685
JP Abgrall69261cb2014-06-19 18:35:24 -0700686 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700687 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700688
JP Abgrall8a932722011-07-13 19:17:35 -0700689 if (!maxBytes) {
690 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000691 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700692 return -1;
693 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700694 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700695 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700696 }
697
JP Abgrall8a932722011-07-13 19:17:35 -0700698 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000699 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700700 return -1;
701 }
702 ifaceName = ifn;
703 costName = iface;
704
JP Abgrall0dad7c22011-06-24 11:58:14 -0700705 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700706 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700707 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700708 break;
709 }
710
711 if (it == quotaIfaces.end()) {
JP Abgralle4788732013-07-02 20:28:45 -0700712 /* Preparing the iface adds a penalty/happy box check */
JP Abgrall26e0d492011-06-24 19:21:51 -0700713 res |= prepCostlyIface(ifn, QuotaUnique);
JP Abgrallbaeccc42013-06-25 09:44:10 -0700714 /*
JP Abgralle4788732013-07-02 20:28:45 -0700715 * The rejecting quota limit should go after the penalty/happy box checks
JP Abgrallbaeccc42013-06-25 09:44:10 -0700716 * or else a naughty app could just eat up the quota.
717 * So we append here.
718 */
JP Abgrall109899b2013-02-12 19:20:13 -0800719 quotaCmd = makeIptablesQuotaCmd(IptOpAppend, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700720 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700721 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000722 ALOGE("Failed set quota rule");
JP Abgrall0dad7c22011-06-24 11:58:14 -0700723 goto fail;
724 }
725
JP Abgrall8a932722011-07-13 19:17:35 -0700726 quotaIfaces.push_front(QuotaInfo(ifaceName, maxBytes, 0));
JP Abgrall0dad7c22011-06-24 11:58:14 -0700727
728 } else {
JP Abgrall8a932722011-07-13 19:17:35 -0700729 res |= updateQuota(costName, maxBytes);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700730 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000731 ALOGE("Failed update quota for %s", iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700732 goto fail;
733 }
JP Abgrall8a932722011-07-13 19:17:35 -0700734 it->quota = maxBytes;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700735 }
736 return 0;
737
738 fail:
739 /*
740 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
741 * rules in the kernel to see which ones need cleaning up.
742 * For now callers needs to choose if they want to "ndc bandwidth enable"
743 * which resets everything.
744 */
745 removeInterfaceSharedQuota(ifn);
746 return -1;
747}
748
JP Abgrall8a932722011-07-13 19:17:35 -0700749int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
750 return getInterfaceQuota("shared", bytes);
751}
752
753int BandwidthController::getInterfaceQuota(const char *costName, int64_t *bytes) {
754 FILE *fp;
755 char *fname;
756 int scanRes;
757
JP Abgrall69261cb2014-06-19 18:35:24 -0700758 if (!isIfaceName(costName))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700759 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700760
JP Abgrall8a932722011-07-13 19:17:35 -0700761 asprintf(&fname, "/proc/net/xt_quota/%s", costName);
Nick Kralevich53ea9ca2015-01-31 13:54:00 -0800762 fp = fopen(fname, "re");
JP Abgrall8a932722011-07-13 19:17:35 -0700763 free(fname);
764 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000765 ALOGE("Reading quota %s failed (%s)", costName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700766 return -1;
767 }
Mark Salyzynca0b5e22014-03-26 14:15:03 -0700768 scanRes = fscanf(fp, "%" SCNd64, bytes);
SynergyDev7776cea2014-03-16 15:48:51 -0700769 ALOGV("Read quota res=%d bytes=%" PRId64, scanRes, *bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700770 fclose(fp);
771 return scanRes == 1 ? 0 : -1;
772}
773
JP Abgrall0dad7c22011-06-24 11:58:14 -0700774int BandwidthController::removeInterfaceQuota(const char *iface) {
775
776 char ifn[MAX_IFACENAME_LEN];
777 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700778 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700779 std::list<QuotaInfo>::iterator it;
JP Abgrall26e0d492011-06-24 19:21:51 -0700780
JP Abgrall69261cb2014-06-19 18:35:24 -0700781 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700782 return -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700783 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000784 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700785 return -1;
786 }
787 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700788
JP Abgrall0dad7c22011-06-24 11:58:14 -0700789 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700790 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700791 break;
792 }
793
794 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000795 ALOGE("No such iface %s to delete", ifn);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700796 return -1;
797 }
798
799 /* This also removes the quota command of CostlyIface chain. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700800 res |= cleanupCostlyIface(ifn, QuotaUnique);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700801
802 quotaIfaces.erase(it);
803
804 return res;
805}
JP Abgrall8a932722011-07-13 19:17:35 -0700806
807int BandwidthController::updateQuota(const char *quotaName, int64_t bytes) {
808 FILE *fp;
809 char *fname;
810
JP Abgrall69261cb2014-06-19 18:35:24 -0700811 if (!isIfaceName(quotaName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700812 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName);
813 return -1;
814 }
815
JP Abgrall8a932722011-07-13 19:17:35 -0700816 asprintf(&fname, "/proc/net/xt_quota/%s", quotaName);
Nick Kralevich53ea9ca2015-01-31 13:54:00 -0800817 fp = fopen(fname, "we");
JP Abgrall8a932722011-07-13 19:17:35 -0700818 free(fname);
819 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000820 ALOGE("Updating quota %s failed (%s)", quotaName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700821 return -1;
822 }
SynergyDev7776cea2014-03-16 15:48:51 -0700823 fprintf(fp, "%" PRId64"\n", bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700824 fclose(fp);
825 return 0;
826}
827
828int BandwidthController::runIptablesAlertCmd(IptOp op, const char *alertName, int64_t bytes) {
829 int res = 0;
830 const char *opFlag;
831 char *alertQuotaCmd;
832
833 switch (op) {
834 case IptOpInsert:
835 opFlag = "-I";
836 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800837 case IptOpAppend:
838 opFlag = "-A";
839 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700840 case IptOpReplace:
841 opFlag = "-R";
842 break;
843 default:
844 case IptOpDelete:
845 opFlag = "-D";
846 break;
847 }
848
JP Abgrall92009c82013-02-06 18:01:24 -0800849 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800850 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700851 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700852 free(alertQuotaCmd);
JP Abgrall92009c82013-02-06 18:01:24 -0800853 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800854 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700855 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700856 free(alertQuotaCmd);
857 return res;
858}
859
JP Abgrallc6c67342011-10-07 16:28:54 -0700860int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
861 int res = 0;
862 const char *opFlag;
JP Abgrall8a932722011-07-13 19:17:35 -0700863 char *alertQuotaCmd;
JP Abgrallc6c67342011-10-07 16:28:54 -0700864
865 switch (op) {
866 case IptOpInsert:
867 opFlag = "-I";
868 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800869 case IptOpAppend:
870 opFlag = "-A";
871 break;
JP Abgrallc6c67342011-10-07 16:28:54 -0700872 case IptOpReplace:
873 opFlag = "-R";
874 break;
875 default:
876 case IptOpDelete:
877 opFlag = "-D";
878 break;
879 }
880
JP Abgrall92009c82013-02-06 18:01:24 -0800881 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800882 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700883 res = runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrallc6c67342011-10-07 16:28:54 -0700884 free(alertQuotaCmd);
885 return res;
886}
887
888int BandwidthController::setGlobalAlert(int64_t bytes) {
889 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700890 int res = 0;
891
892 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000893 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700894 return -1;
895 }
896 if (globalAlertBytes) {
897 res = updateQuota(alertName, bytes);
898 } else {
899 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700900 if (globalAlertTetherCount) {
Steve Block3fb42e02011-10-20 11:55:56 +0100901 ALOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700902 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
903 }
JP Abgrall8a932722011-07-13 19:17:35 -0700904 }
905 globalAlertBytes = bytes;
906 return res;
907}
908
JP Abgrallc6c67342011-10-07 16:28:54 -0700909int BandwidthController::setGlobalAlertInForwardChain(void) {
910 const char *alertName = ALERT_GLOBAL_NAME;
911 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700912
JP Abgrallc6c67342011-10-07 16:28:54 -0700913 globalAlertTetherCount++;
Steve Block3fb42e02011-10-20 11:55:56 +0100914 ALOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700915
916 /*
917 * If there is no globalAlert active we are done.
918 * If there is an active globalAlert but this is not the 1st
919 * tether, we are also done.
920 */
921 if (!globalAlertBytes || globalAlertTetherCount != 1) {
922 return 0;
923 }
924
925 /* We only add the rule if this was the 1st tether added. */
926 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
927 return res;
928}
929
930int BandwidthController::removeGlobalAlert(void) {
931
932 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700933 int res = 0;
934
935 if (!globalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000936 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700937 return -1;
938 }
939 res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700940 if (globalAlertTetherCount) {
941 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
942 }
JP Abgrall8a932722011-07-13 19:17:35 -0700943 globalAlertBytes = 0;
944 return res;
945}
946
JP Abgrallc6c67342011-10-07 16:28:54 -0700947int BandwidthController::removeGlobalAlertInForwardChain(void) {
948 int res = 0;
949 const char *alertName = ALERT_GLOBAL_NAME;
950
951 if (!globalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000952 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700953 return -1;
954 }
955
956 globalAlertTetherCount--;
957 /*
958 * If there is no globalAlert active we are done.
959 * If there is an active globalAlert but there are more
960 * tethers, we are also done.
961 */
962 if (!globalAlertBytes || globalAlertTetherCount >= 1) {
963 return 0;
964 }
965
966 /* We only detete the rule if this was the last tether removed. */
967 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
968 return res;
969}
970
JP Abgrall8a932722011-07-13 19:17:35 -0700971int BandwidthController::setSharedAlert(int64_t bytes) {
972 if (!sharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000973 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700974 return -1;
975 }
976 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000977 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700978 return -1;
979 }
980 return setCostlyAlert("shared", bytes, &sharedAlertBytes);
981}
982
983int BandwidthController::removeSharedAlert(void) {
984 return removeCostlyAlert("shared", &sharedAlertBytes);
985}
986
987int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
988 std::list<QuotaInfo>::iterator it;
989
JP Abgrall69261cb2014-06-19 18:35:24 -0700990 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700991 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface);
992 return -1;
993 }
994
JP Abgrall8a932722011-07-13 19:17:35 -0700995 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000996 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700997 return -1;
998 }
999 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
1000 if (it->ifaceName == iface)
1001 break;
1002 }
1003
1004 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +00001005 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -07001006 return -1;
1007 }
1008
1009 return setCostlyAlert(iface, bytes, &it->alert);
1010}
1011
1012int BandwidthController::removeInterfaceAlert(const char *iface) {
1013 std::list<QuotaInfo>::iterator it;
1014
JP Abgrall69261cb2014-06-19 18:35:24 -07001015 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001016 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface);
1017 return -1;
1018 }
1019
JP Abgrall8a932722011-07-13 19:17:35 -07001020 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
1021 if (it->ifaceName == iface)
1022 break;
1023 }
1024
1025 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +00001026 ALOGE("No prior alert set for interface %s", iface);
JP Abgrall8a932722011-07-13 19:17:35 -07001027 return -1;
1028 }
1029
1030 return removeCostlyAlert(iface, &it->alert);
1031}
1032
1033int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
1034 char *alertQuotaCmd;
JP Abgrall109899b2013-02-12 19:20:13 -08001035 char *chainName;
JP Abgrall8a932722011-07-13 19:17:35 -07001036 int res = 0;
1037 char *alertName;
1038
JP Abgrall69261cb2014-06-19 18:35:24 -07001039 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001040 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName);
1041 return -1;
1042 }
1043
JP Abgrall8a932722011-07-13 19:17:35 -07001044 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001045 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -07001046 return -1;
1047 }
1048 asprintf(&alertName, "%sAlert", costName);
1049 if (*alertBytes) {
1050 res = updateQuota(alertName, *alertBytes);
1051 } else {
JP Abgrall7e51cde2013-07-03 13:33:05 -07001052 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall109899b2013-02-12 19:20:13 -08001053 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-A", chainName, bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001054 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001055 free(alertQuotaCmd);
JP Abgrall109899b2013-02-12 19:20:13 -08001056 free(chainName);
JP Abgrall8a932722011-07-13 19:17:35 -07001057 }
1058 *alertBytes = bytes;
1059 free(alertName);
1060 return res;
1061}
1062
1063int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
1064 char *alertQuotaCmd;
1065 char *chainName;
1066 char *alertName;
1067 int res = 0;
1068
JP Abgrall69261cb2014-06-19 18:35:24 -07001069 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001070 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName);
1071 return -1;
1072 }
1073
JP Abgrall8a932722011-07-13 19:17:35 -07001074 if (!*alertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001075 ALOGE("No prior alert set for %s alert", costName);
JP Abgrall8a932722011-07-13 19:17:35 -07001076 return -1;
1077 }
1078
Jesper Hanssona9d791f2012-04-27 13:54:27 +02001079 asprintf(&alertName, "%sAlert", costName);
JP Abgrall7e51cde2013-07-03 13:33:05 -07001080 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall92009c82013-02-06 18:01:24 -08001081 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001082 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001083 free(alertQuotaCmd);
1084 free(chainName);
1085
1086 *alertBytes = 0;
1087 free(alertName);
1088 return res;
1089}
JP Abgralldb7da582011-09-18 12:57:32 -07001090
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001091void BandwidthController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
1092 for (TetherStats& existing : statsList) {
1093 if (existing.addStatsIfMatch(stats)) {
1094 return;
1095 }
1096 }
1097 // No match. Insert a new interface pair.
1098 statsList.push_back(stats);
1099}
1100
JP Abgralldb7da582011-09-18 12:57:32 -07001101/*
1102 * Parse the ptks and bytes out of:
JP Abgrallbaeccc42013-06-25 09:44:10 -07001103 * Chain natctrl_tether_counters (4 references)
1104 * pkts bytes target prot opt in out source destination
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001105 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1106 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
1107 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
1108 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001109 * or:
1110 * Chain natctrl_tether_counters (0 references)
1111 * pkts bytes target prot opt in out source destination
1112 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
1113 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
1114 *
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001115 * It results in an error if invoked and no tethering counter rules exist. The constraint
1116 * helps detect complete parsing failure.
JP Abgralldb7da582011-09-18 12:57:32 -07001117 */
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001118int BandwidthController::addForwardChainStats(const TetherStats& filter,
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001119 TetherStatsList& statsList,
1120 const std::string& statsOutput,
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001121 std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -07001122 int res;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001123 std::string statsLine;
JP Abgralldb7da582011-09-18 12:57:32 -07001124 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
1125 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
1126 char rest[MAX_IPT_OUTPUT_LINE_LEN];
1127
JP Abgrallbaeccc42013-06-25 09:44:10 -07001128 TetherStats stats;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001129 const char *buffPtr;
JP Abgralldb7da582011-09-18 12:57:32 -07001130 int64_t packets, bytes;
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001131 int statsFound = 0;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001132
1133 bool filterPair = filter.intIface[0] && filter.extIface[0];
1134
1135 char *filterMsg = filter.getStatsLine();
1136 ALOGV("filter: %s", filterMsg);
1137 free(filterMsg);
1138
1139 stats = filter;
JP Abgralldb7da582011-09-18 12:57:32 -07001140
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001141 std::stringstream stream(statsOutput);
1142 while (std::getline(stream, statsLine, '\n')) {
1143 buffPtr = statsLine.c_str();
1144
JP Abgralldb7da582011-09-18 12:57:32 -07001145 /* Clean up, so a failed parse can still print info */
1146 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001147 if (strstr(buffPtr, "0.0.0.0")) {
1148 // IPv4 has -- indicating what to do with fragments...
1149 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1150 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
1151 &packets, &bytes, iface0, iface1, rest);
1152 } else {
1153 // ... but IPv6 does not.
1154 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
1155 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all %s %s ::/%s",
1156 &packets, &bytes, iface0, iface1, rest);
1157 }
SynergyDev7776cea2014-03-16 15:48:51 -07001158 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 -07001159 iface0, iface1, packets, bytes, rest, buffPtr);
JP Abgralla2a64f02011-11-11 20:36:16 -08001160 extraProcessingInfo += buffPtr;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001161 extraProcessingInfo += "\n";
JP Abgralla2a64f02011-11-11 20:36:16 -08001162
JP Abgralldb7da582011-09-18 12:57:32 -07001163 if (res != 5) {
1164 continue;
1165 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001166 /*
1167 * The following assumes that the 1st rule has in:extIface out:intIface,
1168 * which is what NatController sets up.
1169 * If not filtering, the 1st match rx, and sets up the pair for the tx side.
1170 */
1171 if (filter.intIface[0] && filter.extIface[0]) {
1172 if (filter.intIface == iface0 && filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001173 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 -07001174 stats.rxPackets = packets;
1175 stats.rxBytes = bytes;
1176 } else if (filter.intIface == iface1 && filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001177 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 -07001178 stats.txPackets = packets;
1179 stats.txBytes = bytes;
1180 }
1181 } else if (filter.intIface[0] || filter.extIface[0]) {
1182 if (filter.intIface == iface0 || filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001183 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 -07001184 stats.intIface = iface0;
1185 stats.extIface = iface1;
1186 stats.rxPackets = packets;
1187 stats.rxBytes = bytes;
1188 } else if (filter.intIface == iface1 || filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001189 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 -07001190 stats.intIface = iface1;
1191 stats.extIface = iface0;
1192 stats.txPackets = packets;
1193 stats.txBytes = bytes;
1194 }
1195 } else /* if (!filter.intFace[0] && !filter.extIface[0]) */ {
1196 if (!stats.intIface[0]) {
SynergyDev7776cea2014-03-16 15:48:51 -07001197 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 -07001198 stats.intIface = iface0;
1199 stats.extIface = iface1;
1200 stats.rxPackets = packets;
1201 stats.rxBytes = bytes;
1202 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001203 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 -07001204 stats.txPackets = packets;
1205 stats.txBytes = bytes;
1206 }
1207 }
1208 if (stats.rxBytes != -1 && stats.txBytes != -1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001209 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64" filterPair=%d", stats.rxBytes, stats.txBytes, filterPair);
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001210 addStats(statsList, stats);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001211 if (filterPair) {
JP Abgrallbaeccc42013-06-25 09:44:10 -07001212 return 0;
1213 } else {
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001214 statsFound++;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001215 stats = filter;
1216 }
JP Abgralldb7da582011-09-18 12:57:32 -07001217 }
1218 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001219
1220 /* It is always an error to find only one side of the stats. */
1221 /* It is an error to find nothing when not filtering. */
1222 if (((stats.rxBytes == -1) != (stats.txBytes == -1)) ||
1223 (!statsFound && !filterPair)) {
1224 return -1;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001225 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001226 return 0;
JP Abgralldb7da582011-09-18 12:57:32 -07001227}
1228
JP Abgrallbaeccc42013-06-25 09:44:10 -07001229char *BandwidthController::TetherStats::getStatsLine(void) const {
JP Abgralldb7da582011-09-18 12:57:32 -07001230 char *msg;
SynergyDev7776cea2014-03-16 15:48:51 -07001231 asprintf(&msg, "%s %s %" PRId64" %" PRId64" %" PRId64" %" PRId64, intIface.c_str(), extIface.c_str(),
JP Abgralldb7da582011-09-18 12:57:32 -07001232 rxBytes, rxPackets, txBytes, txPackets);
1233 return msg;
1234}
1235
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001236int BandwidthController::getTetherStats(SocketClient *cli, TetherStats& filter,
1237 std::string &extraProcessingInfo) {
1238 int res = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001239
1240 TetherStatsList statsList;
1241
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001242 for (const IptablesTarget target : {V4, V6}) {
1243 std::string statsString;
1244 res = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString);
1245 if (res != 0) {
1246 ALOGE("Failed to run %s err=%d", GET_TETHER_STATS_COMMAND.c_str(), res);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001247 return -1;
1248 }
1249
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001250 res = addForwardChainStats(filter, statsList, statsString, extraProcessingInfo);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001251 if (res != 0) {
1252 return res;
1253 }
1254 }
JP Abgralldb7da582011-09-18 12:57:32 -07001255
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001256 if (filter.intIface[0] && filter.extIface[0] && statsList.size() == 1) {
1257 cli->sendMsg(ResponseCode::TetheringStatsResult, statsList[0].getStatsLine(), false);
1258 } else {
1259 for (const auto& stats: statsList) {
1260 cli->sendMsg(ResponseCode::TetheringStatsListResult, stats.getStatsLine(), false);
1261 }
1262 if (res == 0) {
1263 cli->sendMsg(ResponseCode::CommandOkay, "Tethering stats list completed", false);
1264 }
1265 }
1266
JP Abgralldb7da582011-09-18 12:57:32 -07001267 return res;
1268}
JP Abgrall0e540ec2013-08-26 15:13:10 -07001269
1270void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001271 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
1272 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001273
1274 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001275 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
1276 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001277 return;
1278 }
1279 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001280 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001281}
1282
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001283void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
1284 std::stringstream stream(ruleList);
1285 std::string rule;
1286 std::vector<std::string> clearCommands = { "*filter" };
1287 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001288
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001289 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
1290 while (std::getline(stream, rule, '\n')) {
1291 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
1292 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
1293 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
1294
1295 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -07001296 continue;
1297 }
1298
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001299 clearCommands.push_back(android::base::StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001300 if (doRemove) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001301 clearCommands.push_back(android::base::StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001302 }
1303 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001304
1305 if (clearCommands.size() == 1) {
1306 // No rules found.
1307 return;
1308 }
1309
1310 clearCommands.push_back("COMMIT\n");
1311 iptablesRestoreFunction(V4V6, android::base::Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001312}