blob: 2a196f86da15e7913e1c52cf941b6a831ddc1849 [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 Abgrall8a932722011-07-13 19:17:35 -0700837 default:
838 case IptOpDelete:
839 opFlag = "-D";
840 break;
841 }
842
JP Abgrall92009c82013-02-06 18:01:24 -0800843 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800844 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700845 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700846 free(alertQuotaCmd);
JP Abgrall92009c82013-02-06 18:01:24 -0800847 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800848 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700849 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700850 free(alertQuotaCmd);
851 return res;
852}
853
JP Abgrallc6c67342011-10-07 16:28:54 -0700854int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
855 int res = 0;
856 const char *opFlag;
JP Abgrall8a932722011-07-13 19:17:35 -0700857 char *alertQuotaCmd;
JP Abgrallc6c67342011-10-07 16:28:54 -0700858
859 switch (op) {
860 case IptOpInsert:
861 opFlag = "-I";
862 break;
JP Abgrallc6c67342011-10-07 16:28:54 -0700863 default:
864 case IptOpDelete:
865 opFlag = "-D";
866 break;
867 }
868
JP Abgrall92009c82013-02-06 18:01:24 -0800869 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800870 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700871 res = runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrallc6c67342011-10-07 16:28:54 -0700872 free(alertQuotaCmd);
873 return res;
874}
875
876int BandwidthController::setGlobalAlert(int64_t bytes) {
877 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700878 int res = 0;
879
880 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000881 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700882 return -1;
883 }
884 if (globalAlertBytes) {
885 res = updateQuota(alertName, bytes);
886 } else {
887 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700888 if (globalAlertTetherCount) {
Steve Block3fb42e02011-10-20 11:55:56 +0100889 ALOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700890 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
891 }
JP Abgrall8a932722011-07-13 19:17:35 -0700892 }
893 globalAlertBytes = bytes;
894 return res;
895}
896
JP Abgrallc6c67342011-10-07 16:28:54 -0700897int BandwidthController::setGlobalAlertInForwardChain(void) {
898 const char *alertName = ALERT_GLOBAL_NAME;
899 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700900
JP Abgrallc6c67342011-10-07 16:28:54 -0700901 globalAlertTetherCount++;
Steve Block3fb42e02011-10-20 11:55:56 +0100902 ALOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700903
904 /*
905 * If there is no globalAlert active we are done.
906 * If there is an active globalAlert but this is not the 1st
907 * tether, we are also done.
908 */
909 if (!globalAlertBytes || globalAlertTetherCount != 1) {
910 return 0;
911 }
912
913 /* We only add the rule if this was the 1st tether added. */
914 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
915 return res;
916}
917
918int BandwidthController::removeGlobalAlert(void) {
919
920 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700921 int res = 0;
922
923 if (!globalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000924 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700925 return -1;
926 }
927 res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700928 if (globalAlertTetherCount) {
929 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
930 }
JP Abgrall8a932722011-07-13 19:17:35 -0700931 globalAlertBytes = 0;
932 return res;
933}
934
JP Abgrallc6c67342011-10-07 16:28:54 -0700935int BandwidthController::removeGlobalAlertInForwardChain(void) {
936 int res = 0;
937 const char *alertName = ALERT_GLOBAL_NAME;
938
939 if (!globalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000940 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700941 return -1;
942 }
943
944 globalAlertTetherCount--;
945 /*
946 * If there is no globalAlert active we are done.
947 * If there is an active globalAlert but there are more
948 * tethers, we are also done.
949 */
950 if (!globalAlertBytes || globalAlertTetherCount >= 1) {
951 return 0;
952 }
953
954 /* We only detete the rule if this was the last tether removed. */
955 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
956 return res;
957}
958
JP Abgrall8a932722011-07-13 19:17:35 -0700959int BandwidthController::setSharedAlert(int64_t bytes) {
960 if (!sharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000961 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700962 return -1;
963 }
964 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000965 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700966 return -1;
967 }
968 return setCostlyAlert("shared", bytes, &sharedAlertBytes);
969}
970
971int BandwidthController::removeSharedAlert(void) {
972 return removeCostlyAlert("shared", &sharedAlertBytes);
973}
974
975int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
976 std::list<QuotaInfo>::iterator it;
977
JP Abgrall69261cb2014-06-19 18:35:24 -0700978 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700979 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface);
980 return -1;
981 }
982
JP Abgrall8a932722011-07-13 19:17:35 -0700983 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000984 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700985 return -1;
986 }
987 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
988 if (it->ifaceName == iface)
989 break;
990 }
991
992 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000993 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700994 return -1;
995 }
996
997 return setCostlyAlert(iface, bytes, &it->alert);
998}
999
1000int BandwidthController::removeInterfaceAlert(const char *iface) {
1001 std::list<QuotaInfo>::iterator it;
1002
JP Abgrall69261cb2014-06-19 18:35:24 -07001003 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001004 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface);
1005 return -1;
1006 }
1007
JP Abgrall8a932722011-07-13 19:17:35 -07001008 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
1009 if (it->ifaceName == iface)
1010 break;
1011 }
1012
1013 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +00001014 ALOGE("No prior alert set for interface %s", iface);
JP Abgrall8a932722011-07-13 19:17:35 -07001015 return -1;
1016 }
1017
1018 return removeCostlyAlert(iface, &it->alert);
1019}
1020
1021int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
1022 char *alertQuotaCmd;
JP Abgrall109899b2013-02-12 19:20:13 -08001023 char *chainName;
JP Abgrall8a932722011-07-13 19:17:35 -07001024 int res = 0;
1025 char *alertName;
1026
JP Abgrall69261cb2014-06-19 18:35:24 -07001027 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001028 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName);
1029 return -1;
1030 }
1031
JP Abgrall8a932722011-07-13 19:17:35 -07001032 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001033 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -07001034 return -1;
1035 }
1036 asprintf(&alertName, "%sAlert", costName);
1037 if (*alertBytes) {
1038 res = updateQuota(alertName, *alertBytes);
1039 } else {
JP Abgrall7e51cde2013-07-03 13:33:05 -07001040 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall109899b2013-02-12 19:20:13 -08001041 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-A", chainName, bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001042 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001043 free(alertQuotaCmd);
JP Abgrall109899b2013-02-12 19:20:13 -08001044 free(chainName);
JP Abgrall8a932722011-07-13 19:17:35 -07001045 }
1046 *alertBytes = bytes;
1047 free(alertName);
1048 return res;
1049}
1050
1051int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
1052 char *alertQuotaCmd;
1053 char *chainName;
1054 char *alertName;
1055 int res = 0;
1056
JP Abgrall69261cb2014-06-19 18:35:24 -07001057 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001058 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName);
1059 return -1;
1060 }
1061
JP Abgrall8a932722011-07-13 19:17:35 -07001062 if (!*alertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001063 ALOGE("No prior alert set for %s alert", costName);
JP Abgrall8a932722011-07-13 19:17:35 -07001064 return -1;
1065 }
1066
Jesper Hanssona9d791f2012-04-27 13:54:27 +02001067 asprintf(&alertName, "%sAlert", costName);
JP Abgrall7e51cde2013-07-03 13:33:05 -07001068 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall92009c82013-02-06 18:01:24 -08001069 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001070 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001071 free(alertQuotaCmd);
1072 free(chainName);
1073
1074 *alertBytes = 0;
1075 free(alertName);
1076 return res;
1077}
JP Abgralldb7da582011-09-18 12:57:32 -07001078
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001079void BandwidthController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
1080 for (TetherStats& existing : statsList) {
1081 if (existing.addStatsIfMatch(stats)) {
1082 return;
1083 }
1084 }
1085 // No match. Insert a new interface pair.
1086 statsList.push_back(stats);
1087}
1088
JP Abgralldb7da582011-09-18 12:57:32 -07001089/*
1090 * Parse the ptks and bytes out of:
JP Abgrallbaeccc42013-06-25 09:44:10 -07001091 * Chain natctrl_tether_counters (4 references)
1092 * pkts bytes target prot opt in out source destination
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001093 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1094 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
1095 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
1096 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001097 * or:
1098 * Chain natctrl_tether_counters (0 references)
1099 * pkts bytes target prot opt in out source destination
1100 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
1101 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
1102 *
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001103 * It results in an error if invoked and no tethering counter rules exist. The constraint
1104 * helps detect complete parsing failure.
JP Abgralldb7da582011-09-18 12:57:32 -07001105 */
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001106int BandwidthController::addForwardChainStats(const TetherStats& filter,
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001107 TetherStatsList& statsList,
1108 const std::string& statsOutput,
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001109 std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -07001110 int res;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001111 std::string statsLine;
JP Abgralldb7da582011-09-18 12:57:32 -07001112 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
1113 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
1114 char rest[MAX_IPT_OUTPUT_LINE_LEN];
1115
JP Abgrallbaeccc42013-06-25 09:44:10 -07001116 TetherStats stats;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001117 const char *buffPtr;
JP Abgralldb7da582011-09-18 12:57:32 -07001118 int64_t packets, bytes;
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001119 int statsFound = 0;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001120
1121 bool filterPair = filter.intIface[0] && filter.extIface[0];
1122
1123 char *filterMsg = filter.getStatsLine();
1124 ALOGV("filter: %s", filterMsg);
1125 free(filterMsg);
1126
1127 stats = filter;
JP Abgralldb7da582011-09-18 12:57:32 -07001128
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001129 std::stringstream stream(statsOutput);
1130 while (std::getline(stream, statsLine, '\n')) {
1131 buffPtr = statsLine.c_str();
1132
JP Abgralldb7da582011-09-18 12:57:32 -07001133 /* Clean up, so a failed parse can still print info */
1134 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001135 if (strstr(buffPtr, "0.0.0.0")) {
1136 // IPv4 has -- indicating what to do with fragments...
1137 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1138 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
1139 &packets, &bytes, iface0, iface1, rest);
1140 } else {
1141 // ... but IPv6 does not.
1142 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
1143 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all %s %s ::/%s",
1144 &packets, &bytes, iface0, iface1, rest);
1145 }
SynergyDev7776cea2014-03-16 15:48:51 -07001146 ALOGV("parse res=%d iface0=<%s> iface1=<%s> pkts=%" PRId64" bytes=%" PRId64" rest=<%s> orig line=<%s>", res,
JP Abgralldb7da582011-09-18 12:57:32 -07001147 iface0, iface1, packets, bytes, rest, buffPtr);
JP Abgralla2a64f02011-11-11 20:36:16 -08001148 extraProcessingInfo += buffPtr;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001149 extraProcessingInfo += "\n";
JP Abgralla2a64f02011-11-11 20:36:16 -08001150
JP Abgralldb7da582011-09-18 12:57:32 -07001151 if (res != 5) {
1152 continue;
1153 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001154 /*
1155 * The following assumes that the 1st rule has in:extIface out:intIface,
1156 * which is what NatController sets up.
1157 * If not filtering, the 1st match rx, and sets up the pair for the tx side.
1158 */
1159 if (filter.intIface[0] && filter.extIface[0]) {
1160 if (filter.intIface == iface0 && filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001161 ALOGV("2Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001162 stats.rxPackets = packets;
1163 stats.rxBytes = bytes;
1164 } else if (filter.intIface == iface1 && filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001165 ALOGV("2Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001166 stats.txPackets = packets;
1167 stats.txBytes = bytes;
1168 }
1169 } else if (filter.intIface[0] || filter.extIface[0]) {
1170 if (filter.intIface == iface0 || filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001171 ALOGV("1Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001172 stats.intIface = iface0;
1173 stats.extIface = iface1;
1174 stats.rxPackets = packets;
1175 stats.rxBytes = bytes;
1176 } else if (filter.intIface == iface1 || filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001177 ALOGV("1Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001178 stats.intIface = iface1;
1179 stats.extIface = iface0;
1180 stats.txPackets = packets;
1181 stats.txBytes = bytes;
1182 }
1183 } else /* if (!filter.intFace[0] && !filter.extIface[0]) */ {
1184 if (!stats.intIface[0]) {
SynergyDev7776cea2014-03-16 15:48:51 -07001185 ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001186 stats.intIface = iface0;
1187 stats.extIface = iface1;
1188 stats.rxPackets = packets;
1189 stats.rxBytes = bytes;
1190 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001191 ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64" rx_packets=%" PRId64" ", iface0, iface1, bytes, packets);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001192 stats.txPackets = packets;
1193 stats.txBytes = bytes;
1194 }
1195 }
1196 if (stats.rxBytes != -1 && stats.txBytes != -1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001197 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64" filterPair=%d", stats.rxBytes, stats.txBytes, filterPair);
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001198 addStats(statsList, stats);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001199 if (filterPair) {
JP Abgrallbaeccc42013-06-25 09:44:10 -07001200 return 0;
1201 } else {
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001202 statsFound++;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001203 stats = filter;
1204 }
JP Abgralldb7da582011-09-18 12:57:32 -07001205 }
1206 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001207
1208 /* It is always an error to find only one side of the stats. */
1209 /* It is an error to find nothing when not filtering. */
1210 if (((stats.rxBytes == -1) != (stats.txBytes == -1)) ||
1211 (!statsFound && !filterPair)) {
1212 return -1;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001213 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001214 return 0;
JP Abgralldb7da582011-09-18 12:57:32 -07001215}
1216
JP Abgrallbaeccc42013-06-25 09:44:10 -07001217char *BandwidthController::TetherStats::getStatsLine(void) const {
JP Abgralldb7da582011-09-18 12:57:32 -07001218 char *msg;
SynergyDev7776cea2014-03-16 15:48:51 -07001219 asprintf(&msg, "%s %s %" PRId64" %" PRId64" %" PRId64" %" PRId64, intIface.c_str(), extIface.c_str(),
JP Abgralldb7da582011-09-18 12:57:32 -07001220 rxBytes, rxPackets, txBytes, txPackets);
1221 return msg;
1222}
1223
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001224int BandwidthController::getTetherStats(SocketClient *cli, TetherStats& filter,
1225 std::string &extraProcessingInfo) {
1226 int res = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001227
1228 TetherStatsList statsList;
1229
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001230 for (const IptablesTarget target : {V4, V6}) {
1231 std::string statsString;
1232 res = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString);
1233 if (res != 0) {
1234 ALOGE("Failed to run %s err=%d", GET_TETHER_STATS_COMMAND.c_str(), res);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001235 return -1;
1236 }
1237
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001238 res = addForwardChainStats(filter, statsList, statsString, extraProcessingInfo);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001239 if (res != 0) {
1240 return res;
1241 }
1242 }
JP Abgralldb7da582011-09-18 12:57:32 -07001243
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001244 if (filter.intIface[0] && filter.extIface[0] && statsList.size() == 1) {
1245 cli->sendMsg(ResponseCode::TetheringStatsResult, statsList[0].getStatsLine(), false);
1246 } else {
1247 for (const auto& stats: statsList) {
1248 cli->sendMsg(ResponseCode::TetheringStatsListResult, stats.getStatsLine(), false);
1249 }
1250 if (res == 0) {
1251 cli->sendMsg(ResponseCode::CommandOkay, "Tethering stats list completed", false);
1252 }
1253 }
1254
JP Abgralldb7da582011-09-18 12:57:32 -07001255 return res;
1256}
JP Abgrall0e540ec2013-08-26 15:13:10 -07001257
1258void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001259 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
1260 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001261
1262 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001263 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
1264 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001265 return;
1266 }
1267 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001268 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001269}
1270
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001271void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
1272 std::stringstream stream(ruleList);
1273 std::string rule;
1274 std::vector<std::string> clearCommands = { "*filter" };
1275 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001276
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001277 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
1278 while (std::getline(stream, rule, '\n')) {
1279 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
1280 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
1281 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
1282
1283 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -07001284 continue;
1285 }
1286
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001287 clearCommands.push_back(android::base::StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001288 if (doRemove) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001289 clearCommands.push_back(android::base::StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001290 }
1291 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001292
1293 if (clearCommands.size() == 1) {
1294 // No rules found.
1295 return;
1296 }
1297
1298 clearCommands.push_back("COMMIT\n");
1299 iptablesRestoreFunction(V4V6, android::base::Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001300}