blob: 2a83d91ae459b7a675e22aaf5d120ed789d17c4d [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
Joel Scherpelz01cc5492017-06-16 10:45:14 +090025#include <ctype.h>
JP Abgrall8a932722011-07-13 19:17:35 -070026#include <errno.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070027#include <fcntl.h>
JP Abgralldb7da582011-09-18 12:57:32 -070028#include <stdio.h>
JP Abgrall8a932722011-07-13 19:17:35 -070029#include <stdlib.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070030#include <string.h>
Joel Scherpelz01cc5492017-06-16 10:45:14 +090031#include <string>
32#include <vector>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070033
Matthew Leach2a54d962013-01-14 15:07:12 +000034#define __STDC_FORMAT_MACROS 1
35#include <inttypes.h>
36
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070037#include <sys/socket.h>
38#include <sys/stat.h>
39#include <sys/types.h>
40#include <sys/wait.h>
41
42#include <linux/netlink.h>
43#include <linux/rtnetlink.h>
44#include <linux/pkt_sched.h>
45
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090046#include "android-base/stringprintf.h"
Lorenzo Colitti13debb82016-03-27 17:46:30 +090047#include "android-base/strings.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070048#define LOG_TAG "BandwidthController"
49#include <cutils/log.h>
50#include <cutils/properties.h>
Rom Lemarchand14150212013-01-24 10:01:04 -080051#include <logwrap/logwrap.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070052
Joel Scherpelz01cc5492017-06-16 10:45:14 +090053#include <netdutils/Syscalls.h>
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070054#include "BandwidthController.h"
Joel Scherpelz01cc5492017-06-16 10:45:14 +090055#include "NatController.h" /* For LOCAL_TETHER_COUNTERS_CHAIN */
56#include "NetdConstants.h"
JP Abgrallbaeccc42013-06-25 09:44:10 -070057#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"
Joel Scherpelzbcad6612017-05-30 10:55:11 +090061const 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;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090073using android::netdutils::StatusOr;
74using android::netdutils::UniqueFile;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090075
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090076namespace {
77
78const char ALERT_GLOBAL_NAME[] = "globalAlert";
79const int MAX_CMD_ARGS = 32;
80const int MAX_CMD_LEN = 1024;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090081const int MAX_IPT_OUTPUT_LINE_LEN = 256;
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090082const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colitti3c272702017-04-26 15:48:13 +090083const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
Lorenzo Colittice6748a2017-02-02 01:34:33 +090084 "*filter\n"
85 "-nvx -L %s\n"
86 "COMMIT\n", NatController::LOCAL_TETHER_COUNTERS_CHAIN);
87
Joel Scherpelzbcad6612017-05-30 10:55:11 +090088const char NAUGHTY_CHAIN[] = "bw_penalty_box";
89const char NICE_CHAIN[] = "bw_happy_box";
JP Abgralldb7da582011-09-18 12:57:32 -070090
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070091/**
92 * Some comments about the rules:
93 * * Ordering
94 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070095 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070096 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070097 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070098 *
99 * * global quota vs per interface quota
100 * - global quota for all costly interfaces uses a single costly chain:
101 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -0700102 * iptables -N bw_costly_shared
103 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
104 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
105 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -0700106 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -0700107 * iptables -A bw_costly_shared --jump bw_penalty_box
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900108 * iptables -A bw_penalty_box --jump bw_happy_box
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900109 * iptables -A bw_happy_box --jump bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700110 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700111 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700112 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
113 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700114 *
115 * - quota per interface. This is achieve by having "costly" chains per quota.
116 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700117 * iptables -N bw_costly_iface0
118 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
119 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
120 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -0700121 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -0700122 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700123 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900124 * * Penalty box, happy box and data saver.
125 * - bw_penalty box is a blacklist of apps that are rejected.
126 * - bw_happy_box is a whitelist of apps. It always includes all system apps
127 * - bw_data_saver implements data usage restrictions.
128 * - Via the UI the user can add and remove apps from the whitelist and
129 * blacklist, and turn on/off data saver.
130 * - The blacklist takes precedence over the whitelist and the whitelist
131 * takes precedence over data saver.
132 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700133 * * bw_penalty_box handling:
134 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900135 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700136 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700137 * --jump REJECT --reject-with icmp-port-unreachable
138 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700139 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900140 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700141 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700142 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700143 * --jump RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900144 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900145 * * bw_data_saver handling:
146 * - The bw_data_saver comes after the happy box.
147 * Enable data saver:
148 * iptables -R 1 bw_data_saver --jump REJECT --reject-with icmp-port-unreachable
149 * Disable data saver:
150 * iptables -R 1 bw_data_saver --jump RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700151 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900152
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900153const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900154const std::string HAPPY_BOX_WHITELIST_COMMAND = StringPrintf(
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900155 "-I bw_happy_box -m owner --uid-owner %d-%d --jump RETURN", 0, MAX_SYSTEM_UID);
156
157static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700158 /*
159 * Cleanup rules.
JP Abgrall7e51cde2013-07-03 13:33:05 -0700160 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
JP Abgrall0031cea2012-04-17 16:38:23 -0700161 * to allow coexistance.
JP Abgrall39f8f242011-06-29 19:21:58 -0700162 */
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900163 "*filter",
164 ":bw_INPUT -",
165 ":bw_OUTPUT -",
166 ":bw_FORWARD -",
167 ":bw_happy_box -",
168 ":bw_penalty_box -",
169 ":bw_data_saver -",
170 ":bw_costly_shared -",
171 "COMMIT",
172 "*raw",
173 ":bw_raw_PREROUTING -",
174 "COMMIT",
175 "*mangle",
176 ":bw_mangle_POSTROUTING -",
177 COMMIT_AND_CLOSE
JP Abgrall0031cea2012-04-17 16:38:23 -0700178};
179
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900180static const std::vector<std::string> IPT_BASIC_ACCOUNTING_COMMANDS = {
181 "*filter",
JP Abgrall0031cea2012-04-17 16:38:23 -0700182 "-A bw_INPUT -m owner --socket-exists", /* This is a tracking rule. */
JP Abgrall0031cea2012-04-17 16:38:23 -0700183 "-A bw_OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900184 "-A bw_costly_shared --jump bw_penalty_box",
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900185 "-A bw_penalty_box --jump bw_happy_box",
186 "-A bw_happy_box --jump bw_data_saver",
187 "-A bw_data_saver -j RETURN",
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900188 HAPPY_BOX_WHITELIST_COMMAND,
189 "COMMIT",
190
191 "*raw",
192 "-A bw_raw_PREROUTING -m owner --socket-exists", /* This is a tracking rule. */
193 "COMMIT",
194
195 "*mangle",
196 "-A bw_mangle_POSTROUTING -m owner --socket-exists", /* This is a tracking rule. */
197 COMMIT_AND_CLOSE
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900198};
199
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900200std::vector<std::string> toStrVec(int num, char* strs[]) {
201 std::vector<std::string> tmp;
202 for (int i = 0; i < num; ++i) {
203 tmp.emplace_back(strs[i]);
204 }
205 return tmp;
206}
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900207
208} // namespace
209
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900210BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700211}
212
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900213int BandwidthController::runIpxtablesCmd(const std::string& cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700214 IptFailureLog failureHandling) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700215 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700216
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900217 ALOGV("runIpxtablesCmd(cmd=%s)", cmd.c_str());
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700218 res |= runIptablesCmd(cmd, jumpHandling, IptIpV4, failureHandling);
219 res |= runIptablesCmd(cmd, jumpHandling, IptIpV6, failureHandling);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700220 return res;
221}
222
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900223int BandwidthController::StrncpyAndCheck(char* buffer, const std::string& src, size_t buffSize) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700224 memset(buffer, '\0', buffSize); // strncpy() is not filling leftover with '\0'
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900225 strncpy(buffer, src.c_str(), buffSize);
JP Abgrall26e0d492011-06-24 19:21:51 -0700226 return buffer[buffSize - 1];
227}
228
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900229int BandwidthController::runIptablesCmd(const std::string& cmd, IptJumpOp jumpHandling,
JP Abgrallad729ac2012-04-24 23:27:44 -0700230 IptIpVer iptVer, IptFailureLog failureHandling) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700231 char buffer[MAX_CMD_LEN];
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700232 const char *argv[MAX_CMD_ARGS];
JP Abgrall26e0d492011-06-24 19:21:51 -0700233 int argc = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700234 char *next = buffer;
235 char *tmp;
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700236 int res;
Rom Lemarchand14150212013-01-24 10:01:04 -0800237 int status = 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700238
JP Abgrall0dad7c22011-06-24 11:58:14 -0700239 std::string fullCmd = cmd;
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900240 fullCmd += jumpToString(jumpHandling);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700241
Paul Jensen94b2ab92015-08-04 10:35:05 -0400242 fullCmd.insert(0, " -w ");
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700243 fullCmd.insert(0, iptVer == IptIpV4 ? IPTABLES_PATH : IP6TABLES_PATH);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700244
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900245 if (StrncpyAndCheck(buffer, fullCmd, sizeof(buffer))) {
Rom Lemarchand14150212013-01-24 10:01:04 -0800246 ALOGE("iptables command too long");
247 return -1;
248 }
249
250 argc = 0;
251 while ((tmp = strsep(&next, " "))) {
252 argv[argc++] = tmp;
253 if (argc >= MAX_CMD_ARGS) {
254 ALOGE("iptables argument overflow");
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700255 return -1;
256 }
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700257 }
Rom Lemarchand14150212013-01-24 10:01:04 -0800258
259 argv[argc] = NULL;
Lorenzo Colitti86a47982016-03-18 17:52:25 +0900260 res = execFunction(argc, (char **)argv, &status, false,
Rom Lemarchand14150212013-01-24 10:01:04 -0800261 failureHandling == IptFailShow);
JP Abgrallc8dc63b2013-02-13 16:30:00 -0800262 res = res || !WIFEXITED(status) || WEXITSTATUS(status);
263 if (res && failureHandling == IptFailShow) {
264 ALOGE("runIptablesCmd(): res=%d status=%d failed %s", res, status,
265 fullCmd.c_str());
JP Abgrall11b4e9b2011-08-11 15:34:49 -0700266 }
267 return res;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700268}
269
JP Abgrall0e540ec2013-08-26 15:13:10 -0700270void BandwidthController::flushCleanTables(bool doClean) {
271 /* Flush and remove the bw_costly_<iface> tables */
272 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700273
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900274 std::string commands = android::base::Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900275 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700276}
JP Abgrall0031cea2012-04-17 16:38:23 -0700277
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900278int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700279 /* flush+clean is allowed to fail */
280 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700281 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700282}
283
284int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrall0031cea2012-04-17 16:38:23 -0700285 char value[PROPERTY_VALUE_MAX];
286
287 if (!force) {
288 property_get("persist.bandwidth.enable", value, "1");
289 if (!strcmp(value, "0"))
290 return 0;
291 }
JP Abgrall8a932722011-07-13 19:17:35 -0700292
JP Abgralldb7da582011-09-18 12:57:32 -0700293 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900294 mSharedQuotaIfaces.clear();
295 mQuotaIfaces.clear();
296 mGlobalAlertBytes = 0;
297 mGlobalAlertTetherCount = 0;
298 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700299
JP Abgrall0e540ec2013-08-26 15:13:10 -0700300 flushCleanTables(false);
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900301 std::string commands = android::base::Join(IPT_BASIC_ACCOUNTING_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900302 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700303}
304
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900305int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700306
307 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700308 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700309}
310
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900311int BandwidthController::enableDataSaver(bool enable) {
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900312 std::string cmd = StringPrintf(
313 "*filter\n"
314 "-R bw_data_saver 1%s\n"
315 "COMMIT\n", jumpToString(enable ? IptJumpReject : IptJumpReturn));
316 return iptablesRestoreFunction(V4V6, cmd, nullptr);
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900317}
318
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700319int BandwidthController::addNaughtyApps(int numUids, char *appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900320 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
321 IptJumpReject, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700322}
323
324int BandwidthController::removeNaughtyApps(int numUids, char *appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900325 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
326 IptJumpReject, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700327}
328
JP Abgralle4788732013-07-02 20:28:45 -0700329int BandwidthController::addNiceApps(int numUids, char *appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900330 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
331 IptJumpReturn, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700332}
333
334int BandwidthController::removeNiceApps(int numUids, char *appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900335 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
336 IptJumpReturn, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700337}
338
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900339int BandwidthController::manipulateSpecialApps(const std::vector<std::string>& appStrUids,
340 const std::string& chain, IptJumpOp jumpHandling,
341 IptOp op) {
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900342 std::string cmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900343 for (const auto& appStrUid : appStrUids) {
344 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain.c_str(),
345 appStrUid.c_str(), jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700346 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900347 StringAppendF(&cmd, "COMMIT\n");
348 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700349}
350
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900351std::string BandwidthController::makeIptablesQuotaCmd(IptFullOp op, const std::string& costName,
352 int64_t quota) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700353 std::string res;
JP Abgrall8a932722011-07-13 19:17:35 -0700354 const char *opFlag;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700355
SynergyDev7776cea2014-03-16 15:48:51 -0700356 ALOGV("makeIptablesQuotaCmd(%d, %" PRId64")", op, quota);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700357
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700358 switch (op) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900359 case IptFullOpInsert:
JP Abgrall8a932722011-07-13 19:17:35 -0700360 opFlag = "-I";
361 break;
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900362 case IptFullOpAppend:
JP Abgrall109899b2013-02-12 19:20:13 -0800363 opFlag = "-A";
364 break;
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900365 case IptFullOpDelete:
JP Abgrall8a932722011-07-13 19:17:35 -0700366 opFlag = "-D";
367 break;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700368 }
JP Abgrall8a932722011-07-13 19:17:35 -0700369
JP Abgrallbfa74662011-06-29 19:23:04 -0700370 // The requried IP version specific --jump REJECT ... will be added later.
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900371 StringAppendF(&res, "%s bw_costly_%s -m quota2 ! --quota %" PRId64 " --name %s", opFlag,
372 costName.c_str(), quota, costName.c_str());
JP Abgrall0dad7c22011-06-24 11:58:14 -0700373 return res;
374}
375
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900376int BandwidthController::prepCostlyIface(const std::string& ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700377 char cmd[MAX_CMD_LEN];
JP Abgrall0031cea2012-04-17 16:38:23 -0700378 int res = 0, res1, res2;
JP Abgrall8a932722011-07-13 19:17:35 -0700379 int ruleInsertPos = 1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700380 std::string costString;
381 const char *costCString;
382
JP Abgrall0dad7c22011-06-24 11:58:14 -0700383 /* The "-N costly" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700384 switch (quotaType) {
385 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700386 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700387 costString += ifn;
388 costCString = costString.c_str();
JP Abgrall0031cea2012-04-17 16:38:23 -0700389 /*
JP Abgrall7e51cde2013-07-03 13:33:05 -0700390 * Flush the bw_costly_<iface> is allowed to fail in case it didn't exist.
JP Abgrall0031cea2012-04-17 16:38:23 -0700391 * Creating a new one is allowed to fail in case it existed.
392 * This helps with netd restarts.
393 */
394 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700395 res1 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700396 snprintf(cmd, sizeof(cmd), "-N %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700397 res2 = runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700398 res = (res1 && res2) || (!res1 && !res2);
399
JP Abgrall7e51cde2013-07-03 13:33:05 -0700400 snprintf(cmd, sizeof(cmd), "-A %s -j bw_penalty_box", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700401 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall26e0d492011-06-24 19:21:51 -0700402 break;
403 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700404 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700405 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700406 }
407
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900408 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700409 /* The alert rule comes 1st */
410 ruleInsertPos = 2;
411 }
JP Abgrall0031cea2012-04-17 16:38:23 -0700412
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900413 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn.c_str(), costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700414 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700415
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900416 snprintf(cmd, sizeof(cmd), "-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, ifn.c_str(),
417 costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700418 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrall0031cea2012-04-17 16:38:23 -0700419
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900420 snprintf(cmd, sizeof(cmd), "-D bw_OUTPUT -o %s --jump %s", ifn.c_str(), costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700421 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
JP Abgrall0031cea2012-04-17 16:38:23 -0700422
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900423 snprintf(cmd, sizeof(cmd), "-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, ifn.c_str(),
424 costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700425 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900426
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900427 snprintf(cmd, sizeof(cmd), "-D bw_FORWARD -o %s --jump %s", ifn.c_str(), costCString);
Erik Kline58a94482015-10-02 17:52:37 +0900428 runIpxtablesCmd(cmd, IptJumpNoAdd, IptFailHide);
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900429 snprintf(cmd, sizeof(cmd), "-A bw_FORWARD -o %s --jump %s", ifn.c_str(), costCString);
Erik Kline58a94482015-10-02 17:52:37 +0900430 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
431
JP Abgrall0dad7c22011-06-24 11:58:14 -0700432 return res;
433}
434
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900435int BandwidthController::cleanupCostlyIface(const std::string& ifn, QuotaType quotaType) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700436 char cmd[MAX_CMD_LEN];
437 int res = 0;
438 std::string costString;
439 const char *costCString;
440
JP Abgrall26e0d492011-06-24 19:21:51 -0700441 switch (quotaType) {
442 case QuotaUnique:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700443 costString = "bw_costly_";
JP Abgrall0dad7c22011-06-24 11:58:14 -0700444 costString += ifn;
445 costCString = costString.c_str();
JP Abgrall26e0d492011-06-24 19:21:51 -0700446 break;
447 case QuotaShared:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700448 costCString = "bw_costly_shared";
JP Abgrall26e0d492011-06-24 19:21:51 -0700449 break;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700450 }
451
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900452 snprintf(cmd, sizeof(cmd), "-D bw_INPUT -i %s --jump %s", ifn.c_str(), costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700453 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
Erik Kline58a94482015-10-02 17:52:37 +0900454 for (const auto tableName : {LOCAL_OUTPUT, LOCAL_FORWARD}) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900455 snprintf(cmd, sizeof(cmd), "-D %s -o %s --jump %s", tableName, ifn.c_str(), costCString);
Erik Kline58a94482015-10-02 17:52:37 +0900456 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
457 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700458
JP Abgrall7e51cde2013-07-03 13:33:05 -0700459 /* The "-N bw_costly_shared" is created upfront, no need to handle it here. */
JP Abgrall26e0d492011-06-24 19:21:51 -0700460 if (quotaType == QuotaUnique) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700461 snprintf(cmd, sizeof(cmd), "-F %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700462 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgralla9f802c2011-06-29 15:46:45 -0700463 snprintf(cmd, sizeof(cmd), "-X %s", costCString);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700464 res |= runIpxtablesCmd(cmd, IptJumpNoAdd);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700465 }
466 return res;
467}
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700468
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900469int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700470 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700471 std::string quotaCmd;
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900472 const char costName[] = "shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700473
JP Abgrall8a932722011-07-13 19:17:35 -0700474 if (!maxBytes) {
475 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000476 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700477 return -1;
478 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700479 if (!isIfaceName(iface))
480 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700481
482 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900483 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700484 }
485
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900486 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700487
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900488 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900489 res |= prepCostlyIface(iface, QuotaShared);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900490 if (mSharedQuotaIfaces.empty()) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900491 quotaCmd = makeIptablesQuotaCmd(IptFullOpInsert, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700492 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700493 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000494 ALOGE("Failed set quota rule");
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700495 goto fail;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700496 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900497 mSharedQuotaBytes = maxBytes;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700498 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900499 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700500
501 }
502
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900503 if (maxBytes != mSharedQuotaBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700504 res |= updateQuota(costName, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700505 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000506 ALOGE("Failed update quota for %s", costName);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700507 goto fail;
508 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900509 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700510 }
511 return 0;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700512
513 fail:
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700514 /*
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700515 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
516 * rules in the kernel to see which ones need cleaning up.
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700517 * For now callers needs to choose if they want to "ndc bandwidth enable"
518 * which resets everything.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700519 */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900520 removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700521 return -1;
522}
523
JP Abgrall8a932722011-07-13 19:17:35 -0700524/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900525int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700526 int res = 0;
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900527 const char costName[] = "shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700528
JP Abgrall69261cb2014-06-19 18:35:24 -0700529 if (!isIfaceName(iface))
530 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700531
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900532 auto it = mSharedQuotaIfaces.find(iface);
533
534 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900535 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700536 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700537 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700538
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900539 res |= cleanupCostlyIface(iface, QuotaShared);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900540 mSharedQuotaIfaces.erase(it);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700541
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900542 if (mSharedQuotaIfaces.empty()) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700543 std::string quotaCmd;
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900544 quotaCmd = makeIptablesQuotaCmd(IptFullOpDelete, costName, mSharedQuotaBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700545 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900546 mSharedQuotaBytes = 0;
547 if (mSharedAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700548 removeSharedAlert();
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900549 mSharedAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700550 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700551 }
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700552 return res;
553}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700554
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900555int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700556 int res = 0;
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900557 const auto& costName = iface;
JP Abgrall26e0d492011-06-24 19:21:51 -0700558 std::string quotaCmd;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700559
JP Abgrall69261cb2014-06-19 18:35:24 -0700560 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700561 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700562
JP Abgrall8a932722011-07-13 19:17:35 -0700563 if (!maxBytes) {
564 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000565 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700566 return -1;
567 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700568 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700569 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700570 }
571
JP Abgrall0dad7c22011-06-24 11:58:14 -0700572 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900573 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700574
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900575 if (it == mQuotaIfaces.end()) {
JP Abgralle4788732013-07-02 20:28:45 -0700576 /* Preparing the iface adds a penalty/happy box check */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900577 res |= prepCostlyIface(iface, QuotaUnique);
JP Abgrallbaeccc42013-06-25 09:44:10 -0700578 /*
JP Abgralle4788732013-07-02 20:28:45 -0700579 * The rejecting quota limit should go after the penalty/happy box checks
JP Abgrallbaeccc42013-06-25 09:44:10 -0700580 * or else a naughty app could just eat up the quota.
581 * So we append here.
582 */
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900583 quotaCmd = makeIptablesQuotaCmd(IptFullOpAppend, costName, maxBytes);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700584 res |= runIpxtablesCmd(quotaCmd.c_str(), IptJumpReject);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700585 if (res) {
Steve Block5ea0c052012-01-06 19:18:11 +0000586 ALOGE("Failed set quota rule");
JP Abgrall0dad7c22011-06-24 11:58:14 -0700587 goto fail;
588 }
589
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900590 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
JP Abgrall0dad7c22011-06-24 11:58:14 -0700591
592 } else {
JP Abgrall8a932722011-07-13 19:17:35 -0700593 res |= updateQuota(costName, maxBytes);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700594 if (res) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900595 ALOGE("Failed update quota for %s", iface.c_str());
JP Abgrall0dad7c22011-06-24 11:58:14 -0700596 goto fail;
597 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900598 it->second.quota = maxBytes;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700599 }
600 return 0;
601
602 fail:
603 /*
604 * TODO(jpa): once we get rid of iptables in favor of rtnetlink, reparse
605 * rules in the kernel to see which ones need cleaning up.
606 * For now callers needs to choose if they want to "ndc bandwidth enable"
607 * which resets everything.
608 */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900609 removeInterfaceSharedQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700610 return -1;
611}
612
JP Abgrall8a932722011-07-13 19:17:35 -0700613int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
614 return getInterfaceQuota("shared", bytes);
615}
616
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900617int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900618 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900619 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700620
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900621 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700622
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900623 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
624 if (!isOk(file)) {
625 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700626 return -1;
627 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900628 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
629 if (!isOk(rv)) {
630 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
631 return -1;
632 }
633 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
634 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700635}
636
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900637int BandwidthController::removeInterfaceQuota(const std::string& iface) {
JP Abgrall0dad7c22011-06-24 11:58:14 -0700638 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700639
JP Abgrall69261cb2014-06-19 18:35:24 -0700640 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700641 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700642
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900643 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700644
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900645 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900646 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrall0dad7c22011-06-24 11:58:14 -0700647 return -1;
648 }
649
650 /* This also removes the quota command of CostlyIface chain. */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900651 res |= cleanupCostlyIface(iface, QuotaUnique);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700652
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900653 mQuotaIfaces.erase(it);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700654
655 return res;
656}
JP Abgrall8a932722011-07-13 19:17:35 -0700657
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900658int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900659 const auto& sys = android::netdutils::sSyscalls.get();
660 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700661
JP Abgrall69261cb2014-06-19 18:35:24 -0700662 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900663 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700664 return -1;
665 }
666
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900667 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
668 if (!isOk(file)) {
669 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700670 return -1;
671 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900672 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700673 return 0;
674}
675
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900676int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
677 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900678 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900679 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700680
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900681 // TODO: consider using an alternate template for the delete that does not include the --quota
682 // value. This code works because the --quota value is ignored by deletes
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900683 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT", bytes,
684 alertName.c_str());
685 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT", bytes,
686 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900687 StringAppendF(&alertQuotaCmd, "COMMIT\n");
688
Lorenzo Colitti4773cb42017-04-27 14:03:25 +0900689 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrall8a932722011-07-13 19:17:35 -0700690}
691
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900692int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const std::string& alertName,
693 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900694 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900695 std::string alertQuotaCmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900696 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD", bytes,
697 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900698 StringAppendF(&alertQuotaCmd, "COMMIT\n");
699
700 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700701}
702
703int BandwidthController::setGlobalAlert(int64_t bytes) {
704 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700705 int res = 0;
706
707 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000708 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700709 return -1;
710 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900711 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700712 res = updateQuota(alertName, bytes);
713 } else {
714 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900715 if (mGlobalAlertTetherCount) {
716 ALOGV("setGlobalAlert for %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700717 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
718 }
JP Abgrall8a932722011-07-13 19:17:35 -0700719 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900720 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700721 return res;
722}
723
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900724int BandwidthController::setGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700725 const char *alertName = ALERT_GLOBAL_NAME;
726 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700727
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900728 mGlobalAlertTetherCount++;
729 ALOGV("setGlobalAlertInForwardChain(): %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700730
731 /*
732 * If there is no globalAlert active we are done.
733 * If there is an active globalAlert but this is not the 1st
734 * tether, we are also done.
735 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900736 if (!mGlobalAlertBytes || mGlobalAlertTetherCount != 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700737 return 0;
738 }
739
740 /* We only add the rule if this was the 1st tether added. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900741 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700742 return res;
743}
744
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900745int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700746
747 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700748 int res = 0;
749
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900750 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000751 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700752 return -1;
753 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900754 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
755 if (mGlobalAlertTetherCount) {
756 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700757 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900758 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700759 return res;
760}
761
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900762int BandwidthController::removeGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700763 int res = 0;
764 const char *alertName = ALERT_GLOBAL_NAME;
765
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900766 if (!mGlobalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000767 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700768 return -1;
769 }
770
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900771 mGlobalAlertTetherCount--;
JP Abgrallc6c67342011-10-07 16:28:54 -0700772 /*
773 * If there is no globalAlert active we are done.
774 * If there is an active globalAlert but there are more
775 * tethers, we are also done.
776 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900777 if (!mGlobalAlertBytes || mGlobalAlertTetherCount >= 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700778 return 0;
779 }
780
781 /* We only detete the rule if this was the last tether removed. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900782 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700783 return res;
784}
785
JP Abgrall8a932722011-07-13 19:17:35 -0700786int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900787 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000788 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700789 return -1;
790 }
791 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000792 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700793 return -1;
794 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900795 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700796}
797
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900798int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900799 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700800}
801
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900802int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700803 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900804 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700805 return -1;
806 }
807
JP Abgrall8a932722011-07-13 19:17:35 -0700808 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000809 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700810 return -1;
811 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900812 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700813
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900814 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000815 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700816 return -1;
817 }
818
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900819 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700820}
821
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900822int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700823 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900824 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700825 return -1;
826 }
827
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900828 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700829
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900830 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900831 ALOGE("No prior alert set for interface %s", iface.c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700832 return -1;
833 }
834
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900835 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700836}
837
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900838int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
839 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700840 char *alertQuotaCmd;
JP Abgrall109899b2013-02-12 19:20:13 -0800841 char *chainName;
JP Abgrall8a932722011-07-13 19:17:35 -0700842 int res = 0;
843 char *alertName;
844
JP Abgrall69261cb2014-06-19 18:35:24 -0700845 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900846 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700847 return -1;
848 }
849
JP Abgrall8a932722011-07-13 19:17:35 -0700850 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000851 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700852 return -1;
853 }
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900854 asprintf(&alertName, "%sAlert", costName.c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700855 if (*alertBytes) {
856 res = updateQuota(alertName, *alertBytes);
857 } else {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900858 asprintf(&chainName, "bw_costly_%s", costName.c_str());
JP Abgrall109899b2013-02-12 19:20:13 -0800859 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-A", chainName, bytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700860 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700861 free(alertQuotaCmd);
JP Abgrall109899b2013-02-12 19:20:13 -0800862 free(chainName);
JP Abgrall8a932722011-07-13 19:17:35 -0700863 }
864 *alertBytes = bytes;
865 free(alertName);
866 return res;
867}
868
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900869int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700870 char *alertQuotaCmd;
871 char *chainName;
872 char *alertName;
873 int res = 0;
874
JP Abgrall69261cb2014-06-19 18:35:24 -0700875 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900876 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700877 return -1;
878 }
879
JP Abgrall8a932722011-07-13 19:17:35 -0700880 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900881 ALOGE("No prior alert set for %s alert", costName.c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700882 return -1;
883 }
884
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900885 asprintf(&alertName, "%sAlert", costName.c_str());
886 asprintf(&chainName, "bw_costly_%s", costName.c_str());
JP Abgrall92009c82013-02-06 18:01:24 -0800887 asprintf(&alertQuotaCmd, ALERT_IPT_TEMPLATE, "-D", chainName, *alertBytes, alertName);
JP Abgralla9ba4cb2013-07-02 19:08:48 -0700888 res |= runIpxtablesCmd(alertQuotaCmd, IptJumpNoAdd);
JP Abgrall8a932722011-07-13 19:17:35 -0700889 free(alertQuotaCmd);
890 free(chainName);
891
892 *alertBytes = 0;
893 free(alertName);
894 return res;
895}
JP Abgralldb7da582011-09-18 12:57:32 -0700896
Lorenzo Colitti7364b752016-07-08 18:24:53 +0900897void BandwidthController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
898 for (TetherStats& existing : statsList) {
899 if (existing.addStatsIfMatch(stats)) {
900 return;
901 }
902 }
903 // No match. Insert a new interface pair.
904 statsList.push_back(stats);
905}
906
JP Abgralldb7da582011-09-18 12:57:32 -0700907/*
908 * Parse the ptks and bytes out of:
JP Abgrallbaeccc42013-06-25 09:44:10 -0700909 * Chain natctrl_tether_counters (4 references)
910 * pkts bytes target prot opt in out source destination
JP Abgrallf3cc83f2013-09-11 20:01:59 -0700911 * 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
912 * 27 2002 RETURN all -- rmnet0 wlan0 0.0.0.0/0 0.0.0.0/0
913 * 1040 107471 RETURN all -- bt-pan rmnet0 0.0.0.0/0 0.0.0.0/0
914 * 1450 1708806 RETURN all -- rmnet0 bt-pan 0.0.0.0/0 0.0.0.0/0
Lorenzo Colitti26c91322016-07-11 11:36:25 +0900915 * or:
916 * Chain natctrl_tether_counters (0 references)
917 * pkts bytes target prot opt in out source destination
918 * 0 0 RETURN all wlan0 rmnet_data0 ::/0 ::/0
919 * 0 0 RETURN all rmnet_data0 wlan0 ::/0 ::/0
920 *
JP Abgrallf3cc83f2013-09-11 20:01:59 -0700921 * It results in an error if invoked and no tethering counter rules exist. The constraint
922 * helps detect complete parsing failure.
JP Abgralldb7da582011-09-18 12:57:32 -0700923 */
Lorenzo Colitti7364b752016-07-08 18:24:53 +0900924int BandwidthController::addForwardChainStats(const TetherStats& filter,
Lorenzo Colittice6748a2017-02-02 01:34:33 +0900925 TetherStatsList& statsList,
926 const std::string& statsOutput,
Lorenzo Colitti7364b752016-07-08 18:24:53 +0900927 std::string &extraProcessingInfo) {
JP Abgralldb7da582011-09-18 12:57:32 -0700928 int res;
Lorenzo Colittice6748a2017-02-02 01:34:33 +0900929 std::string statsLine;
JP Abgralldb7da582011-09-18 12:57:32 -0700930 char iface0[MAX_IPT_OUTPUT_LINE_LEN];
931 char iface1[MAX_IPT_OUTPUT_LINE_LEN];
932 char rest[MAX_IPT_OUTPUT_LINE_LEN];
933
JP Abgrallbaeccc42013-06-25 09:44:10 -0700934 TetherStats stats;
Lorenzo Colittice6748a2017-02-02 01:34:33 +0900935 const char *buffPtr;
JP Abgralldb7da582011-09-18 12:57:32 -0700936 int64_t packets, bytes;
JP Abgrallf3cc83f2013-09-11 20:01:59 -0700937 int statsFound = 0;
JP Abgrallbaeccc42013-06-25 09:44:10 -0700938
939 bool filterPair = filter.intIface[0] && filter.extIface[0];
940
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900941 ALOGV("filter: %s", filter.getStatsLine().c_str());
JP Abgrallbaeccc42013-06-25 09:44:10 -0700942
943 stats = filter;
JP Abgralldb7da582011-09-18 12:57:32 -0700944
Lorenzo Colittice6748a2017-02-02 01:34:33 +0900945 std::stringstream stream(statsOutput);
946 while (std::getline(stream, statsLine, '\n')) {
947 buffPtr = statsLine.c_str();
948
JP Abgralldb7da582011-09-18 12:57:32 -0700949 /* Clean up, so a failed parse can still print info */
950 iface0[0] = iface1[0] = rest[0] = packets = bytes = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +0900951 if (strstr(buffPtr, "0.0.0.0")) {
952 // IPv4 has -- indicating what to do with fragments...
953 // 26 2373 RETURN all -- wlan0 rmnet0 0.0.0.0/0 0.0.0.0/0
954 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all -- %s %s 0.%s",
955 &packets, &bytes, iface0, iface1, rest);
956 } else {
957 // ... but IPv6 does not.
958 // 26 2373 RETURN all wlan0 rmnet0 ::/0 ::/0
959 res = sscanf(buffPtr, "%" SCNd64" %" SCNd64" RETURN all %s %s ::/%s",
960 &packets, &bytes, iface0, iface1, rest);
961 }
SynergyDev7776cea2014-03-16 15:48:51 -0700962 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 -0700963 iface0, iface1, packets, bytes, rest, buffPtr);
JP Abgralla2a64f02011-11-11 20:36:16 -0800964 extraProcessingInfo += buffPtr;
Lorenzo Colittice6748a2017-02-02 01:34:33 +0900965 extraProcessingInfo += "\n";
JP Abgralla2a64f02011-11-11 20:36:16 -0800966
JP Abgralldb7da582011-09-18 12:57:32 -0700967 if (res != 5) {
968 continue;
969 }
JP Abgrallbaeccc42013-06-25 09:44:10 -0700970 /*
971 * The following assumes that the 1st rule has in:extIface out:intIface,
972 * which is what NatController sets up.
973 * If not filtering, the 1st match rx, and sets up the pair for the tx side.
974 */
975 if (filter.intIface[0] && filter.extIface[0]) {
976 if (filter.intIface == iface0 && filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -0700977 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 -0700978 stats.rxPackets = packets;
979 stats.rxBytes = bytes;
980 } else if (filter.intIface == iface1 && filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -0700981 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 -0700982 stats.txPackets = packets;
983 stats.txBytes = bytes;
984 }
985 } else if (filter.intIface[0] || filter.extIface[0]) {
986 if (filter.intIface == iface0 || filter.extIface == iface1) {
SynergyDev7776cea2014-03-16 15:48:51 -0700987 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 -0700988 stats.intIface = iface0;
989 stats.extIface = iface1;
990 stats.rxPackets = packets;
991 stats.rxBytes = bytes;
992 } else if (filter.intIface == iface1 || filter.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -0700993 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 -0700994 stats.intIface = iface1;
995 stats.extIface = iface0;
996 stats.txPackets = packets;
997 stats.txBytes = bytes;
998 }
999 } else /* if (!filter.intFace[0] && !filter.extIface[0]) */ {
1000 if (!stats.intIface[0]) {
SynergyDev7776cea2014-03-16 15:48:51 -07001001 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 -07001002 stats.intIface = iface0;
1003 stats.extIface = iface1;
1004 stats.rxPackets = packets;
1005 stats.rxBytes = bytes;
1006 } else if (stats.intIface == iface1 && stats.extIface == iface0) {
SynergyDev7776cea2014-03-16 15:48:51 -07001007 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 -07001008 stats.txPackets = packets;
1009 stats.txBytes = bytes;
1010 }
1011 }
1012 if (stats.rxBytes != -1 && stats.txBytes != -1) {
SynergyDev7776cea2014-03-16 15:48:51 -07001013 ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64" filterPair=%d", stats.rxBytes, stats.txBytes, filterPair);
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001014 addStats(statsList, stats);
JP Abgrallbaeccc42013-06-25 09:44:10 -07001015 if (filterPair) {
JP Abgrallbaeccc42013-06-25 09:44:10 -07001016 return 0;
1017 } else {
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001018 statsFound++;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001019 stats = filter;
1020 }
JP Abgralldb7da582011-09-18 12:57:32 -07001021 }
1022 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001023
1024 /* It is always an error to find only one side of the stats. */
1025 /* It is an error to find nothing when not filtering. */
1026 if (((stats.rxBytes == -1) != (stats.txBytes == -1)) ||
1027 (!statsFound && !filterPair)) {
1028 return -1;
JP Abgrallbaeccc42013-06-25 09:44:10 -07001029 }
JP Abgrallf3cc83f2013-09-11 20:01:59 -07001030 return 0;
JP Abgralldb7da582011-09-18 12:57:32 -07001031}
1032
Joel Scherpelzbcad6612017-05-30 10:55:11 +09001033std::string BandwidthController::TetherStats::getStatsLine() const {
1034 std::string msg;
1035 StringAppendF(&msg, "%s %s %" PRId64" %" PRId64" %" PRId64" %" PRId64, intIface.c_str(),
1036 extIface.c_str(), rxBytes, rxPackets, txBytes, txPackets);
JP Abgralldb7da582011-09-18 12:57:32 -07001037 return msg;
1038}
1039
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001040int BandwidthController::getTetherStats(SocketClient *cli, TetherStats& filter,
1041 std::string &extraProcessingInfo) {
1042 int res = 0;
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001043
1044 TetherStatsList statsList;
1045
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001046 for (const IptablesTarget target : {V4, V6}) {
1047 std::string statsString;
1048 res = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString);
1049 if (res != 0) {
1050 ALOGE("Failed to run %s err=%d", GET_TETHER_STATS_COMMAND.c_str(), res);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001051 return -1;
1052 }
1053
Lorenzo Colittice6748a2017-02-02 01:34:33 +09001054 res = addForwardChainStats(filter, statsList, statsString, extraProcessingInfo);
Lorenzo Colitti26c91322016-07-11 11:36:25 +09001055 if (res != 0) {
1056 return res;
1057 }
1058 }
JP Abgralldb7da582011-09-18 12:57:32 -07001059
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001060 if (filter.intIface[0] && filter.extIface[0] && statsList.size() == 1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +09001061 cli->sendMsg(ResponseCode::TetheringStatsResult,
1062 statsList[0].getStatsLine().c_str(), false);
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001063 } else {
1064 for (const auto& stats: statsList) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +09001065 cli->sendMsg(ResponseCode::TetheringStatsListResult,
1066 stats.getStatsLine().c_str(), false);
Lorenzo Colitti7364b752016-07-08 18:24:53 +09001067 }
1068 if (res == 0) {
1069 cli->sendMsg(ResponseCode::CommandOkay, "Tethering stats list completed", false);
1070 }
1071 }
1072
JP Abgralldb7da582011-09-18 12:57:32 -07001073 return res;
1074}
JP Abgrall0e540ec2013-08-26 15:13:10 -07001075
1076void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001077 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
1078 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001079
1080 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001081 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
1082 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001083 return;
1084 }
1085 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001086 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001087}
1088
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001089void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
1090 std::stringstream stream(ruleList);
1091 std::string rule;
1092 std::vector<std::string> clearCommands = { "*filter" };
1093 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -07001094
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001095 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
1096 while (std::getline(stream, rule, '\n')) {
1097 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
1098 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
1099 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
1100
1101 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -07001102 continue;
1103 }
1104
Lorenzo Colitti3c272702017-04-26 15:48:13 +09001105 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001106 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +09001107 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -07001108 }
1109 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +09001110
1111 if (clearCommands.size() == 1) {
1112 // No rules found.
1113 return;
1114 }
1115
1116 clearCommands.push_back("COMMIT\n");
1117 iptablesRestoreFunction(V4V6, android::base::Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -07001118}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +09001119
1120inline const char *BandwidthController::opToString(IptOp op) {
1121 switch (op) {
1122 case IptOpInsert:
1123 return "-I";
1124 case IptOpDelete:
1125 return "-D";
1126 }
1127}
1128
1129inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
1130 /*
1131 * Must be careful what one rejects with, as upper layer protocols will just
1132 * keep on hammering the device until the number of retries are done.
1133 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
1134 */
1135 switch (jumpHandling) {
1136 case IptJumpNoAdd:
1137 return "";
1138 case IptJumpReject:
1139 return " --jump REJECT";
1140 case IptJumpReturn:
1141 return " --jump RETURN";
1142 }
1143}