blob: 526048728b17e8d77b69a7a83851465373392c0d [file] [log] [blame]
JP Abgrall4a5f5ca2011-06-15 18:37:39 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
JP Abgralle4788732013-07-02 20:28:45 -070017// #define LOG_NDEBUG 0
JP Abgralldb7da582011-09-18 12:57:32 -070018
19/*
20 * The CommandListener, FrameworkListener don't allow for
21 * multiple calls in parallel to reach the BandwidthController.
22 * If they ever were to allow it, then netd/ would need some tweaking.
23 */
24
Lorenzo Colitti13debb82016-03-27 17:46:30 +090025#include <string>
26#include <vector>
27
JP Abgrall8a932722011-07-13 19:17:35 -070028#include <errno.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070029#include <fcntl.h>
JP Abgralldb7da582011-09-18 12:57:32 -070030#include <stdio.h>
JP Abgrall8a932722011-07-13 19:17:35 -070031#include <stdlib.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070032#include <string.h>
Nick Kralevich0b2b9022014-05-01 13:10:45 -070033#include <ctype.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070034
Matthew Leach2a54d962013-01-14 15:07:12 +000035#define __STDC_FORMAT_MACROS 1
36#include <inttypes.h>
37
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070038#include <sys/socket.h>
39#include <sys/stat.h>
40#include <sys/types.h>
41#include <sys/wait.h>
42
43#include <linux/netlink.h>
44#include <linux/rtnetlink.h>
45#include <linux/pkt_sched.h>
46
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090047#include "android-base/stringprintf.h"
Lorenzo Colitti13debb82016-03-27 17:46:30 +090048#include "android-base/strings.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070049#define LOG_TAG "BandwidthController"
50#include <cutils/log.h>
51#include <cutils/properties.h>
Rom Lemarchand14150212013-01-24 10:01:04 -080052#include <logwrap/logwrap.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070053
JP Abgrall0031cea2012-04-17 16:38:23 -070054#include "NetdConstants.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070055#include "BandwidthController.h"
JP Abgrallbaeccc42013-06-25 09:44:10 -070056#include "NatController.h" /* For LOCAL_TETHER_COUNTERS_CHAIN */
57#include "ResponseCode.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070058
JP Abgralldb7da582011-09-18 12:57:32 -070059/* Alphabetical */
Lorenzo Colitti3c272702017-04-26 15:48:13 +090060#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s\n"
Jeff Sharkey8e188ed2012-07-12 18:32:03 -070061const char* BandwidthController::LOCAL_INPUT = "bw_INPUT";
62const char* BandwidthController::LOCAL_FORWARD = "bw_FORWARD";
63const char* BandwidthController::LOCAL_OUTPUT = "bw_OUTPUT";
64const char* BandwidthController::LOCAL_RAW_PREROUTING = "bw_raw_PREROUTING";
65const char* BandwidthController::LOCAL_MANGLE_POSTROUTING = "bw_mangle_POSTROUTING";
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090066
Lorenzo Colitti86a47982016-03-18 17:52:25 +090067auto BandwidthController::execFunction = android_fork_execvp;
68auto BandwidthController::popenFunction = popen;
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090069auto BandwidthController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
Lorenzo Colitti86a47982016-03-18 17:52:25 +090070
Lorenzo Colitti3c272702017-04-26 15:48:13 +090071using android::base::StringAppendF;
72using android::base::StringPrintf;
73
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090074namespace {
75
76const char ALERT_GLOBAL_NAME[] = "globalAlert";
77const int MAX_CMD_ARGS = 32;
78const int MAX_CMD_LEN = 1024;
79const int MAX_IFACENAME_LEN = 64;
80const int MAX_IPT_OUTPUT_LINE_LEN = 256;
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090081const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colitti3c272702017-04-26 15:48:13 +090082const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
Lorenzo Colittice6748a2017-02-02 01:34:33 +090083 "*filter\n"
84 "-nvx -L %s\n"
85 "COMMIT\n", NatController::LOCAL_TETHER_COUNTERS_CHAIN);
86
JP Abgralldb7da582011-09-18 12:57:32 -070087
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070088/**
89 * Some comments about the rules:
90 * * Ordering
91 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070092 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070093 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070094 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070095 *
96 * * global quota vs per interface quota
97 * - global quota for all costly interfaces uses a single costly chain:
98 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -070099 * iptables -N bw_costly_shared
100 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
101 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
102 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -0700103 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -0700104 * iptables -A bw_costly_shared --jump bw_penalty_box
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900105 * iptables -A bw_penalty_box --jump bw_happy_box
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900106 * iptables -A bw_happy_box --jump bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700107 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700108 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700109 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
110 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700111 *
112 * - quota per interface. This is achieve by having "costly" chains per quota.
113 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700114 * iptables -N bw_costly_iface0
115 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
116 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
117 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -0700118 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -0700119 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700120 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900121 * * Penalty box, happy box and data saver.
122 * - bw_penalty box is a blacklist of apps that are rejected.
123 * - bw_happy_box is a whitelist of apps. It always includes all system apps
124 * - bw_data_saver implements data usage restrictions.
125 * - Via the UI the user can add and remove apps from the whitelist and
126 * blacklist, and turn on/off data saver.
127 * - The blacklist takes precedence over the whitelist and the whitelist
128 * takes precedence over data saver.
129 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700130 * * bw_penalty_box handling:
131 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900132 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700133 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700134 * --jump REJECT --reject-with icmp-port-unreachable
135 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700136 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900137 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700138 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700139 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700140 * --jump RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900141 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900142 * * bw_data_saver handling:
143 * - The bw_data_saver comes after the happy box.
144 * Enable data saver:
145 * iptables -R 1 bw_data_saver --jump REJECT --reject-with icmp-port-unreachable
146 * Disable data saver:
147 * iptables -R 1 bw_data_saver --jump RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700148 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900149
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900150const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900151const std::string HAPPY_BOX_WHITELIST_COMMAND = StringPrintf(
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900152 "-I bw_happy_box -m owner --uid-owner %d-%d --jump RETURN", 0, MAX_SYSTEM_UID);
153
154static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700155 /*
156 * Cleanup rules.
JP Abgrall7e51cde2013-07-03 13:33:05 -0700157 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
JP Abgrall0031cea2012-04-17 16:38:23 -0700158 * to allow coexistance.
JP Abgrall39f8f242011-06-29 19:21:58 -0700159 */
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900160 "*filter",
161 ":bw_INPUT -",
162 ":bw_OUTPUT -",
163 ":bw_FORWARD -",
164 ":bw_happy_box -",
165 ":bw_penalty_box -",
166 ":bw_data_saver -",
167 ":bw_costly_shared -",
168 "COMMIT",
169 "*raw",
170 ":bw_raw_PREROUTING -",
171 "COMMIT",
172 "*mangle",
173 ":bw_mangle_POSTROUTING -",
174 COMMIT_AND_CLOSE
JP Abgrall0031cea2012-04-17 16:38:23 -0700175};
176
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900177static const std::vector<std::string> IPT_BASIC_ACCOUNTING_COMMANDS = {
178 "*filter",
JP Abgrall0031cea2012-04-17 16:38:23 -0700179 "-A bw_INPUT -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall0031cea2012-04-17 16:38:23 -0700180 "-A bw_OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900181 "-A bw_costly_shared --jump bw_penalty_box",
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900182 "-A bw_penalty_box --jump bw_happy_box",
183 "-A bw_happy_box --jump bw_data_saver",
184 "-A bw_data_saver -j RETURN",
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900185 HAPPY_BOX_WHITELIST_COMMAND,
186 "COMMIT",
187
188 "*raw",
189 "-A bw_raw_PREROUTING -m owner --socket-exists", /* This is a tracking rule. */
190 "COMMIT",
191
192 "*mangle",
193 "-A bw_mangle_POSTROUTING -m owner --socket-exists", /* This is a tracking rule. */
194 COMMIT_AND_CLOSE
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900195};
196
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900197
198} // namespace
199
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700200BandwidthController::BandwidthController(void) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700201}
202
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700203int BandwidthController::runIpxtablesCmd(const char *cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700204 IptFailureLog failureHandling) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700205 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700206
Steve Block3fb42e02011-10-20 11:55:56 +0100207 ALOGV("runIpxtablesCmd(cmd=%s)", cmd);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700208 res |= runIptablesCmd(cmd, jumpHandling, IptIpV4, failureHandling);
209 res |= runIptablesCmd(cmd, jumpHandling, IptIpV6, failureHandling);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700210 return res;
211}
212
JP Abgrall26e0d492011-06-24 19:21:51 -0700213int BandwidthController::StrncpyAndCheck(char *buffer, const char *src, size_t buffSize) {
214
215 memset(buffer, '\0', buffSize); // strncpy() is not filling leftover with '\0'
216 strncpy(buffer, src, buffSize);
217 return buffer[buffSize - 1];
218}
219
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700220int BandwidthController::runIptablesCmd(const char *cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700221 IptIpVer iptVer, IptFailureLog failureHandling) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700222 char buffer[MAX_CMD_LEN];
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700223 const char *argv[MAX_CMD_ARGS];
JP Abgrall26e0d492011-06-24 19:21:51 -0700224 int argc = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700225 char *next = buffer;
226 char *tmp;
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700227 int res;
Rom Lemarchand14150212013-01-24 10:01:04 -0800228 int status = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700229
JP Abgrall0dad7c22011-06-24 11:58:14 -0700230 std::string fullCmd = cmd;
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900231 fullCmd += jumpToString(jumpHandling);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700232
Paul Jensen94b2ab92015-08-04 10:35:05 -0400233 fullCmd.insert(0, " -w ");
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700234 fullCmd.insert(0, iptVer == IptIpV4 ? IPTABLES_PATH : IP6TABLES_PATH);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700235
Rom Lemarchand14150212013-01-24 10:01:04 -0800236 if (StrncpyAndCheck(buffer, fullCmd.c_str(), sizeof(buffer))) {
237 ALOGE("iptables command too long");
238 return -1;
239 }
240
241 argc = 0;
242 while ((tmp = strsep(&next, " "))) {
243 argv[argc++] = tmp;
244 if (argc >= MAX_CMD_ARGS) {
245 ALOGE("iptables argument overflow");
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700246 return -1;
247 }
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700248 }
Rom Lemarchand14150212013-01-24 10:01:04 -0800249
250 argv[argc] = NULL;
Lorenzo Colitti86a47982016-03-18 17:52:25 +0900251 res = execFunction(argc, (char **)argv, &status, false,
Rom Lemarchand14150212013-01-24 10:01:04 -0800252 failureHandling == IptFailShow);
JP Abgrallc8dc63b2013-02-13 16:30:00 -0800253 res = res || !WIFEXITED(status) || WEXITSTATUS(status);
254 if (res && failureHandling == IptFailShow) {
255 ALOGE("runIptablesCmd(): res=%d status=%d failed %s", res, status,
256 fullCmd.c_str());
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700257 }
258 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700259}
260
JP Abgrall0e540ec2013-08-26 15:13:10 -0700261void BandwidthController::flushCleanTables(bool doClean) {
262 /* Flush and remove the bw_costly_<iface> tables */
263 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700264
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900265 std::string commands = android::base::Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900266 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700267}
JP Abgrall0031cea2012-04-17 16:38:23 -0700268
JP Abgrall0e540ec2013-08-26 15:13:10 -0700269int BandwidthController::setupIptablesHooks(void) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700270 /* flush+clean is allowed to fail */
271 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700272 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700273}
274
275int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrall0031cea2012-04-17 16:38:23 -0700276 char value[PROPERTY_VALUE_MAX];
277
278 if (!force) {
279 property_get("persist.bandwidth.enable", value, "1");
280 if (!strcmp(value, "0"))
281 return 0;
282 }
JP Abgrall8a932722011-07-13 19:17:35 -0700283
JP Abgralldb7da582011-09-18 12:57:32 -0700284 /* Let's pretend we started from scratch ... */
JP Abgrall8a932722011-07-13 19:17:35 -0700285 sharedQuotaIfaces.clear();
286 quotaIfaces.clear();
JP Abgralldb7da582011-09-18 12:57:32 -0700287 globalAlertBytes = 0;
JP Abgrallc6c67342011-10-07 16:28:54 -0700288 globalAlertTetherCount = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700289 sharedQuotaBytes = sharedAlertBytes = 0;
290
JP Abgrall0e540ec2013-08-26 15:13:10 -0700291 flushCleanTables(false);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900292 std::string commands = android::base::Join(IPT_BASIC_ACCOUNTING_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900293 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700294}
295
296int BandwidthController::disableBandwidthControl(void) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700297
298 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700299 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700300}
301
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900302int BandwidthController::enableDataSaver(bool enable) {
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900303 std::string cmd = StringPrintf(
304 "*filter\n"
305 "-R bw_data_saver 1%s\n"
306 "COMMIT\n", jumpToString(enable ? IptJumpReject : IptJumpReturn));
307 return iptablesRestoreFunction(V4V6, cmd, nullptr);
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900308}
309
JP Abgrall8a932722011-07-13 19:17:35 -0700310int BandwidthController::runCommands(int numCommands, const char *commands[],
311 RunCmdErrHandling cmdErrHandling) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700312 int res = 0;
JP Abgrallad729ac2012-04-24 23:27:44 -0700313 IptFailureLog failureLogging = IptFailShow;
314 if (cmdErrHandling == RunCmdFailureOk) {
315 failureLogging = IptFailHide;
316 }
Steve Block3fb42e02011-10-20 11:55:56 +0100317 ALOGV("runCommands(): %d commands", numCommands);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700318 for (int cmdNum = 0; cmdNum < numCommands; cmdNum++) {
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700319 res = runIpxtablesCmd(commands[cmdNum], IptJumpNoAdd, failureLogging);
JP Abgrall0031cea2012-04-17 16:38:23 -0700320 if (res && cmdErrHandling != RunCmdFailureOk)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700321 return res;
322 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700323 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700324}
325
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700326int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900327 return manipulateNaughtyApps(numUids, appUids, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700328}
329
330int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900331 return manipulateNaughtyApps(numUids, appUids, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700332}
333
JP Abgralle4788732013-07-02 20:28:45 -0700334int BandwidthController::addNiceApps(int numUids, char *appUids[]) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900335 return manipulateNiceApps(numUids, appUids, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700336}
337
338int BandwidthController::removeNiceApps(int numUids, char *appUids[]) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900339 return manipulateNiceApps(numUids, appUids, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700340}
341
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900342int BandwidthController::manipulateNaughtyApps(int numUids, char *appStrUids[], IptOp op) {
343 return manipulateSpecialApps(numUids, appStrUids, "bw_penalty_box", IptJumpReject, op);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700344}
345
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900346int BandwidthController::manipulateNiceApps(int numUids, char *appStrUids[], IptOp op) {
347 return manipulateSpecialApps(numUids, appStrUids, "bw_happy_box", IptJumpReturn, op);
JP Abgralle4788732013-07-02 20:28:45 -0700348}
349
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700350int BandwidthController::manipulateSpecialApps(int numUids, char *appStrUids[],
351 const char *chain,
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900352 IptJumpOp jumpHandling, IptOp op) {
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900353 std::string cmd = "*filter\n";
354 for (int uidNum = 0; uidNum < numUids; uidNum++) {
355 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain,
356 appStrUids[uidNum], jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700357 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900358 StringAppendF(&cmd, "COMMIT\n");
359 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700360}
361
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900362std::string BandwidthController::makeIptablesQuotaCmd(IptFullOp op, const char *costName, int64_t quota) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700363 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700364 char *buff;
365 const char *opFlag;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700366
SynergyDev7776cea2014-03-16 15:48:51 -0700367 ALOGV("makeIptablesQuotaCmd(%d, %" PRId64")", op, quota);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700368
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700369 switch (op) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900370 case IptFullOpInsert:
JP Abgrall8a932722011-07-13 19:17:35 -0700371 opFlag = "-I";
372 break;
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900373 case IptFullOpAppend:
JP Abgrall109899b2013-02-12 19:20:13 -0800374 opFlag = "-A";
375 break;
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900376 case IptFullOpDelete:
JP Abgrall8a932722011-07-13 19:17:35 -0700377 opFlag = "-D";
378 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700379 }
JP Abgrall8a932722011-07-13 19:17:35 -0700380
JP Abgrallbfa74662011-06-29 19:23:04 -0700381 // The requried IP version specific --jump REJECT ... will be added later.
SynergyDev7776cea2014-03-16 15:48:51 -0700382 asprintf(&buff, "%s bw_costly_%s -m quota2 ! --quota %" PRId64" --name %s", opFlag, costName, quota,
JP Abgrall8a932722011-07-13 19:17:35 -0700383 costName);
384 res = buff;
385 free(buff);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700386 return res;
387}
388
JP Abgrall26e0d492011-06-24 19:21:51 -0700389int BandwidthController::prepCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700390 char cmd[MAX_CMD_LEN];
JP Abgrall0031cea2012-04-17 16:38:23 -0700391 int res = 0, res1, res2;
JP Abgrall8a932722011-07-13 19:17:35 -0700392 int ruleInsertPos = 1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700393 std::string costString;
394 const char *costCString;
395
JP Abgrall0dad7c22011-06-24 11:58:14 -0700396 /* The "-N costly" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700397 switch (quotaType) {
398 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700399 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700400 costString += ifn;
401 costCString = costString.c_str();
JP Abgrall0031cea2012-04-17 16:38:23 -0700402 /*
JP Abgrall7e51cde2013-07-03 13:33:05 -0700403 * Flush the bw_costly_<iface> is allowed to fail in case it didn't exist.
JP Abgrall0031cea2012-04-17 16:38:23 -0700404 * Creating a new one is allowed to fail in case it existed.
405 * This helps with netd restarts.
406 */
407 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700408 res1 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700409 snprintf(cmd, sizeof(cmd), "-N %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700410 res2 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700411 res = (res1 && res2) || (!res1 && !res2);
412
JP Abgrall7e51cde2013-07-03 13:33:05 -0700413 snprintf(cmd, sizeof(cmd), "-A %s -j bw_penalty_box", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700414 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall26e0d492011-06-24 19:21:51 -0700415 break;
416 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700417 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700418 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700419 }
420
JP Abgrall8a932722011-07-13 19:17:35 -0700421 if (globalAlertBytes) {
422 /* The alert rule comes 1st */
423 ruleInsertPos = 2;
424 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700425
426 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700427 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700428
429 snprintf(cmd, sizeof(cmd), "-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700430 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall0031cea2012-04-17 16:38:23 -0700431
432 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700433 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700434
435 snprintf(cmd, sizeof(cmd), "-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700436 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900437
438 snprintf(cmd, sizeof(cmd), "-D bw_FORWARD -o %s --jump %s", ifn, costCString);
439 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
440 snprintf(cmd, sizeof(cmd), "-A bw_FORWARD -o %s --jump %s", ifn, costCString);
441 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
442
JP Abgrall0dad7c22011-06-24 11:58:14 -0700443 return res;
444}
445
JP Abgrall26e0d492011-06-24 19:21:51 -0700446int BandwidthController::cleanupCostlyIface(const char *ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700447 char cmd[MAX_CMD_LEN];
448 int res = 0;
449 std::string costString;
450 const char *costCString;
451
JP Abgrall26e0d492011-06-24 19:21:51 -0700452 switch (quotaType) {
453 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700454 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700455 costString += ifn;
456 costCString = costString.c_str();
JP Abgrall26e0d492011-06-24 19:21:51 -0700457 break;
458 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700459 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700460 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700461 }
462
JP Abgrall0031cea2012-04-17 16:38:23 -0700463 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn, costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700464 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900465 for (const auto tableName : {LOCAL_OUTPUT, LOCAL_FORWARD}) {
466 snprintf(cmd, sizeof(cmd), "-D %s -o %s --jump %s", tableName, ifn, costCString);
467 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
468 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700469
JP Abgrall7e51cde2013-07-03 13:33:05 -0700470 /* The "-N bw_costly_shared" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700471 if (quotaType == QuotaUnique) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700472 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700473 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgralla9f802c2011-06-29 15:46:45 -0700474 snprintf(cmd, sizeof(cmd), "-X %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700475 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700476 }
477 return res;
478}
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700479
JP Abgrall0dad7c22011-06-24 11:58:14 -0700480int BandwidthController::setInterfaceSharedQuota(const char *iface, int64_t maxBytes) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700481 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700482 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700483 std::string quotaCmd;
JP Abgrall8a932722011-07-13 19:17:35 -0700484 std::string ifaceName;
485 ;
JP Abgrallbfa74662011-06-29 19:23:04 -0700486 const char *costName = "shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700487 std::list<std::string>::iterator it;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700488
JP Abgrall8a932722011-07-13 19:17:35 -0700489 if (!maxBytes) {
490 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000491 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700492 return -1;
493 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700494 if (!isIfaceName(iface))
495 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700496 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000497 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700498 return -1;
499 }
500 ifaceName = ifn;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700501
502 if (maxBytes == -1) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700503 return removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700504 }
505
506 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700507 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
508 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700509 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700510 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700511
JP Abgrall0dad7c22011-06-24 11:58:14 -0700512 if (it == sharedQuotaIfaces.end()) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700513 res |= prepCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700514 if (sharedQuotaIfaces.empty()) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900515 quotaCmd = makeIptablesQuotaCmd(IptFullOpInsert, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700516 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700517 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000518 ALOGE("Failed set quota rule");
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700519 goto fail;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700520 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700521 sharedQuotaBytes = maxBytes;
522 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700523 sharedQuotaIfaces.push_front(ifaceName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700524
525 }
526
527 if (maxBytes != sharedQuotaBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700528 res |= updateQuota(costName, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700529 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000530 ALOGE("Failed update quota for %s", costName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700531 goto fail;
532 }
533 sharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700534 }
535 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700536
537 fail:
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700538 /*
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700539 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
540 * rules in the kernel to see which ones need cleaning up.
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700541 * For now callers needs to choose if they want to "ndc bandwidth enable"
542 * which resets everything.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700543 */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700544 removeInterfaceSharedQuota(ifn);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700545 return -1;
546}
547
JP Abgrall8a932722011-07-13 19:17:35 -0700548/* It will also cleanup any shared alerts */
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700549int BandwidthController::removeInterfaceSharedQuota(const char *iface) {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700550 char ifn[MAX_IFACENAME_LEN];
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700551 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700552 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700553 std::list<std::string>::iterator it;
JP Abgrallbfa74662011-06-29 19:23:04 -0700554 const char *costName = "shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700555
JP Abgrall69261cb2014-06-19 18:35:24 -0700556 if (!isIfaceName(iface))
557 return -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700558 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000559 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700560 return -1;
561 }
JP Abgrall8a932722011-07-13 19:17:35 -0700562 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700563
JP Abgrall0dad7c22011-06-24 11:58:14 -0700564 for (it = sharedQuotaIfaces.begin(); it != sharedQuotaIfaces.end(); it++) {
565 if (*it == ifaceName)
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700566 break;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700567 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700568 if (it == sharedQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000569 ALOGE("No such iface %s to delete", ifn);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700570 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700571 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700572
JP Abgrall26e0d492011-06-24 19:21:51 -0700573 res |= cleanupCostlyIface(ifn, QuotaShared);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700574 sharedQuotaIfaces.erase(it);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700575
JP Abgrall0dad7c22011-06-24 11:58:14 -0700576 if (sharedQuotaIfaces.empty()) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700577 std::string quotaCmd;
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900578 quotaCmd = makeIptablesQuotaCmd(IptFullOpDelete, costName, sharedQuotaBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700579 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall8a932722011-07-13 19:17:35 -0700580 sharedQuotaBytes = 0;
581 if (sharedAlertBytes) {
582 removeSharedAlert();
583 sharedAlertBytes = 0;
584 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700585 }
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700586 return res;
587}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700588
589int BandwidthController::setInterfaceQuota(const char *iface, int64_t maxBytes) {
590 char ifn[MAX_IFACENAME_LEN];
591 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700592 std::string ifaceName;
593 const char *costName;
594 std::list<QuotaInfo>::iterator it;
595 std::string quotaCmd;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700596
JP Abgrall69261cb2014-06-19 18:35:24 -0700597 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700598 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700599
JP Abgrall8a932722011-07-13 19:17:35 -0700600 if (!maxBytes) {
601 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000602 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700603 return -1;
604 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700605 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700606 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700607 }
608
JP Abgrall8a932722011-07-13 19:17:35 -0700609 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000610 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700611 return -1;
612 }
613 ifaceName = ifn;
614 costName = iface;
615
JP Abgrall0dad7c22011-06-24 11:58:14 -0700616 /* Insert ingress quota. */
JP Abgrall0dad7c22011-06-24 11:58:14 -0700617 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700618 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700619 break;
620 }
621
622 if (it == quotaIfaces.end()) {
JP Abgralle4788732013-07-02 20:28:45 -0700623 /* Preparing the iface adds a penalty/happy box check */
JP Abgrall26e0d492011-06-24 19:21:51 -0700624 res |= prepCostlyIface(ifn, QuotaUnique);
JP Abgrallbaeccc42013-06-25 09:44:10 -0700625 /*
JP Abgralle4788732013-07-02 20:28:45 -0700626 * The rejecting quota limit should go after the penalty/happy box checks
JP Abgrallbaeccc42013-06-25 09:44:10 -0700627 * or else a naughty app could just eat up the quota.
628 * So we append here.
629 */
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900630 quotaCmd = makeIptablesQuotaCmd(IptFullOpAppend, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700631 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700632 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000633 ALOGE("Failed set quota rule");
JP Abgrall0dad7c22011-06-24 11:58:14 -0700634 goto fail;
635 }
636
JP Abgrall8a932722011-07-13 19:17:35 -0700637 quotaIfaces.push_front(QuotaInfo(ifaceName, maxBytes, 0));
JP Abgrall0dad7c22011-06-24 11:58:14 -0700638
639 } else {
JP Abgrall8a932722011-07-13 19:17:35 -0700640 res |= updateQuota(costName, maxBytes);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700641 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000642 ALOGE("Failed update quota for %s", iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700643 goto fail;
644 }
JP Abgrall8a932722011-07-13 19:17:35 -0700645 it->quota = maxBytes;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700646 }
647 return 0;
648
649 fail:
650 /*
651 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
652 * rules in the kernel to see which ones need cleaning up.
653 * For now callers needs to choose if they want to "ndc bandwidth enable"
654 * which resets everything.
655 */
656 removeInterfaceSharedQuota(ifn);
657 return -1;
658}
659
JP Abgrall8a932722011-07-13 19:17:35 -0700660int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
661 return getInterfaceQuota("shared", bytes);
662}
663
664int BandwidthController::getInterfaceQuota(const char *costName, int64_t *bytes) {
665 FILE *fp;
666 char *fname;
667 int scanRes;
668
JP Abgrall69261cb2014-06-19 18:35:24 -0700669 if (!isIfaceName(costName))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700670 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700671
JP Abgrall8a932722011-07-13 19:17:35 -0700672 asprintf(&fname, "/proc/net/xt_quota/%s", costName);
Nick Kralevich53ea9ca2015-01-31 13:54:00 -0800673 fp = fopen(fname, "re");
JP Abgrall8a932722011-07-13 19:17:35 -0700674 free(fname);
675 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000676 ALOGE("Reading quota %s failed (%s)", costName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700677 return -1;
678 }
Mark Salyzynca0b5e22014-03-26 14:15:03 -0700679 scanRes = fscanf(fp, "%" SCNd64, bytes);
SynergyDev7776cea2014-03-16 15:48:51 -0700680 ALOGV("Read quota res=%d bytes=%" PRId64, scanRes, *bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700681 fclose(fp);
682 return scanRes == 1 ? 0 : -1;
683}
684
JP Abgrall0dad7c22011-06-24 11:58:14 -0700685int BandwidthController::removeInterfaceQuota(const char *iface) {
686
687 char ifn[MAX_IFACENAME_LEN];
688 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700689 std::string ifaceName;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700690 std::list<QuotaInfo>::iterator it;
JP Abgrall26e0d492011-06-24 19:21:51 -0700691
JP Abgrall69261cb2014-06-19 18:35:24 -0700692 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700693 return -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700694 if (StrncpyAndCheck(ifn, iface, sizeof(ifn))) {
Steve Block5ea0c052012-01-06 19:18:11 +0000695 ALOGE("Interface name longer than %d", MAX_IFACENAME_LEN);
JP Abgrall26e0d492011-06-24 19:21:51 -0700696 return -1;
697 }
698 ifaceName = ifn;
JP Abgrall26e0d492011-06-24 19:21:51 -0700699
JP Abgrall0dad7c22011-06-24 11:58:14 -0700700 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
JP Abgrall8a932722011-07-13 19:17:35 -0700701 if (it->ifaceName == ifaceName)
JP Abgrall0dad7c22011-06-24 11:58:14 -0700702 break;
703 }
704
705 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000706 ALOGE("No such iface %s to delete", ifn);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700707 return -1;
708 }
709
710 /* This also removes the quota command of CostlyIface chain. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700711 res |= cleanupCostlyIface(ifn, QuotaUnique);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700712
713 quotaIfaces.erase(it);
714
715 return res;
716}
JP Abgrall8a932722011-07-13 19:17:35 -0700717
718int BandwidthController::updateQuota(const char *quotaName, int64_t bytes) {
719 FILE *fp;
720 char *fname;
721
JP Abgrall69261cb2014-06-19 18:35:24 -0700722 if (!isIfaceName(quotaName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700723 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName);
724 return -1;
725 }
726
JP Abgrall8a932722011-07-13 19:17:35 -0700727 asprintf(&fname, "/proc/net/xt_quota/%s", quotaName);
Nick Kralevich53ea9ca2015-01-31 13:54:00 -0800728 fp = fopen(fname, "we");
JP Abgrall8a932722011-07-13 19:17:35 -0700729 free(fname);
730 if (!fp) {
Steve Block5ea0c052012-01-06 19:18:11 +0000731 ALOGE("Updating quota %s failed (%s)", quotaName, strerror(errno));
JP Abgrall8a932722011-07-13 19:17:35 -0700732 return -1;
733 }
SynergyDev7776cea2014-03-16 15:48:51 -0700734 fprintf(fp, "%" PRId64"\n", bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700735 fclose(fp);
736 return 0;
737}
738
739int BandwidthController::runIptablesAlertCmd(IptOp op, const char *alertName, int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900740 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900741 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700742
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900743 // TODO: consider using an alternate template for the delete that does not include the --quota
744 // value. This code works because the --quota value is ignored by deletes
745 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT", bytes, alertName);
746 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT", bytes, alertName);
747 StringAppendF(&alertQuotaCmd, "COMMIT\n");
748
Lorenzo Colitti4773cb42017-04-27 14:03:25 +0900749 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrall8a932722011-07-13 19:17:35 -0700750}
751
JP Abgrallc6c67342011-10-07 16:28:54 -0700752int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const char *alertName, int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900753 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900754 std::string alertQuotaCmd = "*filter\n";
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900755 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD", bytes, alertName);
756 StringAppendF(&alertQuotaCmd, "COMMIT\n");
757
758 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700759}
760
761int BandwidthController::setGlobalAlert(int64_t bytes) {
762 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700763 int res = 0;
764
765 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000766 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700767 return -1;
768 }
769 if (globalAlertBytes) {
770 res = updateQuota(alertName, bytes);
771 } else {
772 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700773 if (globalAlertTetherCount) {
Steve Block3fb42e02011-10-20 11:55:56 +0100774 ALOGV("setGlobalAlert for %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700775 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
776 }
JP Abgrall8a932722011-07-13 19:17:35 -0700777 }
778 globalAlertBytes = bytes;
779 return res;
780}
781
JP Abgrallc6c67342011-10-07 16:28:54 -0700782int BandwidthController::setGlobalAlertInForwardChain(void) {
783 const char *alertName = ALERT_GLOBAL_NAME;
784 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700785
JP Abgrallc6c67342011-10-07 16:28:54 -0700786 globalAlertTetherCount++;
Steve Block3fb42e02011-10-20 11:55:56 +0100787 ALOGV("setGlobalAlertInForwardChain(): %d tether", globalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700788
789 /*
790 * If there is no globalAlert active we are done.
791 * If there is an active globalAlert but this is not the 1st
792 * tether, we are also done.
793 */
794 if (!globalAlertBytes || globalAlertTetherCount != 1) {
795 return 0;
796 }
797
798 /* We only add the rule if this was the 1st tether added. */
799 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, globalAlertBytes);
800 return res;
801}
802
803int BandwidthController::removeGlobalAlert(void) {
804
805 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700806 int res = 0;
807
808 if (!globalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000809 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700810 return -1;
811 }
812 res = runIptablesAlertCmd(IptOpDelete, alertName, globalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700813 if (globalAlertTetherCount) {
814 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
815 }
JP Abgrall8a932722011-07-13 19:17:35 -0700816 globalAlertBytes = 0;
817 return res;
818}
819
JP Abgrallc6c67342011-10-07 16:28:54 -0700820int BandwidthController::removeGlobalAlertInForwardChain(void) {
821 int res = 0;
822 const char *alertName = ALERT_GLOBAL_NAME;
823
824 if (!globalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000825 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700826 return -1;
827 }
828
829 globalAlertTetherCount--;
830 /*
831 * If there is no globalAlert active we are done.
832 * If there is an active globalAlert but there are more
833 * tethers, we are also done.
834 */
835 if (!globalAlertBytes || globalAlertTetherCount >= 1) {
836 return 0;
837 }
838
839 /* We only detete the rule if this was the last tether removed. */
840 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, globalAlertBytes);
841 return res;
842}
843
JP Abgrall8a932722011-07-13 19:17:35 -0700844int BandwidthController::setSharedAlert(int64_t bytes) {
845 if (!sharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000846 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700847 return -1;
848 }
849 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000850 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700851 return -1;
852 }
853 return setCostlyAlert("shared", bytes, &sharedAlertBytes);
854}
855
856int BandwidthController::removeSharedAlert(void) {
857 return removeCostlyAlert("shared", &sharedAlertBytes);
858}
859
860int BandwidthController::setInterfaceAlert(const char *iface, int64_t bytes) {
861 std::list<QuotaInfo>::iterator it;
862
JP Abgrall69261cb2014-06-19 18:35:24 -0700863 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700864 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface);
865 return -1;
866 }
867
JP Abgrall8a932722011-07-13 19:17:35 -0700868 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000869 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700870 return -1;
871 }
872 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
873 if (it->ifaceName == iface)
874 break;
875 }
876
877 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000878 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700879 return -1;
880 }
881
882 return setCostlyAlert(iface, bytes, &it->alert);
883}
884
885int BandwidthController::removeInterfaceAlert(const char *iface) {
886 std::list<QuotaInfo>::iterator it;
887
JP Abgrall69261cb2014-06-19 18:35:24 -0700888 if (!isIfaceName(iface)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700889 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface);
890 return -1;
891 }
892
JP Abgrall8a932722011-07-13 19:17:35 -0700893 for (it = quotaIfaces.begin(); it != quotaIfaces.end(); it++) {
894 if (it->ifaceName == iface)
895 break;
896 }
897
898 if (it == quotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000899 ALOGE("No prior alert set for interface %s", iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700900 return -1;
901 }
902
903 return removeCostlyAlert(iface, &it->alert);
904}
905
906int BandwidthController::setCostlyAlert(const char *costName, int64_t bytes, int64_t *alertBytes) {
907 char *alertQuotaCmd;
JP Abgrall109899b2013-02-12 19:20:13 -0800908 char *chainName;
JP Abgrall8a932722011-07-13 19:17:35 -0700909 int res = 0;
910 char *alertName;
911
JP Abgrall69261cb2014-06-19 18:35:24 -0700912 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700913 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName);
914 return -1;
915 }
916
JP Abgrall8a932722011-07-13 19:17:35 -0700917 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000918 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700919 return -1;
920 }
921 asprintf(&alertName, "%sAlert", costName);
922 if (*alertBytes) {
923 res = updateQuota(alertName, *alertBytes);
924 } else {
JP Abgrall7e51cde2013-07-03 13:33:05 -0700925 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall109899b2013-02-12 19:20:13 -0800926 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-A", chainName, bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700927 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700928 free(alertQuotaCmd);
JP Abgrall109899b2013-02-12 19:20:13 -0800929 free(chainName);
JP Abgrall8a932722011-07-13 19:17:35 -0700930 }
931 *alertBytes = bytes;
932 free(alertName);
933 return res;
934}
935
936int BandwidthController::removeCostlyAlert(const char *costName, int64_t *alertBytes) {
937 char *alertQuotaCmd;
938 char *chainName;
939 char *alertName;
940 int res = 0;
941
JP Abgrall69261cb2014-06-19 18:35:24 -0700942 if (!isIfaceName(costName)) {
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700943 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName);
944 return -1;
945 }
946
JP Abgrall8a932722011-07-13 19:17:35 -0700947 if (!*alertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000948 ALOGE("No prior alert set for %s alert", costName);
JP Abgrall8a932722011-07-13 19:17:35 -0700949 return -1;
950 }
951
Jesper Hanssona9d791f2012-04-27 13:54:27 +0200952 asprintf(&alertName, "%sAlert", costName);
JP Abgrall7e51cde2013-07-03 13:33:05 -0700953 asprintf(&chainName, "bw_costly_%s", costName);
JP Abgrall92009c82013-02-06 18:01:24 -0800954 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700955 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700956 free(alertQuotaCmd);
957 free(chainName);
958
959 *alertBytes = 0;
960 free(alertName);
961 return res;
962}
JP Abgralldb7da582011-09-18 12:57:32 -0700963
Lorenzo Colitti7364b752016-07-08 18:24:53 +0900964void BandwidthController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
965 for (TetherStats& existing : statsList) {
966 if (existing.addStatsIfMatch(stats)) {
967 return;
968 }
969 }
970 // No match. Insert a new interface pair.
971 statsList.push_back(stats);
972}
973
JP Abgralldb7da582011-09-18 12:57:32 -0700974/*
975 * Parse the ptks and bytes out of:
JP Abgrallbaeccc42013-06-25 09:44:10 -0700976 * Chain natctrl_tether_counters (4 references)
977 * pkts bytes target prot opt in out source destination
JP Abgrallf3cc83f2013-09-11 20:01:59 -0700978 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
979 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
980 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
981 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
Lorenzo Colitti26c91322016-07-11 11:36:25 +0900982 * or:
983 * Chain natctrl_tether_counters (0 references)
984 * pkts bytes target prot opt in out source destination
985 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
986 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
987 *
JP Abgrallf3cc83f2013-09-11 20:01:59 -0700988 * It results in an error if invoked and no tethering counter rules exist. The constraint
989 * helps detect complete parsing failure.
JP Abgralldb7da582011-09-18 12:57:32 -0700990 */
Lorenzo Colitti7364b752016-07-08 18:24:53 +0900991int BandwidthController::addForwardChainStats(const TetherStats& filter,
Lorenzo Colittice6748a2017-02-02 01:34:33 +0900992 TetherStatsList& statsList,
993 const std::string& statsOutput,
Lorenzo Colitti7364b752016-07-08 18:24:53 +0900994 std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -0700995 int res;
Lorenzo Colittice6748a2017-02-02 01:34:33 +0900996 std::string statsLine;
JP Abgralldb7da582011-09-18 12:57:32 -0700997 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
998 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
999 char rest[MAX_IPT_OUTPUT_LINE_LEN];
1000
JP Abgrallbaeccc42013-06-25 09:44:10 -07001001 TetherStats stats;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001002 const char *buffPtr;
JP Abgralldb7da582011-09-18 12:57:32 -07001003 int64_t packets, bytes;
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001004 int statsFound = 0;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001005
1006 bool filterPair = filter.intIface[0] && filter.extIface[0];
1007
1008 char *filterMsg = filter.getStatsLine();
1009 ALOGV("filter: %s", filterMsg);
1010 free(filterMsg);
1011
1012 stats = filter;
JP Abgralldb7da582011-09-18 12:57:32 -07001013
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001014 std::stringstream stream(statsOutput);
1015 while (std::getline(stream, statsLine, '\n')) {
1016 buffPtr = statsLine.c_str();
1017
JP Abgralldb7da582011-09-18 12:57:32 -07001018 /* Clean up, so a failed parse can still print info */
1019 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001020 if (strstr(buffPtr, "0.0.0.0")) {
1021 // IPv4 has -- indicating what to do with fragments...
1022 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
1023 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
1024 &packets, &bytes, iface0, iface1, rest);
1025 } else {
1026 // ... but IPv6 does not.
1027 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
1028 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all %s %s ::/%s",
1029 &packets, &bytes, iface0, iface1, rest);
1030 }
SynergyDev7776cea2014-03-16 15:48:51 -07001031 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 -07001032 iface0, iface1, packets, bytes, rest, buffPtr);
JP Abgralla2a64f02011-11-11 20:36:16 -08001033 extraProcessingInfo += buffPtr;
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001034 extraProcessingInfo += "\n";
JP Abgralla2a64f02011-11-11 20:36:16 -08001035
JP Abgralldb7da582011-09-18 12:57:32 -07001036 if (res != 5) {
1037 continue;
1038 }
JP Abgrallbaeccc42013-06-25 09:44:10 -07001039 /*
1040 * The following assumes that the 1st rule has in:extIface out:intIface,
1041 * which is what NatController sets up.
1042 * If not filtering, the 1st match rx, and sets up the pair for the tx side.
1043 */
1044 if (filter.intIface[0] && filter.extIface[0]) {
1045 if (filter.intIface == iface0 && filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001046 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 -07001047 stats.rxPackets = packets;
1048 stats.rxBytes = bytes;
1049 } else if (filter.intIface == iface1 && filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001050 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 -07001051 stats.txPackets = packets;
1052 stats.txBytes = bytes;
1053 }
1054 } else if (filter.intIface[0] || filter.extIface[0]) {
1055 if (filter.intIface == iface0 || filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001056 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 -07001057 stats.intIface = iface0;
1058 stats.extIface = iface1;
1059 stats.rxPackets = packets;
1060 stats.rxBytes = bytes;
1061 } else if (filter.intIface == iface1 || filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001062 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 -07001063 stats.intIface = iface1;
1064 stats.extIface = iface0;
1065 stats.txPackets = packets;
1066 stats.txBytes = bytes;
1067 }
1068 } else /* if (!filter.intFace[0] && !filter.extIface[0]) */ {
1069 if (!stats.intIface[0]) {
SynergyDev7776cea2014-03-16 15:48:51 -07001070 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 -07001071 stats.intIface = iface0;
1072 stats.extIface = iface1;
1073 stats.rxPackets = packets;
1074 stats.rxBytes = bytes;
1075 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001076 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 -07001077 stats.txPackets = packets;
1078 stats.txBytes = bytes;
1079 }
1080 }
1081 if (stats.rxBytes != -1 && stats.txBytes != -1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001082 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64" filterPair=%d", stats.rxBytes, stats.txBytes, filterPair);
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001083 addStats(statsList, stats);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001084 if (filterPair) {
JP Abgrallbaeccc42013-06-25 09:44:10 -07001085 return 0;
1086 } else {
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001087 statsFound++;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001088 stats = filter;
1089 }
JP Abgralldb7da582011-09-18 12:57:32 -07001090 }
1091 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001092
1093 /* It is always an error to find only one side of the stats. */
1094 /* It is an error to find nothing when not filtering. */
1095 if (((stats.rxBytes == -1) != (stats.txBytes == -1)) ||
1096 (!statsFound && !filterPair)) {
1097 return -1;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001098 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001099 return 0;
JP Abgralldb7da582011-09-18 12:57:32 -07001100}
1101
JP Abgrallbaeccc42013-06-25 09:44:10 -07001102char *BandwidthController::TetherStats::getStatsLine(void) const {
JP Abgralldb7da582011-09-18 12:57:32 -07001103 char *msg;
SynergyDev7776cea2014-03-16 15:48:51 -07001104 asprintf(&msg, "%s %s %" PRId64" %" PRId64" %" PRId64" %" PRId64, intIface.c_str(), extIface.c_str(),
JP Abgralldb7da582011-09-18 12:57:32 -07001105 rxBytes, rxPackets, txBytes, txPackets);
1106 return msg;
1107}
1108
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001109int BandwidthController::getTetherStats(SocketClient *cli, TetherStats& filter,
1110 std::string &extraProcessingInfo) {
1111 int res = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001112
1113 TetherStatsList statsList;
1114
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001115 for (const IptablesTarget target : {V4, V6}) {
1116 std::string statsString;
1117 res = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString);
1118 if (res != 0) {
1119 ALOGE("Failed to run %s err=%d", GET_TETHER_STATS_COMMAND.c_str(), res);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001120 return -1;
1121 }
1122
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001123 res = addForwardChainStats(filter, statsList, statsString, extraProcessingInfo);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001124 if (res != 0) {
1125 return res;
1126 }
1127 }
JP Abgralldb7da582011-09-18 12:57:32 -07001128
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001129 if (filter.intIface[0] && filter.extIface[0] && statsList.size() == 1) {
1130 cli->sendMsg(ResponseCode::TetheringStatsResult, statsList[0].getStatsLine(), false);
1131 } else {
1132 for (const auto& stats: statsList) {
1133 cli->sendMsg(ResponseCode::TetheringStatsListResult, stats.getStatsLine(), false);
1134 }
1135 if (res == 0) {
1136 cli->sendMsg(ResponseCode::CommandOkay, "Tethering stats list completed", false);
1137 }
1138 }
1139
JP Abgralldb7da582011-09-18 12:57:32 -07001140 return res;
1141}
JP Abgrall0e540ec2013-08-26 15:13:10 -07001142
1143void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001144 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
1145 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001146
1147 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001148 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
1149 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001150 return;
1151 }
1152 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001153 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001154}
1155
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001156void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
1157 std::stringstream stream(ruleList);
1158 std::string rule;
1159 std::vector<std::string> clearCommands = { "*filter" };
1160 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001161
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001162 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
1163 while (std::getline(stream, rule, '\n')) {
1164 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
1165 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
1166 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
1167
1168 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -07001169 continue;
1170 }
1171
Lorenzo Colitti3c272702017-04-26 15:48:13 +09001172 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001173 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +09001174 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001175 }
1176 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001177
1178 if (clearCommands.size() == 1) {
1179 // No rules found.
1180 return;
1181 }
1182
1183 clearCommands.push_back("COMMIT\n");
1184 iptablesRestoreFunction(V4V6, android::base::Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001185}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +09001186
1187inline const char *BandwidthController::opToString(IptOp op) {
1188 switch (op) {
1189 case IptOpInsert:
1190 return "-I";
1191 case IptOpDelete:
1192 return "-D";
1193 }
1194}
1195
1196inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
1197 /*
1198 * Must be careful what one rejects with, as upper layer protocols will just
1199 * keep on hammering the device until the number of retries are done.
1200 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
1201 */
1202 switch (jumpHandling) {
1203 case IptJumpNoAdd:
1204 return "";
1205 case IptJumpReject:
1206 return " --jump REJECT";
1207 case IptJumpReturn:
1208 return " --jump RETURN";
1209 }
1210}