blob: 50064788120f9b03cd9ca1cdbb9ddc2d51943cce [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"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070049#include <cutils/properties.h>
Logan Chien3f461482018-04-23 14:31:32 +080050#include <log/log.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"
Chenbo Feng5ed17992018-03-13 21:30:49 -070055#include "Controllers.h"
Lorenzo Colittiaff28792017-09-26 17:46:18 +090056#include "FirewallController.h" /* For makeCriticalCommands */
Benedict Wongb9baf262017-12-03 15:43:08 -080057#include "Fwmark.h"
Joel Scherpelz01cc5492017-06-16 10:45:14 +090058#include "NetdConstants.h"
Chenbo Feng5ed17992018-03-13 21:30:49 -070059#include "bpf/BpfUtils.h"
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070060
JP Abgralldb7da582011-09-18 12:57:32 -070061/* Alphabetical */
Lorenzo Colitti3c272702017-04-26 15:48:13 +090062#define ALERT_IPT_TEMPLATE "%s %s -m quota2 ! --quota %" PRId64" --name %s\n"
Joel Scherpelzbcad6612017-05-30 10:55:11 +090063const char BandwidthController::LOCAL_INPUT[] = "bw_INPUT";
64const char BandwidthController::LOCAL_FORWARD[] = "bw_FORWARD";
65const char BandwidthController::LOCAL_OUTPUT[] = "bw_OUTPUT";
66const char BandwidthController::LOCAL_RAW_PREROUTING[] = "bw_raw_PREROUTING";
67const char BandwidthController::LOCAL_MANGLE_POSTROUTING[] = "bw_mangle_POSTROUTING";
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090068
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090069auto BandwidthController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
Lorenzo Colitti86a47982016-03-18 17:52:25 +090070
Joel Scherpelzd59526a2017-06-28 16:24:09 +090071using android::base::Join;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090072using android::base::StringAppendF;
73using android::base::StringPrintf;
Chenbo Feng5ed17992018-03-13 21:30:49 -070074using android::bpf::XT_BPF_EGRESS_PROG_PATH;
75using android::bpf::XT_BPF_INGRESS_PROG_PATH;
Joel Scherpelz01cc5492017-06-16 10:45:14 +090076using android::netdutils::StatusOr;
77using android::netdutils::UniqueFile;
Lorenzo Colitti3c272702017-04-26 15:48:13 +090078
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +090079namespace {
80
81const char ALERT_GLOBAL_NAME[] = "globalAlert";
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +090082const std::string NEW_CHAIN_COMMAND = "-N ";
Lorenzo Colittice6748a2017-02-02 01:34:33 +090083
Joel Scherpelzbcad6612017-05-30 10:55:11 +090084const char NAUGHTY_CHAIN[] = "bw_penalty_box";
85const char NICE_CHAIN[] = "bw_happy_box";
JP Abgralldb7da582011-09-18 12:57:32 -070086
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070087/**
88 * Some comments about the rules:
89 * * Ordering
90 * - when an interface is marked as costly it should be INSERTED into the INPUT/OUTPUT chains.
JP Abgrall29e8de22012-05-03 12:52:15 -070091 * E.g. "-I bw_INPUT -i rmnet0 --jump costly"
JP Abgrall7e51cde2013-07-03 13:33:05 -070092 * - quota'd rules in the costly chain should be before bw_penalty_box lookups.
JP Abgrall29e8de22012-05-03 12:52:15 -070093 * - the qtaguid counting is done at the end of the bw_INPUT/bw_OUTPUT user chains.
JP Abgrall4a5f5ca2011-06-15 18:37:39 -070094 *
95 * * global quota vs per interface quota
96 * - global quota for all costly interfaces uses a single costly chain:
97 * . initial rules
JP Abgrall7e51cde2013-07-03 13:33:05 -070098 * iptables -N bw_costly_shared
99 * iptables -I bw_INPUT -i iface0 --jump bw_costly_shared
100 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_shared
101 * iptables -I bw_costly_shared -m quota \! --quota 500000 \
JP Abgrallbfa74662011-06-29 19:23:04 -0700102 * --jump REJECT --reject-with icmp-net-prohibited
JP Abgrall7e51cde2013-07-03 13:33:05 -0700103 * iptables -A bw_costly_shared --jump bw_penalty_box
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900104 * iptables -A bw_penalty_box --jump bw_happy_box
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900105 * iptables -A bw_happy_box --jump bw_data_saver
JP Abgrall8a932722011-07-13 19:17:35 -0700106 *
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700107 * . adding a new iface to this, E.g.:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700108 * iptables -I bw_INPUT -i iface1 --jump bw_costly_shared
109 * iptables -I bw_OUTPUT -o iface1 --jump bw_costly_shared
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700110 *
111 * - quota per interface. This is achieve by having "costly" chains per quota.
112 * E.g. adding a new costly interface iface0 with its own quota:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700113 * iptables -N bw_costly_iface0
114 * iptables -I bw_INPUT -i iface0 --jump bw_costly_iface0
115 * iptables -I bw_OUTPUT -o iface0 --jump bw_costly_iface0
116 * iptables -A bw_costly_iface0 -m quota \! --quota 500000 \
JP Abgralle4788732013-07-02 20:28:45 -0700117 * --jump REJECT --reject-with icmp-port-unreachable
JP Abgrall7e51cde2013-07-03 13:33:05 -0700118 * iptables -A bw_costly_iface0 --jump bw_penalty_box
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700119 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900120 * * Penalty box, happy box and data saver.
121 * - bw_penalty box is a blacklist of apps that are rejected.
122 * - bw_happy_box is a whitelist of apps. It always includes all system apps
123 * - bw_data_saver implements data usage restrictions.
124 * - Via the UI the user can add and remove apps from the whitelist and
125 * blacklist, and turn on/off data saver.
126 * - The blacklist takes precedence over the whitelist and the whitelist
127 * takes precedence over data saver.
128 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700129 * * bw_penalty_box handling:
130 * - only one bw_penalty_box for all interfaces
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900131 * E.g Adding an app:
JP Abgrall7e51cde2013-07-03 13:33:05 -0700132 * iptables -I bw_penalty_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700133 * --jump REJECT --reject-with icmp-port-unreachable
134 *
JP Abgrall7e51cde2013-07-03 13:33:05 -0700135 * * bw_happy_box handling:
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900136 * - The bw_happy_box comes after the penalty box.
JP Abgralle4788732013-07-02 20:28:45 -0700137 * E.g Adding a happy app,
JP Abgrall7e51cde2013-07-03 13:33:05 -0700138 * iptables -I bw_happy_box -m owner --uid-owner app_3 \
JP Abgralle4788732013-07-02 20:28:45 -0700139 * --jump RETURN
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900140 *
Lorenzo Colitti464eabe2016-03-25 13:38:19 +0900141 * * bw_data_saver handling:
142 * - The bw_data_saver comes after the happy box.
143 * Enable data saver:
144 * iptables -R 1 bw_data_saver --jump REJECT --reject-with icmp-port-unreachable
145 * Disable data saver:
146 * iptables -R 1 bw_data_saver --jump RETURN
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700147 */
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900148
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900149const std::string COMMIT_AND_CLOSE = "COMMIT\n";
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900150const std::string HAPPY_BOX_WHITELIST_COMMAND = StringPrintf(
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900151 "-I bw_happy_box -m owner --uid-owner %d-%d --jump RETURN", 0, MAX_SYSTEM_UID);
152
153static const std::vector<std::string> IPT_FLUSH_COMMANDS = {
JP Abgrall0031cea2012-04-17 16:38:23 -0700154 /*
155 * Cleanup rules.
JP Abgrall7e51cde2013-07-03 13:33:05 -0700156 * Should normally include bw_costly_<iface>, but we rely on the way they are setup
JP Abgrall0031cea2012-04-17 16:38:23 -0700157 * to allow coexistance.
JP Abgrall39f8f242011-06-29 19:21:58 -0700158 */
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900159 "*filter",
160 ":bw_INPUT -",
161 ":bw_OUTPUT -",
162 ":bw_FORWARD -",
163 ":bw_happy_box -",
164 ":bw_penalty_box -",
165 ":bw_data_saver -",
166 ":bw_costly_shared -",
167 "COMMIT",
168 "*raw",
169 ":bw_raw_PREROUTING -",
170 "COMMIT",
171 "*mangle",
172 ":bw_mangle_POSTROUTING -",
173 COMMIT_AND_CLOSE
JP Abgrall0031cea2012-04-17 16:38:23 -0700174};
175
Benedict Wongb9baf262017-12-03 15:43:08 -0800176static const uint32_t uidBillingMask = Fwmark::getUidBillingMask();
177
178/**
179 * Basic commands for creation of hooks into data accounting and data boxes.
180 *
181 * Included in these commands are rules to prevent the double-counting of IPsec
182 * packets. The general overview is as follows:
183 * > All interface counters (counted in PREROUTING, POSTROUTING) must be
184 * completely accurate, and count only the outer packet. As such, the inner
185 * packet must be ignored, which is done through the use of two rules: use
186 * of the policy module (for tunnel mode), and VTI interface checks (for
187 * tunnel or transport-in-tunnel mode). The VTI interfaces should be named
188 * ipsec*
189 * > Outbound UID billing can always be done with the outer packets, due to the
190 * ability to always find the correct UID (based on the skb->sk). As such,
191 * the inner packets should be ignored based on the policy module, or the
192 * output interface if a VTI (ipsec+)
193 * > Inbound UDP-encap-ESP packets can be correctly mapped to the UID that
194 * opened the encap socket, and as such, should be billed as early as
195 * possible (for transport mode; tunnel mode usage should be billed to
196 * sending/receiving application). Due to the inner packet being
197 * indistinguishable from the inner packet of ESP, a uidBillingDone mark
198 * has to be applied to prevent counting a second time.
199 * > Inbound ESP has no socket, and as such must be accounted later. ESP
200 * protocol packets are skipped via a blanket rule.
201 * > Note that this solution is asymmetrical. Adding the VTI or policy matcher
202 * ignore rule in the input chain would actually break the INPUT chain;
203 * Those rules are designed to ignore inner packets, and in the tunnel
204 * mode UDP, or any ESP case, we would not have billed the outer packet.
205 *
206 * See go/ipsec-data-accounting for more information.
207 */
Benedict Wongb9baf262017-12-03 15:43:08 -0800208
Chenbo Feng5ed17992018-03-13 21:30:49 -0700209const std::vector<std::string> getBasicAccountingCommands() {
Chenbo Fenga121e202018-03-19 11:51:54 -0700210 bool useBpf = BandwidthController::getBpfStatsStatus();
Chenbo Feng5ed17992018-03-13 21:30:49 -0700211 const std::vector<std::string> ipt_basic_accounting_commands = {
212 "*filter",
213 // Prevents IPSec double counting (ESP and UDP-encap-ESP respectively)
214 "-A bw_INPUT -p esp -j RETURN",
215 StringPrintf("-A bw_INPUT -m mark --mark 0x%x/0x%x -j RETURN",
216 uidBillingMask, uidBillingMask),
217 "-A bw_INPUT -m owner --socket-exists", /* This is a tracking rule. */
218 StringPrintf("-A bw_INPUT -j MARK --or-mark 0x%x", uidBillingMask),
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900219
Chenbo Feng5ed17992018-03-13 21:30:49 -0700220 // Prevents IPSec double counting (Tunnel mode and Transport mode,
221 // respectively)
222 "-A bw_OUTPUT -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
223 "-A bw_OUTPUT -m policy --pol ipsec --dir out -j RETURN",
224 "-A bw_OUTPUT -m owner --socket-exists", /* This is a tracking rule. */
Lorenzo Colitti13debb82016-03-27 17:46:30 +0900225
Chenbo Feng5ed17992018-03-13 21:30:49 -0700226 "-A bw_costly_shared --jump bw_penalty_box",
227 "-A bw_penalty_box --jump bw_happy_box",
228 "-A bw_happy_box --jump bw_data_saver",
229 "-A bw_data_saver -j RETURN",
230 HAPPY_BOX_WHITELIST_COMMAND,
231 "COMMIT",
232
233 "*raw",
234 // Prevents IPSec double counting (Tunnel mode and Transport mode,
235 // respectively)
236 "-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN",
237 "-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN",
238 "-A bw_raw_PREROUTING -m owner --socket-exists", /* This is a tracking rule. */
239 useBpf ? StringPrintf("-A bw_raw_PREROUTING -m bpf --object-pinned %s",
240 XT_BPF_INGRESS_PROG_PATH):"",
241 "COMMIT",
242
243 "*mangle",
244 // Prevents IPSec double counting (Tunnel mode and Transport mode,
245 // respectively)
246 "-A bw_mangle_POSTROUTING -o " IPSEC_IFACE_PREFIX "+ -j RETURN",
247 "-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
248 "-A bw_mangle_POSTROUTING -m owner --socket-exists", /* This is a tracking rule. */
249 StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x",
250 uidBillingMask), // Clear the mark before sending this packet
251 useBpf ? StringPrintf("-A bw_mangle_POSTROUTING -m bpf --object-pinned %s",
252 XT_BPF_EGRESS_PROG_PATH):"",
253 COMMIT_AND_CLOSE
254 };
255 return ipt_basic_accounting_commands;
256}
257
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900258
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900259std::vector<std::string> toStrVec(int num, const char* const strs[]) {
260 return std::vector<std::string>(strs, strs + num);
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900261}
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900262
263} // namespace
264
Chenbo Fenga121e202018-03-19 11:51:54 -0700265bool BandwidthController::getBpfStatsStatus() {
Chenbo Feng33a4de12018-03-16 18:10:07 -0700266 return (access(XT_BPF_INGRESS_PROG_PATH, F_OK) != -1) &&
267 (access(XT_BPF_EGRESS_PROG_PATH, F_OK) != -1);
Chenbo Fenga121e202018-03-19 11:51:54 -0700268}
269
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900270BandwidthController::BandwidthController() {
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700271}
272
JP Abgrall0e540ec2013-08-26 15:13:10 -0700273void BandwidthController::flushCleanTables(bool doClean) {
274 /* Flush and remove the bw_costly_<iface> tables */
275 flushExistingCostlyTables(doClean);
JP Abgrall0031cea2012-04-17 16:38:23 -0700276
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900277 std::string commands = Join(IPT_FLUSH_COMMANDS, '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900278 iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700279}
JP Abgrall0031cea2012-04-17 16:38:23 -0700280
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900281int BandwidthController::setupIptablesHooks() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700282 /* flush+clean is allowed to fail */
283 flushCleanTables(true);
JP Abgrall0031cea2012-04-17 16:38:23 -0700284 return 0;
JP Abgrall0031cea2012-04-17 16:38:23 -0700285}
286
287int BandwidthController::enableBandwidthControl(bool force) {
JP Abgrall0031cea2012-04-17 16:38:23 -0700288 char value[PROPERTY_VALUE_MAX];
289
290 if (!force) {
291 property_get("persist.bandwidth.enable", value, "1");
292 if (!strcmp(value, "0"))
293 return 0;
294 }
JP Abgrall8a932722011-07-13 19:17:35 -0700295
JP Abgralldb7da582011-09-18 12:57:32 -0700296 /* Let's pretend we started from scratch ... */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900297 mSharedQuotaIfaces.clear();
298 mQuotaIfaces.clear();
299 mGlobalAlertBytes = 0;
300 mGlobalAlertTetherCount = 0;
301 mSharedQuotaBytes = mSharedAlertBytes = 0;
JP Abgralldb7da582011-09-18 12:57:32 -0700302
JP Abgrall0e540ec2013-08-26 15:13:10 -0700303 flushCleanTables(false);
Chenbo Feng5ed17992018-03-13 21:30:49 -0700304
305 std::string commands = Join(getBasicAccountingCommands(), '\n');
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900306 return iptablesRestoreFunction(V4V6, commands, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700307}
308
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900309int BandwidthController::disableBandwidthControl() {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700310
311 flushCleanTables(false);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700312 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700313}
314
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900315std::string BandwidthController::makeDataSaverCommand(IptablesTarget target, bool enable) {
316 std::string cmd;
317 const char *chainName = "bw_data_saver";
318 const char *op = jumpToString(enable ? IptJumpReject : IptJumpReturn);
319 std::string criticalCommands = enable ?
320 FirewallController::makeCriticalCommands(target, chainName) : "";
321 StringAppendF(&cmd,
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900322 "*filter\n"
Lorenzo Colittiaff28792017-09-26 17:46:18 +0900323 ":%s -\n"
324 "%s"
325 "-A %s%s\n"
326 "COMMIT\n", chainName, criticalCommands.c_str(), chainName, op);
327 return cmd;
328}
329
330int BandwidthController::enableDataSaver(bool enable) {
331 int ret = iptablesRestoreFunction(V4, makeDataSaverCommand(V4, enable), nullptr);
332 ret |= iptablesRestoreFunction(V6, makeDataSaverCommand(V6, enable), nullptr);
333 return ret;
Lorenzo Colitti7618ccb2016-03-18 12:36:03 +0900334}
335
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900336int BandwidthController::addNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900337 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
338 IptJumpReject, IptOpInsert);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700339}
340
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900341int BandwidthController::removeNaughtyApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900342 return manipulateSpecialApps(toStrVec(numUids, appUids), NAUGHTY_CHAIN,
343 IptJumpReject, IptOpDelete);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700344}
345
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900346int BandwidthController::addNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900347 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
348 IptJumpReturn, IptOpInsert);
JP Abgralle4788732013-07-02 20:28:45 -0700349}
350
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900351int BandwidthController::removeNiceApps(int numUids, const char* const appUids[]) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900352 return manipulateSpecialApps(toStrVec(numUids, appUids), NICE_CHAIN,
353 IptJumpReturn, IptOpDelete);
JP Abgralle4788732013-07-02 20:28:45 -0700354}
355
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900356int BandwidthController::manipulateSpecialApps(const std::vector<std::string>& appStrUids,
357 const std::string& chain, IptJumpOp jumpHandling,
358 IptOp op) {
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900359 std::string cmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900360 for (const auto& appStrUid : appStrUids) {
361 StringAppendF(&cmd, "%s %s -m owner --uid-owner %s%s\n", opToString(op), chain.c_str(),
362 appStrUid.c_str(), jumpToString(jumpHandling));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700363 }
Lorenzo Colitti911bc4c2017-04-28 14:34:01 +0900364 StringAppendF(&cmd, "COMMIT\n");
365 return iptablesRestoreFunction(V4V6, cmd, nullptr);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700366}
367
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900368int BandwidthController::setInterfaceSharedQuota(const std::string& iface, int64_t maxBytes) {
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700369 int res = 0;
JP Abgrall26e0d492011-06-24 19:21:51 -0700370 std::string quotaCmd;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900371 constexpr char cost[] = "shared";
372 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700373
JP Abgrall8a932722011-07-13 19:17:35 -0700374 if (!maxBytes) {
375 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000376 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700377 return -1;
378 }
JP Abgrall69261cb2014-06-19 18:35:24 -0700379 if (!isIfaceName(iface))
380 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700381
382 if (maxBytes == -1) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900383 return removeInterfaceSharedQuota(iface);
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700384 }
385
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900386 auto it = mSharedQuotaIfaces.find(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700387
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900388 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900389 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
390 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900391 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900392 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(), chain),
393 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900394 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900395 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
396 };
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900397 if (mSharedQuotaIfaces.empty()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900398 cmds.push_back(StringPrintf("-I %s -m quota2 ! --quota %" PRId64
399 " --name %s --jump REJECT",
400 chain, maxBytes, cost));
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900401 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900402 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900403
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900404 res |= iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900405 if (res) {
406 ALOGE("Failed set quota rule");
407 removeInterfaceSharedQuota(iface);
408 return -1;
409 }
410 mSharedQuotaBytes = maxBytes;
411 mSharedQuotaIfaces.insert(iface);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700412 }
413
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900414 if (maxBytes != mSharedQuotaBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900415 res |= updateQuota(cost, maxBytes);
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700416 if (res) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900417 ALOGE("Failed update quota for %s", cost);
418 removeInterfaceSharedQuota(iface);
419 return -1;
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700420 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900421 mSharedQuotaBytes = maxBytes;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700422 }
423 return 0;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700424}
425
JP Abgrall8a932722011-07-13 19:17:35 -0700426/* It will also cleanup any shared alerts */
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900427int BandwidthController::removeInterfaceSharedQuota(const std::string& iface) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900428 constexpr char cost[] = "shared";
429 constexpr char chain[] = "bw_costly_shared";
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700430
JP Abgrall69261cb2014-06-19 18:35:24 -0700431 if (!isIfaceName(iface))
432 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700433
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900434 auto it = mSharedQuotaIfaces.find(iface);
435
436 if (it == mSharedQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900437 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700438 return -1;
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700439 }
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700440
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900441 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900442 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900443 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain),
444 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain),
Erik Kline51eb3242017-09-20 18:30:47 +0900445 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900446 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain),
447 };
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900448 if (mSharedQuotaIfaces.size() == 1) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900449 cmds.push_back(StringPrintf("-D %s -m quota2 ! --quota %" PRIu64
450 " --name %s --jump REJECT",
451 chain, mSharedQuotaBytes, cost));
JP Abgrallfa6f46d2011-06-17 23:17:28 -0700452 }
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900453 cmds.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900454
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900455 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
456 ALOGE("Failed to remove shared quota on %s", iface.c_str());
457 return -1;
458 }
459
460 int res = 0;
461 mSharedQuotaIfaces.erase(it);
462 if (mSharedQuotaIfaces.empty()) {
463 mSharedQuotaBytes = 0;
464 if (mSharedAlertBytes) {
465 res = removeSharedAlert();
466 if (res == 0) {
467 mSharedAlertBytes = 0;
468 }
469 }
470 }
471
472 return res;
473
JP Abgrall4a5f5ca2011-06-15 18:37:39 -0700474}
JP Abgrall0dad7c22011-06-24 11:58:14 -0700475
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900476int BandwidthController::setInterfaceQuota(const std::string& iface, int64_t maxBytes) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900477 const std::string& cost = iface;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700478
JP Abgrall69261cb2014-06-19 18:35:24 -0700479 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700480 return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700481
JP Abgrall8a932722011-07-13 19:17:35 -0700482 if (!maxBytes) {
483 /* Don't talk about -1, deprecate it. */
Steve Block5ea0c052012-01-06 19:18:11 +0000484 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700485 return -1;
486 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700487 if (maxBytes == -1) {
JP Abgrall26e0d492011-06-24 19:21:51 -0700488 return removeInterfaceQuota(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700489 }
490
JP Abgrall0dad7c22011-06-24 11:58:14 -0700491 /* Insert ingress quota. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900492 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700493
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900494 if (it != mQuotaIfaces.end()) {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900495 if (updateQuota(cost, maxBytes) != 0) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900496 ALOGE("Failed update quota for %s", iface.c_str());
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900497 removeInterfaceQuota(iface);
498 return -1;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700499 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900500 it->second.quota = maxBytes;
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900501 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700502 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700503
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900504 const std::string chain = "bw_costly_" + iface;
505 const int ruleInsertPos = (mGlobalAlertBytes) ? 2 : 1;
506 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900507 "*filter",
508 StringPrintf(":%s -", chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900509 StringPrintf("-A %s -j bw_penalty_box", chain.c_str()),
510 StringPrintf("-I bw_INPUT %d -i %s --jump %s", ruleInsertPos, iface.c_str(),
511 chain.c_str()),
512 StringPrintf("-I bw_OUTPUT %d -o %s --jump %s", ruleInsertPos, iface.c_str(),
513 chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900514 StringPrintf("-A bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900515 StringPrintf("-A bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
516 StringPrintf("-A %s -m quota2 ! --quota %" PRId64 " --name %s --jump REJECT",
517 chain.c_str(), maxBytes, cost.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900518 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900519 };
520
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900521 if (iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr) != 0) {
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900522 ALOGE("Failed set quota rule");
523 removeInterfaceQuota(iface);
524 return -1;
525 }
526
527 mQuotaIfaces[iface] = QuotaInfo{maxBytes, 0};
528 return 0;
JP Abgrall0dad7c22011-06-24 11:58:14 -0700529}
530
JP Abgrall8a932722011-07-13 19:17:35 -0700531int BandwidthController::getInterfaceSharedQuota(int64_t *bytes) {
532 return getInterfaceQuota("shared", bytes);
533}
534
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900535int BandwidthController::getInterfaceQuota(const std::string& iface, int64_t* bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900536 const auto& sys = android::netdutils::sSyscalls.get();
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900537 const std::string fname = "/proc/net/xt_quota/" + iface;
JP Abgrall8a932722011-07-13 19:17:35 -0700538
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900539 if (!isIfaceName(iface)) return -1;
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700540
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900541 StatusOr<UniqueFile> file = sys.fopen(fname, "re");
542 if (!isOk(file)) {
543 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700544 return -1;
545 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900546 auto rv = sys.fscanf(file.value().get(), "%" SCNd64, bytes);
547 if (!isOk(rv)) {
548 ALOGE("Reading quota %s failed (%s)", iface.c_str(), toString(rv).c_str());
549 return -1;
550 }
551 ALOGV("Read quota res=%d bytes=%" PRId64, rv.value(), *bytes);
552 return rv.value() == 1 ? 0 : -1;
JP Abgrall8a932722011-07-13 19:17:35 -0700553}
554
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900555int BandwidthController::removeInterfaceQuota(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700556 if (!isIfaceName(iface))
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700557 return -1;
JP Abgrall26e0d492011-06-24 19:21:51 -0700558
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900559 auto it = mQuotaIfaces.find(iface);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700560
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900561 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900562 ALOGE("No such iface %s to delete", iface.c_str());
JP Abgrall0dad7c22011-06-24 11:58:14 -0700563 return -1;
564 }
565
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900566 const std::string chain = "bw_costly_" + iface;
567 std::vector<std::string> cmds = {
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900568 "*filter",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900569 StringPrintf("-D bw_INPUT -i %s --jump %s", iface.c_str(), chain.c_str()),
570 StringPrintf("-D bw_OUTPUT -o %s --jump %s", iface.c_str(), chain.c_str()),
Erik Kline51eb3242017-09-20 18:30:47 +0900571 StringPrintf("-D bw_FORWARD -i %s --jump %s", iface.c_str(), chain.c_str()),
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900572 StringPrintf("-D bw_FORWARD -o %s --jump %s", iface.c_str(), chain.c_str()),
573 StringPrintf("-F %s", chain.c_str()),
574 StringPrintf("-X %s", chain.c_str()),
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900575 "COMMIT\n",
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900576 };
Lorenzo Colitti48f83002017-07-06 15:06:04 +0900577
578 const int res = iptablesRestoreFunction(V4V6, Join(cmds, "\n"), nullptr);
JP Abgrall0dad7c22011-06-24 11:58:14 -0700579
Lorenzo Colittib7ac3f72017-07-06 16:52:52 +0900580 if (res == 0) {
581 mQuotaIfaces.erase(it);
582 }
JP Abgrall0dad7c22011-06-24 11:58:14 -0700583
584 return res;
585}
JP Abgrall8a932722011-07-13 19:17:35 -0700586
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900587int BandwidthController::updateQuota(const std::string& quotaName, int64_t bytes) {
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900588 const auto& sys = android::netdutils::sSyscalls.get();
589 const std::string fname = "/proc/net/xt_quota/" + quotaName;
JP Abgrall8a932722011-07-13 19:17:35 -0700590
JP Abgrall69261cb2014-06-19 18:35:24 -0700591 if (!isIfaceName(quotaName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900592 ALOGE("updateQuota: Invalid quotaName \"%s\"", quotaName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700593 return -1;
594 }
595
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900596 StatusOr<UniqueFile> file = sys.fopen(fname, "we");
597 if (!isOk(file)) {
598 ALOGE("Updating quota %s failed (%s)", quotaName.c_str(), toString(file).c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700599 return -1;
600 }
Joel Scherpelz01cc5492017-06-16 10:45:14 +0900601 sys.fprintf(file.value().get(), "%" PRId64 "\n", bytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700602 return 0;
603}
604
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900605int BandwidthController::runIptablesAlertCmd(IptOp op, const std::string& alertName,
606 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900607 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900608 std::string alertQuotaCmd = "*filter\n";
JP Abgrall8a932722011-07-13 19:17:35 -0700609
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900610 // TODO: consider using an alternate template for the delete that does not include the --quota
611 // value. This code works because the --quota value is ignored by deletes
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900612 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_INPUT", bytes,
613 alertName.c_str());
614 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_OUTPUT", bytes,
615 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900616 StringAppendF(&alertQuotaCmd, "COMMIT\n");
617
Lorenzo Colitti4773cb42017-04-27 14:03:25 +0900618 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrall8a932722011-07-13 19:17:35 -0700619}
620
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900621int BandwidthController::runIptablesAlertFwdCmd(IptOp op, const std::string& alertName,
622 int64_t bytes) {
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900623 const char *opFlag = opToString(op);
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900624 std::string alertQuotaCmd = "*filter\n";
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900625 StringAppendF(&alertQuotaCmd, ALERT_IPT_TEMPLATE, opFlag, "bw_FORWARD", bytes,
626 alertName.c_str());
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900627 StringAppendF(&alertQuotaCmd, "COMMIT\n");
628
629 return iptablesRestoreFunction(V4V6, alertQuotaCmd, nullptr);
JP Abgrallc6c67342011-10-07 16:28:54 -0700630}
631
632int BandwidthController::setGlobalAlert(int64_t bytes) {
633 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700634 int res = 0;
635
636 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000637 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700638 return -1;
639 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900640 if (mGlobalAlertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700641 res = updateQuota(alertName, bytes);
642 } else {
643 res = runIptablesAlertCmd(IptOpInsert, alertName, bytes);
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900644 if (mGlobalAlertTetherCount) {
645 ALOGV("setGlobalAlert for %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700646 res |= runIptablesAlertFwdCmd(IptOpInsert, alertName, bytes);
647 }
JP Abgrall8a932722011-07-13 19:17:35 -0700648 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900649 mGlobalAlertBytes = bytes;
JP Abgrall8a932722011-07-13 19:17:35 -0700650 return res;
651}
652
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900653int BandwidthController::setGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700654 const char *alertName = ALERT_GLOBAL_NAME;
655 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700656
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900657 mGlobalAlertTetherCount++;
658 ALOGV("setGlobalAlertInForwardChain(): %d tether", mGlobalAlertTetherCount);
JP Abgrallc6c67342011-10-07 16:28:54 -0700659
660 /*
661 * If there is no globalAlert active we are done.
662 * If there is an active globalAlert but this is not the 1st
663 * tether, we are also done.
664 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900665 if (!mGlobalAlertBytes || mGlobalAlertTetherCount != 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700666 return 0;
667 }
668
669 /* We only add the rule if this was the 1st tether added. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900670 res = runIptablesAlertFwdCmd(IptOpInsert, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700671 return res;
672}
673
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900674int BandwidthController::removeGlobalAlert() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700675
676 const char *alertName = ALERT_GLOBAL_NAME;
JP Abgrall8a932722011-07-13 19:17:35 -0700677 int res = 0;
678
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900679 if (!mGlobalAlertBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000680 ALOGE("No prior alert set");
JP Abgrall8a932722011-07-13 19:17:35 -0700681 return -1;
682 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900683 res = runIptablesAlertCmd(IptOpDelete, alertName, mGlobalAlertBytes);
684 if (mGlobalAlertTetherCount) {
685 res |= runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700686 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900687 mGlobalAlertBytes = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700688 return res;
689}
690
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900691int BandwidthController::removeGlobalAlertInForwardChain() {
JP Abgrallc6c67342011-10-07 16:28:54 -0700692 int res = 0;
693 const char *alertName = ALERT_GLOBAL_NAME;
694
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900695 if (!mGlobalAlertTetherCount) {
Steve Block5ea0c052012-01-06 19:18:11 +0000696 ALOGE("No prior alert set");
JP Abgrallc6c67342011-10-07 16:28:54 -0700697 return -1;
698 }
699
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900700 mGlobalAlertTetherCount--;
JP Abgrallc6c67342011-10-07 16:28:54 -0700701 /*
702 * If there is no globalAlert active we are done.
703 * If there is an active globalAlert but there are more
704 * tethers, we are also done.
705 */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900706 if (!mGlobalAlertBytes || mGlobalAlertTetherCount >= 1) {
JP Abgrallc6c67342011-10-07 16:28:54 -0700707 return 0;
708 }
709
710 /* We only detete the rule if this was the last tether removed. */
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900711 res = runIptablesAlertFwdCmd(IptOpDelete, alertName, mGlobalAlertBytes);
JP Abgrallc6c67342011-10-07 16:28:54 -0700712 return res;
713}
714
JP Abgrall8a932722011-07-13 19:17:35 -0700715int BandwidthController::setSharedAlert(int64_t bytes) {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900716 if (!mSharedQuotaBytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000717 ALOGE("Need to have a prior shared quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700718 return -1;
719 }
720 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000721 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700722 return -1;
723 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900724 return setCostlyAlert("shared", bytes, &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700725}
726
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900727int BandwidthController::removeSharedAlert() {
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900728 return removeCostlyAlert("shared", &mSharedAlertBytes);
JP Abgrall8a932722011-07-13 19:17:35 -0700729}
730
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900731int BandwidthController::setInterfaceAlert(const std::string& iface, int64_t bytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700732 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900733 ALOGE("setInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700734 return -1;
735 }
736
JP Abgrall8a932722011-07-13 19:17:35 -0700737 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000738 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700739 return -1;
740 }
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900741 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700742
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900743 if (it == mQuotaIfaces.end()) {
Steve Block5ea0c052012-01-06 19:18:11 +0000744 ALOGE("Need to have a prior interface quota set to set an alert");
JP Abgrall8a932722011-07-13 19:17:35 -0700745 return -1;
746 }
747
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900748 return setCostlyAlert(iface, bytes, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700749}
750
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900751int BandwidthController::removeInterfaceAlert(const std::string& iface) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700752 if (!isIfaceName(iface)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900753 ALOGE("removeInterfaceAlert: Invalid iface \"%s\"", iface.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700754 return -1;
755 }
756
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900757 auto it = mQuotaIfaces.find(iface);
JP Abgrall8a932722011-07-13 19:17:35 -0700758
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900759 if (it == mQuotaIfaces.end()) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900760 ALOGE("No prior alert set for interface %s", iface.c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700761 return -1;
762 }
763
Joel Scherpelzced1dd92017-06-28 10:19:52 +0900764 return removeCostlyAlert(iface, &it->second.alert);
JP Abgrall8a932722011-07-13 19:17:35 -0700765}
766
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900767int BandwidthController::setCostlyAlert(const std::string& costName, int64_t bytes,
768 int64_t* alertBytes) {
JP Abgrall8a932722011-07-13 19:17:35 -0700769 int res = 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700770
JP Abgrall69261cb2014-06-19 18:35:24 -0700771 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900772 ALOGE("setCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700773 return -1;
774 }
775
JP Abgrall8a932722011-07-13 19:17:35 -0700776 if (!bytes) {
Steve Block5ea0c052012-01-06 19:18:11 +0000777 ALOGE("Invalid bytes value. 1..max_int64.");
JP Abgrall8a932722011-07-13 19:17:35 -0700778 return -1;
779 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900780
781 std::string alertName = costName + "Alert";
782 std::string chainName = "bw_costly_" + costName;
JP Abgrall8a932722011-07-13 19:17:35 -0700783 if (*alertBytes) {
784 res = updateQuota(alertName, *alertBytes);
785 } else {
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900786 std::vector<std::string> commands = {
787 "*filter\n",
788 StringPrintf(ALERT_IPT_TEMPLATE, "-A", chainName.c_str(), bytes, alertName.c_str()),
789 "COMMIT\n"
790 };
791 res = iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr);
792 if (res) {
793 ALOGE("Failed to set costly alert for %s", costName.c_str());
794 }
JP Abgrall8a932722011-07-13 19:17:35 -0700795 }
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900796 if (res == 0) {
797 *alertBytes = bytes;
798 }
JP Abgrall8a932722011-07-13 19:17:35 -0700799 return res;
800}
801
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900802int BandwidthController::removeCostlyAlert(const std::string& costName, int64_t* alertBytes) {
JP Abgrall69261cb2014-06-19 18:35:24 -0700803 if (!isIfaceName(costName)) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900804 ALOGE("removeCostlyAlert: Invalid costName \"%s\"", costName.c_str());
Nick Kralevich0b2b9022014-05-01 13:10:45 -0700805 return -1;
806 }
807
JP Abgrall8a932722011-07-13 19:17:35 -0700808 if (!*alertBytes) {
Joel Scherpelzbcad6612017-05-30 10:55:11 +0900809 ALOGE("No prior alert set for %s alert", costName.c_str());
JP Abgrall8a932722011-07-13 19:17:35 -0700810 return -1;
811 }
812
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900813 std::string alertName = costName + "Alert";
814 std::string chainName = "bw_costly_" + costName;
815 std::vector<std::string> commands = {
816 "*filter\n",
817 StringPrintf(ALERT_IPT_TEMPLATE, "-D", chainName.c_str(), *alertBytes, alertName.c_str()),
818 "COMMIT\n"
819 };
820 if (iptablesRestoreFunction(V4V6, Join(commands, ""), nullptr) != 0) {
821 ALOGE("Failed to remove costly alert %s", costName.c_str());
822 return -1;
823 }
JP Abgrall8a932722011-07-13 19:17:35 -0700824
825 *alertBytes = 0;
Lorenzo Colittie85ffe12017-07-06 17:25:37 +0900826 return 0;
JP Abgrall8a932722011-07-13 19:17:35 -0700827}
JP Abgralldb7da582011-09-18 12:57:32 -0700828
JP Abgrall0e540ec2013-08-26 15:13:10 -0700829void BandwidthController::flushExistingCostlyTables(bool doClean) {
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900830 std::string fullCmd = "*filter\n-S\nCOMMIT\n";
831 std::string ruleList;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700832
833 /* Only lookup ip4 table names as ip6 will have the same tables ... */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900834 if (int ret = iptablesRestoreFunction(V4, fullCmd, &ruleList)) {
835 ALOGE("Failed to list existing costly tables ret=%d", ret);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700836 return;
837 }
838 /* ... then flush/clean both ip4 and ip6 iptables. */
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900839 parseAndFlushCostlyTables(ruleList, doClean);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700840}
841
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900842void BandwidthController::parseAndFlushCostlyTables(const std::string& ruleList, bool doRemove) {
843 std::stringstream stream(ruleList);
844 std::string rule;
845 std::vector<std::string> clearCommands = { "*filter" };
846 std::string chainName;
JP Abgrall0e540ec2013-08-26 15:13:10 -0700847
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900848 // Find and flush all rules starting with "-N bw_costly_<iface>" except "-N bw_costly_shared".
849 while (std::getline(stream, rule, '\n')) {
850 if (rule.find(NEW_CHAIN_COMMAND) != 0) continue;
851 chainName = rule.substr(NEW_CHAIN_COMMAND.size());
852 ALOGV("parse chainName=<%s> orig line=<%s>", chainName.c_str(), rule.c_str());
853
854 if (chainName.find("bw_costly_") != 0 || chainName == std::string("bw_costly_shared")) {
JP Abgrall0e540ec2013-08-26 15:13:10 -0700855 continue;
856 }
857
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900858 clearCommands.push_back(StringPrintf(":%s -", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700859 if (doRemove) {
Lorenzo Colitti3c272702017-04-26 15:48:13 +0900860 clearCommands.push_back(StringPrintf("-X %s", chainName.c_str()));
JP Abgrall0e540ec2013-08-26 15:13:10 -0700861 }
862 }
Lorenzo Colitti56c4b1e2017-02-01 02:45:10 +0900863
864 if (clearCommands.size() == 1) {
865 // No rules found.
866 return;
867 }
868
869 clearCommands.push_back("COMMIT\n");
Joel Scherpelzd59526a2017-06-28 16:24:09 +0900870 iptablesRestoreFunction(V4V6, Join(clearCommands, '\n'), nullptr);
JP Abgrall0e540ec2013-08-26 15:13:10 -0700871}
Lorenzo Colittid9db08c2017-04-28 11:06:40 +0900872
873inline const char *BandwidthController::opToString(IptOp op) {
874 switch (op) {
875 case IptOpInsert:
876 return "-I";
877 case IptOpDelete:
878 return "-D";
879 }
880}
881
882inline const char *BandwidthController::jumpToString(IptJumpOp jumpHandling) {
883 /*
884 * Must be careful what one rejects with, as upper layer protocols will just
885 * keep on hammering the device until the number of retries are done.
886 * For port-unreachable (default), TCP should consider as an abort (RFC1122).
887 */
888 switch (jumpHandling) {
889 case IptJumpNoAdd:
890 return "";
891 case IptJumpReject:
892 return " --jump REJECT";
893 case IptJumpReturn:
894 return " --jump RETURN";
895 }
896}