blob: 3df2309b77979ca136d96808db9efd16b2ee24c6 [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 ";
JP Abgralldb7da582011-09-18 12:57:32 -070079
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070080/**
81 * Some comments about the rules:
82 * * Ordering
83 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070084 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070085 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070086 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070087 *
88 * * global quota vs per interface quota
89 * - global quota for all costly interfaces uses a single costly chain:
90 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -070091 * iptables -N bw_costly_shared
92 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
93 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
94 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -070095 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -070096 * iptables -A bw_costly_shared --jump bw_penalty_box
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090097 * iptables -A bw_penalty_box --jump bw_happy_box
Lorenzo Colitti464eabe2016-03-25 13:38:19 +090098 * iptables -A bw_happy_box --jump bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -070099 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700100 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700101 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
102 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700103 *
104 * - quota per interface. This is achieve by having "costly" chains per quota.
105 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700106 * iptables -N bw_costly_iface0
107 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
108 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
109 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -0700110 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -0700111 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700112 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900113 * * Penalty box, happy box and data saver.
114 * - bw_penalty box is a blacklist of apps that are rejected.
115 * - bw_happy_box is a whitelist of apps. It always includes all system apps
116 * - bw_data_saver implements data usage restrictions.
117 * - Via the UI the user can add and remove apps from the whitelist and
118 * blacklist, and turn on/off data saver.
119 * - The blacklist takes precedence over the whitelist and the whitelist
120 * takes precedence over data saver.
121 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700122 * * bw_penalty_box handling:
123 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900124 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700125 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700126 * --jump REJECT --reject-with icmp-port-unreachable
127 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700128 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900129 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700130 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700131 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700132 * --jump RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900133 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900134 * * bw_data_saver handling:
135 * - The bw_data_saver comes after the happy box.
136 * Enable data saver:
137 * iptables -R 1 bw_data_saver --jump REJECT --reject-with icmp-port-unreachable
138 * Disable data saver:
139 * iptables -R 1 bw_data_saver --jump RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700140 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900141
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900142const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900143const std::string DATA_SAVER_ENABLE_COMMAND = "-R bw_data_saver 1";
144const std::string HAPPY_BOX_WHITELIST_COMMAND = android::base::StringPrintf(
145 "-I bw_happy_box -m owner --uid-owner %d-%d --jump RETURN", 0, MAX_SYSTEM_UID);
146
147static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700148 /*
149 * Cleanup rules.
JP Abgrall7e51cde2013-07-03 13:33:05 -0700150 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
JP Abgrall0031cea2012-04-17 16:38:23 -0700151 * to allow coexistance.
JP Abgrall39f8f242011-06-29 19:21:58 -0700152 */
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900153 "*filter",
154 ":bw_INPUT -",
155 ":bw_OUTPUT -",
156 ":bw_FORWARD -",
157 ":bw_happy_box -",
158 ":bw_penalty_box -",
159 ":bw_data_saver -",
160 ":bw_costly_shared -",
161 "COMMIT",
162 "*raw",
163 ":bw_raw_PREROUTING -",
164 "COMMIT",
165 "*mangle",
166 ":bw_mangle_POSTROUTING -",
167 COMMIT_AND_CLOSE
JP Abgrall0031cea2012-04-17 16:38:23 -0700168};
169
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900170static const std::vector<std::string> IPT_BASIC_ACCOUNTING_COMMANDS = {
171 "*filter",
JP Abgrall0031cea2012-04-17 16:38:23 -0700172 "-A bw_INPUT -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall0031cea2012-04-17 16:38:23 -0700173 "-A bw_OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900174 "-A bw_costly_shared --jump bw_penalty_box",
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900175 "-A bw_penalty_box --jump bw_happy_box",
176 "-A bw_happy_box --jump bw_data_saver",
177 "-A bw_data_saver -j RETURN",
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900178 HAPPY_BOX_WHITELIST_COMMAND,
179 "COMMIT",
180
181 "*raw",
182 "-A bw_raw_PREROUTING -m owner --socket-exists", /* This is a tracking rule. */
183 "COMMIT",
184
185 "*mangle",
186 "-A bw_mangle_POSTROUTING -m owner --socket-exists", /* This is a tracking rule. */
187 COMMIT_AND_CLOSE
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900188};
189
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900190
191} // namespace
192
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700193BandwidthController::BandwidthController(void) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700194}
195
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700196int BandwidthController::runIpxtablesCmd(const char *cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700197 IptFailureLog failureHandling) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700198 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700199
Steve Block3fb42e02011-10-20 11:55:56 +0100200 ALOGV("runIpxtablesCmd(cmd=%s)", cmd);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700201 res |= runIptablesCmd(cmd, jumpHandling, IptIpV4, failureHandling);
202 res |= runIptablesCmd(cmd, jumpHandling, IptIpV6, failureHandling);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700203 return res;
204}
205
JP Abgrall26e0d492011-06-24 19:21:51 -0700206int BandwidthController::StrncpyAndCheck(char *buffer, const char *src, size_t buffSize) {
207
208 memset(buffer, '\0', buffSize); // strncpy() is not filling leftover with '\0'
209 strncpy(buffer, src, buffSize);
210 return buffer[buffSize - 1];
211}
212
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700213int BandwidthController::runIptablesCmd(const char *cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700214 IptIpVer iptVer, IptFailureLog failureHandling) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700215 char buffer[MAX_CMD_LEN];
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700216 const char *argv[MAX_CMD_ARGS];
JP Abgrall26e0d492011-06-24 19:21:51 -0700217 int argc = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700218 char *next = buffer;
219 char *tmp;
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700220 int res;
Rom Lemarchand14150212013-01-24 10:01:04 -0800221 int status = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700222
JP Abgrall0dad7c22011-06-24 11:58:14 -0700223 std::string fullCmd = cmd;
JP Abgrall26e0d492011-06-24 19:21:51 -0700224
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700225 switch (jumpHandling) {
226 case IptJumpReject:
JP Abgrall340d5cc2013-06-28 17:06:00 -0700227 /*
228 * Must be carefull what one rejects with, as uper layer protocols will just
229 * keep on hammering the device until the number of retries are done.
230 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
231 */
232 fullCmd += " --jump REJECT";
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700233 break;
234 case IptJumpReturn:
235 fullCmd += " --jump RETURN";
236 break;
237 case IptJumpNoAdd:
238 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700239 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700240
Paul Jensen94b2ab92015-08-04 10:35:05 -0400241 fullCmd.insert(0, " -w ");
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700242 fullCmd.insert(0, iptVer == IptIpV4 ? IPTABLES_PATH : IP6TABLES_PATH);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700243
Rom Lemarchand14150212013-01-24 10:01:04 -0800244 if (StrncpyAndCheck(buffer, fullCmd.c_str(), sizeof(buffer))) {
245 ALOGE("iptables command too long");
246 return -1;
247 }
248
249 argc = 0;
250 while ((tmp = strsep(&next, " "))) {
251 argv[argc++] = tmp;
252 if (argc >= MAX_CMD_ARGS) {
253 ALOGE("iptables argument overflow");
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700254 return -1;
255 }
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700256 }
Rom Lemarchand14150212013-01-24 10:01:04 -0800257
258 argv[argc] = NULL;
Lorenzo Colitti86a47982016-03-18 17:52:25 +0900259 res = execFunction(argc, (char **)argv, &status, false,
Rom Lemarchand14150212013-01-24 10:01:04 -0800260 failureHandling == IptFailShow);
JP Abgrallc8dc63b2013-02-13 16:30:00 -0800261 res = res || !WIFEXITED(status) || WEXITSTATUS(status);
262 if (res && failureHandling == IptFailShow) {
263 ALOGE("runIptablesCmd(): res=%d status=%d failed %s", res, status,
264 fullCmd.c_str());
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700265 }
266 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700267}
268
JP Abgrall0e540ec2013-08-26 15:13:10 -0700269void BandwidthController::flushCleanTables(bool doClean) {
270 /* Flush and remove the bw_costly_<iface> tables */
271 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700272
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900273 std::string commands = android::base::Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900274 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700275}
JP Abgrall0031cea2012-04-17 16:38:23 -0700276
JP Abgrall0e540ec2013-08-26 15:13:10 -0700277int BandwidthController::setupIptablesHooks(void) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700278 /* flush+clean is allowed to fail */
279 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700280 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700281}
282
283int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrall0031cea2012-04-17 16:38:23 -0700284 char value[PROPERTY_VALUE_MAX];
285
286 if (!force) {
287 property_get("persist.bandwidth.enable", value, "1");
288 if (!strcmp(value, "0"))
289 return 0;
290 }
JP Abgrall8a932722011-07-13 19:17:35 -0700291
JP Abgralldb7da582011-09-18 12:57:32 -0700292 /* Let's pretend we started from scratch ... */
JP Abgrall8a932722011-07-13 19:17:35 -0700293 sharedQuotaIfaces.clear();
294 quotaIfaces.clear();
JP Abgralldb7da582011-09-18 12:57:32 -0700295 globalAlertBytes = 0;
JP Abgrallc6c67342011-10-07 16:28:54 -0700296 globalAlertTetherCount = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700297 sharedQuotaBytes = sharedAlertBytes = 0;
298
JP Abgrall0e540ec2013-08-26 15:13:10 -0700299 flushCleanTables(false);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900300 std::string commands = android::base::Join(IPT_BASIC_ACCOUNTING_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900301 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700302}
303
304int BandwidthController::disableBandwidthControl(void) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700305
306 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700307 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700308}
309
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900310int BandwidthController::enableDataSaver(bool enable) {
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900311 return runIpxtablesCmd(DATA_SAVER_ENABLE_COMMAND.c_str(),
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900312 enable ? IptJumpReject : IptJumpReturn, IptFailShow);
313}
314
JP Abgrall8a932722011-07-13 19:17:35 -0700315int BandwidthController::runCommands(int numCommands, const char *commands[],
316 RunCmdErrHandling cmdErrHandling) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700317 int res = 0;
JP Abgrallad729ac2012-04-24 23:27:44 -0700318 IptFailureLog failureLogging = IptFailShow;
319 if (cmdErrHandling == RunCmdFailureOk) {
320 failureLogging = IptFailHide;
321 }
Steve Block3fb42e02011-10-20 11:55:56 +0100322 ALOGV("runCommands(): %d commands", numCommands);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700323 for (int cmdNum = 0; cmdNum < numCommands; cmdNum++) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700324 res = runIpxtablesCmd(commands[cmdNum], IptJumpNoAdd, failureLogging);
JP Abgrall0031cea2012-04-17 16:38:23 -0700325 if (res && cmdErrHandling != RunCmdFailureOk)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700326 return res;
327 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700328 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700329}
330
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700331std::string BandwidthController::makeIptablesSpecialAppCmd(IptOp op, int uid, const char *chain) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700332 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700333 char *buff;
334 const char *opFlag;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700335
336 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700337 case IptOpInsert:
338 opFlag = "-I";
339 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800340 case IptOpAppend:
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700341 ALOGE("Append op not supported for %s uids", chain);
342 res = "";
343 return res;
JP Abgrall109899b2013-02-12 19:20:13 -0800344 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700345 case IptOpReplace:
346 opFlag = "-R";
347 break;
348 default:
349 case IptOpDelete:
350 opFlag = "-D";
351 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700352 }
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700353 asprintf(&buff, "%s %s -m owner --uid-owner %d", opFlag, chain, uid);
JP Abgrall8a932722011-07-13 19:17:35 -0700354 res = buff;
355 free(buff);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700356 return res;
357}
358
359int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700360 return manipulateNaughtyApps(numUids, appUids, SpecialAppOpAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700361}
362
363int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700364 return manipulateNaughtyApps(numUids, appUids, SpecialAppOpRemove);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700365}
366
JP Abgralle4788732013-07-02 20:28:45 -0700367int BandwidthController::addNiceApps(int numUids, char *appUids[]) {
368 return manipulateNiceApps(numUids, appUids, SpecialAppOpAdd);
369}
370
371int BandwidthController::removeNiceApps(int numUids, char *appUids[]) {
372 return manipulateNiceApps(numUids, appUids, SpecialAppOpRemove);
373}
374
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700375int BandwidthController::manipulateNaughtyApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
Lorenzo Colittib1f05572016-03-18 11:55:56 +0900376 return manipulateSpecialApps(numUids, appStrUids, "bw_penalty_box", IptJumpReject, appOp);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700377}
378
JP Abgralle4788732013-07-02 20:28:45 -0700379int BandwidthController::manipulateNiceApps(int numUids, char *appStrUids[], SpecialAppOp appOp) {
Lorenzo Colittib1f05572016-03-18 11:55:56 +0900380 return manipulateSpecialApps(numUids, appStrUids, "bw_happy_box", IptJumpReturn, appOp);
JP Abgralle4788732013-07-02 20:28:45 -0700381}
382
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700383
384int BandwidthController::manipulateSpecialApps(int numUids, char *appStrUids[],
385 const char *chain,
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700386 IptJumpOp jumpHandling, SpecialAppOp appOp) {
387
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700388 int uidNum;
JP Abgrall26e0d492011-06-24 19:21:51 -0700389 const char *failLogTemplate;
390 IptOp op;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700391 int appUids[numUids];
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700392 std::string iptCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700393
JP Abgrall26e0d492011-06-24 19:21:51 -0700394 switch (appOp) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700395 case SpecialAppOpAdd:
JP Abgrall8a932722011-07-13 19:17:35 -0700396 op = IptOpInsert;
JP Abgrallaf476f72013-07-03 12:23:55 -0700397 failLogTemplate = "Failed to add app uid %s(%d) to %s.";
JP Abgrall8a932722011-07-13 19:17:35 -0700398 break;
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700399 case SpecialAppOpRemove:
JP Abgrall8a932722011-07-13 19:17:35 -0700400 op = IptOpDelete;
JP Abgrallaf476f72013-07-03 12:23:55 -0700401 failLogTemplate = "Failed to delete app uid %s(%d) from %s box.";
JP Abgrall8a932722011-07-13 19:17:35 -0700402 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700403 default:
404 ALOGE("Unexpected app Op %d", appOp);
405 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700406 }
407
408 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrallaf476f72013-07-03 12:23:55 -0700409 char *end;
410 appUids[uidNum] = strtoul(appStrUids[uidNum], &end, 0);
411 if (*end || !*appStrUids[uidNum]) {
412 ALOGE(failLogTemplate, appStrUids[uidNum], appUids[uidNum], chain);
JP Abgrall26e0d492011-06-24 19:21:51 -0700413 goto fail_parse;
414 }
415 }
JP Abgrall26e0d492011-06-24 19:21:51 -0700416
417 for (uidNum = 0; uidNum < numUids; uidNum++) {
JP Abgrallb1d24092012-04-27 01:02:31 -0700418 int uid = appUids[uidNum];
JP Abgrallb1d24092012-04-27 01:02:31 -0700419
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700420 iptCmd = makeIptablesSpecialAppCmd(op, uid, chain);
421 if (runIpxtablesCmd(iptCmd.c_str(), jumpHandling)) {
JP Abgrallaf476f72013-07-03 12:23:55 -0700422 ALOGE(failLogTemplate, appStrUids[uidNum], uid, chain);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700423 goto fail_with_uidNum;
424 }
425 }
426 return 0;
427
JP Abgrall26e0d492011-06-24 19:21:51 -0700428fail_with_uidNum:
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700429 /* Try to remove the uid that failed in any case*/
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700430 iptCmd = makeIptablesSpecialAppCmd(IptOpDelete, appUids[uidNum], chain);
431 runIpxtablesCmd(iptCmd.c_str(), jumpHandling);
JP Abgrall26e0d492011-06-24 19:21:51 -0700432fail_parse:
433 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700434}
435
JP Abgrall26e0d492011-06-24 19:21:51 -0700436std::string BandwidthController::makeIptablesQuotaCmd(IptOp op, const char *costName, int64_t quota) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700437 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700438 char *buff;
439 const char *opFlag;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700440
SynergyDev7776cea2014-03-16 15:48:51 -0700441 ALOGV("makeIptablesQuotaCmd(%d, %" PRId64")", op, quota);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700442
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700443 switch (op) {
JP Abgrall8a932722011-07-13 19:17:35 -0700444 case IptOpInsert:
445 opFlag = "-I";
446 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800447 case IptOpAppend:
448 opFlag = "-A";
449 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700450 case IptOpReplace:
451 opFlag = "-R";
452 break;
453 default:
454 case IptOpDelete:
455 opFlag = "-D";
456 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700457 }
JP Abgrall8a932722011-07-13 19:17:35 -0700458
JP Abgrallbfa74662011-06-29 19:23:04 -0700459 // The requried IP version specific --jump REJECT ... will be added later.
SynergyDev7776cea2014-03-16 15:48:51 -0700460 asprintf(&buff, "%s bw_costly_%s -m quota2 ! --quota %" PRId64" --name %s", opFlag, costName, quota,
JP Abgrall8a932722011-07-13 19:17:35 -0700461 costName);
462 res = buff;
463 free(buff);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700464 return res;
465}
466
JP Abgrall26e0d492011-06-24 19:21:51 -0700467int BandwidthController::prepCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700468 char cmd[MAX_CMD_LEN];
JP Abgrall0031cea2012-04-17 16:38:23 -0700469 int res = 0, res1, res2;
JP Abgrall8a932722011-07-13 19:17:35 -0700470 int ruleInsertPos = 1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700471 std::string costString;
472 const char *costCString;
473
JP Abgrall0dad7c22011-06-24 11:58:14 -0700474 /* The "-N costly" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700475 switch (quotaType) {
476 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700477 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700478 costString += ifn;
479 costCString = costString.c_str();
JP Abgrall0031cea2012-04-17 16:38:23 -0700480 /*
JP Abgrall7e51cde2013-07-03 13:33:05 -0700481 * Flush the bw_costly_<iface> is allowed to fail in case it didn't exist.
JP Abgrall0031cea2012-04-17 16:38:23 -0700482 * Creating a new one is allowed to fail in case it existed.
483 * This helps with netd restarts.
484 */
485 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700486 res1 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700487 snprintf(cmd, sizeof(cmd), "-N %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700488 res2 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700489 res = (res1 && res2) || (!res1 && !res2);
490
JP Abgrall7e51cde2013-07-03 13:33:05 -0700491 snprintf(cmd, sizeof(cmd), "-A %s -j bw_penalty_box", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700492 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall26e0d492011-06-24 19:21:51 -0700493 break;
494 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700495 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700496 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700497 default:
498 ALOGE("Unexpected quotatype %d", quotaType);
499 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700500 }
501
JP Abgrall8a932722011-07-13 19:17:35 -0700502 if (globalAlertBytes) {
503 /* The alert rule comes 1st */
504 ruleInsertPos = 2;
505 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700506
507 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700508 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700509
510 snprintf(cmd, sizeof(cmd), "-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700511 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall0031cea2012-04-17 16:38:23 -0700512
513 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700514 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700515
516 snprintf(cmd, sizeof(cmd), "-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700517 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900518
519 snprintf(cmd, sizeof(cmd), "-D bw_FORWARD -o %s --jump %s", ifn, costCString);
520 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
521 snprintf(cmd, sizeof(cmd), "-A bw_FORWARD -o %s --jump %s", ifn, costCString);
522 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
523
JP Abgrall0dad7c22011-06-24 11:58:14 -0700524 return res;
525}
526
JP Abgrall26e0d492011-06-24 19:21:51 -0700527int BandwidthController::cleanupCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700528 char cmd[MAX_CMD_LEN];
529 int res = 0;
530 std::string costString;
531 const char *costCString;
532
JP Abgrall26e0d492011-06-24 19:21:51 -0700533 switch (quotaType) {
534 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700535 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700536 costString += ifn;
537 costCString = costString.c_str();
JP Abgrall26e0d492011-06-24 19:21:51 -0700538 break;
539 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700540 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700541 break;
JP Abgrall0031cea2012-04-17 16:38:23 -0700542 default:
543 ALOGE("Unexpected quotatype %d", quotaType);
544 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700545 }
546
JP Abgrall0031cea2012-04-17 16:38:23 -0700547 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700548 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900549 for (const auto tableName : {LOCAL_OUTPUT, LOCAL_FORWARD}) {
550 snprintf(cmd, sizeof(cmd), "-D %s -o %s --jump %s", tableName, ifn, costCString);
551 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
552 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700553
JP Abgrall7e51cde2013-07-03 13:33:05 -0700554 /* The "-N bw_costly_shared" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700555 if (quotaType == QuotaUnique) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700556 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700557 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgralla9f802c2011-06-29 15:46:45 -0700558 snprintf(cmd, sizeof(cmd), "-X %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700559 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700560 }
561 return res;
562}
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700563
JP Abgrall0dad7c22011-06-24 11:58:14 -0700564int BandwidthController::setInterfaceSharedQuota(const char *iface, int64_t maxBytes) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700565 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700566 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700567 std::string quotaCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700568 std::string ifaceName;
569 ;
JP Abgrallbfa74662011-06-29 19:23:04 -0700570 const char *costName = "shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700571 std::list<std::string>::iterator it;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700572
JP Abgrall8a932722011-07-13 19:17:35 -0700573 if (!maxBytes) {
574 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000575 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700576 return -1;
577 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700578 if (!isIfaceName(iface))
579 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700580 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000581 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700582 return -1;
583 }
584 ifaceName = ifn;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700585
586 if (maxBytes == -1) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700587 return removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700588 }
589
590 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700591 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
592 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700593 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700594 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700595
JP Abgrall0dad7c22011-06-24 11:58:14 -0700596 if (it == sharedQuotaIfaces.end()) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700597 res |= prepCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700598 if (sharedQuotaIfaces.empty()) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700599 quotaCmd = makeIptablesQuotaCmd(IptOpInsert, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700600 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700601 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000602 ALOGE("Failed set quota rule");
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700603 goto fail;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700604 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700605 sharedQuotaBytes = maxBytes;
606 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700607 sharedQuotaIfaces.push_front(ifaceName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700608
609 }
610
611 if (maxBytes != sharedQuotaBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700612 res |= updateQuota(costName, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700613 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000614 ALOGE("Failed update quota for %s", costName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700615 goto fail;
616 }
617 sharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700618 }
619 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700620
621 fail:
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700622 /*
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700623 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
624 * rules in the kernel to see which ones need cleaning up.
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700625 * For now callers needs to choose if they want to "ndc bandwidth enable"
626 * which resets everything.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700627 */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700628 removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700629 return -1;
630}
631
JP Abgrall8a932722011-07-13 19:17:35 -0700632/* It will also cleanup any shared alerts */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700633int BandwidthController::removeInterfaceSharedQuota(const char *iface) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700634 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700635 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700636 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700637 std::list<std::string>::iterator it;
JP Abgrallbfa74662011-06-29 19:23:04 -0700638 const char *costName = "shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700639
JP Abgrall69261cb2014-06-19 18:35:24 -0700640 if (!isIfaceName(iface))
641 return -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700642 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000643 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700644 return -1;
645 }
JP Abgrall8a932722011-07-13 19:17:35 -0700646 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700647
JP Abgrall0dad7c22011-06-24 11:58:14 -0700648 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
649 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700650 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700651 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700652 if (it == sharedQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000653 ALOGE("No such iface %s to delete", ifn);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700654 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700655 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700656
JP Abgrall26e0d492011-06-24 19:21:51 -0700657 res |= cleanupCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700658 sharedQuotaIfaces.erase(it);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700659
JP Abgrall0dad7c22011-06-24 11:58:14 -0700660 if (sharedQuotaIfaces.empty()) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700661 std::string quotaCmd;
JP Abgrallbfa74662011-06-29 19:23:04 -0700662 quotaCmd = makeIptablesQuotaCmd(IptOpDelete, costName, sharedQuotaBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700663 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall8a932722011-07-13 19:17:35 -0700664 sharedQuotaBytes = 0;
665 if (sharedAlertBytes) {
666 removeSharedAlert();
667 sharedAlertBytes = 0;
668 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700669 }
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700670 return res;
671}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700672
673int BandwidthController::setInterfaceQuota(const char *iface, int64_t maxBytes) {
674 char ifn[MAX_IFACENAME_LEN];
675 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700676 std::string ifaceName;
677 const char *costName;
678 std::list<QuotaInfo>::iterator it;
679 std::string quotaCmd;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700680
JP Abgrall69261cb2014-06-19 18:35:24 -0700681 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700682 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700683
JP Abgrall8a932722011-07-13 19:17:35 -0700684 if (!maxBytes) {
685 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000686 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700687 return -1;
688 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700689 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700690 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700691 }
692
JP Abgrall8a932722011-07-13 19:17:35 -0700693 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000694 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700695 return -1;
696 }
697 ifaceName = ifn;
698 costName = iface;
699
JP Abgrall0dad7c22011-06-24 11:58:14 -0700700 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700701 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700702 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700703 break;
704 }
705
706 if (it == quotaIfaces.end()) {
JP Abgralle4788732013-07-02 20:28:45 -0700707 /* Preparing the iface adds a penalty/happy box check */
JP Abgrall26e0d492011-06-24 19:21:51 -0700708 res |= prepCostlyIface(ifn, QuotaUnique);
JP Abgrallbaeccc42013-06-25 09:44:10 -0700709 /*
JP Abgralle4788732013-07-02 20:28:45 -0700710 * The rejecting quota limit should go after the penalty/happy box checks
JP Abgrallbaeccc42013-06-25 09:44:10 -0700711 * or else a naughty app could just eat up the quota.
712 * So we append here.
713 */
JP Abgrall109899b2013-02-12 19:20:13 -0800714 quotaCmd = makeIptablesQuotaCmd(IptOpAppend, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700715 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700716 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000717 ALOGE("Failed set quota rule");
JP Abgrall0dad7c22011-06-24 11:58:14 -0700718 goto fail;
719 }
720
JP Abgrall8a932722011-07-13 19:17:35 -0700721 quotaIfaces.push_front(QuotaInfo(ifaceName, maxBytes, 0));
JP Abgrall0dad7c22011-06-24 11:58:14 -0700722
723 } else {
JP Abgrall8a932722011-07-13 19:17:35 -0700724 res |= updateQuota(costName, maxBytes);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700725 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000726 ALOGE("Failed update quota for %s", iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700727 goto fail;
728 }
JP Abgrall8a932722011-07-13 19:17:35 -0700729 it->quota = maxBytes;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700730 }
731 return 0;
732
733 fail:
734 /*
735 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
736 * rules in the kernel to see which ones need cleaning up.
737 * For now callers needs to choose if they want to "ndc bandwidth enable"
738 * which resets everything.
739 */
740 removeInterfaceSharedQuota(ifn);
741 return -1;
742}
743
JP Abgrall8a932722011-07-13 19:17:35 -0700744int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
745 return getInterfaceQuota("shared", bytes);
746}
747
748int BandwidthController::getInterfaceQuota(const char *costName, int64_t *bytes) {
749 FILE *fp;
750 char *fname;
751 int scanRes;
752
JP Abgrall69261cb2014-06-19 18:35:24 -0700753 if (!isIfaceName(costName))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700754 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700755
JP Abgrall8a932722011-07-13 19:17:35 -0700756 asprintf(&fname, "/proc/net/xt_quota/%s", costName);
Nick Kralevich53ea9ca2015-01-31 13:54:00 -0800757 fp = fopen(fname, "re");
JP Abgrall8a932722011-07-13 19:17:35 -0700758 free(fname);
759 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000760 ALOGE("Reading quota %s failed (%s)", costName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700761 return -1;
762 }
Mark Salyzynca0b5e22014-03-26 14:15:03 -0700763 scanRes = fscanf(fp, "%" SCNd64, bytes);
SynergyDev7776cea2014-03-16 15:48:51 -0700764 ALOGV("Read quota res=%d bytes=%" PRId64, scanRes, *bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700765 fclose(fp);
766 return scanRes == 1 ? 0 : -1;
767}
768
JP Abgrall0dad7c22011-06-24 11:58:14 -0700769int BandwidthController::removeInterfaceQuota(const char *iface) {
770
771 char ifn[MAX_IFACENAME_LEN];
772 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700773 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700774 std::list<QuotaInfo>::iterator it;
JP Abgrall26e0d492011-06-24 19:21:51 -0700775
JP Abgrall69261cb2014-06-19 18:35:24 -0700776 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700777 return -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700778 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000779 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700780 return -1;
781 }
782 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700783
JP Abgrall0dad7c22011-06-24 11:58:14 -0700784 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700785 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700786 break;
787 }
788
789 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000790 ALOGE("No such iface %s to delete", ifn);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700791 return -1;
792 }
793
794 /* This also removes the quota command of CostlyIface chain. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700795 res |= cleanupCostlyIface(ifn, QuotaUnique);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700796
797 quotaIfaces.erase(it);
798
799 return res;
800}
JP Abgrall8a932722011-07-13 19:17:35 -0700801
802int BandwidthController::updateQuota(const char *quotaName, int64_t bytes) {
803 FILE *fp;
804 char *fname;
805
JP Abgrall69261cb2014-06-19 18:35:24 -0700806 if (!isIfaceName(quotaName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700807 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName);
808 return -1;
809 }
810
JP Abgrall8a932722011-07-13 19:17:35 -0700811 asprintf(&fname, "/proc/net/xt_quota/%s", quotaName);
Nick Kralevich53ea9ca2015-01-31 13:54:00 -0800812 fp = fopen(fname, "we");
JP Abgrall8a932722011-07-13 19:17:35 -0700813 free(fname);
814 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000815 ALOGE("Updating quota %s failed (%s)", quotaName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700816 return -1;
817 }
SynergyDev7776cea2014-03-16 15:48:51 -0700818 fprintf(fp, "%" PRId64"\n", bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700819 fclose(fp);
820 return 0;
821}
822
823int BandwidthController::runIptablesAlertCmd(IptOp op, const char *alertName, int64_t bytes) {
824 int res = 0;
825 const char *opFlag;
826 char *alertQuotaCmd;
827
828 switch (op) {
829 case IptOpInsert:
830 opFlag = "-I";
831 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800832 case IptOpAppend:
833 opFlag = "-A";
834 break;
JP Abgrall8a932722011-07-13 19:17:35 -0700835 case IptOpReplace:
836 opFlag = "-R";
837 break;
838 default:
839 case IptOpDelete:
840 opFlag = "-D";
841 break;
842 }
843
JP Abgrall92009c82013-02-06 18:01:24 -0800844 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800845 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700846 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700847 free(alertQuotaCmd);
JP Abgrall92009c82013-02-06 18:01:24 -0800848 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800849 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700850 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700851 free(alertQuotaCmd);
852 return res;
853}
854
JP Abgrallc6c67342011-10-07 16:28:54 -0700855int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
856 int res = 0;
857 const char *opFlag;
JP Abgrall8a932722011-07-13 19:17:35 -0700858 char *alertQuotaCmd;
JP Abgrallc6c67342011-10-07 16:28:54 -0700859
860 switch (op) {
861 case IptOpInsert:
862 opFlag = "-I";
863 break;
JP Abgrall109899b2013-02-12 19:20:13 -0800864 case IptOpAppend:
865 opFlag = "-A";
866 break;
JP Abgrallc6c67342011-10-07 16:28:54 -0700867 case IptOpReplace:
868 opFlag = "-R";
869 break;
870 default:
871 case IptOpDelete:
872 opFlag = "-D";
873 break;
874 }
875
JP Abgrall92009c82013-02-06 18:01:24 -0800876 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD",
Nick Kralevichc2b26cb2012-02-23 13:04:26 -0800877 bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700878 res = runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrallc6c67342011-10-07 16:28:54 -0700879 free(alertQuotaCmd);
880 return res;
881}
882
883int BandwidthController::setGlobalAlert(int64_t bytes) {
884 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700885 int res = 0;
886
887 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000888 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700889 return -1;
890 }
891 if (globalAlertBytes) {
892 res = updateQuota(alertName, bytes);
893 } else {
894 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700895 if (globalAlertTetherCount) {
Steve Block3fb42e02011-10-20 11:55:56 +0100896 ALOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700897 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
898 }
JP Abgrall8a932722011-07-13 19:17:35 -0700899 }
900 globalAlertBytes = bytes;
901 return res;
902}
903
JP Abgrallc6c67342011-10-07 16:28:54 -0700904int BandwidthController::setGlobalAlertInForwardChain(void) {
905 const char *alertName = ALERT_GLOBAL_NAME;
906 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700907
JP Abgrallc6c67342011-10-07 16:28:54 -0700908 globalAlertTetherCount++;
Steve Block3fb42e02011-10-20 11:55:56 +0100909 ALOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700910
911 /*
912 * If there is no globalAlert active we are done.
913 * If there is an active globalAlert but this is not the 1st
914 * tether, we are also done.
915 */
916 if (!globalAlertBytes || globalAlertTetherCount != 1) {
917 return 0;
918 }
919
920 /* We only add the rule if this was the 1st tether added. */
921 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
922 return res;
923}
924
925int BandwidthController::removeGlobalAlert(void) {
926
927 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700928 int res = 0;
929
930 if (!globalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000931 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700932 return -1;
933 }
934 res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700935 if (globalAlertTetherCount) {
936 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
937 }
JP Abgrall8a932722011-07-13 19:17:35 -0700938 globalAlertBytes = 0;
939 return res;
940}
941
JP Abgrallc6c67342011-10-07 16:28:54 -0700942int BandwidthController::removeGlobalAlertInForwardChain(void) {
943 int res = 0;
944 const char *alertName = ALERT_GLOBAL_NAME;
945
946 if (!globalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000947 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700948 return -1;
949 }
950
951 globalAlertTetherCount--;
952 /*
953 * If there is no globalAlert active we are done.
954 * If there is an active globalAlert but there are more
955 * tethers, we are also done.
956 */
957 if (!globalAlertBytes || globalAlertTetherCount >= 1) {
958 return 0;
959 }
960
961 /* We only detete the rule if this was the last tether removed. */
962 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
963 return res;
964}
965
JP Abgrall8a932722011-07-13 19:17:35 -0700966int BandwidthController::setSharedAlert(int64_t bytes) {
967 if (!sharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000968 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700969 return -1;
970 }
971 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000972 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700973 return -1;
974 }
975 return setCostlyAlert("shared", bytes, &sharedAlertBytes);
976}
977
978int BandwidthController::removeSharedAlert(void) {
979 return removeCostlyAlert("shared", &sharedAlertBytes);
980}
981
982int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
983 std::list<QuotaInfo>::iterator it;
984
JP Abgrall69261cb2014-06-19 18:35:24 -0700985 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700986 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface);
987 return -1;
988 }
989
JP Abgrall8a932722011-07-13 19:17:35 -0700990 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000991 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700992 return -1;
993 }
994 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
995 if (it->ifaceName == iface)
996 break;
997 }
998
999 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +00001000 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -07001001 return -1;
1002 }
1003
1004 return setCostlyAlert(iface, bytes, &it->alert);
1005}
1006
1007int BandwidthController::removeInterfaceAlert(const char *iface) {
1008 std::list<QuotaInfo>::iterator it;
1009
JP Abgrall69261cb2014-06-19 18:35:24 -07001010 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001011 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface);
1012 return -1;
1013 }
1014
JP Abgrall8a932722011-07-13 19:17:35 -07001015 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
1016 if (it->ifaceName == iface)
1017 break;
1018 }
1019
1020 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +00001021 ALOGE("No prior alert set for interface %s", iface);
JP Abgrall8a932722011-07-13 19:17:35 -07001022 return -1;
1023 }
1024
1025 return removeCostlyAlert(iface, &it->alert);
1026}
1027
1028int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
1029 char *alertQuotaCmd;
JP Abgrall109899b2013-02-12 19:20:13 -08001030 char *chainName;
JP Abgrall8a932722011-07-13 19:17:35 -07001031 int res = 0;
1032 char *alertName;
1033
JP Abgrall69261cb2014-06-19 18:35:24 -07001034 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001035 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName);
1036 return -1;
1037 }
1038
JP Abgrall8a932722011-07-13 19:17:35 -07001039 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001040 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -07001041 return -1;
1042 }
1043 asprintf(&alertName, "%sAlert", costName);
1044 if (*alertBytes) {
1045 res = updateQuota(alertName, *alertBytes);
1046 } else {
JP Abgrall7e51cde2013-07-03 13:33:05 -07001047 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall109899b2013-02-12 19:20:13 -08001048 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-A", chainName, bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001049 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001050 free(alertQuotaCmd);
JP Abgrall109899b2013-02-12 19:20:13 -08001051 free(chainName);
JP Abgrall8a932722011-07-13 19:17:35 -07001052 }
1053 *alertBytes = bytes;
1054 free(alertName);
1055 return res;
1056}
1057
1058int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
1059 char *alertQuotaCmd;
1060 char *chainName;
1061 char *alertName;
1062 int res = 0;
1063
JP Abgrall69261cb2014-06-19 18:35:24 -07001064 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -07001065 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName);
1066 return -1;
1067 }
1068
JP Abgrall8a932722011-07-13 19:17:35 -07001069 if (!*alertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +00001070 ALOGE("No prior alert set for %s alert", costName);
JP Abgrall8a932722011-07-13 19:17:35 -07001071 return -1;
1072 }
1073
Jesper Hanssona9d791f2012-04-27 13:54:27 +02001074 asprintf(&alertName, "%sAlert", costName);
JP Abgrall7e51cde2013-07-03 13:33:05 -07001075 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall92009c82013-02-06 18:01:24 -08001076 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -07001077 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -07001078 free(alertQuotaCmd);
1079 free(chainName);
1080
1081 *alertBytes = 0;
1082 free(alertName);
1083 return res;
1084}
JP Abgralldb7da582011-09-18 12:57:32 -07001085
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001086void BandwidthController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
1087 for (TetherStats& existing : statsList) {
1088 if (existing.addStatsIfMatch(stats)) {
1089 return;
1090 }
1091 }
1092 // No match. Insert a new interface pair.
1093 statsList.push_back(stats);
1094}
1095
JP Abgralldb7da582011-09-18 12:57:32 -07001096/*
1097 * Parse the ptks and bytes out of:
JP Abgrallbaeccc42013-06-25 09:44:10 -07001098 * Chain natctrl_tether_counters (4 references)
1099 * pkts bytes target prot opt in out source destination
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001100 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1101 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
1102 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
1103 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001104 * or:
1105 * Chain natctrl_tether_counters (0 references)
1106 * pkts bytes target prot opt in out source destination
1107 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
1108 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
1109 *
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001110 * It results in an error if invoked and no tethering counter rules exist. The constraint
1111 * helps detect complete parsing failure.
JP Abgralldb7da582011-09-18 12:57:32 -07001112 */
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001113int BandwidthController::addForwardChainStats(const TetherStats& filter,
1114 TetherStatsList& statsList, FILE *fp,
1115 std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -07001116 int res;
1117 char lineBuffer[MAX_IPT_OUTPUT_LINE_LEN];
1118 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
1119 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
1120 char rest[MAX_IPT_OUTPUT_LINE_LEN];
1121
JP Abgrallbaeccc42013-06-25 09:44:10 -07001122 TetherStats stats;
JP Abgralldb7da582011-09-18 12:57:32 -07001123 char *buffPtr;
1124 int64_t packets, bytes;
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001125 int statsFound = 0;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001126
1127 bool filterPair = filter.intIface[0] && filter.extIface[0];
1128
1129 char *filterMsg = filter.getStatsLine();
1130 ALOGV("filter: %s", filterMsg);
1131 free(filterMsg);
1132
1133 stats = filter;
JP Abgralldb7da582011-09-18 12:57:32 -07001134
1135 while (NULL != (buffPtr = fgets(lineBuffer, MAX_IPT_OUTPUT_LINE_LEN, fp))) {
1136 /* Clean up, so a failed parse can still print info */
1137 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001138 if (strstr(buffPtr, "0.0.0.0")) {
1139 // IPv4 has -- indicating what to do with fragments...
1140 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1141 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
1142 &packets, &bytes, iface0, iface1, rest);
1143 } else {
1144 // ... but IPv6 does not.
1145 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
1146 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all %s %s ::/%s",
1147 &packets, &bytes, iface0, iface1, rest);
1148 }
SynergyDev7776cea2014-03-16 15:48:51 -07001149 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 -07001150 iface0, iface1, packets, bytes, rest, buffPtr);
JP Abgralla2a64f02011-11-11 20:36:16 -08001151 extraProcessingInfo += buffPtr;
1152
JP Abgralldb7da582011-09-18 12:57:32 -07001153 if (res != 5) {
1154 continue;
1155 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001156 /*
1157 * The following assumes that the 1st rule has in:extIface out:intIface,
1158 * which is what NatController sets up.
1159 * If not filtering, the 1st match rx, and sets up the pair for the tx side.
1160 */
1161 if (filter.intIface[0] && filter.extIface[0]) {
1162 if (filter.intIface == iface0 && filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001163 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 -07001164 stats.rxPackets = packets;
1165 stats.rxBytes = bytes;
1166 } else if (filter.intIface == iface1 && filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001167 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 -07001168 stats.txPackets = packets;
1169 stats.txBytes = bytes;
1170 }
1171 } else if (filter.intIface[0] || filter.extIface[0]) {
1172 if (filter.intIface == iface0 || filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001173 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 -07001174 stats.intIface = iface0;
1175 stats.extIface = iface1;
1176 stats.rxPackets = packets;
1177 stats.rxBytes = bytes;
1178 } else if (filter.intIface == iface1 || filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001179 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 -07001180 stats.intIface = iface1;
1181 stats.extIface = iface0;
1182 stats.txPackets = packets;
1183 stats.txBytes = bytes;
1184 }
1185 } else /* if (!filter.intFace[0] && !filter.extIface[0]) */ {
1186 if (!stats.intIface[0]) {
SynergyDev7776cea2014-03-16 15:48:51 -07001187 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 -07001188 stats.intIface = iface0;
1189 stats.extIface = iface1;
1190 stats.rxPackets = packets;
1191 stats.rxBytes = bytes;
1192 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001193 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 -07001194 stats.txPackets = packets;
1195 stats.txBytes = bytes;
1196 }
1197 }
1198 if (stats.rxBytes != -1 && stats.txBytes != -1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001199 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64" filterPair=%d", stats.rxBytes, stats.txBytes, filterPair);
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001200 addStats(statsList, stats);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001201 if (filterPair) {
JP Abgrallbaeccc42013-06-25 09:44:10 -07001202 return 0;
1203 } else {
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001204 statsFound++;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001205 stats = filter;
1206 }
JP Abgralldb7da582011-09-18 12:57:32 -07001207 }
1208 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001209
1210 /* It is always an error to find only one side of the stats. */
1211 /* It is an error to find nothing when not filtering. */
1212 if (((stats.rxBytes == -1) != (stats.txBytes == -1)) ||
1213 (!statsFound && !filterPair)) {
1214 return -1;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001215 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001216 return 0;
JP Abgralldb7da582011-09-18 12:57:32 -07001217}
1218
JP Abgrallbaeccc42013-06-25 09:44:10 -07001219char *BandwidthController::TetherStats::getStatsLine(void) const {
JP Abgralldb7da582011-09-18 12:57:32 -07001220 char *msg;
SynergyDev7776cea2014-03-16 15:48:51 -07001221 asprintf(&msg, "%s %s %" PRId64" %" PRId64" %" PRId64" %" PRId64, intIface.c_str(), extIface.c_str(),
JP Abgralldb7da582011-09-18 12:57:32 -07001222 rxBytes, rxPackets, txBytes, txPackets);
1223 return msg;
1224}
1225
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001226std::string getTetherStatsCommand(const char *binary) {
JP Abgralldb7da582011-09-18 12:57:32 -07001227 /*
1228 * Why not use some kind of lib to talk to iptables?
1229 * Because the only libs are libiptc and libip6tc in iptables, and they are
1230 * not easy to use. They require the known iptables match modules to be
1231 * preloaded/linked, and require apparently a lot of wrapper code to get
1232 * the wanted info.
1233 */
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001234 return android::base::StringPrintf("%s -nvx -w -L %s", binary,
1235 NatController::LOCAL_TETHER_COUNTERS_CHAIN);
1236}
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001237
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001238int BandwidthController::getTetherStats(SocketClient *cli, TetherStats& filter,
1239 std::string &extraProcessingInfo) {
1240 int res = 0;
1241 std::string fullCmd;
1242 FILE *iptOutput;
1243
1244 TetherStatsList statsList;
1245
1246 for (const auto binary : {IPTABLES_PATH, IP6TABLES_PATH}) {
1247 fullCmd = getTetherStatsCommand(binary);
1248 iptOutput = popenFunction(fullCmd.c_str(), "r");
1249 if (!iptOutput) {
1250 ALOGE("Failed to run %s err=%s", fullCmd.c_str(), strerror(errno));
1251 extraProcessingInfo += "Failed to run iptables.";
1252 return -1;
1253 }
1254
1255 res = addForwardChainStats(filter, statsList, iptOutput, extraProcessingInfo);
1256 pclose(iptOutput);
1257 if (res != 0) {
1258 return res;
1259 }
1260 }
JP Abgralldb7da582011-09-18 12:57:32 -07001261
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001262 if (filter.intIface[0] && filter.extIface[0] && statsList.size() == 1) {
1263 cli->sendMsg(ResponseCode::TetheringStatsResult, statsList[0].getStatsLine(), false);
1264 } else {
1265 for (const auto& stats: statsList) {
1266 cli->sendMsg(ResponseCode::TetheringStatsListResult, stats.getStatsLine(), false);
1267 }
1268 if (res == 0) {
1269 cli->sendMsg(ResponseCode::CommandOkay, "Tethering stats list completed", false);
1270 }
1271 }
1272
JP Abgralldb7da582011-09-18 12:57:32 -07001273 return res;
1274}
JP Abgrall0e540ec2013-08-26 15:13:10 -07001275
1276void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001277 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
1278 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001279
1280 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001281 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
1282 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001283 return;
1284 }
1285 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001286 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001287}
1288
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001289void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
1290 std::stringstream stream(ruleList);
1291 std::string rule;
1292 std::vector<std::string> clearCommands = { "*filter" };
1293 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001294
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001295 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
1296 while (std::getline(stream, rule, '\n')) {
1297 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
1298 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
1299 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
1300
1301 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -07001302 continue;
1303 }
1304
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001305 clearCommands.push_back(android::base::StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001306 if (doRemove) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001307 clearCommands.push_back(android::base::StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001308 }
1309 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001310
1311 if (clearCommands.size() == 1) {
1312 // No rules found.
1313 return;
1314 }
1315
1316 clearCommands.push_back("COMMIT\n");
1317 iptablesRestoreFunction(V4V6, android::base::Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001318}